comparison sat_frontends/primitivus/game_tarot.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 26edcf3a30eb
children 003b8b4b56a7
comparison
equal deleted inserted replaced
2623:49533de4540b 2624:56f94936df1e
26 from sat_frontends.primitivus.keys import action_key_map as a_key 26 from sat_frontends.primitivus.keys import action_key_map as a_key
27 27
28 28
29 class CardDisplayer(urwid.Text): 29 class CardDisplayer(urwid.Text):
30 """Show a card""" 30 """Show a card"""
31 signals = ['click'] 31
32 signals = ["click"]
32 33
33 def __init__(self, card): 34 def __init__(self, card):
34 self.__selected = False 35 self.__selected = False
35 self.card = card 36 self.card = card
36 urwid.Text.__init__(self, card.getAttrText()) 37 urwid.Text.__init__(self, card.getAttrText())
37 38
38 def selectable(self): 39 def selectable(self):
39 return True 40 return True
40 41
41 def keypress(self, size, key): 42 def keypress(self, size, key):
42 if key == a_key['CARD_SELECT']: 43 if key == a_key["CARD_SELECT"]:
43 self.select(not self.__selected) 44 self.select(not self.__selected)
44 self._emit('click') 45 self._emit("click")
45 return key 46 return key
46 47
47 def mouse_event(self, size, event, button, x, y, focus): 48 def mouse_event(self, size, event, button, x, y, focus):
48 if urwid.is_mouse_event(event) and button == 1: 49 if urwid.is_mouse_event(event) and button == 1:
49 self.select(not self.__selected) 50 self.select(not self.__selected)
50 self._emit('click') 51 self._emit("click")
51 return True 52 return True
52 53
53 return False 54 return False
54 55
55 def select(self, state=True): 56 def select(self, state=True):
56 self.__selected = state 57 self.__selected = state
57 attr, txt = self.card.getAttrText() 58 attr, txt = self.card.getAttrText()
58 if self.__selected: 59 if self.__selected:
59 attr += '_selected' 60 attr += "_selected"
60 self.set_text((attr, txt)) 61 self.set_text((attr, txt))
61 self._invalidate() 62 self._invalidate()
62 63
63 def isSelected(self): 64 def isSelected(self):
64 return self.__selected 65 return self.__selected
73 return canvas 74 return canvas
74 75
75 76
76 class Hand(urwid.WidgetWrap): 77 class Hand(urwid.WidgetWrap):
77 """Used to display several cards, and manage a hand""" 78 """Used to display several cards, and manage a hand"""
78 signals = ['click'] 79
80 signals = ["click"]
79 81
80 def __init__(self, hand=[], selectable=False, on_click=None, user_data=None): 82 def __init__(self, hand=[], selectable=False, on_click=None, user_data=None):
81 """@param hand: list of Card""" 83 """@param hand: list of Card"""
82 self.__selectable = selectable 84 self.__selectable = selectable
83 self.columns = urwid.Columns([], dividechars=1) 85 self.columns = urwid.Columns([], dividechars=1)
84 if on_click: 86 if on_click:
85 urwid.connect_signal(self, 'click', on_click, user_data) 87 urwid.connect_signal(self, "click", on_click, user_data)
86 if hand: 88 if hand:
87 self.update(hand) 89 self.update(hand)
88 urwid.WidgetWrap.__init__(self, self.columns) 90 urwid.WidgetWrap.__init__(self, self.columns)
89 91
90 def selectable(self): 92 def selectable(self):
93 def keypress(self, size, key): 95 def keypress(self, size, key):
94 96
95 if CardDisplayer in [wid.__class__ for wid in self.columns.widget_list]: 97 if CardDisplayer in [wid.__class__ for wid in self.columns.widget_list]:
96 return self.columns.keypress(size, key) 98 return self.columns.keypress(size, key)
97 else: 99 else:
98 #No card displayed, we still have to manage the clicks 100 # No card displayed, we still have to manage the clicks
99 if key == a_key['CARD_SELECT']: 101 if key == a_key["CARD_SELECT"]:
100 self._emit('click', None) 102 self._emit("click", None)
101 return key 103 return key
102 104
103 def getSelected(self): 105 def getSelected(self):
104 """Return a list of selected cards""" 106 """Return a list of selected cards"""
105 _selected = [] 107 _selected = []
114 try: 116 try:
115 del self.columns.widget_list[:] 117 del self.columns.widget_list[:]
116 del self.columns.column_types[:] 118 del self.columns.column_types[:]
117 except IndexError: 119 except IndexError:
118 pass 120 pass
119 self.columns.contents.append((urwid.Text(''), ('weight', 1, False))) 121 self.columns.contents.append((urwid.Text(""), ("weight", 1, False)))
120 for card in hand: 122 for card in hand:
121 widget = CardDisplayer(card) 123 widget = CardDisplayer(card)
122 self.columns.widget_list.append(widget) 124 self.columns.widget_list.append(widget)
123 self.columns.column_types.append(('fixed', 3)) 125 self.columns.column_types.append(("fixed", 3))
124 urwid.connect_signal(widget, 'click', self.__onClick) 126 urwid.connect_signal(widget, "click", self.__onClick)
125 self.columns.contents.append((urwid.Text(''), ('weight', 1, False))) 127 self.columns.contents.append((urwid.Text(""), ("weight", 1, False)))
126 self.columns.focus_position = 1 128 self.columns.focus_position = 1
127 129
128 def __onClick(self, card_wid): 130 def __onClick(self, card_wid):
129 self._emit('click', card_wid) 131 self._emit("click", card_wid)
130 132
131 133
132 class Card(TarotCard): 134 class Card(TarotCard):
133 """This class is used to represent a card, logically 135 """This class is used to represent a card, logically
134 and give a text representation with attributes""" 136 and give a text representation with attributes"""
137
135 SIZE = 3 # size of a displayed card 138 SIZE = 3 # size of a displayed card
136 139
137 def __init__(self, suit, value): 140 def __init__(self, suit, value):
138 """@param file: path of the PNG file""" 141 """@param file: path of the PNG file"""
139 TarotCard.__init__(self, (suit, value)) 142 TarotCard.__init__(self, (suit, value))
144 value = "%02i" % int(self.value) 147 value = "%02i" % int(self.value)
145 except ValueError: 148 except ValueError:
146 value = self.value[0].upper() + self.value[1] 149 value = self.value[0].upper() + self.value[1]
147 if self.suit == "atout": 150 if self.suit == "atout":
148 if self.value == "excuse": 151 if self.value == "excuse":
149 suit = 'c' 152 suit = "c"
150 else: 153 else:
151 suit = 'A' 154 suit = "A"
152 color = 'neutral' 155 color = "neutral"
153 elif self.suit == "pique": 156 elif self.suit == "pique":
154 suit = u'♠' 157 suit = u"♠"
155 color = 'black' 158 color = "black"
156 elif self.suit == "trefle": 159 elif self.suit == "trefle":
157 suit = u'♣' 160 suit = u"♣"
158 color = 'black' 161 color = "black"
159 elif self.suit == "coeur": 162 elif self.suit == "coeur":
160 suit = u'♥' 163 suit = u"♥"
161 color = 'red' 164 color = "red"
162 elif self.suit == "carreau": 165 elif self.suit == "carreau":
163 suit = u'♦' 166 suit = u"♦"
164 color = 'red' 167 color = "red"
165 if self.bout: 168 if self.bout:
166 color = 'special' 169 color = "special"
167 return ('card_%s' % color, u"%s%s" % (value, suit)) 170 return ("card_%s" % color, u"%s%s" % (value, suit))
168 171
169 def getWidget(self): 172 def getWidget(self):
170 """Return a widget representing the card""" 173 """Return a widget representing the card"""
171 return CardDisplayer(self) 174 return CardDisplayer(self)
172 175
179 182
180 def putCard(self, location, card): 183 def putCard(self, location, card):
181 """Put a card on the table 184 """Put a card on the table
182 @param location: where to put the card (top, left, bottom or right) 185 @param location: where to put the card (top, left, bottom or right)
183 @param card: Card to play or None""" 186 @param card: Card to play or None"""
184 assert location in ['top', 'left', 'bottom', 'right'] 187 assert location in ["top", "left", "bottom", "right"]
185 assert isinstance(card, Card) or card == None 188 assert isinstance(card, Card) or card == None
186 if [getattr(self, place) for place in ['top', 'left', 'bottom', 'right']].count(None) == 0: 189 if [getattr(self, place) for place in ["top", "left", "bottom", "right"]].count(
187 #If the table is full of card, we remove them 190 None
191 ) == 0:
192 # If the table is full of card, we remove them
188 self.top = self.left = self.bottom = self.right = None 193 self.top = self.left = self.bottom = self.right = None
189 setattr(self, location, card) 194 setattr(self, location, card)
190 self._invalidate() 195 self._invalidate()
191 196
192 def rows(self, size, focus=False): 197 def rows(self, size, focus=False):
197 202
198 def display_widget(self, size, focus): 203 def display_widget(self, size, focus):
199 cards = {} 204 cards = {}
200 max_col, = size 205 max_col, = size
201 separator = " - " 206 separator = " - "
202 margin = max((max_col - Card.SIZE) / 2, 0) * ' ' 207 margin = max((max_col - Card.SIZE) / 2, 0) * " "
203 margin_center = max((max_col - Card.SIZE * 2 - len(separator)) / 2, 0) * ' ' 208 margin_center = max((max_col - Card.SIZE * 2 - len(separator)) / 2, 0) * " "
204 for location in ['top', 'left', 'bottom', 'right']: 209 for location in ["top", "left", "bottom", "right"]:
205 card = getattr(self, location) 210 card = getattr(self, location)
206 cards[location] = card.getAttrText() if card else Card.SIZE * ' ' 211 cards[location] = card.getAttrText() if card else Card.SIZE * " "
207 render_wid = [urwid.Text([margin, cards['top']]), 212 render_wid = [
208 urwid.Text([margin_center, cards['left'], separator, cards['right']]), 213 urwid.Text([margin, cards["top"]]),
209 urwid.Text([margin, cards['bottom']])] 214 urwid.Text([margin_center, cards["left"], separator, cards["right"]]),
215 urwid.Text([margin, cards["bottom"]]),
216 ]
210 return urwid.Pile(render_wid) 217 return urwid.Pile(render_wid)
211 218
212 219
213 class TarotGame(QuickTarotGame, urwid.WidgetWrap): 220 class TarotGame(QuickTarotGame, urwid.WidgetWrap):
214 """Widget for card games""" 221 """Widget for card games"""
215 222
216 def __init__(self, parent, referee, players): 223 def __init__(self, parent, referee, players):
217 QuickTarotGame.__init__(self, parent, referee, players) 224 QuickTarotGame.__init__(self, parent, referee, players)
218 self.loadCards() 225 self.loadCards()
219 self.top = urwid.Pile([urwid.Padding(urwid.Text(self.top_nick), 'center')]) 226 self.top = urwid.Pile([urwid.Padding(urwid.Text(self.top_nick), "center")])
220 #self.parent.host.debug() 227 # self.parent.host.debug()
221 self.table = Table() 228 self.table = Table()
222 self.center = urwid.Columns([('fixed', len(self.left_nick), urwid.Filler(urwid.Text(self.left_nick))), 229 self.center = urwid.Columns(
223 urwid.Filler(self.table), 230 [
224 ('fixed', len(self.right_nick), urwid.Filler(urwid.Text(self.right_nick))) 231 ("fixed", len(self.left_nick), urwid.Filler(urwid.Text(self.left_nick))),
225 ]) 232 urwid.Filler(self.table),
233 (
234 "fixed",
235 len(self.right_nick),
236 urwid.Filler(urwid.Text(self.right_nick)),
237 ),
238 ]
239 )
226 """urwid.Pile([urwid.Padding(self.top_card_wid,'center'), 240 """urwid.Pile([urwid.Padding(self.top_card_wid,'center'),
227 urwid.Columns([('fixed',len(self.left_nick),urwid.Text(self.left_nick)), 241 urwid.Columns([('fixed',len(self.left_nick),urwid.Text(self.left_nick)),
228 urwid.Padding(self.center_cards_wid,'center'), 242 urwid.Padding(self.center_cards_wid,'center'),
229 ('fixed',len(self.right_nick),urwid.Text(self.right_nick)) 243 ('fixed',len(self.right_nick),urwid.Text(self.right_nick))
230 ]), 244 ]),
231 urwid.Padding(self.bottom_card_wid,'center') 245 urwid.Padding(self.bottom_card_wid,'center')
232 ])""" 246 ])"""
233 self.hand_wid = Hand(selectable=True, on_click=self.onClick) 247 self.hand_wid = Hand(selectable=True, on_click=self.onClick)
234 self.main_frame = urwid.Frame(self.center, header=self.top, footer=self.hand_wid, focus_part='footer') 248 self.main_frame = urwid.Frame(
249 self.center, header=self.top, footer=self.hand_wid, focus_part="footer"
250 )
235 urwid.WidgetWrap.__init__(self, self.main_frame) 251 urwid.WidgetWrap.__init__(self, self.main_frame)
236 self.parent.host.bridge.tarotGameReady(self.player_nick, referee, self.parent.profile) 252 self.parent.host.bridge.tarotGameReady(
253 self.player_nick, referee, self.parent.profile
254 )
237 255
238 def loadCards(self): 256 def loadCards(self):
239 """Load all the cards in memory""" 257 """Load all the cards in memory"""
240 QuickTarotGame.loadCards(self) 258 QuickTarotGame.loadCards(self)
241 for value in map(str, range(1, 22)) + ['excuse']: 259 for value in map(str, range(1, 22)) + ["excuse"]:
242 card = Card('atout', value) 260 card = Card("atout", value)
243 self.cards[card.suit, card.value] = card 261 self.cards[card.suit, card.value] = card
244 self.deck.append(card) 262 self.deck.append(card)
245 for suit in ["pique", "coeur", "carreau", "trefle"]: 263 for suit in ["pique", "coeur", "carreau", "trefle"]:
246 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]: 264 for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
247 card = Card(suit, value) 265 card = Card(suit, value)
250 268
251 def tarotGameNewHandler(self, hand): 269 def tarotGameNewHandler(self, hand):
252 """Start a new game, with given hand""" 270 """Start a new game, with given hand"""
253 if hand is []: # reset the display after the scores have been showed 271 if hand is []: # reset the display after the scores have been showed
254 self.resetRound() 272 self.resetRound()
255 for location in ['top', 'left', 'bottom', 'right']: 273 for location in ["top", "left", "bottom", "right"]:
256 self.table.putCard(location, None) 274 self.table.putCard(location, None)
257 self.parent.host.redraw() 275 self.parent.host.redraw()
258 self.parent.host.bridge.tarotGameReady(self.player_nick, self.referee, self.parent.profile) 276 self.parent.host.bridge.tarotGameReady(
277 self.player_nick, self.referee, self.parent.profile
278 )
259 return 279 return
260 QuickTarotGame.tarotGameNewHandler(self, hand) 280 QuickTarotGame.tarotGameNewHandler(self, hand)
261 self.hand_wid.update(self.hand) 281 self.hand_wid.update(self.hand)
262 self.parent.host.redraw() 282 self.parent.host.redraw()
263 283
264 def tarotGameChooseContratHandler(self, xml_data): 284 def tarotGameChooseContratHandler(self, xml_data):
265 """Called when the player has to select his contrat 285 """Called when the player has to select his contrat
266 @param xml_data: SàT xml representation of the form""" 286 @param xml_data: SàT xml representation of the form"""
267 form = xmlui.create(self.parent.host, xml_data, title=_('Please choose your contrat'), flags=['NO_CANCEL'], profile=self.parent.profile) 287 form = xmlui.create(
268 form.show(valign='top') 288 self.parent.host,
289 xml_data,
290 title=_("Please choose your contrat"),
291 flags=["NO_CANCEL"],
292 profile=self.parent.profile,
293 )
294 form.show(valign="top")
269 295
270 def tarotGameShowCardsHandler(self, game_stage, cards, data): 296 def tarotGameShowCardsHandler(self, game_stage, cards, data):
271 """Display cards in the middle of the game (to show for e.g. chien ou poignée)""" 297 """Display cards in the middle of the game (to show for e.g. chien ou poignée)"""
272 QuickTarotGame.tarotGameShowCardsHandler(self, game_stage, cards, data) 298 QuickTarotGame.tarotGameShowCardsHandler(self, game_stage, cards, data)
273 self.center.widget_list[1] = urwid.Filler(Hand(self.to_show)) 299 self.center.widget_list[1] = urwid.Filler(Hand(self.to_show))
280 """Called when the round is over, display the scores 306 """Called when the round is over, display the scores
281 @param xml_data: SàT xml representation of the form""" 307 @param xml_data: SàT xml representation of the form"""
282 if not winners and not loosers: 308 if not winners and not loosers:
283 title = _("Draw game") 309 title = _("Draw game")
284 else: 310 else:
285 title = _('You win \o/') if self.player_nick in winners else _('You loose :(') 311 title = _("You win \o/") if self.player_nick in winners else _("You loose :(")
286 form = xmlui.create(self.parent.host, xml_data, title=title, flags=['NO_CANCEL'], profile=self.parent.profile) 312 form = xmlui.create(
313 self.parent.host,
314 xml_data,
315 title=title,
316 flags=["NO_CANCEL"],
317 profile=self.parent.profile,
318 )
287 form.show() 319 form.show()
288 320
289 def tarotGameInvalidCardsHandler(self, phase, played_cards, invalid_cards): 321 def tarotGameInvalidCardsHandler(self, phase, played_cards, invalid_cards):
290 """Invalid cards have been played 322 """Invalid cards have been played
291 @param phase: phase of the game 323 @param phase: phase of the game
292 @param played_cards: all the cards played 324 @param played_cards: all the cards played
293 @param invalid_cards: cards which are invalid""" 325 @param invalid_cards: cards which are invalid"""
294 QuickTarotGame.tarotGameInvalidCardsHandler(self, phase, played_cards, invalid_cards) 326 QuickTarotGame.tarotGameInvalidCardsHandler(
327 self, phase, played_cards, invalid_cards
328 )
295 self.hand_wid.update(self.hand) 329 self.hand_wid.update(self.hand)
296 if self._autoplay == None: # No dialog if there is autoplay 330 if self._autoplay == None: # No dialog if there is autoplay
297 self.parent.host.barNotify(_('Cards played are invalid !')) 331 self.parent.host.barNotify(_("Cards played are invalid !"))
298 self.parent.host.redraw() 332 self.parent.host.redraw()
299 333
300 def tarotGameCardsPlayedHandler(self, player, cards): 334 def tarotGameCardsPlayedHandler(self, player, cards):
301 """A card has been played by player""" 335 """A card has been played by player"""
302 QuickTarotGame.tarotGameCardsPlayedHandler(self, player, cards) 336 QuickTarotGame.tarotGameCardsPlayedHandler(self, player, cards)
303 self.table.putCard(self.getPlayerLocation(player), self.played[player]) 337 self.table.putCard(self.getPlayerLocation(player), self.played[player])
304 self._checkState() 338 self._checkState()
305 self.parent.host.redraw() 339 self.parent.host.redraw()
306 340
307 def _checkState(self): 341 def _checkState(self):
308 if isinstance(self.center.widget_list[1].original_widget, Hand): # if we have a hand displayed 342 if isinstance(
309 self.center.widget_list[1] = urwid.Filler(self.table) # we show again the table 343 self.center.widget_list[1].original_widget, Hand
344 ): # if we have a hand displayed
345 self.center.widget_list[1] = urwid.Filler(
346 self.table
347 ) # we show again the table
310 if self.state == "chien": 348 if self.state == "chien":
311 self.to_show = [] 349 self.to_show = []
312 self.state = "wait" 350 self.state = "wait"
313 elif self.state == "wait_for_ecart": 351 elif self.state == "wait_for_ecart":
314 self.state = "ecart" 352 self.state = "ecart"
318 self.hand_wid.update(self.hand) 356 self.hand_wid.update(self.hand)
319 357
320 ##EVENTS## 358 ##EVENTS##
321 def onClick(self, hand, card_wid): 359 def onClick(self, hand, card_wid):
322 """Called when user do an action on the hand""" 360 """Called when user do an action on the hand"""
323 if not self.state in ['play', 'ecart', 'wait_for_ecart']: 361 if not self.state in ["play", "ecart", "wait_for_ecart"]:
324 #it's not our turn, we ignore the click 362 # it's not our turn, we ignore the click
325 card_wid.select(False) 363 card_wid.select(False)
326 return 364 return
327 self._checkState() 365 self._checkState()
328 if self.state == "ecart": 366 if self.state == "ecart":
329 if len(self.hand_wid.getSelected()) == 6: 367 if len(self.hand_wid.getSelected()) == 6:
330 pop_up_widget = sat_widgets.ConfirmDialog(_("Do you put these cards in chien ?"), yes_cb=self.onEcartDone, no_cb=self.parent.host.removePopUp) 368 pop_up_widget = sat_widgets.ConfirmDialog(
369 _("Do you put these cards in chien ?"),
370 yes_cb=self.onEcartDone,
371 no_cb=self.parent.host.removePopUp,
372 )
331 self.parent.host.showPopUp(pop_up_widget) 373 self.parent.host.showPopUp(pop_up_widget)
332 elif self.state == "play": 374 elif self.state == "play":
333 card = card_wid.getCard() 375 card = card_wid.getCard()
334 self.parent.host.bridge.tarotGamePlayCards(self.player_nick, self.referee, [(card.suit, card.value)], self.parent.profile) 376 self.parent.host.bridge.tarotGamePlayCards(
377 self.player_nick,
378 self.referee,
379 [(card.suit, card.value)],
380 self.parent.profile,
381 )
335 self.hand.remove(card) 382 self.hand.remove(card)
336 self.hand_wid.update(self.hand) 383 self.hand_wid.update(self.hand)
337 self.state = "wait" 384 self.state = "wait"
338 385
339 def onEcartDone(self, button): 386 def onEcartDone(self, button):
341 ecart = [] 388 ecart = []
342 for card in self.hand_wid.getSelected(): 389 for card in self.hand_wid.getSelected():
343 ecart.append((card.suit, card.value)) 390 ecart.append((card.suit, card.value))
344 self.hand.remove(card) 391 self.hand.remove(card)
345 self.hand_wid.update(self.hand) 392 self.hand_wid.update(self.hand)
346 self.parent.host.bridge.tarotGamePlayCards(self.player_nick, self.referee, ecart, self.parent.profile) 393 self.parent.host.bridge.tarotGamePlayCards(
394 self.player_nick, self.referee, ecart, self.parent.profile
395 )
347 self.state = "wait" 396 self.state = "wait"
348 self.parent.host.removePopUp() 397 self.parent.host.removePopUp()