comparison 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
comparison
equal deleted inserted replaced
1358:bf3f669a6052 1359:83127a4c89ce
57 def __init__(self, host): 57 def __init__(self, host):
58 log.info(_("Plugin Tarot initialization")) 58 log.info(_("Plugin Tarot initialization"))
59 self._sessions = memory.Sessions() 59 self._sessions = memory.Sessions()
60 self.inheritFromRoomGame(host) 60 self.inheritFromRoomGame(host)
61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG), 61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}, 62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
63 player_init={'score': 0}) 63 player_init={'score': 0})
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='asss', out_sign='', method=self.prepareRoom, async=True) # args: players, room_jid, profile 65 host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True) # args: players, room_jid, 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.playerReady) # args: player, referee, profile 67 host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile
68 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile 68 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile
69 host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, profile 69 host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, 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
81 for suit in ["pique", "coeur", "carreau", "trefle"]: 81 for suit in ["pique", "coeur", "carreau", "trefle"]:
82 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]: 82 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
83 self.deck_ordered.append(TarotCard((suit, value))) 83 self.deck_ordered.append(TarotCard((suit, value)))
84 self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True) 84 self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True)
85 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True) 85 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
86
87 86
88 def __card_list_to_xml(self, cards_list, elt_name): 87 def __card_list_to_xml(self, cards_list, elt_name):
89 """Convert a card list to domish element""" 88 """Convert a card list to domish element"""
90 cards_list_elt = domish.Element((None, elt_name)) 89 cards_list_elt = domish.Element((None, elt_name))
91 for card in cards_list: 90 for card in cards_list:
181 def __excuse_hack(self, game_data, played, winner): 180 def __excuse_hack(self, game_data, played, winner):
182 """give a low card to other team and keep excuse if trick is lost 181 """give a low card to other team and keep excuse if trick is lost
183 @param game_data: data of the game 182 @param game_data: data of the game
184 @param played: cards currently on the table 183 @param played: cards currently on the table
185 @param winner: nick of the trick winner""" 184 @param winner: nick of the trick winner"""
186 #TODO: manage the case where excuse is played on the last trick (and lost) 185 # TODO: manage the case where excuse is played on the last trick (and lost)
187 players_data = game_data['players_data'] 186 players_data = game_data['players_data']
188 excuse = TarotCard(("atout", "excuse")) 187 excuse = TarotCard(("atout", "excuse"))
189 188
190 #we first check if the Excuse was already played 189 # we first check if the Excuse was already played
191 #and if somebody is waiting for a card 190 # and if somebody is waiting for a card
192 for player in game_data['players']: 191 for player in game_data['players']:
193 if players_data[player]['wait_for_low']: 192 if players_data[player]['wait_for_low']:
194 #the excuse owner has to give a card to somebody 193 # the excuse owner has to give a card to somebody
195 if winner == player: 194 if winner == player:
196 #the excuse owner win the trick, we check if we have something to give 195 # the excuse owner win the trick, we check if we have something to give
197 for card in played: 196 for card in played:
198 if card.points == 0.5: 197 if card.points == 0.5:
199 pl_waiting = players_data[player]['wait_for_low'] 198 pl_waiting = players_data[player]['wait_for_low']
200 played.remove(card) 199 played.remove(card)
201 players_data[pl_waiting]['levees'].append(card) 200 players_data[pl_waiting]['levees'].append(card)
202 log.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}) 201 log.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})
203 return 202 return
204 return 203 return
205 204
206 if not excuse in played: 205 if excuse not in played:
207 #the Excuse is not on the table, nothing to do 206 # the Excuse is not on the table, nothing to do
208 return 207 return
209 208
210 excuse_player = None # Who has played the Excuse ? 209 excuse_player = None # Who has played the Excuse ?
211 for player in game_data['players']: 210 for player in game_data['players']:
212 if players_data[player]['played'] == excuse: 211 if players_data[player]['played'] == excuse:
214 break 213 break
215 214
216 if excuse_player == winner: 215 if excuse_player == winner:
217 return # the excuse player win the trick, nothing to do 216 return # the excuse player win the trick, nothing to do
218 217
219 #first we remove the excuse from played cards 218 # first we remove the excuse from played cards
220 played.remove(excuse) 219 played.remove(excuse)
221 #then we give it back to the original owner 220 # then we give it back to the original owner
222 owner_levees = players_data[excuse_player]['levees'] 221 owner_levees = players_data[excuse_player]['levees']
223 owner_levees.append(excuse) 222 owner_levees.append(excuse)
224 #finally we give a low card to the trick winner 223 # finally we give a low card to the trick winner
225 low_card = None 224 low_card = None
226 #We look backward in cards won by the Excuse owner to 225 # We look backward in cards won by the Excuse owner to
227 #find a low value card 226 # find a low value card
228 for card_idx in range(len(owner_levees) - 1, -1, -1): 227 for card_idx in range(len(owner_levees) - 1, -1, -1):
229 if owner_levees[card_idx].points == 0.5: 228 if owner_levees[card_idx].points == 0.5:
230 low_card = owner_levees[card_idx] 229 low_card = owner_levees[card_idx]
231 del owner_levees[card_idx] 230 del owner_levees[card_idx]
232 players_data[winner]['levees'].append(low_card) 231 players_data[winner]['levees'].append(low_card)
233 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}) 232 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})
234 break 233 break
235 if not low_card: # The player has no low card yet 234 if not low_card: # The player has no low card yet
236 #TODO: manage case when player never win a trick with low card 235 # TODO: manage case when player never win a trick with low card
237 players_data[excuse_player]['wait_for_low'] = winner 236 players_data[excuse_player]['wait_for_low'] = winner
238 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}) 237 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})
239 238
240 def __draw_game(self, game_data): 239 def __draw_game(self, game_data):
241 """The game is draw, no score change 240 """The game is draw, no score change
263 if card.bout: 262 if card.bout:
264 nb_bouts += 1 263 nb_bouts += 1
265 bouts.append(card.value) 264 bouts.append(card.value)
266 score += card.points 265 score += card.points
267 266
268 #We we do a basic check on score calculation 267 # We do a basic check on score calculation
269 check_score = 0 268 check_score = 0
270 defenseurs = game_data['players'][:] 269 defenseurs = game_data['players'][:]
271 defenseurs.remove(game_data['attaquant']) 270 defenseurs.remove(game_data['attaquant'])
272 for defenseur in defenseurs: 271 for defenseur in defenseurs:
273 for card in players_data[defenseur]['levees']: 272 for card in players_data[defenseur]['levees']:
303 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1) 302 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1)
304 winners = [] 303 winners = []
305 loosers = [] 304 loosers = []
306 player_score = {} 305 player_score = {}
307 for player in game_data['players']: 306 for player in game_data['players']:
308 #TODO: adjust this for 3 and 5 players variants 307 # TODO: adjust this for 3 and 5 players variants
309 #TODO: manage bonuses (petit au bout, poignée, chelem) 308 # TODO: manage bonuses (petit au bout, poignée, chelem)
310 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3 309 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3
311 players_data[player]['score'] += player_score[player] # we add score of this game to the global score 310 players_data[player]['score'] += player_score[player] # we add score of this game to the global score
312 if player_score[player] > 0: 311 if player_score[player] > 0:
313 winners.append(player) 312 winners.append(player)
314 else: 313 else:
315 loosers.append(player) 314 loosers.append(player)
316 315
317 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'} 316 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'}
318 scores_str += '\n' 317 scores_str += '\n'
319 for player in game_data['players']: 318 for player in game_data['players']:
320 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']} 319 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']}
321 log.debug(scores_str) 320 log.debug(scores_str)
322 321
330 forbidden_cards = [] 329 forbidden_cards = []
331 if game_data['stage'] == 'ecart': 330 if game_data['stage'] == 'ecart':
332 for card in cards: 331 for card in cards:
333 if card.bout or card.value == "roi": 332 if card.bout or card.value == "roi":
334 forbidden_cards.append(card) 333 forbidden_cards.append(card)
335 #TODO: manage case where atouts (trumps) are in the dog 334 # TODO: manage case where atouts (trumps) are in the dog
336 elif game_data['stage'] == 'play': 335 elif game_data['stage'] == 'play':
337 biggest_atout = None 336 biggest_atout = None
338 suit_asked = None 337 suit_asked = None
339 players = game_data['players'] 338 players = game_data['players']
340 players_data = game_data['players_data'] 339 players_data = game_data['players_data']
341 idx = players.index(game_data['first_player']) 340 idx = players.index(game_data['first_player'])
342 current_idx = game_data['current_player'] 341 current_idx = game_data['current_player']
343 current_player = players[current_idx] 342 current_player = players[current_idx]
344 if idx == current_idx: 343 if idx == current_idx:
345 #the player is the first to play, he can play what he wants 344 # the player is the first to play, he can play what he wants
346 return forbidden_cards 345 return forbidden_cards
347 while (idx != current_idx): 346 while (idx != current_idx):
348 player = players[idx] 347 player = players[idx]
349 played_card = players_data[player]['played'] 348 played_card = players_data[player]['played']
350 if not suit_asked and played_card.value != "excuse": 349 if not suit_asked and played_card.value != "excuse":
396 except KeyError: 395 except KeyError:
397 log.warning(_("session id doesn't exist, session has probably expired")) 396 log.warning(_("session id doesn't exist, session has probably expired"))
398 # TODO: send error dialog 397 # TODO: send error dialog
399 return defer.succeed({}) 398 return defer.succeed({})
400 399
401 room_jid_s = session_data['room_jid'].userhost() 400 room_jid = session_data['room_jid']
402 referee = self.games[room_jid_s]['referee'] 401 referee_jid = self.games[room_jid]['referee']
403 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile) 402 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
404 data = xml_tools.XMLUIResult2DataFormResult(raw_data) 403 data = xml_tools.XMLUIResult2DataFormResult(raw_data)
405 contrat = data['contrat'] 404 contrat = data['contrat']
406 log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile}) 405 log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
407 d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile) 406 d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
408 d.addCallback(lambda ignore: {}) 407 d.addCallback(lambda ignore: {})
409 del self._sessions[raw_data["session_id"]] 408 del self._sessions[raw_data["session_id"]]
410 return d 409 return d
411 410
412 def _scoreShowed(self, raw_data, profile): 411 def _scoreShowed(self, raw_data, profile):
441 log.debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards}) 440 log.debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
442 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played') 441 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played')
443 self.send(jid.JID(referee), elem, {'player': player}, profile=profile) 442 self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
444 443
445 def newRound(self, room_jid, profile): 444 def newRound(self, room_jid, profile):
446 game_data = self.games[room_jid.userhost()] 445 game_data = self.games[room_jid]
447 players = game_data['players'] 446 players = game_data['players']
448 game_data['first_player'] = None # first player for the current trick 447 game_data['first_player'] = None # first player for the current trick
449 game_data['contrat'] = None 448 game_data['contrat'] = None
450 common_data = {'contrat': None, 449 common_data = {'contrat': None,
451 'levees': [], # cards won 450 'levees': [], # cards won
478 """ 477 """
479 @param mess_elt: instance of twisted.words.xish.domish.Element 478 @param mess_elt: instance of twisted.words.xish.domish.Element
480 """ 479 """
481 from_jid = jid.JID(mess_elt['from']) 480 from_jid = jid.JID(mess_elt['from'])
482 room_jid = jid.JID(from_jid.userhost()) 481 room_jid = jid.JID(from_jid.userhost())
483 nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile) 482 nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
484 483
485 game_elt = mess_elt.firstChildElement() 484 game_elt = mess_elt.firstChildElement()
486 game_data = self.games[room_jid.userhost()] 485 game_data = self.games[room_jid]
487 is_player = self.isPlayer(room_jid.userhost(), nick) 486 is_player = self.isPlayer(room_jid, nick)
488 if 'players_data' in game_data: 487 if 'players_data' in game_data:
489 players_data = game_data['players_data'] 488 players_data = game_data['players_data']
490 489
491 for elt in game_elt.elements(): 490 for elt in game_elt.elements():
492 if not is_player and (elt.name not in ('started', 'players')): 491 if not is_player and (elt.name not in ('started', 'players')):
499 signal = self.host.bridge.tarotGameStarted if elt.name == 'started' else self.host.bridge.tarotGamePlayers 498 signal = self.host.bridge.tarotGameStarted if elt.name == 'started' else self.host.bridge.tarotGamePlayers
500 signal(room_jid.userhost(), from_jid.full(), players, profile) 499 signal(room_jid.userhost(), from_jid.full(), players, profile)
501 500
502 elif elt.name == 'player_ready': # ready to play 501 elif elt.name == 'player_ready': # ready to play
503 player = elt['player'] 502 player = elt['player']
504 status = self.games[room_jid.userhost()]['status'] 503 status = self.games[room_jid]['status']
505 nb_players = len(self.games[room_jid.userhost()]['players']) 504 nb_players = len(self.games[room_jid]['players'])
506 status[player] = 'ready' 505 status[player] = 'ready'
507 log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status}) 506 log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
508 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game 507 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
509 self.newRound(room_jid, profile) 508 self.newRound(room_jid, profile)
510 509
517 session_data["room_jid"] = room_jid 516 session_data["room_jid"] = room_jid
518 xml_data = xml_tools.dataForm2XMLUI(form, self.__choose_contrat_id, session_id).toXml() 517 xml_data = xml_tools.dataForm2XMLUI(form, self.__choose_contrat_id, session_id).toXml()
519 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) 518 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
520 519
521 elif elt.name == 'contrat_choosed': 520 elif elt.name == 'contrat_choosed':
522 #TODO: check we receive the contrat from the right person 521 # TODO: check we receive the contrat from the right person
523 #TODO: use proper XEP-0004 way for answering form 522 # TODO: use proper XEP-0004 way for answering form
524 player = elt['player'] 523 player = elt['player']
525 players_data[player]['contrat'] = unicode(elt) 524 players_data[player]['contrat'] = unicode(elt)
526 contrats = [players_data[player]['contrat'] for player in game_data['players']] 525 contrats = [players_data[player]['contrat'] for player in game_data['players']]
527 if contrats.count(None): 526 if contrats.count(None):
528 #not everybody has choosed his contrat, it's next one turn 527 # not everybody has choosed his contrat, it's next one turn
529 player = self.__next_player(game_data) 528 player = self.__next_player(game_data)
530 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: 529 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
531 self.send(to_jid, self.__ask_contrat(), profile=profile) 530 self.send(to_jid, self.__ask_contrat(), profile=profile)
532 else: 531 else:
533 best_contrat = [None, "Passe"] 532 best_contrat = [None, "Passe"]
551 550
552 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": 551 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
553 self.__start_play(room_jid, game_data, profile) 552 self.__start_play(room_jid, game_data, profile)
554 game_data['attaquant'] = best_contrat[0] 553 game_data['attaquant'] = best_contrat[0]
555 else: 554 else:
556 #Time to show the chien to everybody 555 # Time to show the chien to everybody
557 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof: 556 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
558 elem = self.__card_list_to_xml(game_data['chien'], 'chien') 557 elem = self.__card_list_to_xml(game_data['chien'], 'chien')
559 self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile) 558 self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile)
560 #the attacker (attaquant) get the chien 559 # the attacker (attaquant) get the chien
561 game_data['hand'][best_contrat[0]].extend(game_data['chien']) 560 game_data['hand'][best_contrat[0]].extend(game_data['chien'])
562 del game_data['chien'][:] 561 del game_data['chien'][:]
563 562
564 if game_data['contrat'] == "Garde Sans": 563 if game_data['contrat'] == "Garde Sans":
565 #The chien go into attaquant's (attacker) levees 564 # The chien go into attaquant's (attacker) levees
566 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) 565 players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
567 del game_data['chien'][:] 566 del game_data['chien'][:]
568 567
569 elif elt.name == 'chien': # we have received the chien 568 elif elt.name == 'chien': # we have received the chien
570 log.debug(_("tarot: chien received")) 569 log.debug(_("tarot: chien received"))
573 game_data['attaquant'] = elt['attaquant'] 572 game_data['attaquant'] = elt['attaquant']
574 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) 573 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile)
575 574
576 elif elt.name == 'cards_played': 575 elif elt.name == 'cards_played':
577 if game_data['stage'] == "ecart": 576 if game_data['stage'] == "ecart":
578 #TODO: show atouts (trumps) if player put some in écart 577 # TODO: show atouts (trumps) if player put some in écart
579 assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here 578 assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here
580 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 579 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
581 #we now check validity of card 580 # we now check validity of card
582 invalid_cards = self.__invalid_cards(game_data, list_cards) 581 invalid_cards = self.__invalid_cards(game_data, list_cards)
583 if invalid_cards: 582 if invalid_cards:
584 elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']) 583 elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])
585 self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile) 584 self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile)
586 return 585 return
587 586
588 #FIXME: gof: manage Garde Sans & Garde Contre cases 587 # FIXME: gof: manage Garde Sans & Garde Contre cases
589 players_data[elt['player']]['levees'].extend(list_cards) # we add the chien to attaquant's levées 588 players_data[elt['player']]['levees'].extend(list_cards) # we add the chien to attaquant's levées
590 for card in list_cards: 589 for card in list_cards:
591 game_data['hand'][elt['player']].remove(card) 590 game_data['hand'][elt['player']].remove(card)
592 591
593 self.__start_play(room_jid, game_data, profile) 592 self.__start_play(room_jid, game_data, profile)
597 cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 596 cards = TarotCard.from_tuples(self.__xml_to_list(elt))
598 597
599 if mess_elt['type'] == 'groupchat': 598 if mess_elt['type'] == 'groupchat':
600 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) 599 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
601 else: 600 else:
602 #we first check validity of card 601 # we first check validity of card
603 invalid_cards = self.__invalid_cards(game_data, cards) 602 invalid_cards = self.__invalid_cards(game_data, cards)
604 if invalid_cards: 603 if invalid_cards:
605 elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage']) 604 elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage'])
606 self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile) 605 self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile)
607 return 606 return
608 #the card played is ok, we forward it to everybody 607 # the card played is ok, we forward it to everybody
609 #first we remove it from the hand and put in on the table 608 # first we remove it from the hand and put in on the table
610 game_data['hand'][current_player].remove(cards[0]) 609 game_data['hand'][current_player].remove(cards[0])
611 players_data[current_player]['played'] = cards[0] 610 players_data[current_player]['played'] = cards[0]
612 611
613 #then we forward the message 612 # then we forward the message
614 self.send(room_jid, elt, profile=profile) 613 self.send(room_jid, elt, profile=profile)
615 614
616 #Did everybody played ? 615 # Did everybody played ?
617 played = [players_data[player]['played'] for player in game_data['players']] 616 played = [players_data[player]['played'] for player in game_data['players']]
618 if all(played): 617 if all(played):
619 #everybody has played 618 # everybody has played
620 winner = self.__winner(game_data) 619 winner = self.__winner(game_data)
621 log.debug(_('The winner of this trick is %s') % winner) 620 log.debug(_('The winner of this trick is %s') % winner)
622 #the winner win the trick 621 # the winner win the trick
623 self.__excuse_hack(game_data, played, winner) 622 self.__excuse_hack(game_data, played, winner)
624 players_data[elt['player']]['levees'].extend(played) 623 players_data[elt['player']]['levees'].extend(played)
625 #nothing left on the table 624 # nothing left on the table
626 for player in game_data['players']: 625 for player in game_data['players']:
627 players_data[player]['played'] = None 626 players_data[player]['played'] = None
628 if len(game_data['hand'][current_player]) == 0: 627 if len(game_data['hand'][current_player]) == 0:
629 #no card lef: the game is finished 628 # no card left: the game is finished
630 elem = self.__give_scores(*self.__calculate_scores(game_data)) 629 elem = self.__give_scores(*self.__calculate_scores(game_data))
631 self.send(room_jid, elem, profile=profile) 630 self.send(room_jid, elem, profile=profile)
632 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer 631 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
633 for player in game_data['players']: 632 for player in game_data['players']:
634 game_data['status'][player] = "init" 633 game_data['status'][player] = "init"
635 return 634 return
636 #next player is the winner 635 # next player is the winner
637 next_player = game_data['first_player'] = self.__next_player(game_data, winner) 636 next_player = game_data['first_player'] = self.__next_player(game_data, winner)
638 else: 637 else:
639 next_player = self.__next_player(game_data) 638 next_player = self.__next_player(game_data)
640 639
641 #finally, we tell to the next player to play 640 # finally, we tell to the next player to play
642 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) 641 to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
643 self.send(to_jid, 'your_turn', profile=profile) 642 self.send(to_jid, 'your_turn', profile=profile)
644 643
645 elif elt.name == 'your_turn': 644 elif elt.name == 'your_turn':
646 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) 645 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
666 else: 665 else:
667 log.error(_('Unmanaged error type: %s') % elt['type']) 666 log.error(_('Unmanaged error type: %s') % elt['type'])
668 else: 667 else:
669 log.error(_('Unmanaged card game element: %s') % elt.name) 668 log.error(_('Unmanaged card game element: %s') % elt.name)
670 669
671 def getSyncDataForPlayer(self, room_jid_s, nick): 670 def getSyncDataForPlayer(self, room_jid, nick):
672 return [] 671 return []