comparison src/plugins/plugin_misc_tarot.py @ 587:952322b1d490

Remove trailing whitespaces.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:34 +0100
parents ca13633d3b6b
children beaf6bec2fcd
comparison
equal deleted inserted replaced
586:6a718ede8be1 587:952322b1d490
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
104 def __xml_to_list(self, cards_list_elt): 104 def __xml_to_list(self, cards_list_elt):
105 """Convert a domish element with cards to a list of tuples""" 105 """Convert a domish element with cards to a list of tuples"""
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 111
112 def __create_started_elt(self, players): 112 def __create_started_elt(self, players):
113 """Create a game_started domish element""" 113 """Create a game_started domish element"""
114 started_elt = domish.Element((None,'started')) 114 started_elt = domish.Element((None,'started'))
115 idx = 0 115 idx = 0
162 error_elt['type'] = 'invalid_cards' 162 error_elt['type'] = 'invalid_cards'
163 error_elt['phase'] = game_phase 163 error_elt['phase'] = game_phase
164 error_elt.addChild(played_elt) 164 error_elt.addChild(played_elt)
165 error_elt.addChild(invalid_elt) 165 error_elt.addChild(invalid_elt)
166 return error_elt 166 return error_elt
167 167
168 def __next_player(self, game_data, next_pl = None): 168 def __next_player(self, game_data, next_pl = None):
169 """Increment player number & return player name 169 """Increment player number & return player name
170 @param next_pl: if given, then next_player is forced to this one 170 @param next_pl: if given, then next_player is forced to this one
171 """ 171 """
172 if next_pl: 172 if next_pl:
178 178
179 def __winner(self, game_data): 179 def __winner(self, game_data):
180 """give the nick of the player who win this trick""" 180 """give the nick of the player who win this trick"""
181 players_data = game_data['players_data'] 181 players_data = game_data['players_data']
182 first = game_data['first_player'] 182 first = game_data['first_player']
183 first_idx = game_data['players'].index(first) 183 first_idx = game_data['players'].index(first)
184 suit_asked = None 184 suit_asked = None
185 strongest = None 185 strongest = None
186 winner = None 186 winner = None
187 for idx in [(first_idx + i) % 4 for i in range(4)]: 187 for idx in [(first_idx + i) % 4 for i in range(4)]:
188 player = game_data['players'][idx] 188 player = game_data['players'][idx]
223 return 223 return
224 224
225 if not excuse in played: 225 if not excuse in played:
226 #the Excuse is not on the table, nothing to do 226 #the Excuse is not on the table, nothing to do
227 return 227 return
228 228
229 excuse_player = None #Who has played the Excuse ? 229 excuse_player = None #Who has played the Excuse ?
230 for player in game_data['players']: 230 for player in game_data['players']:
231 if players_data[player]['played'] == excuse: 231 if players_data[player]['played'] == excuse:
232 excuse_player = player 232 excuse_player = player
233 break 233 break
234 234
235 if excuse_player == winner: 235 if excuse_player == winner:
236 return #the excuse player win the trick, nothing to do 236 return #the excuse player win the trick, nothing to do
237 237
238 #first we remove the excuse from played cards 238 #first we remove the excuse from played cards
239 played.remove(excuse) 239 played.remove(excuse)
240 #then we give it back to the original owner 240 #then we give it back to the original owner
241 owner_levees = players_data[excuse_player]['levees'] 241 owner_levees = players_data[excuse_player]['levees']
242 owner_levees.append(excuse) 242 owner_levees.append(excuse)
243 #finally we give a low card to the trick winner 243 #finally we give a low card to the trick winner
244 low_card = None 244 low_card = None
245 #We look backward in cards won by the Excuse owner to 245 #We look backward in cards won by the Excuse owner to
265 scores_str = _('Draw game') 265 scores_str = _('Draw game')
266 scores_str+='\n' 266 scores_str+='\n'
267 for player in game_data['players']: 267 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']} 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']}
269 debug(scores_str) 269 debug(scores_str)
270 270
271 return (scores_str, [], []) 271 return (scores_str, [], [])
272 272
273 273
274 def __calculate_scores(self, game_data): 274 def __calculate_scores(self, game_data):
275 """The game is finished, time to know who won :) 275 """The game is finished, time to know who won :)
276 @param game_data: data of the game 276 @param game_data: data of the game
277 @return: tuple with (string victory message, list of winners, list of loosers)""" 277 @return: tuple with (string victory message, list of winners, list of loosers)"""
278 players_data = game_data['players_data'] 278 players_data = game_data['players_data']
283 for card in levees: 283 for card in levees:
284 if card.bout: 284 if card.bout:
285 nb_bouts +=1 285 nb_bouts +=1
286 bouts.append(card.value) 286 bouts.append(card.value)
287 score += card.points 287 score += card.points
288 288
289 #We we do a basic check on score calculation 289 #We we do a basic check on score calculation
290 check_score = 0 290 check_score = 0
291 defenseurs = game_data['players'][:] 291 defenseurs = game_data['players'][:]
292 defenseurs.remove(game_data['attaquant']) 292 defenseurs.remove(game_data['attaquant'])
293 for defenseur in defenseurs: 293 for defenseur in defenseurs:
295 check_score+=card.points 295 check_score+=card.points
296 if game_data['contrat'] == "Garde Contre": 296 if game_data['contrat'] == "Garde Contre":
297 for card in game_data['chien']: 297 for card in game_data['chien']:
298 check_score+=card.points 298 check_score+=card.points
299 assert (score + check_score == 91) 299 assert (score + check_score == 91)
300 300
301 point_limit = None 301 point_limit = None
302 if nb_bouts == 3: 302 if nb_bouts == 3:
303 point_limit = 36 303 point_limit = 36
304 elif nb_bouts == 2: 304 elif nb_bouts == 2:
305 point_limit = 41 305 point_limit = 41
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'} 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'}
339 scores_str+='\n' 339 scores_str+='\n'
340 for player in game_data['players']: 340 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']} 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']}
342 debug(scores_str) 342 debug(scores_str)
343 343
344 return (scores_str, winners, loosers) 344 return (scores_str, winners, loosers)
345 345
346 def __invalid_cards(self, game_data, cards): 346 def __invalid_cards(self, game_data, cards):
347 """Checks that the player has the right to play what he wants to 347 """Checks that the player has the right to play what he wants to
348 @param game_data: Game data 348 @param game_data: Game data
435 def tarotRoomJoined(room): 435 def tarotRoomJoined(room):
436 _room = room.occupantJID.userhostJID() 436 _room = room.occupantJID.userhostJID()
437 for player in players: 437 for player in players:
438 self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Tarot"}, profile) 438 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 439 self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data
440 440
441 def after_init(ignore): 441 def after_init(ignore):
442 room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key) 442 room_name = "sat_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
443 print "\n\n===> room_name:", room_name 443 print "\n\n===> room_name:", room_name
444 #muc_service = self.host.memory.getServerServiceEntity("conference", "text", profile) 444 #muc_service = self.host.memory.getServerServiceEntity("conference", "text", profile)
445 muc_service = None 445 muc_service = None
446 for service in self.host.memory.getServerServiceEntities("conference", "text", profile): 446 for service in self.host.memory.getServerServiceEntities("conference", "text", profile):
447 if not ".irc." in service.userhost(): 447 if not ".irc." in service.userhost():
448 #FIXME: 448 #FIXME:
449 #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway 449 #This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
450 #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way 450 #use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
451 #to manage this, but this hack fill do it for test purpose 451 #to manage this, but this hack fill do it for test purpose
452 muc_service = service 452 muc_service = service
453 break 453 break
454 if not muc_service: 454 if not muc_service:
455 error(_("Can't find a MUC service")) 455 error(_("Can't find a MUC service"))
456 return 456 return
457 457
458 _jid, xmlstream = self.host.getJidNStream(profile) 458 _jid, xmlstream = self.host.getJidNStream(profile)
459 d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile).addCallback(tarotRoomJoined) 459 d = self.host.plugins["XEP-0045"].join(jid.JID("%s@%s" % (room_name, muc_service.userhost())), _jid.user, {}, profile).addCallback(tarotRoomJoined)
460 460
461 client = self.host.getClient(profile) 461 client = self.host.getClient(profile)
462 if not client: 462 if not client:
578 player = players[pl_idx] 578 player = players[pl_idx]
579 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: 579 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
580 mess = self.createGameElt(to_jid) 580 mess = self.createGameElt(to_jid)
581 mess.firstChildElement().addChild(self.__ask_contrat()) 581 mess.firstChildElement().addChild(self.__ask_contrat())
582 self.host.profiles[profile].xmlstream.send(mess) 582 self.host.profiles[profile].xmlstream.send(mess)
583 583
584 584
585 def card_game_cmd(self, mess_elt, profile): 585 def card_game_cmd(self, mess_elt, profile):
586 from_jid = jid.JID(mess_elt['from']) 586 from_jid = jid.JID(mess_elt['from'])
587 room_jid = jid.JID(from_jid.userhost()) 587 room_jid = jid.JID(from_jid.userhost())
588 game_elt = mess_elt.firstChildElement() 588 game_elt = mess_elt.firstChildElement()
589 game_data = self.games[room_jid.userhost()] 589 game_data = self.games[room_jid.userhost()]
590 players_data = game_data['players_data'] 590 players_data = game_data['players_data']
591 591
592 for elt in game_elt.elements(): 592 for elt in game_elt.elements():
593 593
594 if elt.name == 'started': #new game created 594 if elt.name == 'started': #new game created
595 players = [] 595 players = []
596 for player in elt.elements(): 596 for player in elt.elements():
597 players.append(unicode(player)) 597 players.append(unicode(player))
598 self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile) 598 self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile)
599 599
600 elif elt.name == 'player_ready': #ready to play 600 elif elt.name == 'player_ready': #ready to play
601 player = elt['player'] 601 player = elt['player']
602 status = self.games[room_jid.userhost()]['status'] 602 status = self.games[room_jid.userhost()]['status']
603 nb_players = len(self.games[room_jid.userhost()]['players']) 603 nb_players = len(self.games[room_jid.userhost()]['players'])
604 status[player] = 'ready' 604 status[player] = 'ready'
605 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) 605 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 606 if status.values().count('ready') == nb_players: #everybody is ready, we can start the game
607 self.newGame(room_jid, profile) 607 self.newGame(room_jid, profile)
608 608
609 elif elt.name == 'hand': #a new hand has been received 609 elif elt.name == 'hand': #a new hand has been received
610 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) 610 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile)
611 611
612 elif elt.name == 'contrat': #it's time to choose contrat 612 elif elt.name == 'contrat': #it's time to choose contrat
613 form = data_form.Form.fromElement(elt.firstChildElement()) 613 form = data_form.Form.fromElement(elt.firstChildElement())
614 xml_data = dataForm2xml(form) 614 xml_data = dataForm2xml(form)
615 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) 615 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
616 616
617 elif elt.name == 'contrat_choosed': 617 elif elt.name == 'contrat_choosed':
618 #TODO: check we receive the contrat from the right person 618 #TODO: check we receive the contrat from the right person
619 #TODO: use proper XEP-0004 way for answering form 619 #TODO: use proper XEP-0004 way for answering form
620 player = elt['player'] 620 player = elt['player']
621 players_data[player]['contrat'] = unicode(elt) 621 players_data[player]['contrat'] = unicode(elt)
646 for player in game_data['players']: 646 for player in game_data['players']:
647 game_data['status'][player] = "init" 647 game_data['status'][player] = "init"
648 return 648 return
649 debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]}) 649 debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]})
650 game_data['contrat'] = best_contrat[1] 650 game_data['contrat'] = best_contrat[1]
651 651
652 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": 652 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
653 self.__start_play(room_jid, game_data, profile) 653 self.__start_play(room_jid, game_data, profile)
654 game_data['attaquant'] = best_contrat[0] 654 game_data['attaquant'] = best_contrat[0]
655 else: 655 else:
656 #Time to show the chien to everybody 656 #Time to show the chien to everybody
660 chien_elt['attaquant'] = best_contrat[0] 660 chien_elt['attaquant'] = best_contrat[0]
661 self.host.profiles[profile].xmlstream.send(mess) 661 self.host.profiles[profile].xmlstream.send(mess)
662 #the attacker (attaquant) get the chien 662 #the attacker (attaquant) get the chien
663 game_data['hand'][best_contrat[0]].extend(game_data['chien']) 663 game_data['hand'][best_contrat[0]].extend(game_data['chien'])
664 del game_data['chien'][:] 664 del game_data['chien'][:]
665 665
666 if game_data['contrat'] == "Garde Sans": 666 if game_data['contrat'] == "Garde Sans":
667 #The chien go into attaquant's (attacker) levees 667 #The chien go into attaquant's (attacker) levees
668 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) 668 players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
669 del game_data['chien'][:] 669 del game_data['chien'][:]
670 670
691 691
692 #FIXME: gof: manage Garde Sans & Garde Contre cases 692 #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 693 players_data[elt['player']]['levees'].extend(list_cards) #we add the chien to attaquant's levées
694 for card in list_cards: 694 for card in list_cards:
695 game_data['hand'][elt['player']].remove(card) 695 game_data['hand'][elt['player']].remove(card)
696 696
697 self.__start_play(room_jid, game_data, profile) 697 self.__start_play(room_jid, game_data, profile)
698 698
699 elif game_data['stage'] == "play": 699 elif game_data['stage'] == "play":
700 current_player = game_data['players'][game_data['current_player']] 700 current_player = game_data['players'][game_data['current_player']]
701 cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 701 cards = TarotCard.from_tuples(self.__xml_to_list(elt))
702 702
703 if mess_elt['type'] == 'groupchat': 703 if mess_elt['type'] == 'groupchat':
704 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) 704 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
705 else: 705 else:
706 #we first check validity of card 706 #we first check validity of card
707 invalid_cards = self.__invalid_cards(game_data, cards) 707 invalid_cards = self.__invalid_cards(game_data, cards)
717 717
718 #then we forward the message 718 #then we forward the message
719 mess = self.createGameElt(room_jid) 719 mess = self.createGameElt(room_jid)
720 playcard_elt = mess.firstChildElement().addChild(elt) 720 playcard_elt = mess.firstChildElement().addChild(elt)
721 self.host.profiles[profile].xmlstream.send(mess) 721 self.host.profiles[profile].xmlstream.send(mess)
722 722
723 #Did everybody played ? 723 #Did everybody played ?
724 played = [players_data[player]['played'] for player in game_data['players']] 724 played = [players_data[player]['played'] for player in game_data['players']]
725 if all(played): 725 if all(played):
726 #everybody has played 726 #everybody has played
727 winner = self.__winner(game_data) 727 winner = self.__winner(game_data)
774 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile) 774 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile)
775 else: 775 else:
776 error (_('Unmanaged error type: %s') % elt['type']) 776 error (_('Unmanaged error type: %s') % elt['type'])
777 else: 777 else:
778 error (_('Unmanaged card game element: %s') % elt.name) 778 error (_('Unmanaged card game element: %s') % elt.name)
779 779
780 def getHandler(self, profile): 780 def getHandler(self, profile):
781 return CardGameHandler(self) 781 return CardGameHandler(self)
782 782
783 class CardGameHandler (XMPPHandler): 783 class CardGameHandler (XMPPHandler):
784 implements(iwokkel.IDisco) 784 implements(iwokkel.IDisco)
785 785
786 def __init__(self, plugin_parent): 786 def __init__(self, plugin_parent):
787 self.plugin_parent = plugin_parent 787 self.plugin_parent = plugin_parent
788 self.host = plugin_parent.host 788 self.host = plugin_parent.host
789 789
790 def connectionInitialized(self): 790 def connectionInitialized(self):