comparison sat/plugins/plugin_misc_quiz.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.internet import reactor 26 from twisted.internet import reactor
26 from twisted.words.protocols.jabber import client as jabber_client, jid 27 from twisted.words.protocols.jabber import client as jabber_client, jid
27 from time import time 28 from time import time
28 29
29 30
30 NS_QG = 'http://www.goffi.org/protocol/quiz' 31 NS_QG = "http://www.goffi.org/protocol/quiz"
31 QG_TAG = 'quiz' 32 QG_TAG = "quiz"
32 33
33 PLUGIN_INFO = { 34 PLUGIN_INFO = {
34 C.PI_NAME: "Quiz game plugin", 35 C.PI_NAME: "Quiz game plugin",
35 C.PI_IMPORT_NAME: "Quiz", 36 C.PI_IMPORT_NAME: "Quiz",
36 C.PI_TYPE: "Game", 37 C.PI_TYPE: "Game",
37 C.PI_PROTOCOLS: [], 38 C.PI_PROTOCOLS: [],
38 C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249", "ROOM-GAME"], 39 C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249", "ROOM-GAME"],
39 C.PI_MAIN: "Quiz", 40 C.PI_MAIN: "Quiz",
40 C.PI_HANDLER: "yes", 41 C.PI_HANDLER: "yes",
41 C.PI_DESCRIPTION: _("""Implementation of Quiz game""") 42 C.PI_DESCRIPTION: _("""Implementation of Quiz game"""),
42 } 43 }
43 44
44 45
45 class Quiz(object): 46 class Quiz(object):
46
47 def inheritFromRoomGame(self, host): 47 def inheritFromRoomGame(self, host):
48 global RoomGame 48 global RoomGame
49 RoomGame = host.plugins["ROOM-GAME"].__class__ 49 RoomGame = host.plugins["ROOM-GAME"].__class__
50 self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {}) 50 self.__class__ = type(
51 self.__class__.__name__, (self.__class__, RoomGame, object), {}
52 )
51 53
52 def __init__(self, host): 54 def __init__(self, host):
53 log.info(_("Plugin Quiz initialization")) 55 log.info(_("Plugin Quiz initialization"))
54 self.inheritFromRoomGame(host) 56 self.inheritFromRoomGame(host)
55 RoomGame._init_(self, host, PLUGIN_INFO, (NS_QG, QG_TAG), game_init={'stage': None}, player_init={'score': 0}) 57 RoomGame._init_(
56 host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom) # args: players, room_jid, profile 58 self,
57 host.bridge.addMethod("quizGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile 59 host,
58 host.bridge.addMethod("quizGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile 60 PLUGIN_INFO,
59 host.bridge.addMethod("quizGameAnswer", ".plugin", in_sign='ssss', out_sign='', method=self.playerAnswer) 61 (NS_QG, QG_TAG),
60 host.bridge.addSignal("quizGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile 62 game_init={"stage": None},
61 host.bridge.addSignal("quizGameNew", ".plugin", 63 player_init={"score": 0},
62 signature='sa{ss}s', 64 )
63 doc={'summary': 'Start a new game', 65 host.bridge.addMethod(
64 'param_0': "room_jid: jid of game's room", 66 "quizGameLaunch",
65 'param_1': "game_data: data of the game", 67 ".plugin",
66 'param_2': '%(doc_profile)s'}) 68 in_sign="asss",
67 host.bridge.addSignal("quizGameQuestion", ".plugin", 69 out_sign="",
68 signature='sssis', 70 method=self._prepareRoom,
69 doc={'summary': "Send the current question", 71 ) # args: players, room_jid, profile
70 'param_0': "room_jid: jid of game's room", 72 host.bridge.addMethod(
71 'param_1': "question_id: question id", 73 "quizGameCreate",
72 'param_2': "question: question to ask", 74 ".plugin",
73 'param_3': "timer: timer", 75 in_sign="sass",
74 'param_4': '%(doc_profile)s'}) 76 out_sign="",
75 host.bridge.addSignal("quizGamePlayerBuzzed", ".plugin", 77 method=self._createGame,
76 signature='ssbs', 78 ) # args: room_jid, players, profile
77 doc={'summary': "A player just pressed the buzzer", 79 host.bridge.addMethod(
78 'param_0': "room_jid: jid of game's room", 80 "quizGameReady",
79 'param_1': "player: player who pushed the buzzer", 81 ".plugin",
80 'param_2': "pause: should the game be paused ?", 82 in_sign="sss",
81 'param_3': '%(doc_profile)s'}) 83 out_sign="",
82 host.bridge.addSignal("quizGamePlayerSays", ".plugin", 84 method=self._playerReady,
83 signature='sssis', 85 ) # args: player, referee, profile
84 doc={'summary': "A player just pressed the buzzer", 86 host.bridge.addMethod(
85 'param_0': "room_jid: jid of game's room", 87 "quizGameAnswer",
86 'param_1': "player: player who pushed the buzzer", 88 ".plugin",
87 'param_2': "text: what the player say", 89 in_sign="ssss",
88 'param_3': "delay: how long, in seconds, the text must appear", 90 out_sign="",
89 'param_4': '%(doc_profile)s'}) 91 method=self.playerAnswer,
90 host.bridge.addSignal("quizGameAnswerResult", ".plugin", 92 )
91 signature='ssba{si}s', 93 host.bridge.addSignal(
92 doc={'summary': "Result of the just given answer", 94 "quizGameStarted", ".plugin", signature="ssass"
93 'param_0': "room_jid: jid of game's room", 95 ) # args: room_jid, referee, players, profile
94 'param_1': "player: player who gave the answer", 96 host.bridge.addSignal(
95 'param_2': "good_answer: True if the answer is right", 97 "quizGameNew",
96 'param_3': "score: dict of score with player as key", 98 ".plugin",
97 'param_4': '%(doc_profile)s'}) 99 signature="sa{ss}s",
98 host.bridge.addSignal("quizGameTimerExpired", ".plugin", 100 doc={
99 signature='ss', 101 "summary": "Start a new game",
100 doc={'summary': "Nobody answered the question in time", 102 "param_0": "room_jid: jid of game's room",
101 'param_0': "room_jid: jid of game's room", 103 "param_1": "game_data: data of the game",
102 'param_1': '%(doc_profile)s'}) 104 "param_2": "%(doc_profile)s",
103 host.bridge.addSignal("quizGameTimerRestarted", ".plugin", 105 },
104 signature='sis', 106 )
105 doc={'summary': "Nobody answered the question in time", 107 host.bridge.addSignal(
106 'param_0': "room_jid: jid of game's room", 108 "quizGameQuestion",
107 'param_1': "time_left: time left before timer expiration", 109 ".plugin",
108 'param_2': '%(doc_profile)s'}) 110 signature="sssis",
111 doc={
112 "summary": "Send the current question",
113 "param_0": "room_jid: jid of game's room",
114 "param_1": "question_id: question id",
115 "param_2": "question: question to ask",
116 "param_3": "timer: timer",
117 "param_4": "%(doc_profile)s",
118 },
119 )
120 host.bridge.addSignal(
121 "quizGamePlayerBuzzed",
122 ".plugin",
123 signature="ssbs",
124 doc={
125 "summary": "A player just pressed the buzzer",
126 "param_0": "room_jid: jid of game's room",
127 "param_1": "player: player who pushed the buzzer",
128 "param_2": "pause: should the game be paused ?",
129 "param_3": "%(doc_profile)s",
130 },
131 )
132 host.bridge.addSignal(
133 "quizGamePlayerSays",
134 ".plugin",
135 signature="sssis",
136 doc={
137 "summary": "A player just pressed the buzzer",
138 "param_0": "room_jid: jid of game's room",
139 "param_1": "player: player who pushed the buzzer",
140 "param_2": "text: what the player say",
141 "param_3": "delay: how long, in seconds, the text must appear",
142 "param_4": "%(doc_profile)s",
143 },
144 )
145 host.bridge.addSignal(
146 "quizGameAnswerResult",
147 ".plugin",
148 signature="ssba{si}s",
149 doc={
150 "summary": "Result of the just given answer",
151 "param_0": "room_jid: jid of game's room",
152 "param_1": "player: player who gave the answer",
153 "param_2": "good_answer: True if the answer is right",
154 "param_3": "score: dict of score with player as key",
155 "param_4": "%(doc_profile)s",
156 },
157 )
158 host.bridge.addSignal(
159 "quizGameTimerExpired",
160 ".plugin",
161 signature="ss",
162 doc={
163 "summary": "Nobody answered the question in time",
164 "param_0": "room_jid: jid of game's room",
165 "param_1": "%(doc_profile)s",
166 },
167 )
168 host.bridge.addSignal(
169 "quizGameTimerRestarted",
170 ".plugin",
171 signature="sis",
172 doc={
173 "summary": "Nobody answered the question in time",
174 "param_0": "room_jid: jid of game's room",
175 "param_1": "time_left: time left before timer expiration",
176 "param_2": "%(doc_profile)s",
177 },
178 )
109 179
110 def __game_data_to_xml(self, game_data): 180 def __game_data_to_xml(self, game_data):
111 """Convert a game data dict to domish element""" 181 """Convert a game data dict to domish element"""
112 game_data_elt = domish.Element((None, 'game_data')) 182 game_data_elt = domish.Element((None, "game_data"))
113 for data in game_data: 183 for data in game_data:
114 data_elt = domish.Element((None, data)) 184 data_elt = domish.Element((None, data))
115 data_elt.addContent(game_data[data]) 185 data_elt.addContent(game_data[data])
116 game_data_elt.addChild(data_elt) 186 game_data_elt.addChild(data_elt)
117 return game_data_elt 187 return game_data_elt
127 """Parse answer result element and return a tuple of signal arguments 197 """Parse answer result element and return a tuple of signal arguments
128 @param answer_result_elt: answer result element 198 @param answer_result_elt: answer result element
129 @return: (player, good_answer, score)""" 199 @return: (player, good_answer, score)"""
130 score = {} 200 score = {}
131 for score_elt in answer_result_elt.elements(): 201 for score_elt in answer_result_elt.elements():
132 score[score_elt['player']] = int(score_elt['score']) 202 score[score_elt["player"]] = int(score_elt["score"])
133 return (answer_result_elt['player'], answer_result_elt['good_answer'] == str(True), score) 203 return (
204 answer_result_elt["player"],
205 answer_result_elt["good_answer"] == str(True),
206 score,
207 )
134 208
135 def __answer_result(self, player_answering, good_answer, game_data): 209 def __answer_result(self, player_answering, good_answer, game_data):
136 """Convert a domish an answer_result element 210 """Convert a domish an answer_result element
137 @param player_answering: player who gave the answer 211 @param player_answering: player who gave the answer
138 @param good_answer: True is the answer is right 212 @param good_answer: True is the answer is right
139 @param game_data: data of the game""" 213 @param game_data: data of the game"""
140 players_data = game_data['players_data'] 214 players_data = game_data["players_data"]
141 score = {} 215 score = {}
142 for player in game_data['players']: 216 for player in game_data["players"]:
143 score[player] = players_data[player]['score'] 217 score[player] = players_data[player]["score"]
144 218
145 answer_result_elt = domish.Element((None, 'answer_result')) 219 answer_result_elt = domish.Element((None, "answer_result"))
146 answer_result_elt['player'] = player_answering 220 answer_result_elt["player"] = player_answering
147 answer_result_elt['good_answer'] = str(good_answer) 221 answer_result_elt["good_answer"] = str(good_answer)
148 222
149 for player in score: 223 for player in score:
150 score_elt = domish.Element((None, "score")) 224 score_elt = domish.Element((None, "score"))
151 score_elt['player'] = player 225 score_elt["player"] = player
152 score_elt['score'] = str(score[player]) 226 score_elt["score"] = str(score[player])
153 answer_result_elt.addChild(score_elt) 227 answer_result_elt.addChild(score_elt)
154 228
155 return answer_result_elt 229 return answer_result_elt
156 230
157 def __ask_question(self, question_id, question, timer): 231 def __ask_question(self, question_id, question, timer):
158 """Create a element for asking a question""" 232 """Create a element for asking a question"""
159 question_elt = domish.Element((None, 'question')) 233 question_elt = domish.Element((None, "question"))
160 question_elt['id'] = question_id 234 question_elt["id"] = question_id
161 question_elt['timer'] = str(timer) 235 question_elt["timer"] = str(timer)
162 question_elt.addContent(question) 236 question_elt.addContent(question)
163 return question_elt 237 return question_elt
164 238
165 def __start_play(self, room_jid, game_data, profile): 239 def __start_play(self, room_jid, game_data, profile):
166 """Start the game (tell to the first player after dealer to play""" 240 """Start the game (tell to the first player after dealer to play"""
167 client = self.host.getClient(profile) 241 client = self.host.getClient(profile)
168 game_data['stage'] = "play" 242 game_data["stage"] = "play"
169 next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # the player after the dealer start 243 next_player_idx = game_data["current_player"] = (
170 game_data['first_player'] = next_player = game_data['players'][next_player_idx] 244 game_data["init_player"] + 1
245 ) % len(
246 game_data["players"]
247 ) # the player after the dealer start
248 game_data["first_player"] = next_player = game_data["players"][next_player_idx]
171 to_jid = jid.JID(room_jid.userhost() + "/" + next_player) 249 to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
172 mess = self.createGameElt(to_jid) 250 mess = self.createGameElt(to_jid)
173 mess.firstChildElement().addElement('your_turn') 251 mess.firstChildElement().addElement("your_turn")
174 client.send(mess) 252 client.send(mess)
175 253
176 def playerAnswer(self, player, referee, answer, profile_key=C.PROF_KEY_NONE): 254 def playerAnswer(self, player, referee, answer, profile_key=C.PROF_KEY_NONE):
177 """Called when a player give an answer""" 255 """Called when a player give an answer"""
178 client = self.host.getClient(profile_key) 256 client = self.host.getClient(profile_key)
179 log.debug(u'new player answer (%(profile)s): %(answer)s' % {'profile': client.profile, 'answer': answer}) 257 log.debug(
258 u"new player answer (%(profile)s): %(answer)s"
259 % {"profile": client.profile, "answer": answer}
260 )
180 mess = self.createGameElt(jid.JID(referee)) 261 mess = self.createGameElt(jid.JID(referee))
181 answer_elt = mess.firstChildElement().addElement('player_answer') 262 answer_elt = mess.firstChildElement().addElement("player_answer")
182 answer_elt['player'] = player 263 answer_elt["player"] = player
183 answer_elt.addContent(answer) 264 answer_elt.addContent(answer)
184 client.send(mess) 265 client.send(mess)
185 266
186 def timerExpired(self, room_jid, profile): 267 def timerExpired(self, room_jid, profile):
187 """Called when nobody answered the question in time""" 268 """Called when nobody answered the question in time"""
188 client = self.host.getClient(profile) 269 client = self.host.getClient(profile)
189 game_data = self.games[room_jid] 270 game_data = self.games[room_jid]
190 game_data['stage'] = 'expired' 271 game_data["stage"] = "expired"
191 mess = self.createGameElt(room_jid) 272 mess = self.createGameElt(room_jid)
192 mess.firstChildElement().addElement('timer_expired') 273 mess.firstChildElement().addElement("timer_expired")
193 client.send(mess) 274 client.send(mess)
194 reactor.callLater(4, self.askQuestion, room_jid, client.profile) 275 reactor.callLater(4, self.askQuestion, room_jid, client.profile)
195 276
196 def pauseTimer(self, room_jid): 277 def pauseTimer(self, room_jid):
197 """Stop the timer and save the time left""" 278 """Stop the timer and save the time left"""
198 game_data = self.games[room_jid] 279 game_data = self.games[room_jid]
199 left = max(0, game_data["timer"].getTime() - time()) 280 left = max(0, game_data["timer"].getTime() - time())
200 game_data['timer'].cancel() 281 game_data["timer"].cancel()
201 game_data['time_left'] = int(left) 282 game_data["time_left"] = int(left)
202 game_data['previous_stage'] = game_data['stage'] 283 game_data["previous_stage"] = game_data["stage"]
203 game_data['stage'] = "paused" 284 game_data["stage"] = "paused"
204 285
205 def restartTimer(self, room_jid, profile): 286 def restartTimer(self, room_jid, profile):
206 """Restart a timer with the saved time""" 287 """Restart a timer with the saved time"""
207 client = self.host.getClient(profile) 288 client = self.host.getClient(profile)
208 game_data = self.games[room_jid] 289 game_data = self.games[room_jid]
209 assert game_data['time_left'] is not None 290 assert game_data["time_left"] is not None
210 mess = self.createGameElt(room_jid) 291 mess = self.createGameElt(room_jid)
211 mess.firstChildElement().addElement('timer_restarted') 292 mess.firstChildElement().addElement("timer_restarted")
212 jabber_client.restarted_elt["time_left"] = str(game_data['time_left']) 293 jabber_client.restarted_elt["time_left"] = str(game_data["time_left"])
213 client.send(mess) 294 client.send(mess)
214 game_data["timer"] = reactor.callLater(game_data['time_left'], self.timerExpired, room_jid, profile) 295 game_data["timer"] = reactor.callLater(
296 game_data["time_left"], self.timerExpired, room_jid, profile
297 )
215 game_data["time_left"] = None 298 game_data["time_left"] = None
216 game_data['stage'] = game_data['previous_stage'] 299 game_data["stage"] = game_data["previous_stage"]
217 del game_data['previous_stage'] 300 del game_data["previous_stage"]
218 301
219 def askQuestion(self, room_jid, profile): 302 def askQuestion(self, room_jid, profile):
220 """Ask a new question""" 303 """Ask a new question"""
221 client = self.host.getClient(profile) 304 client = self.host.getClient(profile)
222 game_data = self.games[room_jid] 305 game_data = self.games[room_jid]
223 game_data['stage'] = "question" 306 game_data["stage"] = "question"
224 game_data['question_id'] = "1" 307 game_data["question_id"] = "1"
225 timer = 30 308 timer = 30
226 mess = self.createGameElt(room_jid) 309 mess = self.createGameElt(room_jid)
227 mess.firstChildElement().addChild(self.__ask_question(game_data['question_id'], u"Quel est l'âge du capitaine ?", timer)) 310 mess.firstChildElement().addChild(
228 client.send(mess) 311 self.__ask_question(
229 game_data["timer"] = reactor.callLater(timer, self.timerExpired, room_jid, profile) 312 game_data["question_id"], u"Quel est l'âge du capitaine ?", timer
313 )
314 )
315 client.send(mess)
316 game_data["timer"] = reactor.callLater(
317 timer, self.timerExpired, room_jid, profile
318 )
230 game_data["time_left"] = None 319 game_data["time_left"] = None
231 320
232 def checkAnswer(self, room_jid, player, answer, profile): 321 def checkAnswer(self, room_jid, player, answer, profile):
233 """Check if the answer given is right""" 322 """Check if the answer given is right"""
234 client = self.host.getClient(profile) 323 client = self.host.getClient(profile)
235 game_data = self.games[room_jid] 324 game_data = self.games[room_jid]
236 players_data = game_data['players_data'] 325 players_data = game_data["players_data"]
237 good_answer = game_data['question_id'] == "1" and answer == "42" 326 good_answer = game_data["question_id"] == "1" and answer == "42"
238 players_data[player]['score'] += 1 if good_answer else -1 327 players_data[player]["score"] += 1 if good_answer else -1
239 players_data[player]['score'] = min(9, max(0, players_data[player]['score'])) 328 players_data[player]["score"] = min(9, max(0, players_data[player]["score"]))
240 329
241 mess = self.createGameElt(room_jid) 330 mess = self.createGameElt(room_jid)
242 mess.firstChildElement().addChild(self.__answer_result(player, good_answer, game_data)) 331 mess.firstChildElement().addChild(
332 self.__answer_result(player, good_answer, game_data)
333 )
243 client.send(mess) 334 client.send(mess)
244 335
245 if good_answer: 336 if good_answer:
246 reactor.callLater(4, self.askQuestion, room_jid, profile) 337 reactor.callLater(4, self.askQuestion, room_jid, profile)
247 else: 338 else:
248 reactor.callLater(4, self.restartTimer, room_jid, profile) 339 reactor.callLater(4, self.restartTimer, room_jid, profile)
249 340
250 def newGame(self, room_jid, profile): 341 def newGame(self, room_jid, profile):
251 """Launch a new round""" 342 """Launch a new round"""
252 common_data = {'game_score': 0} 343 common_data = {"game_score": 0}
253 new_game_data = {"instructions": _(u"""Bienvenue dans cette partie rapide de quizz, le premier à atteindre le score de 9 remporte le jeu 344 new_game_data = {
254 345 "instructions": _(
255 Attention, tu es prêt ?""")} 346 u"""Bienvenue dans cette partie rapide de quizz, le premier à atteindre le score de 9 remporte le jeu
347
348 Attention, tu es prêt ?"""
349 )
350 }
256 msg_elts = self.__game_data_to_xml(new_game_data) 351 msg_elts = self.__game_data_to_xml(new_game_data)
257 RoomGame.newRound(self, room_jid, (common_data, msg_elts), profile) 352 RoomGame.newRound(self, room_jid, (common_data, msg_elts), profile)
258 reactor.callLater(10, self.askQuestion, room_jid, profile) 353 reactor.callLater(10, self.askQuestion, room_jid, profile)
259 354
260 def room_game_cmd(self, mess_elt, profile): 355 def room_game_cmd(self, mess_elt, profile):
261 client = self.host.getClient(profile) 356 client = self.host.getClient(profile)
262 from_jid = jid.JID(mess_elt['from']) 357 from_jid = jid.JID(mess_elt["from"])
263 room_jid = jid.JID(from_jid.userhost()) 358 room_jid = jid.JID(from_jid.userhost())
264 game_elt = mess_elt.firstChildElement() 359 game_elt = mess_elt.firstChildElement()
265 game_data = self.games[room_jid] 360 game_data = self.games[room_jid]
266 # if 'players_data' in game_data: 361 #  if 'players_data' in game_data:
267 #  players_data = game_data['players_data'] 362 #   players_data = game_data['players_data']
268 363
269 for elt in game_elt.elements(): 364 for elt in game_elt.elements():
270 365
271 if elt.name == 'started': # new game created 366 if elt.name == "started": # new game created
272 players = [] 367 players = []
273 for player in elt.elements(): 368 for player in elt.elements():
274 players.append(unicode(player)) 369 players.append(unicode(player))
275 self.host.bridge.quizGameStarted(room_jid.userhost(), from_jid.full(), players, profile) 370 self.host.bridge.quizGameStarted(
276 371 room_jid.userhost(), from_jid.full(), players, profile
277 elif elt.name == 'player_ready': # ready to play 372 )
278 player = elt['player'] 373
279 status = self.games[room_jid]['status'] 374 elif elt.name == "player_ready": # ready to play
280 nb_players = len(self.games[room_jid]['players']) 375 player = elt["player"]
281 status[player] = 'ready' 376 status = self.games[room_jid]["status"]
282 log.debug(_(u'Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status}) 377 nb_players = len(self.games[room_jid]["players"])
283 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game 378 status[player] = "ready"
379 log.debug(
380 _(u"Player %(player)s is ready to start [status: %(status)s]")
381 % {"player": player, "status": status}
382 )
383 if (
384 status.values().count("ready") == nb_players
385 ): # everybody is ready, we can start the game
284 self.newGame(room_jid, profile) 386 self.newGame(room_jid, profile)
285 387
286 elif elt.name == 'game_data': 388 elif elt.name == "game_data":
287 self.host.bridge.quizGameNew(room_jid.userhost(), self.__xml_to_game_data(elt), profile) 389 self.host.bridge.quizGameNew(
288 390 room_jid.userhost(), self.__xml_to_game_data(elt), profile
289 elif elt.name == 'question': # A question is asked 391 )
290 self.host.bridge.quizGameQuestion(room_jid.userhost(), elt["id"], unicode(elt), int(elt["timer"]), profile) 392
291 393 elif elt.name == "question": # A question is asked
292 elif elt.name == 'player_answer': 394 self.host.bridge.quizGameQuestion(
293 player = elt['player'] 395 room_jid.userhost(),
294 pause = game_data['stage'] == 'question' # we pause the game only if we are have a question at the moment 396 elt["id"],
397 unicode(elt),
398 int(elt["timer"]),
399 profile,
400 )
401
402 elif elt.name == "player_answer":
403 player = elt["player"]
404 pause = (
405 game_data["stage"] == "question"
406 ) # we pause the game only if we are have a question at the moment
295 # we first send a buzzer message 407 # we first send a buzzer message
296 mess = self.createGameElt(room_jid) 408 mess = self.createGameElt(room_jid)
297 buzzer_elt = mess.firstChildElement().addElement('player_buzzed') 409 buzzer_elt = mess.firstChildElement().addElement("player_buzzed")
298 buzzer_elt['player'] = player 410 buzzer_elt["player"] = player
299 buzzer_elt['pause'] = str(pause) 411 buzzer_elt["pause"] = str(pause)
300 client.send(mess) 412 client.send(mess)
301 if pause: 413 if pause:
302 self.pauseTimer(room_jid) 414 self.pauseTimer(room_jid)
303 # and we send the player answer 415 # and we send the player answer
304 mess = self.createGameElt(room_jid) 416 mess = self.createGameElt(room_jid)
305 _answer = unicode(elt) 417 _answer = unicode(elt)
306 say_elt = mess.firstChildElement().addElement('player_says') 418 say_elt = mess.firstChildElement().addElement("player_says")
307 say_elt['player'] = player 419 say_elt["player"] = player
308 say_elt.addContent(_answer) 420 say_elt.addContent(_answer)
309 say_elt['delay'] = "3" 421 say_elt["delay"] = "3"
310 reactor.callLater(2, client.send, mess) 422 reactor.callLater(2, client.send, mess)
311 reactor.callLater(6, self.checkAnswer, room_jid, player, _answer, profile=profile) 423 reactor.callLater(
312 424 6, self.checkAnswer, room_jid, player, _answer, profile=profile
313 elif elt.name == 'player_buzzed': 425 )
314 self.host.bridge.quizGamePlayerBuzzed(room_jid.userhost(), elt["player"], elt['pause'] == str(True), profile) 426
315 427 elif elt.name == "player_buzzed":
316 elif elt.name == 'player_says': 428 self.host.bridge.quizGamePlayerBuzzed(
317 self.host.bridge.quizGamePlayerSays(room_jid.userhost(), elt["player"], unicode(elt), int(elt["delay"]), profile) 429 room_jid.userhost(), elt["player"], elt["pause"] == str(True), profile
318 430 )
319 elif elt.name == 'answer_result': 431
432 elif elt.name == "player_says":
433 self.host.bridge.quizGamePlayerSays(
434 room_jid.userhost(),
435 elt["player"],
436 unicode(elt),
437 int(elt["delay"]),
438 profile,
439 )
440
441 elif elt.name == "answer_result":
320 player, good_answer, score = self.__answer_result_to_signal_args(elt) 442 player, good_answer, score = self.__answer_result_to_signal_args(elt)
321 self.host.bridge.quizGameAnswerResult(room_jid.userhost(), player, good_answer, score, profile) 443 self.host.bridge.quizGameAnswerResult(
322 444 room_jid.userhost(), player, good_answer, score, profile
323 elif elt.name == 'timer_expired': 445 )
446
447 elif elt.name == "timer_expired":
324 self.host.bridge.quizGameTimerExpired(room_jid.userhost(), profile) 448 self.host.bridge.quizGameTimerExpired(room_jid.userhost(), profile)
325 449
326 elif elt.name == 'timer_restarted': 450 elif elt.name == "timer_restarted":
327 self.host.bridge.quizGameTimerRestarted(room_jid.userhost(), int(elt['time_left']), profile) 451 self.host.bridge.quizGameTimerRestarted(
452 room_jid.userhost(), int(elt["time_left"]), profile
453 )
328 454
329 else: 455 else:
330 log.error(_(u'Unmanaged game element: %s') % elt.name) 456 log.error(_(u"Unmanaged game element: %s") % elt.name)