Quizz game: first draft

This commit is contained in:
Goffi 2011-06-12 16:28:33 +02:00
commit fb41ecbbf5
7 changed files with 539 additions and 2 deletions

View file

@ -176,6 +176,15 @@ class DBusBridgeFrontend(BridgeFrontend):
def tarotGamePlayCards(self, player, referee, cards, profile_key='@DEFAULT@'):
return self.db_comm_iface.tarotGamePlayCards(player, referee, cards, profile_key)
def quizGameLaunch(self, players, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameLaunch(players, profile_key)
def quizGameCreate(self, room_jid, players, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameCreate(room_jid, players, profile_key)
def quizGameReady(self, player, referee, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameReady(player, referee, profile_key)
def sendFile(self, to, path, profile_key='@DEFAULT@'):
return self.db_comm_iface.sendFile(to, path, profile_key)

View file

@ -63,6 +63,9 @@ class QuickApp():
self.bridge.register("tarotGameScore", self.tarotScore)
self.bridge.register("tarotGameCardsPlayed", self.tarotCardsPlayed)
self.bridge.register("tarotGameInvalidCards", self.tarotInvalidCards)
self.bridge.register("quizGameStarted", self.quizGameStarted)
self.bridge.register("quizGameNew", self.quizGameNew)
self.bridge.register("quizGameQuestion", self.quizGameQuestion)
self.bridge.register("subscribe", self.subscribe)
self.bridge.register("paramUpdate", self.paramUpdate)
self.bridge.register("contactDeleted", self.contactDeleted)
@ -372,6 +375,30 @@ class QuickApp():
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Tarot").invalidCards(phase, played_cards, invalid_cards)
def quizGameStarted(self, room_jid, referee, players, profile):
if not self.check_profile(profile):
print "gof: NOT CHECK PROFILE", profile
return
debug (_("Quiz Game Started \o/"))
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].startGame("Quiz", referee, players)
debug (_("new Quiz game started by [%(referee)s] in room [%(room_jid)s] with %(players)s") % {'referee':referee, 'room_jid':room_jid, 'players':[str(player) for player in players]})
def quizGameNew(self, room_jid, data, profile):
if not self.check_profile(profile):
return
debug (_("New Quiz Game"))
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Quiz").quizGameNew(data)
def quizGameQuestion(self, room_jid, question_id, question, timer, profile):
"""Called when a new question is asked"""
if not self.check_profile(profile):
return
debug (_(u"Quiz: new question: %s") % question)
if self.chat_wins.has_key(room_jid):
self.chat_wins[room_jid].getGame("Quiz").quizGameQuestion(question_id, question, timer)
def _subscribe_cb(self, answer, data):
entity, profile = data
if answer:

View file

@ -30,6 +30,7 @@ from sat.tools.jid import JID
from sat_frontends.quick_frontend.quick_chat import QuickChat
from sat_frontends.wix.contact_list import ContactList
from sat_frontends.wix.card_game import CardPanel
from sat_frontends.wix.quiz_game import QuizPanel
idSEND = 1
@ -118,13 +119,21 @@ class Chat(wx.Frame, QuickChat):
self.sizer.Layout()
self.Fit()
self.splitter.UpdateSize()
elif game_type=="Quiz":
debug (_("configure chat window for Quiz game"))
self.quiz_panel = QuizPanel(self, referee, players, self.nick)
self.sizer.Prepend(self.quiz_panel, 0, flag=wx.EXPAND)
self.sizer.Layout()
self.Fit()
self.splitter.UpdateSize()
def getGame(self, game_type):
"""Return class managing the game type"""
#TODO: check that the game is launched, and manage errors
if game_type=="Tarot":
return self.tarot_panel
elif game_type=="Quiz":
return self.quiz_panel
def setPresents(self, nicks):
"""Set the users presents in the contact list for a group chat

View file

@ -0,0 +1,171 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
wix: a SAT frontend
Copyright (C) 2009, 2010, 2011 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import wx
import os.path, glob
import pdb
from logging import debug, info, error
from sat.tools.jid import JID
from time import time
from math import sin, cos, pi
CARD_WIDTH = 74
CARD_HEIGHT = 136
WIDTH = 800
HEIGHT = 600
class GraphicElement():
"""This class is used to represent a card, graphically and logically"""
def __init__(self, file, x=0, y=0, zindex=10, transparent=True):
""" Image used to build the game visual
@param file: path of the PNG file
@param zindex: layer of the element (0=background; the bigger, the more in the foreground)"""
self.bitmap = wx.Image(file).ConvertToBitmap()
self.x = x
self.y = y
self.zindex = zindex
self.transparent = transparent
def __cmp__(self, other):
return self.zindex.__cmp__(other.zindex)
def draw(self, dc, x=None, y=None):
"""Draw the card on the device context
@param dc: device context
@param x: abscissa
@param y: ordinate"""
dc.DrawBitmap(self.bitmap, x or self.x, y or self.y, self.transparent)
class BaseWindow(wx.Window):
"""This is the panel where the game is drawed, under the other widgets"""
def __init__(self, parent):
wx.Window.__init__(self, parent, pos=(0,0), size=(WIDTH, HEIGHT))
self.parent = parent
self.SetMinSize(wx.Size(WIDTH, HEIGHT))
self.Bind(wx.EVT_PAINT, self.onPaint)
self.graphic_elts = {}
self.loadImages("images/quiz/")
def loadImages(self, dir):
"""Load all the images needed for the game
@param dir: directory where the PNG files are"""
for name, sub_dir, filename, x, y, zindex, transparent in [("background", "backgrounds", "blue_background.png", 0, 0, 0, False),
("joueur0", "characters/zombie", "zombie.png", 24, 170, 5, True),
("joueur1", "characters/nerd", "nerd2.png", 209, 170, 5, True),
("joueur2", "characters/zombie", "zombie.png", 392, 170, 5, True),
("joueur3", "characters/zombie", "zombie.png", 578, 170, 5, True),
("foreground", "foreground", "foreground.png", 0, 0, 10, True)]:
self.graphic_elts[name] = GraphicElement(os.path.join(dir, sub_dir, filename), x = x, y = y, zindex=zindex, transparent=transparent)
def fullPaint(self, device_context):
"""Paint all the game on the given dc
@param device_context: wx.DC"""
elements = self.graphic_elts.values()
elements.sort()
for elem in elements:
elem.draw(device_context)
#device_context.DrawArc(39,127, 39, 127,
_font = wx.Font(65, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
device_context.SetFont(_font)
device_context.SetTextForeground(wx.BLACK)
x = 100
for score in [0,1,4,9]:
device_context.DrawText("%d" % score, x, 355)
x+=184
if self.parent.time_origin:
device_context.SetPen(wx.BLACK_PEN)
radius = 20
center_x = 760
center_y = 147
origin = self.parent.time_origin
current = time()
limit = self.parent.time_limit
print "limit:", limit
total = limit - origin
left = self.parent.time_left = max(0,limit - current)
device_context.SetBrush(wx.RED_BRUSH if left/total < 1/4.0 else wx.WHITE_BRUSH)
print "left:",left
if left:
#we now draw the timer
print "total - left:", total - left
angle = ((-2*pi)*((total-left)/total) + (pi/2))
print "angle:", angle*57.3
x = center_x + radius * cos(angle)
y = center_y - radius * sin(angle)
print "x: %s, y:%s" % (x, y)
device_context.DrawArc(center_x, center_y-radius, x, y, center_x, center_y)
def onPaint(self, event):
dc = wx.PaintDC(self)
self.fullPaint(dc)
class QuizPanel(wx.Panel):
"""This class is used to display the quiz game"""
def __init__(self, parent, referee, players, player_nick):
wx.Panel.__init__(self, parent)
self.time_origin = None #set to unix time when the timer start
self.time_limit = None
self.time_left = None
self.parent = parent
self.SetMinSize(wx.Size(WIDTH, HEIGHT))
self.SetSize(wx.Size(WIDTH, HEIGHT))
self.base = BaseWindow(self)
self.question = wx.TextCtrl(self.base, -1, "", pos=(168,17), size=(613, 94), style=wx.TE_MULTILINE | wx.TE_READONLY)
self.reponse = wx.TextCtrl(self.base, -1, pos=(410,569), size=(342, 21), style=wx.TE_PROCESS_ENTER)
self.parent.host.bridge.quizGameReady(player_nick, referee, profile_key = self.parent.host.profile)
self.state = None
def startTimer(self, timer=60):
"""Start the timer to answer the question"""
def _refresh():
self.Refresh()
if self.time_left:
wx.CallLater(1000, _refresh)
self.time_left = timer
self.time_origin = time()
self.time_limit = self.time_origin + timer
_refresh()
def quizGameNew(self, data):
"""Start a new game, with given hand"""
if data.has_key('instructions'):
self.question.ChangeValue(data['instructions'])
self.Refresh()
def quizGameQuestion(self, question_id, question, timer):
"""Called when a new question is available
@param question: question to ask"""
self.question.ChangeValue(question)
self.startTimer(timer)

View file

@ -81,6 +81,15 @@ class DBusBridgeFrontend(BridgeFrontend):
def tarotGamePlayCards(self, player, referee, cards, profile_key='@DEFAULT@'):
return self.db_comm_iface.tarotGamePlayCards(player, referee, cards, profile_key)
def quizGameLaunch(self, players, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameLaunch(players, profile_key)
def quizGameCreate(self, room_jid, players, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameCreate(room_jid, players, profile_key)
def quizGameReady(self, player, referee, profile_key='@DEFAULT@'):
return self.db_comm_iface.quizGameReady(player, referee, profile_key)
def sendFile(self, to, path, profile_key='@DEFAULT@'):
return self.db_comm_iface.sendFile(to, path, profile_key)

312
src/plugins/plugin_misc_quiz.py Executable file
View file

@ -0,0 +1,312 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
SAT plugin for managing Quiz game
Copyright (C) 2009, 2010, 2011 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from logging import debug, info, warning, error
from twisted.words.xish import domish
from twisted.internet import protocol, defer, threads, reactor
from twisted.words.protocols.jabber import client, jid, xmlstream
from twisted.words.protocols.jabber import error as jab_error
from twisted.words.protocols.jabber.xmlstream import IQ
import random
from zope.interface import implements
from wokkel import disco, iwokkel, data_form
from sat.tools.xml_tools import dataForm2xml
from sat.tools.games import TarotCard
from time import time
try:
from twisted.words.protocols.xmlstream import XMPPHandler
except ImportError:
from wokkel.subprotocols import XMPPHandler
MESSAGE = '/message'
NS_QG = 'http://www.goffi.org/protocol/quiz'
QG_TAG = 'quiz'
QG_REQUEST = MESSAGE + '/' + QG_TAG + '[@xmlns="' + NS_QG + '"]'
PLUGIN_INFO = {
"name": "Quiz game plugin",
"import_name": "Quiz",
"type": "Game",
"protocols": [],
"dependencies": ["XEP-0045", "XEP-0249"],
"main": "Quiz",
"handler": "yes",
"description": _("""Implementation of Quiz game""")
}
class Quiz():
def __init__(self, host):
info(_("Plugin Quiz initialization"))
self.host = host
self.games={}
self.waiting_inv = {} #Invitation waiting for people to join to launch a game
host.bridge.addMethod("quizGameLaunch", ".communication", in_sign='ass', out_sign='', method=self.quizGameLaunch) #args: room_jid, players, profile
host.bridge.addMethod("quizGameCreate", ".communication", in_sign='sass', out_sign='', method=self.quizGameCreate) #args: room_jid, players, profile
host.bridge.addMethod("quizGameReady", ".communication", in_sign='sss', out_sign='', method=self.newPlayerReady) #args: player, referee, profile
host.bridge.addSignal("quizGameStarted", ".communication", signature='ssass') #args: room_jid, referee, players, profile
host.bridge.addSignal("quizGameNew", ".communication",
signature='sa{ss}s',
doc = { 'summary': 'Start a new game',
'param_0': "jid of game's room",
'param_1': "data of the game",
'param_2': '%(doc_profile)s'})
host.bridge.addSignal("quizGameQuestion", ".communication",
signature = 'sssis',
doc = { 'summary': "Send the current question",
'param_0': "jid of game's room",
'param_1': "question id",
'param_2': "question to ask",
'param_3': "timer",
'param_4': '%(doc_profile)s'})
host.trigger.add("MUC user joined", self.userJoinedTrigger)
def createGameElt(self, to_jid, type="normal"):
type = "normal" if to_jid.resource else "groupchat"
elt = domish.Element(('jabber:client','message'))
elt["to"] = to_jid.full()
elt["type"] = type
elt.addElement((NS_QG, QG_TAG))
return elt
def __game_data_to_xml(self, game_data):
"""Convert a game data dict to domish element"""
game_data_elt = domish.Element(('','game_data'))
for data in game_data:
data_elt = domish.Element(('',data))
data_elt.addContent(game_data[data])
game_data_elt.addChild(data_elt)
return game_data_elt
def __xml_to_game_data(self, game_data_elt):
"""Convert a domish element with game_data to a dict"""
game_data = {}
for data_elt in game_data_elt.elements():
game_data[data_elt.name] = unicode(data_elt)
return game_data
def __create_started_elt(self, players):
"""Create a game_started domish element"""
started_elt = domish.Element(('','started'))
idx = 0
for player in players:
player_elt = domish.Element(('','player'))
player_elt.addContent(player)
player_elt['index'] = str(idx)
idx+=1
started_elt.addChild(player_elt)
return started_elt
def __ask_question(self, question_id, question, timer=30):
"""Create a element for asking a question"""
question_elt = domish.Element(('','question'))
question_elt['id'] = question_id
question_elt['timer'] = str(timer)
question_elt.addContent(question)
return question_elt
def __start_play(self, room_jid, game_data, profile):
"""Start the game (tell to the first player after dealer to play"""
game_data['stage'] = "play"
next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #the player after the dealer start
game_data['first_player'] = next_player = game_data['players'][next_player_idx]
to_jid = jid.JID(room_jid.userhost()+"/"+next_player) #FIXME: gof:
mess = self.createGameElt(to_jid)
yourturn_elt = mess.firstChildElement().addElement('your_turn')
self.host.profiles[profile].xmlstream.send(mess)
def userJoinedTrigger(self, room, user, profile):
"""This trigger is used to check if we are waiting people in this room,
and to create a game if everybody is here"""
_room_jid = room.occupantJID.userhostJID()
if _room_jid in self.waiting_inv and len(room.roster) == 4:
#When we have 4 people in the room, we create the game
#TODO: check people identity
players = room.roster.keys()
del self.waiting_inv[_room_jid]
self.quizGameCreate(_room_jid.userhost(), players, profile_key=profile)
return True
def quizGameLaunch(self, players, profile_key='@DEFAULT@'):
"""Launch a game: helper method to create a room, invite players, and create the quiz game
@param players: list for players jid"""
debug(_('Launching quiz game'))
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error(_("Unknown profile"))
return
def quizRoomJoined(room):
_room = room.occupantJID.userhostJID()
for player in players:
self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Quiz"}, profile)
self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data
def after_init(ignore):
room_name = "sat_quiz_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
print "\n\n===> room_name:", room_name
muc_service = None
for service in self.host.memory.getServerServiceEntities("conference", "text", profile):
if not ".irc." in service.userhost():
#FIXME:
#This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
#use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
#to manage this, but this hack fill do it for test purpose
muc_service = service
break
if not muc_service:
error(_("Can't find a MUC service"))
return
_jid, xmlstream = self.host.getJidNStream(profile)
d = self.host.plugins["XEP-0045"].join(muc_service.userhost(), room_name, _jid.user, profile).addCallback(quizRoomJoined)
client = self.host.getClient(profile)
if not client:
error(_('No client for this profile key: %s') % profile_key)
return
client.client_initialized.addCallback(after_init)
def quizGameCreate(self, room_jid_param, players, profile_key='@DEFAULT@'):
"""Create a new game
@param room_jid_param: jid of the room
@param players: list of players nick (nick must exist in the room)
@param profile_key: %(doc_profile_key)s"""
debug (_("Creating Quiz game"))
room_jid = jid.JID(room_jid_param)
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error (_("profile %s is unknown") % profile_key)
return
if self.games.has_key(room_jid):
warning (_("Quiz game already started in room %s") % room_jid.userhost())
else:
room_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
if not room_nick:
error ('Internal error')
return
referee = room_jid.userhost() + '/' + room_nick
status = {}
players_data = {}
for player in players:
players_data[player] = {'score':0}
status[player] = "init"
self.games[room_jid.userhost()] = {'referee':referee, 'players':players, 'status':status, 'players_data':players_data, 'stage': None}
for player in players:
mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player))
mess.firstChildElement().addChild(self.__create_started_elt(players))
self.host.profiles[profile].xmlstream.send(mess)
def newPlayerReady(self, player, referee, profile_key='@DEFAULT@'):
"""Must be called when player is ready to start a new game"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error (_("profile %s is unknown") % profile_key)
return
debug ('new player ready: %s' % profile)
mess = self.createGameElt(jid.JID(referee))
ready_elt = mess.firstChildElement().addElement('player_ready')
ready_elt['player'] = player
self.host.profiles[profile].xmlstream.send(mess)
def askQuestion(self, room_jid, profile):
mess = self.createGameElt(room_jid)
mess.firstChildElement().addChild(self.__ask_question("1", u"Quel est l'âge du capitaine ?"))
self.host.profiles[profile].xmlstream.send(mess)
def newGame(self, room_jid, profile):
"""Launch a new round"""
debug (_('new Quiz game'))
game_data = self.games[room_jid.userhost()]
players = game_data['players']
players_data = game_data['players_data']
game_data['stage'] = "init"
for player in players:
players_data[player]['game_score'] = 0
new_game_data = {"instructions": _(u"""Bienvenue dans cette partie rapide de quizz, le premier à atteindre le score de 9 remporte le jeu
Attention, tu es prêt ?""")}
mess = self.createGameElt(room_jid)
mess.firstChildElement().addChild(self.__game_data_to_xml(new_game_data))
self.host.profiles[profile].xmlstream.send(mess)
reactor.callLater(10, self.askQuestion, room_jid, profile)
def quiz_game_cmd(self, mess_elt, profile):
from_jid = jid.JID(mess_elt['from'])
room_jid = jid.JID(from_jid.userhost())
game_elt = mess_elt.firstChildElement()
game_data = self.games[room_jid.userhost()]
players_data = game_data['players_data']
for elt in game_elt.elements():
if elt.name == 'started': #new game created
players = []
for player in elt.elements():
players.append(unicode(player))
self.host.bridge.quizGameStarted(room_jid.userhost(), from_jid.full(), players, profile)
elif elt.name == 'player_ready': #ready to play
player = elt['player']
status = self.games[room_jid.userhost()]['status']
nb_players = len(self.games[room_jid.userhost()]['players'])
status[player] = 'ready'
debug (_('Player %(player)s is ready to start [status: %(status)s]') % {'player':player, 'status':status})
if status.values().count('ready') == nb_players: #everybody is ready, we can start the game
self.newGame(room_jid, profile)
elif elt.name == 'game_data':
self.host.bridge.quizGameNew(room_jid.userhost(), self.__xml_to_game_data(elt), profile)
elif elt.name == 'question': #A question is asked
self.host.bridge.quizGameQuestion(room_jid.userhost(), elt["id"], unicode(elt), int(elt["timer"]), profile )
else:
error (_('Unmanaged game element: %s') % elt.name)
def getHandler(self, profile):
return QuizGameHandler(self)
class QuizGameHandler (XMPPHandler):
implements(iwokkel.IDisco)
def __init__(self, plugin_parent):
self.plugin_parent = plugin_parent
self.host = plugin_parent.host
def connectionInitialized(self):
self.xmlstream.addObserver(QG_REQUEST, self.plugin_parent.quiz_game_cmd, profile = self.parent.profile)
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
return [disco.DiscoFeature(NS_QG)]
def getDiscoItems(self, requestor, target, nodeIdentifier=''):
return []

View file

@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
"""
SAT plugin for managing xep-0045
SAT plugin for managing French Tarot game
Copyright (C) 2009, 2010, 2011 Jérôme Poisson (goffi@goffi.org)
This program is free software: you can redistribute it and/or modify