I'm designing a program that simulates a game of dice. The code calculates the total points get each round and the player that wins each round.
I am trying to get the overall number of wins and the total points. I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
Round 1:
player 1 3 1 5 points: 9
player 2 2 6 6 points: 14
Winner is player 2
Round 2:
player 1 3 6 5 points: 14
player 2 2 3 2 points: 7
Winner is player 1
Round 3:
player 1 3 3 6 points: 12
player 2 5 4 6 points: 15
Winner is player 2
.
Total wins: player 1-->1/ player 2-->2
Total points: player 1-->35/ player 2-->36
Main class
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of players (grater or equal than 2) --> ");
players = input.nextInt();
System.out.print("\n");
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + (r+1) + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
for (int i = 0; i < diceArray.length; i++) { // loop for dice Array (data of Array)
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
System.out.println("Total wins: " );
System.out.println("Total points: " );
}//end Main Method
} // end Class
Calculation class
public class ThreeDiceScorer {
public static int total;
public int die1;
public int die2;
public int die3;
public ThreeDiceScorer(int s1, int s2, int s3) {
die1 = s1;
die2 = s2;
die3 = s3;
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
total= sumOfDice;
}
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
}
I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
I would say, do one thing at a time. Test your implementation and once you confirmed that it is working, then move on. The sequential steps to reach your goal would be:
Steps
Implement dice rolling for one player first. (Can do it in a method)
Call the above implemented method for 2nd player's dice roll.
Decide winner
Once steps 1-3 were implemented correctly, enclose steps 1-3 within a loop (preferable a for-loop for this particular case)
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
Once steps 1-4 is tested and working fine. Implement the display of total score:
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
displayFinalScore();
Total score and total wins can be stored in a very simple Player class which looked like this:
public class Player{
private String name;
private int totalScore;
private int totalWins;
}
Dynamic Multi-player
I tried to keep the solution as short and simple as possible for your understanding. But if you want the program to dynamically take in n number of players. The same program flow still applies.
In step 4, you can do it as:
int numOfPlayers = 2; //can receive this from user input
ArrayList<Player> players = new ArrayList<Player>();
for(int x=0; x<numOfPlayers; x++)
numOfPlayers.add(new Player("Player " + (x+1)));
for(int x=0; x<numOfRounds; x++){
for(int y=0; y<players.size(); y++) //iterate through all players
rollDice(players.get(y));
decideWinner(players); //decide the winner from all the players
}
There are many ways to solve this, I would add two counters like int count = 0 and increment them: one every time there is a victory (for ex.: if(victory) { c++ })and the other through the expression count = count + points.
Remember to implement these ints at the beginning or the for loop will reset count1 and count2 to 0.
Related
So this is what I'm trying to do.
The program should have a loop that iterates 10 times. Each time the loop iterates, it should roll both dice. The die with the highest value wins. In the case of a tie, there is no winner for that particular roll of the dice.
As the loop iterates, the program should:
Ask the user if they are ready to roll.
Display the result of the roll
The number of User’s roll, Computer’s roll, and the result (who win, lose or
tie).
Keep count of the number of times the computer wins.
Keep count of the number of times that the user wins
The Die object code:
import java.util.Random;
/**
The Die class simulates a six-sided die.
*/
public class Die
{
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial
roll of the die.
#param numSides The number of sides for this die.
*/
public Die(int numSides)
{
sides = numSides;
roll();
}
/**
The roll method simulates the rolling of
the die.
*/
public void roll()
{
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
#return The number of sides for this die.
*/
public int getSides()
{
return sides;
}
/**
getValue method
#return The value of the die.
*/
public int getValue()
{
return value;
}
}
This is the code that uses the object code, for the dice and their movement.
public class MitchellLab06
{
public static void main(String[] args)
{
final int DIE1_SIDES = 6; //Number of sides for die #1
final int DIE2_SIDES = 6; //Number of sides for die #1
final int MAX_ROLLS = 10; //Number of ties to roll
// Create two instances of the Die class.
Die die1 = new Die(DIE1_SIDES);
Die die2 = new Die(DIE2_SIDES);
//Display the initial value of the dice.
System.out.println("This program simulates the rolling of a " +
DIE1_SIDES + " sided die and another " +
DIE2_SIDES + " sided die.");
System.out.println("The initial value of the dice:");
System.out.println(die1.getValue() + " " + die2.getValue());
//Roll the dice 10 times.
System.out.println("Rolling the dice " + MAX_ROLLS + " times");
for(int i = 0; i < MAX_ROLLS; i++)
{
//Roll the dice.
die1.roll();
die2.roll();
//Display the value of the dice.
System.out.println(die1.getValue() + " " + die2.getValue());
}
}
}
I need help keeping track of which die wins, out of the 10 rolls and determine if the user wins, the computer wins, or if it's a tie.
One example solution is to initialize two arrays one for the computer one for the user.
Each time you throw a dice you increment the array on position throwing turn number with dice.
int [] computer = new int[10];
int [] user = new int [10];
for (int i=0;i<10; ++i) {
int diceUser = throwDice();
int diceComputer = throwDice();
if (diceUser> diceComputer) {
user[i] = diceUser;
}
else if (diceUSer<diceComputer) {
computer[i]= diceComputer;
}
else {
computer[i] = diceComputer;
user[i] = diceUser;
}
}
Every time computer or user has lost, they will have 0 in the array. When it is a draw both arrays will contain the same value at the same index.
The index of the array is following the turn.
A simple, yet elegant solution that uses a simple while loop and a couple variables to hold the user score, comp score and the total number of wins for each of them.
int userWin = 0, compWin = 0;
int MAX_ATTEMPTS = 10;
while(MAX_ATTEMPTS > 0) {
int userScore = 0, compScore = 0;
//Roll the dice for user
die1.roll();
die2.roll();
userScore = die1.getValue() + die2.getValue();
//Roll the dice for comp
die1.roll();
die2.roll();
compScore = die1.getValue() + die2.getValue();
// determine winner
if (userScore > compScore) {
System.out.println("User wins! \nUser score = " + userScore + ", Comp score = " + compScore);
userWin++;
}
else if (userScore < compScore) {
System.out.println("Comp wins! \nUser score = " + userScore + ", Comp score = " + compScore);
compWin++;
} else {
System.out.println("Draw!\nUser score = " + userScore + ", Comp score = " + compScore);
}
MAX_ATTEMPTS --;
}
System.out.println("User won = " + userWin + " times! ");
System.out.println("Comp won = " + compWin + " times! ");
Created a program that rolls 5 6 sided dice. I repeat this until a yahtzee. I also keep track of the number of rolls, and I repeat the entire process 1000x. My program works, but does not display anything. Please help me to spot the error thank you. In my last for-loop, when i run the program there is no output display after it? Why?
import java.util.Scanner;
/* The DiceTester class simulates the rolling of dice */
public class DiceTester
{
public static void main(String[] args)
{
int userInput; //Holds user input.
int sumDice; //Holds the sum of the dice.
int firstDie; //Holds value of die 1.
int secondDie; //Holds value of die 2.
Scanner keyboard = new Scanner(System.in); //scanner object for input.
//Prompt and collect user input.
System.out.print("Creating two dice. One with 6 sides, enter value for
the second die: ");
userInput = keyboard.nextInt();
//Create two dice objects.
Die die1 = new Die(); //With default constructor.
Die die2 = new Die(userInput); //With argument.
System.out.println("Generating dice ...");
System.out.println(die1); //Show state of dice, toString.
System.out.println(die2);
System.out.println("Rolling the dice ...");
//Roll Dice. Store value of indiviual dice and sum.
die1.roll();
die2.roll();
firstDie = die1.getValue();
secondDie = die2.getValue();
sumDice = firstDie + secondDie;
//Display values to screen.
System.out.println(firstDie + " " + secondDie + " " + sumDice);
System.out.println("\nDie1 Die2 Sum");
System.out.println("-------------");
//Create for loop that runs 10x and shows value of dice.
for (int roll = 1; roll <= 10; roll++)
{
die1.roll();
die2.roll();
firstDie = die1.getValue();
secondDie = die2.getValue();
sumDice = firstDie + secondDie;
System.out.println(firstDie + " " + secondDie + " " +
sumDice);
}
System.out.println("\nGenerating five 6-sided dice ...");
//Creating 5 more dice.
Die yahtDie = new Die();
Die yahtDie2 = new Die();
Die yahtDie3 = new Die();
Die yahtDie4 = new Die();
Die yahtDie5 = new Die();
//Print state of dice.
System.out.println(yahtDie + "\n" + yahtDie2 + "\n" + yahtDie3 + "\n" +
yahtDie4 + "\n" + yahtDie5);
int numRoll = 0; //Holds the number of rolls until yahtzee.
int totalRoll = 0; //Holds the total number of rolls to get yahtzee.
double avgRoll; //Holds the average number of rolls to get yahtzee.
int maxRoll = 0; //Holds the maximum number of rolls, yahtzee
int minRoll = 0; //Holds the minimum number of roll, yahtzee
//Create for loop to iterate 1000x.
for (int roll = 1; roll <= 1000; roll++)
{
//Roll dice in while loop.
while(!(yahtDie == yahtDie2 || yahtDie2 == yahtDie3 || yahtDie3 ==
yahtDie4 || yahtDie4 == yahtDie5))
{
yahtDie.roll();
yahtDie2.roll();
yahtDie3.roll();
yahtDie4.roll();
yahtDie5.roll();
numRoll++;
}
totalRoll += numRoll;
if (maxRoll > numRoll)
maxRoll = numRoll;
if (minRoll < numRoll)
minRoll = numRoll;
}
avgRoll = totalRoll / 1000.0; //Total number of rolls to get yahtzee /
number of yahtzees.
System.out.println("Rolling for 1000 yahtzees... \nCounting the number
of rolls for 1000 yahtzees... \nFound 1000 yahtzees.");
System.out.println("The maximum amount of rolls to get a yahtzee: " +
maxRoll);
System.out.println("The minimum amount of rolls to get a yahtzee: " +
minRoll);
System.out.println("The average amount of rolls to get a yahtzee: " +
avgRoll);
}
}
Output:
Creating two dice. One with 6 sides, enter value for the second die: 5
Generating dice ...
Die[6 sides, value = 2]
Die[6 sides, value = 4]
Rolling the dice ...
4 1 5
Die1 Die2 Sum
-------------
2 6 8
5 6 11
4 2 6
5 3 8
1 3 4
4 6 10
6 6 12
6 5 11
6 5 11
2 1 3
Generating five 6-sided dice ...
Die[6 sides, value = 5]
Die[6 sides, value = 1]
Die[6 sides, value = 3]
Die[6 sides, value = 5]
Die[6 sides, value = 6]
die class:
import java.util.Random;
/* This class creates a die of n sides and rolls it. */
public class Die
{
private int numSides; //holds the amount of sides of dice.
private int faceUp; //holds the value of the die facing up.
/* Default constructor creates a 6 sided die and rolls it. */
public Die()
{
//Random newDie = new Random(); //Create random object for the dice.
numSides = 6;
roll(); //Assign the value from the random newDice method (1-6) to the current side up.
}
/* This constructor creates a die of 4, 6, 8, 10, 12, 20, or 100 sides, and rolls it. */
public Die(int side)
{
//Random newDie = new Random();
if (side == 4 || side == 6 || side == 8 || side == 10 || side == 12 || side == 20 ||
side == 100)
{
numSides = side;
roll();
}
else
{
numSides = 6;
roll();
}
}
/* The getValue method returns the the current value facing up. */
public int getValue()
{
return faceUp;
}
/* This method rolls the dice */
public void roll()
{
Random newDie = new Random(); //Create random object for the dice.
faceUp = newDie.nextInt(numSides) + 1; //Assigns random value from 1 to numSides to faceUp. "Simulate dice roll."
}
/* This method prints the state of the object. */
public String toString()
{
return "Die[" + numSides + " sides, value = " + faceUp + "]";
}
}
My program keeps adding up the score for each player, rather than keeping it separate for example if first player gets 3/5 and the second gets 2/5 the score display for the second player will be 5. I know the answer is probably very simple however I'm not able to find it within the code.
public static void questions(String[] question, String[] answer, int n) {
String[] name = new String[n]; // Player Names
int[] playerscore = new int[n]; // Argument for Score
String[] que = new String[question.length]; //Questions for Loops
int score = 0; // Declare the score
/* --------------------------- For loop for number of players --------------------------- */
for (int i = 0; i < n; i++) {
name[i] = JOptionPane.showInputDialog("What is your name player" + (i + 1) + "?");
JOptionPane.showMessageDialog(null, "Hello :" + name[i] + " Player number " + (i + 1) + ". I hope your ready to start!");
/* --------------------------- Loop in Loop for questions --------------------------- */
for (int x = 0; x < question.length; x++) {
que[x] = JOptionPane.showInputDialog(question[x]);
if (que[x].equals(answer[x])) {
score = score + 1;
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
} // End for loop for Question
playerscore[i] = score;
System.out.println("\nPlayer" + (i) + "Name:" + name[i] + "\tScore" + score);
}
}
You will need to reset the score to 0 before each player starts.
Add this after the loop for each player:
score = 0;
Alternatively you could increment the score directly in the array. Just change:
score = score + 1;
to:
playerscore[i] = playerscore[i] + 1;
or simply:
playerscore[i]++;
Assign score=0 after the line
playerscore[i] = score;
Every each and every player is assigned with his score in inner loop. Since score is declared as instance variable it will not differentiate between two different players. In order to have each and every individual player with his own scores, assign score with zero as soon as questions exceeds.
import java.util.Scanner;
public class DiceSimulator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
// declare diceArray
Die[] diceArray = new Die[amountOfDie];
// create a new Die for each reference
int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {
System.out.print("How many sides on die number " + (i + 1) + "" + ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;
}
int minRoll = amountOfDie;
// int[] sumArray = new int[maxRoll + 1];//to store sum
System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();
System.out.println("\nResults");
// ******** right here is where I'm having the issue.
for (int i = 0; i < numRol; i++) {
diceArray[i].roll();
// System.out.println(diceArray[i]);
int sum = 0;
for (int f = 0; f < numRol; f++) {
sum += diceArray[f].roll();
int[] sumArray = new int[maxRoll + 1];
sumArray[sum]++;
System.out.print("\t" + sum);
}
}
// for(Die d: diceArray){
// System.out.println(d);
// }
}
}
See commented line in code: // ******** right here is where I'm having the issue.
The for loop should spit out the sum of the rolls.
It just isn't spitting out the right values. I'm just curious where I went wrong? The program should ask the user how many rolls. This would go into the first for loop and the second would roll the dice that many times.
I think what you're trying to do is roll these dice a said number of times, keeping track of how often each total is reached, so you can print them at the end. Try this:
int[] sumArray = new int[maxRoll];
for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;
System.out.print("\t" + roll);
}
System.out.println("\t:\t" + sum);
sumArray[sum-1]++;
}
for (int i = 0; i < sumArray.length; i++){
System.out.printf("%d: %d Rolls\n", i+1, sumArray[i]);
}
You can see it working here. Your most basic mistakes were:
Declare your sum array before you start calculating sums.
In the inner loop, iterate over your dice, one at a time, rolling, adding to the sum, and printing.
Print your sum and increment your count after the dice have been rolled.
If you roll two six sided dice 10 times with this algorithm, you'll get:
Results
4 3 : 7
5 5 : 10
2 2 : 4
6 5 : 11
1 1 : 2
6 5 : 11
6 5 : 11
1 2 : 3
2 1 : 3
3 5 : 8
1: 0 Rolls
2: 1 Rolls
3: 2 Rolls
4: 1 Rolls
5: 0 Rolls
6: 0 Rolls
7: 1 Rolls
8: 1 Rolls
9: 0 Rolls
10: 1 Rolls
11: 3 Rolls
12: 0 Rolls
You have a line that looks like this:
diceArray[i].roll();
The problem is that diceArray is only large as the number of dice you have. But you are trying to use it with an index of the number of rolls. This could cause an ArrayOutOfBoundsException.
UPDATE: Figured it out, code has been fixed below. Added a while loop to confirm values 0 or above are entered too.
So I'm doing an assignment where the user enters 8 scores and you must find the highest and lowest scores and their position in the order they were given. I have been able to find the highest and lowest scores but I can't figure out how to find their position. Please help me. Here is my code so far.
import java.util.Scanner;
public class HighestLowestPoints {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int largest = -1;
int smallest = 0;
int highGame = 1;
int lowGame = 1;
for(int games = 1; games <= 8; games++) {
System.out.println("Please enter the Texans' score in game " + games);
int points = keyboard.nextInt();
while(points < 0) {
System.out.println("Please enter a value 0 or above");
points = keyboard.nextInt();
}
if(games == 1) {
smallest = points;
}
if(points > largest) {
largest = points;
highGame = games;
}
if(points < smallest) {
smallest = points;
lowGame = games;
}
if(games == 8){
System.out.println(largest + " in game " + highGame + "\n"
+ smallest + " in game " + lowGame);
}
}
}
}
Your almost there. You need to add to variables to save the hightGame and lowestGame and just assign them when you set the highest and the lowest score respectively.
Ex:
if(points < smallest) {
smallest = points;
lowestGame = games;
}
You could use the game counter variable in your for loop it contains your position :-)
Add another 2 variables, maxIndex and minIndex and when setting smallest or largest, set the appropriate variable as well with "games" variable (contains the position).
create two new variables:
int highPos = -1;
int lowPos = -1;
Every time you assign smallest, assign games to lowPos
Every time you assign highest, assign games to highPos.
add
int lPos = 0, sPos = 0;
before your for loop.
add this lPos = games to your if-block where your find largest number and sPos = games to if-block with lowest.
Also why do you assign the lowest to the first game, but not the highest?
if(games == 1) {
smallest = points;
}
Just for your information. You could also avoid all these different if's and making the code more readable if you would you would store all your games in an ArrayList. And then use the method Collections.max to get the maximum game and Collections.min to get your minimum game. Then with the method list.indexOfyou could find the position where the value is added to the list.
Scanner keyboard = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
for(int games = 1; games <= 8; games++) {
System.out.println("Please enter the Texans' score in game " + games);
int points = keyboard.nextInt();
while(points < 0) {
System.out.println("Please enter a value 0 or above");
points = keyboard.nextInt();
}
numbers.add(points);
}
StringBuilder output = new StringBuilder();
output.append("Maximum points: " + Collections.max(numbers));
output.append(" in game: " + (numbers.indexOf(Collections.max(numbers)) + 1));
output.append(" minimum points: " + Collections.min(numbers));
output.append(" in game: " + (numbers.indexOf(Collections.min(numbers)) + 1));
System.out.println(output.toString());