comparison sat/plugins/plugin_misc_tarot.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 26edcf3a30eb
children 003b8b4b56a7
comparison
equal deleted inserted replaced
2623:49533de4540b 2624:56f94936df1e
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 from sat.core.i18n import _ 20 from sat.core.i18n import _
21 from sat.core.constants import Const as C 21 from sat.core.constants import Const as C
22 from sat.core.log import getLogger 22 from sat.core.log import getLogger
23
23 log = getLogger(__name__) 24 log = getLogger(__name__)
24 from twisted.words.xish import domish 25 from twisted.words.xish import domish
25 from twisted.words.protocols.jabber import jid 26 from twisted.words.protocols.jabber import jid
26 from twisted.internet import defer 27 from twisted.internet import defer
27 from wokkel import data_form 28 from wokkel import data_form
30 from sat.tools import xml_tools 31 from sat.tools import xml_tools
31 from sat_frontends.tools.games import TarotCard 32 from sat_frontends.tools.games import TarotCard
32 import random 33 import random
33 34
34 35
35 NS_CG = 'http://www.goffi.org/protocol/card_game' 36 NS_CG = "http://www.goffi.org/protocol/card_game"
36 CG_TAG = 'card_game' 37 CG_TAG = "card_game"
37 38
38 PLUGIN_INFO = { 39 PLUGIN_INFO = {
39 C.PI_NAME: "Tarot cards plugin", 40 C.PI_NAME: "Tarot cards plugin",
40 C.PI_IMPORT_NAME: "Tarot", 41 C.PI_IMPORT_NAME: "Tarot",
41 C.PI_TYPE: "Misc", 42 C.PI_TYPE: "Misc",
42 C.PI_PROTOCOLS: [], 43 C.PI_PROTOCOLS: [],
43 C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249", "ROOM-GAME"], 44 C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249", "ROOM-GAME"],
44 C.PI_MAIN: "Tarot", 45 C.PI_MAIN: "Tarot",
45 C.PI_HANDLER: "yes", 46 C.PI_HANDLER: "yes",
46 C.PI_DESCRIPTION: _("""Implementation of Tarot card game""") 47 C.PI_DESCRIPTION: _("""Implementation of Tarot card game"""),
47 } 48 }
48 49
49 50
50 class Tarot(object): 51 class Tarot(object):
51
52 def inheritFromRoomGame(self, host): 52 def inheritFromRoomGame(self, host):
53 global RoomGame 53 global RoomGame
54 RoomGame = host.plugins["ROOM-GAME"].__class__ 54 RoomGame = host.plugins["ROOM-GAME"].__class__
55 self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {}) 55 self.__class__ = type(
56 self.__class__.__name__, (self.__class__, RoomGame, object), {}
57 )
56 58
57 def __init__(self, host): 59 def __init__(self, host):
58 log.info(_("Plugin Tarot initialization")) 60 log.info(_("Plugin Tarot initialization"))
59 self._sessions = memory.Sessions() 61 self._sessions = memory.Sessions()
60 self.inheritFromRoomGame(host) 62 self.inheritFromRoomGame(host)
61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG), 63 RoomGame._init_(
62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}, 64 self,
63 player_init={'score': 0}) 65 host,
64 self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')] 66 PLUGIN_INFO,
65 host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True) # args: players, room_jid, profile 67 (NS_CG, CG_TAG),
66 host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile 68 game_init={
67 host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile 69 "hand_size": 18,
68 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile 70 "init_player": 0,
69 host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, profile 71 "current_player": None,
70 host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile 72 "contrat": None,
71 host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') # args: room_jid, hand, profile 73 "stage": None,
72 host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') # args: room_jid, xml_data, profile 74 },
73 host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') # args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile 75 player_init={"score": 0},
74 host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') # args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile 76 )
75 host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') # args: room_jid, profile 77 self.contrats = [
76 host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile 78 _("Passe"),
77 host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') # args: room_jid, game phase, played_cards, invalid_cards, profile 79 _("Petite"),
80 _("Garde"),
81 _("Garde Sans"),
82 _("Garde Contre"),
83 ]
84 host.bridge.addMethod(
85 "tarotGameLaunch",
86 ".plugin",
87 in_sign="asss",
88 out_sign="",
89 method=self._prepareRoom,
90 async=True,
91 ) # args: players, room_jid, profile
92 host.bridge.addMethod(
93 "tarotGameCreate",
94 ".plugin",
95 in_sign="sass",
96 out_sign="",
97 method=self._createGame,
98 ) # args: room_jid, players, profile
99 host.bridge.addMethod(
100 "tarotGameReady",
101 ".plugin",
102 in_sign="sss",
103 out_sign="",
104 method=self._playerReady,
105 ) # args: player, referee, profile
106 host.bridge.addMethod(
107 "tarotGamePlayCards",
108 ".plugin",
109 in_sign="ssa(ss)s",
110 out_sign="",
111 method=self.play_cards,
112 ) # args: player, referee, cards, profile
113 host.bridge.addSignal(
114 "tarotGamePlayers", ".plugin", signature="ssass"
115 ) # args: room_jid, referee, players, profile
116 host.bridge.addSignal(
117 "tarotGameStarted", ".plugin", signature="ssass"
118 ) # args: room_jid, referee, players, profile
119 host.bridge.addSignal(
120 "tarotGameNew", ".plugin", signature="sa(ss)s"
121 ) # args: room_jid, hand, profile
122 host.bridge.addSignal(
123 "tarotGameChooseContrat", ".plugin", signature="sss"
124 ) # args: room_jid, xml_data, profile
125 host.bridge.addSignal(
126 "tarotGameShowCards", ".plugin", signature="ssa(ss)a{ss}s"
127 ) # args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile
128 host.bridge.addSignal(
129 "tarotGameCardsPlayed", ".plugin", signature="ssa(ss)s"
130 ) # args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile
131 host.bridge.addSignal(
132 "tarotGameYourTurn", ".plugin", signature="ss"
133 ) # args: room_jid, profile
134 host.bridge.addSignal(
135 "tarotGameScore", ".plugin", signature="ssasass"
136 ) # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
137 host.bridge.addSignal(
138 "tarotGameInvalidCards", ".plugin", signature="ssa(ss)a(ss)s"
139 ) # args: room_jid, game phase, played_cards, invalid_cards, profile
78 self.deck_ordered = [] 140 self.deck_ordered = []
79 for value in ['excuse'] + map(str, range(1, 22)): 141 for value in ["excuse"] + map(str, range(1, 22)):
80 self.deck_ordered.append(TarotCard(("atout", value))) 142 self.deck_ordered.append(TarotCard(("atout", value)))
81 for suit in ["pique", "coeur", "carreau", "trefle"]: 143 for suit in ["pique", "coeur", "carreau", "trefle"]:
82 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]: 144 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
83 self.deck_ordered.append(TarotCard((suit, value))) 145 self.deck_ordered.append(TarotCard((suit, value)))
84 self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True) 146 self.__choose_contrat_id = host.registerCallback(
147 self._contratChoosed, with_data=True
148 )
85 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True) 149 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
86 150
87 def __card_list_to_xml(self, cards_list, elt_name): 151 def __card_list_to_xml(self, cards_list, elt_name):
88 """Convert a card list to domish element""" 152 """Convert a card list to domish element"""
89 cards_list_elt = domish.Element((None, elt_name)) 153 cards_list_elt = domish.Element((None, elt_name))
90 for card in cards_list: 154 for card in cards_list:
91 card_elt = domish.Element((None, 'card')) 155 card_elt = domish.Element((None, "card"))
92 card_elt['suit'] = card.suit 156 card_elt["suit"] = card.suit
93 card_elt['value'] = card.value 157 card_elt["value"] = card.value
94 cards_list_elt.addChild(card_elt) 158 cards_list_elt.addChild(card_elt)
95 return cards_list_elt 159 return cards_list_elt
96 160
97 def __xml_to_list(self, cards_list_elt): 161 def __xml_to_list(self, cards_list_elt):
98 """Convert a domish element with cards to a list of tuples""" 162 """Convert a domish element with cards to a list of tuples"""
99 cards_list = [] 163 cards_list = []
100 for card in cards_list_elt.elements(): 164 for card in cards_list_elt.elements():
101 cards_list.append((card['suit'], card['value'])) 165 cards_list.append((card["suit"], card["value"]))
102 return cards_list 166 return cards_list
103 167
104 def __ask_contrat(self): 168 def __ask_contrat(self):
105 """Create a element for asking contrat""" 169 """Create a element for asking contrat"""
106 contrat_elt = domish.Element((None, 'contrat')) 170 contrat_elt = domish.Element((None, "contrat"))
107 form = data_form.Form('form', title=_('contrat selection')) 171 form = data_form.Form("form", title=_("contrat selection"))
108 field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True) 172 field = data_form.Field(
173 "list-single",
174 "contrat",
175 options=map(data_form.Option, self.contrats),
176 required=True,
177 )
109 form.addField(field) 178 form.addField(field)
110 contrat_elt.addChild(form.toElement()) 179 contrat_elt.addChild(form.toElement())
111 return contrat_elt 180 return contrat_elt
112 181
113 def __give_scores(self, scores, winners, loosers): 182 def __give_scores(self, scores, winners, loosers):
114 """Create an element to give scores 183 """Create an element to give scores
115 @param scores: unicode (can contain line feed) 184 @param scores: unicode (can contain line feed)
116 @param winners: list of unicode nicks of winners 185 @param winners: list of unicode nicks of winners
117 @param loosers: list of unicode nicks of loosers""" 186 @param loosers: list of unicode nicks of loosers"""
118 187
119 score_elt = domish.Element((None, 'score')) 188 score_elt = domish.Element((None, "score"))
120 form = data_form.Form('form', title=_('scores')) 189 form = data_form.Form("form", title=_("scores"))
121 for line in scores.split('\n'): 190 for line in scores.split("\n"):
122 field = data_form.Field('fixed', value=line) 191 field = data_form.Field("fixed", value=line)
123 form.addField(field) 192 form.addField(field)
124 score_elt.addChild(form.toElement()) 193 score_elt.addChild(form.toElement())
125 for winner in winners: 194 for winner in winners:
126 winner_elt = domish.Element((None, 'winner')) 195 winner_elt = domish.Element((None, "winner"))
127 winner_elt.addContent(winner) 196 winner_elt.addContent(winner)
128 score_elt.addChild(winner_elt) 197 score_elt.addChild(winner_elt)
129 for looser in loosers: 198 for looser in loosers:
130 looser_elt = domish.Element((None, 'looser')) 199 looser_elt = domish.Element((None, "looser"))
131 looser_elt.addContent(looser) 200 looser_elt.addContent(looser)
132 score_elt.addChild(looser_elt) 201 score_elt.addChild(looser_elt)
133 return score_elt 202 return score_elt
134 203
135 def __invalid_cards_elt(self, played_cards, invalid_cards, game_phase): 204 def __invalid_cards_elt(self, played_cards, invalid_cards, game_phase):
136 """Create a element for invalid_cards error 205 """Create a element for invalid_cards error
137 @param list_cards: list of Card 206 @param list_cards: list of Card
138 @param game_phase: phase of the game ['ecart', 'play']""" 207 @param game_phase: phase of the game ['ecart', 'play']"""
139 error_elt = domish.Element((None, 'error')) 208 error_elt = domish.Element((None, "error"))
140 played_elt = self.__card_list_to_xml(played_cards, 'played') 209 played_elt = self.__card_list_to_xml(played_cards, "played")
141 invalid_elt = self.__card_list_to_xml(invalid_cards, 'invalid') 210 invalid_elt = self.__card_list_to_xml(invalid_cards, "invalid")
142 error_elt['type'] = 'invalid_cards' 211 error_elt["type"] = "invalid_cards"
143 error_elt['phase'] = game_phase 212 error_elt["phase"] = game_phase
144 error_elt.addChild(played_elt) 213 error_elt.addChild(played_elt)
145 error_elt.addChild(invalid_elt) 214 error_elt.addChild(invalid_elt)
146 return error_elt 215 return error_elt
147 216
148 def __next_player(self, game_data, next_pl=None): 217 def __next_player(self, game_data, next_pl=None):
149 """Increment player number & return player name 218 """Increment player number & return player name
150 @param next_pl: if given, then next_player is forced to this one 219 @param next_pl: if given, then next_player is forced to this one
151 """ 220 """
152 if next_pl: 221 if next_pl:
153 game_data['current_player'] = game_data['players'].index(next_pl) 222 game_data["current_player"] = game_data["players"].index(next_pl)
154 return next_pl 223 return next_pl
155 else: 224 else:
156 pl_idx = game_data['current_player'] = (game_data['current_player'] + 1) % len(game_data['players']) 225 pl_idx = game_data["current_player"] = (
157 return game_data['players'][pl_idx] 226 game_data["current_player"] + 1
227 ) % len(game_data["players"])
228 return game_data["players"][pl_idx]
158 229
159 def __winner(self, game_data): 230 def __winner(self, game_data):
160 """give the nick of the player who win this trick""" 231 """give the nick of the player who win this trick"""
161 players_data = game_data['players_data'] 232 players_data = game_data["players_data"]
162 first = game_data['first_player'] 233 first = game_data["first_player"]
163 first_idx = game_data['players'].index(first) 234 first_idx = game_data["players"].index(first)
164 suit_asked = None 235 suit_asked = None
165 strongest = None 236 strongest = None
166 winner = None 237 winner = None
167 for idx in [(first_idx + i) % 4 for i in range(4)]: 238 for idx in [(first_idx + i) % 4 for i in range(4)]:
168 player = game_data['players'][idx] 239 player = game_data["players"][idx]
169 card = players_data[player]['played'] 240 card = players_data[player]["played"]
170 if card.value == "excuse": 241 if card.value == "excuse":
171 continue 242 continue
172 if suit_asked is None: 243 if suit_asked is None:
173 suit_asked = card.suit 244 suit_asked = card.suit
174 if (card.suit == suit_asked or card.suit == "atout") and card > strongest: 245 if (card.suit == suit_asked or card.suit == "atout") and card > strongest:
181 """give a low card to other team and keep excuse if trick is lost 252 """give a low card to other team and keep excuse if trick is lost
182 @param game_data: data of the game 253 @param game_data: data of the game
183 @param played: cards currently on the table 254 @param played: cards currently on the table
184 @param winner: nick of the trick winner""" 255 @param winner: nick of the trick winner"""
185 # TODO: manage the case where excuse is played on the last trick (and lost) 256 # TODO: manage the case where excuse is played on the last trick (and lost)
186 players_data = game_data['players_data'] 257 players_data = game_data["players_data"]
187 excuse = TarotCard(("atout", "excuse")) 258 excuse = TarotCard(("atout", "excuse"))
188 259
189 # we first check if the Excuse was already played 260 # we first check if the Excuse was already played
190 # and if somebody is waiting for a card 261 # and if somebody is waiting for a card
191 for player in game_data['players']: 262 for player in game_data["players"]:
192 if players_data[player]['wait_for_low']: 263 if players_data[player]["wait_for_low"]:
193 # the excuse owner has to give a card to somebody 264 # the excuse owner has to give a card to somebody
194 if winner == player: 265 if winner == player:
195 # the excuse owner win the trick, we check if we have something to give 266 # the excuse owner win the trick, we check if we have something to give
196 for card in played: 267 for card in played:
197 if card.points == 0.5: 268 if card.points == 0.5:
198 pl_waiting = players_data[player]['wait_for_low'] 269 pl_waiting = players_data[player]["wait_for_low"]
199 played.remove(card) 270 played.remove(card)
200 players_data[pl_waiting]['levees'].append(card) 271 players_data[pl_waiting]["levees"].append(card)
201 log.debug(_(u'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}) 272 log.debug(
273 _(
274 u"Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation"
275 )
276 % {
277 "excuse_owner": player,
278 "card_waited": card,
279 "player_waiting": pl_waiting,
280 }
281 )
202 return 282 return
203 return 283 return
204 284
205 if excuse not in played: 285 if excuse not in played:
206 # the Excuse is not on the table, nothing to do 286 # the Excuse is not on the table, nothing to do
207 return 287 return
208 288
209 excuse_player = None # Who has played the Excuse ? 289 excuse_player = None # Who has played the Excuse ?
210 for player in game_data['players']: 290 for player in game_data["players"]:
211 if players_data[player]['played'] == excuse: 291 if players_data[player]["played"] == excuse:
212 excuse_player = player 292 excuse_player = player
213 break 293 break
214 294
215 if excuse_player == winner: 295 if excuse_player == winner:
216 return # the excuse player win the trick, nothing to do 296 return # the excuse player win the trick, nothing to do
217 297
218 # first we remove the excuse from played cards 298 # first we remove the excuse from played cards
219 played.remove(excuse) 299 played.remove(excuse)
220 # then we give it back to the original owner 300 # then we give it back to the original owner
221 owner_levees = players_data[excuse_player]['levees'] 301 owner_levees = players_data[excuse_player]["levees"]
222 owner_levees.append(excuse) 302 owner_levees.append(excuse)
223 # finally we give a low card to the trick winner 303 # finally we give a low card to the trick winner
224 low_card = None 304 low_card = None
225 # We look backward in cards won by the Excuse owner to 305 # We look backward in cards won by the Excuse owner to
226 # find a low value card 306 # find a low value card
227 for card_idx in range(len(owner_levees) - 1, -1, -1): 307 for card_idx in range(len(owner_levees) - 1, -1, -1):
228 if owner_levees[card_idx].points == 0.5: 308 if owner_levees[card_idx].points == 0.5:
229 low_card = owner_levees[card_idx] 309 low_card = owner_levees[card_idx]
230 del owner_levees[card_idx] 310 del owner_levees[card_idx]
231 players_data[winner]['levees'].append(low_card) 311 players_data[winner]["levees"].append(low_card)
232 log.debug(_(u'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}) 312 log.debug(
313 _(
314 u"Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation"
315 )
316 % {
317 "excuse_owner": excuse_player,
318 "card_waited": low_card,
319 "player_waiting": winner,
320 }
321 )
233 break 322 break
234 if not low_card: # The player has no low card yet 323 if not low_card: # The player has no low card yet
235 # 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
236 players_data[excuse_player]['wait_for_low'] = winner 325 players_data[excuse_player]["wait_for_low"] = winner
237 log.debug(_(u"%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner}) 326 log.debug(
327 _(
328 u"%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one"
329 )
330 % {"excuse_owner": excuse_player, "winner": winner}
331 )
238 332
239 def __draw_game(self, game_data): 333 def __draw_game(self, game_data):
240 """The game is draw, no score change 334 """The game is draw, no score change
241 @param game_data: data of the game 335 @param game_data: data of the game
242 @return: tuple with (string victory message, list of winners, list of loosers)""" 336 @return: tuple with (string victory message, list of winners, list of loosers)"""
243 players_data = game_data['players_data'] 337 players_data = game_data["players_data"]
244 scores_str = _('Draw game') 338 scores_str = _("Draw game")
245 scores_str += '\n' 339 scores_str += "\n"
246 for player in game_data['players']: 340 for player in game_data["players"]:
247 scores_str += _(u"\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']} 341 scores_str += _(
342 u"\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i"
343 ) % {
344 "player": player,
345 "score_game": 0,
346 "total_score": players_data[player]["score"],
347 }
248 log.debug(scores_str) 348 log.debug(scores_str)
249 349
250 return (scores_str, [], []) 350 return (scores_str, [], [])
251 351
252 def __calculate_scores(self, game_data): 352 def __calculate_scores(self, game_data):
253 """The game is finished, time to know who won :) 353 """The game is finished, time to know who won :)
254 @param game_data: data of the game 354 @param game_data: data of the game
255 @return: tuple with (string victory message, list of winners, list of loosers)""" 355 @return: tuple with (string victory message, list of winners, list of loosers)"""
256 players_data = game_data['players_data'] 356 players_data = game_data["players_data"]
257 levees = players_data[game_data['attaquant']]['levees'] 357 levees = players_data[game_data["attaquant"]]["levees"]
258 score = 0 358 score = 0
259 nb_bouts = 0 359 nb_bouts = 0
260 bouts = [] 360 bouts = []
261 for card in levees: 361 for card in levees:
262 if card.bout: 362 if card.bout:
264 bouts.append(card.value) 364 bouts.append(card.value)
265 score += card.points 365 score += card.points
266 366
267 # We do a basic check on score calculation 367 # We do a basic check on score calculation
268 check_score = 0 368 check_score = 0
269 defenseurs = game_data['players'][:] 369 defenseurs = game_data["players"][:]
270 defenseurs.remove(game_data['attaquant']) 370 defenseurs.remove(game_data["attaquant"])
271 for defenseur in defenseurs: 371 for defenseur in defenseurs:
272 for card in players_data[defenseur]['levees']: 372 for card in players_data[defenseur]["levees"]:
273 check_score += card.points 373 check_score += card.points
274 if game_data['contrat'] == "Garde Contre": 374 if game_data["contrat"] == "Garde Contre":
275 for card in game_data['chien']: 375 for card in game_data["chien"]:
276 check_score += card.points 376 check_score += card.points
277 assert (score + check_score == 91) 377 assert score + check_score == 91
278 378
279 point_limit = None 379 point_limit = None
280 if nb_bouts == 3: 380 if nb_bouts == 3:
281 point_limit = 36 381 point_limit = 36
282 elif nb_bouts == 2: 382 elif nb_bouts == 2:
283 point_limit = 41 383 point_limit = 41
284 elif nb_bouts == 1: 384 elif nb_bouts == 1:
285 point_limit = 51 385 point_limit = 51
286 else: 386 else:
287 point_limit = 56 387 point_limit = 56
288 if game_data['contrat'] == 'Petite': 388 if game_data["contrat"] == "Petite":
289 contrat_mult = 1 389 contrat_mult = 1
290 elif game_data['contrat'] == 'Garde': 390 elif game_data["contrat"] == "Garde":
291 contrat_mult = 2 391 contrat_mult = 2
292 elif game_data['contrat'] == 'Garde Sans': 392 elif game_data["contrat"] == "Garde Sans":
293 contrat_mult = 4 393 contrat_mult = 4
294 elif game_data['contrat'] == 'Garde Contre': 394 elif game_data["contrat"] == "Garde Contre":
295 contrat_mult = 6 395 contrat_mult = 6
296 else: 396 else:
297 log.error(_('INTERNAL ERROR: contrat not managed (mispelled ?)')) 397 log.error(_("INTERNAL ERROR: contrat not managed (mispelled ?)"))
298 assert(False) 398 assert False
299 399
300 victory = (score >= point_limit) 400 victory = score >= point_limit
301 margin = abs(score - point_limit) 401 margin = abs(score - point_limit)
302 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1) 402 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1)
303 winners = [] 403 winners = []
304 loosers = [] 404 loosers = []
305 player_score = {} 405 player_score = {}
306 for player in game_data['players']: 406 for player in game_data["players"]:
307 # TODO: adjust this for 3 and 5 players variants 407 # TODO: adjust this for 3 and 5 players variants
308 # TODO: manage bonuses (petit au bout, poignée, chelem) 408 # TODO: manage bonuses (petit au bout, poignée, chelem)
309 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3 409 player_score[player] = (
310 players_data[player]['score'] += player_score[player] # we add score of this game to the global score 410 points_defenseur
411 if player != game_data["attaquant"]
412 else points_defenseur * -3
413 )
414 players_data[player]["score"] += player_score[
415 player
416 ] # we add score of this game to the global score
311 if player_score[player] > 0: 417 if player_score[player] > 0:
312 winners.append(player) 418 winners.append(player)
313 else: 419 else:
314 loosers.append(player) 420 loosers.append(player)
315 421
316 scores_str = _(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') % {'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'} 422 scores_str = _(
317 scores_str += '\n' 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"
318 for player in game_data['players']: 424 ) % {
319 scores_str += _(u"\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']} 425 "attaquant": game_data["attaquant"],
426 "points": score,
427 "point_limit": point_limit,
428 "nb_bouts": nb_bouts,
429 "plural": "s" if nb_bouts > 1 else "",
430 "separator": ": " if nb_bouts != 0 else "",
431 "bouts": ",".join(map(str, bouts)),
432 "victory": "wins" if victory else "looses",
433 }
434 scores_str += "\n"
435 for player in game_data["players"]:
436 scores_str += _(
437 u"\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i"
438 ) % {
439 "player": player,
440 "score_game": player_score[player],
441 "total_score": players_data[player]["score"],
442 }
320 log.debug(scores_str) 443 log.debug(scores_str)
321 444
322 return (scores_str, winners, loosers) 445 return (scores_str, winners, loosers)
323 446
324 def __invalid_cards(self, game_data, cards): 447 def __invalid_cards(self, game_data, cards):
325 """Checks that the player has the right to play what he wants to 448 """Checks that the player has the right to play what he wants to
326 @param game_data: Game data 449 @param game_data: Game data
327 @param cards: cards the player want to play 450 @param cards: cards the player want to play
328 @return forbidden_cards cards or empty list if cards are ok""" 451 @return forbidden_cards cards or empty list if cards are ok"""
329 forbidden_cards = [] 452 forbidden_cards = []
330 if game_data['stage'] == 'ecart': 453 if game_data["stage"] == "ecart":
331 for card in cards: 454 for card in cards:
332 if card.bout or card.value == "roi": 455 if card.bout or card.value == "roi":
333 forbidden_cards.append(card) 456 forbidden_cards.append(card)
334 # TODO: manage case where atouts (trumps) are in the dog 457 # TODO: manage case where atouts (trumps) are in the dog
335 elif game_data['stage'] == 'play': 458 elif game_data["stage"] == "play":
336 biggest_atout = None 459 biggest_atout = None
337 suit_asked = None 460 suit_asked = None
338 players = game_data['players'] 461 players = game_data["players"]
339 players_data = game_data['players_data'] 462 players_data = game_data["players_data"]
340 idx = players.index(game_data['first_player']) 463 idx = players.index(game_data["first_player"])
341 current_idx = game_data['current_player'] 464 current_idx = game_data["current_player"]
342 current_player = players[current_idx] 465 current_player = players[current_idx]
343 if idx == current_idx: 466 if idx == current_idx:
344 # the player is the first to play, he can play what he wants 467 # the player is the first to play, he can play what he wants
345 return forbidden_cards 468 return forbidden_cards
346 while (idx != current_idx): 469 while idx != current_idx:
347 player = players[idx] 470 player = players[idx]
348 played_card = players_data[player]['played'] 471 played_card = players_data[player]["played"]
349 if not suit_asked and played_card.value != "excuse": 472 if not suit_asked and played_card.value != "excuse":
350 suit_asked = played_card.suit 473 suit_asked = played_card.suit
351 if played_card.suit == "atout" and played_card > biggest_atout: 474 if played_card.suit == "atout" and played_card > biggest_atout:
352 biggest_atout = played_card 475 biggest_atout = played_card
353 idx = (idx + 1) % len(players) 476 idx = (idx + 1) % len(players)
354 has_suit = False # True if there is one card of the asked suit in the hand of the player 477 has_suit = (
478 False
479 ) # True if there is one card of the asked suit in the hand of the player
355 has_atout = False 480 has_atout = False
356 biggest_hand_atout = None 481 biggest_hand_atout = None
357 482
358 for hand_card in game_data['hand'][current_player]: 483 for hand_card in game_data["hand"][current_player]:
359 if hand_card.suit == suit_asked: 484 if hand_card.suit == suit_asked:
360 has_suit = True 485 has_suit = True
361 if hand_card.suit == "atout": 486 if hand_card.suit == "atout":
362 has_atout = True 487 has_atout = True
363 if hand_card.suit == "atout" and hand_card > biggest_hand_atout: 488 if hand_card.suit == "atout" and hand_card > biggest_hand_atout:
369 forbidden_cards.append(card) 494 forbidden_cards.append(card)
370 return forbidden_cards 495 return forbidden_cards
371 if card.suit != suit_asked and card.suit != "atout" and has_atout: 496 if card.suit != suit_asked and card.suit != "atout" and has_atout:
372 forbidden_cards.append(card) 497 forbidden_cards.append(card)
373 return forbidden_cards 498 return forbidden_cards
374 if card.suit == "atout" and card < biggest_atout and biggest_hand_atout > biggest_atout and card.value != "excuse": 499 if (
500 card.suit == "atout"
501 and card < biggest_atout
502 and biggest_hand_atout > biggest_atout
503 and card.value != "excuse"
504 ):
375 forbidden_cards.append(card) 505 forbidden_cards.append(card)
376 else: 506 else:
377 log.error(_('Internal error: unmanaged game stage')) 507 log.error(_("Internal error: unmanaged game stage"))
378 return forbidden_cards 508 return forbidden_cards
379 509
380 def __start_play(self, room_jid, game_data, profile): 510 def __start_play(self, room_jid, game_data, profile):
381 """Start the game (tell to the first player after dealer to play""" 511 """Start the game (tell to the first player after dealer to play"""
382 game_data['stage'] = "play" 512 game_data["stage"] = "play"
383 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # the player after the dealer start 513 next_player_idx = game_data["current_player"] = (
384 game_data['first_player'] = next_player = game_data['players'][next_player_idx] 514 game_data["init_player"] + 1
515 ) % len(
516 game_data["players"]
517 ) # the player after the dealer start
518 game_data["first_player"] = next_player = game_data["players"][next_player_idx]
385 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) # FIXME: gof: 519 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) # FIXME: gof:
386 self.send(to_jid, 'your_turn', profile=profile) 520 self.send(to_jid, "your_turn", profile=profile)
387 521
388 def _contratChoosed(self, raw_data, profile): 522 def _contratChoosed(self, raw_data, profile):
389 """Will be called when the contrat is selected 523 """Will be called when the contrat is selected
390 @param raw_data: contains the choosed session id and the chosen contrat 524 @param raw_data: contains the choosed session id and the chosen contrat
391 @param profile_key: profile 525 @param profile_key: profile
395 except KeyError: 529 except KeyError:
396 log.warning(_("session id doesn't exist, session has probably expired")) 530 log.warning(_("session id doesn't exist, session has probably expired"))
397 # TODO: send error dialog 531 # TODO: send error dialog
398 return defer.succeed({}) 532 return defer.succeed({})
399 533
400 room_jid = session_data['room_jid'] 534 room_jid = session_data["room_jid"]
401 referee_jid = self.games[room_jid]['referee'] 535 referee_jid = self.games[room_jid]["referee"]
402 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile) 536 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
403 data = xml_tools.XMLUIResult2DataFormResult(raw_data) 537 data = xml_tools.XMLUIResult2DataFormResult(raw_data)
404 contrat = data['contrat'] 538 contrat = data["contrat"]
405 log.debug(_(u'contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile}) 539 log.debug(
406 d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile) 540 _(u"contrat [%(contrat)s] choosed by %(profile)s")
541 % {"contrat": contrat, "profile": profile}
542 )
543 d = self.send(
544 referee_jid,
545 ("", "contrat_choosed"),
546 {"player": player},
547 content=contrat,
548 profile=profile,
549 )
407 d.addCallback(lambda ignore: {}) 550 d.addCallback(lambda ignore: {})
408 del self._sessions[raw_data["session_id"]] 551 del self._sessions[raw_data["session_id"]]
409 return d 552 return d
410 553
411 def _scoreShowed(self, raw_data, profile): 554 def _scoreShowed(self, raw_data, profile):
418 except KeyError: 561 except KeyError:
419 log.warning(_("session id doesn't exist, session has probably expired")) 562 log.warning(_("session id doesn't exist, session has probably expired"))
420 # TODO: send error dialog 563 # TODO: send error dialog
421 return defer.succeed({}) 564 return defer.succeed({})
422 565
423 room_jid_s = session_data['room_jid'].userhost() 566 room_jid_s = session_data["room_jid"].userhost()
424 # XXX: empty hand means to the frontend "reset the display"... 567 # XXX: empty hand means to the frontend "reset the display"...
425 self.host.bridge.tarotGameNew(room_jid_s, [], profile) 568 self.host.bridge.tarotGameNew(room_jid_s, [], profile)
426 del self._sessions[raw_data["session_id"]] 569 del self._sessions[raw_data["session_id"]]
427 return defer.succeed({}) 570 return defer.succeed({})
428 571
435 """ 578 """
436 profile = self.host.memory.getProfileName(profile_key) 579 profile = self.host.memory.getProfileName(profile_key)
437 if not profile: 580 if not profile:
438 log.error(_(u"profile %s is unknown") % profile_key) 581 log.error(_(u"profile %s is unknown") % profile_key)
439 return 582 return
440 log.debug(_(u'Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards}) 583 log.debug(
441 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played') 584 _(u"Cards played by %(profile)s: [%(cards)s]")
442 self.send(jid.JID(referee), elem, {'player': player}, profile=profile) 585 % {"profile": profile, "cards": cards}
586 )
587 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), "cards_played")
588 self.send(jid.JID(referee), elem, {"player": player}, profile=profile)
443 589
444 def newRound(self, room_jid, profile): 590 def newRound(self, room_jid, profile):
445 game_data = self.games[room_jid] 591 game_data = self.games[room_jid]
446 players = game_data['players'] 592 players = game_data["players"]
447 game_data['first_player'] = None # first player for the current trick 593 game_data["first_player"] = None # first player for the current trick
448 game_data['contrat'] = None 594 game_data["contrat"] = None
449 common_data = {'contrat': None, 595 common_data = {
450 'levees': [], # cards won 596 "contrat": None,
451 'played': None, # card on the table 597 "levees": [], # cards won
452 'wait_for_low': None # Used when a player wait for a low card because of excuse 598 "played": None, # card on the table
453 } 599 "wait_for_low": None, # Used when a player wait for a low card because of excuse
454 600 }
455 hand = game_data['hand'] = {} 601
456 hand_size = game_data['hand_size'] 602 hand = game_data["hand"] = {}
457 chien = game_data['chien'] = [] 603 hand_size = game_data["hand_size"]
604 chien = game_data["chien"] = []
458 deck = self.deck_ordered[:] 605 deck = self.deck_ordered[:]
459 random.shuffle(deck) 606 random.shuffle(deck)
460 for i in range(4): 607 for i in range(4):
461 hand[players[i]] = deck[0:hand_size] 608 hand[players[i]] = deck[0:hand_size]
462 del deck[0:hand_size] 609 del deck[0:hand_size]
463 chien.extend(deck) 610 chien.extend(deck)
464 del(deck[:]) 611 del (deck[:])
465 msg_elts = {} 612 msg_elts = {}
466 for player in players: 613 for player in players:
467 msg_elts[player] = self.__card_list_to_xml(hand[player], 'hand') 614 msg_elts[player] = self.__card_list_to_xml(hand[player], "hand")
468 615
469 RoomGame.newRound(self, room_jid, (common_data, msg_elts), profile) 616 RoomGame.newRound(self, room_jid, (common_data, msg_elts), profile)
470 617
471 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) # the player after the dealer start 618 pl_idx = game_data["current_player"] = (game_data["init_player"] + 1) % len(
619 players
620 ) # the player after the dealer start
472 player = players[pl_idx] 621 player = players[pl_idx]
473 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: 622 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
474 self.send(to_jid, self.__ask_contrat(), profile=profile) 623 self.send(to_jid, self.__ask_contrat(), profile=profile)
475 624
476 def room_game_cmd(self, mess_elt, profile): 625 def room_game_cmd(self, mess_elt, profile):
477 """ 626 """
478 @param mess_elt: instance of twisted.words.xish.domish.Element 627 @param mess_elt: instance of twisted.words.xish.domish.Element
479 """ 628 """
480 client = self.host.getClient(profile) 629 client = self.host.getClient(profile)
481 from_jid = jid.JID(mess_elt['from']) 630 from_jid = jid.JID(mess_elt["from"])
482 room_jid = jid.JID(from_jid.userhost()) 631 room_jid = jid.JID(from_jid.userhost())
483 nick = self.host.plugins["XEP-0045"].getRoomNick(client, room_jid) 632 nick = self.host.plugins["XEP-0045"].getRoomNick(client, room_jid)
484 633
485 game_elt = mess_elt.firstChildElement() 634 game_elt = mess_elt.firstChildElement()
486 game_data = self.games[room_jid] 635 game_data = self.games[room_jid]
487 is_player = self.isPlayer(room_jid, nick) 636 is_player = self.isPlayer(room_jid, nick)
488 if 'players_data' in game_data: 637 if "players_data" in game_data:
489 players_data = game_data['players_data'] 638 players_data = game_data["players_data"]
490 639
491 for elt in game_elt.elements(): 640 for elt in game_elt.elements():
492 if not is_player and (elt.name not in ('started', 'players')): 641 if not is_player and (elt.name not in ("started", "players")):
493 continue # user is in the room but not playing 642 continue # user is in the room but not playing
494 643
495 if elt.name in ('started', 'players'): # new game created and/or players list updated 644 if elt.name in (
645 "started",
646 "players",
647 ): # new game created and/or players list updated
496 players = [] 648 players = []
497 for player in elt.elements(): 649 for player in elt.elements():
498 players.append(unicode(player)) 650 players.append(unicode(player))
499 signal = self.host.bridge.tarotGameStarted if elt.name == 'started' else self.host.bridge.tarotGamePlayers 651 signal = (
652 self.host.bridge.tarotGameStarted
653 if elt.name == "started"
654 else self.host.bridge.tarotGamePlayers
655 )
500 signal(room_jid.userhost(), from_jid.full(), players, profile) 656 signal(room_jid.userhost(), from_jid.full(), players, profile)
501 657
502 elif elt.name == 'player_ready': # ready to play 658 elif elt.name == "player_ready": # ready to play
503 player = elt['player'] 659 player = elt["player"]
504 status = self.games[room_jid]['status'] 660 status = self.games[room_jid]["status"]
505 nb_players = len(self.games[room_jid]['players']) 661 nb_players = len(self.games[room_jid]["players"])
506 status[player] = 'ready' 662 status[player] = "ready"
507 log.debug(_(u'Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status}) 663 log.debug(
508 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game 664 _(u"Player %(player)s is ready to start [status: %(status)s]")
665 % {"player": player, "status": status}
666 )
667 if (
668 status.values().count("ready") == nb_players
669 ): # everybody is ready, we can start the game
509 self.newRound(room_jid, profile) 670 self.newRound(room_jid, profile)
510 671
511 elif elt.name == 'hand': # a new hand has been received 672 elif elt.name == "hand": # a new hand has been received
512 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) 673 self.host.bridge.tarotGameNew(
513 674 room_jid.userhost(), self.__xml_to_list(elt), profile
514 elif elt.name == 'contrat': # it's time to choose contrat 675 )
676
677 elif elt.name == "contrat": # it's time to choose contrat
515 form = data_form.Form.fromElement(elt.firstChildElement()) 678 form = data_form.Form.fromElement(elt.firstChildElement())
516 session_id, session_data = self._sessions.newSession(profile=profile) 679 session_id, session_data = self._sessions.newSession(profile=profile)
517 session_data["room_jid"] = room_jid 680 session_data["room_jid"] = room_jid
518 xml_data = xml_tools.dataForm2XMLUI(form, self.__choose_contrat_id, session_id).toXml() 681 xml_data = xml_tools.dataForm2XMLUI(
519 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) 682 form, self.__choose_contrat_id, session_id
520 683 ).toXml()
521 elif elt.name == 'contrat_choosed': 684 self.host.bridge.tarotGameChooseContrat(
685 room_jid.userhost(), xml_data, profile
686 )
687
688 elif elt.name == "contrat_choosed":
522 # TODO: check we receive the contrat from the right person 689 # TODO: check we receive the contrat from the right person
523 # TODO: use proper XEP-0004 way for answering form 690 # TODO: use proper XEP-0004 way for answering form
524 player = elt['player'] 691 player = elt["player"]
525 players_data[player]['contrat'] = unicode(elt) 692 players_data[player]["contrat"] = unicode(elt)
526 contrats = [players_data[p]['contrat'] for p in game_data['players']] 693 contrats = [players_data[p]["contrat"] for p in game_data["players"]]
527 if contrats.count(None): 694 if contrats.count(None):
528 # not everybody has choosed his contrat, it's next one turn 695 # not everybody has choosed his contrat, it's next one turn
529 player = self.__next_player(game_data) 696 player = self.__next_player(game_data)
530 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: 697 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
531 self.send(to_jid, self.__ask_contrat(), profile=profile) 698 self.send(to_jid, self.__ask_contrat(), profile=profile)
532 else: 699 else:
533 best_contrat = [None, "Passe"] 700 best_contrat = [None, "Passe"]
534 for player in game_data['players']: 701 for player in game_data["players"]:
535 contrat = players_data[player]['contrat'] 702 contrat = players_data[player]["contrat"]
536 idx_best = self.contrats.index(best_contrat[1]) 703 idx_best = self.contrats.index(best_contrat[1])
537 idx_pl = self.contrats.index(contrat) 704 idx_pl = self.contrats.index(contrat)
538 if idx_pl > idx_best: 705 if idx_pl > idx_best:
539 best_contrat[0] = player 706 best_contrat[0] = player
540 best_contrat[1] = contrat 707 best_contrat[1] = contrat
541 if best_contrat[1] == "Passe": 708 if best_contrat[1] == "Passe":
542 log.debug(_("Everybody is passing, round ended")) 709 log.debug(_("Everybody is passing, round ended"))
543 to_jid = jid.JID(room_jid.userhost()) 710 to_jid = jid.JID(room_jid.userhost())
544 self.send(to_jid, self.__give_scores(*self.__draw_game(game_data)), profile=profile) 711 self.send(
545 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer 712 to_jid,
546 for player in game_data['players']: 713 self.__give_scores(*self.__draw_game(game_data)),
547 game_data['status'][player] = "init" 714 profile=profile,
715 )
716 game_data["init_player"] = (game_data["init_player"] + 1) % len(
717 game_data["players"]
718 ) # we change the dealer
719 for player in game_data["players"]:
720 game_data["status"][player] = "init"
548 return 721 return
549 log.debug(_(u"%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]}) 722 log.debug(
550 game_data['contrat'] = best_contrat[1] 723 _(u"%(player)s win the bid with %(contrat)s")
551 724 % {"player": best_contrat[0], "contrat": best_contrat[1]}
552 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": 725 )
726 game_data["contrat"] = best_contrat[1]
727
728 if (
729 game_data["contrat"] == "Garde Sans"
730 or game_data["contrat"] == "Garde Contre"
731 ):
553 self.__start_play(room_jid, game_data, profile) 732 self.__start_play(room_jid, game_data, profile)
554 game_data['attaquant'] = best_contrat[0] 733 game_data["attaquant"] = best_contrat[0]
555 else: 734 else:
556 # Time to show the chien to everybody 735 # Time to show the chien to everybody
557 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof: 736 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
558 elem = self.__card_list_to_xml(game_data['chien'], 'chien') 737 elem = self.__card_list_to_xml(game_data["chien"], "chien")
559 self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile) 738 self.send(
739 to_jid, elem, {"attaquant": best_contrat[0]}, profile=profile
740 )
560 # the attacker (attaquant) get the chien 741 # the attacker (attaquant) get the chien
561 game_data['hand'][best_contrat[0]].extend(game_data['chien']) 742 game_data["hand"][best_contrat[0]].extend(game_data["chien"])
562 del game_data['chien'][:] 743 del game_data["chien"][:]
563 744
564 if game_data['contrat'] == "Garde Sans": 745 if game_data["contrat"] == "Garde Sans":
565 # The chien go into attaquant's (attacker) levees 746 # The chien go into attaquant's (attacker) levees
566 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) 747 players_data[best_contrat[0]]["levees"].extend(game_data["chien"])
567 del game_data['chien'][:] 748 del game_data["chien"][:]
568 749
569 elif elt.name == 'chien': # we have received the chien 750 elif elt.name == "chien": # we have received the chien
570 log.debug(_("tarot: chien received")) 751 log.debug(_("tarot: chien received"))
571 data = {"attaquant": elt['attaquant']} 752 data = {"attaquant": elt["attaquant"]}
572 game_data['stage'] = "ecart" 753 game_data["stage"] = "ecart"
573 game_data['attaquant'] = elt['attaquant'] 754 game_data["attaquant"] = elt["attaquant"]
574 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) 755 self.host.bridge.tarotGameShowCards(
575 756 room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile
576 elif elt.name == 'cards_played': 757 )
577 if game_data['stage'] == "ecart": 758
759 elif elt.name == "cards_played":
760 if game_data["stage"] == "ecart":
578 # TODO: show atouts (trumps) if player put some in écart 761 # TODO: show atouts (trumps) if player put some in écart
579 assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here 762 assert (
763 game_data["attaquant"] == elt["player"]
764 ) # TODO: throw an xml error here
580 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 765 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
581 # we now check validity of card 766 # we now check validity of card
582 invalid_cards = self.__invalid_cards(game_data, list_cards) 767 invalid_cards = self.__invalid_cards(game_data, list_cards)
583 if invalid_cards: 768 if invalid_cards:
584 elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']) 769 elem = self.__invalid_cards_elt(
585 self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile) 770 list_cards, invalid_cards, game_data["stage"]
771 )
772 self.send(
773 jid.JID(room_jid.userhost() + "/" + elt["player"]),
774 elem,
775 profile=profile,
776 )
586 return 777 return
587 778
588 # FIXME: gof: manage Garde Sans & Garde Contre cases 779 # 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 780 players_data[elt["player"]]["levees"].extend(
781 list_cards
782 ) # we add the chien to attaquant's levées
590 for card in list_cards: 783 for card in list_cards:
591 game_data['hand'][elt['player']].remove(card) 784 game_data["hand"][elt["player"]].remove(card)
592 785
593 self.__start_play(room_jid, game_data, profile) 786 self.__start_play(room_jid, game_data, profile)
594 787
595 elif game_data['stage'] == "play": 788 elif game_data["stage"] == "play":
596 current_player = game_data['players'][game_data['current_player']] 789 current_player = game_data["players"][game_data["current_player"]]
597 cards = TarotCard.from_tuples(self.__xml_to_list(elt)) 790 cards = TarotCard.from_tuples(self.__xml_to_list(elt))
598 791
599 if mess_elt['type'] == 'groupchat': 792 if mess_elt["type"] == "groupchat":
600 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) 793 self.host.bridge.tarotGameCardsPlayed(
794 room_jid.userhost(),
795 elt["player"],
796 self.__xml_to_list(elt),
797 profile,
798 )
601 else: 799 else:
602 # we first check validity of card 800 # we first check validity of card
603 invalid_cards = self.__invalid_cards(game_data, cards) 801 invalid_cards = self.__invalid_cards(game_data, cards)
604 if invalid_cards: 802 if invalid_cards:
605 elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage']) 803 elem = self.__invalid_cards_elt(
606 self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile) 804 cards, invalid_cards, game_data["stage"]
805 )
806 self.send(
807 jid.JID(room_jid.userhost() + "/" + current_player),
808 elem,
809 profile=profile,
810 )
607 return 811 return
608 # the card played is ok, we forward it to everybody 812 # the card played is ok, we forward it to everybody
609 # first we remove it from the hand and put in on the table 813 # first we remove it from the hand and put in on the table
610 game_data['hand'][current_player].remove(cards[0]) 814 game_data["hand"][current_player].remove(cards[0])
611 players_data[current_player]['played'] = cards[0] 815 players_data[current_player]["played"] = cards[0]
612 816
613 # then we forward the message 817 # then we forward the message
614 self.send(room_jid, elt, profile=profile) 818 self.send(room_jid, elt, profile=profile)
615 819
616 # Did everybody played ? 820 # Did everybody played ?
617 played = [players_data[player]['played'] for player in game_data['players']] 821 played = [
822 players_data[player]["played"]
823 for player in game_data["players"]
824 ]
618 if all(played): 825 if all(played):
619 # everybody has played 826 # everybody has played
620 winner = self.__winner(game_data) 827 winner = self.__winner(game_data)
621 log.debug(_(u'The winner of this trick is %s') % winner) 828 log.debug(_(u"The winner of this trick is %s") % winner)
622 # the winner win the trick 829 # the winner win the trick
623 self.__excuse_hack(game_data, played, winner) 830 self.__excuse_hack(game_data, played, winner)
624 players_data[elt['player']]['levees'].extend(played) 831 players_data[elt["player"]]["levees"].extend(played)
625 # nothing left on the table 832 # nothing left on the table
626 for player in game_data['players']: 833 for player in game_data["players"]:
627 players_data[player]['played'] = None 834 players_data[player]["played"] = None
628 if len(game_data['hand'][current_player]) == 0: 835 if len(game_data["hand"][current_player]) == 0:
629 # no card left: the game is finished 836 # no card left: the game is finished
630 elem = self.__give_scores(*self.__calculate_scores(game_data)) 837 elem = self.__give_scores(
838 *self.__calculate_scores(game_data)
839 )
631 self.send(room_jid, elem, profile=profile) 840 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 841 game_data["init_player"] = (
633 for player in game_data['players']: 842 game_data["init_player"] + 1
634 game_data['status'][player] = "init" 843 ) % len(
844 game_data["players"]
845 ) # we change the dealer
846 for player in game_data["players"]:
847 game_data["status"][player] = "init"
635 return 848 return
636 # next player is the winner 849 # next player is the winner
637 next_player = game_data['first_player'] = self.__next_player(game_data, winner) 850 next_player = game_data["first_player"] = self.__next_player(
851 game_data, winner
852 )
638 else: 853 else:
639 next_player = self.__next_player(game_data) 854 next_player = self.__next_player(game_data)
640 855
641 # finally, we tell to the next player to play 856 # finally, we tell to the next player to play
642 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) 857 to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
643 self.send(to_jid, 'your_turn', profile=profile) 858 self.send(to_jid, "your_turn", profile=profile)
644 859
645 elif elt.name == 'your_turn': 860 elif elt.name == "your_turn":
646 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) 861 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
647 862
648 elif elt.name == 'score': 863 elif elt.name == "score":
649 form_elt = elt.elements(name='x', uri='jabber:x:data').next() 864 form_elt = elt.elements(name="x", uri="jabber:x:data").next()
650 winners = [] 865 winners = []
651 loosers = [] 866 loosers = []
652 for winner in elt.elements(name='winner', uri=NS_CG): 867 for winner in elt.elements(name="winner", uri=NS_CG):
653 winners.append(unicode(winner)) 868 winners.append(unicode(winner))
654 for looser in elt.elements(name='looser', uri=NS_CG): 869 for looser in elt.elements(name="looser", uri=NS_CG):
655 loosers.append(unicode(looser)) 870 loosers.append(unicode(looser))
656 form = data_form.Form.fromElement(form_elt) 871 form = data_form.Form.fromElement(form_elt)
657 session_id, session_data = self._sessions.newSession(profile=profile) 872 session_id, session_data = self._sessions.newSession(profile=profile)
658 session_data["room_jid"] = room_jid 873 session_data["room_jid"] = room_jid
659 xml_data = xml_tools.dataForm2XMLUI(form, self.__score_id, session_id).toXml() 874 xml_data = xml_tools.dataForm2XMLUI(
660 self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile) 875 form, self.__score_id, session_id
661 elif elt.name == 'error': 876 ).toXml()
662 if elt['type'] == 'invalid_cards': 877 self.host.bridge.tarotGameScore(
663 played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next()) 878 room_jid.userhost(), xml_data, winners, loosers, profile
664 invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next()) 879 )
665 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile) 880 elif elt.name == "error":
881 if elt["type"] == "invalid_cards":
882 played_cards = self.__xml_to_list(
883 elt.elements(name="played", uri=NS_CG).next()
884 )
885 invalid_cards = self.__xml_to_list(
886 elt.elements(name="invalid", uri=NS_CG).next()
887 )
888 self.host.bridge.tarotGameInvalidCards(
889 room_jid.userhost(),
890 elt["phase"],
891 played_cards,
892 invalid_cards,
893 profile,
894 )
666 else: 895 else:
667 log.error(_(u'Unmanaged error type: %s') % elt['type']) 896 log.error(_(u"Unmanaged error type: %s") % elt["type"])
668 else: 897 else:
669 log.error(_(u'Unmanaged card game element: %s') % elt.name) 898 log.error(_(u"Unmanaged card game element: %s") % elt.name)
670 899
671 def getSyncDataForPlayer(self, room_jid, nick): 900 def getSyncDataForPlayer(self, room_jid, nick):
672 return [] 901 return []