Created
May 2, 2018 18:52
-
-
Save 4Kaylum/f73aab6525ff16c524552cee48cf3933 to your computer and use it in GitHub Desktop.
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
from random import shuffle | |
class Card(object): | |
''' | |
A card object - represents a card from the deck | |
''' | |
def __init__(self, value, suit): | |
self.value = value | |
self.name = { | |
1: 'Ace', | |
2: 'Two', | |
3: 'Three', | |
4: 'Four', | |
5: 'Five', | |
6: 'Six', | |
7: 'Seven', | |
8: 'Eight', | |
9: 'Nine', | |
10: 'Ten', | |
11: 'Jack', | |
12: 'Queen', | |
13: 'King' | |
}[self.value] | |
self.suit = suit | |
self.sort_value = self.value + { | |
'Clubs': 13 * 0, | |
'Spades': 13 * 1, | |
'Hearts': 13 * 2, | |
'Diamonds': 13 * 3 | |
}[self.suit] | |
def __str__(self) -> str: | |
return '{} of {}'.format(self.name, self.suit) | |
def __repr__(self) -> str: | |
return '<{0.__class__.__name__}; {0.value}{0.suit[0]}>'.format(self) | |
class Hand(object): | |
''' | |
A hand of cards, dealt from the deck | |
''' | |
def __init__(self, cards:list=[]): | |
self.cards = cards[:] | |
def add_card(self, card:Card) -> None: | |
''' | |
Adds a card to the hand | |
''' | |
self.cards.append(card) | |
self.cards.sort(key=lambda c: c.sort_value) | |
def remove_card(self, card:Card) -> None: | |
''' | |
Removes a card object from the hand | |
''' | |
self.cards.remove(card) | |
class Deck(object): | |
''' | |
A deck of cards | |
''' | |
def __init__(self): | |
self.deck_cards = [] | |
self.dealt_cards = [] | |
self.add_all_cards() | |
def add_all_cards(self) -> None: | |
''' | |
Generates the deck of cards (minus jokers) and shuffles the deck | |
''' | |
for value in range(1, 14): | |
for suit in ['Clubs', 'Spades', 'Diamonds', 'Hearts']: | |
self.deck_cards.append(Card(value, suit)) | |
shuffle(self.deck_cards) | |
def get_card(self) -> Card: | |
''' | |
Gets a card from the top of the deck and deals it out to you | |
''' | |
try: | |
x = self.deck_cards.pop() | |
except IndexError as e: | |
raise IndexError('No remaining cards in deck.') | |
self.dealt_cards.append(x) | |
return x | |
def deal_hand(self, cards:int) -> Hand: | |
''' | |
Generates a hand object with a given amount of cards | |
''' | |
h = Hand() | |
for i in range(cards): | |
h.add_card(self.get_card()) | |
return h | |
def deal_hands(self, hands:int, cards_per_hand:int) -> list: | |
''' | |
Generates an array of hand objects | |
''' | |
hand_list = [] | |
for i in range(hands): | |
h = self.deal_hand(cards_per_hand) | |
hand_list.append(h) | |
return hand_list | |
def __repr__(self) -> str: | |
return '<{0.__class__.__name__}; {1} cards remaining>'.format(self, len(deck_cards)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment