Course 1.2Lesson 5 of 5
In this project we build a deck of playing cards. A Card knows its rank and suit, and has special methods so that two cards can be compared for equality, put in order by rank and then by suit, and shown as text. A Deck has fifty-two Cards, which is composition, and can say how many cards are left, shuffle, and deal a number of cards, refusing when there are not enough. We plan the expected results by hand, build the classes, test the order of cards and the refused deal, and extend the project with a hand class and a simple game.
Try the code and the simulations beside the lesson.
After this lesson you can
A card game needs cards and a deck. We want:
A of spades, that can be compared (==, <) so that a hand can be sorted, and that knows its value,| Class | It knows | It does |
|---|---|---|
Card | rank, suit | value(), ==, <, text |
Deck | a list of Card objects | len, shuffle, deal |
Deck has Card objects: composition. A card is not a kind of deck, and a deck is not a kind of card.
Work out by hand.
A is the highest (value 12) and 2 the lowest (value 0).| Test | Expected |
|---|---|
| a new deck | 52 cards, no repeated card |
| deal 5 | the hand has 5 cards, the deck has 47, and no card of the hand is still in the deck |
| deal 100 | refused, and the deck is unchanged |
| deal 0 | an empty hand, the deck is unchanged |
Card("A", "spades") == Card("A", "spades") | True |
| 2 of clubs against 2 of hearts | the 2 of clubs is less |
| 3 of clubs against 2 of spades | the 3 is greater, because the rank decides first |
| the same seed twice | the same hand |
The last row tests chance: the same seed must give the same shuffle.
len(deck) works because Deck has __len__. A shuffle would mix the suits, but the count would be the same.
Pick one or two, and do them without looking at a solution. Write the expected results first.
Hand has a list of cards, shows them sorted, and tells the total value.value and the comparison do?__eq__. Return NotImplemented for an object that is not a Card.__str__ that prints. It must return.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
Deck has Card objects.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
deal check the number of cards first?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.