Java Reference
In-Depth Information
7.5 Introducing the enum Construct
We will next write a game that is similar to the Yahtzee game. However, we will use
coins instead of dice. Every coin has two faces: heads and tails. When we flip a coin, we can
get either heads or tails (depending of which face is on top). Every coin also has a value: 1,
5, 10, or 25. This is the value of the coin in cents. In the game, we will flip ten coins in the
air and let them land. We will assume that the value of a coin can only be seen if the coin
is tails. As Figure 7.3 suggests, the value of a coin is not visible when it is heads. Our score
is the sum of the face values of all the coins that are tails. Once we get our score, we have
two choices: either reroll selected coins or keep the current total. We are allowed up to two
Our solution will be similar to the Yahtzee solution from Chapter 6 in that we will use
a multi-class approach. However, this time we will use an ArrayList insteadofanarray.
Let us start with the Coin class (i.e., we will perform a bottom-up design as we did in the
Battleship game). A coin has two variables: value and face . The first value represents the
value of the coin, while the second value is the face of the coin. To be even more general,
we will assume that our coin does not need to be fair. We will introduce a variable bias ,
which represents the probability that the coin is heads. One of our constructors will take
as input the value and the bias of the coin and flip it to determine if the coin is heads or
tails. Another constructor will take as input only the value of the coin and use the default
bias. We will also add a toString method that returns a string description of the coin. A
possible implementation follows.
public class Coin
public static final double DEFAULT BIAS = 0 . 5 ;
private int value ;
private boolean face ;
private double bias ;
public Coin() {
this . b i a s = DEFAULT BIAS ;
this . value = getRandomCoinValue () ;
} public Coin( int value) {
this . value = value ;
this . b i a s = DEFAULT BIAS ;
} public Coin( int value , double bias) {
this . value = value ;
FIGURE 7.3: Heads of different coins.
Search WWH ::

Custom Search