Chapter 14. Extending Classes
In this chapter, we present a comprehensive example of object-oriented programming. Crazy Eights is a classic card game for two or more players. The main objective is to be the first player to get rid of all your cards. Here’s how to play:
Deal five or more cards to each player, and then deal one card face up to create the discard pile. Place the remaining cards face down to create the draw pile.
Each player takes turns placing a single card on the discard pile. The card must match the rank or suit of the previously played card, or be an eight, which is a wildcard.
When players don’t have a matching card or an eight, they must draw new cards until they get one.
If the draw pile ever runs out, the discard pile is shuffled (except the top card) and becomes the new draw pile.
As soon as a player has no cards, the game ends, and all other players score penalty points for their remaining cards. Eights are worth 20, face cards are worth 10, and all others are worth their rank.
You can read Wikipedia’s “Crazy Eights” entry for more details, but we have enough to get started.
CardCollection
To implement Crazy Eights, we need to represent a deck of cards, a discard pile, a draw pile, and a hand for each player. And we need to be able to deal, draw, and discard cards.
The Deck
and Pile
classes from the previous chapter meet some of these requirements. But unless we make some changes, neither of them represents a hand of cards very well.
Furthermore, Deck
and ...
Get Think Java, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.