Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need a java code that uses objects for this question Exercise 2 of 2: Create a

ID: 3736351 • Letter: I

Question

I need a java code that uses objects for this question

Exercise 2 of 2: Create a program that lets the player play a simplified game of Yahtzee. The game starts with the user throwing five 6-sided dice. The user can choose which dice to keep and which dice to re-roll. The user can re-roll a maximum of 2 times. After two times, the user has 5 dice with a certain value. The player then has to choose where they want their final combination of dice values applied. The following list is a simplified Yahtzee card, which we will use for this game: Ones, Twos, Threes, Fours, Fives, Sixes, 3 of a kind, 4 of a kind, Full House, Straight, Yahtzee For a Full House, the player needs 3 of a kind AND 2 of a kind. For a Straight, the player needs to have all 5 dice in consecutive order, i.e. either 1 ,2, 3, 4, 5, or 2, 3, 4, 5, 6. Yahtzee means 5 of a kind. If the player applies his dice score to something inapplicable, e.g. the player only has 2 of a kind, but applies it to 3 of a kind, or the player has no Ones, but applies his dice result to the Ones category, he scores zero in this category. Implementing the Bonus, Small Straight, and Chance (as usually available in most Yahtzee games) is not required for this homework exercise. Requirement: You wil need a random number generator for the dice roll. Make use of objects, which means either create a Dice class for the 5 dice, or implement a class that represents the 5 dice together (the choice is up to you.) Also, as mentioned, the player can re-throw his dice up to two times. The player can chose which dice to re-throw and which to keep.

Explanation / Answer

     /**
     * this is java program which allow user to play Yahtzee with 5 dice also keep score.
     */

import java.util.*;
  
    public class YahtzeeClass {
      public static void main(String[] args) {
        int play = 1, score = 0, sum = 0;
        int[] wins = new int[15];
        while ((play == 1) && (sum < 15)) {
          sum = 0;
          int[] DiceArray = new int[] { 0, 0, 0, 0, 0 };// creates an array
          int roll = 0;
          int x, y, w, z;
          int roll_againA = 0, roll_againB = 03;
          Die die = new Die();
          for (x = 0; x < 5; x++) {
            die.roll();
            DiceArray[x] = die.get();// sets the dice values
          }
   
          System.out.println("this is Die 1: " + DiceArray[0]);
          System.out.println("this is Die 2: " + DiceArray[1]);
          System.out.println("this is Die 3: " + DiceArray[2]);
          System.out.println("this is Die 4: " + DiceArray[3]);
          System.out.println("this is Die 5: " + DiceArray[4]);
   
          do {
            roll_againA = inputInt("How many dice do you want to reroll? (0-5)");
            if (roll_againA > 0) {
              int[] reroll = new int[roll_againA];
              for (y = 0; y < roll_againA; y++) {
                roll_againB = inputInt("Which ones?");
                reroll[y] = roll_againB;
              }
              for (w = 0; w < roll_againA; w++) {
                if (reroll[w] == 1) {
                  die.roll();
                  DiceArray[0] = die.get();
                }
                if (reroll[w] == 2) {
                  die.roll();
                  DiceArray[1] = die.get();
                }
                if (reroll[w] == 3) {
                  die.roll();
                  DiceArray[2] = die.get();
                }
                if (reroll[w] == 4) {
                  die.roll();
                  DiceArray[3] = die.get();
                }
                if (reroll[w] == 5) {
                  die.roll();
                  DiceArray[4] = die.get();
                }
              }
              roll++;
              System.out.println("Die 1: " + DiceArray[0]);
              System.out.println("Die 2: " + DiceArray[1]);
              System.out.println("Die 3: " + DiceArray[2]);
              System.out.println("Die 4: " + DiceArray[3]);
              System.out.println("Die 5: " + DiceArray[4]);
   
            }
          } while ((roll < 2) && (roll_againA > 0));
          Winnings prize = new Winnings();
          prize.checkWinnings(DiceArray, wins);
          wins[prize.choice() - 1] = 1;
          for (z = 0; z < 15; z++) {
            sum += wins[z];
          }
          score += prize.score();
          System.out.println("Your total score is: " + score);
          if (sum < 15) {
            play = inputInt("do you want to play again?(1=yes, 2=no)");
          } else {
            System.out.println("GAME OVER!");
          }
        }
      }
   
      static int inputInt(String Prompt) {
        int result = 0;
        try {
          result = Integer.parseInt(input(Prompt).trim());
        } catch (Exception e) {
          result = 0;
        }
        return result;
      }
   
      static String input(String prompt) {
        String inputLine = "";
        System.out.print(prompt);
        try {
          java.io.InputStreamReader sys = new java.io.InputStreamReader(
              System.in);
          java.io.BufferedReader inBuffer = new java.io.BufferedReader(sys);
          inputLine = inBuffer.readLine();
        } catch (Exception e) {
          String err = e.toString();
          System.out.println(err);
        }
        return inputLine;
      }
    }
   
    /* The class for handling each of the dice */
    class Die {
      private int value;
      private Random rand;
   
      public Die() {
        value = 0;
        rand = new Random();
      }
   
      public void roll() {
        value = 1 + rand.nextInt(6);
      }
   
      public int get() {
        return (value);
      }
    }
   
    /* The class for determining what you have (i.e. a pair, straight, etc) */
    class Winnings {
      private int score;
      private int choice;
   
      public Winnings() {
        score = 0;
      }
   
      public void checkWinnings(int[] DiceArray, int[] wins) {
        System.out.println("Which do you want to see if you have?");
        if (wins[0] == 0) {
          System.out.println("1 - yahtzee");
        }
        if (wins[1] == 0) {
          System.out.println("2 - full house");
        }
        if (wins[2] == 0) {
          System.out.println("3 - large straigt");
        }
        if (wins[3] == 0) {
          System.out.println("4 - small straigt");
        }
        if (wins[4] == 0) {
          System.out.println("5 - four of a kind");
        }
        if (wins[5] == 0) {
          System.out.println("6 - three of a kind");
        }
        if (wins[6] == 0) {
          System.out.println("7 - pair");
        }
        if (wins[7] == 0) {
          System.out.println("8 - two pair");
        }
        if (wins[8] == 0) {
          System.out.println("9 - number of 1's");
        }
        if (wins[9] == 0) {
          System.out.println("10 - number of 2's");
        }
        if (wins[10] == 0) {
          System.out.println("11 - number of 3's");
        }
        if (wins[11] == 0) {
          System.out.println("12 - number of 4's");
        }
        if (wins[12] == 0) {
          System.out.println("13 - number of 5's");
        }
        if (wins[13] == 0) {
          System.out.println("14 - number of 6's");
        }
        if (wins[14] == 0) {
          System.out.println("15 - chance");
        }
        choice = YahtzeeClass.inputInt("");
   
        int x = 0, y = 0, winings = 0, winingsa = 0;
        int twos = 0, threes = 0, fours = 0, fives = 0, sixes = 0;
        Arrays.sort(DiceArray);
   
        //Numbers
        for (y = 0; y < 5; y++) {
          if (DiceArray[y] == 1) {
            ones++;
          }
          if (DiceArray[y] == 2) {
            twos++;
          }
          if (DiceArray[y] == 3) {
            threes++;
          }
          if (DiceArray[y] == 4) {
            fours++;
          }
          if (DiceArray[y] == 5) {
            fives++;
          }
          if (DiceArray[y] == 6) {
            sixes++;
          }
        }
   
        //Straights
        if ((DiceArray[0] == DiceArray[1] - 1) && (DiceArray[1] == DiceArray[2] - 1)
            && (DiceArray[2] == DiceArray[3] - 1) && (DiceArray[3] == DiceArray[4] - 1)
            && (choice == 3)) {
          winingsa = 1;
        } else if ((ones > 0) && (twos > 0) && (threes > 0) && (fours > 0)) {
          winingsa = 2;
        } else if ((threes > 0) && (fours > 0) && (fives > 0) && (sixes > 0)) {
          winingsa = 2;
        } else if ((twos > 0) && (threes > 0) && (fours > 0) && (fives > 0)) {
          winingsa = 2;
        }
   
        //Pairs
        for (x = 0; x < 5; x++) {
          if (x != 0) {
            if ((DiceArray[0] == DiceArray[x])) {
              winings++;
            }
          }
          if ((x != 0) && (x != 1)) {
            if ((DiceArray[1] == DiceArray[x])) {
              winings++;
            }
          }
          if ((x != 0) && (x != 1) && (x != 2)) {
            if ((DiceArray[2] == DiceArray[x])) {
              winings++;
            }
          }
          if ((x != 0) && (x != 1) && (x != 2) && (x != 3)) {
            if ((DiceArray[3] == DiceArray[x])) {
              winings++;
            }
          }
        }
   
        //Winnings
        if ((winingsa == 1) && (choice == 3)) {
          System.out.println("You have a straight.");
          score = 40;
        } else if ((winingsa == 2) && (choice == 4)) {
          System.out.println("You have a small straight.");
          score = 30;
        } else if ((winings == 10) && (choice == 1)) {
          System.out.println("Yatzee!");
          score = 50;
        } else if ((choice == 6) && (winings >= 3)) {
          System.out.println("You have three of a kind.");
          score = DiceArray[0] + DiceArray[1] + DiceArray[2] + DiceArray[3] + DiceArray[4];
        } else if ((choice == 7) && (winings > 0)) {
          System.out.println("You have a pair.");
          score = 5;
        } else if ((winings == 2) && (choice == 8)) {
          System.out.println("You have two pairs.");
          score = 10;
        } else if ((winings == 4) && (choice == 2)) {
          System.out.println("You have a full house.");
          score = 25;
        } else if ((winings >= 6) && (choice == 5)) {
          System.out.println("You have four of a kind.");
          score = DiceArray[0] + DiceArray[1] + DiceArray[2] + DiceArray[3] + DiceArray[4];
        } else if (choice == 9) {
          System.out.println("You have " + ones + " ones.");
          score = ones;
        } else if (choice == 10) {
          System.out.println("You have " + twos + " twos.");
          score = twos * 2;
        } else if (choice == 11) {
          System.out.println("You have " + threes + " threes.");
          score = threes * 3;
        } else if (choice == 12) {
          System.out.println("You have " + fours + " fours.");
          score = fours * 4;
        } else if (choice == 13) {
          System.out.println("You have " + fives + " fives.");
          score = fives * 5;
        } else if (choice == 14) {
          System.out.println("You have " + sixes + " sixes.");
          score = sixes * 6;
        } else if (choice == 15) {
          score = DiceArray[0] + DiceArray[1] + DiceArray[2] + DiceArray[3] + DiceArray[4];
          System.out.println("Your get " + score + " points.");
        } else {
          System.out.println("You got nothin'.");
          score = 0;
        }
      }
   
      public int score() {
        return (score);
      }
   
      public int choice() {
        return (choice);
      }
    }

-------------------------------------------------------------------------------

i am also given program which play yahtzee

/*
* File: yeahtzee.java
* This program plays the yeahtzee game.
*/

import java.util.ArrayList;
import acm.io.*;
import acm.program.*;
import acm.util.*;

public class yeahtzee extends GraphicsProgram implements yeahtzeeConstants {

   /* Private instance variables */
   private int nPlayers;
   private String[] playerNames;
   private yeahtzeeDisplay display;
   private RandomGenerator rgen = new RandomGenerator();
   private int[][] categoryScores;
   private int[][] selectedCategories;
   private int[] diceArray;

   public static void main(String[] args) {
      new yeahtzee().start(args);
   }

   public void run() {
      setupGame();
    
      for (int i = 1; i<=N_SCORING_CATEGORIES; i++) {
            for (int j = 1; j<=nPlayers; j++) {
               firstRollDice(j);
               secondAndThirdRollDice(j);
               selectAndSetCategoryScore(j);   
            }
         }
      decideWinner();
   }

   private void setupGame() {
      IODialog dialog = getDialog();
      nPlayers = dialog.readInt("Enter number of players");
      playerNames = new String[nPlayers];
      for (int i = 1; i <= nPlayers; i++) {
         playerNames[i-1] = dialog.readLine("Enter name for player " + i);
      }
      display = new yeahtzeeDisplay(getGCanvas(), playerNames);
    
      categoryScores= new int[nPlayers+1][N_CATEGORIES+1];
      selectedCategories = new int[nPlayers+1][N_CATEGORIES+1];
      diceArray = new int [N_DICE];
   }


private void firstRollDice(int j) {
     display.printMessage(playerNames[j-1] + "'s turn. Click 'Roll Dice' button to roll the dice.");
     display.waitForPlayerToClickRoll(j);                
     for (int l=0; l<N_DICE; l++) {              // 5 dice each turn
        int diceRollNumber = rgen.nextInt(1,6); // 6 numbers per die
        diceArray[l] = diceRollNumber;
     }
     display.displayDice(diceArray);
}

/**Method:
   *
   * secondAndThirdRollDice
   *
   * @param j playerNumber
   *
   *
   */

private void secondAndThirdRollDice(int p) {
     for (int i = 0; i<2; i++) {
        display.printMessage("Select the dice you wish to re-roll and click 'Roll Again'"); // 3 turns
        display.waitForPlayerToSelectDice();
       for (int l=0; l<N_DICE; l++) {              // 5 dice each turn
          int diceRollNumber = rgen.nextInt(1,6); // 6 numbers per die
            if (display.isDieSelected(l)) {
                 diceArray[l] = diceRollNumber;
              }
           }
       display.displayDice(diceArray);

     }
}
   
private void selectAndSetCategoryScore(int playerNumber) {
       display.printMessage("Select a Category for this roll.");
       int category = display.waitForPlayerToSelectCategory();
       if (selectedCategories[playerNumber][category] == 1 || category ==UPPER_SCORE || category == LOWER_SCORE
             || category == TOTAL) {
          //display.printMessage("Please choose a new category.");
          selectAndSetCategoryScore(playerNumber);          // self-referencing loop
       }
       if (checkCategory(category) == true) {
          calculateCategoryScore(category, playerNumber, diceArray);
       } else if (checkCategory(category) ==false) {
          categoryScores[playerNumber][category] = 0;
       }
       updateScores(category, playerNumber);
}


   private void calculateCategoryScore (int category, int playerNumber, int [] diceArray) {
      selectedCategories[playerNumber][category] = 1;
      int cscore = 0;
    
      //Ones through sixes
      // Since each category is "named" after the number it represents,
      // Multiplying the category name by its occurrences in diceArray yields the score
      if (category ==ONES || category ==TWOS || category ==THREES ||
            category ==FOURS || category ==FIVES || category ==SIXES) {
         int count = 0;    
         for (int i = 1; i<=diceArray.length; i++) {
            if (diceArray[i-1] == (category)) {
               count++;
            }
         }
         cscore = count * category;
      }
    
      if (category== THREE_OF_A_KIND || category == FOUR_OF_A_KIND || category == CHANCE) {
         cscore = sumArray(diceArray);
      }
    
      // Full house, Small Straight, Large Straight, yeahtzee!
      if (category == FULL_HOUSE) cscore = 25;
      if (category == SMALL_STRAIGHT) cscore = 30;
      if (category == LARGE_STRAIGHT) cscore = 40;
      if (category == yeahtzee) cscore = 50;
    
      categoryScores[playerNumber][category] = cscore;
   }


   /**
    * Utility function. Sums all digits in an array.
    * Used for both counting scores in 3- or 4- of a kind, and CHANCE.
    * Also used for summing total UPPER and LOWER scoreboard.     *
    * @param array
    * @return sum of all digits in array
    */
   private int sumArray(int[] array)
   {
      int sumscore = 0;
      for (int i = 0; i<array.length; i++) {
         sumscore += array[i];
      }
      return sumscore;
   }

   public static final int UPPER_SCORE = 7;
   public static final int UPPER_BONUS = 8;
   public static final int LOWER_SCORE = 16;
   public static final int TOTAL = 17;

   private void updateScores(int category, int playerNumber)
{    
      // Individual Category Score
      int score = 0;
      score = categoryScores[playerNumber][category];
      display.updateScorecard(category, playerNumber, score);
    
      // Upper Score
      int UpperScore = 0;
      for (int i = 0; i<UPPER_SCORE; i++) {
         UpperScore += categoryScores[playerNumber][i];
         }
      display.updateScorecard(UPPER_SCORE, playerNumber, UpperScore);

      // Lower Score
      int LowerScore = 0;
      for (int i = 0; i<LOWER_SCORE; i++) {
         LowerScore += categoryScores[playerNumber][i];
         }
      display.updateScorecard(LOWER_SCORE, playerNumber, LowerScore);
    
      // Total
      int Totalscore = UPPER_SCORE + LOWER_SCORE;
      display.updateScorecard(TOTAL, playerNumber, Totalscore);
}


private void decideWinner() {
   int highestSoFar = 0;
   int winningPlayer=0;
   for (int i = 0; i<nPlayers; i++) {
      if (highestSoFar < categoryScores[i][TOTAL] ) {
         highestSoFar = categoryScores[i][TOTAL];
         winningPlayer = i;
      }
   }
   display.printMessage("Congratulations, " + playerNames[winningPlayer] +
         "you are the winner with " + categoryScores[winningPlayer][TOTAL] +
         " smackaroos.");
}

// Checks the category selection and diceArray to for valid selection.
// Returns score if dice fulfill requirements; otherwise returns 0.
private boolean checkCategory(int category) {

   // Ones through Sixes
   if (category >=1 && category<=6 || category ==CHANCE) {
      return true;
   }

   // Setup ingenious ArrayLists for diceArray

   ArrayList <Integer> ArrayList <Integer>();
   ArrayList <Integer> twos = new ArrayList <Integer>();
   ArrayList <Integer> threes = new ArrayList <Integer>();
   ArrayList <Integer> fours = new ArrayList <Integer>();
   ArrayList <Integer> fives = new ArrayList <Integer> ();
   ArrayList <Integer> sixes = new ArrayList <Integer> ();

   for (int i = 0; i<diceArray.length; i++) {
      if (diceArray[i] ==1) ones.add(1);
      if (diceArray[i] ==2) twos.add(1);
      if (diceArray[i] ==3) threes.add(1);
      if (diceArray[i] ==4) fours.add(1);
      if (diceArray[i] ==5) fives.add(1);
      if (diceArray[i] ==6) sixes.add(1);
   }

// Three of a kind, Four of a Kind, and yeahtzee (5 of a kind)
if (category ==9 || category==10 || category == 14) {
     int itsnec = 0;                  // iterations necessary to acheive score
      if (category == 9) itsnec = 3;   // Three of a kind
      if (category == 10) itsnec = 4; // Four of a kind
      if (category == 14) itsnec = 5; // Five of a kind (yeahtzee!)
    
      if (ones.size()>= itsnec || twos.size()>=itsnec || threes.size() >=itsnec
            || fours.size() >=itsnec || fives.size() >=itsnec || sixes.size() >=itsnec) {
         return true;
      } else { return false; }
}
    
   if (category == FULL_HOUSE) {
      if ( (ones.size() >=3 || twos.size() >=3 || threes.size() >=3 ||     // Three of one kind
            fours.size() >=3 || fives.size() >=3 || sixes.size() >=3) &&
            (ones.size() >=2 || twos.size() >=2 || threes.size() >=2 ||    // Two of the other
            fours.size() >=2 || fives.size() >=2 || sixes.size() >=2)) {
         return true;
      } else { return false; }
   }

   if (category == SMALL_STRAIGHT) {
      if ( (ones.size()>0 && twos.size()>0 && threes.size()>0 && fours.size()>0) ||
            (twos.size()>0 && threes.size()>0 && fours.size()>0 && fives.size()>0) ||
            (threes.size()>0 && fours.size()>0 && fives.size()>0 && sixes.size()>0)) {
            return true;
       } else { return false; }
   }
   if (category == LARGE_STRAIGHT) {
      if ( (ones.size()>0 && twos.size()>0 && threes.size()>0 && fours.size()>0 && fives.size()>0) ||
            (twos.size()>0 && threes.size()>0 && fours.size()>0 && fives.size()>0 && sixes.size()>0)) {
            return true;
       } else { return false; }
   }
   if (category>13 || category <1) {
      throw new Error ("Invalid category passed to checkCategory().");
   }
   return false;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote