diff src/plugins/plugin_misc_tarot.py @ 1359:83127a4c89ce frontends_multi_profiles

plugins room_game, quiz, radiocol, tarot: use JID instead of unicode in many methods + class attributes
author souliane <souliane@mailoo.org>
date Wed, 11 Mar 2015 12:36:22 +0100
parents 83ed877541e3
children 069ad98b360d
line wrap: on
line diff
--- a/src/plugins/plugin_misc_tarot.py	Wed Mar 11 12:35:21 2015 +0100
+++ b/src/plugins/plugin_misc_tarot.py	Wed Mar 11 12:36:22 2015 +0100
@@ -59,12 +59,12 @@
         self._sessions = memory.Sessions()
         self.inheritFromRoomGame(host)
         RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
-                          game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
-                          player_init={'score': 0})
+                        game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
+                        player_init={'score': 0})
         self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
-        host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom, async=True)  # args: players, room_jid, profile
-        host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame)  # args: room_jid, players, profile
-        host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady)  # args: player, referee, profile
+        host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True)  # args: players, room_jid, profile
+        host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame)  # args: room_jid, players, profile
+        host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady)  # args: player, referee, profile
         host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards)  # args: player, referee, cards, profile
         host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass')  # args: room_jid, referee, players, profile
         host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass')  # args: room_jid, referee, players, profile
@@ -84,7 +84,6 @@
         self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True)
         self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
 
-
     def __card_list_to_xml(self, cards_list, elt_name):
         """Convert a card list to domish element"""
         cards_list_elt = domish.Element((None, elt_name))
@@ -183,17 +182,17 @@
         @param game_data: data of the game
         @param played: cards currently on the table
         @param winner: nick of the trick winner"""
-        #TODO: manage the case where excuse is played on the last trick (and lost)
+        # TODO: manage the case where excuse is played on the last trick (and lost)
         players_data = game_data['players_data']
         excuse = TarotCard(("atout", "excuse"))
 
-        #we first check if the Excuse was already played
-        #and if somebody is waiting for a card
+        # we first check if the Excuse was already played
+        # and if somebody is waiting for a card
         for player in game_data['players']:
             if players_data[player]['wait_for_low']:
-                #the excuse owner has to give a card to somebody
+                # the excuse owner has to give a card to somebody
                 if winner == player:
-                    #the excuse owner win the trick, we check if we have something to give
+                    # the excuse owner win the trick, we check if we have something to give
                     for card in played:
                         if card.points == 0.5:
                             pl_waiting = players_data[player]['wait_for_low']
@@ -203,8 +202,8 @@
                             return
                 return
 
-        if not excuse in played:
-            #the Excuse is not on the table, nothing to do
+        if excuse not in played:
+            # the Excuse is not on the table, nothing to do
             return
 
         excuse_player = None  # Who has played the Excuse ?
@@ -216,15 +215,15 @@
         if excuse_player == winner:
             return  # the excuse player win the trick, nothing to do
 
-        #first we remove the excuse from played cards
+        # first we remove the excuse from played cards
         played.remove(excuse)
-        #then we give it back to the original owner
+        # then we give it back to the original owner
         owner_levees = players_data[excuse_player]['levees']
         owner_levees.append(excuse)
-        #finally we give a low card to the trick winner
+        # finally we give a low card to the trick winner
         low_card = None
-        #We look backward in cards won by the Excuse owner to
-        #find a low value card
+        # We look backward in cards won by the Excuse owner to
+        # find a low value card
         for card_idx in range(len(owner_levees) - 1, -1, -1):
             if owner_levees[card_idx].points == 0.5:
                 low_card = owner_levees[card_idx]
@@ -233,7 +232,7 @@
                 log.debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": excuse_player, "card_waited": low_card, "player_waiting": winner})
                 break
         if not low_card:  # The player has no low card yet
-            #TODO: manage case when player never win a trick with low card
+            # TODO: manage case when player never win a trick with low card
             players_data[excuse_player]['wait_for_low'] = winner
             log.debug(_("%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner})
 
@@ -265,7 +264,7 @@
                 bouts.append(card.value)
             score += card.points
 
-        #We we do a basic check on score calculation
+        # We do a basic check on score calculation
         check_score = 0
         defenseurs = game_data['players'][:]
         defenseurs.remove(game_data['attaquant'])
@@ -305,8 +304,8 @@
         loosers = []
         player_score = {}
         for player in game_data['players']:
-            #TODO: adjust this for 3 and 5 players variants
-            #TODO: manage bonuses (petit au bout, poignée, chelem)
+            # TODO: adjust this for 3 and 5 players variants
+            # TODO: manage bonuses (petit au bout, poignée, chelem)
             player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3
             players_data[player]['score'] += player_score[player]  # we add score of this game to the global score
             if player_score[player] > 0:
@@ -314,7 +313,7 @@
             else:
                 loosers.append(player)
 
-        scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'win' if victory else 'loose'}
+        scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): (s)he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'wins' if victory else 'looses'}
         scores_str += '\n'
         for player in game_data['players']:
             scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': player_score[player], 'total_score': players_data[player]['score']}
@@ -332,7 +331,7 @@
             for card in cards:
                 if card.bout or card.value == "roi":
                     forbidden_cards.append(card)
-                #TODO: manage case where atouts (trumps) are in the dog
+                # TODO: manage case where atouts (trumps) are in the dog
         elif game_data['stage'] == 'play':
             biggest_atout = None
             suit_asked = None
@@ -342,7 +341,7 @@
             current_idx = game_data['current_player']
             current_player = players[current_idx]
             if idx == current_idx:
-                #the player is the first to play, he can play what he wants
+                # the player is the first to play, he can play what he wants
                 return forbidden_cards
             while (idx != current_idx):
                 player = players[idx]
@@ -398,13 +397,13 @@
             # TODO: send error dialog
             return defer.succeed({})
 
-        room_jid_s = session_data['room_jid'].userhost()
-        referee = self.games[room_jid_s]['referee']
-        player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
+        room_jid = session_data['room_jid']
+        referee_jid = self.games[room_jid]['referee']
+        player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
         data = xml_tools.XMLUIResult2DataFormResult(raw_data)
         contrat = data['contrat']
         log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
-        d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
+        d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
         d.addCallback(lambda ignore: {})
         del self._sessions[raw_data["session_id"]]
         return d
@@ -443,7 +442,7 @@
         self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
 
     def newRound(self, room_jid, profile):
-        game_data = self.games[room_jid.userhost()]
+        game_data = self.games[room_jid]
         players = game_data['players']
         game_data['first_player'] = None  # first player for the current trick
         game_data['contrat'] = None
@@ -480,11 +479,11 @@
         """
         from_jid = jid.JID(mess_elt['from'])
         room_jid = jid.JID(from_jid.userhost())
-        nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
+        nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
 
         game_elt = mess_elt.firstChildElement()
-        game_data = self.games[room_jid.userhost()]
-        is_player = self.isPlayer(room_jid.userhost(), nick)
+        game_data = self.games[room_jid]
+        is_player = self.isPlayer(room_jid, nick)
         if 'players_data' in game_data:
             players_data = game_data['players_data']
 
@@ -501,8 +500,8 @@
 
             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 = self.games[room_jid]['status']
+                nb_players = len(self.games[room_jid]['players'])
                 status[player] = 'ready'
                 log.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
@@ -519,13 +518,13 @@
                 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
 
             elif elt.name == 'contrat_choosed':
-                #TODO: check we receive the contrat from the right person
-                #TODO: use proper XEP-0004 way for answering form
+                # TODO: check we receive the contrat from the right person
+                # 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
+                    # 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:
                     self.send(to_jid, self.__ask_contrat(), profile=profile)
@@ -553,16 +552,16 @@
                         self.__start_play(room_jid, game_data, profile)
                         game_data['attaquant'] = best_contrat[0]
                     else:
