import cs1.Keyboard;
public class craps {
// Program to simulate playing several games of craps with the
user
// Authors: CS105 class
Date: February 12, 2002
public static void main(String[] args) {
// variable declarations
int die1, die2, roll, firstroll;
//
Each die is a random integer from 1-6; each of
// 'roll' and 'firstroll' is the sum of two dice.
char game = 'y';
// User decides when to quit playing
System.out.println("Welcome to craps!");
// Each time through the loop, play one
game and display the result
while (game == 'y') {
// compute first roll
die1 = (int)(Math.random()*6
+ 1);
die2 = (int)(Math.random()*6
+ 1);
firstroll = die1 + die2;
// check for immediate
win or loss (and display result)
if (firstroll == 7 ||
firstroll == 11)
System.out.println("You
rolled " + firstroll + " and won!");
else if (firstroll ==
2 || firstroll == 3 || firstroll == 12)
System.out.println("You
rolled " + firstroll + " and lost!");
else {
// if not, continue
rolling (and display intermediate rolls)
System.out.print("You
rolled " + firstroll);
die1
= (int)(Math.random()*6 + 1);
die2
= (int)(Math.random()*6 + 1);
roll
= die1 + die2;
while
(roll != firstroll && roll != 7) {
System.out.print(", " + roll);
die1 = (int)(Math.random()*6 + 1);
die2 = (int)(Math.random()*6 + 1);
roll = die1 + die2;
}
// end of while loop
System.out.print(",
" + roll);
if
(roll == firstroll)
System.out.println(" and made your point!");
else
System.out.println(" and crapped out!");
}
System.out.println("Want
to play again? (y/n)");
game = Keyboard.readChar();
} // end of while loop
}
}
Below is the result of a sample run of this program in which the user wants to play exactly 10 games. Hmmm... two wins and 8 losses... looks like a very bad day at the tables!
Part 1 Questions
Step 1 - Design a Program to Monitor the Game
Before writing this program, it is useful to sit down and determine its overall design by answering for yourself the following questions:
A typical dialog between the program and the user should look like this:
Step 2 - Type and Run the Program
When you type your program, it should be saved with a file name that identifies you uniquely, such as lab4atucker.java . Be sure to add this program to your project (in place of the craps.java program) before you run it.
Step 3 - Debugging
As you test the program, try using the Debug option to single-step through it and observe the values of the variables as they change. Also, observe how control changes from one method to another as you enter and return from each call.
Step 4 (Optional) - A Perfect Strategy?
Rather than use a random number to govern the computer's next move, is there a better strategy that can be used to guarantee that the computer never loses? If so, how would you alter the program so the computer never loses?