changeset 141:8c80d4dec7a8

mover Card class to tools/games and renamed it in TarotCard
author Goffi <goffi@goffi.org>
date Thu, 22 Jul 2010 15:49:16 +0800
parents e496134ed679
children 23023aff91fd
files frontends/wix/card_game.py plugins/plugin_misc_tarot.py tools/games.py
diffstat 3 files changed, 91 insertions(+), 90 deletions(-) [+]
line wrap: on
line diff
--- a/frontends/wix/card_game.py	Thu Jul 22 15:48:03 2010 +0800
+++ b/frontends/wix/card_game.py	Thu Jul 22 15:49:16 2010 +0800
@@ -26,6 +26,7 @@
 import pdb
 from logging import debug, info, error
 from tools.jid  import JID
+from tools.games import TarotCard
 from xmlui import XMLUI
 
 CARD_WIDTH = 74
@@ -33,10 +34,7 @@
 MIN_WIDTH = 950 #Minimum size of the panel
 MIN_HEIGHT = 500
 
-suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
-values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
-
-class Card():
+class wxCard(TarotCard):
     """This class is used to represent a card, graphically and logically"""
 
     def __init__(self, file):
@@ -44,33 +42,9 @@
         self.bitmap = wx.Image(file).ConvertToBitmap()
         root_name = os.path.splitext(os.path.basename(file))[0]
         self.suit,self.value=root_name.split('_')
-        #gof: self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
-
+        TarotCard.__init__(self, (self.suit, self.value))
         print "Carte:",self.suit, self.value #, self.bout
 
-    def __cmp__(self, other):
-        if other == None:
-            return 1
-        if self.suit != other.suit:
-            idx1 = suits_order.index(self.suit)
-            idx2 = suits_order.index(other.suit)
-            return idx1.__cmp__(idx2)
-        if self.suit == 'atout':
-            if self.value == other.value == 'excuse':
-                return 0
-            if self.value == 'excuse':
-                return -1
-            if other.value == 'excuse':
-                return 1
-            return int(self.value).__cmp__(int(other.value))
-        #at this point we have the same suit which is not 'atout'
-        idx1 = values_order.index(self.value)
-        idx2 = values_order.index(other.value)
-        return idx1.__cmp__(idx2)
-
-    def __str__(self):
-        return "[%s,%s]" % (self.suit, self.value)
-
     def draw(self, dc, x, y):
         """Draw the card on the device context
         @param dc: device context
@@ -127,7 +101,7 @@
         self.cards["carreau"]={} #diamond
         self.cards["trefle"]={} #club
         for file in glob.glob(dir+'/*_*.png'):
-            card = Card(file)
+            card = wxCard(file)
             self.cards[card.suit, card.value]=card
             self.deck.append(card)
         """for value in map(str,range(1,22))+['excuse']:
--- a/plugins/plugin_misc_tarot.py	Thu Jul 22 15:48:03 2010 +0800
+++ b/plugins/plugin_misc_tarot.py	Thu Jul 22 15:49:16 2010 +0800
@@ -33,6 +33,7 @@
 
 from wokkel import disco, iwokkel, data_form
 from tools.xml_tools import dataForm2xml
+from tools.games import TarotCard
 
 try:
     from twisted.words.protocols.xmlstream import XMPPHandler
@@ -55,60 +56,6 @@
 "description": _("""Implementation of Tarot card game""")
 }
 
-suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
-values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
-
-class Card():
-    """This class is used to represent a car logically"""
-    #TODO: move this in a library in tools, and share this with frontends (e.g. card_game in wix use the same class)
-
-    def __init__(self, tuple_card):
-        """@param tuple_card: tuple (suit, value)"""
-        self.suit, self.value = tuple_card
-        self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
-        if self.bout or self.value == "roi":
-            self.points = 4.5
-        elif self.value == "dame":
-            self.points = 3.5
-        elif self.value == "cavalier":
-            self.points = 2.5
-        elif self.value == "valet":
-            self.points = 1.5
-        else:
-            self.points = 0.5
-
-    def get_tuple(self):
-        return (self.suit,self.value)
-
-    @staticmethod
-    def from_tuples(tuple_list):
-        result = []
-        for card_tuple in tuple_list:
-            result.append(Card(card_tuple))
-        return result
-
-    def __cmp__(self, other):
-        if other == None:
-            return 1
-        if self.suit != other.suit:
-            idx1 = suits_order.index(self.suit)
-            idx2 = suits_order.index(other.suit)
-            return idx1.__cmp__(idx2)
-        if self.suit == 'atout':
-            if self.value == other.value == 'excuse':
-                return 0
-            if self.value == 'excuse':
-                return -1
-            if other.value == 'excuse':
-                return 1
-            return int(self.value).__cmp__(int(other.value))
-        #at this point we have the same suit which is not 'atout'
-        idx1 = values_order.index(self.value)
-        idx2 = values_order.index(other.value)
-        return idx1.__cmp__(idx2)
-
-    def __str__(self):
-        return "[%s,%s]" % (self.suit, self.value)
 
 class Tarot():
 
