Skip to content

Instantly share code, notes, and snippets.

@pathunstrom
Created Jun 23, 2020
Embed
What would you like to do?
A simple model of a deck of cards.
import enum
from collections import UserList
from dataclasses import dataclass
from itertools import product
from random import shuffle
from random import choice
from typing import List
class Suit(enum.Enum):
CLUBS = "♣"
DIAMONDS = "♦"
HEARTS = "♥"
SPADES = "♠"
faces = {
1: "Ace",
11: "Jack",
12: "Queen",
13: "King"
}
class Deck(UserList):
def shuffle(self) -> 'Deck':
shuffle(self)
return self
def draw_random(self):
card = choice(self)
self.remove(card)
return card
@dataclass
class Card:
suit: Suit
rank: int
@staticmethod
def get_deck() -> List['Card']:
return Deck(Card(suit, rank) for suit, rank in product([Suit.CLUBS, Suit.DIAMONDS, Suit.HEARTS, Suit.SPADES], range(1, 14)))
def __str__(self):
return f"{faces.get(self.rank, self.rank)} of {self.suit.value}"
def __eq__(self, other):
return self.rank == other.rank and self.suit is other.suit
deck = Card.get_deck()
print(Card(Suit.DIAMONDS, 1) in deck)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment