88
|
1 #!/usr/bin/python |
|
2 # -*- coding: utf-8 -*- |
|
3 |
|
4 """ |
|
5 SAT plugin for managing xep-0045 |
|
6 Copyright (C) 2009, 2010 Jérôme Poisson (goffi@goffi.org) |
|
7 |
|
8 This program is free software: you can redistribute it and/or modify |
|
9 it under the terms of the GNU General Public License as published by |
|
10 the Free Software Foundation, either version 3 of the License, or |
|
11 (at your option) any later version. |
|
12 |
|
13 This program is distributed in the hope that it will be useful, |
|
14 but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
16 GNU General Public License for more details. |
|
17 |
|
18 You should have received a copy of the GNU General Public License |
|
19 along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
20 """ |
|
21 |
|
22 from logging import debug, info, warning, error |
|
23 from twisted.words.xish import domish |
|
24 from twisted.internet import protocol, defer, threads, reactor |
|
25 from twisted.words.protocols.jabber import client, jid, xmlstream |
|
26 from twisted.words.protocols.jabber import error as jab_error |
|
27 from twisted.words.protocols.jabber.xmlstream import IQ |
|
28 import os.path |
|
29 import pdb |
|
30 import random |
|
31 |
|
32 from zope.interface import implements |
|
33 |
91
|
34 from wokkel import disco, iwokkel, data_form |
|
35 from tools.xml_tools import XMLTools |
88
|
36 |
|
37 from base64 import b64decode |
|
38 from hashlib import sha1 |
|
39 from time import sleep |
|
40 |
|
41 try: |
|
42 from twisted.words.protocols.xmlstream import XMPPHandler |
|
43 except ImportError: |
|
44 from wokkel.subprotocols import XMPPHandler |
|
45 |
90
|
46 MESSAGE = '/message' |
|
47 NS_CG = 'http://www.goffi.org/protocol/card_game' |
|
48 CG_TAG = 'card_game' |
|
49 CG_REQUEST = MESSAGE + '/' + CG_TAG + '[@xmlns="' + NS_CG + '"]' |
88
|
50 |
|
51 PLUGIN_INFO = { |
|
52 "name": "Tarot cards plugin", |
|
53 "import_name": "Tarot", |
|
54 "type": "Misc", |
|
55 "protocols": [], |
|
56 "dependencies": ["XEP_0045"], |
|
57 "main": "Tarot", |
90
|
58 "handler": "yes", |
88
|
59 "description": _("""Implementation of Tarot card game""") |
|
60 } |
|
61 |
|
62 class Tarot(): |
|
63 |
|
64 def __init__(self, host): |
|
65 info(_("Plugin Tarot initialization")) |
|
66 self.host = host |
|
67 self.games={} |
91
|
68 self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')] |
90
|
69 host.bridge.addMethod("tarotGameCreate", ".communication", in_sign='sass', out_sign='', method=self.createGame) #args: room_jid, players, profile |
92
|
70 host.bridge.addMethod("tarotGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: player, referee, profile |
|
71 host.bridge.addMethod("tarotGameContratChoosed", ".communication", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: player, referee, contrat, profile |
|
72 host.bridge.addMethod("tarotGamePlayCards", ".communication", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) #args: player, referee, cards, profile |
90
|
73 host.bridge.addSignal("tarotGameStarted", ".communication", signature='ssass') #args: room_jid, referee, players, profile |
|
74 host.bridge.addSignal("tarotGameNew", ".communication", signature='sa(ss)s') #args: room_jid, hand, profile |
92
|
75 host.bridge.addSignal("tarotGameChooseContrat", ".communication", signature='sss') #args: room_jid, xml_data, profile |
|
76 host.bridge.addSignal("tarotGameShowCards", ".communication", signature='ssa(ss)a{ss}s') #args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile |
|
77 host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile |
88
|
78 self.deck_ordered = [] |
92
|
79 for value in ['excuse']+map(str,range(1,22)): |
88
|
80 self.deck_ordered.append(("atout",value)) |
92
|
81 for suit in ["pique", "coeur", "carreau", "trefle"]: |
88
|
82 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]: |
92
|
83 self.deck_ordered.append((suit, value)) |
88
|
84 |
92
|
85 def createGameElt(self, to_jid, type="normal"): |
|
86 type = "normal" if to_jid.resource else "groupchat" |
90
|
87 elt = domish.Element(('jabber:client','message')) |
|
88 elt["to"] = to_jid.full() |
92
|
89 elt["type"] = type |
90
|
90 elt.addElement((NS_CG, CG_TAG)) |
|
91 return elt |
|
92 |
92
|
93 def __list_to_xml(self, cards_list, elt_name): |
|
94 """Convert a card list (list of tuples) to domish element""" |
|
95 cards_list_elt = domish.Element(('',elt_name)) |
|
96 for suit, value in cards_list: |
90
|
97 card_elt = domish.Element(('','card')) |
92
|
98 card_elt['suit'] = suit |
90
|
99 card_elt['value'] = value |
92
|
100 cards_list_elt.addChild(card_elt) |
|
101 return cards_list_elt |
90
|
102 |
92
|
103 def __xml_to_list(self, cards_list_elt): |
|
104 """Convert a domish element with cards to a list of tuples""" |
|
105 cards_list = [] |
|
106 for card in cards_list_elt.elements(): |
|
107 cards_list.append((card['suit'], card['value'])) |
|
108 return cards_list |
90
|
109 |
|
110 def __create_started_elt(self, players): |
|
111 """Create a game_started domish element""" |
|
112 started_elt = domish.Element(('','started')) |
|
113 idx = 0 |
|
114 for player in players: |
|
115 player_elt = domish.Element(('','player')) |
|
116 player_elt.addContent(player) |
|
117 player_elt['index'] = str(idx) |
|
118 idx+=1 |
|
119 started_elt.addChild(player_elt) |
|
120 return started_elt |
|
121 |
91
|
122 def __ask_contrat(self): |
|
123 """Create a element for asking contrat""" |
|
124 contrat_elt = domish.Element(('','contrat')) |
|
125 form = data_form.Form('form', title=_('contrat selection')) |
|
126 field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True) |
|
127 form.addField(field) |
|
128 contrat_elt.addChild(form.toElement()) |
|
129 return contrat_elt |
|
130 |
|
131 def __next_player(self, game_data): |
|
132 """It's next player turn |
|
133 Increment player number & return player name""" |
|
134 pl_idx = game_data['current_player'] = (game_data['current_player'] + 1) % len(game_data['players']) |
|
135 return game_data['players'][pl_idx] |
|
136 |
90
|
137 def createGame(self, room_jid_param, players, profile_key='@DEFAULT@'): |
88
|
138 """Create a new game""" |
|
139 debug (_("Creating Tarot game")) |
90
|
140 room_jid = jid.JID(room_jid_param) |
88
|
141 profile = self.host.memory.getProfileName(profile_key) |
|
142 if not profile: |
|
143 error (_("profile %s is unknown") % profile_key) |
|
144 return |
|
145 if False: #gof: self.games.has_key(room_jid): |
90
|
146 warning (_("Tarot game already started in room %s") % room_jid.userhost()) |
88
|
147 else: |
90
|
148 status = {} |
91
|
149 players_data = {} |
90
|
150 for player in players: |
91
|
151 players_data[player] = {} |
90
|
152 status[player] = "init" |
92
|
153 self.games[room_jid.userhost()] = {'players':players, 'status':status, 'players_data':players_data, 'hand_size':18, 'init_player':0, 'current_player': None, 'stage': None} |
90
|
154 for player in players: |
|
155 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player)) |
|
156 mess.firstChildElement().addChild(self.__create_started_elt(players)) |
|
157 self.host.profiles[profile].xmlstream.send(mess) |
|
158 |
92
|
159 def newPlayerReady(self, player, referee, profile_key='@DEFAULT@'): |
90
|
160 """Must be called when player is ready to start a new game""" |
|
161 profile = self.host.memory.getProfileName(profile_key) |
|
162 if not profile: |
|
163 error (_("profile %s is unknown") % profile_key) |
|
164 return |
|
165 debug ('new player ready: %s' % profile) |
|
166 mess = self.createGameElt(jid.JID(referee)) |
91
|
167 ready_elt = mess.firstChildElement().addElement('player_ready') |
92
|
168 ready_elt['player'] = player |
91
|
169 self.host.profiles[profile].xmlstream.send(mess) |
|
170 |
92
|
171 def contratChoosed(self, player, referee, contrat, profile_key='@DEFAULT@'): |
91
|
172 """Must be call by player when the contrat is selected |
92
|
173 @param player: player's name |
91
|
174 @param referee: arbiter jid |
|
175 @contrat: contrat choosed (must be the exact same string than in the give list options) |
|
176 @profile_key: profile |
|
177 """ |
|
178 profile = self.host.memory.getProfileName(profile_key) |
|
179 if not profile: |
|
180 error (_("profile %s is unknown") % profile_key) |
|
181 return |
|
182 debug (_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat':contrat, 'profile':profile}) |
|
183 mess = self.createGameElt(jid.JID(referee)) |
|
184 contrat_elt = mess.firstChildElement().addElement(('','contrat_choosed'), content=contrat) |
92
|
185 contrat_elt['player'] = player |
90
|
186 self.host.profiles[profile].xmlstream.send(mess) |
88
|
187 |
92
|
188 def play_cards(self, player, referee, cards, profile_key='@DEFAULT@'): |
|
189 """Must be call by player when the contrat is selected |
|
190 @param player: player's name |
|
191 @param referee: arbiter jid |
|
192 @cards: cards played (list of tuples) |
|
193 @profile_key: profile |
|
194 """ |
|
195 profile = self.host.memory.getProfileName(profile_key) |
|
196 if not profile: |
|
197 error (_("profile %s is unknown") % profile_key) |
|
198 return |
|
199 debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards}) |
|
200 mess = self.createGameElt(jid.JID(referee)) |
|
201 playcard_elt = mess.firstChildElement().addChild(self.__list_to_xml(cards, 'cards_played')) |
|
202 playcard_elt['player'] = player |
|
203 self.host.profiles[profile].xmlstream.send(mess) |
88
|
204 |
92
|
205 def newGame(self, room_jid, profile): |
88
|
206 """Launch a new round""" |
|
207 debug (_('new Tarot game')) |
|
208 deck = self.deck_ordered[:] |
|
209 random.shuffle(deck) |
91
|
210 game_data = self.games[room_jid.userhost()] |
|
211 players = game_data['players'] |
|
212 players_data = game_data['players_data'] |
|
213 current_player = game_data['current_player'] |
92
|
214 game_data['stage'] = "init" |
91
|
215 hand = game_data['hand'] = {} |
|
216 hand_size = game_data['hand_size'] |
|
217 chien = game_data['chien'] = [] |
88
|
218 for i in range(4): #TODO: distribute according to real Tarot rules (3 by 3 counter-clockwise, 1 card at once to chien) |
|
219 hand[players[i]] = deck[0:hand_size] |
|
220 del deck[0:hand_size] |
92
|
221 chien.extend(deck) |
88
|
222 del(deck[:]) |
|
223 |
|
224 for player in players: |
90
|
225 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
226 mess = self.createGameElt(to_jid) |
92
|
227 mess.firstChildElement().addChild(self.__list_to_xml(hand[player], 'hand')) |
|
228 self.host.profiles[profile].xmlstream.send(mess) |
91
|
229 players_data[player]['contrat'] = None |
92
|
230 players_data[player]['levees'] = [] #cards won |
91
|
231 |
|
232 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) #the player after the dealer start |
|
233 player = players[pl_idx] |
|
234 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
235 mess = self.createGameElt(to_jid) |
|
236 mess.firstChildElement().addChild(self.__ask_contrat()) |
92
|
237 self.host.profiles[profile].xmlstream.send(mess) |
90
|
238 |
|
239 |
|
240 def card_game_cmd(self, mess_elt, profile): |
|
241 print "\n\nCARD GAME command received (profile=%s): %s" % (profile, mess_elt.toXml()) |
|
242 room_jid = jid.JID(mess_elt['from']) |
|
243 game_elt = mess_elt.firstChildElement() |
92
|
244 game_data = self.games[room_jid.userhost()] |
|
245 players_data = game_data['players_data'] |
|
246 |
|
247 for elt in game_elt.elements(): |
91
|
248 |
92
|
249 if elt.name == 'started': #new game created |
90
|
250 players = [] |
|
251 for player in elt.elements(): |
|
252 players.append(unicode(player)) |
|
253 self.host.bridge.tarotGameStarted(room_jid.userhost(), room_jid.full(), players, profile) |
91
|
254 |
92
|
255 elif elt.name == 'player_ready': #ready to play |
|
256 player = elt['player'] |
90
|
257 status = self.games[room_jid.userhost()]['status'] |
|
258 nb_players = len(self.games[room_jid.userhost()]['players']) |
|
259 status[player] = 'ready' |
|
260 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) |
91
|
261 if status.values().count('ready') == nb_players: #everybody is ready, we can start the game |
92
|
262 self.newGame(room_jid, profile) |
88
|
263 |
90
|
264 elif elt.name == 'hand': #a new hand has been received |
92
|
265 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) |
91
|
266 |
|
267 elif elt.name == 'contrat': #it's time to choose contrat |
|
268 form = data_form.Form.fromElement(elt.firstChildElement()) |
|
269 xml_data = XMLTools.dataForm2xml(form) |
92
|
270 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) |
91
|
271 |
92
|
272 elif elt.name == 'contrat_choosed': |
91
|
273 #TODO: check we receive the contrat from the right person |
92
|
274 #TODO: use proper XEP-0004 way for answering form |
|
275 player = elt['player'] |
|
276 players_data[player]['contrat'] = unicode(elt) |
91
|
277 contrats = [players_data[player]['contrat'] for player in game_data['players']] |
|
278 if contrats.count(None): |
|
279 #not everybody has choosed his contrat, it's next one turn |
|
280 player = self.__next_player(game_data) |
|
281 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
282 mess = self.createGameElt(to_jid) |
|
283 mess.firstChildElement().addChild(self.__ask_contrat()) |
92
|
284 self.host.profiles[profile].xmlstream.send(mess) |
91
|
285 else: |
|
286 #TODO: manage "everybody pass" case |
|
287 best_contrat = [None, "Passe"] |
|
288 for player in game_data['players']: |
|
289 contrat = players_data[player]['contrat'] |
|
290 idx_best = self.contrats.index(best_contrat[1]) |
|
291 idx_pl = self.contrats.index(contrat) |
|
292 if idx_pl > idx_best: |
|
293 best_contrat[0] = player |
|
294 best_contrat[1] = contrat |
|
295 debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]}) |
92
|
296 #Time to show the chien to everybody |
|
297 to_jid = jid.JID(room_jid.userhost()) #FIXME: gof: |
|
298 mess = self.createGameElt(to_jid) |
|
299 chien_elt = mess.firstChildElement().addChild(self.__list_to_xml(game_data['chien'], 'chien')) |
|
300 chien_elt['attaquant'] = best_contrat[0] |
|
301 self.host.profiles[profile].xmlstream.send(mess) |
91
|
302 |
92
|
303 #the attacker (attaquant) get the chien |
|
304 game_data['hand'][best_contrat[0]].extend(game_data['chien']) |
|
305 del game_data['chien'][:] |
|
306 |
|
307 elif elt.name == 'chien': #we have received the chien |
|
308 debug (_("tarot: chien received")) |
|
309 data = {"attaquant":elt['attaquant']} |
|
310 players_data = game_data['players_data'] |
|
311 game_data['stage'] = "ecart" |
|
312 game_data['attaquant'] = elt['attaquant'] |
|
313 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) |
|
314 |
|
315 elif elt.name == 'cards_played': |
|
316 if game_data['stage'] == "ecart": |
|
317 #TODO: check validity of écart (no king, no oulder, cards must be in player hand) |
|
318 #TODO: show atouts (trumps) if player put some in écart |
|
319 assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here |
|
320 players_data[elt['player']]['levees'].extend(self.__xml_to_list(elt)) |
|
321 game_data['stage'] = "play" |
|
322 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #the player after the dealer start |
|
323 next_player = game_data['players'][next_player_idx] |
|
324 to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof: |
|
325 mess = self.createGameElt(to_jid) |
|
326 self.host.profiles[profile].xmlstream.send(mess) |
|
327 yourturn_elt = mess.firstChildElement().addElement('your_turn') |
|
328 self.host.profiles[profile].xmlstream.send(mess) |
|
329 |
|
330 elif elt.name == 'your_turn': |
|
331 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) |
91
|
332 |
90
|
333 |
|
334 def getHandler(self, profile): |
|
335 return CardGameHandler(self) |
|
336 |
|
337 |
88
|
338 |
90
|
339 class CardGameHandler (XMPPHandler): |
|
340 implements(iwokkel.IDisco) |
|
341 |
|
342 def __init__(self, plugin_parent): |
|
343 self.plugin_parent = plugin_parent |
|
344 self.host = plugin_parent.host |
|
345 |
|
346 def connectionInitialized(self): |
|
347 self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile) |
|
348 |
|
349 def getDiscoInfo(self, requestor, target, nodeIdentifier=''): |
|
350 return [disco.DiscoFeature(NS_CB)] |
|
351 |
|
352 def getDiscoItems(self, requestor, target, nodeIdentifier=''): |
|
353 return [] |
|
354 |