changeset 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
files frontends/quick_frontend/quick_app.py frontends/sat_bridge_frontend/DBus.py frontends/wix/card_game.py frontends/wix/form.py plugins/plugin_misc_tarot.py
diffstat 5 files changed, 225 insertions(+), 91 deletions(-) [+]
line wrap: on
line diff
--- a/frontends/quick_frontend/quick_app.py	Thu May 27 19:26:19 2010 +0930
+++ b/frontends/quick_frontend/quick_app.py	Sat May 29 20:53:03 2010 +0930
@@ -50,7 +50,9 @@
         self.bridge.register("roomNewSubject", self.roomNewSubject)
         self.bridge.register("tarotGameStarted", self.tarotGameStarted)
         self.bridge.register("tarotGameNew", self.tarotGameNew)
-        self.bridge.register("tarotChooseContrat", self.tarotChooseContrat)
+        self.bridge.register("tarotGameChooseContrat", self.tarotChooseContrat)
+        self.bridge.register("tarotGameShowCards", self.tarotShowCards)
+        self.bridge.register("tarotGameYourTurn", self.tarotMyTurn)
         self.bridge.register("subscribe", self.subscribe)
         self.bridge.register("paramUpdate", self.paramUpdate)
         self.bridge.register("contactDeleted", self.contactDeleted)
@@ -291,7 +293,19 @@
         if self.chat_wins.has_key(room_jid):
             self.chat_wins[room_jid].getGame("Tarot").chooseContrat(xml_data)
 
+    def tarotShowCards(self, room_jid, game_stage, cards, data, profile):
+        if not self.__check_profile(profile):
+            return
+        debug (_("Show cards"))
+        if self.chat_wins.has_key(room_jid):
+            self.chat_wins[room_jid].getGame("Tarot").showCards(game_stage, cards, data)
 
+    def tarotMyTurn(self, room_jid, profile):
+        if not self.__check_profile(profile):
+            return
+        debug (_("My turn to play"))
+        if self.chat_wins.has_key(room_jid):
+            self.chat_wins[room_jid].getGame("Tarot").MyTurn()
 
     def subscribe(self, type, raw_jid, profile):
         """Called when a subsciption management signal is received"""
--- a/frontends/sat_bridge_frontend/DBus.py	Thu May 27 19:26:19 2010 +0930
+++ b/frontends/sat_bridge_frontend/DBus.py	Sat May 29 20:53:03 2010 +0930
@@ -122,11 +122,14 @@
     def tarotGameCreate(self, room_jid, players, profile_key='@DEFAULT@'):
         return self.db_comm_iface.tarotGameCreate(room_jid, players, profile_key)
 
-    def tarotGameReady(self, user, referee, profile_key='@DEFAULT@'):
-        return self.db_comm_iface.tarotGameReady(user, referee, profile_key)
+    def tarotGameReady(self, player, referee, profile_key='@DEFAULT@'):
+        return self.db_comm_iface.tarotGameReady(player, referee, profile_key)
 
-    def tarotGameContratChoosed(self, user, referee, contrat, profile_key='@DEFAULT@'):
-        return self.db_comm_iface.tarotGameContratChoosed(user, referee, contrat, profile_key)
+    def tarotGameContratChoosed(self, player, referee, contrat, profile_key='@DEFAULT@'):
+        return self.db_comm_iface.tarotGameContratChoosed(player, referee, contrat, profile_key)
+
+    def tarotGamePlayCards(self, player, referee, cards, profile_key='@DEFAULT@'):
+        return self.db_comm_iface.tarotGamePlayCards(player, referee, cards, profile_key)
 
     def sendFile(self, to, path, profile_key='@DEFAULT@'):
         return self.db_comm_iface.sendFile(to, path, profile_key)
--- 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()
--- a/frontends/wix/form.py	Thu May 27 19:26:19 2010 +0930
+++ b/frontends/wix/form.py	Sat May 29 20:53:03 2010 +0930
@@ -32,7 +32,8 @@
     """Create a form from a SàT xml"""
 
     def __init__(self, host, xml_data='', title="Form", options=[], misc={}):
-        super(Form, self).__init__(None, title=title)
+        style = wx.DEFAULT_FRAME_STYLE & ~wx.CLOSE_BOX if 'NO_CANCEL' in options else wx.DEFAULT_FRAME_STYLE #FIXME: gof: Q&D tmp hack
+        super(Form, self).__init__(None, title=title, style=style)
 
         self.host = host
         self.options = options
--- a/plugins/plugin_misc_tarot.py	Thu May 27 19:26:19 2010 +0930
+++ b/plugins/plugin_misc_tarot.py	Sat May 29 20:53:03 2010 +0930
@@ -67,41 +67,45 @@
         self.games={}
         self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
         host.bridge.addMethod("tarotGameCreate", ".communication", in_sign='sass', out_sign='', method=self.createGame) #args: room_jid, players, profile
-        host.bridge.addMethod("tarotGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: user, referee, profile
-        host.bridge.addMethod("tarotGameContratChoosed", ".communication", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: user, referee, contrat, profile
+        host.bridge.addMethod("tarotGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: player, referee, profile
+        host.bridge.addMethod("tarotGameContratChoosed", ".communication", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: player, referee, contrat, profile
+        host.bridge.addMethod("tarotGamePlayCards", ".communication", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) #args: player, referee, cards, profile
         host.bridge.addSignal("tarotGameStarted", ".communication", signature='ssass') #args: room_jid, referee, players, profile
         host.bridge.addSignal("tarotGameNew", ".communication", signature='sa(ss)s') #args: room_jid, hand, profile
-        host.bridge.addSignal("tarotChooseContrat", ".communication", signature='sss') #args: room_jid, xml_data, profile
+        host.bridge.addSignal("tarotGameChooseContrat", ".communication", signature='sss') #args: room_jid, xml_data, profile
+        host.bridge.addSignal("tarotGameShowCards", ".communication", signature='ssa(ss)a{ss}s') #args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile
+        host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile
         self.deck_ordered = []
-        for value in map(str,range(1,22))+['excuse']:
+        for value in ['excuse']+map(str,range(1,22)):
             self.deck_ordered.append(("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.deck_ordered.append((family, value))
+                self.deck_ordered.append((suit, value))
 
-    def createGameElt(self, to_jid):
+    def createGameElt(self, to_jid, type="normal"):
+        type = "normal" if to_jid.resource else "groupchat"
         elt = domish.Element(('jabber:client','message'))
         elt["to"] = to_jid.full()
+        elt["type"] = type
         elt.addElement((NS_CG, CG_TAG))
         return elt
 
-    def __hand_to_xml(self, hand):
-        """Convert a hand (list of tuples) to domish element"""
-        hand_elt = domish.Element(('','hand'))
-        for family, value in hand:
+    def __list_to_xml(self, cards_list, elt_name):
+        """Convert a card list (list of tuples) to domish element"""
+        cards_list_elt = domish.Element(('',elt_name))
+        for suit, value in cards_list:
             card_elt = domish.Element(('','card'))
-            card_elt['family'] = family
+            card_elt['suit'] = suit
             card_elt['value'] = value
-            hand_elt.addChild(card_elt) 
-        return hand_elt
+            cards_list_elt.addChild(card_elt) 
+        return cards_list_elt
 
-    def __xml_to_hand(self, hand_elt):
-        """Convert a hand domish element to a list of tuples"""
-        hand = []
-        assert (hand_elt.name == 'hand')
-        for card in hand_elt.elements():
-            hand.append((card['family'], card['value']))
-        return hand
+    def __xml_to_list(self, cards_list_elt):
+        """Convert a domish element with cards to a list of tuples"""
+        cards_list = []
+        for card in cards_list_elt.elements():
+            cards_list.append((card['suit'], card['value']))
+        return cards_list
 
     def __create_started_elt(self, players):
         """Create a game_started domish element"""
@@ -123,9 +127,6 @@
         form.addField(field)
         contrat_elt.addChild(form.toElement())
         return contrat_elt
-        
-
-
 
     def __next_player(self, game_data):
         """It's next player turn
@@ -149,13 +150,13 @@
             for player in players:
                 players_data[player] = {}
                 status[player] = "init"
-            self.games[room_jid.userhost()] = {'players':players, 'status':status, 'players_data':players_data, 'referee_profile':profile, 'hand_size':18, 'init_player':0, 'current_player': None}
+            self.games[room_jid.userhost()] = {'players':players, 'status':status, 'players_data':players_data, 'hand_size':18, 'init_player':0, 'current_player': None, 'stage': None}
             for player in players:
                 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player))
                 mess.firstChildElement().addChild(self.__create_started_elt(players))
                 self.host.profiles[profile].xmlstream.send(mess)
 
-    def newPlayerReady(self, user, referee, profile_key='@DEFAULT@'):
+    def newPlayerReady(self, player, referee, profile_key='@DEFAULT@'):
         """Must be called when player is ready to start a new game"""
         profile = self.host.memory.getProfileName(profile_key)
         if not profile:
@@ -164,12 +165,12 @@
         debug ('new player ready: %s' % profile)
         mess = self.createGameElt(jid.JID(referee))
         ready_elt = mess.firstChildElement().addElement('player_ready')
-        ready_elt['user'] = user
+        ready_elt['player'] = player
         self.host.profiles[profile].xmlstream.send(mess)
 
-    def contratChoosed(self, user, referee, contrat, profile_key='@DEFAULT@'):
+    def contratChoosed(self, player, referee, contrat, profile_key='@DEFAULT@'):
         """Must be call by player when the contrat is selected
-        @param user: player's name
+        @param player: player's name
         @param referee: arbiter jid
         @contrat: contrat choosed (must be the exact same string than in the give list options)
         @profile_key: profile
@@ -181,80 +182,98 @@
         debug (_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat':contrat, 'profile':profile})
         mess = self.createGameElt(jid.JID(referee))
         contrat_elt = mess.firstChildElement().addElement(('','contrat_choosed'), content=contrat)
-        contrat_elt['user'] = user
+        contrat_elt['player'] = player
         self.host.profiles[profile].xmlstream.send(mess)
 
+    def play_cards(self, player, referee, cards, profile_key='@DEFAULT@'):
+        """Must be call by player when the contrat is selected
+        @param player: player's name
+        @param referee: arbiter jid
+        @cards: cards played (list of tuples)
+        @profile_key: profile
+        """
+        profile = self.host.memory.getProfileName(profile_key)
+        if not profile:
+            error (_("profile %s is unknown") % profile_key)
+            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.__list_to_xml(cards, 'cards_played'))
+        playcard_elt['player'] = player
+        self.host.profiles[profile].xmlstream.send(mess)
 
-    def newGame(self, room_jid):
+    def newGame(self, room_jid, profile):
         """Launch a new round"""
         debug (_('new Tarot game'))
         deck = self.deck_ordered[:]
         random.shuffle(deck)
         game_data = self.games[room_jid.userhost()]
-        referee_profile = game_data['referee_profile']
         players = game_data['players']
         players_data = game_data['players_data']
         current_player = game_data['current_player']
+        game_data['stage'] = "init"
         hand = game_data['hand'] = {}
         hand_size = game_data['hand_size']
         chien = game_data['chien'] = []
         for i in range(4): #TODO: distribute according to real Tarot rules (3 by 3 counter-clockwise, 1 card at once to chien)
             hand[players[i]] = deck[0:hand_size]
             del deck[0:hand_size]
-        chien = deck[:]
+        chien.extend(deck)
         del(deck[:])
 
         for player in players:
             to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
             mess = self.createGameElt(to_jid)
-            mess.firstChildElement().addChild(self.__hand_to_xml(hand[player]))
-            self.host.profiles[referee_profile].xmlstream.send(mess)
+            mess.firstChildElement().addChild(self.__list_to_xml(hand[player], 'hand'))
+            self.host.profiles[profile].xmlstream.send(mess)
             players_data[player]['contrat'] = None
+            players_data[player]['levees'] = [] #cards won
 
         pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) #the player after the dealer start
         player = players[pl_idx]
         to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
         mess = self.createGameElt(to_jid)
         mess.firstChildElement().addChild(self.__ask_contrat())
-        self.host.profiles[referee_profile].xmlstream.send(mess)
+        self.host.profiles[profile].xmlstream.send(mess)
             
 
     def card_game_cmd(self, mess_elt, profile):
         print "\n\nCARD GAME command received (profile=%s): %s" % (profile, mess_elt.toXml())
         room_jid = jid.JID(mess_elt['from'])
         game_elt = mess_elt.firstChildElement()
-        for elt in game_elt.elements(): #new game created
+        game_data = self.games[room_jid.userhost()]
+        players_data = game_data['players_data']
+        
+        for elt in game_elt.elements():
             
-            if elt.name == 'started':
+            if elt.name == 'started': #new game created
                 players = []
                 for player in elt.elements():
                     players.append(unicode(player))
                 self.host.bridge.tarotGameStarted(room_jid.userhost(), room_jid.full(), players, profile)
             
-            elif elt.name == 'player_ready':
-                player = elt['user']
+            elif elt.name == 'player_ready': #ready to play
+                player = elt['player']
                 status = self.games[room_jid.userhost()]['status']
                 nb_players = len(self.games[room_jid.userhost()]['players'])
                 status[player] = 'ready'
                 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status})
                 if status.values().count('ready') == nb_players: #everybody is ready, we can start the game
-                    self.newGame(room_jid)
+                    self.newGame(room_jid, profile)
             
             elif elt.name == 'hand': #a new hand has been received
-                self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_hand(elt), profile)
+                self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile)
 
             elif elt.name == 'contrat': #it's time to choose contrat
                 form = data_form.Form.fromElement(elt.firstChildElement())
                 xml_data = XMLTools.dataForm2xml(form)
-                self.host.bridge.tarotChooseContrat(room_jid.userhost(), xml_data, profile)
+                self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
            
-            elif elt.name == 'contrat_choosed': #the player has chooser a contrat
+            elif elt.name == 'contrat_choosed':
                 #TODO: check we receive the contrat from the right person
-                #TODO: user proper XEP-0004 way for answering form
-                user = elt['user']
-                game_data = self.games[room_jid.userhost()]
-                players_data = game_data['players_data']
-                players_data[user]['contrat'] = unicode(elt)
+                #TODO: use proper XEP-0004 way for answering form
+                player = elt['player']
+                players_data[player]['contrat'] = unicode(elt)
                 contrats = [players_data[player]['contrat'] for player in game_data['players']]
                 if contrats.count(None):
                     #not everybody has choosed his contrat, it's next one turn
@@ -262,7 +281,7 @@
                     to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
                     mess = self.createGameElt(to_jid)
                     mess.firstChildElement().addChild(self.__ask_contrat())
-                    self.host.profiles[game_data['referee_profile']].xmlstream.send(mess)
+                    self.host.profiles[profile].xmlstream.send(mess)
                 else:
                     #TODO: manage "everybody pass" case
                     best_contrat = [None, "Passe"]
@@ -274,7 +293,42 @@
                             best_contrat[0] = player
                             best_contrat[1] = contrat
                     debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]})
