diff plugins/plugin_misc_tarot.py @ 91:39c672544593

Tarot: bidding phase - quick_app: command line is now parsed, "profile" option allow to select it - xml_tools: list-single is now managed - plugin tarot: method and signal to manage contract (contrat): tarotChooseContrat & tarotGameContratChoosed - wix: Q&D Form hack to manage more generic form (not only registration), used to show contract selection form
author Goffi <goffi@goffi.org>
date Thu, 27 May 2010 19:26:19 +0930
parents 4020931569b8
children 2503de7fb4c7
line wrap: on
line diff
--- a/plugins/plugin_misc_tarot.py	Sun May 23 16:39:05 2010 +0930
+++ b/plugins/plugin_misc_tarot.py	Thu May 27 19:26:19 2010 +0930
@@ -31,7 +31,8 @@
 
 from zope.interface import implements
 
-from wokkel import disco, iwokkel, muc
+from wokkel import disco, iwokkel, data_form
+from tools.xml_tools import XMLTools
 
 from base64 import b64decode
 from hashlib import sha1
@@ -64,10 +65,13 @@
         info(_("Plugin Tarot initialization"))
         self.host = host
         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.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
         self.deck_ordered = []
         for value in map(str,range(1,22))+['excuse']:
             self.deck_ordered.append(("atout",value))
@@ -111,6 +115,24 @@
             started_elt.addChild(player_elt)
         return started_elt
 
+    def __ask_contrat(self):
+        """Create a element for asking contrat"""
+        contrat_elt = domish.Element(('','contrat'))
+        form = data_form.Form('form', title=_('contrat selection'))
+        field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True)
+        form.addField(field)
+        contrat_elt.addChild(form.toElement())
+        return contrat_elt
+        
+
+
+
+    def __next_player(self, game_data):
+        """It's next player turn
+        Increment player number & return player name"""
+        pl_idx = game_data['current_player'] = (game_data['current_player'] + 1) % len(game_data['players'])
+        return game_data['players'][pl_idx]
+
     def createGame(self, room_jid_param, players, profile_key='@DEFAULT@'):
         """Create a new game"""
         debug (_("Creating Tarot game"))
@@ -123,9 +145,11 @@
             warning (_("Tarot game already started in room %s") % room_jid.userhost())
         else:
             status = {}
+            players_data = {}
             for player in players:
+                players_data[player] = {}
                 status[player] = "init"
-            self.games[room_jid.userhost()] = {'players':players, 'status':status, 'profile':profile, 'hand_size':18, 'player_start':0}
+            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}
             for player in players:
                 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player))
                 mess.firstChildElement().addChild(self.__create_started_elt(players))
@@ -139,7 +163,25 @@
             return
         debug ('new player ready: %s' % profile)
         mess = self.createGameElt(jid.JID(referee))
-        mess.firstChildElement().addElement('player_ready', content=user)
+        ready_elt = mess.firstChildElement().addElement('player_ready')
+        ready_elt['user'] = user
+        self.host.profiles[profile].xmlstream.send(mess)
+
+    def contratChoosed(self, user, referee, contrat, profile_key='@DEFAULT@'):
+        """Must be call by player when the contrat is selected
+        @param user: 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
+        """
+        profile = self.host.memory.getProfileName(profile_key)
+        if not profile:
+            error (_("profile %s is unknown") % profile_key)
+            return
+        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
         self.host.profiles[profile].xmlstream.send(mess)
 
 
@@ -148,11 +190,14 @@
         debug (_('new Tarot game'))
         deck = self.deck_ordered[:]
         random.shuffle(deck)
-        profile = self.games[room_jid.userhost()]['profile']
-        players = self.games[room_jid.userhost()]['players']
-        hand = self.games[room_jid.userhost()]['hand'] = {}
-        hand_size = self.games[room_jid.userhost()]['hand_size']
-        chien = self.games[room_jid.userhost()]['chien'] = []
+        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']
+        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]
@@ -163,7 +208,15 @@
             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[profile].xmlstream.send(mess)
+            self.host.profiles[referee_profile].xmlstream.send(mess)
+            players_data[player]['contrat'] = None
+
+        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)
             
 
     def card_game_cmd(self, mess_elt, profile):
@@ -171,23 +224,58 @@
         room_jid = jid.JID(mess_elt['from'])
         game_elt = mess_elt.firstChildElement()
         for elt in game_elt.elements(): #new game created
+            
             if elt.name == 'started':
                 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 = unicode(elt)
+                player = elt['user']
                 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') == 2: #gof: nb_players: #everybody is ready, we can start the game
+                if status.values().count('ready') == nb_players: #everybody is ready, we can start the game
                     self.newGame(room_jid)
             
             elif elt.name == 'hand': #a new hand has been received
                 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_hand(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)
+           
+            elif elt.name == 'contrat_choosed': #the player has chooser a contrat
+                #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)
+                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
+                    player = self.__next_player(game_data)
+                    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)
+                else:
+                    #TODO: manage "everybody pass" case
+                    best_contrat = [None, "Passe"]
+                    for player in game_data['players']:
+                        contrat = players_data[player]['contrat']
+                        idx_best = self.contrats.index(best_contrat[1])
+                        idx_pl = self.contrats.index(contrat)
+                        if idx_pl > idx_best:
+                            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]})
+
+
 
     def getHandler(self, profile):
             return CardGameHandler(self)
@@ -202,7 +290,6 @@
         self.host = plugin_parent.host
 
     def connectionInitialized(self):
-        print "gof: ajout d'observer", CG_REQUEST
         self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile)
 
     def getDiscoInfo(self, requestor, target, nodeIdentifier=''):