comparison plugins/plugin_misc_tarot.py @ 141:8c80d4dec7a8

mover Card class to tools/games and renamed it in TarotCard
author Goffi <goffi@goffi.org>
date Thu, 22 Jul 2010 15:49:16 +0800
parents 7201851d9aed
children dc692acde155
comparison
equal deleted inserted replaced
140:e496134ed679 141:8c80d4dec7a8
31 31
32 from zope.interface import implements 32 from zope.interface import implements
33 33
34 from wokkel import disco, iwokkel, data_form 34 from wokkel import disco, iwokkel, data_form
35 from tools.xml_tools import dataForm2xml 35 from tools.xml_tools import dataForm2xml
36 from tools.games import TarotCard
36 37
37 try: 38 try:
38 from twisted.words.protocols.xmlstream import XMPPHandler 39 from twisted.words.protocols.xmlstream import XMPPHandler
39 except ImportError: 40 except ImportError:
40 from wokkel.subprotocols import XMPPHandler 41 from wokkel.subprotocols import XMPPHandler
53 "main": "Tarot", 54 "main": "Tarot",
54 "handler": "yes", 55 "handler": "yes",
55 "description": _("""Implementation of Tarot card game""") 56 "description": _("""Implementation of Tarot card game""")
56 } 57 }
57 58
58 suits_order = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] #I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
59 values_order = map(str,range(1,11))+["valet","cavalier","dame","roi"]
60
61 class Card():
62 """This class is used to represent a car logically"""
63 #TODO: move this in a library in tools, and share this with frontends (e.g. card_game in wix use the same class)
64
65 def __init__(self, tuple_card):
66 """@param tuple_card: tuple (suit, value)"""
67 self.suit, self.value = tuple_card
68 self.bout = True if self.suit=="atout" and self.value in ["1","21","excuse"] else False
69 if self.bout or self.value == "roi":
70 self.points = 4.5
71 elif self.value == "dame":
72 self.points = 3.5
73 elif self.value == "cavalier":
74 self.points = 2.5
75 elif self.value == "valet":
76 self.points = 1.5
77 else:
78 self.points = 0.5
79
80 def get_tuple(self):
81 return (self.suit,self.value)
82
83 @staticmethod
84 def from_tuples(tuple_list):
85 result = []
86 for card_tuple in tuple_list:
87 result.append(Card(card_tuple))
88 return result
89
90 def __cmp__(self, other):
91 if other == None:
92 return 1
93 if self.suit != other.suit:
94 idx1 = suits_order.index(self.suit)
95 idx2 = suits_order.index(other.suit)
96 return idx1.__cmp__(idx2)
97 if self.suit == 'atout':
98 if self.value == other.value == 'excuse':
99 return 0
100 if self.value == 'excuse':
101 return -1
102 if other.value == 'excuse':
103 return 1
104 return int(self.value).__cmp__(int(other.value))
105 #at this point we have the same suit which is not 'atout'
106 idx1 = values_order.index(self.value)
107 idx2 = values_order.index(other.value)
108 return idx1.__cmp__(idx2)
109
110 def __str__(self):
111 return "[%s,%s]" % (self.suit, self.value)
112 59
113 class Tarot(): 60 class Tarot():
114 61
115 def __init__(self, host): 62 def __init__(self, host):
116 info(_("Plugin Tarot initialization")) 63 info(_("Plugin Tarot initialization"))
129 host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile 76 host.bridge.addSignal("tarotGameYourTurn", ".communication", signature='ss') #args: room_jid, profile
130 host.bridge.addSignal("tarotGameScore", ".communication", signature='ssasass') #args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile 77 host.bridge.addSignal("tarotGameScore", ".communication", signature='ssasass') #args: room_jid, xml_data, winners (list of nicks), loosers (list of nicks), profile
131 host.bridge.addSignal("tarotGameInvalidCards", ".communication", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile 78 host.bridge.addSignal("tarotGameInvalidCards", ".communication", signature='ssa(ss)a(ss)s') #args: room_jid, game phase, played_cards, invalid_cards, profile
132 self.deck_ordered = [] 79 self.deck_ordered = []
133 for value in ['excuse']+map(str,range(1,22)): 80 for value in ['excuse']+map(str,range(1,22)):
134 self.deck_ordered.append(Card(("atout",value))) 81 self.deck_ordered.append(TarotCard(("atout",value)))
135 for suit in ["pique", "coeur", "carreau", "trefle"]: 82 for suit in ["pique", "coeur", "carreau", "trefle"]:
136 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]: 83 for value in map(str,range(1,11))+["valet","cavalier","dame","roi"]:
137 self.deck_ordered.append(Card((suit, value))) 84 self.deck_ordered.append(TarotCard((suit, value)))
138 85
139 def createGameElt(self, to_jid, type="normal"): 86 def createGameElt(self, to_jid, type="normal"):
140 type = "normal" if to_jid.resource else "groupchat" 87 type = "normal" if to_jid.resource else "groupchat"
141 elt = domish.Element(('jabber:client','message')) 88 elt = domish.Element(('jabber:client','message'))
142 elt["to"] = to_jid.full() 89 elt["to"] = to_jid.full()
255 @param played: cards currently on the table 202 @param played: cards currently on the table
256 @param winner: nick of the trick winner""" 203 @param winner: nick of the trick winner"""
257 #TODO: manage the case where excuse is played on the last trick (and lost) 204 #TODO: manage the case where excuse is played on the last trick (and lost)
258 #TODO: gof: manage excuse (fool) 205 #TODO: gof: manage excuse (fool)
259 players_data = game_data['players_data'] 206 players_data = game_data['players_data']
260 excuse = Card(("atout","excuse")) 207 excuse = TarotCard(("atout","excuse"))
261 208
262 #we first check if the Excuse was already player 209 #we first check if the Excuse was already player
263 #and if somebody is waiting for a card 210 #and if somebody is waiting for a card
264 for player in game_data['players']: 211 for player in game_data['players']:
265 if players_data[player]['wait_for_low']: 212 if players_data[player]['wait_for_low']:
516 if not profile: 463 if not profile:
517 error (_("profile %s is unknown") % profile_key) 464 error (_("profile %s is unknown") % profile_key)
518 return 465 return
519 debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards}) 466 debug (_('Cards played by %(profile)s: [%(cards)s]') % {'profile':profile,'cards':cards})
520 mess = self.createGameElt(jid.JID(referee)) 467 mess = self.createGameElt(jid.JID(referee))
521 playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(Card.from_tuples(cards), 'cards_played')) 468 playcard_elt = mess.firstChildElement().addChild(self.__card_list_to_xml(TarotCard.from_tuples(cards), 'cards_played'))
522 playcard_elt['player'] = player 469 playcard_elt['player'] = player
523 self.host.profiles[profile].xmlstream.send(mess) 470 self.host.profiles[profile].xmlstream.send(mess)
524 471
525 def newGame(self, room_jid, profile): 472 def newGame(self, room_jid, profile):
526 """Launch a new round""" 473 """Launch a new round"""
648 595
649 elif elt.name == 'cards_played': 596 elif elt.name == 'cards_played':
650 if game_data['stage'] == "ecart": 597 if game_data['stage'] == "ecart":
651 #TODO: show atouts (trumps) if player put some in écart 598 #TODO: show atouts (trumps) if player put some in écart
652 assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here 599 assert (game_data['attaquant'] == elt['player']) #TODO: throw an xml error here
653 list_cards = Card.from_tuples(self.__xml_to_list(elt)) 600 list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
654 #we now check validity of card 601 #we now check validity of card
655 invalid_cards = self.__invalid_cards(game_data, list_cards) 602 invalid_cards = self.__invalid_cards(game_data, list_cards)
656 if invalid_cards: 603 if invalid_cards:
657 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+elt['player'])) 604 mess = self.createGameElt(jid.JID(room_jid.userhost()+'/'+elt['player']))
658 mess.firstChildElement().addChild(self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])) 605 mess.firstChildElement().addChild(self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage']))
666 613
667 self.__start_play(room_jid, game_data, profile) 614 self.__start_play(room_jid, game_data, profile)
668 615
669 elif game_data['stage'] == "play": 616 elif game_data['stage'] == "play":
670 current_player = game_data['players'][game_data['current_player']] 617 current_player = game_data['players'][game_data['current_player']]
671 cards = Card.from_tuples(self.__xml_to_list(elt)) 618 cards = TarotCard.from_tuples(self.__xml_to_list(elt))
672 619
673 if mess_elt['type'] == 'groupchat': 620 if mess_elt['type'] == 'groupchat':
674 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile) 621 self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
675 else: 622 else:
676 #we first check validity of card 623 #we first check validity of card