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!
Related
import java.util.Random;
public class Player {
int att;
int str;
int def;
int hp;
int attackRoll;
int defenceRoll;
int maxHit;
//A player has variable attack, strength, defence, and hp stats
//attack = determines accuracy, strength = determines damage, defence = determines ability to block hits
public Player(int attack, int strength, int defence, int hitpoints)
{
attack = att;
strength = str;
defence = def;
hitpoints = hp;
/*
attackRoll and defenceRoll are used by the 2 players to determine probability
of successfully scoring a hit, in m sample testing attRoll will always be
higher than defRoll; they are integer numbers used in below method
*/
attackRoll = (this.att + 3)*(90+64);
defenceRoll = (this.def + 3)*(0+64);
maxHit = (int) ((0.5) + ((this.str + 0 + 8.0)*(86.0+64.0))/(640.0));
//maxHit determines the maximum number player can deal each attack
}
//this determines if p1 successfully lands a hit on p2, true if so, false if not
//accuracy is calculated as a probability, ie .7 probability of hitting
//in which case there is .7 probability of being true and .3 of being false
public static boolean hit(Player p1, Player p2)
{
double accuracy;
if (p1.attackRoll > p2.defenceRoll)
{
accuracy = 1.0 - ((double)(p2.defenceRoll+2.0)/(2*(p1.attackRoll+1.0)));
}
else
{
accuracy = (double) (p1.attackRoll/(2*(p2.defenceRoll+1.0)));
}
Random r = new Random();
System.out.println("Accuracy: " + accuracy);
return r.nextDouble() <= accuracy;
//idea is that if accuracy is .7 for example, nextDouble() generates
//between 0-1.0 so the probability that nextDouble() is <= .7 is .7, what we want
}
//calculates damage p1 does to p2, if hit returns true
public static void attack(Player attacker, Player defender)
{
int damage = 0;
if(!hit(attacker, defender)) return; //if the attacker missed, damage is 0, defender doesn't lose hp
//if p1 successfully landed a hit on p2 as determined in previous method
else if(hit(attacker, defender))
{
Random r = new Random();
damage = r.nextInt(attacker.maxHit+1); //p1 deals (0 to maxHit) damage on p2 from that attack
defender.hp -= damage; //p2 loses that much hp
}
}
public static void main(String[] args) {
int p1wins = 0; //counts number of times p1 won
int p2wins = 0; //counts number of times p2 won
int firstCounter = 0; //counts the number of times p1 went first, should be near 50% as its randomly decided
int secondCounter = 0; //couonts the number of times p2 went first, should be near 50%
for (int i = 1; i <= 10000; i++) //10000 trials of p1 and p2 battling
{
Player p1 = new Player(99, 99, 99, 99); //set p1's attack, strength, defence, hp to 99
Player p2 = new Player(99, 99, 99, 40); //p2 only has 40 hp, therefore p2 should lose most of the time
Random r = new Random();
int first = r.nextInt(2); //determines which player attacks first
if(first == 0) firstCounter++;
if(first == 1) secondCounter++;
while((p1.hp>0) && (p2.hp>0)) //the fight goes on until one player dies (hp is <= 0)
{
if(first == 0) //if player 1 attacks first
{
attack(p1, p2); //player 1 attacks player 2
if(p2.hp <= 0) break; //if player 2's hp goes 0 or below from that attack, he dies and there's no more fighting
attack(p2, p1); //then p2 attacks p1, and repeat
if(p1.hp <= 0) break;
}
else if (first == 1) //if player 2 attacks first
{
attack(p2, p1); //player 2 attacks player 1
if(p1.hp <= 0) break;
attack(p1, p2);
if(p2.hp <= 0) break;
}
}
if(p1.hp <= 0) p2wins++;
else if(p2.hp <= 0) p1wins++;
}
System.out.println("p1 won " + p1wins + " times."); //prints number of times p1 wins
System.out.println("p2 won " + p2wins + " times.");
System.out.println(firstCounter); //prints number of times p1 went first, should be near 50% with large sample size
System.out.println(secondCounter);
}
}
The above code is a program that simulates 2 players fighting.
The main idea is to understand that a player has 4 stats (attack, strength, defense, hp) and that if two players fight with the same stats (ie 99,99,99,99 both), then the probability that anyone will win is naturally about 50%.
The problem I'm encountering is that the program makes p2 win every single game, even with stats that are obviously vastly inferior
(ie p1 having 99 att, 99 str, 99 def, 99 hp p2 having 99 att, 99 str, 99 def, but 20 hp), thus p2 would die much sooner in most trials, but a run of 10000 fights displays p2 winning all 10000 of them, which is obviously wrong and not intended. I can't figure out why p2 is winning 100% of the time.
You have an error at the beginning of the Player constructor.
Assignments' order are wrong. The correct way is:
att = attack;
str = strength;
def = defence;
hp = hitpoints;
Otherwise, p1.hp and p2.hp are always 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'm stuck on this while loop question, would be glad if someone could spot out where I am going wrong :)
Golf game Write a program that uses a while loop to play a dice golf game. The distance to the hole starts at 100m. The person repeatedly chooses which club to use. The different choices each correspond to a different sided virtual ‘dice’ to roll – ie giving a random number. If they choose club 1 (a putter) they roll a number from 0-5 representing the distance hit. If they choose club 2 (for pitching) they roll a number from 0-30. If they choose club 3 (an iron) they roll a number from 0 to 150. After each roll that number is subtracted from the distance to the hole (with negative distances being made positive for the next round). They keep rolling until they get the distance to exactly 0. When they do the number of shots taken is printed.
The following shows an example run of the program:
Distance to hole 100m. Which club (1-putting, 2-pitching or 3-iron) 3
You hit it...120m
Distance to hole 20m. Which club (1-putting, 2-pitching or 3-iron) 2
You hit it...16m
Distance to hole 4m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...1m
Distance to hole 3m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...3m
Congratulations. You took 4 shots.
I am new to java, below is what I managed to get done, but shows error on: while (input.equals !( "1" || "2" || "3") ). I'm not sure whether its done correctly and spent ages on this, would be glad if someone could help out on the question problem :) Much appreciated.
public static void dicegolfgame(String[] args)
{
String input = "";
int difference = 0;
int newdistance = 0;
int distance = 0;
int i = 0;
while (input.equals ( "1" || "2" || "3") )
{
Random roll2 = new Random();
distance = roll2.nextInt(100);
input = JOptionPane.showInputDialog ( "distance to hole " + distance + " Which club (1-putting), 2-(pitching) or 3-iron");
while (difference > 0 && difference < 0)
if (input.equals ("1"))
{
Random roll = new Random();
newdistance = roll.nextInt(5);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("2"))
{
Random roll = new Random();
newdistance = roll.nextInt(30);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("3"))
{
Random roll = new Random();
newdistance = roll.nextInt(150);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
if (difference == 0)
{
break;
JOptionPane.showMessageDialog(null, "Congratulations, you took" + i + "shots.");
}
It's the distance to the hole that determines whether the golfer has to shoot again or not - so that should be in the while loop. I've added some comments in the code:
String input = "";
int distance = 100;
int numberOfHits = 0;
int hit = 0;
while (distance > 0) {
numberOfHits++;//increasing the nuber of hits
input = JOptionPane.showInputDialog("distance to hole " + distance + " Which club (1-putting), 2-(pitching) or 3-iron");
switch (input) {//if you don't know switch you coukd use if-else
case "1":
Random roll = new Random();
hit = roll.nextInt(6);//a random int netween 0-5
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;//sets the new distance to the old distance subtracted the hit
distance = Math.abs(distance);//if distance is negative make it positive
break;
case "2":
roll = new Random();
hit = roll.nextInt(31);
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;
distance = Math.abs(distance);
break;
case "3":
roll = new Random();
hit = roll.nextInt(151);
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;
distance = Math.abs(distance);
break;
}
}
//when we are out of the loop the distance is zero
JOptionPane.showMessageDialog(null, "Congratulations, you took " + numberOfHits + " shots.");
Judging by how well known this Nim exercise is in the programming world I won't bother explaining the jist of the game.
Anyway
So I tried coding an "illegal move" parameter that denies an illegal user input of greater than half the total pile of rocks, which then loops back to ask the user to input a valid number. Problem is it isn't prompting the user to re-enter a valid input, it just goes straight to the computer's turn.
here's my code.
import java.util.*;
public class Nim {
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
int pile, turn, difficulty, pick;
pile = (int)(Math.random() * 90 + 10);
turn = (int)(Math.random() + .5);
difficulty = (int)(Math.random() + .5);
if(difficulty == 0)
System.out.println("Computer is set to HARD MODE.");
else if(difficulty == 1)
System.out.println("Computer is set to easy mode.");
System.out.println("The pile of rocks has " + pile + " total rocks. LETS GET IT ON");
while(pile>0)
{
if(turn == 0)
{
System.out.println("Your move.");
pick = in.nextInt();
if(pick >= 1 && pick <= pile/2){
pile = pile - pick;
System.out.println(pile + "left.");}
else {
System.out.println("Illegal Move.");
turn = 0;}
}
if(turn == 1 && difficulty == 1)
{
System.out.println("Computer's move.");
pick = (int)(Math.random()*pile/2+1);
pile = pile - pick;
System.out.println("Computer picks " + pick + " there are " + pile + " rocks left.");
}
else if(turn == 1 && difficulty == 0)
{
System.out.println("Computer's move.");
pick = (int)(Math.pow(2,n);
pile = pile - pick;
System.out.println("Computer picks " + pick + " there are " + pile + " rocks left.");
}
if(turn == 0)
turn = 1;
else turn = 0;
}
if(turn == 0)
System.out.println("Computer: This game is for noobs.");
else
System.out.println("Computer: Scrub.");
}}
As you may be able to see, it's suppose to detect the illegal move and reset the turn back to 0 prompting the user's turn again, except it's just skipping to the computer's turn. I don't know what I'm doing wrong.
Also I've been trying to find a more elegant way to code the 'smart' mode for the computer. My professor showed us a more sloppy way where he just took the flat amounts (perfect squares - 1) and copy pasted the value over and over for different amounts, but I want to be able to get it in a nice compact formula since it's a more elegant solution -- I'm thinking either I'm going to use the square root function or the power function but I'm unsure. Any help I could get for that would be much appreciated.
I think you are missing a continue directive after setting turn to 0. Try this:
if(pick >= 1 && pick <= pile/2){
pile = pile - pick;
System.out.println(pile + "left.");}
else {
System.out.println("Illegal Move.");
turn = 0;
continue;
}
Setting turn to 0 is no help, because it's already 0. You need to EITHER set it to 1 when there's an illegal move (which is probably easiest), OR somehow skip out that chunk of code down the bottom that changes it from 0 to 1.
I have a problem with my dealerhand method in my blackjack game.
I have a method to produce a random card from the class deck.
The cards have assigned values to them and so forth.
however the problem lies in the code where i want the dealer to draw a new card, and add the value to the existing total hand value. the code is a following.
//Basics for the values of dealers cards
int dealerHandValue = 0;
int tempDealerHandValue = 0;
int totalDealerHandValue= 0;
//Dealers first card
randomGenNum = (int)((range * Math.random()) + 1)*2;
dealerHandValue = arrayCardRank[randomGenNum];
CardSuit = arrayCardSuit[randomGenNum];
System.out.println("Dealer First Card Shows : " + (CardSuit));
tempDealerHandValue = dealerHandValue;
//Code executed when player stops drawing and stands.
while (totalDealerHandValue < 18 && totalDealerHandValue <21)
{
randomGenNum = (int)((range * Math.random()) + 1)*2;
dealerHandValue = arrayCardRank[randomGenNum];
CardSuit = arrayCardSuit[randomGenNum];
System.out.println("Dealer next Card Shows : " + (CardSuit));
tempDealerHandValue = dealerHandValue;
totalDealerHandValue = (tempDealerHandValue) + (dealerHandValue);
System.out.println("Dealer total hand value is " + (totalDealerHandValue));
}
{
System.out.println("Dealer stopped drawing");
if (totalDealerHandValue >= totalUserHandValue)
{
System.out.println("Dealer wins");
return;
}
else
System.out.println("Congratulations! You Win!");
return;
}
This method will just add the new cards value to itself, on and on until the while statement ends.
i have gone blind on the problem, and i know it is easily fixed.
can anyone help me towards what i am missing?
you're never incrementing totalDealerHandValue, just overwriting the value over and over again.
Replace these two lines:
tempDealerHandValue = dealerHandValue;
totalDealerHandValue = (tempDealerHandValue) + (dealerHandValue);
with
totalDealerHandValue += dealerHandValue;