-                        #Time to show the chien to everybody
+                        # Time to show the chien to everybody
                         to_jid = jid.JID(room_jid.userhost())  # FIXME: gof:
                         elem = self.__card_list_to_xml(game_data['chien'], 'chien')
                         self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile)
-                        #the attacker (attaquant) get the chien
+                        # the attacker (attaquant) get the chien
                         game_data['hand'][best_contrat[0]].extend(game_data['chien'])
                         del game_data['chien'][:]
 
                     if game_data['contrat'] == "Garde Sans":
-                        #The chien go into attaquant's (attacker) levees
+                        # The chien go into attaquant's (attacker) levees
                         players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
                         del game_data['chien'][:]
 
@@ -575,17 +574,17 @@
 
             elif elt.name == 'cards_played':
                 if game_data['stage'] == "ecart":
-                    #TODO: show atouts (trumps) if player put some in écart
+                    # TODO: show atouts (trumps) if player put some in écart
                     assert (game_data['attaquant'] == elt['player'])  # TODO: throw an xml error here
                     list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
-                    #we now check validity of card
+                    # we now check validity of card
                     invalid_cards = self.__invalid_cards(game_data, list_cards)
                     if invalid_cards:
                         elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])
                         self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile)
                         return
 
-                    #FIXME: gof: manage Garde Sans & Garde Contre cases
+                    # FIXME: gof: manage Garde Sans & Garde Contre cases
                     players_data[elt['player']]['levees'].extend(list_cards)  # we add the chien to attaquant's levées
                     for card in list_cards:
                         game_data['hand'][elt['player']].remove(card)
@@ -599,46 +598,46 @@
                     if mess_elt['type'] == 'groupchat':
                         self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
                     else:
-                        #we first check validity of card
+                        # we first check validity of card
                         invalid_cards = self.__invalid_cards(game_data, cards)
                         if invalid_cards:
                             elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage'])
                             self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile)
                             return
-                        #the card played is ok, we forward it to everybody
-                        #first we remove it from the hand and put in on the table
+                        # the card played is ok, we forward it to everybody
+                        # first we remove it from the hand and put in on the table
                         game_data['hand'][current_player].remove(cards[0])
                         players_data[current_player]['played'] = cards[0]
 
-                        #then we forward the message
+                        # then we forward the message
                         self.send(room_jid, elt, profile=profile)
 
-                        #Did everybody played ?
+                        # Did everybody played ?
                         played = [players_data[player]['played'] for player in game_data['players']]
                         if all(played):
-                            #everybody has played
+                            # everybody has played
                             winner = self.__winner(game_data)
                             log.debug(_('The winner of this trick is %s') % winner)
-                            #the winner win the trick
+                            # the winner win the trick
                             self.__excuse_hack(game_data, played, winner)
                             players_data[elt['player']]['levees'].extend(played)
-                            #nothing left on the table
+                            # nothing left on the table
                             for player in game_data['players']:
                                 players_data[player]['played'] = None
                             if len(game_data['hand'][current_player]) == 0:
-                                #no card lef: the game is finished
+                                # no card left: the game is finished
                                 elem = self.__give_scores(*self.__calculate_scores(game_data))
                                 self.send(room_jid, elem, profile=profile)
                                 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players'])  # we change the dealer
                                 for player in game_data['players']:
                                     game_data['status'][player] = "init"
                                 return
-                            #next player is the winner
+                            # next player is the winner
                             next_player = game_data['first_player'] = self.__next_player(game_data, winner)
                         else:
                             next_player = self.__next_player(game_data)
 
-                        #finally, we tell to the next player to play
+                        # finally, we tell to the next player to play
                         to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
                         self.send(to_jid, 'your_turn', profile=profile)
 
@@ -668,5 +667,5 @@
             else:
                 log.error(_('Unmanaged card game element: %s') % elt.name)
 
-    def getSyncDataForPlayer(self, room_jid_s, nick):
+    def getSyncDataForPlayer(self, room_jid, nick):
         return []