comparison src/plugins/plugin_misc_tarot.py @ 993:301b342c697a

core: use of the new core.log module: /!\ this is a massive refactoring and was largely automated, it probably did bring some bugs /!\
author Goffi <goffi@goffi.org>
date Sat, 19 Apr 2014 19:19:19 +0200
parents 1a759096ccbd
children 83ed877541e3
comparison
equal deleted inserted replaced
992:f51a1895275c 993:301b342c697a
17 # You should have received a copy of the GNU Affero General Public License 17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 from sat.core.i18n import _ 20 from sat.core.i18n import _
21 from sat.core.constants import Const as C 21 from sat.core.constants import Const as C
22 from logging import debug, info, warning, error 22 from sat.core.log import getLogger
23 log = getLogger(__name__)
23 from twisted.words.xish import domish 24 from twisted.words.xish import domish
24 from twisted.words.protocols.jabber import jid 25 from twisted.words.protocols.jabber import jid
25 from twisted.internet import defer 26 from twisted.internet import defer
26 from wokkel import data_form 27 from wokkel import data_form
27 28
28 from sat.memory import memory 29 from sat.memory import memory
29 from sat.tools import xml_tools 30 from sat.tools import xml_tools
30 from sat_frontends.tools.games import TarotCard 31 from sat_frontends.tools.games import TarotCard
31 from time import time
32 import random 32 import random
33 33
34 34
35 NS_CG = 'http://www.goffi.org/protocol/card_game' 35 NS_CG = 'http://www.goffi.org/protocol/card_game'
36 CG_TAG = 'card_game' 36 CG_TAG = 'card_game'
53 global RoomGame 53 global RoomGame
54 RoomGame = host.plugins["ROOM-GAME"].__class__ 54 RoomGame = host.plugins["ROOM-GAME"].__class__
55 self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {}) 55 self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {})
56 56
57 def __init__(self, host): 57 def __init__(self, host):
58 info(_("Plugin Tarot initialization")) 58 log.info(_("Plugin Tarot initialization"))
59 self._sessions = memory.Sessions() 59 self._sessions = memory.Sessions()
60 self.inheritFromRoomGame(host) 60 self.inheritFromRoomGame(host)
61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG), 61 RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None}, 62 game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
63 player_init={'score': 0}) 63 player_init={'score': 0})
197 for card in played: 197 for card in played:
198 if card.points == 0.5: 198 if card.points == 0.5:
199 pl_waiting = players_data[player]['wait_for_low'] 199 pl_waiting = players_data[player]['wait_for_low']
200 played.remove(card) 200 played.remove(card)
201 players_data[pl_waiting]['levees'].append(card) 201 players_data[pl_waiting]['levees'].append(card)
202 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}) 202 log.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})
203 return 203 return
204 return 204 return
205 205
206 if not excuse in played: 206 if not excuse in played:
207 #the Excuse is not on the table, nothing to do 207 #the Excuse is not on the table, nothing to do
228 for card_idx in range(len(owner_levees) - 1, -1, -1): 228 for card_idx in range(len(owner_levees) - 1, -1, -1):
229 if owner_levees[card_idx].points == 0.5: 229 if owner_levees[card_idx].points == 0.5:
230 low_card = owner_levees[card_idx] 230 low_card = owner_levees[card_idx]
231 del owner_levees[card_idx] 231 del owner_levees[card_idx]
232 players_data[winner]['levees'].append(low_card) 232 players_data[winner]['levees'].append(low_card)
233 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}) 233 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})
234 break 234 break
235 if not low_card: # The player has no low card yet 235 if not low_card: # The player has no low card yet
236 #TODO: manage case when player never win a trick with low card 236 #TODO: manage case when player never win a trick with low card
237 players_data[excuse_player]['wait_for_low'] = winner 237 players_data[excuse_player]['wait_for_low'] = winner
238 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}) 238 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})
239 239
240 def __draw_game(self, game_data): 240 def __draw_game(self, game_data):
241 """The game is draw, no score change 241 """The game is draw, no score change
242 @param game_data: data of the game 242 @param game_data: data of the game
243 @return: tuple with (string victory message, list of winners, list of loosers)""" 243 @return: tuple with (string victory message, list of winners, list of loosers)"""
244 players_data = game_data['players_data'] 244 players_data = game_data['players_data']
245 scores_str = _('Draw game') 245 scores_str = _('Draw game')
246 scores_str += '\n' 246 scores_str += '\n'
247 for player in game_data['players']: 247 for player in game_data['players']:
248 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']} 248 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']}
249 debug(scores_str) 249 log.debug(scores_str)
250 250
251 return (scores_str, [], []) 251 return (scores_str, [], [])
252 252
253 def __calculate_scores(self, game_data): 253 def __calculate_scores(self, game_data):
254 """The game is finished, time to know who won :) 254 """The game is finished, time to know who won :)
293 elif game_data['contrat'] == 'Garde Sans': 293 elif game_data['contrat'] == 'Garde Sans':
294 contrat_mult = 4 294 contrat_mult = 4
295 elif game_data['contrat'] == 'Garde Contre': 295 elif game_data['contrat'] == 'Garde Contre':
296 contrat_mult = 6 296 contrat_mult = 6
297 else: 297 else:
298 error(_('INTERNAL ERROR: contrat not managed (mispelled ?)')) 298 log.error(_('INTERNAL ERROR: contrat not managed (mispelled ?)'))
299 assert(False) 299 assert(False)
300 300
301 victory = (score >= point_limit) 301 victory = (score >= point_limit)
302 margin = abs(score - point_limit) 302 margin = abs(score - point_limit)
303 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1) 303 points_defenseur = (margin + 25) * contrat_mult * (-1 if victory else 1)
316 316
317 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'} 317 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'}
318 scores_str += '\n' 318 scores_str += '\n'
319 for player in game_data['players']: 319 for player in game_data['players']:
320 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']} 320 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']}
321 debug(scores_str) 321 log.debug(scores_str)
322 322
323 return (scores_str, winners, loosers) 323 return (scores_str, winners, loosers)
324 324
325 def __invalid_cards(self, game_data, cards): 325 def __invalid_cards(self, game_data, cards):
326 """Checks that the player has the right to play what he wants to 326 """Checks that the player has the right to play what he wants to
373 forbidden_cards.append(card) 373 forbidden_cards.append(card)
374 return forbidden_cards 374 return forbidden_cards
375 if card.suit == "atout" and card < biggest_atout and biggest_hand_atout > biggest_atout and card.value != "excuse": 375 if card.suit == "atout" and card < biggest_atout and biggest_hand_atout > biggest_atout and card.value != "excuse":
376 forbidden_cards.append(card) 376 forbidden_cards.append(card)
377 else: 377 else:
378 error(_('Internal error: unmanaged game stage')) 378 log.error(_('Internal error: unmanaged game stage'))
379 return forbidden_cards 379 return forbidden_cards
380 380
381 def __start_play(self, room_jid, game_data, profile): 381 def __start_play(self, room_jid, game_data, profile):
382 """Start the game (tell to the first player after dealer to play""" 382 """Start the game (tell to the first player after dealer to play"""
383 game_data['stage'] = "play" 383 game_data['stage'] = "play"
392 @param profile_key: profile 392 @param profile_key: profile
393 """ 393 """
394 try: 394 try:
395 session_data = self._sessions.profileGet(raw_data["session_id"], profile) 395 session_data = self._sessions.profileGet(raw_data["session_id"], profile)
396 except KeyError: 396 except KeyError:
397 warning(_("session id doesn't exist, session has probably expired")) 397 log.warning(_("session id doesn't exist, session has probably expired"))
398 # TODO: send error dialog 398 # TODO: send error dialog
399 return defer.succeed({}) 399 return defer.succeed({})
400 400
401 room_jid_s = session_data['room_jid'].userhost() 401 room_jid_s = session_data['room_jid'].userhost()
402 referee = self.games[room_jid_s]['referee'] 402 referee = self.games[room_jid_s]['referee']
403 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile) 403 player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
404 data = xml_tools.XMLUIResult2DataFormResult(raw_data) 404 data = xml_tools.XMLUIResult2DataFormResult(raw_data)
405 contrat = data['contrat'] 405 contrat = data['contrat']
406 debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile}) 406 log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
407 d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile) 407 d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
408 d.addCallback(lambda ignore: {}) 408 d.addCallback(lambda ignore: {})
409 del self._sessions[raw_data["session_id"]] 409 del self._sessions[raw_data["session_id"]]
410 return d 410 return d
411 411
415 @param profile_key: profile 415 @param profile_key: profile
416 """ 416 """
417 try: 417 try:
418 session_data = self._sessions.profileGet(raw_data["session_id"], profile) 418 session_data = self._sessions.profileGet(raw_data["session_id"], profile)
419 except KeyError: 419 except KeyError:
420 warning(_("session id doesn't exist, session has probably expired")) 420 log.warning(_("session id doesn't exist, session has probably expired"))
421 # TODO: send error dialog 421 # TODO: send error dialog
422 return defer.succeed({}) 422 return defer.succeed({})
423 423
424 room_jid_s = session_data['room_jid'].userhost() 424 room_jid_s = session_data['room_jid'].userhost()
425 # XXX: empty hand means to the frontend "reset the display"... 425 # XXX: empty hand means to the frontend "reset the display"...
434 @cards: cards played (list of tuples) 434 @cards: cards played (list of tuples)
435 @profile_key: profile 435 @profile_key: profile
436 """ 436 """
437 profile = self.host.memory.getProfileName(profile_key) 437 profile = self.host.memory.getProfileName(profile_key)
438 if not profile: 438 if not profile:
439 error(_("profile %s is unknown") % profile_key) 439 log.error(_("profile %s is unknown") % profile_key)
440 return 440 return
441 debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards}) 441 log.debug(_('Cards played by %(profile)s: [%(cards)s]') % {'profile': profile, 'cards': cards})
442 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played') 442 elem = self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played')
443 self.send(jid.JID(referee), elem, {'player': player}, profile=profile) 443 self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
444 444
445 def newRound(self, room_jid, profile): 445 def newRound(self, room_jid, profile):
446 game_data = self.games[room_jid.userhost()] 446 game_data = self.games[room_jid.userhost()]
502 elif elt.name == 'player_ready': # ready to play 502 elif elt.name == 'player_ready': # ready to play
503 player = elt['player'] 503 player = elt['player']
504 status = self.games[room_jid.userhost()]['status'] 504 status = self.games[room_jid.userhost()]['status']
505 nb_players = len(self.games[room_jid.userhost()]['players']) 505 nb_players = len(self.games[room_jid.userhost()]['players'])
506 status[player] = 'ready' 506 status[player] = 'ready'
507 debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status}) 507 log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
508 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game 508 if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
509 self.newRound(room_jid, profile) 509 self.newRound(room_jid, profile)
510 510
511 elif elt.name == 'hand': # a new hand has been received 511 elif elt.name == 'hand': # a new hand has been received
512 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile) 512 self.host.bridge.tarotGameNew(room_jid.userhost(), self.__xml_to_list(elt), profile)
537 idx_pl = self.contrats.index(contrat) 537 idx_pl = self.contrats.index(contrat)
538 if idx_pl > idx_best: 538 if idx_pl > idx_best:
539 best_contrat[0] = player 539 best_contrat[0] = player
540 best_contrat[1] = contrat 540 best_contrat[1] = contrat
541 if best_contrat[1] == "Passe": 541 if best_contrat[1] == "Passe":
542 debug(_("Everybody is passing, round ended")) 542 log.debug(_("Everybody is passing, round ended"))
543 to_jid = jid.JID(room_jid.userhost()) 543 to_jid = jid.JID(room_jid.userhost())
544 self.send(to_jid, self.__give_scores(*self.__draw_game(game_data)), profile=profile) 544 self.send(to_jid, self.__give_scores(*self.__draw_game(game_data)), profile=profile)
545 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer 545 game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
546 for player in game_data['players']: 546 for player in game_data['players']:
547 game_data['status'][player] = "init" 547 game_data['status'][player] = "init"
548 return 548 return
549 debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]}) 549 log.debug(_("%(player)s win the bid with %(contrat)s") % {'player': best_contrat[0], 'contrat': best_contrat[1]})
550 game_data['contrat'] = best_contrat[1] 550 game_data['contrat'] = best_contrat[1]
551 551
552 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre": 552 if game_data['contrat'] == "Garde Sans" or game_data['contrat'] == "Garde Contre":
553 self.__start_play(room_jid, game_data, profile) 553 self.__start_play(room_jid, game_data, profile)
554 game_data['attaquant'] = best_contrat[0] 554 game_data['attaquant'] = best_contrat[0]
565 #The chien go into attaquant's (attacker) levees 565 #The chien go into attaquant's (attacker) levees
566 players_data[best_contrat[0]]['levees'].extend(game_data['chien']) 566 players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
567 del game_data['chien'][:] 567 del game_data['chien'][:]
568 568
569 elif elt.name == 'chien': # we have received the chien 569 elif elt.name == 'chien': # we have received the chien
570 debug(_("tarot: chien received")) 570 log.debug(_("tarot: chien received"))
571 data = {"attaquant": elt['attaquant']} 571 data = {"attaquant": elt['attaquant']}
572 game_data['stage'] = "ecart" 572 game_data['stage'] = "ecart"
573 game_data['attaquant'] = elt['attaquant'] 573 game_data['attaquant'] = elt['attaquant']
574 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile) 574 self.host.bridge.tarotGameShowCards(room_jid.userhost(), "chien", self.__xml_to_list(elt), data, profile)
575 575
616 #Did everybody played ? 616 #Did everybody played ?
617 played = [players_data[player]['played'] for player in game_data['players']] 617 played = [players_data[player]['played'] for player in game_data['players']]
618 if all(played): 618 if all(played):
619 #everybody has played 619 #everybody has played
620 winner = self.__winner(game_data) 620 winner = self.__winner(game_data)
621 debug(_('The winner of this trick is %s') % winner) 621 log.debug(_('The winner of this trick is %s') % winner)
622 #the winner win the trick 622 #the winner win the trick
623 self.__excuse_hack(game_data, played, winner) 623 self.__excuse_hack(game_data, played, winner)
624 players_data[elt['player']]['levees'].extend(played) 624 players_data[elt['player']]['levees'].extend(played)
625 #nothing left on the table 625 #nothing left on the table
626 for player in game_data['players']: 626 for player in game_data['players']:
662 if elt['type'] == 'invalid_cards': 662 if elt['type'] == 'invalid_cards':
663 played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next()) 663 played_cards = self.__xml_to_list(elt.elements(name='played', uri=NS_CG).next())
664 invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next()) 664 invalid_cards = self.__xml_to_list(elt.elements(name='invalid', uri=NS_CG).next())
665 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile) 665 self.host.bridge.tarotGameInvalidCards(room_jid.userhost(), elt['phase'], played_cards, invalid_cards, profile)
666 else: 666 else:
667 error(_('Unmanaged error type: %s') % elt['type']) 667 log.error(_('Unmanaged error type: %s') % elt['type'])
668 else: 668 else:
669 error(_('Unmanaged card game element: %s') % elt.name) 669 log.error(_('Unmanaged card game element: %s') % elt.name)
670 670
671 def getSyncDataForPlayer(self, room_jid_s, nick): 671 def getSyncDataForPlayer(self, room_jid_s, nick):
672 return [] 672 return []