- The casino game of craps involves rolling a pair of dice. The rules of the game are as follows. (Refer to Lesson A6 if you need to review the Random class)
- If you roll a 7 or 11 on the first roll, you win.
- If you roll a 2, 3, or 12 on the first roll, you lose.
- Otherwise, rolling a 4, 5, 6, 8, 9, or 10 establishes what is called the point value.
- If you roll the point value before you roll a 7, you win. If you roll a 7 before you match the point value, you lose.
- After the point value has been matched, or a 7 terminates the game, play resumes from the top.
The following sequences of dice rolls give these results.
7
4 5 3 7
8 6 2 8
3 |
player wins
player loses
player wins
player loses |
The rules of the game are set so that the house (casino) always wins a higher percentage of the games. Based on probability calculations, the actual winning percentage of a player is 49.29%.
A complete program, Craps.java, is provided in Handout A14.1. The application of DeMorgan’s Laws occurs in the getPoint()
method. The do-while
loop has a compound exit condition.
do{
sum = rollDice();
}
while ((sum != point) && (sum != 7));
-
When developing a conditional loop, it is very helpful to think about what assertions are true when the loop will be finished. In other words, when the loop is done, what will be true?
-
When the loop in getPoint
is done, one of two things will be true:
- the point will be matched
(sum == point)
.
- or a seven has been rolled.
These two statements can be combined into one summary assertion statement:
((sum == point) || (sum == 7))
-
The loop assertion states what will be true when the loop is done. Once you have established the loop assertion, writing the boundary condition involves a simple negation of the loop assertion.
- Taking the assertion developed in Section 6 above, the negation of the assertion follows.
!((sum == point) || (sum == 7))
- Applying DeMorgan's law results in
(!(sum == point)) && (!(sum == 7))
Rewriting each half of the expression gives
(sum != point) && (sum != 7)
-
Looking at the first half of the developing boundary condition, the statement (sum != point)
means that we have not yet matched the point. In other words, we haven’t won yet.
-
The second half of the boundary condition (value != 7)
means we have not yet “crapped” out (i.e., rolled a 7). In other words, we also haven’t lost yet, so we must keep rolling the dice.
- You may use the equivalent Boolean expressions in Sections 8 and 9 interchangeably. Choose the one that you think makes your code easier to read.