comparison src/plugins/plugin_misc_tarot.py @ 594:e629371a28d3

Fix pep8 support in src/plugins.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:35 +0100
parents beaf6bec2fcd
children 84a6e83157c2
comparison
equal deleted inserted replaced
593:70bae685d05c 594:e629371a28d3
41 NS_CG = 'http://www.goffi.org/protocol/card_game' 41 NS_CG = 'http://www.goffi.org/protocol/card_game'
42 CG_TAG = 'card_game' 42 CG_TAG = 'card_game'
43 CG_REQUEST = MESSAGE + '/' + CG_TAG + '[@xmlns="' + NS_CG + '"]' 43 CG_REQUEST = MESSAGE + '/' + CG_TAG + '[@xmlns="' + NS_CG + '"]'
44 44
45 PLUGIN_INFO = { 45 PLUGIN_INFO = {
46 "name": "Tarot cards plugin", 46 "name": "Tarot cards plugin",
47 "import_name": "Tarot", 47 "import_name": "Tarot",
48 "type": "Misc", 48 "type": "Misc",
49 "protocols": [], 49 "protocols": [],
50 "dependencies": ["XEP-0045", "XEP-0249"], 50 "dependencies": ["XEP-0045", "XEP-0249"],
51 "main": "Tarot", 51 "main": "Tarot",
52 "handler": "yes", 52 "handler": "yes",
53 "description": _("""Implementation of Tarot card game""") 53 "description": _("""Implementation of Tarot card game""")
54 } 54 }
55 55
56 56
57 class Tarot(object): 57 class Tarot(object):
58 58
59 def __init__(self, host): 59 def __init__(self, host):
60 info(_("Plugin Tarot initialization")) 60 info(_("Plugin Tarot initialization"))
61 self.host = host 61 self.host = host
62 self.games={} 62 self.games = {}
63 self.waiting_inv = {} #Invitation waiting for people to join to launch a game 63 self.waiting_inv = {} # Invitation waiting for people to join to launch a game
64 self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')] 64 self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
65 host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='ass', out_sign='', method=self.launchGame) #args: room_jid, players, profile 65 host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='ass', out_sign='', method=self.launchGame) # args: room_jid, players, profile
66 host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) #args: room_jid, players, profile 66 host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) # args: room_jid, players, profile
67 host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: player, referee, profile 67 host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.newPlayerReady) # args: player, referee, profile
68 host.bridge.addMethod("tarotGameContratChoosed", ".plugin", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: player, referee, contrat, profile 68 host.bridge.addMethod("tarotGameContratChoosed", ".plugin", in_sign='ssss', out_sign='', method=self.contratChoosed) # args: player, referee, contrat, profile
69 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) #args: player, referee, cards, profile 69 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile
70 host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') #args: room_jid, referee, players, profile 70 host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
71 host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') #args: room_jid, hand, profile 71 host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') # args: room_jid, hand, profile
72 host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') #args: room_jid, xml_data, profile 72 host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') # args: room_jid, xml_data, profile
73 host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') #args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile 73 host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') # args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile
74 host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') #args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile 74 host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') # args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile
75 host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') #args: room_jid, profile 75 host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') # args: room_jid, profile
76 host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') #args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile 76 host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
77 host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile 77 host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') # args: room_jid, game phase, played_cards, invalid_cards, profile
78 host.trigger.add("MUC user joined", self.userJoinedTrigger) 78 host.trigger.add("MUC user joined", self.userJoinedTrigger)
79 self.deck_ordered = [] 79 self.deck_ordered = []
80 for value in ['excuse']+map(str,range(1,22)): 80 for value in ['excuse'] + map(str, range(1, 22)):
81 self.deck_ordered.append(TarotCard(("atout",value))) 81 self.deck_ordered.append(TarotCard(("atout", value)))
82 for suit in ["pique", "coeur", "carreau", "trefle"]: 82 for suit in ["pique", "coeur", "carreau", "trefle"]:
83 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]: 83 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
84 self.deck_ordered.append(TarotCard((suit, value))) 84 self.deck_ordered.append(TarotCard((suit, value)))
85 85
86 def createGameElt(self, to_jid, type="normal"): 86 def createGameElt(self, to_jid, type="normal"):
87 type = "normal" if to_jid.resource else "groupchat" 87 type = "normal" if to_jid.resource else "groupchat"
88 elt = domish.Element((None,'message')) 88 elt = domish.Element((None, 'message'))
89 elt["to"] = to_jid.full() 89 elt["to"] = to_jid.full()
90 elt["type"] = type 90 elt["type"] = type
91 elt.addElement((NS_CG, CG_TAG)) 91 elt.addElement((NS_CG, CG_TAG))
92 return elt 92 return elt
93 93
94 def __card_list_to_xml(self, cards_list, elt_name): 94 def __card_list_to_xml(self, cards_list, elt_name):
95 """Convert a card list to domish element""" 95 """Convert a card list to domish element"""
96 cards_list_elt = domish.Element((None,elt_name)) 96 cards_list_elt = domish.Element((None, elt_name))
97 for card in cards_list: 97 for card in cards_list:
98 card_elt = domish.Element((None,'card')) 98 card_elt = domish.Element((None, 'card'))
99 card_elt['suit'] = card.suit 99 card_elt['suit'] = card.suit
100 card_elt['value'] = card.value 100 card_elt['value'] = card.value
101 cards_list_elt.addChild(card_elt) 101 cards_list_elt.addChild(card_elt)
102 return cards_list_elt 102 return cards_list_elt
103 103
106 cards_list = [] 106 cards_list = []
107 for card in cards_list_elt.elements(): 107 for card in cards_list_elt.elements():
108 cards_list.append((card['suit'], card['value'])) 108 cards_list.append((card['suit'], card['value']))
109 return cards_list 109 return cards_list
110 110
111
112 def __create_started_elt(self, players): 111 def __create_started_elt(self, players):
113 """Create a game_started domish element""" 112 """Create a game_started domish element"""
114 started_elt = domish.Element((None,'started')) 113 started_elt = domish.Element((None, 'started'))
115 idx = 0 114 idx = 0
116 for player in players: 115 for player in players:
117 player_elt = domish.Element((None,'player')) 116 player_elt = domish.Element((None, 'player'))
118 player_elt.addContent(player) 117 player_elt.addContent(player)
119 player_elt['index'] = str(idx) 118 player_elt['index'] = str(idx)
120 idx+=1 119 idx += 1
121 started_elt.addChild(player_elt) 120 started_elt.addChild(player_elt)
122 return started_elt 121 return started_elt
123 122
124 def __ask_contrat(self): 123 def __ask_contrat(self):
125 """Create a element for asking contrat""" 124 """Create a element for asking contrat"""
126 contrat_elt = domish.Element((None,'contrat')) 125 contrat_elt = domish.Element((None, 'contrat'))
127 form = data_form.Form('form', title=_('contrat selection')) 126 form = data_form.Form('form', title=_('contrat selection'))
128 field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True) 127 field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True)
129 form.addField(field) 128 form.addField(field)
130 contrat_elt.addChild(form.toElement()) 129 contrat_elt.addChild(form.toElement())
131 return contrat_elt 130 return contrat_elt
134 """Create an element to give scores 133 """Create an element to give scores
135 @param scores: unicode (can contain line feed) 134 @param scores: unicode (can contain line feed)
136 @param winners: list of unicode nicks of winners 135 @param winners: list of unicode nicks of winners
137 @param loosers: list of unicode nicks of loosers""" 136 @param loosers: list of unicode nicks of loosers"""
138 137
139 score_elt = domish.Element((None,'score')) 138 score_elt = domish.Element((None, 'score'))
140 form = data_form.Form('form', title=_('scores')) 139 form = data_form.Form('form', title=_('scores'))
141 for line in scores.split('\n'): 140 for line in scores.split('\n'):
142 field = data_form.Field('fixed', value = line) 141 field = data_form.Field('fixed', value=line)
143 form.addField(field) 142 form.addField(field)
144 score_elt.addChild(form.toElement()) 143 score_elt.addChild(form.toElement())
145 for winner in winners: 144 for winner in winners:
146 winner_elt = domish.Element((None,'winner')) 145 winner_elt = domish.Element((None, 'winner'))
147 winner_elt.addContent(winner) 146 winner_elt.addContent(winner)
148 score_elt.addChild(winner_elt) 147 score_elt.addChild(winner_elt)
149 for looser in loosers: 148 for looser in loosers:
150 looser_elt = domish.Element((None,'looser')) 149 looser_elt = domish.Element((None, 'looser'))
151 looser_elt.addContent(looser) 150 looser_elt.addContent(looser)
152 score_elt.addChild(looser_elt) 151 score_elt.addChild(looser_elt)
153 return score_elt 152 return score_elt
154 153
155 def __invalid_cards_elt(self, played_cards, invalid_cards, game_phase): 154 def __invalid_cards_elt(self, played_cards, invalid_cards, game_phase):
156 """Create a element for invalid_cards error 155 """Create a element for invalid_cards error
157 @param list_cards: list of Card 156 @param list_cards: list of Card
158 @param game_phase: phase of the game ['ecart', 'play']""" 157 @param game_phase: phase of the game ['ecart', 'play']"""
159 error_elt = domish.Element((None,'error')) 158 error_elt = domish.Element((None, 'error'))
160 played_elt = self.__card_list_to_xml(played_cards, 'played') 159 played_elt = self.__card_list_to_xml(played_cards, 'played')
161 invalid_elt = self.__card_list_to_xml(invalid_cards, 'invalid') 160 invalid_elt = self.__card_list_to_xml(invalid_cards, 'invalid')
162 error_elt['type'] = 'invalid_cards' 161 error_elt['type'] = 'invalid_cards'
163 error_elt['phase'] = game_phase 162 error_elt['phase'] = game_phase
164 error_elt.addChild(played_elt) 163 error_elt.addChild(played_elt)
165 error_elt.addChild(invalid_elt) 164 error_elt.addChild(invalid_elt)
166 return error_elt 165 return error_elt
167 166
168 def __next_player(self, game_data, next_pl = None): 167 def __next_player(self, game_data, next_pl=None):
169 """Increment player number & return player name 168 """Increment player number & return player name
170 @param next_pl: if given, then next_player is forced to this one 169 @param next_pl: if given, then next_player is forced to this one
171 """ 170 """
172 if next_pl: 171 if next_pl:
173 game_data['current_player'] = game_data['players'].index(next_pl) 172 game_data['current_player'] = game_data['players'].index(next_pl)
187 for idx in [(first_idx + i) % 4 for i in range(4)]: 186 for idx in [(first_idx + i) % 4 for i in range(4)]:
188 player = game_data['players'][idx] 187 player = game_data['players'][idx]
189 card = players_data[player]['played'] 188 card = players_data[player]['played']
190 if card.value == "excuse": 189 if card.value == "excuse":
191 continue 190 continue
192 if suit_asked == None: 191 if suit_asked is None:
193 suit_asked = card.suit 192 suit_asked = card.suit
194 if (card.suit == suit_asked or card.suit == "atout") and card > strongest: 193 if (card.suit == suit_asked or card.suit == "atout") and card > strongest:
195 strongest = card 194 strongest = card
196 winner = player 195 winner = player
197 assert winner 196 assert winner
202 @param game_data: data of the game 201 @param game_data: data of the game
203 @param played: cards currently on the table 202 @param played: cards currently on the table
204 @param winner: nick of the trick winner""" 203 @param winner: nick of the trick winner"""
205 #TODO: manage the case where excuse is played on the last trick (and lost) 204 #TODO: manage the case where excuse is played on the last trick (and lost)
206 players_data = game_data['players_data'] 205 players_data = game_data['players_data']
207 excuse = TarotCard(("atout","excuse")) 206 excuse = TarotCard(("atout", "excuse"))
208 207
209 #we first check if the Excuse was already played 208 #we first check if the Excuse was already played
210 #and if somebody is waiting for a card 209 #and if somebody is waiting for a card
211 for player in game_data['players']: 210 for player in game_data['players']:
212 if players_data[player]['wait_for_low']: 211 if players_data[player]['wait_for_low']:
216 for card in played: 215 for card in played:
217 if card.points == 0.5: 216 if card.points == 0.5:
218 pl_waiting = players_data[player]['wait_for_low'] 217 pl_waiting = players_data[player]['wait_for_low']
219 played.remove(card) 218 played.remove(card)
220 players_data[pl_waiting]['levees'].append(card) 219 players_data[pl_waiting]['levees'].append(card)
221 debug (_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner":player, "card_waited": card, "player_waiting":pl_waiting}) 220 debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": player, "card_waited": card, "player_waiting": pl_waiting})
222 return 221 return
223 return 222 return
224 223
225 if not excuse in played: 224 if not excuse in played:
226 #the Excuse is not on the table, nothing to do 225 #the Excuse is not on the table, nothing to do
227 return 226 return
228 227
229 excuse_player = None #Who has played the Excuse ? 228 excuse_player = None # Who has played the Excuse ?
230 for player in game_data['players']: 229 for player in game_data['players']:
231 if players_data[player]['played'] == excuse: 230 if players_data[player]['played'] == excuse:
232 excuse_player = player 231 excuse_player = player
233 break 232 break
234 233
235 if excuse_player == winner: 234 if excuse_player == winner:
236 return #the excuse player win the trick, nothing to do 235 return # the excuse player win the trick, nothing to do
237 236
238 #first we remove the excuse from played cards 237 #first we remove the excuse from played cards
239 played.remove(excuse) 238 played.remove(excuse)
240 #then we give it back to the original owner 239 #then we give it back to the original owner
241 owner_levees = players_data[excuse_player]['levees'] 240 owner_levees = players_data[excuse_player]['levees']
242 owner_levees.append(excuse) 241 owner_levees.append(excuse)
243 #finally we give a low card to the trick winner 242 #finally we give a low card to the trick winner
244 low_card = None 243 low_card = None
245 #We look backward in cards won by the Excuse owner to 244 #We look backward in cards won by the Excuse owner to
246 #find a low value card 245 #find a low value card
247 for card_idx in range(len(owner_levees)-1, -1, -1): 246 for card_idx in range(len(owner_levees) - 1, -1, -1):
248 if owner_levees[card_idx].points == 0.5: 247 if owner_levees[card_idx].points == 0.5:
249 low_card = owner_levees[card_idx] 248 low_card = owner_levees[card_idx]
250 del owner_levees[card_idx] 249 del owner_levees[card_idx]
251 players_data[winner]['levees'].append(low_card) 250 players_data[winner]['levees'].append(low_card)
252 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}) 251 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})
253 break 252 break
254 if not low_card: #The player has no low card yet 253 if not low_card: # The player has no low card yet
255 #TODO: manage case when player never win a trick with low card 254 #TODO: manage case when player never win a trick with low card
256 players_data[excuse_player]['wait_for_low'] = winner 255 players_data[excuse_player]['wait_for_low'] = winner
257 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}) 256 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})
258
259 257
260 def __draw_game(self, game_data): 258 def __draw_game(self, game_data):
261 """The game is draw, no score change 259 """The game is draw, no score change
262 @param game_data: data of the game 260 @param game_data: data of the game
263 @return: tuple with (string victory message, list of winners, list of loosers)""" 261 @return: tuple with (string victory message, list of winners, list of loosers)"""
264 players_data = game_data['players_data'] 262 players_data = game_data['players_data']
265 scores_str = _('Draw game') 263 scores_str = _('Draw game')
266 scores_str+='\n' 264 scores_str += '\n'
267 for player in game_data['players']: 265 for player in game_data['players']:
268 scores_str+=_("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player':player, 'score_game':0, 'total_score': players_data[player]['score']} 266 scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': 0, 'total_score': players_data[player]['score']}
269 debug(scores_str) 267 debug(scores_str)
270 268
271 return (scores_str, [], []) 269 return (scores_str, [], [])
272
273 270
274 def __calculate_scores(self, game_data): 271 def __calculate_scores(self, game_data):
275 """The game is finished, time to know who won :) 272 """The game is finished, time to know who won :)
276 @param game_data: data of the game 273 @param game_data: data of the game
277 @return: tuple with (string victory message, list of winners, list of loosers)""" 274 @return: tuple with (string victory message, list of winners, list of loosers)"""
280 score = 0 277 score = 0
281 nb_bouts = 0 278 nb_bouts = 0
282 bouts = [] 279 bouts = []
283 for card in levees: 280 for card in levees:
284 if card.bout: 281 if card.bout:
285 nb_bouts +=1 282 nb_bouts += 1
286 bouts.append(card.value) 283 bouts.append(card.value)
287 score += card.points 284 score += card.points
288 285
289 #We we do a basic check on score calculation 286 #We we do a basic check on score calculation
290 check_score = 0 287 check_score = 0
291 defenseurs = game_data['players'][:] 288 defenseurs = game_data['players'][:]
292 defenseurs.remove(game_data['attaquant']) 289 defenseurs.remove(game_data['attaquant'])
293 for defenseur in defenseurs: 290 for defenseur in defenseurs:
294 for card in players_data[defenseur]['levees']: 291 for card in players_data[defenseur]['levees']:
295 check_score+=card.points 292 check_score += card.points
296 if game_data['contrat'] == "Garde Contre": 293 if game_data['contrat'] == "Garde Contre":
297 for card in game_data['chien']: 294 for card in game_data['chien']:
298 check_score+=card.points 295 check_score += card.points
299 assert (score + check_score == 91) 296 assert (score + check_score == 91)
300 297
301 point_limit = None 298 point_limit = None
302 if nb_bouts == 3: 299 if nb_bouts == 3:
303 point_limit = 36 300 point_limit = 36
327 player_score = {} 324 player_score = {}
328 for player in game_data['players']: 325 for player in game_data['players']:
329 #TODO: adjust this for 3 and 5 players variants 326 #TODO: adjust this for 3 and 5 players variants
330 #TODO: manage bonuses (petit au bout, poignée, chelem) 327 #TODO: manage bonuses (petit au bout, poignée, chelem)
331 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3 328 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3
332 players_data[player]['score'] += player_score[player] #we add score of this game to the global score 329 players_data[player]['score'] += player_score[player] # we add score of this game to the global score
333 if player_score[player] > 0: 330 if player_score[player] > 0:
334 winners.append(player) 331 winners.append(player)
335 else: 332 else:
336 loosers.append(player) 333 loosers.append(player)
337 334
338 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'} 335 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'}
339 scores_str+='\n' 336 scores_str += '\n'
340 for player in game_data['players']: 337 for player in game_data['players']:
341 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']} 338 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']}
342 debug(scores_str) 339 debug(scores_str)
343 340
344 return (scores_str, winners, loosers) 341 return (scores_str, winners, loosers)
345 342
346 def __invalid_cards(self, game_data, cards): 343 def __invalid_cards(self, game_data, cards):
349 @param cards: cards the player want to play 346 @param cards: cards the player want to play
350 @return forbidden_cards cards or empty list if cards are ok""" 347 @return forbidden_cards cards or empty list if cards are ok"""
351 forbidden_cards = [] 348 forbidden_cards = []
352 if game_data['stage'] == 'ecart': 349 if game_data['stage'] == 'ecart':
353 for card in cards: 350 for card in cards:
354 if card.bout or card.value=="roi": 351 if card.bout or card.value == "roi":
355 forbidden_cards.append(card) 352 forbidden_cards.append(card)
356 #TODO: manage case where atouts (trumps) are in the dog 353 #TODO: manage case where atouts (trumps) are in the dog
357 elif game_data['stage'] == 'play': 354 elif game_data['stage'] == 'play':
358 biggest_atout = None 355 biggest_atout = None
359 suit_asked = None 356 suit_asked = None
371 if not suit_asked and played_card.value != "excuse": 368 if not suit_asked and played_card.value != "excuse":
372 suit_asked = played_card.suit 369 suit_asked = played_card.suit
373 if played_card.suit == "atout" and played_card > biggest_atout: 370 if played_card.suit == "atout" and played_card > biggest_atout:
374 biggest_atout = played_card 371 biggest_atout = played_card
375 idx = (idx + 1) % len(players) 372 idx = (idx + 1) % len(players)
376 has_suit = False #True if there is one card of the asked suit in the hand of the player 373 has_suit = False # True if there is one card of the asked suit in the hand of the player
377 has_atout = False 374 has_atout = False
378 biggest_hand_atout = None 375 biggest_hand_atout = None
379 376
380 for hand_card in game_data['hand'][current_player]: 377 for hand_card in game_data['hand'][current_player]:
381 if hand_card.suit == suit_asked: 378 if hand_card.suit == suit_asked:
397 forbidden_cards.append(card) 394 forbidden_cards.append(card)
398 else: 395 else:
399 error(_('Internal error: unmanaged game stage')) 396 error(_('Internal error: unmanaged game stage'))
400 return forbidden_cards 397 return forbidden_cards
401 398
402
403 def __start_play(self, room_jid, game_data, profile): 399 def __start_play(self, room_jid, game_data, profile):
404 """Start the game (tell to the first player after dealer to play""" 400 """Start the game (tell to the first player after dealer to play"""
405 game_data['stage'] = "play" 401 game_data['stage'] = "play"
406 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #the player after the dealer start 402 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # the player after the dealer start
407 game_data['first_player'] = next_player = game_data['players'][next_player_idx] 403 game_data['first_player'] = next_player = game_data['players'][next_player_idx]
408 to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof: 404 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) # FIXME: gof:
409 mess = self.createGameElt(to_jid) 405 mess = self.createGameElt(to_jid)
410 yourturn_elt = mess.firstChildElement().addElement('your_turn') 406 yourturn_elt = mess.firstChildElement().addElement('your_turn')
411 self.host.profiles[profile].xmlstream.send(mess) 407 self.host.profiles[profile].xmlstream.send(mess)
412
413 408
414 def userJoinedTrigger(self, room, user, profile): 409 def userJoinedTrigger(self, room, user, profile):
415 """This trigger is used to check if we are waiting people in this room, 410 """This trigger is used to check if we are waiting people in this room,
416 and to create a game if everybody is here""" 411 and to create a game if everybody is here"""
417 _room_jid = room.occupantJID.userhostJID() 412 _room_jid = room.occupantJID.userhostJID()
433 return 428 return
434 429
435 def tarotRoomJoined(room): 430 def tarotRoomJoined(room):
436 _room = room.occupantJID.userhostJID() 431 _room = room.occupantJID.userhostJID()
437 for player in players: 432 for player in players:
438 self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Tarot"}, profile) 433 self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game": "Tarot"}, profile)
439 self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data 434 self.waiting_inv[_room] = (time(), players) # TODO: remove invitation waiting for too long, using the time data
440 435
441 def after_init(ignore): 436 def after_init(ignore):
442 room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key) 437 room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
443 print "\n\n===> room_name:", room_name 438 print "\n\n===> room_name:", room_name
444 #muc_service = self.host.memory.getServerServiceEntity("conference", "text", profile) 439 #muc_service = self.host.memory.getServerServiceEntity("conference", "text", profile)
462 if not client: 457 if not client:
463 error(_('No client for this profile key: %s') % profile_key) 458 error(_('No client for this profile key: %s') % profile_key)
464 return 459 return
465 client.client_initialized.addCallback(after_init) 460 client.client_initialized.addCallback(after_init)
466 461
467
468
469
470 def createGame(self, room_jid_param, players, profile_key='@NONE@'): 462 def createGame(self, room_jid_param, players, profile_key='@NONE@'):
471 """Create a new game 463 """Create a new game
472 @param room_jid_param: jid of the room 464 @param room_jid_param: jid of the room
473 @param players: list of players nick (nick must exist in the room) 465 @param players: list of players nick (nick must exist in the room)
474 @param profile_key: %(doc_profile_key)s""" 466 @param profile_key: %(doc_profile_key)s"""
475 debug (_("Creating Tarot game")) 467 debug(_("Creating Tarot game"))
476 room_jid = jid.JID(room_jid_param) 468 room_jid = jid.JID(room_jid_param)
477 profile = self.host.memory.getProfileName(profile_key) 469 profile = self.host.memory.getProfileName(profile_key)
478 if not profile: 470 if not profile:
479 error (_("profile %s is unknown") % profile_key) 471 error(_("profile %s is unknown") % profile_key)
480 return 472 return
481 if self.games.has_key(room_jid): 473 if room_jid in self.games:
482 warning (_("Tarot game already started in room %s") % room_jid.userhost()) 474 warning(_("Tarot game already started in room %s") % room_jid.userhost())
483 else: 475 else:
484 room_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile) 476 room_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
485 if not room_nick: 477 if not room_nick:
486 error ('Internal error') 478 error('Internal error')
487 return 479 return
488 referee = room_jid.userhost() + '/' + room_nick 480 referee = room_jid.userhost() + '/' + room_nick
489 status = {} 481 status = {}
490 players_data = {} 482 players_data = {}
491 for player in players: 483 for player in players:
492 players_data[player] = {'score':0} 484 players_data[player] = {'score': 0}
493 status[player] = "init" 485 status[player] = "init"
494 self.games[room_jid.userhost()] = {'referee':referee, 'players':players, 'status':status, 'players_data':players_data, 'hand_size':18, 'init_player':0, 'current_player': None, 'contrat': None, 'stage': None} 486 self.games[room_jid.userhost()] = {'referee': referee, 'players': players, 'status': status, 'players_data': players_data, 'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}
495 for player in players: 487 for player in players:
496 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player)) 488 mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + player))
497 mess.firstChildElement().addChild(self.__create_started_elt(players)) 489 mess.firstChildElement().addChild(self.__create_started_elt(players))
498 self.host.profiles[profile].xmlstream.send(mess) 490 self.host.profiles[profile].xmlstream.send(mess)
499 491
500 def newPlayerReady(self, player, referee, profile_key='@NONE@'): 492 def newPlayerReady(self, player, referee, profile_key='@NONE@'):
501 """Must be called when player is ready to start a new game""" 493 """Must be called when player is ready to start a new game"""
502 profile = self.host.memory.getProfileName(profile_key) 494 profile = self.host.memory.getProfileName(profile_key)
503 if not profile: 495 if not profile:
504 error (_("profile %s is unknown") % profile_key) 496 error(_("profile %s is unknown") % profile_key)
505 return 497 return
506 debug ('new player ready: %s' % profile) 498 debug('new player ready: %s' % profile)
507 mess = self.createGameElt(jid.JID(referee)) 499 mess = self.createGameElt(jid.JID(referee))
508 ready_elt = mess.firstChildElement().addElement('player_ready') 500 ready_elt = mess.firstChildElement().addElement('player_ready')
509 ready_elt['player'] = player 501 ready_elt['player'] = player
510 self.host.profiles[profile].xmlstream.send(mess) 502 self.host.profiles[profile].xmlstream.send(mess)
511 503
516 @contrat: contrat choosed (must be the exact same string than in the give list options) 508 @contrat: contrat choosed (must be the exact same string than in the give list options)
517 @profile_key: profile 509 @profile_key: profile
518 """ 510 """
519 profile = self.host.memory.getProfileName(profile_key) 511 profile = self.host.memory.getProfileName(profile_key)
520 if not profile: 512 if not profile:
521 error (_("profile %s is unknown") % profile_key) 513 error(_("profile %s is unknown") % profile_key)
522 return 514 return
523 debug (_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat':contrat, 'profile':profile}) 515 debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
524 mess = self.createGameElt(jid.JID(referee)) 516 mess = self.createGameElt(jid.JID(referee))
525 contrat_elt = mess.firstChildElement().addElement(('','contrat_choosed'), content=contrat) 517 contrat_elt = mess.firstChildElement().addElement(('', 'contrat_choosed'), content=contrat)
526 contrat_elt['player'] = player 518 contrat_elt['player'] = player
527 self.host.profiles[profile].xmlstream.send(mess) 519 self.host.profiles[profile].xmlstream.send(mess)
528 520
529 def play_cards(self, player, referee, cards, profile_key='@NONE@'): 521 def play_cards(self, player, referee, cards, profile_key='@NONE@'):
530 """Must be call by player when the contrat is selected 522 """Must be call by player when the contrat is selected
533 @cards: cards played (list of tuples) 525 @cards: cards played (list of tuples)
534 @profile_key: profile 526 @profile_key: profile
535 """ 527 """
536 profile = self.host.memory.getProfileName(profile_key) 528 profile = self.host.memory.getProfileName(profile_key)
537 if not profile: 529 if not profile:
538 error (_("profile %s is unknown") % profile_key) 530 error(_("profile %s is unknown") % profile_key)
539 return 531 return
540 debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards}) 532 debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
541 mess = self.createGameElt(jid.JID(referee)) 533 mess = self.createGameElt(jid.JID(referee))
542 playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played')) 534 playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played'))
543 playcard_elt['player'] = player 535 playcard_elt['player'] = player
544 self.host.profiles[profile].xmlstream.send(mess) 536 self.host.profiles[profile].xmlstream.send(mess)
545 537
546 def newGame(self, room_jid, profile): 538 def newGame(self, room_jid, profile):
547 """Launch a new round""" 539 """Launch a new round"""
548 debug (_('new Tarot game')) 540 debug(_('new Tarot game'))
549 deck = self.deck_ordered[:] 541 deck = self.deck_ordered[:]
550 random.shuffle(deck) 542 random.shuffle(deck)
551 game_data = self.games[room_jid.userhost()] 543 game_data = self.games[room_jid.userhost()]
552 players = game_data['players'] 544 players = game_data['players']
553 players_data = game_data['players_data'] 545 players_data = game_data['players_data']
554 current_player = game_data['current_player'] 546 current_player = game_data['current_player']
555 game_data['stage'] = "init" 547 game_data['stage'] = "init"
556 game_data['first_player'] = None #first player for the current trick 548 game_data['first_player'] = None # first player for the current trick
557 game_data['contrat'] = None 549 game_data['contrat'] = None
558 hand = game_data['hand'] = {} 550 hand = game_data['hand'] = {}
559 hand_size = game_data['hand_size'] 551 hand_size = game_data['hand_size']
560 chien = game_data['chien'] = [] 552 chien = game_data['chien'] = []
561 for i in range(4): 553 for i in range(4):
563 del deck[0:hand_size] 555 del deck[0:hand_size]
564 chien.extend(deck) 556 chien.extend(deck)
565 del(deck[:]) 557 del(deck[:])
566 558
567 for player in players: 559 for player in players:
568 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: 560 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
569 mess = self.createGameElt(to_jid) 561 mess = self.createGameElt(to_jid)
570 mess.firstChildElement().addChild(self.__card_list_to_xml(hand[player], 'hand')) 562 mess.firstChildElement().addChild(self.__card_list_to_xml(hand[player], 'hand'))
571 self.host.profiles[profile].xmlstream.send(mess) 563 self.host.profiles[profile].xmlstream.send(mess)
572 players_data[player]['contrat'] = None 564 players_data[player]['contrat'] = None
573 players_data[player]['levees'] = [] #cards won 565 players_data[player]['levees'] = [] # cards won
574 players_data[player]['played'] = None #card on the table 566 players_data[player]['played'] = None # card on the table
575 players_data[player]['wait_for_low'] = None #Used when a player wait for a low card because of excuse 567 players_data[player]['wait_for_low'] = None # Used when a player wait for a low card because of excuse
576 568
577 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) #the player after the dealer start 569 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) # the player after the dealer start
578 player = players[pl_idx] 570 player = players[pl_idx]
579 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: 571 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
580 mess = self.createGameElt(to_jid) 572 mess = self.createGameElt(to_jid)
581 mess.firstChildElement().addChild(self.__ask_contrat()) 573 mess.firstChildElement().addChild(self.__ask_contrat())
582 self.host.profiles[profile].xmlstream.send(mess) 574 self.host.profiles[profile].xmlstream.send(mess)
583
584 575
585 def card_game_cmd(self, mess_elt, profile): 576 def card_game_cmd(self, mess_elt, profile):
586 from_jid = jid.JID(mess_elt['from']) 577 from_jid = jid.JID(mess_elt['from'])
587 room_jid = jid.JID(from_jid.userhost()) 578 room_jid = jid.JID(from_jid.userhost())
588 game_elt = mess_elt.firstChildElement() 579 game_elt = mess_elt.firstChildElement()
589 game_data = self.games[room_jid.userhost()] 580 game_data = self.games[room_jid.userhost()]
590 players_data = game_data['players_data'] 581 players_data = game_data['players_data']
591 582
592 for elt in game_elt.elements(): 583 for elt in game_elt.elements():
593 584
594 if elt.name == 'started': #new game created 585 if elt.name == 'started': # new game created
595 players = [] 586 players = []
596 for player in elt.elements(): 587 for player in elt.elements():
597 players.append(unicode(player)) 588 players.append(unicode(player))
598 self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile) 589 self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile)
599 590
600 elif elt.name == 'player_ready': #ready to play 591 elif elt.name == 'player_ready': # ready to play
601 player = elt['player'] 592 player = elt['player']
602 status = self.games[room_jid.userhost()]['status'] 593 status = self.games[room_jid.userhost()]['status']
603 nb_players = len(self.games[room_jid.userhost()]['players']) 594 nb_players = len(self.games[room_jid.userhost()]['players'])
604 status[player] = 'ready' 595 status[player] = 'ready'
605 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) 596 debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
606 if status.values().count('ready') == nb_players: #everybody is ready, we can start the game 597 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
607 self.newGame(room_jid, profile) 598 self.newGame(room_jid, profile)
608 599
609 elif elt.name == 'hand': #a new hand has been received 600 elif elt.name == 'hand': # a new hand has been received
610 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) 601 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile)
611 602
612 elif elt.name == 'contrat': #it's time to choose contrat 603 elif elt.name == 'contrat': # it's time to choose contrat
613 form = data_form.Form.fromElement(elt.firstChildElement()) 604 form = data_form.Form.fromElement(elt.firstChildElement())
614 xml_data = dataForm2xml(form) 605 xml_data = dataForm2xml(form)
615 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) 606 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
616 607
617 elif elt.name == 'contrat_choosed': 608 elif elt.name == 'contrat_choosed':
621 players_data[player]['contrat'] = unicode(elt) 612 players_data[player]['contrat'] = unicode(elt)
622 contrats = [players_data[player]['contrat'] for player in game_data['players']] 613 contrats = [players_data[player]['contrat'] for player in game_data['players']]
623 if contrats.count(None): 614 if contrats.count(None):
624 #not everybody has choosed his contrat, it's next one turn 615 #not everybody has choosed his contrat, it's next one turn
625 player = self.__next_player(game_data) 616 player = self.__next_player(game_data)
626 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: 617 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
627 mess = self.createGameElt(to_jid) 618 mess = self.createGameElt(to_jid)
628 mess.firstChildElement().addChild(self.__ask_contrat()) 619 mess.firstChildElement().addChild(self.__ask_contrat())
629 self.host.profiles[profile].xmlstream.send(mess) 620 self.host.profiles[profile].xmlstream.send(mess)
630 else: 621 else:
631 best_contrat = [None, "Passe"] 622 best_contrat = [None, "Passe"]
640 debug(_("Everybody is passing, round ended")) 631 debug(_("Everybody is passing, round ended"))
641 to_jid = jid.JID(room_jid.userhost()) 632 to_jid = jid.JID(room_jid.userhost())
642 mess = self.createGameElt(to_jid) 633 mess = self.createGameElt(to_jid)
643 mess.firstChildElement().addChild(self.__give_scores(*self.__draw_game(game_data))) 634 mess.firstChildElement().addChild(self.__give_scores(*self.__draw_game(game_data)))
644 self.host.profiles[profile].xmlstream.send(mess) 635 self.host.profiles[profile].xmlstream.send(mess)
645 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #we change the dealer 636 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
646 for player in game_data['players']: 637 for player in game_data['players']:
647 game_data['status'][player] = "init" 638 game_data['status'][player] = "init"
648 return 639 return
649 debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]}) 640 debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]})
650 game_data['contrat'] = best_contrat[1] 641 game_data['contrat'] = best_contrat[1]
651 642
652 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": 643 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
653 self.__start_play(room_jid, game_data, profile) 644 self.__start_play(room_jid, game_data, profile)
654 game_data['attaquant'] = best_contrat[0] 645 game_data['attaquant'] = best_contrat[0]
655 else: 646 else:
656 #Time to show the chien to everybody 647 #Time to show the chien to everybody
657 to_jid = jid.JID(room_jid.userhost()) #FIXME: gof: 648 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
658 mess = self.createGameElt(to_jid) 649 mess = self.createGameElt(to_jid)
659 chien_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(game_data['chien'], 'chien')) 650 chien_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(game_data['chien'], 'chien'))
660 chien_elt['attaquant'] = best_contrat[0] 651 chien_elt['attaquant'] = best_contrat[0]
661 self.host.profiles[profile].xmlstream.send(mess) 652 self.host.profiles[profile].xmlstream.send(mess)
662 #the attacker (attaquant) get the chien 653 #the attacker (attaquant) get the chien
666 if game_data['contrat'] == "Garde Sans": 657 if game_data['contrat'] == "Garde Sans":
667 #The chien go into attaquant's (attacker) levees 658 #The chien go into attaquant's (attacker) levees
668 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) 659 players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
669 del game_data['chien'][:] 660 del game_data['chien'][:]
670 661
671 662 elif elt.name == 'chien': # we have received the chien
672 elif elt.name == 'chien': #we have received the chien 663 debug(_("tarot: chien received"))
673 debug (_("tarot: chien received")) 664 data = {"attaquant": elt['attaquant']}
674 data = {"attaquant":elt['attaquant']}
675 game_data['stage'] = "ecart" 665 game_data['stage'] = "ecart"
676 game_data['attaquant'] = elt['attaquant'] 666 game_data['attaquant'] = elt['attaquant']
677 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) 667 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile)
678 668
679 elif elt.name == 'cards_played': 669 elif elt.name == 'cards_played':
680 if game_data['stage'] == "ecart": 670 if game_data['stage'] == "ecart":
681 #TODO: show atouts (trumps) if player put some in écart 671 #TODO: show atouts (trumps) if player put some in écart
682 assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here 672 assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here
683 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 673 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
684 #we now check validity of card 674 #we now check validity of card
685 invalid_cards = self.__invalid_cards(game_data, list_cards) 675 invalid_cards = self.__invalid_cards(game_data, list_cards)
686 if invalid_cards: 676 if invalid_cards:
687 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+elt['player'])) 677 mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + elt['player']))
688 mess.firstChildElement().addChild(self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])) 678 mess.firstChildElement().addChild(self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']))
689 self.host.profiles[profile].xmlstream.send(mess) 679 self.host.profiles[profile].xmlstream.send(mess)
690 return 680 return
691 681
692 #FIXME: gof: manage Garde Sans & Garde Contre cases 682 #FIXME: gof: manage Garde Sans & Garde Contre cases
693 players_data[elt['player']]['levees'].extend(list_cards) #we add the chien to attaquant's levées 683 players_data[elt['player']]['levees'].extend(list_cards) # we add the chien to attaquant's levées
694 for card in list_cards: 684 for card in list_cards:
695 game_data['hand'][elt['player']].remove(card) 685 game_data['hand'][elt['player']].remove(card)
696 686
697 self.__start_play(room_jid, game_data, profile) 687 self.__start_play(room_jid, game_data, profile)
698 688
704 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) 694 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
705 else: 695 else:
706 #we first check validity of card 696 #we first check validity of card
707 invalid_cards = self.__invalid_cards(game_data, cards) 697 invalid_cards = self.__invalid_cards(game_data, cards)
708 if invalid_cards: 698 if invalid_cards:
709 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+current_player)) 699 mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + current_player))
710 mess.firstChildElement().addChild(self.__invalid_cards_elt(cards, invalid_cards, game_data['stage'])) 700 mess.firstChildElement().addChild(self.__invalid_cards_elt(cards, invalid_cards, game_data['stage']))
711 self.host.profiles[profile].xmlstream.send(mess) 701 self.host.profiles[profile].xmlstream.send(mess)
712 return 702 return
713 #the card played is ok, we forward it to everybody 703 #the card played is ok, we forward it to everybody
714 #first we remove it from the hand and put in on the table 704 #first we remove it from the hand and put in on the table
723 #Did everybody played ? 713 #Did everybody played ?
724 played = [players_data[player]['played'] for player in game_data['players']] 714 played = [players_data[player]['played'] for player in game_data['players']]
725 if all(played): 715 if all(played):
726 #everybody has played 716 #everybody has played
727 winner = self.__winner(game_data) 717 winner = self.__winner(game_data)
728 debug (_('The winner of this trick is %s') % winner) 718 debug(_('The winner of this trick is %s') % winner)
729 #the winner win the trick 719 #the winner win the trick
730 self.__excuse_hack(game_data, played, winner) 720 self.__excuse_hack(game_data, played, winner)
731 players_data[elt['player']]['levees'].extend(played) 721 players_data[elt['player']]['levees'].extend(played)
732 #nothing left on the table 722 #nothing left on the table
733 for player in game_data['players']: 723 for player in game_data['players']:
736 #no card lef: the game is finished 726 #no card lef: the game is finished
737 to_jid = room_jid 727 to_jid = room_jid
738 mess = self.createGameElt(to_jid) 728 mess = self.createGameElt(to_jid)
739 chien_elt = mess.firstChildElement().addChild(self.__give_scores(*self.__calculate_scores(game_data))) 729 chien_elt = mess.firstChildElement().addChild(self.__give_scores(*self.__calculate_scores(game_data)))
740 self.host.profiles[profile].xmlstream.send(mess) 730 self.host.profiles[profile].xmlstream.send(mess)
741 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #we change the dealer 731 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
742 for player in game_data['players']: 732 for player in game_data['players']:
743 game_data['status'][player] = "init" 733 game_data['status'][player] = "init"
744 return 734 return
745 #next player is the winner 735 #next player is the winner
746 next_player = game_data['first_player'] = self.__next_player(game_data, winner) 736 next_player = game_data['first_player'] = self.__next_player(game_data, winner)
747 else: 737 else:
748 next_player = self.__next_player(game_data) 738 next_player = self.__next_player(game_data)
749 739
750 #finally, we tell to the next player to play 740 #finally, we tell to the next player to play
751 to_jid = jid.JID(room_jid.userhost()+"/"+next_player) 741 to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
752 mess = self.createGameElt(to_jid) 742 mess = self.createGameElt(to_jid)
753 yourturn_elt = mess.firstChildElement().addElement('your_turn') 743 yourturn_elt = mess.firstChildElement().addElement('your_turn')
754 self.host.profiles[profile].xmlstream.send(mess) 744 self.host.profiles[profile].xmlstream.send(mess)
755 745
756 elif elt.name == 'your_turn': 746 elif elt.name == 'your_turn':
757 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) 747 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
758 748
759 elif elt.name == 'score': 749 elif elt.name == 'score':
760 form_elt = elt.elements(name='x',uri='jabber:x:data').next() 750 form_elt = elt.elements(name='x', uri='jabber:x:data').next()
761 winners = [] 751 winners = []
762 loosers = [] 752 loosers = []
763 for winner in elt.elements(name='winner', uri=NS_CG): 753 for winner in elt.elements(name='winner', uri=NS_CG):
764 winners.append(unicode(winner)) 754 winners.append(unicode(winner))
765 for looser in elt.elements(name='looser', uri=NS_CG): 755 for looser in elt.elements(name='looser', uri=NS_CG):
767 form = data_form.Form.fromElement(form_elt) 757 form = data_form.Form.fromElement(form_elt)
768 xml_data = dataForm2xml(form) 758 xml_data = dataForm2xml(form)
769 self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile) 759 self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile)
770 elif elt.name == 'error': 760 elif elt.name == 'error':
771 if elt['type'] == 'invalid_cards': 761 if elt['type'] == 'invalid_cards':
772 played_cards = self.__xml_to_list(elt.elements(name='played',uri=NS_CG).next()) 762 played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next())
773 invalid_cards = self.__xml_to_list(elt.elements(name='invalid',uri=NS_CG).next()) 763 invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next())
774 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile) 764 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile)
775 else: 765 else:
776 error (_('Unmanaged error type: %s') % elt['type']) 766 error(_('Unmanaged error type: %s') % elt['type'])
777 else: 767 else:
778 error (_('Unmanaged card game element: %s') % elt.name) 768 error(_('Unmanaged card game element: %s') % elt.name)
779 769
780 def getHandler(self, profile): 770 def getHandler(self, profile):
781 return CardGameHandler(self) 771 return CardGameHandler(self)
772
782 773
783 class CardGameHandler (XMPPHandler): 774 class CardGameHandler (XMPPHandler):
784 implements(iwokkel.IDisco) 775 implements(iwokkel.IDisco)
785 776
786 def __init__(self, plugin_parent): 777 def __init__(self, plugin_parent):
787 self.plugin_parent = plugin_parent 778 self.plugin_parent = plugin_parent
788 self.host = plugin_parent.host 779 self.host = plugin_parent.host
789 780
790 def connectionInitialized(self): 781 def connectionInitialized(self):
791 self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile) 782 self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile=self.parent.profile)
792 783
793 def getDiscoInfo(self, requestor, target, nodeIdentifier=''): 784 def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
794 return [disco.DiscoFeature(NS_CG)] 785 return [disco.DiscoFeature(NS_CG)]
795 786
796 def getDiscoItems(self, requestor, target, nodeIdentifier=''): 787 def getDiscoItems(self, requestor, target, nodeIdentifier=''):
797 return [] 788 return []
798