+                    #Time to show the chien to everybody
+                    to_jid = jid.JID(room_jid.userhost()) #FIXME: gof:
+                    mess = self.createGameElt(to_jid)
+                    chien_elt = mess.firstChildElement().addChild(self.__list_to_xml(game_data['chien'], 'chien'))
+                    chien_elt['attaquant'] = best_contrat[0]
+                    self.host.profiles[profile].xmlstream.send(mess)
 
+                    #the attacker (attaquant) get the chien
+                    game_data['hand'][best_contrat[0]].extend(game_data['chien'])
+                    del game_data['chien'][:]
+
+            elif elt.name == 'chien': #we have received the chien
+                debug (_("tarot: chien received"))
+                data = {"attaquant":elt['attaquant']}
+                players_data = game_data['players_data']
+                game_data['stage'] = "ecart"
+                game_data['attaquant'] = elt['attaquant']
+                self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile)
+
+            elif elt.name == 'cards_played':
+                if game_data['stage'] == "ecart":
+                    #TODO: check validity of écart (no king, no oulder, cards must be in player hand)
+                    #TODO: show atouts (trumps) if player put some in écart
+                    assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here
+                    players_data[elt['player']]['levees'].extend(self.__xml_to_list(elt))
+                    game_data['stage'] = "play"
+                    next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #the player after the dealer start
+                    next_player = game_data['players'][next_player_idx]
+                    to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof:
+                    mess = self.createGameElt(to_jid)
+                    self.host.profiles[profile].xmlstream.send(mess)
+                    yourturn_elt = mess.firstChildElement().addElement('your_turn')
+                    self.host.profiles[profile].xmlstream.send(mess)
+            
+            elif elt.name == 'your_turn':
+                self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
 
 
     def getHandler(self, profile):