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.
Related
I'm making a game called 'Game of Nim' in Netbeans. Basically, a random amount of stones between 15-30 is generated and a computer and a player take turns taking 1-3 stones until there are none left. The player to take the last stones loses. I'm coding this in a jframe form. I want to make sure the player doesn't enter a number bigger than 3, less than 1 and bigger than the total stones, so I made a while loop with an if statement for the input that meets the requirements and an else statement if they aren't met. My problem is that when a player does enter numbers that shouldn't be entered, no error message appears and the game continues as normal.
Here is where I think the problem is:
public int playerInput(){
// Getting the user input and converting it into an integer
int userIn = Integer.parseInt(txtIn.getText());
//
boolean input = false;
// Do this while the input isn't between 1-3 and higher than the total amount of rocks
while(!input){
//
if (userIn < 3 || userIn > 1 || userIn < totalStone){
//
input = true;
}
//
else{
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
}
}
// return the amount of rocks the user takes
return userIn;
}
Here is most of the code for the game (I am going to use the random slashes for commenting):
public void computerMove() {
// Generating a number for the computer's move
int comIn = (int)(Math.random() * 2) + 1;
// If number generated is bigger than the total stones,
if (comIn > totalStone){
// Get the difference between the total and the random number
int totalComDiff = Math.abs(totalStone - comIn);
// Subtract the difference from the random number
comIn -= totalComDiff;
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// Otherwise, if the random number is smaller than the total,
else if (comIn < totalStone){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
}
// If the total equals amount the computer takes,
else if (totalStone == comIn){
// Substract the rocks taken from the total
totalStone -= comIn;
// Display a message of the rocks taken and the rocks left
txtaOut.setText(txtaOut.getText() +"\nThe computer picked up " +comIn +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the player wins
txtaOut.setText(txtaOut.getText() +"\nThere are no more stones left. The player wins!");
}
// Otherwise, if the amount of stones is 0,
else if (totalStone == 0){
// Display an end game message
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
public void playerMove(){
// If there are no more stones left,
if (playerInput() == totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
// Display a message that says the computer wins
txtaOut.setText(txtaOut.getText() + "\nThere are no more stones left. The computer wins.");
}
//
else if (playerInput() != totalStone){
// Subtracting how much the player took from the total amount of rocks
totalStone -= playerInput();
// Displaying how many rocks were taken and how many are left
txtaOut.setText(txtaOut.getText() +"\nYou picked up " +playerInput() +" stone(s). There are " +totalStone +" stones left.");
}
//
else if (totalStone <= 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtaOut.setText(txtaOut.getText() +"\nThere are " +totalStone +" stones.");
// The player does their move
playerMove();
}
//
if (totalStone > 0){
// Computer does a turn
computerMove();
}
//
else if (totalStone == 0){
//
txtaOut.setText(txtaOut.getText() + "\nThe game has ended.");
}
}
private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {
// Generating another random number
totalStone = (int)(Math.random() * 15) + 15;
// Clearing all the textfields
txtIn.setText("");
txtaOut.setText("");
// Outputting the number of starting stones
txtaOut.setText(txtaOut.getText() +"There are " +totalStone +" stones. It's your turn.");
}
your if needs to look like this:
while (!input) {
if (!(userIn < 3 && userIn > 1 && userIn < totalStone)) {
// Output an error message
txtaOut.setText(txtaOut.getText() +"\nEnter a number between 1 - 3 and less than the amount of stones left.");
// Prompt the user again
userIn = Integer.parseInt(txtIn.getText());
} else {
input = true;
}
}
And, it will work.
It is better to check if conditions are not valid first, and then if the verification is passed do the normal flow in else block.
The way you wrote it, the if condition would always be true since || represents 'or' so you're asking weather userIn is less then 3 or greater then 1 or lesser than totalStone which is always true.
On the other hand && represents 'and' and '!' represents not. So, you basically want all the conditions to be fulfilled and checking if they aren't by putting them into the brackets and putting ! (negation) in front
You also need to prompt the user again if the condition is not met. Otherwise it's gonna run forever and freeze the ui.
If the user enters an incorrect number, they should then be prompted to enter a new one. In your code, it will be stuck in the loop forever.
You should also be checking that all conditions are satisfied using &&.
You need a number that is (<=3) AND (>=1) AND (<=totalStones)
public int playerInput () {
int userIn;
do {
System.out.println("Enter a number between 1 - 3 and less than the amount of stones left.")
userIn = Integer.parseInt (txtIn.getText ());
} while (!(userIn <= 3 && userIn >= 1 && userIn <= totalStone));
This will continue to loop while the conditions are not satisfied.
Calculate the Probability of winning (wins/ (wins + losses)) using 10,000 simulations in the game of craps. Here is the method for the game of craps:
public class CrapsGame {
public static void main(String[] args) {
int dice1 = (int)(Math.random()* 6) + 1;
int dice2 = (int)(Math.random()* 6) + 1;
int roll = dice1 + dice2;
System.out.println();
System.out.print("You rolled "+roll+". ");
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
}else{
System.out.println("Point is "+roll+"\n");
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
int roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
while(roll2 != 7){
if(roll == roll2){
System.out.println("You Win !");
break;
}else{
System.out.println("Point is "+roll+"\n");
}
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
}
if(roll2 == 7){
System.out.println("You Lose !");
}
}
}
}
I don't think this should be difficult, I just need code to run 10,000 simulations and then also calculating the probability. Thank you :)
Would it be possible to have someone insert a working version of this
Putting a while or for loop outside of the logic and creating 2 counters (timesWinning, timesLosing). Incrementing each according, inside the existing code. After the loop runs 10.000 times, do the math as needed: wins/ (wins + losses)
thank you this is part of an assignment
And you should modify his code to this at the end:
System.out.println("Probability of winning: " + ((double)timesWon/(timesWon + timesLost)));
I got this as a result from my own:
You played: 10000.0, won: 5078, probability of winning : 0.5078
You played: 1.0E8, won: 50707214, probability of winning : 0.50707214
Your code has already all the logic needed. To repeat it as many times you want, there are different ways. They are known as loops. If you search on Google you will find for, while, do/while and some others (you have a while already inside the code).
For your question, the basic would be to repeat it 10,000 times the same things.
public class CrapsGame {
public static void main(String[] args) {
// Create some variables to control the times it won and times it lost
int timesWon = 0;
int timesLost = 0;
// Here we're saying it's gonna repeat 10000 times, incrementing 1 by 1
for(int i=0; i<10000; i++) {
// Here you will insert all the existing logic from your program
// In the existing code, increment the variables declared according
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
timesLost++;
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
timesWon++;
}else{
// Where you find it won, insert `timesWon++;`
// Where you find it lost, insert `timesLost++;`
}
}
// Here it exits the for loop (after 10000 times)
// Here's where you can calculate
System.out.println("Probability of winning: " + (timesWon/(timesWon + timesLost)));
}
}
This should be sufficient to get the desired result.
Hope it helps.
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!
I'm new to this so sorry if I am a bit confusing
So this is my code, its a game based around 2 players adding 1 or 2 to the variable "counter" the one who puts the final 1 or 2 adding all the numbers up to 21 wins.
So what I would like to have help with is that I want to lock the user input to only be able to select 1 or 2, not anything else because that would break the rules of the game. Also I would like to have a way to determine who won, player 1 or player 2. Like counting the amount of times the loop happens, so I can distinguish if player 1 or 2 one.
Any help would be appreciated! Thanks!
package hemtenta;
import java.util.Scanner;
public class Hemtenta {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 0;
int addcounter = 0;
int sum;
System.out.println("Welcome to 21");
System.out.println("The game revolves about you or your opponent getting to 21 ");
System.out.println("You both start on the same number 0, ");
System.out.println("adding 1 or 2 to see which one of you will put the final number adding it all up to 21 and winning.");
System.out.println("Think smart!");
while(counter <= 20) {
System.out.println("Please choose to add 1 or 2");
addcounter = input.nextInt();
counter += addcounter;
System.out.println("We are now on a total of " + (counter));
}
if (counter==21) {
System.out.println("Congratulations x! you won");
}
else {
System.out.println("Something went wrong! Try again");
}
}
}
You could look towards adding a
while (addcounter != 1 && addcounter != 2) {
// Prompt for values
}
To check that the value input by the user is either a 1 or a 2. If it isn't, then don't accept it and continue prompting till a valid input is registered.
And a
int turnCounter = 0;
...
// Within the loop
turnCounter += 1;
...
// At the end
if (turnCounter % 2 == 0) {
//Player Y wins
} else {
//Player X wins
}
To identify the turns, since turn 1s will be by player X, and turn 2s will be player Y. All turns by player Y will be in multiples of 2.
A fairly trivial problem to most I am sure but I can't quite work out how I'm meant to get the previous dice integer to remain the same as the previous roll of die in the program. I think the code is fairly self explanatory and this is such a trivial program I'm kicking myself for not being able to get my head around it.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int min = 1;
int max = 6;
int loop = 0;
int diceRollOne = 0;
int diceRollTwo = 0;
int diceTotal = 0;
int prevDiceTotal = 0;
while (loop < 15000) {
loop++;
diceRollOne = rand.nextInt(max - min + 1) + min;
diceRollTwo = rand.nextInt(max - min + 1) + min;
diceTotal = diceRollOne + diceRollTwo;
System.out.println("Dice Roll 1: " + diceRollOne);
System.out.println("Dice Roll 2: " + diceRollTwo);
System.out.println("Dice Total: " + diceTotal);
System.out.println("previous total: " + prevDiceTotal);
prevDiceTotal = diceTotal;
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
}
}
}
The basic idea being 15,000 simulations. Roll two dice. If you roll a double quit. If you roll the same sum in the current roll as the sum of the previous roll then quit. I've tried debugging by printing out the previous dice total but it defaults to zero every time.
You just want to move the prevDiceTotal = diceTotal; to after your if statement.
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
prevDiceTotal = diceTotal;
You have the following:
prevDiceTotal = diceTotal;
if(diceRollOne == diceRollTwo || diceTotal == prevDiceTotal){
As it's written now it guarantees if-expression to be True.
Move the assignment after your if block.
This is where a good IDE can help you. Here is what IntelliJ IDEA (which has a free Community Edition) shows for your code. Note the highlighting of the if() statement along with a description of the problem.
As others have said, move the assignment of prevDiceTotal after the if() block to solve the problem.