In this lesson, you’ll practice playing with Python types and learn about adding annotations and type hints for sequence objects.
Up until now, you’ve only used basic types like str
, float
, and bool
in your type hints. The Python type system is quite powerful and supports many kinds of more complex types. This is necessary as it needs to be able to reasonably model Python’s dynamic duck typing nature.
In this lesson, you’ll learn more about this type system by making a card game. You’ll see how to specify:
- The type of sequences and mappings like tuples, lists, and dictionaries
- Type aliases that make code easier to read
The following example shows an implementation of a regular (French) deck of cards:
# game.py
import random
SUITS = "♠ ♡ ♢ ♣".split()
RANKS = "2 3 4 5 6 7 8 9 10 J Q K A".split()
def create_deck(shuffle=False):
"""Create a new deck of 52 cards"""
deck = [(s, r) for r in RANKS for s in SUITS]
if shuffle:
random.shuffle(deck)
return deck
def deal_hands(deck):
"""Deal the cards in the deck into four hands"""
return (deck[0::4], deck[1::4], deck[2::4], deck[3::4])
def play():
"""Play a 4-player card game"""
deck = create_deck(shuffle=True)
names = "P1 P2 P3 P4".split()
hands = {n: h for n, h in zip(names, deal_hands(deck))}
for name, cards in hands.items():
card_str = " ".join(f"{s}{r}" for (s, r) in cards)
print(f"{name}: {card_str}")
if __name__ == "__main__":
play()
Each card is represented as a tuple of strings denoting the suit and rank. The deck is represented as a list of cards. create_deck()
creates a regular deck of 52 playing cards and optionally shuffles the cards. deal_hands()
deals the deck of cards to four players.