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 |
93
|
77 host.bridge.addSignal("tarotGameCardsPlayed", ".communication", signature='ssa(ss)s') #args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile |
92
|
78 host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile |
88
|
79 self.deck_ordered = [] |
92
|
80 for value in ['excuse']+map(str,range(1,22)): |
88
|
81 self.deck_ordered.append(("atout",value)) |
92
|
82 for suit in ["pique", "coeur", "carreau", "trefle"]: |
88
|
83 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]: |
92
|
84 self.deck_ordered.append((suit, value)) |
88
|
85 |
92
|
86 def createGameElt(self, to_jid, type="normal"): |
|
87 type = "normal" if to_jid.resource else "groupchat" |
90
|
88 elt = domish.Element(('jabber:client','message')) |
|
89 elt["to"] = to_jid.full() |
92
|
90 elt["type"] = type |
90
|
91 elt.addElement((NS_CG, CG_TAG)) |
|
92 return elt |
|
93 |
92
|
94 def __list_to_xml(self, cards_list, elt_name): |
|
95 """Convert a card list (list of tuples) to domish element""" |
|
96 cards_list_elt = domish.Element(('',elt_name)) |
|
97 for suit, value in cards_list: |
90
|
98 card_elt = domish.Element(('','card')) |
92
|
99 card_elt['suit'] = suit |
90
|
100 card_elt['value'] = value |
92
|
101 cards_list_elt.addChild(card_elt) |
|
102 return cards_list_elt |
90
|
103 |
92
|
104 def __xml_to_list(self, cards_list_elt): |
|
105 """Convert a domish element with cards to a list of tuples""" |
|
106 cards_list = [] |
|
107 for card in cards_list_elt.elements(): |
|
108 cards_list.append((card['suit'], card['value'])) |
|
109 return cards_list |
90
|
110 |
|
111 def __create_started_elt(self, players): |
|
112 """Create a game_started domish element""" |
|
113 started_elt = domish.Element(('','started')) |
|
114 idx = 0 |
|
115 for player in players: |
|
116 player_elt = domish.Element(('','player')) |
|
117 player_elt.addContent(player) |
|
118 player_elt['index'] = str(idx) |
|
119 idx+=1 |
|
120 started_elt.addChild(player_elt) |
|
121 return started_elt |
|
122 |
91
|
123 def __ask_contrat(self): |
|
124 """Create a element for asking contrat""" |
|
125 contrat_elt = domish.Element(('','contrat')) |
|
126 form = data_form.Form('form', title=_('contrat selection')) |
|
127 field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True) |
|
128 form.addField(field) |
|
129 contrat_elt.addChild(form.toElement()) |
|
130 return contrat_elt |
|
131 |
|
132 def __next_player(self, game_data): |
|
133 """It's next player turn |
|
134 Increment player number & return player name""" |
|
135 pl_idx = game_data['current_player'] = (game_data['current_player'] + 1) % len(game_data['players']) |
|
136 return game_data['players'][pl_idx] |
|
137 |
90
|
138 def createGame(self, room_jid_param, players, profile_key='@DEFAULT@'): |
88
|
139 """Create a new game""" |
|
140 debug (_("Creating Tarot game")) |
90
|
141 room_jid = jid.JID(room_jid_param) |
88
|
142 profile = self.host.memory.getProfileName(profile_key) |
|
143 if not profile: |
|
144 error (_("profile %s is unknown") % profile_key) |
|
145 return |
|
146 if False: #gof: self.games.has_key(room_jid): |
90
|
147 warning (_("Tarot game already started in room %s") % room_jid.userhost()) |
88
|
148 else: |
93
|
149 room_nick = self.host.plugins["XEP_0045"].getRoomNick(room_jid.userhost(), profile) |
|
150 if not room_nick: |
|
151 error ('Internal error') |
|
152 return |
|
153 referee = room_jid.userhost() + '/' + room_nick |
90
|
154 status = {} |
91
|
155 players_data = {} |
90
|
156 for player in players: |
91
|
157 players_data[player] = {} |
90
|
158 status[player] = "init" |
93
|
159 self.games[room_jid.userhost()] = {'referee':referee, 'players':players, 'status':status, 'players_data':players_data, 'hand_size':18, 'init_player':0, 'current_player': None, 'stage': None} |
90
|
160 for player in players: |
|
161 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player)) |
|
162 mess.firstChildElement().addChild(self.__create_started_elt(players)) |
|
163 self.host.profiles[profile].xmlstream.send(mess) |
|
164 |
92
|
165 def newPlayerReady(self, player, referee, profile_key='@DEFAULT@'): |
90
|
166 """Must be called when player is ready to start a new game""" |
|
167 profile = self.host.memory.getProfileName(profile_key) |
|
168 if not profile: |
|
169 error (_("profile %s is unknown") % profile_key) |
|
170 return |
|
171 debug ('new player ready: %s' % profile) |
|
172 mess = self.createGameElt(jid.JID(referee)) |
91
|
173 ready_elt = mess.firstChildElement().addElement('player_ready') |
92
|
174 ready_elt['player'] = player |
91
|
175 self.host.profiles[profile].xmlstream.send(mess) |
|
176 |
92
|
177 def contratChoosed(self, player, referee, contrat, profile_key='@DEFAULT@'): |
91
|
178 """Must be call by player when the contrat is selected |
92
|
179 @param player: player's name |
91
|
180 @param referee: arbiter jid |
|
181 @contrat: contrat choosed (must be the exact same string than in the give list options) |
|
182 @profile_key: profile |
|
183 """ |
|
184 profile = self.host.memory.getProfileName(profile_key) |
|
185 if not profile: |
|
186 error (_("profile %s is unknown") % profile_key) |
|
187 return |
|
188 debug (_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat':contrat, 'profile':profile}) |
|
189 mess = self.createGameElt(jid.JID(referee)) |
|
190 contrat_elt = mess.firstChildElement().addElement(('','contrat_choosed'), content=contrat) |
92
|
191 contrat_elt['player'] = player |
90
|
192 self.host.profiles[profile].xmlstream.send(mess) |
88
|
193 |
92
|
194 def play_cards(self, player, referee, cards, profile_key='@DEFAULT@'): |
|
195 """Must be call by player when the contrat is selected |
|
196 @param player: player's name |
|
197 @param referee: arbiter jid |
|
198 @cards: cards played (list of tuples) |
|
199 @profile_key: profile |
|
200 """ |
|
201 profile = self.host.memory.getProfileName(profile_key) |
|
202 if not profile: |
|
203 error (_("profile %s is unknown") % profile_key) |
|
204 return |
|
205 debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards}) |
|
206 mess = self.createGameElt(jid.JID(referee)) |
|
207 playcard_elt = mess.firstChildElement().addChild(self.__list_to_xml(cards, 'cards_played')) |
|
208 playcard_elt['player'] = player |
|
209 self.host.profiles[profile].xmlstream.send(mess) |
88
|
210 |
92
|
211 def newGame(self, room_jid, profile): |
88
|
212 """Launch a new round""" |
|
213 debug (_('new Tarot game')) |
|
214 deck = self.deck_ordered[:] |
|
215 random.shuffle(deck) |
91
|
216 game_data = self.games[room_jid.userhost()] |
|
217 players = game_data['players'] |
|
218 players_data = game_data['players_data'] |
|
219 current_player = game_data['current_player'] |
92
|
220 game_data['stage'] = "init" |
91
|
221 hand = game_data['hand'] = {} |
|
222 hand_size = game_data['hand_size'] |
|
223 chien = game_data['chien'] = [] |
88
|
224 for i in range(4): #TODO: distribute according to real Tarot rules (3 by 3 counter-clockwise, 1 card at once to chien) |
|
225 hand[players[i]] = deck[0:hand_size] |
|
226 del deck[0:hand_size] |
92
|
227 chien.extend(deck) |
88
|
228 del(deck[:]) |
|
229 |
|
230 for player in players: |
90
|
231 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
232 mess = self.createGameElt(to_jid) |
92
|
233 mess.firstChildElement().addChild(self.__list_to_xml(hand[player], 'hand')) |
|
234 self.host.profiles[profile].xmlstream.send(mess) |
91
|
235 players_data[player]['contrat'] = None |
92
|
236 players_data[player]['levees'] = [] #cards won |
91
|
237 |
|
238 pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) #the player after the dealer start |
|
239 player = players[pl_idx] |
|
240 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
241 mess = self.createGameElt(to_jid) |
|
242 mess.firstChildElement().addChild(self.__ask_contrat()) |
92
|
243 self.host.profiles[profile].xmlstream.send(mess) |
90
|
244 |
|
245 |
|
246 def card_game_cmd(self, mess_elt, profile): |
|
247 print "\n\nCARD GAME command received (profile=%s): %s" % (profile, mess_elt.toXml()) |
93
|
248 from_jid = jid.JID(mess_elt['from']) |
|
249 room_jid = jid.JID(from_jid.userhost()) |
90
|
250 game_elt = mess_elt.firstChildElement() |
92
|
251 game_data = self.games[room_jid.userhost()] |
|
252 players_data = game_data['players_data'] |
|
253 |
|
254 for elt in game_elt.elements(): |
91
|
255 |
92
|
256 if elt.name == 'started': #new game created |
90
|
257 players = [] |
|
258 for player in elt.elements(): |
|
259 players.append(unicode(player)) |
93
|
260 self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile) |
91
|
261 |
92
|
262 elif elt.name == 'player_ready': #ready to play |
|
263 player = elt['player'] |
90
|
264 status = self.games[room_jid.userhost()]['status'] |
|
265 nb_players = len(self.games[room_jid.userhost()]['players']) |
|
266 status[player] = 'ready' |
|
267 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) |
91
|
268 if status.values().count('ready') == nb_players: #everybody is ready, we can start the game |
92
|
269 self.newGame(room_jid, profile) |
88
|
270 |
90
|
271 elif elt.name == 'hand': #a new hand has been received |
92
|
272 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) |
91
|
273 |
|
274 elif elt.name == 'contrat': #it's time to choose contrat |
|
275 form = data_form.Form.fromElement(elt.firstChildElement()) |
|
276 xml_data = XMLTools.dataForm2xml(form) |
92
|
277 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile) |
91
|
278 |
92
|
279 elif elt.name == 'contrat_choosed': |
91
|
280 #TODO: check we receive the contrat from the right person |
92
|
281 #TODO: use proper XEP-0004 way for answering form |
|
282 player = elt['player'] |
|
283 players_data[player]['contrat'] = unicode(elt) |
91
|
284 contrats = [players_data[player]['contrat'] for player in game_data['players']] |
|
285 if contrats.count(None): |
|
286 #not everybody has choosed his contrat, it's next one turn |
|
287 player = self.__next_player(game_data) |
|
288 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
289 mess = self.createGameElt(to_jid) |
|
290 mess.firstChildElement().addChild(self.__ask_contrat()) |
92
|
291 self.host.profiles[profile].xmlstream.send(mess) |
91
|
292 else: |
|
293 #TODO: manage "everybody pass" case |
|
294 best_contrat = [None, "Passe"] |
|
295 for player in game_data['players']: |
|
296 contrat = players_data[player]['contrat'] |
|
297 idx_best = self.contrats.index(best_contrat[1]) |
|
298 idx_pl = self.contrats.index(contrat) |
|
299 if idx_pl > idx_best: |
|
300 best_contrat[0] = player |
|
301 best_contrat[1] = contrat |
|
302 debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]}) |
92
|
303 #Time to show the chien to everybody |
|
304 to_jid = jid.JID(room_jid.userhost()) #FIXME: gof: |
|
305 mess = self.createGameElt(to_jid) |
|
306 chien_elt = mess.firstChildElement().addChild(self.__list_to_xml(game_data['chien'], 'chien')) |
|
307 chien_elt['attaquant'] = best_contrat[0] |
|
308 self.host.profiles[profile].xmlstream.send(mess) |
91
|
309 |
92
|
310 #the attacker (attaquant) get the chien |
|
311 game_data['hand'][best_contrat[0]].extend(game_data['chien']) |
|
312 del game_data['chien'][:] |
|
313 |
|
314 elif elt.name == 'chien': #we have received the chien |
|
315 debug (_("tarot: chien received")) |
|
316 data = {"attaquant":elt['attaquant']} |
|
317 players_data = game_data['players_data'] |
|
318 game_data['stage'] = "ecart" |
|
319 game_data['attaquant'] = elt['attaquant'] |
|
320 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) |
|
321 |
|
322 elif elt.name == 'cards_played': |
|
323 if game_data['stage'] == "ecart": |
|
324 #TODO: check validity of écart (no king, no oulder, cards must be in player hand) |
|
325 #TODO: show atouts (trumps) if player put some in écart |
|
326 assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here |
|
327 players_data[elt['player']]['levees'].extend(self.__xml_to_list(elt)) |
|
328 game_data['stage'] = "play" |
|
329 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #the player after the dealer start |
|
330 next_player = game_data['players'][next_player_idx] |
|
331 to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof: |
|
332 mess = self.createGameElt(to_jid) |
|
333 yourturn_elt = mess.firstChildElement().addElement('your_turn') |
|
334 self.host.profiles[profile].xmlstream.send(mess) |
93
|
335 elif game_data['stage'] == "play": |
|
336 current_player = game_data['players'][game_data['current_player']] |
|
337 #assert (elt['player'] == current_player) #TODO: throw xml error here |
|
338 cards = self.__xml_to_list(elt) |
|
339 #TODO: check card validity and send error mess if necessary |
|
340 if mess_elt['type'] != 'groupchat': |
|
341 #the card played is ok, we forward it to everybody |
|
342 #first we remove it from the hand |
|
343 game_data['hand'][current_player].remove(cards[0]) |
|
344 |
|
345 #then we forward the message |
|
346 mess = self.createGameElt(room_jid) |
|
347 playcard_elt = mess.firstChildElement().addChild(elt) |
|
348 self.host.profiles[profile].xmlstream.send(mess) |
|
349 |
|
350 #finally, we tell to the next player to play |
|
351 next_player = self.__next_player(game_data) |
|
352 to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof: |
|
353 mess = self.createGameElt(to_jid) |
|
354 yourturn_elt = mess.firstChildElement().addElement('your_turn') |
|
355 self.host.profiles[profile].xmlstream.send(mess) |
|
356 else: |
|
357 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) |
|
358 |
|
359 |
|
360 |
92
|
361 |
|
362 elif elt.name == 'your_turn': |
|
363 self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile) |
91
|
364 |
90
|
365 |
|
366 def getHandler(self, profile): |
|
367 return CardGameHandler(self) |
|
368 |
|
369 |
88
|
370 |
90
|
371 class CardGameHandler (XMPPHandler): |
|
372 implements(iwokkel.IDisco) |
|
373 |
|
374 def __init__(self, plugin_parent): |
|
375 self.plugin_parent = plugin_parent |
|
376 self.host = plugin_parent.host |
|
377 |
|
378 def connectionInitialized(self): |
|
379 self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile) |
|
380 |
|
381 def getDiscoInfo(self, requestor, target, nodeIdentifier=''): |
|
382 return [disco.DiscoFeature(NS_CB)] |
|
383 |
|
384 def getDiscoItems(self, requestor, target, nodeIdentifier=''): |
|
385 return [] |
|
386 |