Fix pep8 support in src/plugins.

This commit is contained in:
Emmanuel Gil Peyrot 2013-01-18 17:55:35 +01:00
commit 0dca274360

View file

@ -43,14 +43,14 @@ CG_TAG = 'card_game'
CG_REQUEST = MESSAGE + '/' + CG_TAG + '[@xmlns="' + NS_CG + '"]'
PLUGIN_INFO = {
"name": "Tarot cards plugin",
"import_name": "Tarot",
"type": "Misc",
"protocols": [],
"dependencies": ["XEP-0045", "XEP-0249"],
"main": "Tarot",
"handler": "yes",
"description": _("""Implementation of Tarot card game""")
"name": "Tarot cards plugin",
"import_name": "Tarot",
"type": "Misc",
"protocols": [],
"dependencies": ["XEP-0045", "XEP-0249"],
"main": "Tarot",
"handler": "yes",
"description": _("""Implementation of Tarot card game""")
}
@ -59,33 +59,33 @@ class Tarot(object):
def __init__(self, host):
info(_("Plugin Tarot initialization"))
self.host = host
self.games={}
self.waiting_inv = {} #Invitation waiting for people to join to launch a game
self.games = {}
self.waiting_inv = {} # Invitation waiting for people to join to launch a game
self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='ass', out_sign='', method=self.launchGame) #args: room_jid, players, 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.newPlayerReady) #args: player, referee, profile
host.bridge.addMethod("tarotGameContratChoosed", ".plugin", in_sign='ssss', out_sign='', method=self.contratChoosed) #args: player, referee, contrat, 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("tarotGameStarted", ".plugin", signature='ssass') #args: room_jid, referee, players, profile
host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') #args: room_jid, hand, profile
host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') #args: room_jid, xml_data, profile
host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') #args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile
host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') #args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile
host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') #args: room_jid, profile
host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') #args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='ass', out_sign='', method=self.launchGame) # args: room_jid, players, 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.newPlayerReady) # args: player, referee, profile
host.bridge.addMethod("tarotGameContratChoosed", ".plugin", in_sign='ssss', out_sign='', method=self.contratChoosed) # args: player, referee, contrat, 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("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
host.bridge.addSignal("tarotGameNew", ".plugin", signature='sa(ss)s') # args: room_jid, hand, profile
host.bridge.addSignal("tarotGameChooseContrat", ".plugin", signature='sss') # args: room_jid, xml_data, profile
host.bridge.addSignal("tarotGameShowCards", ".plugin", signature='ssa(ss)a{ss}s') # args: room_jid, type ["chien", "poignée",...], cards, data[dict], profile
host.bridge.addSignal("tarotGameCardsPlayed", ".plugin", signature='ssa(ss)s') # args: room_jid, player, type ["chien", "poignée",...], cards, data[dict], profile
host.bridge.addSignal("tarotGameYourTurn", ".plugin", signature='ss') # args: room_jid, profile
host.bridge.addSignal("tarotGameScore", ".plugin", signature='ssasass') # args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
host.bridge.addSignal("tarotGameInvalidCards", ".plugin", signature='ssa(ss)a(ss)s') # args: room_jid, game phase, played_cards, invalid_cards, profile
host.trigger.add("MUC user joined", self.userJoinedTrigger)
self.deck_ordered = []
for value in ['excuse']+map(str,range(1,22)):
self.deck_ordered.append(TarotCard(("atout",value)))
for value in ['excuse'] + map(str, range(1, 22)):
self.deck_ordered.append(TarotCard(("atout", value)))
for suit in ["pique", "coeur", "carreau", "trefle"]:
for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]:
for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
self.deck_ordered.append(TarotCard((suit, value)))
def createGameElt(self, to_jid, type="normal"):
type = "normal" if to_jid.resource else "groupchat"
elt = domish.Element((None,'message'))
elt = domish.Element((None, 'message'))
elt["to"] = to_jid.full()
elt["type"] = type
elt.addElement((NS_CG, CG_TAG))
@ -93,9 +93,9 @@ class Tarot(object):
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))
cards_list_elt = domish.Element((None, elt_name))
for card in cards_list:
card_elt = domish.Element((None,'card'))
card_elt = domish.Element((None, 'card'))
card_elt['suit'] = card.suit
card_elt['value'] = card.value
cards_list_elt.addChild(card_elt)
@ -108,22 +108,21 @@ class Tarot(object):
cards_list.append((card['suit'], card['value']))
return cards_list
def __create_started_elt(self, players):
"""Create a game_started domish element"""
started_elt = domish.Element((None,'started'))
started_elt = domish.Element((None, 'started'))
idx = 0
for player in players:
player_elt = domish.Element((None,'player'))
player_elt = domish.Element((None, 'player'))
player_elt.addContent(player)
player_elt['index'] = str(idx)
idx+=1
idx += 1
started_elt.addChild(player_elt)
return started_elt
def __ask_contrat(self):
"""Create a element for asking contrat"""
contrat_elt = domish.Element((None,'contrat'))
contrat_elt = domish.Element((None, 'contrat'))
form = data_form.Form('form', title=_('contrat selection'))
field = data_form.Field('list-single', 'contrat', options=map(data_form.Option, self.contrats), required=True)
form.addField(field)
@ -136,18 +135,18 @@ class Tarot(object):
@param winners: list of unicode nicks of winners
@param loosers: list of unicode nicks of loosers"""
score_elt = domish.Element((None,'score'))
score_elt = domish.Element((None, 'score'))
form = data_form.Form('form', title=_('scores'))
for line in scores.split('\n'):
field = data_form.Field('fixed', value = line)
field = data_form.Field('fixed', value=line)
form.addField(field)
score_elt.addChild(form.toElement())
for winner in winners:
winner_elt = domish.Element((None,'winner'))
winner_elt = domish.Element((None, 'winner'))
winner_elt.addContent(winner)
score_elt.addChild(winner_elt)
for looser in loosers:
looser_elt = domish.Element((None,'looser'))
looser_elt = domish.Element((None, 'looser'))
looser_elt.addContent(looser)
score_elt.addChild(looser_elt)
return score_elt
@ -156,7 +155,7 @@ class Tarot(object):
"""Create a element for invalid_cards error
@param list_cards: list of Card
@param game_phase: phase of the game ['ecart', 'play']"""
error_elt = domish.Element((None,'error'))
error_elt = domish.Element((None, 'error'))
played_elt = self.__card_list_to_xml(played_cards, 'played')
invalid_elt = self.__card_list_to_xml(invalid_cards, 'invalid')
error_elt['type'] = 'invalid_cards'
@ -165,7 +164,7 @@ class Tarot(object):
error_elt.addChild(invalid_elt)
return error_elt
def __next_player(self, game_data, next_pl = None):
def __next_player(self, game_data, next_pl=None):
"""Increment player number & return player name
@param next_pl: if given, then next_player is forced to this one
"""
@ -189,7 +188,7 @@ class Tarot(object):
card = players_data[player]['played']
if card.value == "excuse":
continue
if suit_asked == None:
if suit_asked is None:
suit_asked = card.suit
if (card.suit == suit_asked or card.suit == "atout") and card > strongest:
strongest = card
@ -204,7 +203,7 @@ class Tarot(object):
@param winner: nick of the trick winner"""
#TODO: manage the case where excuse is played on the last trick (and lost)
players_data = game_data['players_data']
excuse = TarotCard(("atout","excuse"))
excuse = TarotCard(("atout", "excuse"))
#we first check if the Excuse was already played
#and if somebody is waiting for a card
@ -218,7 +217,7 @@ class Tarot(object):
pl_waiting = players_data[player]['wait_for_low']
played.remove(card)
players_data[pl_waiting]['levees'].append(card)
debug (_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner":player, "card_waited": card, "player_waiting":pl_waiting})
debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": player, "card_waited": card, "player_waiting": pl_waiting})
return
return
@ -226,14 +225,14 @@ class Tarot(object):
#the Excuse is not on the table, nothing to do
return
excuse_player = None #Who has played the Excuse ?
excuse_player = None # Who has played the Excuse ?
for player in game_data['players']:
if players_data[player]['played'] == excuse:
excuse_player = player
break
if excuse_player == winner:
return #the excuse player win the trick, nothing to do
return # the excuse player win the trick, nothing to do
#first we remove the excuse from played cards
played.remove(excuse)
@ -244,18 +243,17 @@ class Tarot(object):
low_card = None
#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):
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]
del owner_levees[card_idx]
players_data[winner]['levees'].append(low_card)
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})
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
if not low_card: # The player has no low card yet
#TODO: manage case when player never win a trick with low card
players_data[excuse_player]['wait_for_low'] = winner
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})
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})
def __draw_game(self, game_data):
"""The game is draw, no score change
@ -263,14 +261,13 @@ class Tarot(object):
@return: tuple with (string victory message, list of winners, list of loosers)"""
players_data = game_data['players_data']
scores_str = _('Draw game')
scores_str+='\n'
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':0, 'total_score': players_data[player]['score']}
scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': 0, 'total_score': players_data[player]['score']}
debug(scores_str)
return (scores_str, [], [])
def __calculate_scores(self, game_data):
"""The game is finished, time to know who won :)
@param game_data: data of the game
@ -282,7 +279,7 @@ class Tarot(object):
bouts = []
for card in levees:
if card.bout:
nb_bouts +=1
nb_bouts += 1
bouts.append(card.value)
score += card.points
@ -292,10 +289,10 @@ class Tarot(object):
defenseurs.remove(game_data['attaquant'])
for defenseur in defenseurs:
for card in players_data[defenseur]['levees']:
check_score+=card.points
check_score += card.points
if game_data['contrat'] == "Garde Contre":
for card in game_data['chien']:
check_score+=card.points
check_score += card.points
assert (score + check_score == 91)
point_limit = None
@ -329,16 +326,16 @@ class Tarot(object):
#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
players_data[player]['score'] += player_score[player] # we add score of this game to the global score
if player_score[player] > 0:
winners.append(player)
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+='\n'
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 += '\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']}
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']}
debug(scores_str)
return (scores_str, winners, loosers)
@ -351,7 +348,7 @@ class Tarot(object):
forbidden_cards = []
if game_data['stage'] == 'ecart':
for card in cards:
if card.bout or card.value=="roi":
if card.bout or card.value == "roi":
forbidden_cards.append(card)
#TODO: manage case where atouts (trumps) are in the dog
elif game_data['stage'] == 'play':
@ -373,7 +370,7 @@ class Tarot(object):
if played_card.suit == "atout" and played_card > biggest_atout:
biggest_atout = played_card
idx = (idx + 1) % len(players)
has_suit = False #True if there is one card of the asked suit in the hand of the player
has_suit = False # True if there is one card of the asked suit in the hand of the player
has_atout = False
biggest_hand_atout = None
@ -399,18 +396,16 @@ class Tarot(object):
error(_('Internal error: unmanaged game stage'))
return forbidden_cards
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
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:
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"""
@ -435,8 +430,8 @@ class Tarot(object):
def tarotRoomJoined(room):
_room = room.occupantJID.userhostJID()
for player in players:
self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game":"Tarot"}, profile)
self.waiting_inv[_room] = (time(), players) #TODO: remove invitation waiting for too long, using the time data
self.host.plugins["XEP-0249"].invite(jid.JID(player), room.occupantJID.userhostJID(), {"game": "Tarot"}, 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_tarot_%s" % self.host.plugins["XEP-0045"].getUniqueName(profile_key)
@ -464,36 +459,33 @@ class Tarot(object):
return
client.client_initialized.addCallback(after_init)
def createGame(self, room_jid_param, players, profile_key='@NONE@'):
"""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 Tarot game"))
debug(_("Creating Tarot 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)
error(_("profile %s is unknown") % profile_key)
return
if self.games.has_key(room_jid):
warning (_("Tarot game already started in room %s") % room_jid.userhost())
if room_jid in self.games:
warning(_("Tarot 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')
error('Internal error')
return
referee = room_jid.userhost() + '/' + room_nick
status = {}
players_data = {}
for player in players:
players_data[player] = {'score':0}
players_data[player] = {'score': 0}
status[player] = "init"
self.games[room_jid.userhost()] = {'referee':referee, 'players':players, 'status':status, 'players_data':players_data, 'hand_size':18, 'init_player':0, 'current_player': None, 'contrat': None, 'stage': None}
self.games[room_jid.userhost()] = {'referee': referee, 'players': players, 'status': status, 'players_data': players_data, 'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}
for player in players:
mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+player))
mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + player))
mess.firstChildElement().addChild(self.__create_started_elt(players))
self.host.profiles[profile].xmlstream.send(mess)
@ -501,9 +493,9 @@ class Tarot(object):
"""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)
error(_("profile %s is unknown") % profile_key)
return
debug ('new player ready: %s' % profile)
debug('new player ready: %s' % profile)
mess = self.createGameElt(jid.JID(referee))
ready_elt = mess.firstChildElement().addElement('player_ready')
ready_elt['player'] = player
@ -518,11 +510,11 @@ class Tarot(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error (_("profile %s is unknown") % profile_key)
error(_("profile %s is unknown") % profile_key)
return
debug (_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat':contrat, 'profile':profile})
debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
mess = self.createGameElt(jid.JID(referee))
contrat_elt = mess.firstChildElement().addElement(('','contrat_choosed'), content=contrat)
contrat_elt = mess.firstChildElement().addElement(('', 'contrat_choosed'), content=contrat)
contrat_elt['player'] = player
self.host.profiles[profile].xmlstream.send(mess)
@ -535,9 +527,9 @@ class Tarot(object):
"""
profile = self.host.memory.getProfileName(profile_key)
if not profile:
error (_("profile %s is unknown") % profile_key)
error(_("profile %s is unknown") % profile_key)
return
debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards})
debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
mess = self.createGameElt(jid.JID(referee))
playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played'))
playcard_elt['player'] = player
@ -545,7 +537,7 @@ class Tarot(object):
def newGame(self, room_jid, profile):
"""Launch a new round"""
debug (_('new Tarot game'))
debug(_('new Tarot game'))
deck = self.deck_ordered[:]
random.shuffle(deck)
game_data = self.games[room_jid.userhost()]
@ -553,7 +545,7 @@ class Tarot(object):
players_data = game_data['players_data']
current_player = game_data['current_player']
game_data['stage'] = "init"
game_data['first_player'] = None #first player for the current trick
game_data['first_player'] = None # first player for the current trick
game_data['contrat'] = None
hand = game_data['hand'] = {}
hand_size = game_data['hand_size']
@ -565,23 +557,22 @@ class Tarot(object):
del(deck[:])
for player in players:
to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
mess = self.createGameElt(to_jid)
mess.firstChildElement().addChild(self.__card_list_to_xml(hand[player], 'hand'))
self.host.profiles[profile].xmlstream.send(mess)
players_data[player]['contrat'] = None
players_data[player]['levees'] = [] #cards won
players_data[player]['played'] = None #card on the table
players_data[player]['wait_for_low'] = None #Used when a player wait for a low card because of excuse
players_data[player]['levees'] = [] # cards won
players_data[player]['played'] = None # card on the table
players_data[player]['wait_for_low'] = None # Used when a player wait for a low card because of excuse
pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) #the player after the dealer start
pl_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(players) # the player after the dealer start
player = players[pl_idx]
to_jid = jid.JID(room_jid.userhost()+"/"+player) #FIXME: gof:
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
mess = self.createGameElt(to_jid)
mess.firstChildElement().addChild(self.__ask_contrat())
self.host.profiles[profile].xmlstream.send(mess)
def card_game_cmd(self, mess_elt, profile):
from_jid = jid.JID(mess_elt['from'])
room_jid = jid.JID(from_jid.userhost())
@ -591,25 +582,25 @@ class Tarot(object):
for elt in game_elt.elements():
if elt.name == 'started': #new game created
if elt.name == 'started': # new game created
players = []
for player in elt.elements():
players.append(unicode(player))
self.host.bridge.tarotGameStarted(room_jid.userhost(), from_jid.full(), players, profile)
elif elt.name == 'player_ready': #ready to play
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
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 == 'hand': #a new hand has been received
elif elt.name == 'hand': # a new hand has been received
self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile)
elif elt.name == 'contrat': #it's time to choose contrat
elif elt.name == 'contrat': # it's time to choose contrat
form = data_form.Form.fromElement(elt.firstChildElement())
xml_data = dataForm2xml(form)
self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
@ -623,7 +614,7 @@ class Tarot(object):
if contrats.count(None):
#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:
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
mess = self.createGameElt(to_jid)
mess.firstChildElement().addChild(self.__ask_contrat())
self.host.profiles[profile].xmlstream.send(mess)
@ -642,11 +633,11 @@ class Tarot(object):
mess = self.createGameElt(to_jid)
mess.firstChildElement().addChild(self.__give_scores(*self.__draw_game(game_data)))
self.host.profiles[profile].xmlstream.send(mess)
game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #we change the dealer
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
debug (_("%(player)s win the bid with %(contrat)s") % {'player':best_contrat[0],'contrat':best_contrat[1]})
debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]})
game_data['contrat'] = best_contrat[1]
if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
@ -654,7 +645,7 @@ class Tarot(object):
game_data['attaquant'] = best_contrat[0]
else:
#Time to show the chien to everybody
to_jid = jid.JID(room_jid.userhost()) #FIXME: gof:
to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
mess = self.createGameElt(to_jid)
chien_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(game_data['chien'], 'chien'))
chien_elt['attaquant'] = best_contrat[0]
@ -668,10 +659,9 @@ class Tarot(object):
players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
del game_data['chien'][:]
elif elt.name == 'chien': #we have received the chien
debug (_("tarot: chien received"))
data = {"attaquant":elt['attaquant']}
elif elt.name == 'chien': # we have received the chien
debug(_("tarot: chien received"))
data = {"attaquant": elt['attaquant']}
game_data['stage'] = "ecart"
game_data['attaquant'] = elt['attaquant']
self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile)
@ -679,18 +669,18 @@ class Tarot(object):
elif elt.name == 'cards_played':
if game_data['stage'] == "ecart":
#TODO: show atouts (trumps) if player put some in écart
assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here
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
invalid_cards = self.__invalid_cards(game_data, list_cards)
if invalid_cards:
mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+elt['player']))
mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + elt['player']))
mess.firstChildElement().addChild(self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']))
self.host.profiles[profile].xmlstream.send(mess)
return
#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
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)
@ -706,7 +696,7 @@ class Tarot(object):
#we first check validity of card
invalid_cards = self.__invalid_cards(game_data, cards)
if invalid_cards:
mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+current_player))
mess = self.createGameElt(jid.JID(room_jid.userhost() + '/' + current_player))
mess.firstChildElement().addChild(self.__invalid_cards_elt(cards, invalid_cards, game_data['stage']))
self.host.profiles[profile].xmlstream.send(mess)
return
@ -725,7 +715,7 @@ class Tarot(object):
if all(played):
#everybody has played
winner = self.__winner(game_data)
debug (_('The winner of this trick is %s') % winner)
debug(_('The winner of this trick is %s') % winner)
#the winner win the trick
self.__excuse_hack(game_data, played, winner)
players_data[elt['player']]['levees'].extend(played)
@ -738,7 +728,7 @@ class Tarot(object):
mess = self.createGameElt(to_jid)
chien_elt = mess.firstChildElement().addChild(self.__give_scores(*self.__calculate_scores(game_data)))
self.host.profiles[profile].xmlstream.send(mess)
game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) #we change the dealer
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
@ -748,7 +738,7 @@ class Tarot(object):
next_player = self.__next_player(game_data)
#finally, we tell to the next player to play
to_jid = jid.JID(room_jid.userhost()+"/"+next_player)
to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
mess = self.createGameElt(to_jid)
yourturn_elt = mess.firstChildElement().addElement('your_turn')
self.host.profiles[profile].xmlstream.send(mess)
@ -757,7 +747,7 @@ class Tarot(object):
self.host.bridge.tarotGameYourTurn(room_jid.userhost(), profile)
elif elt.name == 'score':
form_elt = elt.elements(name='x',uri='jabber:x:data').next()
form_elt = elt.elements(name='x', uri='jabber:x:data').next()
winners = []
loosers = []
for winner in elt.elements(name='winner', uri=NS_CG):
@ -769,16 +759,17 @@ class Tarot(object):
self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile)
elif elt.name == 'error':
if elt['type'] == 'invalid_cards':
played_cards = self.__xml_to_list(elt.elements(name='played',uri=NS_CG).next())
invalid_cards = self.__xml_to_list(elt.elements(name='invalid',uri=NS_CG).next())
played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next())
invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next())
self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile)
else:
error (_('Unmanaged error type: %s') % elt['type'])
error(_('Unmanaged error type: %s') % elt['type'])
else:
error (_('Unmanaged card game element: %s') % elt.name)
error(_('Unmanaged card game element: %s') % elt.name)
def getHandler(self, profile):
return CardGameHandler(self)
return CardGameHandler(self)
class CardGameHandler (XMPPHandler):
implements(iwokkel.IDisco)
@ -788,11 +779,10 @@ class CardGameHandler (XMPPHandler):
self.host = plugin_parent.host
def connectionInitialized(self):
self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile = self.parent.profile)
self.xmlstream.addObserver(CG_REQUEST, self.plugin_parent.card_game_cmd, profile=self.parent.profile)
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
return [disco.DiscoFeature(NS_CG)]
def getDiscoItems(self, requestor, target, nodeIdentifier=''):
return []