comparison sat/plugins/plugin_misc_tarot.py @ 3028:ab2696e34d29

Python 3 port: /!\ this is a huge commit /!\ starting from this commit, SàT is needs Python 3.6+ /!\ SàT maybe be instable or some feature may not work anymore, this will improve with time This patch port backend, bridge and frontends to Python 3. Roughly this has been done this way: - 2to3 tools has been applied (with python 3.7) - all references to python2 have been replaced with python3 (notably shebangs) - fixed files not handled by 2to3 (notably the shell script) - several manual fixes - fixed issues reported by Python 3 that where not handled in Python 2 - replaced "async" with "async_" when needed (it's a reserved word from Python 3.7) - replaced zope's "implements" with @implementer decorator - temporary hack to handle data pickled in database, as str or bytes may be returned, to be checked later - fixed hash comparison for password - removed some code which is not needed anymore with Python 3 - deactivated some code which needs to be checked (notably certificate validation) - tested with jp, fixed reported issues until some basic commands worked - ported Primitivus (after porting dependencies like urwid satext) - more manual fixes
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:08:41 +0200
parents 003b8b4b56a7
children 9d0df638c8b4
comparison
equal deleted inserted replaced
3027:ff5bcb12ae60 3028:ab2696e34d29
1 #!/usr/bin/env python2 1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*- 2 # -*- coding: utf-8 -*-
3 3
4 # SAT plugin for managing French Tarot game 4 # SAT plugin for managing French Tarot game
5 # Copyright (C) 2009-2019 Jérôme Poisson (goffi@goffi.org) 5 # Copyright (C) 2009-2019 Jérôme Poisson (goffi@goffi.org)
6 6
85 "tarotGameLaunch", 85 "tarotGameLaunch",
86 ".plugin", 86 ".plugin",
87 in_sign="asss", 87 in_sign="asss",
88 out_sign="", 88 out_sign="",
89 method=self._prepareRoom, 89 method=self._prepareRoom,
90 async=True, 90 async_=True,
91 ) # args: players, room_jid, profile 91 ) # args: players, room_jid, profile
92 host.bridge.addMethod( 92 host.bridge.addMethod(
93 "tarotGameCreate", 93 "tarotGameCreate",
94 ".plugin", 94 ".plugin",
95 in_sign="sass", 95 in_sign="sass",
136 ) # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile 136 ) # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
137 host.bridge.addSignal( 137 host.bridge.addSignal(
138 "tarotGameInvalidCards", ".plugin", signature="ssa(ss)a(ss)s" 138 "tarotGameInvalidCards", ".plugin", signature="ssa(ss)a(ss)s"
139 ) # args: room_jid, game phase, played_cards, invalid_cards, profile 139 ) # args: room_jid, game phase, played_cards, invalid_cards, profile
140 self.deck_ordered = [] 140 self.deck_ordered = []
141 for value in ["excuse"] + map(str, range(1, 22)): 141 for value in ["excuse"] + list(map(str, list(range(1, 22)))):
142 self.deck_ordered.append(TarotCard(("atout", value))) 142 self.deck_ordered.append(TarotCard(("atout", value)))
143 for suit in ["pique", "coeur", "carreau", "trefle"]: 143 for suit in ["pique", "coeur", "carreau", "trefle"]:
144 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]: 144 for value in list(map(str, list(range(1, 11)))) + ["valet", "cavalier", "dame", "roi"]:
145 self.deck_ordered.append(TarotCard((suit, value))) 145 self.deck_ordered.append(TarotCard((suit, value)))
146 self.__choose_contrat_id = host.registerCallback( 146 self.__choose_contrat_id = host.registerCallback(
147 self._contratChoosed, with_data=True 147 self._contratChoosed, with_data=True
148 ) 148 )
149 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True) 149 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
170 contrat_elt = domish.Element((None, "contrat")) 170 contrat_elt = domish.Element((None, "contrat"))
171 form = data_form.Form("form", title=_("contrat selection")) 171 form = data_form.Form("form", title=_("contrat selection"))
172 field = data_form.Field( 172 field = data_form.Field(
173 "list-single", 173 "list-single",
174 "contrat", 174 "contrat",
175 options=map(data_form.Option, self.contrats), 175 options=list(map(data_form.Option, self.contrats)),
176 required=True, 176 required=True,
177 ) 177 )
178 form.addField(field) 178 form.addField(field)
179 contrat_elt.addChild(form.toElement()) 179 contrat_elt.addChild(form.toElement())
180 return contrat_elt 180 return contrat_elt
269 pl_waiting = players_data[player]["wait_for_low"] 269 pl_waiting = players_data[player]["wait_for_low"]
270 played.remove(card) 270 played.remove(card)
271 players_data[pl_waiting]["levees"].append(card) 271 players_data[pl_waiting]["levees"].append(card)
272 log.debug( 272 log.debug(
273 _( 273 _(
274 u"Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation" 274 "Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation"
275 ) 275 )
276 % { 276 % {
277 "excuse_owner": player, 277 "excuse_owner": player,
278 "card_waited": card, 278 "card_waited": card,
279 "player_waiting": pl_waiting, 279 "player_waiting": pl_waiting,
309 low_card = owner_levees[card_idx] 309 low_card = owner_levees[card_idx]
310 del owner_levees[card_idx] 310 del owner_levees[card_idx]
311 players_data[winner]["levees"].append(low_card) 311 players_data[winner]["levees"].append(low_card)
312 log.debug( 312 log.debug(
313 _( 313 _(
314 u"Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation" 314 "Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation"
315 ) 315 )
316 % { 316 % {
317 "excuse_owner": excuse_player, 317 "excuse_owner": excuse_player,
318 "card_waited": low_card, 318 "card_waited": low_card,
319 "player_waiting": winner, 319 "player_waiting": winner,
323 if not low_card: # The player has no low card yet 323 if not low_card: # The player has no low card yet
324 # TODO: manage case when player never win a trick with low card 324 # TODO: manage case when player never win a trick with low card
325 players_data[excuse_player]["wait_for_low"] = winner 325 players_data[excuse_player]["wait_for_low"] = winner
326 log.debug( 326 log.debug(
327 _( 327 _(
328 u"%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one" 328 "%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one"
329 ) 329 )
330 % {"excuse_owner": excuse_player, "winner": winner} 330 % {"excuse_owner": excuse_player, "winner": winner}
331 ) 331 )
332 332
333 def __draw_game(self, game_data): 333 def __draw_game(self, game_data):
337 players_data = game_data["players_data"] 337 players_data = game_data["players_data"]
338 scores_str = _("Draw game") 338 scores_str = _("Draw game")
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 += _( 341 scores_str += _(
342 u"\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i" 342 "\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i"
343 ) % { 343 ) % {
344 "player": player, 344 "player": player,
345 "score_game": 0, 345 "score_game": 0,
346 "total_score": players_data[player]["score"], 346 "total_score": players_data[player]["score"],
347 } 347 }
418 winners.append(player) 418 winners.append(player)
419 else: 419 else:
420 loosers.append(player) 420 loosers.append(player)
421 421
422 scores_str = _( 422 scores_str = _(
423 u"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" 423 "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"
424 ) % { 424 ) % {
425 "attaquant": game_data["attaquant"], 425 "attaquant": game_data["attaquant"],
426 "points": score, 426 "points": score,
427 "point_limit": point_limit, 427 "point_limit": point_limit,
428 "nb_bouts": nb_bouts, 428 "nb_bouts": nb_bouts,
432 "victory": "wins" if victory else "looses", 432 "victory": "wins" if victory else "looses",
433 } 433 }
434 scores_str += "\n" 434 scores_str += "\n"
435 for player in game_data["players"]: 435 for player in game_data["players"]:
436 scores_str += _( 436 scores_str += _(
437 u"\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i" 437 "\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i"
438 ) % { 438 ) % {
439 "player": player, 439 "player": player,
440 "score_game": player_score[player], 440 "score_game": player_score[player],
441 "total_score": players_data[player]["score"], 441 "total_score": players_data[player]["score"],
442 } 442 }
535 referee_jid = self.games[room_jid]["referee"] 535 referee_jid = self.games[room_jid]["referee"]
536 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile) 536 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
537 data = xml_tools.XMLUIResult2DataFormResult(raw_data) 537 data = xml_tools.XMLUIResult2DataFormResult(raw_data)
538 contrat = data["contrat"] 538 contrat = data["contrat"]
539 log.debug( 539 log.debug(
540 _(u"contrat [%(contrat)s] choosed by %(profile)s") 540 _("contrat [%(contrat)s] choosed by %(profile)s")
541 % {"contrat": contrat, "profile": profile} 541 % {"contrat": contrat, "profile": profile}
542 ) 542 )
543 d = self.send( 543 d = self.send(
544 referee_jid, 544 referee_jid,
545 ("", "contrat_choosed"), 545 ("", "contrat_choosed"),
576 @cards: cards played (list of tuples) 576 @cards: cards played (list of tuples)
577 @profile_key: profile 577 @profile_key: profile
578 """ 578 """
579 profile = self.host.memory.getProfileName(profile_key) 579 profile = self.host.memory.getProfileName(profile_key)
580 if not profile: 580 if not profile:
581 log.error(_(u"profile %s is unknown") % profile_key) 581 log.error(_("profile %s is unknown") % profile_key)
582 return 582 return
583 log.debug( 583 log.debug(
584 _(u"Cards played by %(profile)s: [%(cards)s]") 584 _("Cards played by %(profile)s: [%(cards)s]")
585 % {"profile": profile, "cards": cards} 585 % {"profile": profile, "cards": cards}
586 ) 586 )
587 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), "cards_played") 587 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), "cards_played")
588 self.send(jid.JID(referee), elem, {"player": player}, profile=profile) 588 self.send(jid.JID(referee), elem, {"player": player}, profile=profile)
589 589
645 "started", 645 "started",
646 "players", 646 "players",
647 ): # new game created and/or players list updated 647 ): # new game created and/or players list updated
648 players = [] 648 players = []
649 for player in elt.elements(): 649 for player in elt.elements():
650 players.append(unicode(player)) 650 players.append(str(player))
651 signal = ( 651 signal = (
652 self.host.bridge.tarotGameStarted 652 self.host.bridge.tarotGameStarted
653 if elt.name == "started" 653 if elt.name == "started"
654 else self.host.bridge.tarotGamePlayers 654 else self.host.bridge.tarotGamePlayers
655 ) 655 )
659 player = elt["player"] 659 player = elt["player"]
660 status = self.games[room_jid]["status"] 660 status = self.games[room_jid]["status"]
661 nb_players = len(self.games[room_jid]["players"]) 661 nb_players = len(self.games[room_jid]["players"])
662 status[player] = "ready" 662 status[player] = "ready"
663 log.debug( 663 log.debug(
664 _(u"Player %(player)s is ready to start [status: %(status)s]") 664 _("Player %(player)s is ready to start [status: %(status)s]")
665 % {"player": player, "status": status} 665 % {"player": player, "status": status}
666 ) 666 )
667 if ( 667 if (
668 status.values().count("ready") == nb_players 668 list(status.values()).count("ready") == nb_players
669 ): # everybody is ready, we can start the game 669 ): # everybody is ready, we can start the game
670 self.newRound(room_jid, profile) 670 self.newRound(room_jid, profile)
671 671
672 elif elt.name == "hand": # a new hand has been received 672 elif elt.name == "hand": # a new hand has been received
673 self.host.bridge.tarotGameNew( 673 self.host.bridge.tarotGameNew(
687 687
688 elif elt.name == "contrat_choosed": 688 elif elt.name == "contrat_choosed":
689 # TODO: check we receive the contrat from the right person 689 # TODO: check we receive the contrat from the right person
690 # TODO: use proper XEP-0004 way for answering form 690 # TODO: use proper XEP-0004 way for answering form
691 player = elt["player"] 691 player = elt["player"]
692 players_data[player]["contrat"] = unicode(elt) 692 players_data[player]["contrat"] = str(elt)
693 contrats = [players_data[p]["contrat"] for p in game_data["players"]] 693 contrats = [players_data[p]["contrat"] for p in game_data["players"]]
694 if contrats.count(None): 694 if contrats.count(None):
695 # not everybody has choosed his contrat, it's next one turn 695 # not everybody has choosed his contrat, it's next one turn
696 player = self.__next_player(game_data) 696 player = self.__next_player(game_data)
697 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: 697 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
718 ) # we change the dealer 718 ) # we change the dealer
719 for player in game_data["players"]: 719 for player in game_data["players"]:
720 game_data["status"][player] = "init" 720 game_data["status"][player] = "init"
721 return 721 return
722 log.debug( 722 log.debug(
723 _(u"%(player)s win the bid with %(contrat)s") 723 _("%(player)s win the bid with %(contrat)s")
724 % {"player": best_contrat[0], "contrat": best_contrat[1]} 724 % {"player": best_contrat[0], "contrat": best_contrat[1]}
725 ) 725 )
726 game_data["contrat"] = best_contrat[1] 726 game_data["contrat"] = best_contrat[1]
727 727
728 if ( 728 if (
823 for player in game_data["players"] 823 for player in game_data["players"]
824 ] 824 ]
825 if all(played): 825 if all(played):
826 # everybody has played 826 # everybody has played
827 winner = self.__winner(game_data) 827 winner = self.__winner(game_data)
828 log.debug(_(u"The winner of this trick is %s") % winner) 828 log.debug(_("The winner of this trick is %s") % winner)
829 # the winner win the trick 829 # the winner win the trick
830 self.__excuse_hack(game_data, played, winner) 830 self.__excuse_hack(game_data, played, winner)
831 players_data[elt["player"]]["levees"].extend(played) 831 players_data[elt["player"]]["levees"].extend(played)
832 # nothing left on the table 832 # nothing left on the table
833 for player in game_data["players"]: 833 for player in game_data["players"]:
859 859
860 elif elt.name == "your_turn": 860 elif elt.name == "your_turn":
861 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) 861 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
862 862
863 elif elt.name == "score": 863 elif elt.name == "score":
864 form_elt = elt.elements(name="x", uri="jabber:x:data").next() 864 form_elt = next(elt.elements(name="x", uri="jabber:x:data"))
865 winners = [] 865 winners = []
866 loosers = [] 866 loosers = []
867 for winner in elt.elements(name="winner", uri=NS_CG): 867 for winner in elt.elements(name="winner", uri=NS_CG):
868 winners.append(unicode(winner)) 868 winners.append(str(winner))
869 for looser in elt.elements(name="looser", uri=NS_CG): 869 for looser in elt.elements(name="looser", uri=NS_CG):
870 loosers.append(unicode(looser)) 870 loosers.append(str(looser))
871 form = data_form.Form.fromElement(form_elt) 871 form = data_form.Form.fromElement(form_elt)
872 session_id, session_data = self._sessions.newSession(profile=profile) 872 session_id, session_data = self._sessions.newSession(profile=profile)
873 session_data["room_jid"] = room_jid 873 session_data["room_jid"] = room_jid
874 xml_data = xml_tools.dataForm2XMLUI( 874 xml_data = xml_tools.dataForm2XMLUI(
875 form, self.__score_id, session_id 875 form, self.__score_id, session_id
878 room_jid.userhost(), xml_data, winners, loosers, profile 878 room_jid.userhost(), xml_data, winners, loosers, profile
879 ) 879 )
880 elif elt.name == "error": 880 elif elt.name == "error":
881 if elt["type"] == "invalid_cards": 881 if elt["type"] == "invalid_cards":
882 played_cards = self.__xml_to_list( 882 played_cards = self.__xml_to_list(
883 elt.elements(name="played", uri=NS_CG).next() 883 next(elt.elements(name="played", uri=NS_CG))
884 ) 884 )
885 invalid_cards = self.__xml_to_list( 885 invalid_cards = self.__xml_to_list(
886 elt.elements(name="invalid", uri=NS_CG).next() 886 next(elt.elements(name="invalid", uri=NS_CG))
887 ) 887 )
888 self.host.bridge.tarotGameInvalidCards( 888 self.host.bridge.tarotGameInvalidCards(
889 room_jid.userhost(), 889 room_jid.userhost(),
890 elt["phase"], 890 elt["phase"],
891 played_cards, 891 played_cards,
892 invalid_cards, 892 invalid_cards,
893 profile, 893 profile,
894 ) 894 )
895 else: 895 else:
896 log.error(_(u"Unmanaged error type: %s") % elt["type"]) 896 log.error(_("Unmanaged error type: %s") % elt["type"])
897 else: 897 else:
898 log.error(_(u"Unmanaged card game element: %s") % elt.name) 898 log.error(_("Unmanaged card game element: %s") % elt.name)
899 899
900 def getSyncDataForPlayer(self, room_jid, nick): 900 def getSyncDataForPlayer(self, room_jid, nick):
901 return [] 901 return []