Example: A Game of Chance
The Rules of Crap
- A player rolls 2 dice, each of which has 6 faces, numbered 1 - 6.
- If the sum of the dice is 7 or 11, the player wins.
- If the sum of the dice is 2, 3, or 12, the player loses.
- Otherwise, the sum of the dice becomes the player's point.
- To win, the player must roll that sum again before rolling a sum of 7.
- Otherwise, the player loses.
Program Comments
- Method rollDice is invoked from 2 points in the applet. (Is that necessary?)
- It returns the sum of the 2 dice, hence the return type of int.
- Taking no arguments, it always generates 2 random numbers in the interval [1, 6].
- The int variable gameStatus and the boolean variable firstRoll record the state of the game:
- gameStatus has 3 possible values: WON, LOST, and CONTINUE.
- The keyword final preceding their int declaration indicates that the value of these variables is not to be
changed at execution.
- Capitalization of such variables is a programmer custom that goes back to the C programming language.
- We use a GUI component that we've not used before: a Button.
- Our action method is invoked whenever the Button, roll, is clicked.
- What happens if we press enter or return while the cursor is in a TextField? Why?