plugins room_game, quiz, radiocol, tarot: use JID instead of unicode in many methods + class attributes
This commit is contained in:
parent
d9cc2f181e
commit
5ef7999fa7
4 changed files with 265 additions and 251 deletions
|
|
@ -58,9 +58,9 @@ class Quiz(object):
|
|||
log.info(_("Plugin Quiz initialization"))
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NS_QG, QG_TAG), game_init={'stage': None}, player_init={'score': 0})
|
||||
host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("quizGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("quizGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("quizGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("quizGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("quizGameAnswer", ".plugin", in_sign='ssss', out_sign='', method=self.playerAnswer)
|
||||
host.bridge.addSignal("quizGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
host.bridge.addSignal("quizGameNew", ".plugin",
|
||||
|
|
@ -192,7 +192,7 @@ class Quiz(object):
|
|||
|
||||
def timerExpired(self, room_jid, profile):
|
||||
"""Called when nobody answered the question in time"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
game_data['stage'] = 'expired'
|
||||
mess = self.createGameElt(room_jid)
|
||||
expired_elt = mess.firstChildElement().addElement('timer_expired')
|
||||
|
|
@ -201,7 +201,7 @@ class Quiz(object):
|
|||
|
||||
def pauseTimer(self, room_jid):
|
||||
"""Stop the timer and save the time left"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
left = max(0, game_data["timer"].getTime() - time())
|
||||
game_data['timer'].cancel()
|
||||
game_data['time_left'] = int(left)
|
||||
|
|
@ -210,7 +210,7 @@ class Quiz(object):
|
|||
|
||||
def restartTimer(self, room_jid, profile):
|
||||
"""Restart a timer with the saved time"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
assert game_data['time_left'] is not None
|
||||
mess = self.createGameElt(room_jid)
|
||||
restarted_elt = mess.firstChildElement().addElement('timer_restarted')
|
||||
|
|
@ -223,7 +223,7 @@ class Quiz(object):
|
|||
|
||||
def askQuestion(self, room_jid, profile):
|
||||
"""Ask a new question"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
game_data['stage'] = "question"
|
||||
game_data['question_id'] = "1"
|
||||
timer = 30
|
||||
|
|
@ -235,7 +235,7 @@ class Quiz(object):
|
|||
|
||||
def checkAnswer(self, room_jid, player, answer, profile):
|
||||
"""Check if the answer given is right"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players_data = game_data['players_data']
|
||||
good_answer = game_data['question_id'] == "1" and answer == "42"
|
||||
players_data[player]['score'] += 1 if good_answer else -1
|
||||
|
|
@ -264,7 +264,7 @@ Attention, tu es prêt ?""")}
|
|||
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()]
|
||||
game_data = self.games[room_jid]
|
||||
if 'players_data' in game_data:
|
||||
players_data = game_data['players_data']
|
||||
|
||||
|
|
@ -278,8 +278,8 @@ Attention, tu es prêt ?""")}
|
|||
|
||||
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 = self.games[room_jid]['status']
|
||||
nb_players = len(self.games[room_jid]['players'])
|
||||
status[player] = 'ready'
|
||||
log.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
|
||||
|
|
@ -294,7 +294,7 @@ Attention, tu es prêt ?""")}
|
|||
elif elt.name == 'player_answer':
|
||||
player = elt['player']
|
||||
pause = game_data['stage'] == 'question' # we pause the game only if we are have a question at the moment
|
||||
#we first send a buzzer message
|
||||
# we first send a buzzer message
|
||||
mess = self.createGameElt(room_jid)
|
||||
buzzer_elt = mess.firstChildElement().addElement('player_buzzed')
|
||||
buzzer_elt['player'] = player
|
||||
|
|
@ -302,7 +302,7 @@ Attention, tu es prêt ?""")}
|
|||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
if pause:
|
||||
self.pauseTimer(room_jid)
|
||||
#and we send the player answer
|
||||
# and we send the player answer
|
||||
mess = self.createGameElt(room_jid)
|
||||
_answer = unicode(elt)
|
||||
say_elt = mess.firstChildElement().addElement('player_says')
|
||||
|
|
|
|||
|
|
@ -67,10 +67,10 @@ class Radiocol(object):
|
|||
log.info(_("Radio collective initialization"))
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NC_RADIOCOL, RADIOC_TAG),
|
||||
game_init={'queue': [], 'upload': True, 'playing': None, 'playing_time': 0, 'to_delete': {}})
|
||||
game_init={'queue': [], 'upload': True, 'playing': None, 'playing_time': 0, 'to_delete': {}})
|
||||
self.host = host
|
||||
host.bridge.addMethod("radiocolLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom, async=True)
|
||||
host.bridge.addMethod("radiocolCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame)
|
||||
host.bridge.addMethod("radiocolLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True)
|
||||
host.bridge.addMethod("radiocolCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame)
|
||||
host.bridge.addMethod("radiocolSongAdded", ".plugin", in_sign='sss', out_sign='', method=self.radiocolSongAdded, async=True)
|
||||
host.bridge.addSignal("radiocolPlayers", ".plugin", signature='ssass') # room_jid, referee, players, profile
|
||||
host.bridge.addSignal("radiocolStarted", ".plugin", signature='ssasais') # room_jid, referee, players, [QUEUE_TO_START, QUEUE_LIMIT], profile
|
||||
|
|
@ -96,7 +96,7 @@ class Radiocol(object):
|
|||
@param profile_key: %(doc_profile_key)s
|
||||
@return: a Deferred instance
|
||||
"""
|
||||
#XXX: this is a Q&D way for the proof of concept. In the future, the song should
|
||||
# XXX: this is a Q&D way for the proof of concept. In the future, the song should
|
||||
# be streamed to the backend using XMPP file copy
|
||||
# Here we cheat because we know we are on the same host, and we don't
|
||||
# check data. Referee will have to parse the song himself to check it
|
||||
|
|
@ -115,7 +115,7 @@ class Radiocol(object):
|
|||
else:
|
||||
song = OggVorbis(song_path)
|
||||
except (OggVorbisHeaderError, HeaderNotFoundError):
|
||||
#this file is not ogg vorbis nor mp3, we reject it
|
||||
# this file is not ogg vorbis nor mp3, we reject it
|
||||
self.deleteFile(song_path) # FIXME: same host trick (see note above)
|
||||
return defer.fail(exceptions.DataError(D_("The uploaded file has been rejected, only Ogg Vorbis and MP3 songs are accepted.")))
|
||||
|
||||
|
|
@ -125,16 +125,16 @@ class Radiocol(object):
|
|||
'album': song.get("album", ["Unknown"])[0],
|
||||
'length': str(song.info.length)
|
||||
}
|
||||
radio_data = self.games[jid.JID(referee).userhost()] # FIXME: referee comes from Libervia's client side, it's unsecure
|
||||
radio_data = self.games[jid.JID(referee).userhostJID()] # FIXME: referee comes from Libervia's client side, it's unsecure
|
||||
radio_data['to_delete'][attrs['filename']] = song_path # FIXME: works only because of the same host trick, see the note under the docstring
|
||||
return self.send(jid.JID(referee), ('', 'song_added'), attrs, profile=profile)
|
||||
|
||||
def playNext(self, room_jid, profile):
|
||||
""""Play next song in queue if exists, and put a timer
|
||||
which trigger after the song has been played to play next one"""
|
||||
#TODO: songs need to be erased once played or found invalids
|
||||
# TODO: songs need to be erased once played or found invalids
|
||||
# ==> unlink done the Q&D way with the same host trick (see above)
|
||||
radio_data = self.games[room_jid.userhost()]
|
||||
radio_data = self.games[room_jid]
|
||||
if len(radio_data['players']) == 0:
|
||||
log.debug(_('No more participants in the radiocol: cleaning data'))
|
||||
radio_data['queue'] = []
|
||||
|
|
@ -143,7 +143,7 @@ class Radiocol(object):
|
|||
radio_data['to_delete'] = {}
|
||||
queue = radio_data['queue']
|
||||
if not queue:
|
||||
#nothing left to play, we need to wait for uploads
|
||||
# nothing left to play, we need to wait for uploads
|
||||
radio_data['playing'] = None
|
||||
return
|
||||
song = queue.pop(0)
|
||||
|
|
@ -153,12 +153,12 @@ class Radiocol(object):
|
|||
radio_data['playing_time'] = time.time()
|
||||
|
||||
if not radio_data['upload'] and len(queue) < QUEUE_LIMIT:
|
||||
#upload is blocked and we now have resources to get more, we reactivate it
|
||||
# upload is blocked and we now have resources to get more, we reactivate it
|
||||
self.send(room_jid, ('', 'upload_ok'), profile=profile)
|
||||
radio_data['upload'] = True
|
||||
|
||||
reactor.callLater(length, self.playNext, room_jid, profile)
|
||||
#we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
# we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
reactor.callLater(length + 90, self.deleteFile, filename, radio_data) # FIXME: same host trick (see above)
|
||||
|
||||
def deleteFile(self, filename, radio_data=None):
|
||||
|
|
@ -185,17 +185,17 @@ class Radiocol(object):
|
|||
|
||||
def room_game_cmd(self, mess_elt, profile):
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
|
||||
room_jid = from_jid.userhostJID()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
|
||||
radio_elt = mess_elt.firstChildElement()
|
||||
radio_data = self.games[room_jid.userhost()]
|
||||
radio_data = self.games[room_jid]
|
||||
if 'queue' in radio_data:
|
||||
queue = radio_data['queue']
|
||||
|
||||
from_referee = self.isReferee(room_jid.userhost(), from_jid.resource)
|
||||
to_referee = self.isReferee(room_jid.userhost(), jid.JID(mess_elt['to']).user)
|
||||
is_player = self.isPlayer(room_jid.userhost(), nick)
|
||||
from_referee = self.isReferee(room_jid, from_jid.resource)
|
||||
to_referee = self.isReferee(room_jid, jid.JID(mess_elt['to']).user)
|
||||
is_player = self.isPlayer(room_jid, nick)
|
||||
for elt in radio_elt.elements():
|
||||
if not from_referee and not (to_referee and elt.name == 'song_added'):
|
||||
continue # sender must be referee, expect when a song is submitted
|
||||
|
|
@ -219,20 +219,20 @@ class Radiocol(object):
|
|||
elif elt.name == 'upload_ok':
|
||||
self.host.bridge.radiocolUploadOk(room_jid.userhost(), profile)
|
||||
elif elt.name == 'song_added': # a song has been added
|
||||
#FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue.
|
||||
# FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue.
|
||||
# Need to manage some sort of rules to allow peoples to send songs
|
||||
if len(queue) >= QUEUE_LIMIT:
|
||||
#there are already too many songs in queue, we reject this one
|
||||
#FIXME: add an error code
|
||||
# there are already too many songs in queue, we reject this one
|
||||
# FIXME: add an error code
|
||||
self.send(from_jid, ('', 'song_rejected'), {'reason': "Too many songs in queue"}, profile=profile)
|
||||
return
|
||||
|
||||
#The song is accepted and added in queue
|
||||
# The song is accepted and added in queue
|
||||
preload_elt = self.__create_preload_elt(from_jid.resource, elt)
|
||||
queue.append(preload_elt)
|
||||
|
||||
if len(queue) >= QUEUE_LIMIT:
|
||||
#We are at the limit, we refuse new upload until next play
|
||||
# We are at the limit, we refuse new upload until next play
|
||||
self.send(room_jid, ('', 'no_upload'), profile=profile)
|
||||
radio_data['upload'] = False
|
||||
|
||||
|
|
@ -244,8 +244,8 @@ class Radiocol(object):
|
|||
else:
|
||||
log.error(_('Unmanaged game element: %s') % elt.name)
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
game_data = self.games[room_jid_s]
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
game_data = self.games[room_jid]
|
||||
elements = []
|
||||
if game_data['playing']:
|
||||
preload = copy.deepcopy(game_data['playing'])
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ from sat.core.i18n import _
|
|||
from sat.core.constants import Const as C
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from twisted.words.protocols.jabber import jid
|
||||
from twisted.words.xish import domish
|
||||
from twisted.internet import defer
|
||||
from time import time
|
||||
|
|
@ -51,7 +51,7 @@ PLUGIN_INFO = {
|
|||
class RoomGame(object):
|
||||
"""This class is used to help launching a MUC game.
|
||||
|
||||
Bridge methods callbacks: prepareRoom, playerReady, createGame
|
||||
Bridge methods callbacks: _prepareRoom, _playerReady, _createGame
|
||||
Triggered methods: userJoinedTrigger, userLeftTrigger
|
||||
Also called from subclasses: newRound
|
||||
|
||||
|
|
@ -107,7 +107,7 @@ class RoomGame(object):
|
|||
self.game_init = game_init
|
||||
self.player_init = player_init
|
||||
self.games = {}
|
||||
self.invitations = {} # list of couple (x, y) with x the time and y a list of users
|
||||
self.invitations = {} # values are a couple (x, y) with x the time and y a list of users
|
||||
|
||||
# These are the default settings, which can be overwritten by child class after initialization
|
||||
self.invite_mode = self.FROM_PLAYERS if self.player_init == {} else self.FROM_NONE
|
||||
|
|
@ -126,129 +126,134 @@ class RoomGame(object):
|
|||
def _createOrInvite(self, room, other_players, profile):
|
||||
"""
|
||||
This is called only when someone explicitly wants to play.
|
||||
|
||||
The game will not be created if one already exists in the room,
|
||||
also its creation could be postponed until all the expected players
|
||||
join the room (in that case it will be created from userJoinedTrigger).
|
||||
@param room: instance of wokkel.muc.Room
|
||||
@param other_players: list for other players JID userhosts
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the other players JID (bare)
|
||||
"""
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
nicks = [nick]
|
||||
if self._gameExists(room_jid_s):
|
||||
if not self._checkJoinAuth(room_jid_s, user_jid.userhost(), nick):
|
||||
if self._gameExists(room_jid):
|
||||
if not self._checkJoinAuth(room_jid, user_jid, nick):
|
||||
return
|
||||
nicks.extend(self._invitePlayers(room, other_players, nick, profile))
|
||||
self._updatePlayers(room_jid_s, nicks, True, profile)
|
||||
self._updatePlayers(room_jid, nicks, True, profile)
|
||||
else:
|
||||
self._initGame(room_jid_s, nick)
|
||||
self._initGame(room_jid, nick)
|
||||
(auth, waiting, missing) = self._checkWaitAuth(room, other_players)
|
||||
nicks.extend(waiting)
|
||||
nicks.extend(self._invitePlayers(room, missing, nick, profile))
|
||||
if auth:
|
||||
self.createGame(room_jid_s, nicks, profile)
|
||||
self.createGame(room_jid, nicks, profile)
|
||||
else:
|
||||
self._updatePlayers(room_jid_s, nicks, False, profile)
|
||||
self._updatePlayers(room_jid, nicks, False, profile)
|
||||
|
||||
def _initGame(self, room_jid_s, referee_nick):
|
||||
"""Important: do not add the referee to 'players' yet. For a
|
||||
<players /> message to be emitted whenever a new player is joining,
|
||||
it is necessary to not modify 'players' outside of _updatePlayers.
|
||||
def _initGame(self, room_jid, referee_nick):
|
||||
"""
|
||||
referee = room_jid_s + '/' + referee_nick
|
||||
self.games[room_jid_s] = {'referee': referee, 'players': [], 'started': False, 'status': {}}
|
||||
self.games[room_jid_s].update(copy.deepcopy(self.game_init))
|
||||
self.invitations.setdefault(room_jid_s, [])
|
||||
|
||||
def _gameExists(self, room_jid_s, started=False):
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param referee_nick (unicode): nickname of the referee
|
||||
"""
|
||||
# Important: do not add the referee to 'players' yet. For a
|
||||
# <players /> message to be emitted whenever a new player is joining,
|
||||
# it is necessary to not modify 'players' outside of _updatePlayers.
|
||||
referee_jid = jid.JID(room_jid.userhost() + '/' + referee_nick)
|
||||
self.games[room_jid] = {'referee': referee_jid, 'players': [], 'started': False, 'status': {}}
|
||||
self.games[room_jid].update(copy.deepcopy(self.game_init))
|
||||
self.invitations.setdefault(room_jid, [])
|
||||
|
||||
def _gameExists(self, room_jid, started=False):
|
||||
"""Return True if a game has been initialized/started.
|
||||
@param started: if False, the game must be initialized to return True,
|
||||
otherwise it must be initialized and started with createGame.
|
||||
@return: True if a game is initialized/started in that room"""
|
||||
return room_jid_s in self.games and (not started or self.games[room_jid_s]['started'])
|
||||
return room_jid in self.games and (not started or self.games[room_jid]['started'])
|
||||
|
||||
def _checkJoinAuth(self, room_jid_s, user_jid_s=None, nick="", verbose=False):
|
||||
def _checkJoinAuth(self, room_jid, user_jid=None, nick="", verbose=False):
|
||||
"""Checks if this profile is allowed to join the game.
|
||||
|
||||
The parameter nick is used to check if the user is already
|
||||
a player in that game. When this method is called from
|
||||
userJoinedTrigger, nick is also used to check the user
|
||||
identity instead of user_jid_s (see TODO comment below).
|
||||
@param room_jid_s: the room hosting the game
|
||||
@param user_jid_s: JID userhost of the user
|
||||
@param nick: nick of the user
|
||||
@param room_jid (jid.JID): the JID of the room hosting the game
|
||||
@param user_jid (jid.JID): JID of the user
|
||||
@param nick (unicode): nick of the user
|
||||
@return: True if this profile can join the game
|
||||
"""
|
||||
auth = False
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
auth = False
|
||||
elif self.join_mode == self.ALL or self.isPlayer(room_jid_s, nick):
|
||||
elif self.join_mode == self.ALL or self.isPlayer(room_jid, nick):
|
||||
auth = True
|
||||
elif self.join_mode == self.INVITED:
|
||||
user_jid_s = JID(user_jid_s).userhost()
|
||||
# considering all the batches of invitations
|
||||
for invitations in self.invitations[room_jid_s]:
|
||||
if user_jid_s is not None:
|
||||
if user_jid_s in invitations[1]:
|
||||
for invitations in self.invitations[room_jid]:
|
||||
if user_jid is not None:
|
||||
if user_jid.userhostJID() in invitations[1]:
|
||||
auth = True
|
||||
break
|
||||
else:
|
||||
# TODO: that's not secure enough but what to do if
|
||||
# wokkel.muc.User's 'entity' attribute is not set?!
|
||||
if nick in [JID(invited).user for invited in invitations[1]]:
|
||||
if nick in [invited.user for invited in invitations[1]]:
|
||||
auth = True
|
||||
break
|
||||
|
||||
if not auth and (verbose or _DEBUG):
|
||||
log.debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid_s or nick, 'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid.userhost() or nick, 'game': self.name, 'room': room_jid.userhost()})
|
||||
return auth
|
||||
|
||||
def _updatePlayers(self, room_jid_s, nicks, sync, profile):
|
||||
def _updatePlayers(self, room_jid, nicks, sync, profile):
|
||||
"""Update the list of players and signal to the room that some players joined the game.
|
||||
If sync is True, the news players are synchronized with the game data they have missed.
|
||||
Remark: self.games[room_jid_s]['players'] should not be modified outside this method.
|
||||
@param room_jid_s: room userhost
|
||||
@param nicks: list of players nicks in the room (referee included, in first position)
|
||||
@param sync: set to True to send synchronization data to the new players
|
||||
@param profile
|
||||
Remark: self.games[room_jid]['players'] should not be modified outside this method.
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nicks (list[unicode]): list of players nicks in the room (referee included, in first position)
|
||||
@param sync (bool): set to True to send synchronization data to the new players
|
||||
@param profile (unicode): %(doc_profile)s
|
||||
"""
|
||||
if nicks == []:
|
||||
return
|
||||
# this is better than set(nicks).difference(...) as it keeps the order
|
||||
new_nicks = [nick for nick in nicks if nick not in self.games[room_jid_s]['players']]
|
||||
new_nicks = [nick for nick in nicks if nick not in self.games[room_jid]['players']]
|
||||
if len(new_nicks) == 0:
|
||||
return
|
||||
|
||||
def setStatus(status):
|
||||
for nick in new_nicks:
|
||||
self.games[room_jid_s]['status'][nick] = status
|
||||
self.games[room_jid]['status'][nick] = status
|
||||
|
||||
sync = sync and self._gameExists(room_jid_s, True) and len(self.games[room_jid_s]['players']) > 0
|
||||
sync = sync and self._gameExists(room_jid, True) and len(self.games[room_jid]['players']) > 0
|
||||
setStatus('desync' if sync else 'init')
|
||||
self.games[room_jid_s]['players'].extend(new_nicks)
|
||||
self._synchronizeRoom(room_jid_s, [JID(room_jid_s)], profile)
|
||||
self.games[room_jid]['players'].extend(new_nicks)
|
||||
self._synchronizeRoom(room_jid, [room_jid], profile)
|
||||
if sync:
|
||||
setStatus('init')
|
||||
|
||||
def _synchronizeRoom(self, room_jid_s, recipients, profile):
|
||||
def _synchronizeRoom(self, room_jid, recipients, profile):
|
||||
"""Communicate the list of players to the whole room or only to some users,
|
||||
also send the synchronization data to the players who recently joined the game.
|
||||
@param room_jid_s: room userhost
|
||||
@recipients: list of JIDs, the recipients of the message could be:
|
||||
- room JID
|
||||
- room JID + "/" + user nick
|
||||
@param profile
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@recipients (list[jid.JID]): list of JIDs, the recipients of the message could be:
|
||||
- room JID
|
||||
- room JID + "/" + user nick
|
||||
@param profile (unicode): %(doc_profile)s
|
||||
"""
|
||||
if self._gameExists(room_jid_s, started=True):
|
||||
element = self._createStartElement(self.games[room_jid_s]['players'])
|
||||
if self._gameExists(room_jid, started=True):
|
||||
element = self._createStartElement(self.games[room_jid]['players'])
|
||||
else:
|
||||
element = self._createStartElement(self.games[room_jid_s]['players'], name="players")
|
||||
element = self._createStartElement(self.games[room_jid]['players'], name="players")
|
||||
elements = [(element, None, None)]
|
||||
|
||||
sync_args = []
|
||||
sync_data = self._getSyncData(room_jid_s)
|
||||
sync_data = self._getSyncData(room_jid)
|
||||
for nick in sync_data:
|
||||
user_jid = JID(room_jid_s + '/' + nick)
|
||||
user_jid = jid.JID(room_jid.userhost() + '/' + nick)
|
||||
if user_jid in recipients:
|
||||
user_elements = copy.deepcopy(elements)
|
||||
for child in sync_data[nick]:
|
||||
|
|
@ -263,18 +268,18 @@ class RoomGame(object):
|
|||
for args, kwargs in sync_args:
|
||||
self._sendElements(*args, **kwargs)
|
||||
|
||||
def _getSyncData(self, room_jid_s, force_nicks=None):
|
||||
def _getSyncData(self, room_jid, force_nicks=None):
|
||||
"""The synchronization data are returned for each player who
|
||||
has the state 'desync' or if he's been contained by force_nicks.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param force_nicks: force the synchronization for this list of the nicks
|
||||
@return: a mapping between player nicks and a list of elements to
|
||||
be sent by self._synchronizeRoom for the game to be synchronized.
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return {}
|
||||
data = {}
|
||||
status = self.games[room_jid_s]['status']
|
||||
status = self.games[room_jid]['status']
|
||||
nicks = [nick for nick in status if status[nick] == 'desync']
|
||||
if force_nicks is None:
|
||||
force_nicks = []
|
||||
|
|
@ -282,14 +287,14 @@ class RoomGame(object):
|
|||
if nick not in nicks:
|
||||
nicks.append(nick)
|
||||
for nick in nicks:
|
||||
elements = self.getSyncDataForPlayer(room_jid_s, nick)
|
||||
elements = self.getSyncDataForPlayer(room_jid, nick)
|
||||
if elements:
|
||||
data[nick] = elements
|
||||
return data
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
"""This method may (and should probably) be overwritten by a child class.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: the nick of the player to be synchronized
|
||||
@return: a list of elements to synchronize this player with the game.
|
||||
"""
|
||||
|
|
@ -297,20 +302,19 @@ class RoomGame(object):
|
|||
|
||||
def _invitePlayers(self, room, other_players, nick, profile):
|
||||
"""Invite players to a room, associated game may exist or not.
|
||||
@param room: wokkel.muc.Room instance
|
||||
@param other_players: list of JID userhosts to invite
|
||||
@param nick: nick of the user who send the invitation
|
||||
@return: list of room nicks for invited players who are already in the room
|
||||
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the players to invite
|
||||
@param nick (unicode): nick of the user who send the invitation
|
||||
@return: list[unicode] of room nicks for invited players who are already in the room
|
||||
"""
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
if not self._checkInviteAuth(room_jid_s, nick):
|
||||
if not self._checkInviteAuth(room_jid, nick):
|
||||
return []
|
||||
# TODO: remove invitation waiting for too long, using the time data
|
||||
players_jids = [JID(player) for player in other_players]
|
||||
self.invitations[room_jid_s].append((time(), [player.userhost() for player in players_jids]))
|
||||
self.invitations[room_jid].append((time(), [player.userhostJID() for player in other_players]))
|
||||
nicks = []
|
||||
for player_jid in [player.userhostJID() for player in players_jids]:
|
||||
for player_jid in [player.userhostJID() for player in other_players]:
|
||||
# TODO: find a way to make it secure
|
||||
other_nick = self.host.plugins["XEP-0045"].getRoomNickOfUser(room, player_jid, secure=self.testing)
|
||||
if other_nick is None:
|
||||
|
|
@ -319,58 +323,59 @@ class RoomGame(object):
|
|||
nicks.append(other_nick)
|
||||
return nicks
|
||||
|
||||
def _checkInviteAuth(self, room_jid_s, nick, verbose=False):
|
||||
def _checkInviteAuth(self, room_jid, nick, verbose=False):
|
||||
"""Checks if this user is allowed to invite players
|
||||
@param room_jid_s: room userhost
|
||||
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: user nick in the room
|
||||
@param verbose: display debug message
|
||||
@return: True if the user is allowed to invite other players
|
||||
"""
|
||||
auth = False
|
||||
if self.invite_mode == self.FROM_ALL or not self._gameExists(room_jid_s):
|
||||
if self.invite_mode == self.FROM_ALL or not self._gameExists(room_jid):
|
||||
auth = True
|
||||
elif self.invite_mode == self.FROM_NONE:
|
||||
auth = not self._gameExists(room_jid_s, started=True) and self.isReferee(room_jid_s, nick)
|
||||
auth = not self._gameExists(room_jid, started=True) and self.isReferee(room_jid, nick)
|
||||
elif self.invite_mode == self.FROM_REFEREE:
|
||||
auth = self.isReferee(room_jid_s, nick)
|
||||
auth = self.isReferee(room_jid, nick)
|
||||
elif self.invite_mode == self.FROM_PLAYERS:
|
||||
auth = self.isPlayer(room_jid_s, nick)
|
||||
auth = self.isPlayer(room_jid, nick)
|
||||
if not auth and (verbose or _DEBUG):
|
||||
log.debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid.userhost()})
|
||||
return auth
|
||||
|
||||
def isReferee(self, room_jid_s, nick):
|
||||
def isReferee(self, room_jid, nick):
|
||||
"""Checks if the player with this nick is the referee for the game in this room"
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): room JID
|
||||
@param nick: user nick in the room
|
||||
@return: True if the user is the referee of the game in this room
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return False
|
||||
return room_jid_s + '/' + nick == self.games[room_jid_s]['referee']
|
||||
return jid.JID(room_jid.userhost() + '/' + nick) == self.games[room_jid]['referee']
|
||||
|
||||
def isPlayer(self, room_jid_s, nick):
|
||||
def isPlayer(self, room_jid, nick):
|
||||
"""Checks if the user with this nick is a player for the game in this room.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: user nick in the room
|
||||
@return: True if the user is a player of the game in this room
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return False
|
||||
# Important: the referee is not in the 'players' list right after
|
||||
# the game initialization, that's why we do also check with isReferee
|
||||
return nick in self.games[room_jid_s]['players'] or self.isReferee(room_jid_s, nick)
|
||||
return nick in self.games[room_jid]['players'] or self.isReferee(room_jid, nick)
|
||||
|
||||
def _checkWaitAuth(self, room, other_players, verbose=False):
|
||||
"""Check if we must wait for other players before starting the game.
|
||||
|
||||
@param room: wokkel.muc.Room instance
|
||||
@param other_players: list of players JID userhosts without the referee
|
||||
@param verbose: display debug message
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the players without the referee
|
||||
@param verbose (bool): display debug message
|
||||
@return: (x, y, z) with:
|
||||
x: False if we must wait, True otherwise
|
||||
y: the nicks of the players that have been checked and confirmed
|
||||
z: the players that have not been checked or that are missing
|
||||
x: False if we must wait, True otherwise
|
||||
y: the nicks of the players that have been checked and confirmed
|
||||
z: the JID of the players that have not been checked or that are missing
|
||||
"""
|
||||
if self.wait_mode == self.FOR_NONE or other_players == []:
|
||||
result = (True, [], other_players)
|
||||
|
|
@ -388,20 +393,25 @@ class RoomGame(object):
|
|||
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Generate unique room name
|
||||
|
||||
@param muc_service: you can leave empty to autofind the muc service
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
@return: a unique name for a new room to be created
|
||||
@param muc_service (jid.JID): you can leave empty to autofind the muc service
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
@return: jid.JID (unique name for a new room to be created)
|
||||
"""
|
||||
# FIXME: jid.JID must be used instead of strings
|
||||
room = self.host.plugins["XEP-0045"].getUniqueName(muc_service, profile_key=profile_key)
|
||||
return "sat_%s_%s" % (self.name.lower(), room.full())
|
||||
return jid.JID("sat_%s_%s" % (self.name.lower(), room.userhost()))
|
||||
|
||||
def prepareRoom(self, other_players=None, room_jid_s=None, profile_key=C.PROF_KEY_NONE):
|
||||
def _prepareRoom(self, other_players=None, room_jid_s='', profile_key=C.PROF_KEY_NONE):
|
||||
room_jid = jid.JID(room_jid_s) if room_jid_s else None
|
||||
other_players = [jid.JID(player).userhostJID() for player in other_players]
|
||||
return self.prepareRoom(other_players, room_jid, profile_key)
|
||||
|
||||
def prepareRoom(self, other_players=None, room_jid=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Prepare the room for a game: create it if it doesn't exist and invite players.
|
||||
|
||||
@param other_players: list for other players JID userhosts
|
||||
@param room_jid_s: JID userhost of the room, or None to generate a unique name
|
||||
@param profile_key
|
||||
@param other_players (list[JID]): list of other players JID (bare)
|
||||
@param room_jid (jid.JID): JID of the room, or None to generate a unique name
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
"""
|
||||
log.debug(_('Preparing room for %s game') % self.name)
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
|
|
@ -413,19 +423,18 @@ class RoomGame(object):
|
|||
|
||||
def roomJoined(room):
|
||||
"""@param room: instance of wokkel.muc.Room"""
|
||||
self._createOrInvite(room, [JID(player).userhost() for player in other_players], profile)
|
||||
self._createOrInvite(room, other_players, profile)
|
||||
|
||||
# Create/join the given room, or a unique generated one if no room is specified.
|
||||
if room_jid_s is not None and room_jid_s != "": # a room name has been specified
|
||||
if room_jid_s in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
roomJoined(self.host.plugins["XEP-0045"].clients[profile].joined_rooms[room_jid_s])
|
||||
return defer.succeed(None)
|
||||
if room_jid is None:
|
||||
room_jid = self.getUniqueName(profile_key=profile_key)
|
||||
else:
|
||||
room_jid_s = self.getUniqueName(profile_key=profile_key)
|
||||
if room_jid_s == "":
|
||||
if room_jid in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
roomJoined(self.host.plugins["XEP-0045"].clients[profile].joined_rooms[room_jid])
|
||||
return defer.succeed(None)
|
||||
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
d = self.host.plugins["XEP-0045"].join(JID(room_jid_s), user_jid.user, {}, profile)
|
||||
d = self.host.plugins["XEP-0045"].join(room_jid, user_jid.user, {}, profile)
|
||||
return d.addCallback(roomJoined)
|
||||
|
||||
def userJoinedTrigger(self, room, user, profile):
|
||||
|
|
@ -435,29 +444,29 @@ class RoomGame(object):
|
|||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
"""
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
profile_nick = room.occupantJID.resource
|
||||
if not self.isReferee(room_jid_s, profile_nick):
|
||||
if not self.isReferee(room_jid, profile_nick):
|
||||
return True # profile is not the referee
|
||||
if not self._checkJoinAuth(room_jid_s, user.entity.userhost() if user.entity else None, user.nick):
|
||||
if not self._checkJoinAuth(room_jid, user.entity if user.entity else None, user.nick):
|
||||
# user not allowed but let him know that we are playing :p
|
||||
self._synchronizeRoom(room_jid_s, [JID(room_jid_s + '/' + user.nick)], profile)
|
||||
self._synchronizeRoom(room_jid, [jid.JID(room_jid.userhost() + '/' + user.nick)], profile)
|
||||
return True
|
||||
if self.wait_mode == self.FOR_ALL:
|
||||
# considering the last batch of invitations
|
||||
batch = len(self.invitations[room_jid_s]) - 1
|
||||
batch = len(self.invitations[room_jid]) - 1
|
||||
if batch < 0:
|
||||
log.error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid_s))
|
||||
log.error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid.userhost()))
|
||||
return True
|
||||
other_players = self.invitations[room_jid_s][batch][1]
|
||||
other_players = self.invitations[room_jid][batch][1]
|
||||
(auth, nicks, dummy) = self._checkWaitAuth(room, other_players)
|
||||
if auth:
|
||||
del self.invitations[room_jid_s][batch]
|
||||
del self.invitations[room_jid][batch]
|
||||
nicks.insert(0, profile_nick) # add the referee
|
||||
self.createGame(room_jid_s, nicks, profile_key=profile)
|
||||
self.createGame(room_jid, nicks, profile_key=profile)
|
||||
return True
|
||||
# let the room know that a new player joined
|
||||
self._updatePlayers(room_jid_s, [user.nick], True, profile)
|
||||
self._updatePlayers(room_jid, [user.nick], True, profile)
|
||||
return True
|
||||
|
||||
def userLeftTrigger(self, room, user, profile):
|
||||
|
|
@ -467,89 +476,95 @@ class RoomGame(object):
|
|||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
"""
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
profile_nick = room.occupantJID.resource
|
||||
if not self.isReferee(room_jid_s, profile_nick):
|
||||
if not self.isReferee(room_jid, profile_nick):
|
||||
return True # profile is not the referee
|
||||
if self.isPlayer(room_jid_s, user.nick):
|
||||
if self.isPlayer(room_jid, user.nick):
|
||||
try:
|
||||
self.games[room_jid_s]['players'].remove(user.nick)
|
||||
self.games[room_jid]['players'].remove(user.nick)
|
||||
except ValueError:
|
||||
pass
|
||||
if len(self.games[room_jid_s]['players']) == 0:
|
||||
del self.games[room_jid_s] # finish the game
|
||||
if len(self.games[room_jid]['players']) == 0:
|
||||
return True
|
||||
if self.wait_mode == self.FOR_ALL:
|
||||
# allow this user to join the game again
|
||||
user_jid_s = user.entity.userhost()
|
||||
if len(self.invitations[room_jid_s]) == 0:
|
||||
self.invitations[room_jid_s].append((time(), [user_jid_s]))
|
||||
user_jid = user.entity.userhostJID()
|
||||
if len(self.invitations[room_jid]) == 0:
|
||||
self.invitations[room_jid].append((time(), [user_jid]))
|
||||
else:
|
||||
batch = 0 # add to the first batch of invitations
|
||||
if user_jid_s not in self.invitations[room_jid_s][batch][1]:
|
||||
self.invitations[room_jid_s][batch][1].append(user_jid_s)
|
||||
if user_jid not in self.invitations[room_jid][batch][1]:
|
||||
self.invitations[room_jid][batch][1].append(user_jid)
|
||||
return True
|
||||
|
||||
def _checkCreateGameAndInit(self, room_jid_s, profile):
|
||||
"""Check if that profile can create the game. If the game can be created but is not initialized yet, this method will also do the initialization.
|
||||
def _checkCreateGameAndInit(self, room_jid, profile):
|
||||
"""Check if that profile can create the game. If the game can be created
|
||||
but is not initialized yet, this method will also do the initialization.
|
||||
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param profile
|
||||
@return: a couple (create, sync) with:
|
||||
- create: set to True to allow the game creation
|
||||
- sync: set to True to advice a game synchronization
|
||||
"""
|
||||
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
if not user_nick:
|
||||
log.error('Internal error: profile %s has not joined the room %s' % (profile, room_jid_s))
|
||||
log.error('Internal error: profile %s has not joined the room %s' % (profile, room_jid.userhost()))
|
||||
return False, False
|
||||
if self._gameExists(room_jid_s):
|
||||
is_referee = self.isReferee(room_jid_s, user_nick)
|
||||
if self._gameExists(room_jid_s, started=True):
|
||||
log.warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid_s})
|
||||
if self._gameExists(room_jid):
|
||||
is_referee = self.isReferee(room_jid, user_nick)
|
||||
if self._gameExists(room_jid, started=True):
|
||||
log.warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid.userhost()})
|
||||
return False, is_referee
|
||||
elif not is_referee:
|
||||
log.warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid_s, 'user': user_nick})
|
||||
log.warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid.userhost(), 'user': user_nick})
|
||||
return False, False
|
||||
else:
|
||||
self._initGame(room_jid_s, user_nick)
|
||||
self._initGame(room_jid, user_nick)
|
||||
return True, False
|
||||
|
||||
def createGame(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
def _createGame(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
self.createGame(jid.JID(room_jid_s), nicks, profile_key)
|
||||
|
||||
def createGame(self, room_jid, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Create a new game.
|
||||
|
||||
This can be called directly from a frontend and skips all the checks and invitation system,
|
||||
but the game must not exist and all the players must be in the room already.
|
||||
@param room_jid: JID userhost of the room
|
||||
@param nicks: list of players nicks in the room (referee included, in first position)
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nicks (list[unicode]): list of players nicks in the room (referee included, in first position)
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
"""
|
||||
log.debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid})
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
log.error(_("profile %s is unknown") % profile_key)
|
||||
return
|
||||
(create, sync) = self._checkCreateGameAndInit(room_jid_s, profile)
|
||||
(create, sync) = self._checkCreateGameAndInit(room_jid, profile)
|
||||
if nicks is None:
|
||||
nicks = []
|
||||
if not create:
|
||||
if sync:
|
||||
self._updatePlayers(room_jid_s, nicks, True, profile)
|
||||
self._updatePlayers(room_jid, nicks, True, profile)
|
||||
return
|
||||
self.games[room_jid_s]['started'] = True
|
||||
self._updatePlayers(room_jid_s, nicks, False, profile)
|
||||
self.games[room_jid]['started'] = True
|
||||
self._updatePlayers(room_jid, nicks, False, profile)
|
||||
if self.player_init:
|
||||
# specific data to each player (score, private data)
|
||||
self.games[room_jid_s].setdefault('players_data', {})
|
||||
self.games[room_jid].setdefault('players_data', {})
|
||||
for nick in nicks:
|
||||
# The dict must be COPIED otherwise it is shared between all users
|
||||
self.games[room_jid_s]['players_data'][nick] = copy.deepcopy(self.player_init)
|
||||
self.games[room_jid]['players_data'][nick] = copy.deepcopy(self.player_init)
|
||||
|
||||
def playerReady(self, player, referee, profile_key=C.PROF_KEY_NONE):
|
||||
def _playerReady(self, player_nick, referee_jid_s, profile_key=C.PROF_KEY_NONE):
|
||||
self.playerReady(player_nick, jid.JID(referee_jid_s), profile_key)
|
||||
|
||||
def playerReady(self, player_nick, referee_jid, profile_key=C.PROF_KEY_NONE):
|
||||
"""Must be called when player is ready to start a new game
|
||||
|
||||
@param player: the player nick in the room
|
||||
@param referee: referee userhost
|
||||
@param referee_jid (jid.JID): JID of the referee
|
||||
"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
|
|
@ -557,7 +572,7 @@ class RoomGame(object):
|
|||
return
|
||||
log.debug('new player ready: %s' % profile)
|
||||
# TODO: we probably need to add the game and room names in the sent message
|
||||
self.send(JID(referee), 'player_ready', {'player': player}, profile=profile)
|
||||
self.send(referee_jid, 'player_ready', {'player': player_nick}, profile=profile)
|
||||
|
||||
def newRound(self, room_jid, data, profile):
|
||||
"""Launch a new round (reinit the user data)
|
||||
|
|
@ -569,7 +584,7 @@ class RoomGame(object):
|
|||
@param profile
|
||||
"""
|
||||
log.debug(_('new round for %s game') % self.name)
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players = game_data['players']
|
||||
players_data = game_data['players_data']
|
||||
game_data['stage'] = "init"
|
||||
|
|
@ -578,7 +593,7 @@ class RoomGame(object):
|
|||
|
||||
if isinstance(msg_elts, dict):
|
||||
for player in players:
|
||||
to_jid = JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
elem = msg_elts[player] if isinstance(msg_elts[player], domish.Element) else None
|
||||
self.send(to_jid, elem, profile=profile)
|
||||
elif isinstance(msg_elts, domish.Element):
|
||||
|
|
|
|||
|
|
@ -59,12 +59,12 @@ class Tarot(object):
|
|||
self._sessions = memory.Sessions()
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
|
||||
game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
|
||||
player_init={'score': 0})
|
||||
game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
|
||||
player_init={'score': 0})
|
||||
self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
|
||||
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom, async=True) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile
|
||||
host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
|
|
@ -84,7 +84,6 @@ class Tarot(object):
|
|||
self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True)
|
||||
self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
|
||||
|
||||
|
||||
def __card_list_to_xml(self, cards_list, elt_name):
|
||||
"""Convert a card list to domish element"""
|
||||
cards_list_elt = domish.Element((None, elt_name))
|
||||
|
|
@ -183,17 +182,17 @@ class Tarot(object):
|
|||
@param game_data: data of the game
|
||||
@param played: cards currently on the table
|
||||
@param winner: nick of the trick winner"""
|
||||
#TODO: manage the case where excuse is played on the last trick (and lost)
|
||||
# TODO: manage the case where excuse is played on the last trick (and lost)
|
||||
players_data = game_data['players_data']
|
||||
excuse = TarotCard(("atout", "excuse"))
|
||||
|
||||
#we first check if the Excuse was already played
|
||||
#and if somebody is waiting for a card
|
||||
# we first check if the Excuse was already played
|
||||
# and if somebody is waiting for a card
|
||||
for player in game_data['players']:
|
||||
if players_data[player]['wait_for_low']:
|
||||
#the excuse owner has to give a card to somebody
|
||||
# the excuse owner has to give a card to somebody
|
||||
if winner == player:
|
||||
#the excuse owner win the trick, we check if we have something to give
|
||||
# the excuse owner win the trick, we check if we have something to give
|
||||
for card in played:
|
||||
if card.points == 0.5:
|
||||
pl_waiting = players_data[player]['wait_for_low']
|
||||
|
|
@ -203,8 +202,8 @@ class Tarot(object):
|
|||
return
|
||||
return
|
||||
|
||||
if not excuse in played:
|
||||
#the Excuse is not on the table, nothing to do
|
||||
if excuse not in played:
|
||||
# the Excuse is not on the table, nothing to do
|
||||
return
|
||||
|
||||
excuse_player = None # Who has played the Excuse ?
|
||||
|
|
@ -216,15 +215,15 @@ class Tarot(object):
|
|||
if excuse_player == winner:
|
||||
return # the excuse player win the trick, nothing to do
|
||||
|
||||
#first we remove the excuse from played cards
|
||||
# first we remove the excuse from played cards
|
||||
played.remove(excuse)
|
||||
#then we give it back to the original owner
|
||||
# then we give it back to the original owner
|
||||
owner_levees = players_data[excuse_player]['levees']
|
||||
owner_levees.append(excuse)
|
||||
#finally we give a low card to the trick winner
|
||||
# finally we give a low card to the trick winner
|
||||
low_card = None
|
||||
#We look backward in cards won by the Excuse owner to
|
||||
#find a low value card
|
||||
# We look backward in cards won by the Excuse owner to
|
||||
# find a low value card
|
||||
for card_idx in range(len(owner_levees) - 1, -1, -1):
|
||||
if owner_levees[card_idx].points == 0.5:
|
||||
low_card = owner_levees[card_idx]
|
||||
|
|
@ -233,7 +232,7 @@ class Tarot(object):
|
|||
log.debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": excuse_player, "card_waited": low_card, "player_waiting": winner})
|
||||
break
|
||||
if not low_card: # The player has no low card yet
|
||||
#TODO: manage case when player never win a trick with low card
|
||||
# TODO: manage case when player never win a trick with low card
|
||||
players_data[excuse_player]['wait_for_low'] = winner
|
||||
log.debug(_("%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner})
|
||||
|
||||
|
|
@ -265,7 +264,7 @@ class Tarot(object):
|
|||
bouts.append(card.value)
|
||||
score += card.points
|
||||
|
||||
#We we do a basic check on score calculation
|
||||
# We do a basic check on score calculation
|
||||
check_score = 0
|
||||
defenseurs = game_data['players'][:]
|
||||
defenseurs.remove(game_data['attaquant'])
|
||||
|
|
@ -305,8 +304,8 @@ class Tarot(object):
|
|||
loosers = []
|
||||
player_score = {}
|
||||
for player in game_data['players']:
|
||||
#TODO: adjust this for 3 and 5 players variants
|
||||
#TODO: manage bonuses (petit au bout, poignée, chelem)
|
||||
# TODO: adjust this for 3 and 5 players variants
|
||||
# TODO: manage bonuses (petit au bout, poignée, chelem)
|
||||
player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3
|
||||
players_data[player]['score'] += player_score[player] # we add score of this game to the global score
|
||||
if player_score[player] > 0:
|
||||
|
|
@ -314,7 +313,7 @@ class Tarot(object):
|
|||
else:
|
||||
loosers.append(player)
|
||||
|
||||
scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'win' if victory else 'loose'}
|
||||
scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): (s)he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'wins' if victory else 'looses'}
|
||||
scores_str += '\n'
|
||||
for player in game_data['players']:
|
||||
scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': player_score[player], 'total_score': players_data[player]['score']}
|
||||
|
|
@ -332,7 +331,7 @@ class Tarot(object):
|
|||
for card in cards:
|
||||
if card.bout or card.value == "roi":
|
||||
forbidden_cards.append(card)
|
||||
#TODO: manage case where atouts (trumps) are in the dog
|
||||
# TODO: manage case where atouts (trumps) are in the dog
|
||||
elif game_data['stage'] == 'play':
|
||||
biggest_atout = None
|
||||
suit_asked = None
|
||||
|
|
@ -342,7 +341,7 @@ class Tarot(object):
|
|||
current_idx = game_data['current_player']
|
||||
current_player = players[current_idx]
|
||||
if idx == current_idx:
|
||||
#the player is the first to play, he can play what he wants
|
||||
# the player is the first to play, he can play what he wants
|
||||
return forbidden_cards
|
||||
while (idx != current_idx):
|
||||
player = players[idx]
|
||||
|
|
@ -398,13 +397,13 @@ class Tarot(object):
|
|||
# TODO: send error dialog
|
||||
return defer.succeed({})
|
||||
|
||||
room_jid_s = session_data['room_jid'].userhost()
|
||||
referee = self.games[room_jid_s]['referee']
|
||||
player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
room_jid = session_data['room_jid']
|
||||
referee_jid = self.games[room_jid]['referee']
|
||||
player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
data = xml_tools.XMLUIResult2DataFormResult(raw_data)
|
||||
contrat = data['contrat']
|
||||
log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
|
||||
d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
|
||||
d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
|
||||
d.addCallback(lambda ignore: {})
|
||||
del self._sessions[raw_data["session_id"]]
|
||||
return d
|
||||
|
|
@ -443,7 +442,7 @@ class Tarot(object):
|
|||
self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
|
||||
|
||||
def newRound(self, room_jid, profile):
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players = game_data['players']
|
||||
game_data['first_player'] = None # first player for the current trick
|
||||
game_data['contrat'] = None
|
||||
|
|
@ -480,11 +479,11 @@ class Tarot(object):
|
|||
"""
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
|
||||
game_elt = mess_elt.firstChildElement()
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
is_player = self.isPlayer(room_jid.userhost(), nick)
|
||||
game_data = self.games[room_jid]
|
||||
is_player = self.isPlayer(room_jid, nick)
|
||||
if 'players_data' in game_data:
|
||||
players_data = game_data['players_data']
|
||||
|
||||
|
|
@ -501,8 +500,8 @@ class Tarot(object):
|
|||
|
||||
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 = self.games[room_jid]['status']
|
||||
nb_players = len(self.games[room_jid]['players'])
|
||||
status[player] = 'ready'
|
||||
log.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
|
||||
|
|
@ -519,13 +518,13 @@ class Tarot(object):
|
|||
self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
|
||||
|
||||
elif elt.name == 'contrat_choosed':
|
||||
#TODO: check we receive the contrat from the right person
|
||||
#TODO: use proper XEP-0004 way for answering form
|
||||
# TODO: check we receive the contrat from the right person
|
||||
# TODO: use proper XEP-0004 way for answering form
|
||||
player = elt['player']
|
||||
players_data[player]['contrat'] = unicode(elt)
|
||||
contrats = [players_data[player]['contrat'] for player in game_data['players']]
|
||||
if contrats.count(None):
|
||||
#not everybody has choosed his contrat, it's next one turn
|
||||
# not everybody has choosed his contrat, it's next one turn
|
||||
player = self.__next_player(game_data)
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
self.send(to_jid, self.__ask_contrat(), profile=profile)
|
||||
|
|
@ -553,16 +552,16 @@ class Tarot(object):
|
|||
self.__start_play(room_jid, game_data, profile)
|
||||
game_data['attaquant'] = best_contrat[0]
|
||||
else:
|
||||
#Time to show the chien to everybody
|
||||
# Time to show the chien to everybody
|
||||
to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
|
||||
elem = self.__card_list_to_xml(game_data['chien'], 'chien')
|
||||
self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile)
|
||||
#the attacker (attaquant) get the chien
|
||||
# the attacker (attaquant) get the chien
|
||||
game_data['hand'][best_contrat[0]].extend(game_data['chien'])
|
||||
del game_data['chien'][:]
|
||||
|
||||
if game_data['contrat'] == "Garde Sans":
|
||||
#The chien go into attaquant's (attacker) levees
|
||||
# The chien go into attaquant's (attacker) levees
|
||||
players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
|
||||
del game_data['chien'][:]
|
||||
|
||||
|
|
@ -575,17 +574,17 @@ class Tarot(object):
|
|||
|
||||
elif elt.name == 'cards_played':
|
||||
if game_data['stage'] == "ecart":
|
||||
#TODO: show atouts (trumps) if player put some in écart
|
||||
# TODO: show atouts (trumps) if player put some in écart
|
||||
assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here
|
||||
list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
|
||||
#we now check validity of card
|
||||
# we now check validity of card
|
||||
invalid_cards = self.__invalid_cards(game_data, list_cards)
|
||||
if invalid_cards:
|
||||
elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])
|
||||
self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile)
|
||||
return
|
||||
|
||||
#FIXME: gof: manage Garde Sans & Garde Contre cases
|
||||
# FIXME: gof: manage Garde Sans & Garde Contre cases
|
||||
players_data[elt['player']]['levees'].extend(list_cards) # we add the chien to attaquant's levées
|
||||
for card in list_cards:
|
||||
game_data['hand'][elt['player']].remove(card)
|
||||
|
|
@ -599,46 +598,46 @@ class Tarot(object):
|
|||
if mess_elt['type'] == 'groupchat':
|
||||
self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
|
||||
else:
|
||||
#we first check validity of card
|
||||
# we first check validity of card
|
||||
invalid_cards = self.__invalid_cards(game_data, cards)
|
||||
if invalid_cards:
|
||||
elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage'])
|
||||
self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile)
|
||||
return
|
||||
#the card played is ok, we forward it to everybody
|
||||
#first we remove it from the hand and put in on the table
|
||||
# the card played is ok, we forward it to everybody
|
||||
# first we remove it from the hand and put in on the table
|
||||
game_data['hand'][current_player].remove(cards[0])
|
||||
players_data[current_player]['played'] = cards[0]
|
||||
|
||||
#then we forward the message
|
||||
# then we forward the message
|
||||
self.send(room_jid, elt, profile=profile)
|
||||
|
||||
#Did everybody played ?
|
||||
# Did everybody played ?
|
||||
played = [players_data[player]['played'] for player in game_data['players']]
|
||||
if all(played):
|
||||
#everybody has played
|
||||
# everybody has played
|
||||
winner = self.__winner(game_data)
|
||||
log.debug(_('The winner of this trick is %s') % winner)
|
||||
#the winner win the trick
|
||||
# the winner win the trick
|
||||
self.__excuse_hack(game_data, played, winner)
|
||||
players_data[elt['player']]['levees'].extend(played)
|
||||
#nothing left on the table
|
||||
# nothing left on the table
|
||||
for player in game_data['players']:
|
||||
players_data[player]['played'] = None
|
||||
if len(game_data['hand'][current_player]) == 0:
|
||||
#no card lef: the game is finished
|
||||
# no card left: the game is finished
|
||||
elem = self.__give_scores(*self.__calculate_scores(game_data))
|
||||
self.send(room_jid, elem, profile=profile)
|
||||
game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
|
||||
for player in game_data['players']:
|
||||
game_data['status'][player] = "init"
|
||||
return
|
||||
#next player is the winner
|
||||
# next player is the winner
|
||||
next_player = game_data['first_player'] = self.__next_player(game_data, winner)
|
||||
else:
|
||||
next_player = self.__next_player(game_data)
|
||||
|
||||
#finally, we tell to the next player to play
|
||||
# finally, we tell to the next player to play
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
|
||||
self.send(to_jid, 'your_turn', profile=profile)
|
||||
|
||||
|
|
@ -668,5 +667,5 @@ class Tarot(object):
|
|||
else:
|
||||
log.error(_('Unmanaged card game element: %s') % elt.name)
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
return []
|
||||
|
|
|
|||
Loading…
Reference in a new issue