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! ");
Related
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.
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 + "]";
}
}
I am trying to write code for a game that has a player and a computer roll dice until one, or both, reach 250( its possible for them to tie). The player and the computer can choose from 1 of 3 die choices. One - 24 sided tie, two - 10 sided die, or three - 6 sided die. There is a bonus for the 10 and 6 sided die if the die are all the same. There are 2 "lakes" where if the player lands in them the player has to go back to the lower number right before the beginning of the lake, there is also a muddy swamp where every move the player makes while in the swamp is cut in half. For every 10 spots (10, 20, 30, 40 ETC.) the player randomly draws a card. There are 11 different cards the player can randomly get:
1-4: player moves ahead a random amount from 1-6
5: player moves ahead a random amount from 4-11 (random 8 + 4)
6: player moves to where the other player is (see below)
7: player moves back to the beginning (moves to location 0)
8-9: player moves back a random amount from 1-6
10-11: player moves back a random amount from 4-11
I have a few problems. My first problem is that the die rolls do not change after every turn, they will remain the same. So if I choose 3 die I might get 3 random numbers, if I choose those die again I will get those same 3 numbers.
I also cannot seem to get the players die count to correctly update. If the player rolls 18 total points and the next turn he rolls 14 the count will go from 18 to 14.
My third problem is it seems like no matter what I do the print statement for the lakes,muddy patch and the winner announcement always print. I have tried a few different things and nothing seems to work.
I am new at code writing ( this is my 4th program written) and do not have extensive knowledge to know what is wrong. The code does not have to be expertly done, I just would like it to work properly. Any and all help is greatly appreciated.
/*This program will create a "Board" game. Each player can choose
from several different types of die. The computer and user will take
turns "rolling" a dice. There are several obstacles that can send one
of the players back. The goal is to get above 250*/
import java.util.*;
public class Project4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//assigning variables
int p1, p2;
p1=p2=0;
int spacesmoved = 0;
//Setting up the randomization of the 24 sided die
int minimum1 = 1;
int maximum1 = 24;
Random rn1 = new Random();
int range1 = maximum1 - minimum1 + 1;
int die1 = rn1.nextInt(range1) + minimum1;
//Setting up the randomization of the 10 sided die
int minimum2 = 1;
int maximum2 = 10;
Random rn2 = new Random();
int range2 = maximum2 - minimum2+ 1;
int die2 = rn2.nextInt(range2) + minimum2;
int die22 = rn2.nextInt(range2) + minimum2;
int die222 = rn2.nextInt(range2) + minimum2;
//Setting up the randomization of the 6 sided die
int minimum3 = 1;
int maximum3 = 10;
Random rn3 = new Random();
int range3 = maximum3 - minimum3+ 1;
int die3 = rn3.nextInt(range3) + minimum3;
int die33 = rn3.nextInt(range3) + minimum3;
int die333 = rn3.nextInt(range3) + minimum3;
//Setting a loop for the players to take turns until one, or both, reach > 250
while (p1 <= 250 && p2 <= 250) {
{System.out.println(" Current positions. Player: " + p1 + " Computer: " + p2);
System.out.println("Which die would you like to roll? die1(1) = one 24-sided die, die2(2) = two 10-sided dice, die3(3) = three 6-sided dice: ");
String diechoice = in.nextLine().toLowerCase();
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
spacesmoved = (die1);
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=spacesmoved;
}
//Getting the die roll if the player chooses the two 10 sided die
if (diechoice.equals ("2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Player rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Players 3rd dice roll is " + die222);
System.out.println("Player moves forward a total of " + spacesmoved + " spots");
p1 += spacesmoved;
}
// player1spot = (currentspot + spacesmoved);
}
//Getting the die roll if the player chooses three 6 sided die
if (diechoice.equals("3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Player 1 moves forward a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p1 += spacesmoved;
}}
/*Setting up the lakes and muddy patch. If the player lands in a lake he goes back
to the lower edge of the lake. If in the mud his moves are cut in half ONLY while in the mud */
{if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
//Setting up the random cards if the player lands on a 10
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if player gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
p1 = cardmove;
//if player gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
p1 = cardmove5;
//if player gets a card that moves them to the spot of the other player
if (card == 6);
p2 = p1;
//if player gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if player gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if player gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
//Setting up the computers turn
System.out.println("Computers turn");
{
int minimum = 0;
int maximum = 2;
Random rn = new Random();
int range = maximum - minimum + 1;
int computersturn = rn.nextInt(range) + minimum;
//If computer randomly chooses a 24 sided die
spacesmoved = (die1);
System.out.println("Computer rolled a " + die1);
System.out.println("Computer moved " + die1 +" spaces");
p2+=spacesmoved;
}
//If the computer randomly chooses the two 10 sided die
if (diechoice.equals ("die2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Computer rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Computer 3rd dice roll is " + die222);
System.out.println("Computer moves a total of " + spacesmoved + " spots");
p2 += spacesmoved;
}
}
//If the computer randomly chooses three 6 sided die
if (diechoice.equals("die3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Computer 1 moves a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p2 += spacesmoved;
}
//Setting the lakes and mud for the computer
if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Computer landed in mud, players turns are cut in half until player gets out");
//Setting up the cards for the computer
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if computer gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
//if computer gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
//if computer gets a card that moves them to the spot of the other player
if (card == 6);
p1 = p2;
//if computer gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if computer gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if computer gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
}
//Writing a final statment showing the winner, or if both tied.
{ if (p1 > p2);
System.out.println("Player 1 wins! Good job!");
if (p2 >p1);
System.out.println("Computer wins! Better luck next time!");
if (p2 == p1);
System.out.println("The game ends in a tie!");
}
}
}
}
}
Here are the things I noticed in relation to the three problems you mentioned:
Problem number 1:
You are setting the values of the dice at the very beginning of code execution. From that point on, you aren't changing them at all. That is the cause of the problem of always rolling the same numbers every turn. You might be thinking that every time you use die1 or any of the other die variables, that it is re-executing the code at the top of your file, but it doesn't.
The code at the top of your file is executed only once and then the value stored in that variable is used for the rest of the program execution. Until you change it. So you would want something more like this:
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
die1 = rn1.nextInt(range1) + minimum1;
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=die1;
}
You would also need to change that in the other cases where the die is rolled.
Another benefit to doing it this way is that you really only need one random number generator. You don't actually need one for each die. You can use the same one for all die rolls.
Problem number 2:
I'm not sure exactly what is going wrong with die rolls, if there really is something going wrong there, but I did notice a few places where you'll want to change what is done to p1 and p2:
When the player gets a card that moves them ahead, you'll want to use += instead of =. i.e. p1 += cardmove5 instead of p1 = cardmove5
When the player gets a card that moves them back, it looks like you forgot to add the p1 -= cardmove statements.
Also, make sure you have p1 and p2 in the right places. For example, I'm thinking that on the computer's turn, if they get the card to move them to the other player's spot, you meant to do p2 = p1, but instead you have p1 = p2. Same with the computer going back to 0. You have p1 = 0, but it seems like you would want p2 = 0. So just be careful about that. (Also be careful about copy paste. I'm guessing that's why that happened)
Problem number 3:
This problem looks like it's caused by the fact that you are using the || operator where you should be using &&. When you use ||, you are effectively saying "or". So this first statement
if (spacesmoved >= (83) || spacesmoved <= (89))
reads as "if spacesmoved is greater than or equal to 83 OR less than or equal to 89"... Think about that for a second. Is there any number that is NOT greater than 83 OR less than 89? The answer is no. EVERY number will satisfy this condition. You would want to use &&, which means "and" like this:
if (spacesmoved >= (83) && spacesmoved <= (89))
"if spacesmoved is greater than or equal to 83 AND less than or equal to 89", which would only work for numbers between 83 to 89 inclusive.
You will also want to remove the semicolons after your "if" statements in that block and the other similar blocks. If you don't, the code inside those conditions won't get executed. That's actually a really tough bug to find when it happens.
Another thing to know is that when you want multiple things to be executed in an "if" condition, you must enclose it in curly braces {}, otherwise, only the first line will be included in the condition, and any following lines will be executed unconditionally. That is another fact that is causing this third problem.
One last thing is that you should try using "else if" and "else" statements. It will help your code flow make more sense. I'm not going to do all the work for you, but this code block should probably look more like this:
if (p1 >= (83) && p1 <= (89))
{
p1 = (82);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (152) && p1 <= (155))
{
p1 = (151);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (201) && p1 <= (233))
{
spacesmoved = (spacesmoved / 2);
p1 -= spacesmoved;
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
Bonus Tip
You're learning well, and it seems you are thinking of code flow pretty well. Just keep working and learning and you'll get it.
Look into your usage of parentheses. Using them doesn't hurt anything, but you are using them WAY more than you need.
Good luck! And keep learning!
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.
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());