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