My final project for class is a text based game. So far I have it working how I want, except for 1 or 2 issues. First big issue is when I enter my "magic" menu (switch statement loop) none of the data has any impact. Meaning if the user's HP drops below 0, they don't die, it doesn't happen until you exit the loop. I've messed with it, and made it work, but it broke other parts of the code, so please help if you can.
Another solution I was able to do was setting the boolean value to false after each case, making the user enter a case, then it jumps out of the switch, which works great, except it executes the entire switch loop, meaning every single input.
Here's the main code, keep in mind it has another class
package textRPG;
import java.util.Random;
import java.util.Scanner;
public class LoopyLoop {
private static int maxEnemyHealth = 155;
private static int enemyAttackDmg = 25;
private static int health = 109;
private static int attackDmg = 30;
private static int mana = 15;
private static int numHealthPots = 3;
private static int healthPotionHealAmount = 30;
private static int healthPotionDropChance = 20;
private static int manaPotionRecoveryAmount = 12;
private static int count = 0;
private static int count2 = 0;
private static int expUp = 0;
private static int level = 1;
public static void main(String[] args) {
SpellsAndAbilities spells = new SpellsAndAbilities();
Scanner in = new Scanner(System.in);
Random rand = new Random();
//String Array for enemies, more can be added, or taken away
String[] enemies = {"Skeleton", "Zombie", "Goblin", "Tiny Dragon", "Ben Afleck", "Little weird man", "Huge Bee", "Jeff", "Crazy Ray"};
//Set a variable running to true, to allow the program to run, so that if the user chooses to end the game early, they can do so
boolean running = true;
System.out.println("==================================================================");
System.out.println("Welcome to Mysterical World of Mysterical Things!");
System.out.println("Please press the number corresponding the action you wish to take.");
System.out.println("==================================================================");
//Clause to keep the game running with invalid inputs
GAME:
while(running) {
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\n\t### " + enemy + " has appeared! ###\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
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. Spells");
System.out.println("\t3. Use potion");
System.out.println("\t4. Run");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDmg);
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t>>> You hit the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> The " + enemy + " hit you for " + damageTaken + " damage <<<");
System.out.println();
if(health < 1) {
System.out.println("\t=== You died! ===");
break;
}
//
//Problem Starts Here
//
}else if (input.equals("2")) {
boolean set=true;
while(set) {
System.out.println("____________________________________________\n");
System.out.println("1. Fireblast (Cost: 6 mana, Damage: 10-19)");
System.out.println("2. Ice Sickle (Cost: 9 mana, Damage: 22-26)");
System.out.println("3. Whirlwind (Cost: 14 mana, Damage: 31-36)");
System.out.println("4. Earth shard (Cost: 28 mana, Damage: 38-42)");
System.out.println("5. Heal (Cost: 50 mana, Heals: 35 to 55 HP)");
System.out.println("6. Exit this menu");
System.out.println("____________________________________________");
int spellInput = in.nextInt();
switch (spellInput) {
case 1: if(mana >= 6) {
mana -= 6;
int damageDealt = spells.fireBlast();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Fire Blast!");
System.out.println("\t====================");
System.out.println("\n\t>>> Fireblast hits the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage<<<");
System.out.println();
break;
}
else {
break;
}
case 2: if (mana >= 9) {
mana -= 9;
int damageDealt = spells.iceSickle();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Ice Sickle!");
System.out.println("\t====================");
System.out.println("\n\t>>> Ice Sickle slashes the " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
System.out.println("You need more mana");
break;
}
case 3: if(mana >= 14) {
mana -= 14;
int damageDealt = spells.whirlWind();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Whirlwind!");
System.out.println("\t====================");
System.out.println("\n\t>>> Whirlwind ravages " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 4: if(mana >= 28) {
mana -= 28;
int damageDealt = spells.earthShard();
int damageTaken = rand.nextInt(enemyAttackDmg);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t====================");
System.out.println("\tYou cast Earth Shard!");
System.out.println("\t====================");
System.out.println("\n\t>>> Earth shard pummels " + enemy + " for " + damageDealt + " damage <<<");
System.out.println("\t>>> You took " + damageTaken+ " <<<");
System.out.println();
break;
}
else {
break;
}
case 5: if(mana >= 50) {
mana -= 50;
health += spells.Heal();
int damageTaken = rand.nextInt(enemyAttackDmg);
health -= damageTaken;
System.out.println("\t===============");
System.out.println("\tYou cast Heal!");
System.out.println("\t===============");
System.out.println("\n\t>>> You recover " + spells.Heal() + " HP <<<");
System.out.println("\t>>> You took " + damageTaken+ " damage <<<");
System.out.println("\tYour HP: " + health);
System.out.println("\tYour Mana: " + mana);
System.out.println();
break;
}
else {
break;;
}
case 6: set = false;
default: break;
}
}
}
else if (input.equals("3")) {
if (numHealthPots > 0) {
count2++;
health += healthPotionHealAmount;
mana += manaPotionRecoveryAmount;
numHealthPots--;
System.out.println("\tYou drink a potion, healing for " + healthPotionHealAmount + " HP and recovering " + manaPotionRecoveryAmount + " mana" +
"\n\t>> You now have " + health + " HP and " + mana +" Mana <<" +
"\n\t>> You have " + numHealthPots + " potions left <<");
}
else {
System.out.println("\tYou have no potions left! Defeat enemies for a chance to get one!");
}
} else if (input.equals("4")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("-------------------------------------");
}
}
if(health < 1) {
System.out.println("You pitifully limp out of the dungeon, too weak to go on!");
break;
}
count++;
System.out.println("=========================================");
System.out.println(" *** " + enemy +" was defeated! ***");
System.out.println("### You have " + health + " HP ### \n### And " + mana + " mana ###");
expUp += expUp + 25;
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPots++;
System.out.println(" # The " + enemy + " dropped a health potion");
System.out.println(" # You now have " + numHealthPots + " health potion(s) # ");
}
if(expUp > 99) {
level++;
health = health+22;
attackDmg = attackDmg + 2;
mana = mana + 7;
System.out.println("****** LEVEL UP!!! ******");
System.out.println("You are now level " + level + "!");
System.out.println("Each level up rewards 22 to total health, +2 to attack, and +7 to mana!");
}
System.out.println("=========================================");
System.out.println("What would you like to do now?");
System.out.println("Press 1 to continue fighting");
System.out.println("Pess 2 to exit");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command");
input = in.nextLine();
}
if (input.equals("1")) {
System.out.println("You choose to continue, good luck!");
}
else if (input.equals("2")) {
System.out.println("You exit the game");
break;
}
}
System.out.println("####################");
System.out.println("Thanks for playing!");
System.out.println("####################");
System.out.println("Press 5 to see your score!");
String input2 = in.nextLine();
if (input2.equals("5")){
System.out.println("You defeated " + count + " enemies");
System.out.println("Max level achieved: " + level);
System.out.println("And you used " + count2 + " potions");
}
else {
System.out.println("Invalid input");
input2 = in.nextLine();
}
in.close();
}
}
Output ends up looking like this:
6. Exit this menu
____________________________________________
6
=========================================
*** Tiny Dragon was defeated! ***
### You have 136 HP ###
### And 6 mana ###
****** LEVEL UP!!! ******
Related
I am stuck at a part where in a game, I use while loop and to end the loop and get the results of the game, I want either "player1" or "player2" to enter "Q", and so i tried doing it like this:
if (player1.equals("Q") || player2.equals("Q")){
go = false; //go is a boolean variable
}
This doesn't seem to work as I have to enter "Q" for both player1 and player2 for the game to end, but instead I just want either of them to enter "Q" and the game would stop.
Code:
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Soccer Game Between 2 Teams");
System.out.println("Win is 2 points" + "\n" + "Loss is worth 0 points" + "\n" + "Overtime is worth 1 point");
System.out.println("Type W, O, or L" + "\n" + "Type Q to end the game");
int pointsw = 0;
int pointsl = 0;
int pointso = 0;
int pointsw2 = 0;
int pointsl2 = 0;
int pointso2 = 0;
int totalpoints = 0;
int totalpoints2 = 0;
int counter = 0;
int counter2 = 0;
boolean go = true;
System.out.println("\n" + "Enter team one:");
String phrase = keyboard.next();
System.out.println("\n" + "Enter team two:");
String phrase2 = keyboard.next();
System.out.println();
while (go) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next();
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next();
if (team1.equals("W") || team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("O") || team1.equals("o")) {
pointso += 1;
} else if (team1.equals("L") || team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("W") || team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("O") || team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("L") || team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
if (team1.equals("Q") || team2.equals("Q")) {
go = false;
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
}
}
}
}
You should reorganize your code:
while (true) {
System.out.println("Enter " + phrase + " Result:");
String team1 = keyboard.next().toLowerCase();
if ("q".equals(team1)) {
break;
}
System.out.println("Enter " + phrase2 + " Result");
String team2 = keyboard.next().toLowerCase();
if ("q".equals(team2)) {
break;
}
if (team1.equals("w")) {
pointsw += 2;
} else if (team1.equals("o")) {
pointso += 1;
} else if (team1.equals("l")) {
pointsl += 0;
}
counter++;
if (team2.equals("w")) {
pointsw2 += 2;
} else if (team2.equals("o")) {
pointso2 += 1;
} else if (team2.equals("l")) {
pointsl2 += 0;
}
counter2++;
totalpoints = pointsw + pointso + pointsl;
totalpoints2 = pointsw2 + pointso2 + pointsl2;
} // loop completed
if (totalpoints > totalpoints2) {
System.out.println(phrase + " wins with " + totalpoints + " points");
System.out.println("It took " + phrase + " " + counter + " rounds to win");
} else if (totalpoints < totalpoints2) {
System.out.println(phrase2 + " wins with " + totalpoints2 + " points");
System.out.println("It took " + phrase2 + " " + counter2 + " rounds to win");
} else if (totalpoints == totalpoints2) {
int totalrounds = counter + counter2;
System.out.println("It is tie game between " + phrase + " and " + phrase2);
System.out.println("The game lasted till " + totalrounds + " rounds");
}
I'm not completely sure, but I think the issue is that after player 1 / player 2 says 'Q'
the scanner is still waiting for the next line to read.
String phrase = keyboard.next();
System.out.println("\n"+"Enter team two:");
String phrase2 = keyboard.next();//if player 1 types q this next() method must be resolved before it will continue to the logic
so add an if statement before play 2 goes asking if player 1 typed 'Q' , if so calculate scores and end game, if player 1 did not type 'Q' use else statement to continue on to player 2's turn
I am just 2 months into programming so I apologize for my poorly written code. I appreciate it if you will give me tips and advice on how i can improve my code.
I created a program that creates a hero.(in this case I used dota heroes)
The program starts by asking The hero name, Health pool, mana pool, attack speed and attack damage.
after I created a method that will ask a user what type of hero it is.
the selection are 1. Strength 2. Agility 3. Intelligence. Each selection will set the hero's attack damage per level, attack speed per level, Hp per level and mp per level.
after this, the program will then ask a user to choose a level(max level is only 25)
after selecting the level the program will display the new attributes after leveling up. for example if the user chooses 25 then Healthpool = healthpool + (hp per level * selected level) and etc.
After this the program will then show a selection of enemies in this example is tower and roshan.
after the user chooses an enemy the program will then show an option on what to do such as 1. attack 2. end.
What I want to happen is when the user chooses to attack, I want the program to show the current hp of the tower after attacking then will go back to the options on what to do.
I really do not know what loop should I do.
import java.util.Scanner;
class Hero {
Scanner sc = new Scanner(System.in);
String name, heroType, heroOpponent;
double baseHp, baseMp, baseAs, baseAd, asplvl, adplvl, hplvl, mplvl, tower;
int lvl, type, opponent, option;
void UserInput() {
System.out.print("Please enter hero name: ");
name = sc.nextLine();
System.out.print("Please enter your base Health Pool: ");
baseHp = sc.nextDouble();
System.out.print("Please enter your base Mana Pool: ");
baseMp = sc.nextDouble();
System.out.print("Please enter your base Attack Speed: ");
baseAs = sc.nextDouble();
System.out.print("Please enter your base Attack Damage: ");
baseAd = sc.nextDouble();
}
void TypeMethod() {
do {
System.out.println("Please select your hero type");
System.out.println();
System.out.println("1. Strength");
System.out.println("2. Agility");
System.out.println("3. Intelligence");
type = sc.nextInt();
switch (type) {
case 1:
heroType = ("Strength");
asplvl = 2.5;
adplvl = 5;
hplvl = 20;
mplvl = 12;
break;
case 2:
heroType = ("Agility");
asplvl = 7;
adplvl = 5;
hplvl = 12;
mplvl = 12;
break;
case 3:
heroType = ("Intelligence");
asplvl = 2.5;
adplvl = 5;
hplvl = 12;
mplvl = 20;
break;
default:
System.out.println("Selection Error! Try again!");
}
} while (type > 3 && type < 1);
}
void DisplayUserInput() {
System.out.println("Hero name: " + name);
System.out.println("Hero type: " + heroType);
System.out.println("Base Health Pool: " + baseHp);
System.out.println("Base Mana Pool: " + baseMp);
System.out.println("Base Attack Speed: " + baseAs);
System.out.println("Base Attack Damage: " + baseAd);
}
int HeroLevel() {
do {
System.out.println("Choose your level! Maximum level is 25");
lvl = sc.nextInt();
return lvl;
} while (lvl > 25 | lvl < 0);
}
double MpAfterLevel(int i) {
return baseMp = baseMp + (mplvl * (double) i);
}
double HpAfterLevel(int i) {
return baseHp + (hplvl * (double) i);
}
double AsAfterLevel(int i) {
return baseAs = baseAs + (baseAs * (double) i);
}
double AdAfterLevel(int i) {
return baseAd = baseAd + (baseAd * (double) i);
}
void DisplayHeroAfterLevel() {
System.out.println("Hero name : " + name);
System.out.println("Hero type : " + heroType);
System.out.println("Health Pool after at level " + lvl + " " + baseHp);
System.out.println("Mana Pool after at level " + lvl + " " + baseMp);
System.out.println("Attack Damage after at level " + lvl + " " + baseAd);
System.out.println("Attack Speed after at level " + lvl + " " + baseAs);
System.out.println();
}
void WhotoAttack() {
System.out.println("Please select an opponent");
System.out.println("1. Tower");
System.out.println("2. Roshan");
opponent = sc.nextInt();
switch (opponent) {
case 1:
do {
tower = 5000;
System.out.println("tower has " + tower + " Health points");
System.out.println("Please take action!");
System.out.println("1. Attack ");
System.out.println("2. End");
option = sc.nextInt();
switch (option) {
case 1:
case 2:
}
} while (tower != 0);
}
}
}
public class DotaHeroV1 {
public static void main(String args[]) {
Hero h1 = new Hero();
int i;
h1.UserInput();
h1.TypeMethod();
h1.DisplayUserInput();
i = h1.HeroLevel();
h1.HpAfterLevel(i);
h1.MpAfterLevel(i);
h1.AsAfterLevel(i);
h1.AdAfterLevel(i);
h1.DisplayHeroAfterLevel();
h1.WhotoAttack();
}
}
It's been more than a year, and I've just stumbled onto this question.
You probably don't need an answer anymore, but if you happen to need it i am making a game that involves enemies attacking each other until someone dies.
Here's a snippet for what I'm using for a Player1 attacking a Player2:
new Thread(new Runnable() {
#Override
public void run() {
do {
try {
System.out.println("DELAYING " + (long) game.getAttackDelay(finalPlayer1));
Thread.sleep((long) game.getAttackDelay(finalPlayer1));
float p1DamageDealt = game.fight(finalPlayer1, finalPlayer2);
game.setCurrentHp(finalPlayer2, p1DamageDealt);
if (game.getCurrentHp(finalPlayer1) <= 0 || game.getCurrentHp(finalPlayer2) <= 0) {
break;
}
sendToPlayerOne.writeObject("YOU DEALT " + p1DamageDealt + "!");
sendToPlayerTwo.writeObject("YOU TOOK " + p1DamageDealt + "!");
sendToPlayerOne.writeObject("ENEMY HAS " + game.getCurrentHp(finalPlayer2) + " HP LEFT!");
sendToPlayerTwo.writeObject("YOU HAVE " + game.getCurrentHp(finalPlayer2) + " HP LEFT!");
//sendToPlayerOne.writeObject(p1DamageDealt);
} catch (InterruptedException | IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
} while (finalPlayer1.getCurrentHp() > 0 && finalPlayer2.getCurrentHp() > 0);
if (finalPlayer1.getCurrentHp() <= 0 && finalPlayer2.getCurrentHp() > 0) {
gameResult = "YOU LOSE!";
} else if (finalPlayer2.getCurrentHp() <= 0 && finalPlayer1.getCurrentHp() > 0) {
gameResult = "YOU WIN!";
} else {
gameResult = "IT'S A TIE!\n"
+ "Your HP : " + finalPlayer1.getCurrentHp() + "\n"
+ "Enemy HP:" + finalPlayer2.getCurrentHp();
}
try {
sendToPlayerOne.writeObject(gameResult);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
It's not very good but works for what I need, and probably will work for you with some adjustments, since the basics for this to work is just do a "do X(attack) while Y(enemy health is not 0)"
I'm having an issue with exportation in Java. When I launch the JAR file I have created (in Eclipse), it instantly gives me an error, reading:
"Error: Invalid or corrupt jarfile C:\Users\Samuel\Desktop\Deep Dungeons.jar"
My Code is as follows:
import java.util.*;
public class Main {
public static void main(String[] args) {
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton" , "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
// Player Variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 5;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
int enemiesKilled = 0;
int maxHealth = 100;
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("\t Your 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 + " damage");
System.out.println("\t> You recieve " + damageTaken + " in retaliation!");
if (health < 1) {
System.out.println("\t You have taken too much damage, you are to weak to go on!");
break;
}
} else if(input.equals("2")) {
if (numHealthPotions > 0) {
health += healthPotionHealAmount;
if (health > maxHealth)
health = 100;
numHealthPotions --;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP."
+ "\n\t> You now have " + numHealthPotions + "health potions left.\n");
} else {
System.out.println("\t> You have no health potions left! Defeat enemies for 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("\nInvalid command!");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle.");
System.out.println("You killed " + enemiesKilled + ".");
break;
}
System.out.println("--------------------------------------");
System.out.println(" # " + enemy + " was defeated! # ");
enemiesKilled ++;
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 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("2. Exit dungeon");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command!");
input = in.nextLine();
}
if (input.equals("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!");
System.out.println("You killed " + enemiesKilled + "!");
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
}
}
I figured out the problem. When I was exporting, I should have been attempting to export as a runnable jar file, rather than a regular JAR file.
I am not sure why I am getting this error. It even shows when I compile it that I have the class file in the folder but this error happens. I will give my code which is a basic game I made. I am new to Java.
package game;
import java.util.Scanner;
import java.util.Random;
public class DungeonGame {
public static void main (String[] args){
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game Variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
// Player Variables
int health = 100; // How much health we have
int attackDamage = 50; // How much damage our player can do
int numHealthPotions = 3; // Number of health pots our player is set with
int healthPotionHealAmount = 30; // Amount a health the pot will raise
int healthPotionDropChance = 50; // Percentage drop
boolean running = true;
GAME:
while (running) {
System.out.println("---------------------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth); // Get a random health for enemy (How strong is the enemy?)
String enemy = enemies[rand.nextInt(enemies.length)]; //Set random enemy from array
System.out.println("\t#" + enemy + "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 + "damage.");
System.out.println("\t> You recieve" + damageTaken + "in retaliation!");
if(health < 1) {
System.out.println(">t You have taken too much damage, you are to weak to go on!");
break;
}
}
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 potions left.\n");
}
else {
System.out.println("\t> You have no health potions left!! Defeat enemies for 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("2. Exit game");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("invalid Command!");
input = in.nextLine();
}
if(input.equals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dengeon, successful from your adventures!");
break;
}
}
}
}
I have been trying to figure out how to make it so players could choose to restart the game at the end, but whenever I try to restart the loop, it says
Label Game was not found
even though it is clearly shown in this code.
// System objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assassin"};
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;
int enemyDeaths = 0;
List scores = new ArrayList();
// Player variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
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 + " damage. ");
System.out.println("\t> You received " + damageTaken + " in retaliation");
if(health < 1) {
System.out.println("\t> You have taken too much damage! You are too weak to go on!");
break;
}
}
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 potions left.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
else if(input.equals("3")) {
System.out.println("\tYou ran 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;
}
enemyDeaths++;
System.out.println("-----------------------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
System.out.println(" # Your current score is " + enemyDeaths * 100 + " # ");
if(rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! #");
System.out.println(" # You 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("2. Exit Dungeon");
String input = in.nextLine();
while(!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid Command");
input = in.nextLine();
}
if (input.equals("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!");
scores.add(enemyDeaths * 100);
break;
}
}
System.out.println("######################");
System.out.println("# THANKS FOR PLAYING #");
System.out.println("######################");
String randomWords;
in = new Scanner(System.in);
System.out.println("Enter a name to be remembered by");
randomWords = in.next();
scores.add(randomWords + " " + enemyDeaths * 100);
System.out.println(scores);
System.out.println("\n");
System.out.println("\n");
{
System.out.println("Would you like to play again?");
String input = in.nextLine();
if(input.equals("yes")) {
continue Game;
}
}
}
}
To keep it simple, you could just change the exit criteria:
if (!input.equals("yes")) {
break; // end the loop
}
Just a hint: it is considered a good practice to compare a literal against some variable:
if (!"yes".equals(input)) {
break; // end the loop
}
Doing the check this way will not fail with NullPointerException in case input is null, it just returns false in this case.
it's easier if you set the opposite:
if(input.equals("no")) running = false;
That way the while loop gets out cleanly and you don't need to use a cumbersome label to control your flow.
From
Branching Statements
The continue statement skips the current iteration of a for, while , or do-while loop.
You want to jump to the label 'Game' from outside of the labelled while loop,
which is not allowed.