SlideShare a Scribd company logo
TASK #1
In the domain class you will create a loop that will prompt the user to enter a value of 1, 2, or 3,
which will in turn, be translated to a floor number in the game. Make sure the user only picks a
selection you are expecting (1, 2, or 3) with a while-loop. Then you will create a switch or if-else
statement. If you are more comfortable with if-else then do switch, or if you are more
comfortable with switch then do if-else. Based on the number the user chooses you will set the
floor variable to the appropriate value. When they select 1 floor should be set to 3, when they
select 2 floor should be set to 6, and when they select 3 floor should be set to 10.
TASK #2
In the domain class you will create a constructor with 6 parameters, representing all the data
loaded from the input file that was saved from a previous adventure. This constructor receives 6
parameters: aName, anAttack, aDefense, aHealth, aCurrentFloor, & aMaxFloor.
TASK #3
In the domain class you will create a save method that will allow the user to save their progress
using a PrintWriter object. This file will overwrite whatever was there before, so no need to use
FileWriter, only PrintWriter. There are 6 attributes that you need to write to the file:
name, attack, defense, health, currentFloor, & maxFloor
public void saveFile()
{
String filename = “game.txt”;
PrintWriter pw = new PrintWriter(filename);
pw.println(name);
pw.println(attack);
pw.println(defense);
pw.println(health);
pw.println(currentFloor);
pw.println(maxFloor);
pw.close();
}
TASK #4
In the driver class you will create a load method that will allow the user to pick up from where
they left off. You will do this using a File object and a Scanner object. Remember to use the File
and Scanner classes, and to close the file object after you’re done. There are 6 attributes you will
need to load from the file to successfully continue an Adventure:
name, attack, defense, health, currentFloor, & maxFloor
After you read the record from the file, and store the data in these 6 variables, you can create a
new Adventure object called JavaQuest with those 6 variables. Remember JavaQuest is a global
variable defined at the beginning of the driver class. Then, within the load method, invoke the
startAdventure() method for the newly created Adventure object.
public static void load()
{
String filename = “load.txt”;
File myFile = new File(filename);
Scanner myScan = new Scanner(myFile);
String name;
int attack, defense, health, currentFloor, maxFloor;
name = myScan.nextLine();
attack = myScan.nextInt();
myScan.nextLine();
defense = myScan.nextInt();
myScan.nextLine();
…
javaQuest = new Adventure(name, attack, defense, health, currentFloor, maxFloor);
}
javaQuest.startAdventure();
The Files
package Adventure;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Adventure
{
int health, defense, attack;
String monster, name;
int success;
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
int enemyHP;
int enemyAtk;
int enemyDef;
int currentFloor = 1;
int userChoice = 0;
int floor = 0;
public Adventure(int playerClass)
{
System.out.println(" What is your champion's name?");
name = keyboard.nextLine();
if(playerClass == 1) //warrior
{
this.health = 10;
this.defense = 8;
this.attack = 4;
}
else if(playerClass == 2) //ranger
{
this.health = 10;
this.defense = 4;
this.attack = 8;
}
else //wizard
{
this.health = 8;
this.defense = 4;
this.attack = 10;
}
//Task #1 Goes here:
//Loop to validate the selection (1,2,or 3). After loop, create an Adventure
//using one of the floor values that correspond to the user choice ( 1 = 3, 2 = 6, & 3 = 10).
//Use either switch or if-statements.
System.out.println("--------------------------------");
}
//Task #2 Goes here:
//Create a constructor that receives as parameters all the values of the Adventure object:
public void increaseHealth(int number)
{
if(health + number < 10)
{
health += number;
}
else if (health + number < 11)
{
health = 10;
}
else
{
System.out.println(" ---------------------"
+ "You are already at full HP! "
+ "---------------------");
}
}
public void setHealth(int health)
{
this.health = health;
}
public int getAttack()
{
return this.attack;
}
public int getHealth()
{
return this.health;
}
public int getDefense()
{
return this.defense;
}
public void setEnemyHP(int enemyHP)
{
this.enemyHP = enemyHP;
}
public String toString()
{
return "-------------------------------------------------- "
+ "Your current health is " + getHealth() + ".  You have " + getAttack() + " attack and " +
getDefense() + " defense. "
+ "You are currently on floor " + (currentFloor + 1) + " of " + floor +" "
+ "--------------------------------------------------";
}
public void startAdventure() throws IOException
{
int randNum = 0;
String strChoice="";
char chrChoice;
do
{
randNum = myRand.nextInt(5);
switch(randNum)
{
case 0:
System.out.println(" A slime draws near!");
monster = "Slime";
battle(monster);
break;
case 1:
System.out.println(" A skeleton draws near!");
monster = "Skeleton";
battle(monster);
break;
case 2:
System.out.println(" A dragon draws near!");
monster = "Dragon";
battle(monster);
break;
case 3:
System.out.println("You found a trap room! Choose your next step wisely! ");
trapRoom();
break;
case 4:
System.out.println("You found a health potion!");
if(this.health < 8)
{
increaseHealth(2);
System.out.println("You restore some health.");
}
else
{
System.out.println("Unfortunately you are already at full health! "
+ "The potion is to big to put in your pocket, so you just leave it for the next adventurer that
comes through.");
}
break;
}
currentFloor++;
if(health > 0)
{
System.out.println("You made it to a new floor, do you wish to continue? yes/no");
strChoice = keyboard.next();
strChoice = strChoice.toLowerCase();
chrChoice = strChoice.charAt(0);
if(chrChoice == 'n')
{
save();
break;
}
}
}
while(currentFloor < floor && health > 0);
if (health > 0)
{
System.out.println("You've survived the adventure! Congratulations!");
}
else
{
System.out.println("You made it to floor " + currentFloor + ". Better luck next time.");
}
}
public void battle(String enemy)
{
if (enemy.equals("Slime"))
{
enemyHP = 4;
enemyAtk = 5;
enemyDef = 1;
}
else if (enemy.equals("Skeleton"))
{
enemyHP = 6;
enemyAtk = 7;
enemyDef = 2;
}
else
{
enemyHP = 8;
enemyAtk = 9;
enemyDef = 3;
}
while (enemyHP > 0 && health > 0)
{
System.out.println("You are in battle! What is your action?");
System.out.println(" 1. Attack"
+ " 2. Defend"
+ " 3. Flee"
+ " 4. Switch Pokemon");
int battleChoice = keyboard.nextInt();
switch (battleChoice)
{
case 1:
dmgCalc(true);
if (enemyHP > 0)
{
dmgCalc(false);
}
break;
case 2:
System.out.println(" You defend and make a cautious attack!");
enemyHP -= 1;
System.out.println("1 damage!");
if (enemyHP > 0)
{
dmgCalc(false);
}
break;
case 3:
System.out.println(" You attempt to escape!");
int escapeCheck = myRand.nextInt(10);
if (escapeCheck > enemyHP)
{
System.out.println("Got away safely!");
enemyHP = 0;
}
else
{
dmgCalc(false);
}
break;
case 4:
System.out.println(" Professor Oak's words ring in your head..."
+ " "Now is not the time to use that!"");
}
System.out.println(toString());
if (enemyHP <= 0)
{
System.out.println("---> You are victorious! <--- ");
}
if (health <= 0)
{
System.out.println("You have been slain...");
}
}
}
public void dmgCalc(boolean userAttack)
{
String dmg="";
if(userAttack)
{
System.out.println("You attack!");
setEnemyHP(enemyHP - (attack - enemyDef));
System.out.println("The monster took " + (attack - enemyDef) + " damage!");
}
else
{
System.out.println("The monster attacks!");
if(enemyAtk - defense < 0)
{
setHealth(health - 1);
dmg = "1";
}
else
{
setHealth(health - (enemyAtk - defense));
dmg="" + (enemyAtk - defense);
}
System.out.println("You took " + dmg + " damage!");
}
}
public void trapRoom()
{
int trapChoice;
trapChoice = myRand.nextInt(3);
int userAns;
switch(trapChoice)
{
case 0:
System.out.println(" ---> The ceiling slowly starts to descend! <---");
success = myRand.nextInt(3) + 1;
System.out.println(" Quick! What do you do? 1. Run straight 2. Go left 3. Go right");
userAns = keyboard.nextInt();
if(success == userAns)
{
System.out.println("You found a way out!");
}
else
{
success = myRand.nextInt(2);
System.out.println("You don't see a way out!");
switch(success)
{
case 1:
if(currentFloor>1)
{
System.out.println("You managed to find a hole in the floor! You made it out alive! But you
went down a floor.");
currentFloor --;
}
else
System.out.println("Accepting your fate you punch the wall in rage, the old rocks crumble
away, enough so you can squeeze through."
+ " But....you broke your hand in the process.");
setHealth(health - 2);
break;
}
}
break;
case 1:
System.out.println("You walk into the room and see the way out! The only thing preventing
you from getting there is a spike pit about 10 feet across that spans the entire room.");
System.out.println(" Do you:  (1) Get a running start and jump accross? (2) Realize that you
are no athlete and turn around and try to find a different way up?");
userAns = keyboard.nextInt();
switch(userAns)
{
case 1:
success = myRand.nextInt(2);
if(success == 1)
{
System.out.println(" You made it!");
}
else
{
System.out.println(" You fall into the pit of spikes. Unfortunately there is no happy ending.");
setHealth(health - health);
}
break;
case 2:
System.out.println("You went back where you came from to try and find a different way up.");
currentFloor --;
break;
}
break;
case 2:
System.out.println("Oh look! You found a Dragon.");
battle("Dragon");
break;
}
}
public void save() throws IOException
{
//Task #3:
//Using PrintWriter, save the values in the Adventure object's 6 fields.
}
package Adventure;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class AdventureTester
{
static Adventure JavaQuest;
public static void main(String[] args) throws IOException
{
int userChoice = 0;
Scanner kb = new Scanner(System.in);
do
{
System.out.println("Welcome to JavaQuest!"
+ "Do you want to:"
+ " 1. Start New Adventure"
+ " 2. Load Previous Adventure");
userChoice = kb.nextInt();
}
while(userChoice < 1 || userChoice > 2);
if(userChoice == 1)
{
System.out.println("Select your class:"
+ " 1. Warrior"
+ " 2. Ranger"
+ " 3. Wizard");
userChoice = kb.nextInt();
if (userChoice < 1 || userChoice > 3)
{
System.out.println("You, uh, didn't pick a valid choice. Here, have a wizard.");
userChoice = 3;
}
JavaQuest = new Adventure(userChoice);
JavaQuest.startAdventure();
}
else
{
load();
}
}
public static void load() throws IOException
{
String name;
int attack, defense, health;
int currentFloor, maxFloor;
//Task #4 Goes here:
//Define a File and Scanner objects
//Read from the file into 6 local variables:
//Create a new Adventure object, and invoke the startAdventure() method
}
}
Solution
Adventure.java
AdventureTest.java // driver class to test the Adventure
Note- please create a file "load.text" to use the second option first time and please enter some
random value as you want.
Sample i/o -
Welcome to JavaQuest!Do you want to:
1. Start New Adventure
2. Load Previous Adventure
1
Select your class:
1. Warrior
2. Ranger
3. Wizard
3
What is your champion's name?
Alex
A dragon draws near!
You are in battle! What is your action?
1. Attack
2. Defend
3. Flee
4. Switch Pokemon
1
You attack!
The monster took 7 damage!
The monster attacks!
You took 5 damage!
--------------------------------------------------
Your current health is 3.
You have 10 attack and 4 defense.
You are currently on floor 2 of 10
--------------------------------------------------
You are in battle! What is your action?
1. Attack
2. Defend
3. Flee
4. Switch Pokemon
2
You defend and make a cautious attack!
1 damage!
--------------------------------------------------
Your current health is 3.
You have 10 attack and 4 defense.
You are currently on floor 2 of 10
--------------------------------------------------
---> You are victorious! <---
You made it to a new floor, do you wish to continue? yes/no
no
You've survived the adventure! Congratulations!

More Related Content

PDF
Implement threads and a GUI interface using advanced Java Swing clas.pdf
PDF
Integration Project Inspection 3
PDF
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
PDF
PSI 3 Integration
PDF
33rd Degree 2013, Bad Tests, Good Tests
PPT
2012 JDays Bad Tests Good Tests
DOCX
Import java
PDF
java programming language part-2 decision making .pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdf
Integration Project Inspection 3
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
PSI 3 Integration
33rd Degree 2013, Bad Tests, Good Tests
2012 JDays Bad Tests Good Tests
Import java
java programming language part-2 decision making .pdf

Similar to TASK #1In the domain class you will create a loop that will prompt.pdf (12)

PDF
Create a Flight class that uses the Plane and Time class. This class.pdf
PDF
Modified Code Game.java­import java.util.;public class Game.pdf
PPTX
Programming ppt files (final)
PDF
Review Questions for Exam 10182016 1. public class .pdf
PDF
You will write a multi-interface version of the well-known concentra.pdf
PPTX
Javascript 101
PPTX
JPC#8 Introduction to Java Programming
PDF
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
PDF
So I am writing a CS code for a project and I keep getting cannot .pdf
PDF
Simple 27 Java Program on basic java syntax
PDF
Please observe the the code and validations of user inputs.import .pdf
PPT
07-Basic-Input-Output.ppt
Create a Flight class that uses the Plane and Time class. This class.pdf
Modified Code Game.java­import java.util.;public class Game.pdf
Programming ppt files (final)
Review Questions for Exam 10182016 1. public class .pdf
You will write a multi-interface version of the well-known concentra.pdf
Javascript 101
JPC#8 Introduction to Java Programming
please send edited code of RCBug.javaRCBUG.javaimport java.util..pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
Simple 27 Java Program on basic java syntax
Please observe the the code and validations of user inputs.import .pdf
07-Basic-Input-Output.ppt
Ad

More from indiaartz (20)

PDF
Some Calvin Cycle enzymes contain disulfide bonds that must be reduc.pdf
PDF
Simplify and write the answer with positive exponents Simplify and w.pdf
PDF
Question 7 (of 20) 7. 1000 poants TB 1301 which of the following an.pdf
PDF
Problem 12-9ACondensed financial data of Waterway Industries follo.pdf
PDF
Please help me with these 3 questions! True or False. Assortment of .pdf
PDF
Performance BudgetingPerformance budgeting has been attempted at t.pdf
PDF
Many bridges are made from rebar-reinforced concrete composites. Cla.pdf
PDF
If the cystic fibrosis allele protects against tuberculosis the same .pdf
PDF
Match the graph of the sine function to the equation over [-4 Pi. 4 P.pdf
PDF
location in the stem, function, and Chemical Composition of their Wa.pdf
PDF
If Zn Binomial (n, ) , and n~possion(), find the distribution of Z .pdf
PDF
Given the global financial crisis of 2007–2009, do you anticipate an.pdf
PDF
Generativity versus stagnation        Early adult transitio.pdf
PDF
Genetics Question 2 In the insect sex determination system, th.pdf
PDF
Explain why malaria infection may lead to anemia. How would you clas.pdf
PDF
Figure 13.2 of a single pair of homologous chromosomes as they might.pdf
PDF
Every individual produced by sexual reproduction is unique. This is .pdf
PDF
Explain to them the probability of future offspring being normal or h.pdf
PDF
explain conceptual questionsvariabilitystandard devationz-sc.pdf
PDF
Explain the difference between fermentation and respiration in biolo.pdf
Some Calvin Cycle enzymes contain disulfide bonds that must be reduc.pdf
Simplify and write the answer with positive exponents Simplify and w.pdf
Question 7 (of 20) 7. 1000 poants TB 1301 which of the following an.pdf
Problem 12-9ACondensed financial data of Waterway Industries follo.pdf
Please help me with these 3 questions! True or False. Assortment of .pdf
Performance BudgetingPerformance budgeting has been attempted at t.pdf
Many bridges are made from rebar-reinforced concrete composites. Cla.pdf
If the cystic fibrosis allele protects against tuberculosis the same .pdf
Match the graph of the sine function to the equation over [-4 Pi. 4 P.pdf
location in the stem, function, and Chemical Composition of their Wa.pdf
If Zn Binomial (n, ) , and n~possion(), find the distribution of Z .pdf
Given the global financial crisis of 2007–2009, do you anticipate an.pdf
Generativity versus stagnation        Early adult transitio.pdf
Genetics Question 2 In the insect sex determination system, th.pdf
Explain why malaria infection may lead to anemia. How would you clas.pdf
Figure 13.2 of a single pair of homologous chromosomes as they might.pdf
Every individual produced by sexual reproduction is unique. This is .pdf
Explain to them the probability of future offspring being normal or h.pdf
explain conceptual questionsvariabilitystandard devationz-sc.pdf
Explain the difference between fermentation and respiration in biolo.pdf
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
RMMM.pdf make it easy to upload and study
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Lesson notes of climatology university.
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Types and Its function , kingdom of life
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Chinmaya Tiranga quiz Grand Finale.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
RMMM.pdf make it easy to upload and study
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Microbial disease of the cardiovascular and lymphatic systems
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Lesson notes of climatology university.

TASK #1In the domain class you will create a loop that will prompt.pdf

  • 1. TASK #1 In the domain class you will create a loop that will prompt the user to enter a value of 1, 2, or 3, which will in turn, be translated to a floor number in the game. Make sure the user only picks a selection you are expecting (1, 2, or 3) with a while-loop. Then you will create a switch or if-else statement. If you are more comfortable with if-else then do switch, or if you are more comfortable with switch then do if-else. Based on the number the user chooses you will set the floor variable to the appropriate value. When they select 1 floor should be set to 3, when they select 2 floor should be set to 6, and when they select 3 floor should be set to 10. TASK #2 In the domain class you will create a constructor with 6 parameters, representing all the data loaded from the input file that was saved from a previous adventure. This constructor receives 6 parameters: aName, anAttack, aDefense, aHealth, aCurrentFloor, & aMaxFloor. TASK #3 In the domain class you will create a save method that will allow the user to save their progress using a PrintWriter object. This file will overwrite whatever was there before, so no need to use FileWriter, only PrintWriter. There are 6 attributes that you need to write to the file: name, attack, defense, health, currentFloor, & maxFloor public void saveFile() { String filename = “game.txt”; PrintWriter pw = new PrintWriter(filename); pw.println(name); pw.println(attack); pw.println(defense); pw.println(health); pw.println(currentFloor); pw.println(maxFloor); pw.close(); } TASK #4 In the driver class you will create a load method that will allow the user to pick up from where they left off. You will do this using a File object and a Scanner object. Remember to use the File and Scanner classes, and to close the file object after you’re done. There are 6 attributes you will need to load from the file to successfully continue an Adventure: name, attack, defense, health, currentFloor, & maxFloor
  • 2. After you read the record from the file, and store the data in these 6 variables, you can create a new Adventure object called JavaQuest with those 6 variables. Remember JavaQuest is a global variable defined at the beginning of the driver class. Then, within the load method, invoke the startAdventure() method for the newly created Adventure object. public static void load() { String filename = “load.txt”; File myFile = new File(filename); Scanner myScan = new Scanner(myFile); String name; int attack, defense, health, currentFloor, maxFloor; name = myScan.nextLine(); attack = myScan.nextInt(); myScan.nextLine(); defense = myScan.nextInt(); myScan.nextLine(); … javaQuest = new Adventure(name, attack, defense, health, currentFloor, maxFloor); } javaQuest.startAdventure(); The Files package Adventure; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Adventure { int health, defense, attack; String monster, name; int success; Scanner keyboard = new Scanner(System.in); Random myRand = new Random();
  • 3. int enemyHP; int enemyAtk; int enemyDef; int currentFloor = 1; int userChoice = 0; int floor = 0; public Adventure(int playerClass) { System.out.println(" What is your champion's name?"); name = keyboard.nextLine(); if(playerClass == 1) //warrior { this.health = 10; this.defense = 8; this.attack = 4; } else if(playerClass == 2) //ranger { this.health = 10; this.defense = 4; this.attack = 8; } else //wizard { this.health = 8; this.defense = 4; this.attack = 10; } //Task #1 Goes here: //Loop to validate the selection (1,2,or 3). After loop, create an Adventure //using one of the floor values that correspond to the user choice ( 1 = 3, 2 = 6, & 3 = 10). //Use either switch or if-statements.
  • 4. System.out.println("--------------------------------"); } //Task #2 Goes here: //Create a constructor that receives as parameters all the values of the Adventure object: public void increaseHealth(int number) { if(health + number < 10) { health += number; } else if (health + number < 11) { health = 10; } else { System.out.println(" ---------------------" + "You are already at full HP! " + "---------------------"); } } public void setHealth(int health) { this.health = health; } public int getAttack() { return this.attack; }
  • 5. public int getHealth() { return this.health; } public int getDefense() { return this.defense; } public void setEnemyHP(int enemyHP) { this.enemyHP = enemyHP; } public String toString() { return "-------------------------------------------------- " + "Your current health is " + getHealth() + ". You have " + getAttack() + " attack and " + getDefense() + " defense. " + "You are currently on floor " + (currentFloor + 1) + " of " + floor +" " + "--------------------------------------------------"; } public void startAdventure() throws IOException { int randNum = 0; String strChoice=""; char chrChoice; do { randNum = myRand.nextInt(5); switch(randNum) {
  • 6. case 0: System.out.println(" A slime draws near!"); monster = "Slime"; battle(monster); break; case 1: System.out.println(" A skeleton draws near!"); monster = "Skeleton"; battle(monster); break; case 2: System.out.println(" A dragon draws near!"); monster = "Dragon"; battle(monster); break; case 3: System.out.println("You found a trap room! Choose your next step wisely! "); trapRoom(); break; case 4: System.out.println("You found a health potion!"); if(this.health < 8) { increaseHealth(2); System.out.println("You restore some health."); } else { System.out.println("Unfortunately you are already at full health! " + "The potion is to big to put in your pocket, so you just leave it for the next adventurer that comes through."); } break; }
  • 7. currentFloor++; if(health > 0) { System.out.println("You made it to a new floor, do you wish to continue? yes/no"); strChoice = keyboard.next(); strChoice = strChoice.toLowerCase(); chrChoice = strChoice.charAt(0); if(chrChoice == 'n') { save(); break; } } } while(currentFloor < floor && health > 0); if (health > 0) { System.out.println("You've survived the adventure! Congratulations!"); } else { System.out.println("You made it to floor " + currentFloor + ". Better luck next time."); } } public void battle(String enemy) { if (enemy.equals("Slime")) { enemyHP = 4; enemyAtk = 5; enemyDef = 1;
  • 8. } else if (enemy.equals("Skeleton")) { enemyHP = 6; enemyAtk = 7; enemyDef = 2; } else { enemyHP = 8; enemyAtk = 9; enemyDef = 3; } while (enemyHP > 0 && health > 0) { System.out.println("You are in battle! What is your action?"); System.out.println(" 1. Attack" + " 2. Defend" + " 3. Flee" + " 4. Switch Pokemon"); int battleChoice = keyboard.nextInt(); switch (battleChoice) { case 1: dmgCalc(true); if (enemyHP > 0) { dmgCalc(false); } break; case 2: System.out.println(" You defend and make a cautious attack!"); enemyHP -= 1; System.out.println("1 damage!");
  • 9. if (enemyHP > 0) { dmgCalc(false); } break; case 3: System.out.println(" You attempt to escape!"); int escapeCheck = myRand.nextInt(10); if (escapeCheck > enemyHP) { System.out.println("Got away safely!"); enemyHP = 0; } else { dmgCalc(false); } break; case 4: System.out.println(" Professor Oak's words ring in your head..." + " "Now is not the time to use that!""); } System.out.println(toString()); if (enemyHP <= 0) { System.out.println("---> You are victorious! <--- "); } if (health <= 0) { System.out.println("You have been slain..."); } } } public void dmgCalc(boolean userAttack)
  • 10. { String dmg=""; if(userAttack) { System.out.println("You attack!"); setEnemyHP(enemyHP - (attack - enemyDef)); System.out.println("The monster took " + (attack - enemyDef) + " damage!"); } else { System.out.println("The monster attacks!"); if(enemyAtk - defense < 0) { setHealth(health - 1); dmg = "1"; } else { setHealth(health - (enemyAtk - defense)); dmg="" + (enemyAtk - defense); } System.out.println("You took " + dmg + " damage!"); } } public void trapRoom() { int trapChoice; trapChoice = myRand.nextInt(3); int userAns; switch(trapChoice) { case 0: System.out.println(" ---> The ceiling slowly starts to descend! <---"); success = myRand.nextInt(3) + 1;
  • 11. System.out.println(" Quick! What do you do? 1. Run straight 2. Go left 3. Go right"); userAns = keyboard.nextInt(); if(success == userAns) { System.out.println("You found a way out!"); } else { success = myRand.nextInt(2); System.out.println("You don't see a way out!"); switch(success) { case 1: if(currentFloor>1) { System.out.println("You managed to find a hole in the floor! You made it out alive! But you went down a floor."); currentFloor --; } else System.out.println("Accepting your fate you punch the wall in rage, the old rocks crumble away, enough so you can squeeze through." + " But....you broke your hand in the process."); setHealth(health - 2); break; } } break; case 1: System.out.println("You walk into the room and see the way out! The only thing preventing you from getting there is a spike pit about 10 feet across that spans the entire room."); System.out.println(" Do you: (1) Get a running start and jump accross? (2) Realize that you are no athlete and turn around and try to find a different way up?"); userAns = keyboard.nextInt(); switch(userAns) {
  • 12. case 1: success = myRand.nextInt(2); if(success == 1) { System.out.println(" You made it!"); } else { System.out.println(" You fall into the pit of spikes. Unfortunately there is no happy ending."); setHealth(health - health); } break; case 2: System.out.println("You went back where you came from to try and find a different way up."); currentFloor --; break; } break; case 2: System.out.println("Oh look! You found a Dragon."); battle("Dragon"); break; } } public void save() throws IOException { //Task #3: //Using PrintWriter, save the values in the Adventure object's 6 fields. } package Adventure; import java.io.File; import java.io.IOException; import java.util.Scanner;
  • 13. public class AdventureTester { static Adventure JavaQuest; public static void main(String[] args) throws IOException { int userChoice = 0; Scanner kb = new Scanner(System.in); do { System.out.println("Welcome to JavaQuest!" + "Do you want to:" + " 1. Start New Adventure" + " 2. Load Previous Adventure"); userChoice = kb.nextInt(); } while(userChoice < 1 || userChoice > 2); if(userChoice == 1) { System.out.println("Select your class:" + " 1. Warrior" + " 2. Ranger" + " 3. Wizard"); userChoice = kb.nextInt(); if (userChoice < 1 || userChoice > 3) { System.out.println("You, uh, didn't pick a valid choice. Here, have a wizard."); userChoice = 3; } JavaQuest = new Adventure(userChoice); JavaQuest.startAdventure(); } else { load(); }
  • 14. } public static void load() throws IOException { String name; int attack, defense, health; int currentFloor, maxFloor; //Task #4 Goes here: //Define a File and Scanner objects //Read from the file into 6 local variables: //Create a new Adventure object, and invoke the startAdventure() method } } Solution Adventure.java AdventureTest.java // driver class to test the Adventure Note- please create a file "load.text" to use the second option first time and please enter some random value as you want. Sample i/o - Welcome to JavaQuest!Do you want to: 1. Start New Adventure 2. Load Previous Adventure 1 Select your class: 1. Warrior 2. Ranger 3. Wizard 3 What is your champion's name?
  • 15. Alex A dragon draws near! You are in battle! What is your action? 1. Attack 2. Defend 3. Flee 4. Switch Pokemon 1 You attack! The monster took 7 damage! The monster attacks! You took 5 damage! -------------------------------------------------- Your current health is 3. You have 10 attack and 4 defense. You are currently on floor 2 of 10 -------------------------------------------------- You are in battle! What is your action? 1. Attack 2. Defend 3. Flee 4. Switch Pokemon 2 You defend and make a cautious attack! 1 damage! -------------------------------------------------- Your current health is 3. You have 10 attack and 4 defense. You are currently on floor 2 of 10 -------------------------------------------------- ---> You are victorious! <--- You made it to a new floor, do you wish to continue? yes/no no You've survived the adventure! Congratulations!