int i = 1;
int answer;
int d;
int e;
boolean alive = true;
System.out.println("\n");
System.out.println(enemies[i].getName() + " has appeared!");
System.out.print("\n");
while (alive == true) {
System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
System.out.println("Attack[ATK] : " + enemies[i].getATK());
System.out.println("Mana[MANA] : " + enemies[i].getMANA());
System.out.println("\n");
System.out.println("[1 - Attack]");
System.out.println("[2 - Flee]");
answer = In.getInt();
System.out.println("\n");
if (answer == 1) {
if (user.getP_HP() > 0) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
System.out.println("\n");
} else if (user.getP_HP() <= 0) {
System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
alive = false;
}
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
System.out.println("\n");
} else if (enemies[1].getHP() <= 0) {
System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
alive = false;
}
} else if (answer == 2) {
System.out.println("You try to run, but fall into a pit of spikes and die!");
alive = false;
}
}
Hello, I'm having problems solving this issue for about 2 hours now. What I want to do is for the enemy to die immediately after its HP reaches 0 or below, and same for the player.
This works only if the player kills the goblin first, and not vice versa.
Whenever the enemy kills the player first, it does not output that you have been killed. Instead, it gives you the option to choose if you want to attack or flee again. After choosing the attack option, it only then states that you have been killed. That's not all though, after that the goblin attacks you again before the program stops.
Here is the sample output if the enemy kills you first:
stackoverflow strikes the Goblin for 1 damage.
Goblin has 12 HP remaining.
The Goblin attacked you for 3 damage.
stackoverflow has 1 HP remaining.
Hitpoints[HP]: 12
Attack[ATK] : 3
Mana[MANA] : 1
[1 - Attack]
[2 - Flee]
1
stackoverflow strikes the Goblin for 1 damage.
Goblin has 11 HP remaining.
The Goblin attacked you for 3 damage.
stackoverflow has -2 HP remaining.
Hitpoints[HP]: 11
Attack[ATK] : 3
Mana[MANA] : 1
[1 - Attack]
[2 - Flee]
1
stackoverflow has been slain by the Goblin!
The Goblin attacked you for 3 damage.
stackoverflow has -5 HP remaining.
try this:
int i = 1;
int answer;
int d;
int e;
boolean alive = true;
System.out.println("\n");
System.out.println(enemies[i].getName() + " has appeared!");
System.out.print("\n");
while (alive == true) {
System.out.println("Hitpoints[HP]: " + enemies[i].getHP());
System.out.println("Attack[ATK] : " + enemies[i].getATK());
System.out.println("Mana[MANA] : " + enemies[i].getMANA());
System.out.println("\n");
if (user.getP_HP() > 0) {
System.out.println("[1 - Attack]");
System.out.println("[2 - Flee]");
answer = In.getInt();
System.out.println("\n");
} else if (user.getP_HP() <= 0) {
System.out.println(user.getP_Name() + " has been slain by the " + enemies[i].getName() + "!");
alive = false;
answer = 0; //so it won't execute the rest of the code
}
if (answer == 1) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
System.out.println(user.getP_Name() + " strikes the " + enemies[i].getName() + " for " + user.getP_ATK() + " damage.");
System.out.println(enemies[i].getName() + " has " + enemies[i].getHP() + " HP remaining.");
System.out.println("\n");
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
System.out.println("The " + enemies[i].getName() + " attacked you for " + enemies[i].getATK() + " damage.");
System.out.println(user.getP_Name() + " has " + user.getP_HP() + " HP remaining.");
System.out.println("\n");
} else if (enemies[1].getHP() <= 0) {
System.out.println(user.getP_Name() + " has slain the " + enemies[i].getName() + "!");
alive = false;
}
} else if (answer == 2) {
System.out.println("You try to run, but fall into a pit of spikes and die!");
alive = false;
}
}
you need to check if you're alive BEFORE asking for an input. Might not be the best solution, but it's a fast one and I hope it points you in the right direction
You actually want to do things in the following order (assuming that you attack):
Ask the player whether they want to attack or flee
You attack
See if you killed the monster; if so, the game is over
The monster attacks
See if the monster killed you; if so, the game is over
Repeat until either #3 or #5 occurs
You reverse #3 and #5.
Also, the following line:
else if (enemies[1].getHP() <= 0)
has what I assume is a typo. I assume that you actually meant to do
else if (enemies[i].getHP() <= 0)
It seems like instead of using else if, what you want is something like this:
// Process both attacks first.
if (user.getP_HP() > 0) {
d = enemies[i].getHP() - user.getP_ATK();
enemies[i].setHP(d);
// ...
}
if (enemies[i].getHP() > 0) {
e = user.getP_HP() - enemies[i].getATK();
user.setP_HP(e);
// ...
}
// Then resolve the deaths immediately after.
if (user.getP_HP() <= 0) {
// ...
alive = false;
}
if (enemies[1].getHP() <= 0) {
// ...
alive = false;
}
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
You are using the wrong operator. != checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory).
You must write while (! "no".equals(proceed) ).
I did not write while (! proceed.equals("no") ) on purpose because if the string is null then you would get a NullPointerException.
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the "reverse" way as in my first example is more safely in general.
For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
You have to use .equals(String) to compare Strings, like so:
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (!proceed.equals("no")){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)
the below code is a part of code where computer plays the game. and the problem is the comp_overall_score is not getting updated when computer plays.
plzz help.
while(comp_turn_score < 20)
{
//roll logic
rollValue = rolldice();
Log.v("\nComputer Roll:",Integer.toString(rollValue));
if(rollValue != 1)
{
comp_turn_score += rollValue;
updateLabel("Computer's Turn Score: " + comp_turn_score);
return;
}
else //computer roll a 1
{
//reset turn score to 0 and give control to user
comp_turn_score = 0;
updateLabel("\nComputer rolled a 1! Your's Turn");
rollb.setEnabled(true);
}
}
//computer holds
comp_overall_score+= comp_turn_score;
updateLabel("\nComputer Holds! Your's Turn");
if(checkWinner()) return;
rollb.setEnabled(true);
}
private void updateLabel(String s)
{
lable.setText("\nYour score: " + user_overall_score + " Computer Score: " + comp_overall_score +" " + s);
}
if(rollValue != 1)
{
comp_turn_score += rollValue;
updateLabel("Computer's Turn Score: " + comp_turn_score);
return;
}
Remove the return statement and all would work as planned.
I have been trying to make a game in java called pig where a player rolls 2 dice. the player earns point based off of what they roll for example if the player rolls 5 and 4 he now has 9 points but if the player rolls a 1 they gain no points and control switches over to the computer and if the player rolls snake eyes ( 1 and 1) the player loses all point and control switches over to the computer. i have the game working but i need to stop the computer after it gains 20 points in its turn. Whichever player hits 100 first wins.
Here is my code:
//this program runs 4.4
import java.util.Scanner;
public class run {
public static void main(String[] args)
{Scanner scan = new Scanner (System.in);
dice thing = new dice();
dice thing1 = new dice();
boolean control=true;
int x = 0,points=0,a,b,y=0,c,d,turn=0,save=0,no=0;
while(x<100 && y<100)
{
while (control == true && x<100)
{
a=thing.roll();
b=thing1.roll();
if (a == 1 && b==1)
{
control=false;
System.out.println("your first die rolled a " + thing.getroll() + " second die rolled a " + thing1.getroll()+"computer now has control");
x=0;
}
else if(a == 1 || b==1)
{
control = false;
System.out.println("your first die rolled a " + thing.getroll() + " second die rolled a " + thing1.getroll() + " now you have " + x +" points "+"computer now has control");
}
else
{
x +=(a+b);
System.out.println("your first die rolled a " + thing.getroll() + " your second die rolled a " + thing1.getroll() + " now you have " + x +" points" );
System.out.println(" would you like to end your turn put in 1 for yes 0 for no");
points = scan.nextInt();
if(points==1)
{
control= false;
}
if (x>=100)
{
System.out.println("you win");
}
}
}
while (control==false && y<100)
{
c=thing.roll();
d=thing1.roll();
if (c == 1 && d==1)
{
control=true;
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll()+"you now have control");
turn = y;
y=0;
}
else if(c == 1 || d==1)
{
control = true;
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll()+ " now the computer has " + y +" points "+"you now have control");
turn = y;
}
else
{
y +=(c+d);
System.out.println("The computers first die rolled a " + thing.getroll() + " The computers second die rolled a " + thing1.getroll() + " now the computer has " + y +" points" );
turn = y;
if (y>=100)
{
System.out.println("you lose");
}
}
}
}
}
}
Try adding:
if (turn >= 20){
control = true;
turn = 0;
}
after:
while (control==false && y<100)
{
I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}