I have two different classes: TextBasedGame and IntroductionChoices.
IntroductionChoices makes all the decisions while TextBasedGame basically just prints the story (it's the one with the main method).
What I want to know is how to make the game END if the user makes a wrong choice.
In this case, if the user types in "Take down the group.", a message is displayed and the game ends. In my case, in the main method, it just keeps on going. How do I stop the game from running?
I was thinking I could somehow, in the main method, check if return from IntroductionChoicesis "GAME OVER" and end the game there.
//Snippet from the main method
System.out.println("What do you do?");
System.out.println(choice.choice1());
System.out.println("Next part...");
//Method choice1 from IntroductionChoices
public static String choice1()
{
Scanner scan = new Scanner(System.in);
System.out.println("Warn her of her shadows.");
System.out.println("Take down the group.");
String decision = scan.next();
if (decision.equalsIgnoreCase("right decision"))
{
System.out.println("some text");
return "some more text in continuation to continue story in main";
}
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
return "GAME OVER";
}
else
{
return "That is not a valid response.";
}
}
System.exit(0)
else if (decision.equalsIgnoreCase("wrong decision"))
{
System.out.println("You creep towards the men, hoping to surprise them from behind.");
System.out.println("Consequence");
System.exit(0);
You won't need to return anything, it will end the program.
OR
Give the user an option:
Start new game-> start a new game
Quit -> System.exit(0)
I'd also use a switch to check through the user options, you're less liekly to make mistakes and it can be neater and quicker when the options start accumulating.
You can create an enum of options or use final ints with meaningful names so your code is easier to navigate and then match with user options.
From java the docs.
Related
I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat
I'm really scratching my heard on this one. I'm new at java, and I'm having the strangest thing happen.
It's homework and I'm taking it one step at a time. My issue is the loop just keeps going and stops asking for input, just keeps looping until it terminates. My comments are largely for myself. I tried to extract what was causing my problem and post it here.
Look at the "hatColor" switch, you'll notice the way I'm making sure the user enter only from the options I have allotted. Should I be using a exception handler or something?
Anyway, in short, the problem is that if I enter something with spaces, the loop skips asking for my next input. Like, if I entered "y y y y y " to the scanner when first prompted, the program will terminate and not give me the chance to enter something else.
Please, anyone that understands this, I would really appreciate your help.
import java.util.Scanner;
public class Testing
{
static String hatColor;
public static void main(String[] args) {
gameStart();
}
public static void gameStart()
{
Scanner userInput = new Scanner(System.in);
boolean keepLooping = true;
int loopCounter = 0;
System.out.println("The game begins. You must choose between 3 different colored hats."
+ " You can type white, black, or gray.");
while (keepLooping == true)
{
hatColor = userInput.next();
switch(hatColor)
{
case "white":
System.out.println("You have chosen the path of well intentioned decisions.");
walletDrop();
//the two items below are only there in case the wallet drop somehow completes without calling another method
keepLooping = false; // stops the while loop from looping again.
break; // breaks out of the switch
case "gray":
System.out.println("You have chosen the path of free will.");
walletDrop();
keepLooping = false;
break;
case "black" :
System.out.println("You have chosen the path of personal gain.");
walletDrop();
keepLooping = false;
break;
default : //we could just copy this default chunk for later switch statements
if (loopCounter >= 3)//end program on them
{
System.exit(0);
}
System.out.println("You didn't enter a usable answer. Try again");
loopCounter++;
if (loopCounter == 3)
{
System.out.println("This program will self destruct if you enter another invalid response.");
}
}//end of switch
}//end of while
}//end of game start method
public static void walletDrop()
{
System.out.println("wallet drop successful");
}
}
So I have actually solved this right after posting. In case someone else needs to look here for help:
The issue I was experiencing was due to using the scanner method
variableToAssign = scannerName.next();
instead of
variableToAssign = scannerName.nextLine();
I am currently working on a project and I have been asked to create a puzzle type game based on a 2d array. I have created the methods which all work fine, but I dont quite know how to make it so that the user can call upon the methods via user input whilst the program is running.
I'd prefer not to upload my code as this is quite a big class and I don't want other class members to find this and copy my code.
Thanks :-)
Try a simple menu loop like this:
// scanner created outside the loop because it will be used every iteration
Scanner s = new Scanner(System.in);
while(true) {
System.out.print("Please choose an option: ");
// read some input and trim the trailing/ leading whitespaace
String input = s.nextLine().trim();
// check to see which move was called
if (input.equals("foo")) {
foo();
}
else if (input.equals("bar")) {
bar();
}
// break out of the menu loop
else if (input.equals("exit")) {
break;
}
// if none of the above options were called
// inform user of invalid input
else {
System.out.println("Invalid input");
}
}
// exit program
System.out.println("Goodbye!");
Just add in options as you need them
You can use GUI or console to give your command to your apllication for execution those methods.
offtop
this is quite a big class
I think you should divide one big class to some smaller classes(less them 100 lines).
The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.
I'm sorry the code is so long, I just need to know what I'm missing to initialize all my decisions. The compiler is complaining about my variable not being initialized. Thank you.
import javax.swing.JOptionPane;
public class SemesterProject
{
public static void main(String[] args)
{
String SemesterProject =
"Hello and welcome to Juans adventure story! Your choices throughout this story will bring your doom or your salvation!\n"+
"No one has been able to complete this story and lived to tell the tale, but maybe you will be the first one!.\n"+
"Our story begins in the small town of Badow. Many people in the town spread rumors of brave adventurers that\n"+
"go on the quest to solve the mysterious riddles of the abandond castle at the top of the hill.\n"+
"No one really knows who or what lies at the heart of the castle. Legend says that monsters guards the\n"+
"the many riches once owned by the family that died there, so many years ago.\n"+
"The Castle is full of dizzing turns and hidden corridors and dangerous monsters. Many adventureres \n"+
"have gone insane because of how they lose their way or go get stuck. It is the hardes quest known to man.\n"+
"The quest for you is to go to the castle, solve the riddles and claim the riches.\n"+
"The world will little note, nor long remember what we say here, but it can never forget what they did here.\n"+
"Be careful. Watch your back and always mark your trail because you never know what you will find next.\n"+
"If for some crazy reason you end up successful in this task, you will not only get the riches in the castle but\n"+
"you will also be crowned the king of the town of Badow. If you die, you lose.\n"+
"The last thing you have to do is input some of your personal information so that we keep you in our records.\n";
JOptionPane.showMessageDialog(null,SemesterProject);
String name = JOptionPane.showInputDialog(null,"Please give us your first name.");
String age = JOptionPane.showInputDialog(null,"Please give us your age.");
String weight = JOptionPane.showInputDialog(null,"Please give us your weight.");
String haircolor = JOptionPane.showInputDialog(null,"Please give us your hair color.");
String GPA = JOptionPane.showInputDialog(null,"Please give us your GPA.");
String favoritecolor = JOptionPane.showInputDialog(null,"Please give us your favorite color.");
String decision1,decision2,decision3,decision4,decision5,decision6;
decision1 = JOptionPane.showInputDialog("Brave adventurer, welcome to the entrance of the abandoned castle of town Badow. At this moment\n"+
"You have a choice right now to give up and take a walk of shame back to the village, and to safety\n"+
"Or you can decide to go in and test your unique set of skills on the various challenges of the adventure\n"+
"ahead of you. Enter the number of your choice.You can either 1. Enter the castle 2. Stay behind.");
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
if (decision3.equals("1"))
{
decision4 = JOptionPane.showInputDialog
("You are back in the hall slowly hearing the echoing sound of your footsteps\n"+
"you head downstairs into what seems to be another hallway but this one full of barred rooms, kind of like a dungeon. There is\n"+
"a skeleton body on the ground which seems to be of another failure by an adventurer in the castle. You reach the end of the hall\n"+
"and there is two ways to go left or right. 1. Left 2. Right.");
}
else
{
JOptionPane.showMessageDialog(null,"You squeeze through the trapdoor and fall down to the ground where you find youself lost and disoriented\n"+
"You dont know where you are and start to panic, you start becoming insane and die.");
}
if (decision4.equals("1"))
{
decision5 = JOptionPane.showInputDialog
("You go left and hear a door open behind you, you panic and start to run\n"+
"you run intro different halls to try and escape but you trip. You just remembered that you have a sword with you and can now\n"+
"choose what to do 1. Take out sword and fight enemy 2. Get up and keep running.");
}
else
{
JOptionPane.showInputDialog(null,"You go right and get locked in behind you. You realize that there isnt anwhere to go\n"+
"and get lost in the darkest part of the castle and die alone.");
}
if (decision5.equals("1"))
{
decision6 = JOptionPane.showInputDialog
("You were able to fight of the armored enemy. But something tells you that that isnt the last of them. You continue on down the\n"+"hall and see from the distance to what seems to be your first prize. It cant be that easy.");
}
}
}
Define the decision variables as null. Instead of:
String decision1,decision2,decision3,decision4,decision5,decision6;
Define the variables as:
String decision1 = null;
String decision2 = null;
String decision3 = null;
String decision4 = null;
String decision5 = null;
String decision6 = null;
decision2 is only being set if decision1 is equal to 1. I think you want to put the if statements for the other decisions inside of each other like below:
if (decision1.equals("1"))
{
decision2 = JOptionPane.showInputDialog
("You find yourself at the entrance of the castle with a choice to go down a dark hall\n"+
"or to the closest room on the right side. Be vary wary the darkness can make you lose your mind and go insane and remember\n"+
"to keep track of were you are. 1. Into the room 2. Down the hall.");
if (decision2.equals("1"))
{
decision3 = JOptionPane.showInputDialog
("You step into the room and find some medication and a lantern with some oil.\n"+
"you also find a sword. You can choose now to go back to the dark hallway or to go down a hidden trap door in the room. It could be\n"+
"a shortcut or it could lead somewhere dangerous. 1. Back down the hall 2. Take your chances with the trapdoor.");
}
else
{
JOptionPane.showMessageDialog(null,"you should have looked in the room, you quickly lose your way and the darkness\n"+
"makes you crazy.");
}
}
else
{
JOptionPane.showMessageDialog(null,"You go back to your boring life in the town, you wont be remembered by anything and you\n"+
"lost your chance at getting the riches that lie deep in the castle. You lose.");
}
You must initialize your String variables (decision1, decision2,...) as:
String decision1 = null, decision2 = null, decision3 = null, decision4 = null, decision5 = null, decision6 = null;
Note that you don't get a compile error for decision1 because in the line
decision1 = JOptionPane.showInputDialog(...);
it is being initialized.
Also, your program's logic is bad. If decision1 is not 1, then you will just show a message, but the program will continue to check the next condition:
if (decision2.equals("1"))
where you will get a NullPointerException because you are comparing null with 1.
JOptionPane variable might not have been initialized
So keep in mind one thing that whenever you get such kind of error messages try to see that your variables are properly declared.
See when you try to use int variable it can give you error message if that variable is used in some computation. So try to initialize the variables like:
int a=0;
You can do the same thing with string variables also like:
String a=null;
Returning to answer
In your code you have just declared the variables , but the fact is that you have to actually initialize them.
Replace
String decision1,decision2,decision3,decision4,decision5,decision6;
By
String decision1=null,decision2=null,decision3=null,decision4=null,decision5=null,decision6=null;