Java Reference
In-Depth Information
9
10
// enum type with constants that represent the game status
private enum
Status {
CONTINUE
,
WON
,
LOST
};
11
12
13
// constants that represent common rolls of the dice
14
private static final int
SNAKE_EYES
=
2
;
private static final int
TREY
=
3
;
private static final int
SEVEN
=
7
;
private static final int
YO_LEVEN
=
11
;
private static final int
BOX_CARS
=
12
;
15
16
17
18
19
20
// plays one game of craps
21
public static void
main(String[] args)
22
{
23
int
myPoint =
0
;
// point if no win or loss on first roll
24
Status gameStatus;
// can contain CONTINUE, WON or LOST
25
26
int
sumOfDice = rollDice();
// first roll of the dice
27
28
// determine game status and point based on first roll
29
switch
(sumOfDice)
30
{
31
case
SEVEN
:
// win with 7 on first roll
case
YO_LEVEN
:
// win with 11 on first roll
gameStatus =
Status.WON
;
32
33
34
break
;
35
case
SNAKE_EYES
:
// lose with 2 on first roll
case
TREY
:
// lose with 3 on first roll
case
BOX_CARS
:
// lose with 12 on first roll
gameStatus =
Status.LOST
;
36
37
38
39
break
;
40
default
:
// did not win or lose, so remember point
gameStatus =
Status.CONTINUE
;
// game is not over
myPoint = sumOfDice;
// remember the point
41
42
43
System.out.printf(
"Point is %d%n"
, myPoint);
44
break
;
45
}
46
47
// while game is not complete
48
while
(
gameStatus ==
Status.CONTINUE
)
// not WON or LOST
49
{
50
sumOfDice = rollDice();
// roll dice again
51
52
// determine game status
53
if
(sumOfDice == myPoint)
// win by making point
54
gameStatus =
Status.WON
;
55
else
56
if
(sumOfDice ==
SEVEN
)
// lose by rolling 7 before point
57
gameStatus =
Status.LOST
;
58
}
59
Fig. 6.8
|
Craps
class simulates the dice game craps. (Part 2 of 3.)