Mercurial > libervia-backend
comparison sat/plugins/plugin_misc_tarot.py @ 2562:26edcf3a30eb
core, setup: huge cleaning:
- moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention
- move twisted directory to root
- removed all hacks from setup.py, and added missing dependencies, it is now clean
- use https URL for website in setup.py
- removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed
- renamed sat.sh to sat and fixed its installation
- added python_requires to specify Python version needed
- replaced glib2reactor which use deprecated code by gtk3reactor
sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
author | Goffi <goffi@goffi.org> |
---|---|
date | Mon, 02 Apr 2018 19:44:50 +0200 |
parents | src/plugins/plugin_misc_tarot.py@0046283a285d |
children | 56f94936df1e |
comparison
equal
deleted
inserted
replaced
2561:bd30dc3ffe5a | 2562:26edcf3a30eb |
---|---|
1 #!/usr/bin/env python2 | |
2 # -*- coding: utf-8 -*- | |
3 | |
4 # SAT plugin for managing French Tarot game | |
5 # Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org) | |
6 | |
7 # This program is free software: you can redistribute it and/or modify | |
8 # it under the terms of the GNU Affero General Public License as published by | |
9 # the Free Software Foundation, either version 3 of the License, or | |
10 # (at your option) any later version. | |
11 | |
12 # This program is distributed in the hope that it will be useful, | |
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 # GNU Affero General Public License for more details. | |
16 | |
17 # You should have received a copy of the GNU Affero General Public License | |
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | |
20 from sat.core.i18n import _ | |
21 from sat.core.constants import Const as C | |
22 from sat.core.log import getLogger | |
23 log = getLogger(__name__) | |
24 from twisted.words.xish import domish | |
25 from twisted.words.protocols.jabber import jid | |
26 from twisted.internet import defer | |
27 from wokkel import data_form | |
28 | |
29 from sat.memory import memory | |
30 from sat.tools import xml_tools | |
31 from sat_frontends.tools.games import TarotCard | |
32 import random | |
33 | |
34 | |
35 NS_CG = 'http://www.goffi.org/protocol/card_game' | |
36 CG_TAG = 'card_game' | |
37 | |
38 PLUGIN_INFO = { | |
39 C.PI_NAME: "Tarot cards plugin", | |
40 C.PI_IMPORT_NAME: "Tarot", | |
41 C.PI_TYPE: "Misc", | |
42 C.PI_PROTOCOLS: [], | |
43 C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249", "ROOM-GAME"], | |
44 C.PI_MAIN: "Tarot", | |
45 C.PI_HANDLER: "yes", | |
46 C.PI_DESCRIPTION: _("""Implementation of Tarot card game""") | |
47 } | |
48 | |
49 | |
50 class Tarot(object): | |
51 | |
52 def inheritFromRoomGame(self, host): | |
53 global RoomGame | |
54 RoomGame = host.plugins["ROOM-GAME"].__class__ | |
55 self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {}) | |
56 | |
57 def __init__(self, host): | |
58 log.info(_("Plugin Tarot initialization")) | |
59 self._sessions = memory.Sessions() | |
60 self.inheritFromRoomGame(host) | |
61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG), | |
62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}, | |
63 player_init={'score': 0}) | |
64 self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')] | |
65 host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True) # args: players, room_jid, profile | |
66 host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile | |
67 host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile | |
68 host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile | |
69 host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, profile | |
70 host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile | |
71 host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') # args: room_jid, hand, profile | |
72 host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') # args: room_jid, xml_data, profile | |
73 host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') # args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile | |
74 host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') # args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile | |
75 host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') # args: room_jid, profile | |
76 host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile | |
77 host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') # args: room_jid, game phase, played_cards, invalid_cards, profile | |
78 self.deck_ordered = [] | |
79 for value in ['excuse'] + map(str, range(1, 22)): | |
80 self.deck_ordered.append(TarotCard(("atout", value))) | |
81 for suit in ["pique", "coeur", "carreau", "trefle"]: | |
82 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]: | |
83 self.deck_ordered.append(TarotCard((suit, value))) | |
84 self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True) | |
85 self.__score_id = host.registerCallback(self._scoreShowed, with_data=True) | |
86 | |
87 def __card_list_to_xml(self, cards_list, elt_name): | |
88 """Convert a card list to domish element""" | |
89 cards_list_elt = domish.Element((None, elt_name)) | |
90 for card in cards_list: | |
91 card_elt = domish.Element((None, 'card')) | |
92 card_elt['suit'] = card.suit | |
93 card_elt['value'] = card.value | |
94 cards_list_elt.addChild(card_elt) | |
95 return cards_list_elt | |
96 | |
97 def __xml_to_list(self, cards_list_elt): | |
98 """Convert a domish element with cards to a list of tuples""" | |
99 cards_list = [] | |
100 for card in cards_list_elt.elements(): | |
101 cards_list.append((card['suit'], card['value'])) | |
102 return cards_list | |
103 | |
104 def __ask_contrat(self): | |
105 """Create a element for asking contrat""" | |
106 contrat_elt = domish.Element((None, 'contrat')) | |
107 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) | |
109 form.addField(field) | |
110 contrat_elt.addChild(form.toElement()) | |
111 return contrat_elt | |
112 | |
113 def __give_scores(self, scores, winners, loosers): | |
114 """Create an element to give scores | |
115 @param scores: unicode (can contain line feed) | |
116 @param winners: list of unicode nicks of winners | |
117 @param loosers: list of unicode nicks of loosers""" | |
118 | |
119 score_elt = domish.Element((None, 'score')) | |
120 form = data_form.Form('form', title=_('scores')) | |
121 for line in scores.split('\n'): | |
122 field = data_form.Field('fixed', value=line) | |
123 form.addField(field) | |
124 score_elt.addChild(form.toElement()) | |
125 for winner in winners: | |
126 winner_elt = domish.Element((None, 'winner')) | |
127 winner_elt.addContent(winner) | |
128 score_elt.addChild(winner_elt) | |
129 for looser in loosers: | |
130 looser_elt = domish.Element((None, 'looser')) | |
131 looser_elt.addContent(looser) | |
132 score_elt.addChild(looser_elt) | |
133 return score_elt | |
134 | |
135 def __invalid_cards_elt(self, played_cards, invalid_cards, game_phase): | |
136 """Create a element for invalid_cards error | |
137 @param list_cards: list of Card | |
138 @param game_phase: phase of the game ['ecart', 'play']""" | |
139 error_elt = domish.Element((None, 'error')) | |
140 played_elt = self.__card_list_to_xml(played_cards, 'played') | |
141 invalid_elt = self.__card_list_to_xml(invalid_cards, 'invalid') | |
142 error_elt['type'] = 'invalid_cards' | |
143 error_elt['phase'] = game_phase | |
144 error_elt.addChild(played_elt) | |
145 error_elt.addChild(invalid_elt) | |
146 return error_elt | |
147 | |
148 def __next_player(self, game_data, next_pl=None): | |
149 """Increment player number & return player name | |
150 @param next_pl: if given, then next_player is forced to this one | |
151 """ | |
152 if next_pl: | |
153 game_data['current_player'] = game_data['players'].index(next_pl) | |
154 return next_pl | |
155 else: | |
156 pl_idx = game_data['current_player'] = (game_data['current_player'] + 1) % len(game_data['players']) | |
157 return game_data['players'][pl_idx] | |
158 | |
159 def __winner(self, game_data): | |
160 """give the nick of the player who win this trick""" | |
161 players_data = game_data['players_data'] | |
162 first = game_data['first_player'] | |
163 first_idx = game_data['players'].index(first) | |
164 suit_asked = None | |
165 strongest = None | |
166 winner = None | |
167 for idx in [(first_idx + i) % 4 for i in range(4)]: | |
168 player = game_data['players'][idx] | |
169 card = players_data[player]['played'] | |
170 if card.value == "excuse": | |
171 continue | |
172 if suit_asked is None: | |
173 suit_asked = card.suit | |
174 if (card.suit == suit_asked or card.suit == "atout") and card > strongest: | |
175 strongest = card | |
176 winner = player | |
177 assert winner | |
178 return winner | |
179 | |
180 def __excuse_hack(self, game_data, played, winner): | |
181 """give a low card to other team and keep excuse if trick is lost | |
182 @param game_data: data of the game | |
183 @param played: cards currently on the table | |
184 @param winner: nick of the trick winner""" | |
185 # TODO: manage the case where excuse is played on the last trick (and lost) | |
186 players_data = game_data['players_data'] | |
187 excuse = TarotCard(("atout", "excuse")) | |
188 | |
189 # we first check if the Excuse was already played | |
190 # and if somebody is waiting for a card | |
191 for player in game_data['players']: | |
192 if players_data[player]['wait_for_low']: | |
193 # the excuse owner has to give a card to somebody | |
194 if winner == player: | |
195 # the excuse owner win the trick, we check if we have something to give | |
196 for card in played: | |
197 if card.points == 0.5: | |
198 pl_waiting = players_data[player]['wait_for_low'] | |
199 played.remove(card) | |
200 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}) | |
202 return | |
203 return | |
204 | |
205 if excuse not in played: | |
206 # the Excuse is not on the table, nothing to do | |
207 return | |
208 | |
209 excuse_player = None # Who has played the Excuse ? | |
210 for player in game_data['players']: | |
211 if players_data[player]['played'] == excuse: | |
212 excuse_player = player | |
213 break | |
214 | |
215 if excuse_player == winner: | |
216 return # the excuse player win the trick, nothing to do | |
217 | |
218 # first we remove the excuse from played cards | |
219 played.remove(excuse) | |
220 # then we give it back to the original owner | |
221 owner_levees = players_data[excuse_player]['levees'] | |
222 owner_levees.append(excuse) | |
223 # finally we give a low card to the trick winner | |
224 low_card = None | |
225 # We look backward in cards won by the Excuse owner to | |
226 # find a low value card | |
227 for card_idx in range(len(owner_levees) - 1, -1, -1): | |
228 if owner_levees[card_idx].points == 0.5: | |
229 low_card = owner_levees[card_idx] | |
230 del owner_levees[card_idx] | |
231 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}) | |
233 break | |
234 if not low_card: # The player has no low card yet | |
235 # TODO: manage case when player never win a trick with low card | |
236 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}) | |
238 | |
239 def __draw_game(self, game_data): | |
240 """The game is draw, no score change | |
241 @param game_data: data of the game | |
242 @return: tuple with (string victory message, list of winners, list of loosers)""" | |
243 players_data = game_data['players_data'] | |
244 scores_str = _('Draw game') | |
245 scores_str += '\n' | |
246 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']} | |
248 log.debug(scores_str) | |
249 | |
250 return (scores_str, [], []) | |
251 | |
252 def __calculate_scores(self, game_data): | |
253 """The game is finished, time to know who won :) | |
254 @param game_data: data of the game | |
255 @return: tuple with (string victory message, list of winners, list of loosers)""" | |
256 players_data = game_data['players_data'] | |
257 levees = players_data[game_data['attaquant']]['levees'] | |
258 score = 0 | |
259 nb_bouts = 0 | |
260 bouts = [] | |
261 for card in levees: | |
262 if card.bout: | |
263 nb_bouts += 1 | |
264 bouts.append(card.value) | |
265 score += card.points | |
266 | |
267 # We do a basic check on score calculation | |
268 check_score = 0 | |
269 defenseurs = game_data['players'][:] | |
270 defenseurs.remove(game_data['attaquant']) | |
271 for defenseur in defenseurs: | |
272 for card in players_data[defenseur]['levees']: | |
273 check_score += card.points | |
274 if game_data['contrat'] == "Garde Contre": | |
275 for card in game_data['chien']: | |
276 check_score += card.points | |
277 assert (score + check_score == 91) | |
278 | |
279 point_limit = None | |
280 if nb_bouts == 3: | |
281 point_limit = 36 | |
282 elif nb_bouts == 2: | |
283 point_limit = 41 | |
284 elif nb_bouts == 1: | |
285 point_limit = 51 | |
286 else: | |
287 point_limit = 56 | |
288 if game_data['contrat'] == 'Petite': | |
289 contrat_mult = 1 | |
290 elif game_data['contrat'] == 'Garde': | |
291 contrat_mult = 2 | |
292 elif game_data['contrat'] == 'Garde Sans': | |
293 contrat_mult = 4 | |
294 elif game_data['contrat'] == 'Garde Contre': | |
295 contrat_mult = 6 | |
296 else: | |
297 log.error(_('INTERNAL ERROR: contrat not managed (mispelled ?)')) | |
298 assert(False) | |
299 | |
300 victory = (score >= point_limit) | |
301 margin = abs(score - point_limit) | |
302 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1) | |
303 winners = [] | |
304 loosers = [] | |
305 player_score = {} | |
306 for player in game_data['players']: | |
307 # TODO: adjust this for 3 and 5 players variants | |
308 # TODO: manage bonuses (petit au bout, poignée, chelem) | |
309 player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3 | |
310 players_data[player]['score'] += player_score[player] # we add score of this game to the global score | |
311 if player_score[player] > 0: | |
312 winners.append(player) | |
313 else: | |
314 loosers.append(player) | |
315 | |
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'} | |
317 scores_str += '\n' | |
318 for player in game_data['players']: | |
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']} | |
320 log.debug(scores_str) | |
321 | |
322 return (scores_str, winners, loosers) | |
323 | |
324 def __invalid_cards(self, game_data, cards): | |
325 """Checks that the player has the right to play what he wants to | |
326 @param game_data: Game data | |
327 @param cards: cards the player want to play | |
328 @return forbidden_cards cards or empty list if cards are ok""" | |
329 forbidden_cards = [] | |
330 if game_data['stage'] == 'ecart': | |
331 for card in cards: | |
332 if card.bout or card.value == "roi": | |
333 forbidden_cards.append(card) | |
334 # TODO: manage case where atouts (trumps) are in the dog | |
335 elif game_data['stage'] == 'play': | |
336 biggest_atout = None | |
337 suit_asked = None | |
338 players = game_data['players'] | |
339 players_data = game_data['players_data'] | |
340 idx = players.index(game_data['first_player']) | |
341 current_idx = game_data['current_player'] | |
342 current_player = players[current_idx] | |
343 if idx == current_idx: | |
344 # the player is the first to play, he can play what he wants | |
345 return forbidden_cards | |
346 while (idx != current_idx): | |
347 player = players[idx] | |
348 played_card = players_data[player]['played'] | |
349 if not suit_asked and played_card.value != "excuse": | |
350 suit_asked = played_card.suit | |
351 if played_card.suit == "atout" and played_card > biggest_atout: | |
352 biggest_atout = played_card | |
353 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 | |
355 has_atout = False | |
356 biggest_hand_atout = None | |
357 | |
358 for hand_card in game_data['hand'][current_player]: | |
359 if hand_card.suit == suit_asked: | |
360 has_suit = True | |
361 if hand_card.suit == "atout": | |
362 has_atout = True | |
363 if hand_card.suit == "atout" and hand_card > biggest_hand_atout: | |
364 biggest_hand_atout = hand_card | |
365 | |
366 assert len(cards) == 1 | |
367 card = cards[0] | |
368 if card.suit != suit_asked and has_suit and card.value != "excuse": | |
369 forbidden_cards.append(card) | |
370 return forbidden_cards | |
371 if card.suit != suit_asked and card.suit != "atout" and has_atout: | |
372 forbidden_cards.append(card) | |
373 return forbidden_cards | |
374 if card.suit == "atout" and card < biggest_atout and biggest_hand_atout > biggest_atout and card.value != "excuse": | |
375 forbidden_cards.append(card) | |
376 else: | |
377 log.error(_('Internal error: unmanaged game stage')) | |
378 return forbidden_cards | |
379 | |
380 def __start_play(self, room_jid, game_data, profile): | |
381 """Start the game (tell to the first player after dealer to play""" | |
382 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 | |
384 game_data['first_player'] = next_player = game_data['players'][next_player_idx] | |
385 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) # FIXME: gof: | |
386 self.send(to_jid, 'your_turn', profile=profile) | |
387 | |
388 def _contratChoosed(self, raw_data, profile): | |
389 """Will be called when the contrat is selected | |
390 @param raw_data: contains the choosed session id and the chosen contrat | |
391 @param profile_key: profile | |
392 """ | |
393 try: | |
394 session_data = self._sessions.profileGet(raw_data["session_id"], profile) | |
395 except KeyError: | |
396 log.warning(_("session id doesn't exist, session has probably expired")) | |
397 # TODO: send error dialog | |
398 return defer.succeed({}) | |
399 | |
400 room_jid = session_data['room_jid'] | |
401 referee_jid = self.games[room_jid]['referee'] | |
402 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile) | |
403 data = xml_tools.XMLUIResult2DataFormResult(raw_data) | |
404 contrat = data['contrat'] | |
405 log.debug(_(u'contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile}) | |
406 d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile) | |
407 d.addCallback(lambda ignore: {}) | |
408 del self._sessions[raw_data["session_id"]] | |
409 return d | |
410 | |
411 def _scoreShowed(self, raw_data, profile): | |
412 """Will be called when the player closes the score dialog | |
413 @param raw_data: nothing to retrieve from here but the session id | |
414 @param profile_key: profile | |
415 """ | |
416 try: | |
417 session_data = self._sessions.profileGet(raw_data["session_id"], profile) | |
418 except KeyError: | |
419 log.warning(_("session id doesn't exist, session has probably expired")) | |
420 # TODO: send error dialog | |
421 return defer.succeed({}) | |
422 | |
423 room_jid_s = session_data['room_jid'].userhost() | |
424 # XXX: empty hand means to the frontend "reset the display"... | |
425 self.host.bridge.tarotGameNew(room_jid_s, [], profile) | |
426 del self._sessions[raw_data["session_id"]] | |
427 return defer.succeed({}) | |
428 | |
429 def play_cards(self, player, referee, cards, profile_key=C.PROF_KEY_NONE): | |
430 """Must be call by player when the contrat is selected | |
431 @param player: player's name | |
432 @param referee: arbiter jid | |
433 @cards: cards played (list of tuples) | |
434 @profile_key: profile | |
435 """ | |
436 profile = self.host.memory.getProfileName(profile_key) | |
437 if not profile: | |
438 log.error(_(u"profile %s is unknown") % profile_key) | |
439 return | |
440 log.debug(_(u'Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards}) | |
441 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played') | |
442 self.send(jid.JID(referee), elem, {'player': player}, profile=profile) | |
443 | |
444 def newRound(self, room_jid, profile): | |
445 game_data = self.games[room_jid] | |
446 players = game_data['players'] | |
447 game_data['first_player'] = None # first player for the current trick | |
448 game_data['contrat'] = None | |
449 common_data = {'contrat': None, | |
450 'levees': [], # cards won | |
451 'played': None, # card on the table | |
452 'wait_for_low': None # Used when a player wait for a low card because of excuse | |
453 } | |
454 | |
455 hand = game_data['hand'] = {} | |
456 hand_size = game_data['hand_size'] | |
457 chien = game_data['chien'] = [] | |
458 deck = self.deck_ordered[:] | |
459 random.shuffle(deck) | |
460 for i in range(4): | |
461 hand[players[i]] = deck[0:hand_size] | |
462 del deck[0:hand_size] | |
463 chien.extend(deck) | |
464 del(deck[:]) | |
465 msg_elts = {} | |
466 for player in players: | |
467 msg_elts[player] = self.__card_list_to_xml(hand[player], 'hand') | |
468 | |
469 RoomGame.newRound(self, room_jid, (common_data, msg_elts), profile) | |
470 | |
471 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) # the player after the dealer start | |
472 player = players[pl_idx] | |
473 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: | |
474 self.send(to_jid, self.__ask_contrat(), profile=profile) | |
475 | |
476 def room_game_cmd(self, mess_elt, profile): | |
477 """ | |
478 @param mess_elt: instance of twisted.words.xish.domish.Element | |
479 """ | |
480 client = self.host.getClient(profile) | |
481 from_jid = jid.JID(mess_elt['from']) | |
482 room_jid = jid.JID(from_jid.userhost()) | |
483 nick = self.host.plugins["XEP-0045"].getRoomNick(client, room_jid) | |
484 | |
485 game_elt = mess_elt.firstChildElement() | |
486 game_data = self.games[room_jid] | |
487 is_player = self.isPlayer(room_jid, nick) | |
488 if 'players_data' in game_data: | |
489 players_data = game_data['players_data'] | |
490 | |
491 for elt in game_elt.elements(): | |
492 if not is_player and (elt.name not in ('started', 'players')): | |
493 continue # user is in the room but not playing | |
494 | |
495 if elt.name in ('started', 'players'): # new game created and/or players list updated | |
496 players = [] | |
497 for player in elt.elements(): | |
498 players.append(unicode(player)) | |
499 signal = self.host.bridge.tarotGameStarted if elt.name == 'started' else self.host.bridge.tarotGamePlayers | |
500 signal(room_jid.userhost(), from_jid.full(), players, profile) | |
501 | |
502 elif elt.name == 'player_ready': # ready to play | |
503 player = elt['player'] | |
504 status = self.games[room_jid]['status'] | |
505 nb_players = len(self.games[room_jid]['players']) | |
506 status[player] = 'ready' | |
507 log.debug(_(u'Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status}) | |
508 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game | |
509 self.newRound(room_jid, profile) | |
510 | |
511 elif elt.name == 'hand': # a new hand has been received | |
512 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) | |
513 | |
514 elif elt.name == 'contrat': # it's time to choose contrat | |
515 form = data_form.Form.fromElement(elt.firstChildElement()) | |
516 session_id, session_data = self._sessions.newSession(profile=profile) | |
517 session_data["room_jid"] = room_jid | |
518 xml_data = xml_tools.dataForm2XMLUI(form, self.__choose_contrat_id, session_id).toXml() | |
519 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) | |
520 | |
521 elif elt.name == 'contrat_choosed': | |
522 # TODO: check we receive the contrat from the right person | |
523 # TODO: use proper XEP-0004 way for answering form | |
524 player = elt['player'] | |
525 players_data[player]['contrat'] = unicode(elt) | |
526 contrats = [players_data[p]['contrat'] for p in game_data['players']] | |
527 if contrats.count(None): | |
528 # not everybody has choosed his contrat, it's next one turn | |
529 player = self.__next_player(game_data) | |
530 to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: | |
531 self.send(to_jid, self.__ask_contrat(), profile=profile) | |
532 else: | |
533 best_contrat = [None, "Passe"] | |
534 for player in game_data['players']: | |
535 contrat = players_data[player]['contrat'] | |
536 idx_best = self.contrats.index(best_contrat[1]) | |
537 idx_pl = self.contrats.index(contrat) | |
538 if idx_pl > idx_best: | |
539 best_contrat[0] = player | |
540 best_contrat[1] = contrat | |
541 if best_contrat[1] == "Passe": | |
542 log.debug(_("Everybody is passing, round ended")) | |
543 to_jid = jid.JID(room_jid.userhost()) | |
544 self.send(to_jid, self.__give_scores(*self.__draw_game(game_data)), profile=profile) | |
545 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer | |
546 for player in game_data['players']: | |
547 game_data['status'][player] = "init" | |
548 return | |
549 log.debug(_(u"%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]}) | |
550 game_data['contrat'] = best_contrat[1] | |
551 | |
552 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": | |
553 self.__start_play(room_jid, game_data, profile) | |
554 game_data['attaquant'] = best_contrat[0] | |
555 else: | |
556 # Time to show the chien to everybody | |
557 to_jid = jid.JID(room_jid.userhost()) # FIXME: gof: | |
558 elem = self.__card_list_to_xml(game_data['chien'], 'chien') | |
559 self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile) | |
560 # the attacker (attaquant) get the chien | |
561 game_data['hand'][best_contrat[0]].extend(game_data['chien']) | |
562 del game_data['chien'][:] | |
563 | |
564 if game_data['contrat'] == "Garde Sans": | |
565 # The chien go into attaquant's (attacker) levees | |
566 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) | |
567 del game_data['chien'][:] | |
568 | |
569 elif elt.name == 'chien': # we have received the chien | |
570 log.debug(_("tarot: chien received")) | |
571 data = {"attaquant": elt['attaquant']} | |
572 game_data['stage'] = "ecart" | |
573 game_data['attaquant'] = elt['attaquant'] | |
574 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) | |
575 | |
576 elif elt.name == 'cards_played': | |
577 if game_data['stage'] == "ecart": | |
578 # TODO: show atouts (trumps) if player put some in écart | |
579 assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here | |
580 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt)) | |
581 # we now check validity of card | |
582 invalid_cards = self.__invalid_cards(game_data, list_cards) | |
583 if invalid_cards: | |
584 elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']) | |
585 self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile) | |
586 return | |
587 | |
588 # 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 | |
590 for card in list_cards: | |
591 game_data['hand'][elt['player']].remove(card) | |
592 | |
593 self.__start_play(room_jid, game_data, profile) | |
594 | |
595 elif game_data['stage'] == "play": | |
596 current_player = game_data['players'][game_data['current_player']] | |
597 cards = TarotCard.from_tuples(self.__xml_to_list(elt)) | |
598 | |
599 if mess_elt['type'] == 'groupchat': | |
600 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) | |
601 else: | |
602 # we first check validity of card | |
603 invalid_cards = self.__invalid_cards(game_data, cards) | |
604 if invalid_cards: | |
605 elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage']) | |
606 self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile) | |
607 return | |
608 # the card played is ok, we forward it to everybody | |
609 # first we remove it from the hand and put in on the table | |
610 game_data['hand'][current_player].remove(cards[0]) | |
611 players_data[current_player]['played'] = cards[0] | |
612 | |
613 # then we forward the message | |
614 self.send(room_jid, elt, profile=profile) | |
615 | |
616 # Did everybody played ? | |
617 played = [players_data[player]['played'] for player in game_data['players']] | |
618 if all(played): | |
619 # everybody has played | |
620 winner = self.__winner(game_data) | |
621 log.debug(_(u'The winner of this trick is %s') % winner) | |
622 # the winner win the trick | |
623 self.__excuse_hack(game_data, played, winner) | |
624 players_data[elt['player']]['levees'].extend(played) | |
625 # nothing left on the table | |
626 for player in game_data['players']: | |
627 players_data[player]['played'] = None | |
628 if len(game_data['hand'][current_player]) == 0: | |
629 # no card left: the game is finished | |
630 elem = self.__give_scores(*self.__calculate_scores(game_data)) | |
631 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 | |
633 for player in game_data['players']: | |
634 game_data['status'][player] = "init" | |
635 return | |
636 # next player is the winner | |
637 next_player = game_data['first_player'] = self.__next_player(game_data, winner) | |
638 else: | |
639 next_player = self.__next_player(game_data) | |
640 | |
641 # finally, we tell to the next player to play | |
642 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) | |
643 self.send(to_jid, 'your_turn', profile=profile) | |
644 | |
645 elif elt.name == 'your_turn': | |
646 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) | |
647 | |
648 elif elt.name == 'score': | |
649 form_elt = elt.elements(name='x', uri='jabber:x:data').next() | |
650 winners = [] | |
651 loosers = [] | |
652 for winner in elt.elements(name='winner', uri=NS_CG): | |
653 winners.append(unicode(winner)) | |
654 for looser in elt.elements(name='looser', uri=NS_CG): | |
655 loosers.append(unicode(looser)) | |
656 form = data_form.Form.fromElement(form_elt) | |
657 session_id, session_data = self._sessions.newSession(profile=profile) | |
658 session_data["room_jid"] = room_jid | |
659 xml_data = xml_tools.dataForm2XMLUI(form, self.__score_id, session_id).toXml() | |
660 self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile) | |
661 elif elt.name == 'error': | |
662 if elt['type'] == 'invalid_cards': | |
663 played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next()) | |
664 invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next()) | |
665 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile) | |
666 else: | |
667 log.error(_(u'Unmanaged error type: %s') % elt['type']) | |
668 else: | |
669 log.error(_(u'Unmanaged card game element: %s') % elt.name) | |
670 | |
671 def getSyncDataForPlayer(self, room_jid, nick): | |
672 return [] |