@@ -131,10 +78,10 @@
         host.bridge.addSignal("tarotGameInvalidCards", ".communication", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile
         self.deck_ordered = []
         for value in ['excuse']+map(str,range(1,22)):
-            self.deck_ordered.append(Card(("atout",value)))
+            self.deck_ordered.append(TarotCard(("atout",value)))
         for suit in ["pique", "coeur", "carreau", "trefle"]:
             for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]:
-                self.deck_ordered.append(Card((suit, value)))
+                self.deck_ordered.append(TarotCard((suit, value)))
 
     def createGameElt(self, to_jid, type="normal"):
         type = "normal" if to_jid.resource else "groupchat"
@@ -257,7 +204,7 @@
         #TODO: manage the case where excuse is played on the last trick (and lost)
         #TODO: gof: manage excuse (fool)
         players_data = game_data['players_data']
-        excuse = Card(("atout","excuse"))
+        excuse = TarotCard(("atout","excuse"))
 
         #we first check if the Excuse was already player
         #and if somebody is waiting for a card
@@ -518,7 +465,7 @@
             return
         debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards})
         mess = self.createGameElt(jid.JID(referee))
-        playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(Card.from_tuples(cards), 'cards_played'))
+        playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played'))
         playcard_elt['player'] = player
         self.host.profiles[profile].xmlstream.send(mess)
 
@@ -650,7 +597,7 @@
                 if game_data['stage'] == "ecart":
                     #TODO: show atouts (trumps) if player put some in écart
                     assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here
-                    list_cards = Card.from_tuples(self.__xml_to_list(elt))
+                    list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
                     #we now check validity of card
                     invalid_cards = self.__invalid_cards(game_data, list_cards)
                     if invalid_cards:
@@ -668,7 +615,7 @@
                     
                 elif game_data['stage'] == "play":
                     current_player = game_data['players'][game_data['current_player']]
-                    cards = Card.from_tuples(self.__xml_to_list(elt))
+                    cards = TarotCard.from_tuples(self.__xml_to_list(elt))
                     
                     if mess_elt['type'] == 'groupchat':
                         self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/games.py	Thu Jul 22 15:49:16 2010 +0800
@@ -0,0 +1,80 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""
+SAT: a jabber client
+Copyright (C) 2009, 2010  Jérôme Poisson (goffi@goffi.org)
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+
+from logging import debug, info, error
+
+"""This library help manage general games (e.g. card games)"""
+
+    
+suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
+values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
+
+class TarotCard():
+    """This class is used to represent a car logically"""
+    #TODO: move this in a library in tools, and share this with frontends (e.g. card_game in wix use the same class)
+
+    def __init__(self, tuple_card):
+        """@param tuple_card: tuple (suit, value)"""
+        self.suit, self.value = tuple_card
+        self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
+        if self.bout or self.value == "roi":
+            self.points = 4.5
+        elif self.value == "dame":
+            self.points = 3.5
+        elif self.value == "cavalier":
+            self.points = 2.5
+        elif self.value == "valet":
+            self.points = 1.5
+        else:
+            self.points = 0.5
+
+    def get_tuple(self):
+        return (self.suit,self.value)
+
+    @staticmethod
+    def from_tuples(tuple_list):
+        result = []
+        for card_tuple in tuple_list:
+            result.append(TarotCard(card_tuple))
+        return result
+
+    def __cmp__(self, other):
+        if other == None:
+            return 1
+        if self.suit != other.suit:
+            idx1 = suits_order.index(self.suit)
+            idx2 = suits_order.index(other.suit)
+            return idx1.__cmp__(idx2)
+        if self.suit == 'atout':
+            if self.value == other.value == 'excuse':
+                return 0
+            if self.value == 'excuse':
+                return -1
+            if other.value == 'excuse':
+                return 1
+            return int(self.value).__cmp__(int(other.value))
+        #at this point we have the same suit which is not 'atout'
+        idx1 = values_order.index(self.value)
+        idx2 = values_order.index(other.value)
+        return idx1.__cmp__(idx2)
+
+    def __str__(self):
+        return "[%s,%s]" % (self.suit, self.value)