I have a question about the while loop in my code - java

How do I make the while loop stop forcefully by using playerHP when it becomes zero? Sometimes I would put an If statement around it, but it wouldn't work. New to coding so it would be cool to give some tips too. :)
public class RPGFight {
public static void main (String args[]) {
int playerHP = 30;
int boss1HP = 420;
int exp = 0;
System.out.println("You open the chamber door to see what lies beyond.");
System.out.println("A demogorgon jumps out and attacks!");
System.out.println("You deftly pull out your mighty blade and defend youself");
while (boss1HP > 0) {
if (boss1HP > 0) {
int hit1 = (int)(Math.random()*20);
int hit2 = (int)(Math.random()*20);
int hit3 = (int)(Math.random()*20);
int hit4 = (int)(Math.random()*20);
int hit5 = (int)(Math.random()*20);
int hit6 = (int)(Math.random()*20);
int bossDMG = (int)(Math.random()*5);
System.out.println("\nYou hit the demogorgon for " + hit1 + " points of damage");
System.out.println("You hit the demogorgon for " + hit2 + " points of damage");
System.out.println("You hit the demogorgon for " + hit3 + " points of damage");
System.out.println("You hit the demogorgon for " + hit4 + " points of damage");
System.out.println("You hit the demogorgon for " + hit5 + " points of damage");
System.out.println("You hit the demogorgon for " + hit6 + " points of damage");
System.out.println("You have been hit for " + bossDMG + " points of damage");
playerHP -= bossDMG;
boss1HP -= hit1+hit2+hit3+hit4+hit5+hit6;
}
if (boss1HP < 0) {
int expbattle = (int)(Math.random()*126+5);
exp += expbattle;
System.out.println("\nThe demogorgon falls to the floor, lifeless.");
System.out.println("Congratulations! You earned " + expbattle + " points of experience.");
}
}
}
}

Put the if condition after
playerHP -= bossDMG;
if (playerHP < 1)
break;
this will break the while loop when playerHP value is less than equal to 0.

By adding a break immediately after you modify the playerHP after checking that is less than or equal to zero. Like,
playerHP -= bossDMG;
if (playerHP <= 0) {
break;
}
// ...

Related

I am stuck, trying to make a turn based game but have been having trouble ending a turn and starting a new one

I can end the first. I am trying to make it on odd turns player goes and even turns CPU goes.
public static void main(String[] args) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
String mage = "mage";
System.out.println("mage, warrior, assassin, ranger?");
String input = keyboard.nextLine();
int playerAttackDice = random.nextInt(20) + 1;
int cpuAttackDice = random.nextInt(20) + 1;
int playerDefenseDice = random.nextInt(5) + 1;
int cpuDefenseDice = random.nextInt(5) + 1;
int turn = 1;
while(mage.equalsIgnoreCase(input)) {
Mage player = new Mage();
Warrior CPU = new Warrior();
System.out.println("You have selected: mage");
System.out.println("Your Attack Power is: " + player.getMageAttack());
System.out.println("Your Defense is: " + player.getMageDefense());
System.out.println("Your Health is: " + player.getMageHealth());
System.out.println("Your enemy is a: warrior");
System.out.println("Enemy Attack Power is: " + CPU.getMageAttack());
System.out.println("Enemy Defense is: " + CPU.getMageDefense());
System.out.println("Enemy Health is: " + CPU.getMageHealth());
System.out.println();
This is where the turn begins. I was trying to set it to make it player goes on odd numbers in the when the CPU goes. Am I even approaching this in the right way? Any help would be very much appreciated.
while(player.mageHealth != 0) {
System.out.println("Your health is: " + player.mageHealth);
for(turn = 1; turn % 1 ==0; turn++) {
if(turn % 1==0) {
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
return;
}
}
turn++;
for(turn = 2; turn % 2 ==0; turn++) {
while(turn % 2==0) {
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
}
}
}
System.out.println("end loop");
break;
}
}
If you want Player and CPU to play their move one after another - just put their actions one after another with no inner loops and complex conditions around
while (!game.isOver()) {
player.makeMove();
cpu.makeMove();
}
or having your code there
while(player.mageHealth > 0) { // game over condition
//player move
System.out.println("Your health is: " + player.mageHealth);
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
//cpu move
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
player.mageHealth = player.mageHealth + playerDefence - cpuDamage;
}

