""" cards.py """ import random suits = ('clubs', 'diamonds', 'hearts', 'spades') ranks = ('ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'jack', 'queen', 'king') blackjack_values = { 'ace' : 1, 'two' : 2, 'three' : 3, 'four' : 4, 'five' : 5, 'six' : 6, 'seven' : 7, 'eight' : 8, 'nine' : 9, 'ten' : 10, 'jack' : 10, 'queen' : 10, 'king' : 10 } class Card: """ One playing card. """ def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): return "{} of {}".format(self.rank, self.suit) def value(self): return blackjack_values[self.rank] class Hand: """ a group of cards """ def __init__(self): self.cards = [] def value(self): result = 0 for card in self.cards: result = result + card.value() return result def __str__(self): result = "" def push(self, card): """ add a card to this hand """ self.cards.append(card) class Deck: """ A deck of cards. """ def __init__(self): self.cards = [] for suit in suits: for rank in ranks: card = Card(rank, suit) self.cards.append(card) def __str__(self): return "".format(len(self.cards)) def shuffle(self): random.shuffle(self.cards) def push(self, card): """ put one card onto the top of the deck """ self.cards.append(card) def pull(self, rand=False): """ pull one card from the top of the deck or from a random place in the deck. """ if rand: which = random.randrange(len(self.cards)) return self.cards.pop(which) else: return self.cards.pop() def main(): deck = Deck() print("New deck: {}".format(deck)) top_card = deck.pull() print("Pulled top card. It is {}.".format(top_card)) print("The deck is now : {}".format(deck)) print("-- adding cards to a hand --") hand = Hand() deck.shuffle() for i in range(4): print("value={} {}".format(hand.value(), hand)) card = deck.pull() hand.push(card) main()