Question

Console yahtzee game- -using arrays -ask user if they want to play again -let user roll...

Console yahtzee game-

-using arrays

-ask user if they want to play again

-let user roll 3 times & after first two hold

At the end of the round, it will incremt the round counter + 1.  

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Console Yahtzee.java

import java.util.*;

import java.math.*;

class YahtzeeGame {

int num_of_rolls_remaining = 2;

final static int NUM_OF_DICE = 5;

public int rollDice() {

int diceRoll = (int) (Math.random() * 6) + 1;

num_of_rolls_remaining = num_of_rolls_remaining - 1;

return diceRoll;

}

public void testGame() {

System.out.println(NUM_OF_DICE);

for (int i = 0; i < NUM_OF_DICE; i++) {

System.out.println(rollDice());

}

}

}

public class ConsoleYahtzee {

public static void main(String[] args) {

YahtzeeGame game = new YahtzeeGame();

game.testGame();

}

}

Yahtzee game

import java.util.ArrayList;

import acm.io.*;

import acm.program.*;

import acm.util.*;

public class Yahtzee extends GraphicsProgram implements YahtzeeConstants {

/* Private instance variables */

private int nPlayers;

private String[] playerNames;

private YahtzeeDisplay display;

private RandomGenerator rgen = new RandomGenerator();

private int[][] categoryScores;

private int[][] selectedCategories;

private int[] diceArray;

  

public static void main(String[] args) {

new Yahtzee().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 YahtzeeDisplay(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, Yahtzee!

if (category == FULL_HOUSE) cscore = 25;

if (category == SMALL_STRAIGHT) cscore = 30;

if (category == LARGE_STRAIGHT) cscore = 40;

if (category == YAHTZEE) 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> ones = new 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 Yahtzee (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 (Yahtzee!)

  

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;

}

}

Add a comment
Know the answer?
Add Answer to:
Console yahtzee game- -using arrays -ask user if they want to play again -let user roll...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In the game of Yahtzee®, players roll five dice simultaneously to try to make certain combinations....

    In the game of Yahtzee®, players roll five dice simultaneously to try to make certain combinations. In a single turn, a player may roll up to three total times. On the first roll, the player rolls all five dice. On subsequent rolls, the player may choose to roll any number of the five dice ("keeping" dice by leaving selected unrolled dice on the table). If a player's first roll results in exactly three 5's (e.g., 2-5-5-3-5), what is the probability...

  • Develop a C++ program which will play a simplified version of the dice game Yahtzee For...

    Develop a C++ program which will play a simplified version of the dice game Yahtzee For simplicity, this version of the game only uses four dice No prompting of the user for input values is required Simply use four variables called A, B, C, D to maintain dice roll values int A = 2; No input validation is required as well From the input you will determine if the player rolled 4 of a kind, 3 of a kind, 2...

  • I need java code for this . The assignment requires using objects Exercise 2 of 2:...

    I need java code for this . The assignment requires using objects 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...

  • Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented...

    Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented by random variable X and those of the second die be represented by random variable Y. Let random variable Z be |X-Y|. The range of Z will be from 0 to 3. 1. Find E(Z). 2. Find P(Z = 1|Z <3). 3. What is the probability that you have to play the game 4 times before you roll Z=3? 4. What is the probability...

  • Game of Craps C++ #include <iostream> using namespace std; void roll (int *); // using pointer...

    Game of Craps C++ #include <iostream> using namespace std; void roll (int *); // using pointer to catch the random variable value of two dicerolls at one time . //these global variable with static variable win use to operate the working of code . //static win, account because two times input given by user to add the diceroll with win number and //account (means balance of user) . static int account = 100; static int win = 0; int bet...

  • C# Code: Write the code that simulates the gambling game of craps. To play the game,...

    C# Code: Write the code that simulates the gambling game of craps. To play the game, a player rolls a pair of dice (2 die). After the dice come to rest, the sum of the faces of the 2 die is calculated. If the sum is 7 or 11 on the first throw, the player wins and the game is over. If the sum is 2, 3, or 12 on the first throw, the player loses and the game is...

  • Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented...

    Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented by random variable X and those of the second die be represented by random variable Y. Let random variable Z be X-Y). The range of Z will be from 0 to 3. 1. (2.5 points) Find E(Z). 2. (2.5 points) Find P(Z = 21Z >1). 3. (2.5 points) What is the probability that you have to play the game 6 times before you roll...

  • Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented...

    Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented by random variable X and those of the second die be represented by random variable Y. Let random variable Z be (X-Y). The range of Z will be from -3 to 3. 1. (2.5 points) Find E(Z). 2. (2.5 points) Find P(Z =-1|Z < 1). 3. (2.5 points) What is the probability that you have to play the game 3 times before you roll...

  • Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented...

    Suppose you roll two 4 sided dice. Let the probabilities of the first die be represented by random variable X and those of the second die be represented by random variable Y. Let random variable Z be (X-Y). The range of Z will be from -3 to 3. 1. (2.5 points) Find E(Z). 2. (2.5 points) Find P(Z =-1|Z < 1). 3. (2.5 points) What is the probability that you have to play the game 3 times before you roll...

  • Ask the user to enter a message Ask the user how many time they want to...

    Ask the user to enter a message Ask the user how many time they want to print the message Then use "while","do-while" and "for" loop to print the message. Show the number at the beginning of the lines when printing. For example: Enter your message: Welcome to Java How many time you want to print this message: 3 Using "while" loop: 1=> Welcome to Java 2=> Welcome to Java 3=> Welcome to Java Using "do-while" loop: 1=> Welcome to Java...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT