The Playing Cards Program 2.0
This is an example from:
Chapter 9: Python Programming for the Absolute Beginner, Third Edition - Michael Dawson.
It is a simple program that extends the previous playing cards program using inheritance.
Along with the two simple classes Card
and Hand
you will find a new class called Deck
.
Deck
represents a card deck. Interestingly if you think of a deck, it is quite like a hand, it is just a special hand that has all 52 different cards in to start with.
Hence our deck just extends (inherits) from Hand
.
It then has three additional methods to the standard Hand
class - populate()
(populate the deck with all 52 cards), shuffle()
(shuffle the card order in the list) and finally deal()
which given a list of hands will deal out a number of cards to each by calling its give()
method which gives a card from the deck to the other hand.
Copy the following into main.py
.
import random
# Playing Cards 2.0
# Demonstrates inheritance - class extension
class Card(object):
""" A playing card. """
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
SUITS = ["c", "d", "h", "s"]
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep
class Hand(object):
""" A hand of playing cards. """
def __init__(self):
self.cards = []
def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
""" A deck of playing cards. """
def populate(self):
for suit in Card.SUITS:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
random.shuffle(self.cards)
def deal(self, hand_list, per_hand=1):
for rounds in range(per_hand):
for hand in hand_list:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print("Can't continue deal. Out of cards!")
def main():
# create a deck
deck_one = Deck()
print("Created a new deck.")
print("Deck:")
print(deck_one)
# populate the deck
deck_one.populate()
print("\nPopulated the deck.")
print("Deck:")
print(deck_one)
# shuffle the deck
deck_one.shuffle()
print("\nShuffled the deck.")
print("Deck:")
print(deck_one)
# create my hand
my_hand = Hand()
# create your hand
your_hand = Hand()
# create a list of hands
hand_list = [my_hand, your_hand]
# deal 5 cards to each of the hands in the hand_list
deck_one.deal(hand_list, per_hand = 5)
print("\nDealt 5 cards to my hand and your hand.")
# print out the hands
print("My hand:")
print(my_hand)
print("Your hand:")
print(your_hand)
print("Deck:")
print(deck_one)
if __name__ == "__main__":
main()