Skip to content

Instantly share code, notes, and snippets.

@rogfrich
Last active March 21, 2020 16:44
Show Gist options
  • Save rogfrich/fe20162a557aef285f572e8edb8c1dc9 to your computer and use it in GitHub Desktop.
Save rogfrich/fe20162a557aef285f572e8edb8c1dc9 to your computer and use it in GitHub Desktop.
Object oriented card dealing app for Dad. The same thing as deal.py, but in a more object oriented way.
import random
import sys
class Deck:
def __init__(self, number_of_cards):
self.number_of_cards = number_of_cards
self.reset()
def reset(self):
self.cards = []
for i in range(1, self.number_of_cards + 1): # 1 - 52 feels more natural for a deck of cards than 0 - 51
self.cards.append(i)
def shuffle(self):
random.shuffle(self.cards)
def deal_one_card(self):
try:
return self.cards.pop()
except IndexError:
sys.exit('Not enough cards in the deck to continue dealing')
def __repr__(self):
return f'deck with {len(self.cards)} in it'
def __str__(self):
return f'deck with {len(self.cards)} in it'
class Hand:
def __init__(self, player_number):
self.cards = []
self.name = f'Player {player_number}'
def get_card(self, card):
self.cards.append(card)
def __repr__(self):
return f'{self.name}: {self.cards}'
def __str__(self):
return f'{self.name}: {self.cards}'
CARDS_IN_DECK = 52
CARDS_IN_HAND = 13
PLAYERS = 3
deck = Deck(CARDS_IN_DECK)
deck.shuffle()
hands = {}
for i in range(PLAYERS):
hands[f'hand{i}'] = Hand(i)
for i in range(CARDS_IN_HAND):
for k, v in hands.items():
v.get_card(deck.deal_one_card())
# Print the hands to show it worked...
for k, v in hands.items():
print(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment