diff frontends/wix/card_game.py @ 92:2503de7fb4c7

Tarot game: chien/écart stage - tarot plugin: new methods/signals tarotGamePlayCards, tarotGameShowCards, tarotGameYourTurn - tarot plugin: protocole update - tarot plugin: family renamed in suit - wix: card_game: card can be selected for écart, card move when mouse is over only if it's our turn
author Goffi <goffi@goffi.org>
date Sat, 29 May 2010 20:53:03 +0930
parents 39c672544593
children 2f87651a5ad8
line wrap: on
line diff
--- a/frontends/wix/card_game.py	Thu May 27 19:26:19 2010 +0930
+++ b/frontends/wix/card_game.py	Sat May 29 20:53:03 2010 +0930
@@ -33,7 +33,7 @@
 MIN_WIDTH = 950 #Minimum size of the panel
 MIN_HEIGHT = 500
 
-families_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have swith the usual order 'trefle' and 'carreau' because card are more easy to see if couleur change (black, red, black, red)
+suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have swith the usual order 'trefle' and 'carreau' because card are more easy to see if couleur change (black, red, black, red)
 values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
 
 class Card():
@@ -43,19 +43,19 @@
         """@param file: path of the PNG file"""
         self.bitmap = wx.Image(file).ConvertToBitmap()
         root_name = os.path.splitext(os.path.basename(file))[0]
-        self.family,self.value=root_name.split('_')
-        self.bout = True if self.family=="atout" and self.value in ["1","21","excuse"] else False
+        self.suit,self.value=root_name.split('_')
+        #gof: self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
 
-        print "Carte:",self.family, self.value, self.bout
+        print "Carte:",self.suit, self.value #, self.bout
 
     def __cmp__(self, other):
         if other == None:
             return 1
-        if self.family != other.family:
-            idx1 = families_order.index(self.family)
-            idx2 = families_order.index(other.family)
+        if self.suit != other.suit:
+            idx1 = suits_order.index(self.suit)
+            idx2 = suits_order.index(other.suit)
             return idx1.__cmp__(idx2)
-        if self.family == 'atout':
+        if self.suit == 'atout':
             if self.value == other.value == 'excuse':
                 return 0
             if self.value == 'excuse':
@@ -63,13 +63,13 @@
             if other.value == 'excuse':
                 return 1
             return int(self.value).__cmp__(int(other.value))
-        #at this point we have the same family which is not 'atout'
+        #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.family, self.value)
+        return "[%s,%s]" % (self.suit, self.value)
 
     def draw(self, dc, x, y):
         """Draw the card on the device context
@@ -82,14 +82,14 @@
 class CardPanel(wx.Panel):
     """This class is used to display the cards"""
 
-    def __init__(self, parent, referee, players, user):
+    def __init__(self, parent, referee, players, player_nick):
         wx.Panel.__init__(self, parent)
         self.parent = parent
         self.referee = referee
         self.players = players
-        self.user = user
-        self.bottom_nick = self.user
-        idx = self.players.index(self.user)
+        self.player_nick = player_nick
+        self.bottom_nick = self.player_nick
+        idx = self.players.index(self.player_nick)
         idx = (idx + 1) % len(self.players)
         self.right_nick = self.players[idx]
         idx = (idx + 1) % len(self.players)
@@ -98,17 +98,19 @@
         self.left_nick = self.players[idx]
         self.SetMinSize(wx.Size(MIN_WIDTH, MIN_HEIGHT))
         self.load_cards("/home/goffi/dev/divers/images/cards/")
-        self.selected = None #contain the card to highlight
+        self.mouse_over_card = None #contain the card to highlight
+        self.selected = [] #Card choosed by the player (e.g. during ecart)
         self.hand_size = 13 #number of cards in a hand
         self.visible_size = CARD_WIDTH/2 #number of pixels visible for cards
         self.hand = []
-        self.my_turn = False
+        self.to_show = []
+        self.state = None
         self.SetBackgroundColour(wx.GREEN)
         self.Bind(wx.EVT_SIZE, self.onResize)
         self.Bind(wx.EVT_PAINT, self.onPaint)
         self.Bind(wx.EVT_MOTION, self.onMouseMove)
         self.Bind(wx.EVT_LEFT_UP, self.onMouseClick)
-        self.parent.host.bridge.tarotGameReady(user, referee, profile_key = self.parent.host.profile)
+        self.parent.host.bridge.tarotGameReady(player_nick, referee, profile_key = self.parent.host.profile)
 
     def load_cards(self, dir):
         """Load all the cards in memory
@@ -122,30 +124,30 @@
         self.cards["trefle"]={} #club
         for file in glob.glob(dir+'/*_*.png'):
             card = Card(file)
-            self.cards[card.family, card.value]=card
+            self.cards[card.suit, card.value]=card
             self.deck.append(card)
         """for value in map(str,range(1,22))+['excuse']:
             self.idx_cards.append(self.cards["atout",value])
-        for family in ["pique", "coeur", "carreau", "trefle"]:
+        for suit in ["pique", "coeur", "carreau", "trefle"]:
             for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]:
-                self.idx_cards.append(self.cards[family, value])"""  #XXX: no need to sort the cards !
+                self.idx_cards.append(self.cards[suit, value])"""  #XXX: no need to sort the cards !
 
     def newGame(self, hand):
         """Start a new game, with given hand"""
-        print "gof: new game ici avec",hand
         assert (len(self.hand) == 0)
-        for family, value in hand:
-            self.hand.append(self.cards[family, value])
+        for suit, value in hand:
+            self.hand.append(self.cards[suit, value])
         self.hand.sort()
-        self.my_turn = True
+        self.state = "init"
+        self._recalc_ori()
+        self.Refresh()
 
     def contratSelected(self, data):
         """Called when the contrat has been choosed
         @param data: form result"""
         debug (_("Contrat choosed"))
-        print "\n\n\n===============>>>> \o/ :) :) :) ", data, "\n\n\n"
         contrat = data[0][1]
-        self.parent.host.bridge.tarotGameContratChoosed(self.user, self.referee, contrat or 'Passe', self.parent.host.profile)
+        self.parent.host.bridge.tarotGameContratChoosed(self.player_nick, self.referee, contrat or 'Passe', self.parent.host.profile)
 
     def chooseContrat(self, xml_data):
         """Called when the player as to select hist contrat
@@ -153,6 +155,21 @@
         misc = {'callback': self.contratSelected}
         form = Form(self.parent.host, xml_data, title = _('Please choose your contrat'), options = ['NO_CANCEL'], misc = misc)
 
+    def showCards(self, game_stage, cards, data):
+        """Display cards in the middle of the game (to show for e.g. chien ou poignée)"""
+        self.to_show = []
+        for suit, value in cards:
+            self.to_show.append(self.cards[suit, value])
+            if game_stage == "chien" and data['attaquant'] == self.player_nick:
+                self.state = "wait_for_ecart"
+            else:
+                self.state = "chien"
+
+    def MyTurn(self):
+        """Called when we have to play :)"""
+        if self.state == "chien":
+            self.to_show = []
+        self.state="play"
 
     def _is_on_hand(self, pos_x, pos_y):
         """Return True if the coordinate are on the hand cards"""
@@ -166,7 +183,7 @@
         self._recalc_ori()
 
     def _recalc_ori(self):
-        """Recalculate origines, must be call when size change"""
+        """Recalculate origins of hand, must be call when hand size change"""
         self.orig_x = (self.GetSizeTuple()[0]-(len(self.hand)+1)*self.visible_size)/2 #where we start to draw cards
         self.orig_y = self.GetSizeTuple()[1] - CARD_HEIGHT - 20
         self.end_y = self.orig_y + CARD_HEIGHT
@@ -190,29 +207,74 @@
 
         x=self.orig_x
         for card in self.hand:
-            card.draw(dc,x,self.orig_y - 30 if self.my_turn and card == self.selected else self.orig_y)
+            if (self.state == "play" or self.state == "ecart") and card == self.mouse_over_card \
+                or self.state == "ecart" and card in self.selected:
+                y = self.orig_y - 30
+            else:
+                y = self.orig_y
+
+            card.draw(dc,x,y)
             x+=self.visible_size
 
+        if self.to_show:
+            """There are cards to display in the middle"""
+            size = len(self.to_show)*(CARD_WIDTH+10)-10
+            x = (max_x - size)/2
+            for card in self.to_show:
+                card.draw(dc, x, 150)
+                x+=CARD_WIDTH+10
+
     def onMouseMove(self, event):
         pos_x,pos_y = event.GetPosition()
         if self._is_on_hand(pos_x, pos_y):
            try:
-               self.selected = self.hand[(pos_x-self.orig_x)/self.visible_size]
+               self.mouse_over_card = self.hand[(pos_x-self.orig_x)/self.visible_size]
            except IndexError:
-               self.selected = self.hand[-1]
+               self.mouse_over_card = self.hand[-1]
            self.Refresh()
         else:
-            self.selected = None
+            self.mouse_over_card = None
             self.Refresh()
 
     def onMouseClick(self, event):
         print "mouse click:",event.GetPosition()
         pos_x,pos_y = event.GetPosition()
+        
+        if self.state == "chien":
+            self.to_show = []
+            self.state = "wait"
+            return
+        elif self.state == "wait_for_ecart":
+            self.state = "ecart"
+            self.hand.extend(self.to_show)
+            self.hand.sort()
+            self.to_show = []
+            self._recalc_ori()
+            self.Refresh()
+            return
+
         if self._is_on_hand(pos_x, pos_y):
            idx = (pos_x-self.orig_x)/self.visible_size
            if idx == len(self.hand):
                idx-=1
-           if self.hand[idx] == self.selected:
-               del self.hand[idx]
-               self._recalc_ori()
-               self.Refresh()
+           if self.hand[idx] == self.mouse_over_card:
+               if self.state == "ecart":
+                   if self.hand[idx] in self.selected:
+                       self.selected.remove(self.hand[idx])
+                   else:
+                       self.selected.append(self.hand[idx])
+                       if len(self.selected) == 6: #TODO: use variable here, as chien len can change with variants
+                           dlg = wx.MessageDialog(self, _("Do you put these cards in chien ?"), _(u"Écart"), wx.YES_NO | wx.ICON_QUESTION)
+                           answer = dlg.ShowModal()
+                           if answer == wx.ID_YES:
+                               ecart = []
+                               for card in self.selected:
+                                   ecart.append((card.suit, card.value))
+                                   self.hand.remove(card)
+                               print "gof: Cartes envoyes au chien:", ecart
+                               del self.selected[:]
+                               self.parent.host.bridge.tarotGamePlayCards(self.player_nick, self.referee, ecart, profile_key = self.parent.host.profile)
+                               self.state = "wait"
+
+                   self._recalc_ori()
+                   self.Refresh()