|
|
|
|
|
|
|
1. Take a deck of playing cards and shuffle it. |
|
|
|
|
|
|
|
|
2. Place four cards side by side, left to right, face up on the table. |
|
|
|
|
|
|
|
|
3. If the four cards (or the rightmost four if there are more than four on the table) are of the same suit, move them to a discard pile. Otherwise, if the first one and the fourth one (of the rightmost four cards) are of the same suit, move the other two cards (second and third) to a discard pile. Repeat until no cards can be removed. |
|
|
|
|
|
|
|
|
4. Take the next card from the shuffled deck and place it face up to the right of those already there. Repeat this step if there are fewer than four cards face up (assuming there are more cards in the deck). |
|
|
|
|
|
|
|
|
5. Repeat Steps 3 and 4 until there are no more cards in the deck. You win if all the cards are on the discard pile. |
|
|
|
|
|
|
|
|
Figure 18-7 walks us through the beginning of a typical game to demonstrate how the rules operate. Remember that the game deals with suits only. There must be at least four cards face up on the table before the rules can be applied. |
|
|
|
|
|
|
|
|
Input: The number of times the simulation is to be run (numberOfGames), the number of times the deck is to be shuffled between games (numberOfShuffles), and an initial seed value for a random number generator (seed). We discuss the seed variable later. |
|
|
|
|
|
|
|
|
Output: The number of games played, and the number of games won. |
|
|
|
|
|
|
|
|
Discussion: A program that plays a game is an example of a simulation program. The program simulates what a human does when playing the game. Programs that simulate games or real-world processes are very common in computing. |
|
|
|
|
|
|
|
|
In developing a simulation, object-oriented design helps us decide how to represent the physical items being simulated. In a card game, the basic item is, of course, a card. A deck of cards becomes a list of 52 cards in the program. We can use a variation of the CardPile class developed in the previous case study to represent the deck. |
|
|
|
|
|
|
|
|
Cards face up on the table and the discard pile must also be simulated in this program. Putting a card face up on the table means that a card is being taken from the deck and put onto the table where the player can see it. The cards on the table can be represented by a CardPile class object. The rules that determine whether or not cards can be moved to the discard pile are applied to the top four cards in this listthat is, the last four cards put into the list. |
|
|
|
|
|
|
|
|
The discard pile is also a list of cards and can be represented as a CardPile class object. If no cards remain on the table (they are all on the discard pile) at the end of the game, then the player has won. If any cards remain on the table face up, the player has lost. |
|
|
|
|
|