I am trying to write a method that simulates a dice game in which a dice (with values from 1 to 6) is rolled four times, and that returns true if there is at least one 6 rolled, and false otherwise. The game is 'won' if true is returned.
I declare two variables to keep track of the number of times a '6' is thrown, and another to keep track of whether the game is won (i.e. if a 6 is thrown).
I then use a for loop to simulate the rolling of the dice; this increments the count of the number of 6's rolled, if a 6 is thrown.
I then use conditionals to return true, if a 6 has been thrown, and false otherwise.
I would expect that if I run the code enough times, that true would be returned on at least some occasions (i.e. I would 'win' the game). When I actually run the code however, I only ever get false returned.
What am I doing wrong?
Here is my code:
import java.util.Random;
public class DiceGame {
Random generator;
public DiceGame() {
generator = new Random(45);
}
/**
* Throw a die four times and bet on at least one 6.
* @return true if the chevalier wins.
*/
public boolean game1() {
int trueDice = 0;
boolean gameWon = false;
for (int i=0; i < 4;i++) {
int dieRoll = generator.nextInt(6);
if (dieRoll == 6) {
trueDice++;
}
}
if (trueDice >= 1) {
gameWon = true;
} else {
gameWon = false;
}
return gameWon;
}
Thanks in advance for any help.