Skip to content

Instantly share code, notes, and snippets.

@SebDeclercq
Last active June 4, 2019 08:45
Show Gist options
  • Save SebDeclercq/538887f0b4cb01d4313de32d0c802c7f to your computer and use it in GitHub Desktop.
Save SebDeclercq/538887f0b4cb01d4313de32d0c802c7f to your computer and use it in GitHub Desktop.
from typing import Sequence, Union, List
from dataclasses import dataclass, field
import random
@dataclass
class Card:
color: str
value: Union[int, str]
AVAILABLE_COLORS: Sequence[str] = field(default=('coeur', 'pique', 'trèfle', 'carreau'), repr=False)
AVAILABLE_VALUES: Sequence[Union[int, str]] = field(default=(*range(1, 11), 'valet', 'dame', 'roi'), repr=False)
@dataclass
class Hand:
cards: List[Card] = field(default_factory=list)
class Deck:
def __init__(self) -> None:
deck: List[Card] = [Card(color, value) for color in Card.AVAILABLE_COLORS
for value in Card.AVAILABLE_VALUES]
random.shuffle(deck)
self.deck: List[Card] = deck
def deal_hands(self, nb_hands: int, nb_cards_per_hand: int) -> List[Hand]:
if nb_hands * nb_cards_per_hand > len(self.deck):
raise ValueError('Too few cards in deck')
hands: List[Hand] = []
for _ in range(nb_hands):
hands.append(Hand(self._get_cards(nb_cards_per_hand)))
return hands
def _get_cards(self, nb_cards: int = 1) -> List[Card]:
cards, self.deck = self.deck[:nb_cards], self.deck[nb_cards:]
return cards
deck = Deck()
deck.deal_hands(4, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment