2
\$\begingroup\$

This is a dice game where, if you try to get as close as 24 without going over, you are allowed to "hit" three times. If you decide hit, you have the option of rolling one or two more dice. Player and computer alternate turns.

How should I alternate turns without repeating the code?

import java.util.*;

public class DiceGame {
   public static void main(String [] args) {
      int playerRoll1 = 0; int computerRoll1 = 0;
      int playerRoll2 = 0; int computerRoll2 = 0;
      int playerRoll3 = 0; int computerRoll3 = 0;
      int playerSum = 0; int computerSum = 0;
      int oneOrTwo = 0;
      String hitOrStay = "";                    //asks the player to hit or stay
      String newLine = "";                      //to consume newline character after scnr.nextInt()
      int loopCounter = 1;                      //keeps track of loop if computer/player hits
      int gamesWonPlayer = 0;                   //total rounds won by player
      int gamesWonComputer = 0;                 //total rounds won by computer     
      Scanner scnr = new Scanner(System.in);
      Random randGen = new Random();     

      System.out.println("What is your name?");
      String playerName = scnr.nextLine();      
      System.out.println("How many rounds do you want to play?");
      int gamesPlayed = scnr.nextInt();
      System.out.println();                      //prompts no. of round played
      newLine = scnr.nextLine();                 //consumes the newline character from above to make way for scnr.nextLine()

      int i = 1;
      while(i<=gamesPlayed && gamesWonPlayer<=(int)(gamesPlayed/2) && gamesWonComputer<=(int)(gamesPlayed/2)){//outermost loop based on no. of game played
         System.out.println("Let's begin round " + i);
         System.out.println("-------------------");           

         if (i % 2 == 1) {                        //if-else branch to alternate turns
            System.out.println("In round " + i + ", you will go first. \n");

            playerRoll1 = randGen.nextInt(6) + 1;
            playerRoll2 = randGen.nextInt(6) + 1;
            playerRoll3 = randGen.nextInt(6) + 1;
            playerSum = sumThreeRolls(playerRoll1, playerRoll2, playerRoll3);
            System.out.println("Your three dice rolls are " + playerRoll1 + ", " + playerRoll2 + " and " + playerRoll3 + ".");                       
            System.out.println("Your total score is " + playerSum + ".");                        
            if (playerSum < 24) {
               System.out.println("Do you want to hit or stay?");
               hitOrStay = scnr.nextLine(); 
            }                        

            loopCounter = 1;
            while (hitOrStay.toLowerCase().equals("hit")) {       //inner loop for if player hits                                    
               System.out.println("Do you want to roll one or two dice?");
               oneOrTwo = scnr.nextInt();
               newLine = scnr.nextLine();                         //consumes the newline character to make way for scnr.nextLine()                  
               if (oneOrTwo == 1) {
                  int playerRoll4 = randGen.nextInt(6) + 1;
                  playerSum = playerSum + playerRoll4;            //one additional roll
                  System.out.println("You roll one more die. It is " + playerRoll4 + ".");
               }
               else {
                  int playerRoll4 = randGen.nextInt(6) + 1;       //two additional rolls
                  int playerRoll5 = randGen.nextInt(6) + 1;       //--------------------
                  playerSum = playerSum + playerRoll4 + playerRoll5;
                  System.out.println("You roll two more dice. They are " + playerRoll4 + " and " + playerRoll5 + ".");
               }
               System.out.println("Your total score is " + playerSum + ".");               
               loopCounter++;
               hitOrStay = "";                
               if (playerSum < 24 && loopCounter <= 3) {
                  System.out.println("Do you want to hit or stay?");
                  hitOrStay = scnr.nextLine();
               }                                              
            }                                                     // end of inner while loop for if player hits                               
            System.out.println(); 

            computerRoll1 = randGen.nextInt(6) + 1;
            computerRoll2 = randGen.nextInt(6) + 1;
            computerRoll3 = randGen.nextInt(6) + 1;
            computerSum = sumThreeRolls(computerRoll1, computerRoll2, computerRoll3);
            System.out.println("Computer's three dice rolls are " + computerRoll1 + ", " + computerRoll2 + " and " + computerRoll3 + ".");                       
            System.out.println("Computer's total score is " + computerSum + ".");

            loopCounter =1;
            while (computerSum < 21 && loopCounter <= 3) {     //inner while loop if computer hits
               if (computerSum < 15) {
                  int computerRoll4 = randGen.nextInt(6) + 1;  //two additional rolls
                  int computerRoll5 = randGen.nextInt(6) + 1;  //^^^^^^^^^^^^^^^
                  computerSum = computerSum + computerRoll4 + computerRoll5;
                  System.out.println("Computer rolls two more dice. They are " + computerRoll4 + " and " + computerRoll5 + ".");
               }
               else if (computerSum <= 20) {
                  int computerRoll4 = randGen.nextInt(6) + 1;  //additional roll}
                  computerSum = computerSum + computerRoll4;
                  System.out.println("Compute rolls one more die. It is " + computerRoll4 + ".");
               }
               System.out.println("Computer's total score is " + computerSum + ".");
               loopCounter++;
            }                                            //end of inner while loop if computer hits
            System.out.println();                                          
         }                                               //end of if-else branch to alternate turns
         else {                                          //if-else branch to alternate turns
            System.out.println("In round " + i + ", computer will go first. \n");
            computerRoll1 = randGen.nextInt(6) + 1;
            computerRoll2 = randGen.nextInt(6) + 1;
            computerRoll3 = randGen.nextInt(6) + 1;
            computerSum = sumThreeRolls(computerRoll1, computerRoll2, computerRoll3);
            System.out.println("Computer's three dice rolls are " + computerRoll1 + ", " + computerRoll2 + " and " + computerRoll3 + ".");                       
            System.out.println("Computer's total score is " + computerSum + ".");

            loopCounter =1;
            while (computerSum < 21 && loopCounter <= 3) {     //inner while loop if computer hits
               if (computerSum < 15) {
                  int computerRoll4 = randGen.nextInt(6) + 1;  //two additional rolls
                  int computerRoll5 = randGen.nextInt(6) + 1;  //^^^^^^^^^^^^^^^
                  computerSum = computerSum + computerRoll4 + computerRoll5;
                  System.out.println("Computer rolls two more dice. They are " + computerRoll4 + " and " + computerRoll5 + ".");
               }
               else if (computerSum <= 20) {
                  int computerRoll4 = randGen.nextInt(6) + 1;  //additional roll}
                  computerSum = computerSum + computerRoll4;
                  System.out.println("Compute rolls one more die. It is " + computerRoll4 + ".");
               }
               System.out.println("Computer's total score is " + computerSum + ".");
               loopCounter++;
            }                                                  //end of inner while loop if computer hits
            System.out.println();

            playerRoll1 = randGen.nextInt(6) + 1;
            playerRoll2 = randGen.nextInt(6) + 1;
            playerRoll3 = randGen.nextInt(6) + 1;
            playerSum = sumThreeRolls(playerRoll1, playerRoll2, playerRoll3);
            System.out.println("Your three dice rolls are " + playerRoll1 + ", " + playerRoll2 + " and " + playerRoll3 + ".");                       
            System.out.println("Your total score is " + playerSum + ".");                        
            if (playerSum < 24) {
               System.out.println("Do you want to hit or stay?");
               hitOrStay = scnr.nextLine(); 
            }                        

            loopCounter = 1;
            while (hitOrStay.toLowerCase().equals("hit")) {       //inner loop for if player hits                                    
               System.out.println("Do you want to roll one or two dice?");
               oneOrTwo = scnr.nextInt();
               newLine = scnr.nextLine();                         //consumes the newline character to make way for scnr.nextLine()                  
               if (oneOrTwo == 1) {
                  int playerRoll4 = randGen.nextInt(6) + 1;
                  playerSum = playerSum + playerRoll4;            //one additional roll
                  System.out.println("You roll one more die. It is " + playerRoll4 + ".");
               }
               else {
                  int playerRoll4 = randGen.nextInt(6) + 1;       //two additional rolls
                  int playerRoll5 = randGen.nextInt(6) + 1;       //--------------------
                  playerSum = playerSum + playerRoll4 + playerRoll5;
                  System.out.println("You roll two more dice. They are " + playerRoll4 + " and " + playerRoll5 + ".");
               }
               System.out.println("Your total score is " + playerSum + ".");               
               loopCounter++;
               hitOrStay = "";                
               if (playerSum < 24 && loopCounter <= 3) {
                  System.out.println("Do you want to hit or stay?");
                  hitOrStay = scnr.nextLine();
               }                                              
            }                                                     // end of inner while loop for if player hits                               
            System.out.println();
         }                                                        //end of if-else branch to alternate turns

         if (playerSum <= 24 && computerSum <= 24) {               
            if (playerSum > computerSum) {
               System.out.println(playerName + " wins this round.");
               gamesWonPlayer++;
            }
            else {
               System.out.println("Computer wins this round.");
               gamesWonComputer++;
            }
         }      

         else if (playerSum > 24 && computerSum <= 24) {
            System.out.println("Computer wins this round.");
            gamesWonComputer++;  
         }

         else if (playerSum <= 24 && computerSum > 24) {
            System.out.println(playerName + " wins this round.");
            gamesWonPlayer++;
         }
         else {
            if (playerSum < computerSum) {
               System.out.println(playerName + " wins this round.");
               gamesWonPlayer++;      
            }
            else {
               System.out.println("Computer wins this round.");
               gamesWonComputer++;     
            }
         }
         System.out.println("TOTAL ROUNDS WON:\n" + playerName + ": " + gamesWonPlayer + " vs " + "Computer: " + gamesWonComputer + "\n");
         i++;
      }                           //end of outermost for loop based on gamePlayed

      if (gamesWonPlayer > gamesWonComputer)
         System.out.println(playerName.toUpperCase() + " WINS THE TOURNAMENT!!!");
      else if (gamesWonPlayer < gamesWonComputer)
         System.out.println("COMPUTER WINS THE TOURNAMENT!!!");
      else
         System.out.println("IT IS A TIE!!!");       
   }

   public static int sumThreeRolls(int roll1, int roll2, int roll3) {
      int sum = 0;
      if (roll1 == roll2 && roll2 == roll3)
         sum = 24;
      else
         sum = roll1 + roll2 + roll3;
      return sum;

   }   
}
\$\endgroup\$

migrated from stackoverflow.com Mar 13 '16 at 3:40

This question came from our site for professional and enthusiast programmers.

  • 1
    \$\begingroup\$ Oh boy ........ ;) it would be a good idea to notice duplication before you write all of that ;) \$\endgroup\$ – dbf Mar 6 '16 at 12:38
2
\$\begingroup\$

Example code:

import static java.lang.System.out;
import java.util.Random;
import java.util.Scanner;

public class DiceGame {

    private static final Random randGen = new Random();
    private static final Scanner scnr = new Scanner(System.in);
    private static String playerName;

    public static void main(String[] args) {

        out.println("What is your name?");
        playerName = scnr.nextLine();
        out.println("How many rounds do you want to play?");
        int roundsToPlay = scnr.nextInt();
        scnr.nextLine(); //consumes the newline character from above to make way for scnr.nextLine()
        out.println();

        int roundsWonPlayer = 0, roundsWonComp = 0;
        for (int roundsPlayed = 0; roundsPlayed < roundsToPlay &&
                roundsWonPlayer <= roundsToPlay / 2 &&
                roundsWonComp <= roundsToPlay / 2; roundsPlayed++) {

            out.format("Let's begin round %d%n", roundsPlayed + 1);
            out.println("-------------------");

            boolean youFirst = (roundsPlayed & 1) == 1;
            out.format("In round %d, %s will go first.%n", roundsPlayed + 1, getRoundName(youFirst));

            int score1 = doTurn(youFirst),
                    score2 = doTurn(!youFirst),
                    playerScore = youFirst ? score1 : score2,
                    compScore = youFirst ? score2 : score1;

            boolean playerWins;
            if (playerScore <= 24 && compScore <= 24) {
                playerWins = playerScore > compScore;
            } else if (playerScore > 24 && compScore <= 24) {
                playerWins = false;
            } else if (playerScore <= 24 && compScore > 24) {
                playerWins = true;
            } else {
                playerWins = playerScore < compScore;
            }

            out.format("%s wins this round.%n", playerWins ? playerName : "Computer");
            if (playerWins) {
                roundsWonPlayer++;
            } else {
                roundsWonComp++;
            }

            out.format("TOTAL ROUNDS WON:%n"
                    + "%s: %d%n"
                    + "Computer: %d%n%n",
                    playerName, roundsWonPlayer, roundsWonComp);
        }

        if (roundsWonPlayer > roundsWonComp) {
            out.format("%s WINS THE TOURNAMENT!!!%n", playerName.toUpperCase());
        } else if (roundsWonPlayer < roundsWonComp) {
            out.println("COMPUTER WINS THE TOURNAMENT!!!");
        } else {
            out.println("IT IS A TIE!!!");
        }
    }

    private static int doTurn(boolean yourTurn) {
        String roundName = getRoundName(yourTurn);
        int[] rolls = getRolls();

        out.format("Dice rolls for %s: ", roundName);
        for (int i = 0; i < rolls.length - 1; i++) {
            out.format("%d, ", rolls[i]);
        }
        out.format("and %d.%n", rolls[rolls.length - 1]);

        int sum = getRollScore(rolls);
        out.format("Score for %s: %d%n", roundName, sum);

        for (int hitCounter = 0; hitCounter < 3; hitCounter++) {
            if (yourTurn && sum >= 24 || !yourTurn && sum >= 21) {
                break;
            }
            boolean rollOne;
            if (yourTurn) {
                out.println("Do you want to hit or stay?");
                if (!scnr.nextLine().equalsIgnoreCase("hit")) {
                    break;
                }
                out.println("Do you want to roll one (1) or two (2) dice?");
                rollOne = scnr.nextInt() == 1;
                scnr.nextLine();  //consumes the newline character to make way for scnr.nextLine()                  
            } else {
                rollOne = sum >= 15;
            }

            int roll4 = newRoll();
            sum += roll4;            //one additional roll
            if (rollOne) {
                out.format("%s rolls one more die. It is %d.%n", roundName, roll4);
            } else {
                int roll5 = newRoll();
                sum += roll5;
                out.format("%s rolls two more dice. They are %d and %d.%n", roundName, roll4, roll5);
            }
            out.format("%s's total score is %d.%n", roundName, sum);
        } 
        out.println();

        return sum;
    }

    private static String getRoundName(boolean yourTurn) {
        return yourTurn ? playerName : "computer";
    }

    private static int getRollScore(int[] roll) {
        if (roll[0] == roll[1] && roll[0] == roll[2]) {
            return 24;
        }
        return roll[0] + roll[1] + roll[2];
    }

    private static int newRoll() {
        return randGen.nextInt(6) + 1;
    }

    private static int[] getRolls() {
        return new int[]{newRoll(), newRoll(), newRoll()};
    }
}

Suggestions:

  • Use functions where appropriate
  • Use static imports where appropriate to abbreviate static calls
  • Use consistent names (i.e. round instead of game)
  • Use String.format where appropriate
  • Use equalsIgnoreCase where appropriate
  • Declare variables where they're used, not at the beginning of function scope (this is a C twang that you need to avoid)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy