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 |
|
34 from wokkel import disco, iwokkel, muc |
|
35 |
|
36 from base64 import b64decode |
|
37 from hashlib import sha1 |
|
38 from time import sleep |
|
39 |
|
40 try: |
|
41 from twisted.words.protocols.xmlstream import XMPPHandler |
|
42 except ImportError: |
|
43 from wokkel.subprotocols import XMPPHandler |
|
44 |
90
|
45 MESSAGE = '/message' |
|
46 NS_CG = 'http://www.goffi.org/protocol/card_game' |
|
47 CG_TAG = 'card_game' |
|
48 CG_REQUEST = MESSAGE + '/' + CG_TAG + '[@xmlns="' + NS_CG + '"]' |
88
|
49 |
|
50 PLUGIN_INFO = { |
|
51 "name": "Tarot cards plugin", |
|
52 "import_name": "Tarot", |
|
53 "type": "Misc", |
|
54 "protocols": [], |
|
55 "dependencies": ["XEP_0045"], |
|
56 "main": "Tarot", |
90
|
57 "handler": "yes", |
88
|
58 "description": _("""Implementation of Tarot card game""") |
|
59 } |
|
60 |
|
61 class Tarot(): |
|
62 |
|
63 def __init__(self, host): |
|
64 info(_("Plugin Tarot initialization")) |
|
65 self.host = host |
|
66 self.games={} |
90
|
67 host.bridge.addMethod("tarotGameCreate", ".communication", in_sign='sass', out_sign='', method=self.createGame) #args: room_jid, players, profile |
|
68 host.bridge.addMethod("tarotGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: user, referee, profile |
|
69 host.bridge.addSignal("tarotGameStarted", ".communication", signature='ssass') #args: room_jid, referee, players, profile |
|
70 host.bridge.addSignal("tarotGameNew", ".communication", signature='sa(ss)s') #args: room_jid, hand, profile |
88
|
71 self.deck_ordered = [] |
|
72 for value in map(str,range(1,22))+['excuse']: |
|
73 self.deck_ordered.append(("atout",value)) |
|
74 for family in ["pique", "coeur", "carreau", "trefle"]: |
|
75 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]: |
|
76 self.deck_ordered.append((family, value)) |
|
77 |
90
|
78 def createGameElt(self, to_jid): |
|
79 elt = domish.Element(('jabber:client','message')) |
|
80 elt["to"] = to_jid.full() |
|
81 elt.addElement((NS_CG, CG_TAG)) |
|
82 return elt |
|
83 |
|
84 def __hand_to_xml(self, hand): |
|
85 """Convert a hand (list of tuples) to domish element""" |
|
86 hand_elt = domish.Element(('','hand')) |
|
87 for family, value in hand: |
|
88 card_elt = domish.Element(('','card')) |
|
89 card_elt['family'] = family |
|
90 card_elt['value'] = value |
|
91 hand_elt.addChild(card_elt) |
|
92 return hand_elt |
|
93 |
|
94 def __xml_to_hand(self, hand_elt): |
|
95 """Convert a hand domish element to a list of tuples""" |
|
96 hand = [] |
|
97 assert (hand_elt.name == 'hand') |
|
98 for card in hand_elt.elements(): |
|
99 hand.append((card['family'], card['value'])) |
|
100 return hand |
|
101 |
|
102 def __create_started_elt(self, players): |
|
103 """Create a game_started domish element""" |
|
104 started_elt = domish.Element(('','started')) |
|
105 idx = 0 |
|
106 for player in players: |
|
107 player_elt = domish.Element(('','player')) |
|
108 player_elt.addContent(player) |
|
109 player_elt['index'] = str(idx) |
|
110 idx+=1 |
|
111 started_elt.addChild(player_elt) |
|
112 return started_elt |
|
113 |
|
114 def createGame(self, room_jid_param, players, profile_key='@DEFAULT@'): |
88
|
115 """Create a new game""" |
|
116 debug (_("Creating Tarot game")) |
90
|
117 room_jid = jid.JID(room_jid_param) |
88
|
118 profile = self.host.memory.getProfileName(profile_key) |
|
119 if not profile: |
|
120 error (_("profile %s is unknown") % profile_key) |
|
121 return |
|
122 if False: #gof: self.games.has_key(room_jid): |
90
|
123 warning (_("Tarot game already started in room %s") % room_jid.userhost()) |
88
|
124 else: |
90
|
125 status = {} |
|
126 for player in players: |
|
127 status[player] = "init" |
|
128 self.games[room_jid.userhost()] = {'players':players, 'status':status, 'profile':profile, 'hand_size':18, 'player_start':0} |
|
129 for player in players: |
|
130 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player)) |
|
131 mess.firstChildElement().addChild(self.__create_started_elt(players)) |
|
132 self.host.profiles[profile].xmlstream.send(mess) |
|
133 |
|
134 def newPlayerReady(self, user, referee, profile_key='@DEFAULT@'): |
|
135 """Must be called when player is ready to start a new game""" |
|
136 profile = self.host.memory.getProfileName(profile_key) |
|
137 if not profile: |
|
138 error (_("profile %s is unknown") % profile_key) |
|
139 return |
|
140 debug ('new player ready: %s' % profile) |
|
141 mess = self.createGameElt(jid.JID(referee)) |
|
142 mess.firstChildElement().addElement('player_ready', content=user) |
|
143 self.host.profiles[profile].xmlstream.send(mess) |
88
|
144 |
|
145 |
|
146 def newGame(self, room_jid): |
|
147 """Launch a new round""" |
|
148 debug (_('new Tarot game')) |
|
149 deck = self.deck_ordered[:] |
|
150 random.shuffle(deck) |
90
|
151 profile = self.games[room_jid.userhost()]['profile'] |
|
152 players = self.games[room_jid.userhost()]['players'] |
|
153 hand = self.games[room_jid.userhost()]['hand'] = {} |
|
154 hand_size = self.games[room_jid.userhost()]['hand_size'] |
|
155 chien = self.games[room_jid.userhost()]['chien'] = [] |
88
|
156 for i in range(4): #TODO: distribute according to real Tarot rules (3 by 3 counter-clockwise, 1 card at once to chien) |
|
157 hand[players[i]] = deck[0:hand_size] |
|
158 del deck[0:hand_size] |
|
159 chien = deck[:] |
|
160 del(deck[:]) |
|
161 |
|
162 for player in players: |
90
|
163 to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof: |
|
164 mess = self.createGameElt(to_jid) |
|
165 mess.firstChildElement().addChild(self.__hand_to_xml(hand[player])) |
|
166 self.host.profiles[profile].xmlstream.send(mess) |
|
167 |
|
168 |
|
169 def card_game_cmd(self, mess_elt, profile): |
|
170 print "\n\nCARD GAME command received (profile=%s): %s" % (profile, mess_elt.toXml()) |
|
171 room_jid = jid.JID(mess_elt['from']) |
|
172 game_elt = mess_elt.firstChildElement() |
|
173 for elt in game_elt.elements(): #new game created |
|
174 if elt.name == 'started': |
|
175 players = [] |
|
176 for player in elt.elements(): |
|
177 players.append(unicode(player)) |
|
178 self.host.bridge.tarotGameStarted(room_jid.userhost(), room_jid.full(), players, profile) |
|
179 elif elt.name == 'player_ready': |
|
180 player = unicode(elt) |
|
181 status = self.games[room_jid.userhost()]['status'] |
|
182 nb_players = len(self.games[room_jid.userhost()]['players']) |
|
183 status[player] = 'ready' |
|
184 debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status}) |
|
185 if status.values().count('ready') == 2: #gof: nb_players: #everybody is ready, we can start the game |
|
186 self.newGame(room_jid) |
88
|
187 |
90
|
188 elif elt.name == 'hand': #a new hand has been received |
|
189 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_hand(elt), profile) |
|
190 |
|
191 |
|
192 def getHandler(self, profile): |
|
193 return CardGameHandler(self) |
|
194 |
|
195 |
88
|
196 |
90
|
197 class CardGameHandler (XMPPHandler): |
|
198 implements(iwokkel.IDisco) |
|
199 |
|
200 def __init__(self, plugin_parent): |
|
201 self.plugin_parent = plugin_parent |
|
202 self.host = plugin_parent.host |
|
203 |
|
204 def connectionInitialized(self): |
|
205 print "gof: ajout d'observer", CG_REQUEST |
|
206 self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile) |
|
207 |
|
208 def getDiscoInfo(self, requestor, target, nodeIdentifier=''): |
|
209 return [disco.DiscoFeature(NS_CB)] |
|
210 |
|
211 def getDiscoItems(self, requestor, target, nodeIdentifier=''): |
|
212 return [] |
|
213 |