0% found this document useful (0 votes)
7 views6 pages

Card and Deck Class Overview

Uploaded by

8bhv9p5y7d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views6 pages

Card and Deck Class Overview

Uploaded by

8bhv9p5y7d
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ST101A: Card and Deck Classes

(Instructor Teaching Notes)

1 Card Class
1.1 Code

_SUIT_DISPLAY = [None, ’’, ’’, ’’, ’’] # 1..4


_RANK_DISPLAY = [None, ’A’, ’2’, ’3’, ’4’, ’5’, ’6’,
’7’, ’8’, ’9’, ’10’, ’J’, ’Q’, ’K’] # 1..13

class Card:
"""
Represent a playing card with an integer rank and suit.

Cards can be compared with each other to see if one card is


smaller/larger than another card.
"""

def __init__(self, rank, suit):


"""
rank : int
integer 1 to 13 mapping to A,2,...,Q,K
i.e. 1 for A, 2 for 2, ..., 10 for 10, 11 for J,
12 for Q and 13 for K
suit : int
integer 1 to 4 mapping to , , ,
i.e. 1 for , 2 for , 3 for and 4 for
return : None
"""
if not (1 <= rank <= 13):
raise ValueError("rank must be an integer between 1 and 13")
if not (1 <= suit <= 4):
raise ValueError("suit must be an integer between 1 and 4")

self._rank = rank
self._suit = suit

def __str__(self):
"""
Return a human-readable string for this card, e.g. ’5’ or ’K’.
"""
return f"{_SUIT_DISPLAY[self._suit]}{_RANK_DISPLAY[self._rank]}"

def __lt__(self, other):


"""
other : Card
the other card to compare

1
Return : bool
True if the rank of self is smaller than the rank of other,
or the rank is the same but the suit of self is smaller
than the suit of other.

Ordering:
A < 2 < 3 < ... < 10 < J < Q < K for rank and
< < < for suit.
"""
if not isinstance(other, Card):
return NotImplemented

if self._rank != other._rank:
return self._rank < other._rank
return self._suit < other._suit

1.2 Teaching Notes


1. Overall goal
We want Card to represent one playing card.

• Internally we store integers for rank (1–13) and suit (1–4).


• We can display a card nicely as something like ’K’.
• We want to compare cards using <, e.g. for sorting.

“A Card object is our own data type for one playing card. We encode the rank and suit as
numbers so it’s easy to compare, and we provide methods to display and compare them.”

2. Lookup tables
Explain _SUIT_DISPLAY and _RANK_DISPLAY:

• Index 1–13 give the rank symbols: A, 2, . . . , 10, J, Q, K.


• Index 1–4 give the suits: , , , .
• Index 0 is None and is never used.

You can ask students:


“What is RANK DISPLAY[11]? What is SUIT DISPLAY[2]?”

3. init (constructor)
Key points:

• Validation: check that rank is between 1 and 13, and suit is between 1 and 4.
• If invalid, raise a clear ValueError.
• Store them as instance variables self._rank and self._suit.

Example to show in class:

c = Card(1, 4) # Ace of Spades


c2 = Card(11, 2) # Jack of Diamonds

2
4. str (string representation)
Explain:

• When we print(card), Python calls str ().

• We look up the suit symbol and rank symbol from the tables.

• Then we combine them using an f-string.

You can demonstrate:

c1 = Card(5, 2) # 5
c2 = Card(13, 4) # K
print(c1)
print(c2)

5. lt (less-than comparison)
Emphasise the rule:

• Compare rank first: A ¡ 2 ¡ 3 ¡ ... ¡ 10 ¡ J ¡ Q ¡ K.

• If ranks are equal, compare suit: ¡ ¡ ¡ .

Walk through the code:

• If ranks are different, just compare self._rank and other._rank.

• If ranks are equal, compare suits.

Nice quick check in class:

Card(1,1) < Card(1,4) # True: A < A


Card(13,1) < Card(1,4) # False: K > A

3
2 Deck Class
2.1 Code

import random
from card import Card # assuming Card is defined in [Link]

class Deck:
"""
Represent a deck of 52 standard playing cards.
A Deck can be shuffled, and cards can be drawn until empty.
"""

def __init__(self):
"""
Initialise the deck:
- create all 52 Card objects
- shuffle them
"""
self._cards = []
for rank in range(1, 14): # 113
for suit in range(1, 5): # 14
self._cards.append(Card(rank, suit))

[Link](self._cards)

def shuffle(self):
"""
Randomly shuffle the current deck.
Return: None
"""
[Link](self._cards)

def draw(self):
"""
Draw a card from the deck.
Return: Card (and remove it from the deck)

Raise: IndexError if the deck is empty


"""
if not self._cards:
raise IndexError("Cannot draw from an empty deck.")
return self._cards.pop()

def __str__(self):
"""
Return a string showing all remaining cards.
"""
return " ".join(str(card) for card in self._cards)

2.2 Notes
1. Goal of the Deck class
Explain that:

• A Deck object represents one full deck of 52 different cards.

4
• When we construct it, it should automatically create all 52 and shuffle them.

• We can shuffle again later, and we can draw cards until the deck is empty.

2. init : nested loops and creation


Key explanation:

• Use a nested loop to generate all combinations:

– rank goes from 1 to 13,


– suit goes from 1 to 4.

• For each pair (rank, suit), create one Card(rank, suit) and append it to self. cards.

• After we have all 52 cards, we call [Link](self. cards).

You can say:


“We are composing objects: a Deck ‘has many’ Card objects inside a list.”

3. shuffle()
• This simply re-shuffles whatever cards remain in self. cards.

• No return value.

4. draw()
Important points:

• If the list is empty, it raises an IndexError to signal that there are no cards left.

• Otherwise, it uses pop() to remove and return the last card.

• This ensures a card cannot be drawn twice.

You can show:

deck = Deck()
c1 = [Link]()
c2 = [Link]()
print(c1, c2)

5. str for Deck


Explain:

• We convert each remaining card to a string, then join them with spaces.

• This is mainly for debugging / visualisation: print(deck) shows the whole deck.

5
6. Suggested small classroom demo
You can run the following live:
deck = Deck()
print(deck) # see all 52 cards
c1 = [Link]()
c2 = [Link]()
print("Drew:", c1, c2)
print("Cards left:", len(deck._cards))
[Link]()
print("After shuffle:")
print(deck)

• What happens if we call draw() 52 times and then once more?

• Why is Deck a good example of “composition” rather than inheritance?

You might also like