Created
June 23, 2020 16:39
-
-
Save pathunstrom/8fb787abdd623da6a7b425c225b2a9c2 to your computer and use it in GitHub Desktop.
A simple model of a deck of cards.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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