So I'm writing a program where two users take turns rolling a die. If the user rolls a 1 then their turn ends, if the user rolls 2-6 then I'm supposed to keep a running total of the points scored until the user either decides to roll again and risk his stored points for the round or to save it.
The problem I'm currently having now has to do with where I should place a while loop in my code so that the user can play for an undetermined amount of time. Ideally I would like to get out of the while loop whenever the user rolls a 1, but I'm also having trouble with how to update that number every time outside of the loop.
Any help would be much appreciated! Note: The game isn't finished yet, I'm trying to write through some of these problems before moving on, also the place where I'd like to put my while loop is in the takeTurn method.
Thanks again!
Here is my code:
import java.util.*;
public class PigDice {
// when a player reaches this number, they win
public static final int WINNING_SCORE = 50;
public static final int DIE = 6; // sides on a die.
public static void main( String[] args ) {
Scanner keyboard = new Scanner( System.in );
Random rand = new Random();
String winner = playGame( keyboard, rand );
System.out.println( winner + " wins!" );
}
public static String playGame( Scanner scanner, Random rand ) {
int score1 = 0; // player 1's score
int score2 = 0; // player 2's score
// play till someone wins
while ( score1 < WINNING_SCORE && score2 < WINNING_SCORE ) {
score1 += takeTurn( scanner, rand, 1, score1 );
System.out.println( "Player 1 score: " + score1 );
System.out.println( "***************************" );
if ( score1 < WINNING_SCORE ) {
score2 += takeTurn( scanner, rand, 2, score2 );
System.out.println( "Player 2 score: " + score2 );
System.out.println( "***************************" );
}
}
if ( score1 >= WINNING_SCORE ) {
return "Player 1";
}
else {
return "Player 2";
}
}
public static int takeTurn( Scanner scanner, Random rand, int player, int score ) {
int random = rand.nextInt(DIE)+ 1;
System.out.println("Player " + player + " rolls: " + random);
int firstRoll = random;
int roundTotal = 0;
if ( random > 1) {
System.out.println( "Player " + player + " total for this round: " + firstRoll);
roundTotal += firstRoll;
System.out.print("Roll again? (y or n) : ");
String getAnswer = scanner.nextLine();
System.out.println();
if ( "y".equalsIgnoreCase(getAnswer)) {
System.out.println("Player " + player + " rolls: " + random);
}else if ( "n".equalsIgnoreCase(getAnswer)) {
System.out.println("Player " + player + " score: " + roundTotal);
}
}else {
System.out.println("Player " + player + ": turn ends with no new points.");
System.out.println("Player " + player + " score: " + score);
}
return WINNING_SCORE;
}
}