Certain "if" statements containing print lines not being executed and thus not printing onto the console

I am coding a text-based java game where the user types in certain inputs to ultimately defeat an enemy. I want to create a score by writing out if statements that state if the damage done on the enemy was x amount, then award x points. However, I believe the if statement is being skipped over because it is not printing the print statements.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
game gameObject = new game();
gameObject.runGame();
}
}
class game {
public void runGame() {
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game Variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assasain"};
int maxEnemyHealth = 100;
int enemyAttackDamage = 50;
// Player Variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
int counter = 0;
int points =0;
boolean running = true;
System.out.println("Welcome to the Dungeon!");
GAME:
while (running) {
System.out.println("-----------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt);
System.out.println("\t> You recieve " + damageTaken + " in retaliation!");
if (health < 1) {
System.out.println("\t> You have taken too much damage, you are too weak to move on!");
break;
}
if (damageDealt > 20) {
points += 50;
System.out.print("You gained 50 points. You have" + points + " points in total.");
}
else if (damageDealt > 30) {
points += 60;
System.out.print("You gained 60 points. You have" + points + " points in total.");
}
else if (damageDealt >50) {
points += 100;
System.out.print("You gained 100 points. You have" + points + " points in total.");
}
}
else if (input.equals("2")) {
if (numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP."
+ "\n\t> You have " + numHealthPotions + " health potionsleft.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies to get a chance to get one.\n");
}
}
else if (input.equals("3")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("\tInvalid command.");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
System.out.println("-----------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPotions + " health potion(s). #");
}
System.out.println("-----------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("1. Exit the dungeon");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.print("Invalid command!");
input = in.nextLine();
}
if (input.contentEquals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
break;
}
counter++;
}
}
class exit {
public String byeStatements () {
String format;
String thanks;
format = "###########";
thanks = "Thanks for playing!";
System.out.println(format);
System.out.println(thanks);
return (format + thanks);
}
}

Can't figure out how to reset an int so I can use my loop properly making the game of Pig

When it is the computer's turn I need it to keep going until it reaches 35 points for the current turn but I am not sure how to reset it back to 0 for a new turn so every time after the computer reaches 35 points it will only go once.
import java.util.Scanner;
import java.util.Random;
public class PigGamev1
{
public static void main(String[] args)
{
int humanScore = 0;
int computerScore = 0;
int win = 100;
int die1 = 0;
int die2 = 0;
int total = 0;
boolean gameOver = false;
boolean turnOver = false;
char repeat = 'r';
String input;
Scanner keyboard = new Scanner(System.in);
Random randomGenerator = new Random();
do
{
//human rolls dice
do
{
die1 = randomGenerator.nextInt(6) + 1;
die2 = randomGenerator.nextInt(6) + 1;
total = die1 + die2;
if(total == 2)
{
humanScore += 0;
System.out.println("You rolled a: " + total);
System.out.println("Turn over.");
System.out.println("Your current score is " + humanScore);
turnOver = true;
}
else if(humanScore <= win && total != 2)
{
humanScore += total;
System.out.println("You rolled a: " + total);
if(humanScore >= win)
{
System.out.println("Your score is " + humanScore + " and my score is "
+ computerScore);
System.out.println("You win!");
turnOver = true;
gameOver = true;
System.exit(0);
}
System.out.println("Your current score is " + humanScore);
System.out.println("Enter r to roll again or h to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'r')
{
turnOver=false;
}
else if(repeat == 'h')
{
System.out.println("Turn over.");
System.out.println("Your current score is " + humanScore +
" total computer score is " + computerScore + "\n");
turnOver = true;
}
}
}while(turnOver == false);
//computer rolls dice
System.out.println("My turn! \n");
do
{
turnOver = false;
die1 = randomGenerator.nextInt(6) + 1;
die2 = randomGenerator.nextInt(6) + 1;
total = die1 + die2;
System.out.println("I rolled a: " + total);
if(total == 2)
{
computerScore += 0;
System.out.println("Turn over.");
System.out.println("My current score is " + computerScore + "\n");
turnOver = true;
}
else
{
computerScore += total;
System.out.println("My current score is " + computerScore + "\n");
if(computerScore >= 35)
{
System.out.println("I hold.");
System.out.println("Your turn!\n");
System.out.println("My current score is " + computerScore +
" your score is " + humanScore + "\n");
turnOver = true;
}
}
if(computerScore >= win)
{
System.out.println("I win!");
turnOver = true;
gameOver = true;
System.exit(0);
}
}while(turnOver == false);
}while(gameOver == false);
keyboard.close();
}
}
Use different variables to keep track of the total score for the computer and the score it has on their current turn. For instance, you could define int computerTurn; with the rest of your variables, and use it as such in your program, remembering to reset it to 0 when the turn ends:
//some code omitted if not relevant to your problem
do
{
if(total == 2)
{
computerScore += computerTurn; //adds current turn to running total
System.out.println("Turn over.");
System.out.println("My current score is " + computerScore + "\n");
turnOver = true;
}
else
{
computerTurn+= total;
System.out.println("My current score is " + computerScore + "\n");
if(computerTurn >= 35) //checks against current turn instead of total
{
computerScore += computerTurn; //adds current turn to running total
System.out.println("I hold.");
System.out.println("Your turn!\n");
System.out.println("My current score is " + computerScore +
" your score is " + humanScore + "\n");
turnOver = true;
}
}
}while(turnOver == false);
computerTurn = 0;

Correcting and improving java code

The code I have written so far, is below and works however I am having a few issues with it
1) It runs the program more than once
2) The numbers don't seem to be very random, it seems to pick the same numbers out
3) I need the value 1 to display as Ace, the value 11 to display as Jack, the value 12 to display at Queen and the value 13 to display as King
I have gone over my code several times and cant figure out why it is doing point 1
I am not sure if it is just me, or if it is an issue with point 2
I know I need an if statment to do number 3 but not quite sure where to put it
The idea of the program is for the player to verse the computer and draw 7 cards each in turn, (suite doesn't need to be included) and output each card followed by the winner, with 1 output as ace, 11 output as jack, 12 output as queen and 13 output at king.
Many thanks for your help
import java.math.*;
import java.util.*;
public class CardProj {
public static void main(String[] args) {
Scanner mykbd = new Scanner(System.in);
Random rn = new Random();
{
for (int i = 0; i < 14; i++) {
int card1player = 0;
int card2player = 0;
int card3player = 0;
int card4player = 0;
int card5player = 0;
int card6player = 0;
int card7player = 0;
int card1Computer = 0;
int card2Computer = 0;
int card3Computer = 0;
int card4Computer = 0;
int card5Computer = 0;
int card6Computer = 0;
int card7Computer = 0;
System.out.println("Player Card 1: " + card1player);
card1Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 1: " + card1Computer);
System.out.println("");
card2player = rn.nextInt(7) + 1;
System.out.println("Player Card 2: " + card2player);
card2Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 2: " + card2Computer);
System.out.println("");
card3player = rn.nextInt(7) + 1;
System.out.println("Player Card 3: " + card3player);
card3Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 3: " + card3Computer);
System.out.println("");
card4player = rn.nextInt(7) + 1;
System.out.println("Player Card 4: " + card4player);
card4Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 4: " + card4Computer);
System.out.println("");
card5player = rn.nextInt(7) + 1;
System.out.println("Player Card 5: " + card5player);
card5Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 5: " + card5Computer);
System.out.println("");
card6player = rn.nextInt(7) + 1;
System.out.println("Player Card 6: " + card6player);
card6Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 6: " + card6Computer);
System.out.println("");
card7player = rn.nextInt(7) + 1;
System.out.println("Player Card 7: " + card7player);
card7Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 7: " + card7Computer);
System.out.println("");
int playertotal = card1player + card2player + card3player + card4player + card5player + card6player + card7player;
int computertotal = card1Computer + card2Computer + card3Computer + card4Computer + card5Computer + card6Computer + card7Computer;
if (playertotal > computertotal) {
System.out.print("Player Wins, Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
} else if (computertotal > playertotal) {
System.out.print("Computer Wins, Computer Score is, " + computertotal + " Players Score is, " + playertotal + " ");
} else {
System.out.print("Draw Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
}
}
}
}
}
You can create an array of cardPlayers and cardComputers. For instance try this below
int numPlayers = 14;
int [] cardPlayer = new int[numPlayers];
int [] cardComputer = new int[numPlayers];
for (int i = 0; i < numPlayers; i++) {
System.out.println("Player Card " + i + ": " + cardPlayer[i]);
cardComputer[i] = rn.nextInt(7) + 1;
System.out.println("Computer Card " + "i" + cardComputer[i]);
System.out.println("");
}
This will make your code more readable and reduce lines in total

Hanging token from user input is not allowing me to proceed in my program

My program is not allowing me to enter user input if i do not enter a number and i want to go through the program again, it think its due to a hanging token somewhere but i cannot seem to find it.
import java.util.Scanner;
public class LessonTwo {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
char answer = ' ';
do {
System.out.print("Your favorite number: ");
if (userInput.hasNextInt()) {
int numberEntered = userInput.nextInt();
userInput.nextLine();
System.out.println("You entered " + numberEntered);
int numEnteredTimes2 = numberEntered + numberEntered;
System.out.println(numberEntered + " + " + numberEntered
+ " = " + numEnteredTimes2);
int numEnteredMinus2 = numberEntered - 2;
System.out.println(numberEntered + " - 2 " + " = "
+ numEnteredMinus2);
int numEnteredTimesSelf = numberEntered * numberEntered;
System.out.println(numberEntered + " * " + numberEntered
+ " = " + numEnteredTimesSelf);
double numEnteredDivide2 = (double) numberEntered / 2;
System.out.println(numberEntered + " / 2 " + " = "
+ numEnteredDivide2);
int numEnteredRemainder = numberEntered % 2;
System.out.println(numberEntered + " % 2 " + " = "
+ numEnteredRemainder);
numberEntered += 2; // *= /= %= Also work
numberEntered -= 2;
numberEntered++;
numberEntered--;
int numEnteredABS = Math.abs(numberEntered); // Returns the
int whichIsBigger = Math.max(5, 7);
int whichIsSmaller = Math.min(5, 7);
double numSqrt = Math.sqrt(5.23);
int numCeiling = (int) Math.ceil(5.23);
System.out.println("Ceiling: " + numCeiling);
int numFloor = (int) Math.floor(5.23);
System.out.println("Floor: " + numFloor);
int numRound = (int) Math.round(5.23);
System.out.println("Rounded: " + numRound);
int randomNumber = (int) (Math.random() * 10);
System.out.println("A random number " + randomNumber);
} else {
System.out.println("Sorry you must enter an integer");
}
System.out.print("Would you like to try again? ");
answer = userInput.next().charAt(0);
}while(Character.toUpperCase(answer) == 'Y');
System.exit(0);
}
}
Yes you are right you need to consume the characters first after the user inputted character in the nextInt before allowing the user to input data again
just add this in your else block and it will work:
else {
System.out.println("Sorry you must enter an integer");
userInput.nextLine(); //will consume the character that was inputted in the `nextInt`
}
EDIT:
change this:
answer = userInput.next().charAt(0);
to:
answer = userInput.nextLine().charAt(0);

Categories

Resources