In: Computer Science
In Java Language.
Must Include Comments.
We will simulate a dice game in which 2 dice are rolled.
If the roll is 7 or 11, you win.
If the roll is 2, 3 or 12, you lose
If the roll is any other value, it establishes a point.
If, with a point established, that point is rolled again before a 7, you win.
If, with a point established, a 7 is rolled before the point is rolled again you lose.
Build your algorithm incrementally. First write a program that simulates a roll of two dice, then
outputs if it is a simple win (7 or 11), or a simple loss (2 or 3 or 12), or something else.
1. I will help you with the algorithm:
//get a random number between 1 and 6, call it d1
//get a second random number between 1 and 6, call it d2.
//compute the total & print it so we know what it was
//if the total is 7 or 11 print “congratulations, you win”
// else if the total is 2 or 3 or 12 print “you lose”
//else print “something else”
2. Create the program and test it by running it a few times to verify that you are correctly
printing whether you won, lost, or “something else”.
3. Now fix the part where you wrote “something else”. In this case you rolled a number which
we called total. We need to keep rolling the dice and looking at the new total each time. If the
new total is the same as total, you win. If the new total is 7, you lose. And if something else
you roll again...... For example, an initial total of 6 was neither a win or a lose. So 6 is now
the important number called “point” above. Roll the dice again, if it is 6 you win, and if 7 you
lose. If anything else you roll again and keep doing so until you roll either a 6 and win, or 7
and lose.
Write this part of your algorithm here (or on another piece of paper). Once we verify your logic is
correct you may code it.
CODE IN JAVA:
DiceGame.java file:
import java.util.Random;
public class DiceGame {
public static void main(String[] args) {
//creating object to the Random class to generate random numbers
Random r = new Random();
//simulating the rolling of two dice
int die1 = r.nextInt(6) + 1;
int die2 = r.nextInt(6) + 1;
int roll = die1 + die2;
System.out.println("The roll is:" + roll);
//checking the roll
if (roll == 7 || roll == 11) {
System.out.println("Congratulations, You win the game");
} else if (roll == 2 || roll == 3 || roll == 12) {
System.out.println("You lose the game");
} else {
System.out.println("Roll again...");
die1 = r.nextInt(6) + 1;
die2 = r.nextInt(6) + 1;
int total = die1 + die2;
System.out.println("The roll is:" + total);
while (total != roll && total != 7) {
System.out.println("Roll again...");
die1 = r.nextInt(6) + 1;
die2 = r.nextInt(6) + 1;
total = die1 + die2;
System.out.println("The roll is:" + total);
}
if (total == roll) {
System.out.println("Congratulations, You win the game");
} else {
System.out.println("You lose the game");
}
}
}
}
OUTPUT:
