(a) FileIO
In the FileIO class add a public static method named writeCharacter. This method takes as input a Character to write, and a String which is the filename to write to. Within this writeCharacter method, use the FileWriter and BufferedWriter objects to write the character’s information back to a file. Make sure to catch the IOException when writing a file, and throw an IllegalArgumentException with an appropriate error message. If you prefer, you can also use the throws statement to throw the IOException up to the calling playGame method. Then this Exceptions would be caught in a try/catch block there. The format of the file that is written must match the format that is expected when a character is read. That is, you should be able to write a character to a file, and then read a character from that same file. Recall that the format of a character in a file is each value on a separate line: • Name of the character • Attack value • Maximum health • Number of wins so far in the battle game Note that this means you will have to write getter methods for the attributes in the Character class.
(b) BattleGame
In the playGame method, after you have increased the wins for either the monster or the player, print how many wins each character has. As well, you must write the characters to the files you loaded them from. For example, write the player character to player.txt or the monster character to monster.txt. Call the writeCharacter method in the FileIO class, and pass the character who won and the file which stores that character as parameters. This will save the number of wins for that character, so that after playing the battle game multiple times, you will know which character has won more often. Here is some sample output for the finished program. Again, your output doesn’t need to exactly match, as long as the same information is presented. Name: Odin Health: 30.00 Attack: 10.00 Number of Wins: 8 Name: Fenrir Health: 30.00 Attack: 12.00 Number of Wins: 12 Spells: Name: fireball Damage: 5.0-10.0 Chance: 50.0% Name: icestorm Damage: 1.0-7.0 Chance: 90.0% Name: meteorstrike Damage: 10.0-10.0 Chance: 5.0% Enter a command: fireball Odin tried to cast fireball, but they failed Fenrir attacks for 9.84 damage! Page 8 Odin takes 9.84 damage! Name: Odin Health: 20.16 Enter a command: ICESTORM Odin casted icestorm for damage of 6.50 Fenrir takes 6.50 damage! Name: Fenrir Health: 23.50 Fenrir attacks for 10.18 damage! Odin takes 10.18 damage! Name: Odin Health: 9.98 Enter a command: badbreath Odin tried to cast badbreath, but they don’t know that spell Fenrir attacks for 10.09 damage! Odin takes 10.09 damage! Odin was knocked out! Name: Odin Health: 0.00 Oh no! You lost! Fenrir has won: 13 times
Program Screenshot:
Sample Output:
Input files;
dictionary.txt
A
a
AA
AAA
Aachen
aah
Aaliyah
Aaliyah's
aardvark
aardvark's
aardvarks
Aaron
AA's
AB
ab
ABA
abaci
aback
abacus
abacuses
abacus's
abaft
abalone
abalone's
abalones
abandon
abandoned
abandoning
abandonment
abandonment's
abandons
abase
abased
abasement
abasement's
abases
abash
abashed
abashedly
abashes
abashing
abashment
abashment's
abasing
abate
abated
abatement
abatement's
abates
abating
abattoir
abattoir's
abattoirs
abbé
Abbas
Abbasid
abbe
abbe's
abbes
abbess
abbesses
abbess's
abbey
abbey's
abbeys
abbot
abbot's
abbots
Abbott
Abbott's
abbr
abbrev
abbreviate
abbreviated
abbreviates
abbreviating
abbreviation
abbreviation's
abbreviations
abbrevs
abbe's
abbes
Abby
Abby's
ABC
ABC's
ABCs
abdicate
abdicated
abdicates
abdicating
abdication
abdication's
abdications
abdomen
abdomen's
abdomens
abdominal
abduct
abducted
abducting
abduction
abduction's
abductions
abductor
abductor's
abductors
abducts
Abdul
Abdul's
Abe
abeam
abed
Abel
Abelard
Abel's
Abelson
Abelson's
Aberdeen
Aberdeen's
Abernathy
Abernathy's
aberrant
aberration
aberrational
aberration's
aberrations
Abe's
abet
abets
abetted
abetter
abetter's
abetters
abetting
abettor
abettor's
abettors
abeyance
abeyance's
abhor
abhorred
abhorrence
abhorrence's
abhorrent
abhorrently
abhorring
abhors
abidance
abidance's
abide
abided
abides
abiding
abidingly
Abidjan
Abidjan's
Abigail
Abilene
abilities
ability
ability's
abject
abjection
abjection's
abjectly
abjectness
abjectness's
abjuration
abjuration's
abjurations
abjuratory
abjure
abjured
abjurer
abjurer's
abjurers
abjures
abjuring
ablate
ablated
ablates
ablating
ablation
ablation's
ablations
ablative
ablative's
ablatives
ablaze
able
abler
ablest
abloom
ablution
ablution's
ablutions
ably
ABM
ABM's
ABMs
abnegate
abnegated
abnegates
abnegating
abnegation
abnegation's
Abner
Abner's
abnormal
abnormalities
abnormality
abnormality's
abnormally
aboard
abode
abode's
abodes
abolish
abolished
abolishes
abolishing
abolition
abolitionism
abolitionism's
abolitionist
abolitionist's
abolitionists
abolition's
abominable
abominably
abominate
abominated
abominates
abominating
abomination
abomination's
abominations
aboriginal
aboriginal's
aboriginals
Aborigine
aborigine
Aborigine's
Aborigines
aborigine's
aborigines
aborning
abort
aborted
monster.txt
Fenrir
12.0
30.0
3
player.txt
Odin
10.0
30.0
0
spells.txt
fireball 5 10 0.5
icestorm 1 7 0.9
meteorstrike 10 10 0.05
----------------------
Code to copy:
//BattleGame.java
//import the packages
import java.util.*;
//implementation of the class BattleGame
public class BattleGame
{
//Definition of the playGame method
@SuppressWarnings("resource")
private static void playGame(String file1, String
file2)
{
ArrayList<Spell> lsObj =
FileIO.readSpells("spells.txt");
System.out.println(":: Players ::
");
Character m =
FileIO.readCharacter(file1);
Character n =
FileIO.readCharacter(file2);
System.out.println(FileIO.readCharacter(file1));
System.out.println(FileIO.readCharacter(file2));
m.setSpells(lsObj);
System.out.println(":: Spells ::
");
int i = 0;
while ( i < lsObj.size() )
{
System.out.print(lsObj.get(i));
i++;
}
//use a while loop, to read a
command from the user
while (m.getCurrentHealth() > 0
&& n.getCurrentHealth() > 0)
{
Scanner in = new
Scanner(System.in);
//Prompt and
read a command from the user
System.out.println("Enter a command :");
System.out.println("(Attack-Quit-Name of Spell) ");
String s =
in.nextLine();
//check the
command is equal to the attack
if
(s.equalsIgnoreCase("attack"))
{
doAttack(m, n);
doAttack(n, m);
}
//check the
command is equal to the quit
else if
(s.equalsIgnoreCase("quit"))
{
System.out.println(" Goodbye! ");
return;
}
//check the
command is equal to the attack or quit
else if
(!s.equalsIgnoreCase("attack") || s.equalsIgnoreCase("quit"))
{
double x = m.castSpell(s);
System.out.println(n.getName() + " takes " + x +
" damage!");
n.takeDamage(x);
System.out.println(n.getName() + "'s current
health : " + n.getCurrentHealth());
System.out.println();
}
}
if (m.getCurrentHealth() <=
0)
{
System.out.println("You lost!");
n.increaseWins();
System.out.println(n.getName() + "'s number of wins : " +
n.getnoOfwins());
FileIO.writeCharacter(n, "monster.txt");
} else if (n.getCurrentHealth()
<= 0)
{
System.out.println("You won!");
m.increaseWins();
System.out.println(m.getName() + "'s number of wins : " +
m.getnoOfwins());
FileIO.writeCharacter(m, "player.txt");
}
}
//Definition of the doAttack
private static void doAttack(Character one, Character
two)
{
double attackValue =
one.calcAttack();
System.out.println(one.getName()
+ " attacks for " + attackValue + " damage!");
two.takeDamage(attackValue);
if (two.getCurrentHealth() >
0)
{
System.out.println(two.getName() + " takes " + attackValue + "
damage! ");
System.out.println(" Name : " + two.getName());
System.out.println(" [Health: " + two.getCurrentHealth() + "]
");
}
else
{
//display the
result
System.out.println(two.getName() + " takes " + attackValue + "
damage! ");
System.out.println(" Name : " + two.getName());
System.out.println(" [Health: " + two.getCurrentHealth() + "]
");
System.out.println(two.getName() + " is knocked out.");
}
}
//main method
public static void main(String[] args)
{
playGame("player.txt",
"monster.txt");
}
}
-------------
//Character.java
//import the packages
import java.util.*;
//implementation of the class Character
public class Character
{
//declare the private variables
private String name;
private double attack;
private double maximumHealth;
private double currentHealth;
private int noOfwins;
private static ArrayList<Spell> spells;
// The constructor
public Character(String name, double attack, double
maximumHealth, int noOfwins)
{
this.name = name;
this.attack = attack;
this.maximumHealth =
maximumHealth;
this.currentHealth =
maximumHealth;
this.noOfwins =
noOfwins;
}
//Definition of the calcAttack function
public double calcAttack()
{
Random x = new Random();
double c = 0,a,b,z,attackValue =
0;
a = 0.3;
b = 0.7;
z = b - a;
c = x.nextDouble();
attackValue = a + (c * (z));
attackValue = attack *
attackValue;
return attackValue;
}
//Definition of the takeDamage
public void takeDamage(double attack)
{
this.currentHealth =
this.currentHealth - attack;
}
//Definition of the increaseWins
public void increaseWins()
{
this.noOfwins += 1;
}
//Definition of the setSpells
public void setSpells(ArrayList<Spell>
spells)
{
this.spells = spells;
}
//Definition of the castSpell
public double castSpell(String spellName)
{
double damage = 0;
boolean checker = true;
for(int i = 0; i <
this.spells.size(); i++)
{
System.out.println();
if(this.spells.get(i).getName().equalsIgnoreCase(spellName))
{
damage = this.spells.get(i).getDamage();
if(damage > 0){
System.out.println(name + "
casted " + spellName + " for damage of " + damage);
checker = true;
break;
} else {
System.out.println(name + "
tried to cast " + spellName + ", but they failed.");
checker = true;
break;
}
} else{
checker = false;
}
} if (!checker)
{
System.out.println(name + " tried to cast " + spellName
+ ", but they don't know that
spell.");
}
return damage;
}
//Definition of the toString
public String toString()
{
return "Name of the player : " +
name + " " + " [Health : "
+ currentHealth + "] [Attack Value : " + attack + "]
[Number of Wins : " + noOfwins +"] ";
}
// The getters
public Double getCurrentHealth()
{
return this.currentHealth;
}
public Double getmaximumHealth()
{
return this.maximumHealth;
}
public int getnoOfwins()
{
return this.noOfwins;
}
public Double getAttack()
{
return this.attack;
}
public String getName()
{
return this.name;
}
}
------------------
//FileIO.java
//import the packages
import java.io.*;
import java.util.*;
//Implementation of the class FileIO
public class FileIO
{
//definition of the method readCharacter
public static Character readCharacter(String sf)
{
try
{
//Create a file
object
FileReader f1 =
new FileReader(sf);
BufferedReader
br = new BufferedReader(f1);
String name =
br.readLine();
double attack =
Double.parseDouble(br.readLine());
double
maximumHealth = Double.parseDouble(br.readLine());
int noOfWins =
Integer.parseInt(br.readLine());
br.close();
f1.close();
Character
newUser = new Character(name, attack, maximumHealth,
noOfWins);
return
newUser;
}
catch (FileNotFoundException
e)
{
throw new
IllegalArgumentException("File not find :" + sf);
}
catch (IOException e)
{
throw new
IllegalArgumentException("Error in the file :" + sf);
}
}
//Definition of the readSpells
public static ArrayList<Spell> readSpells(String
sf){
ArrayList<Spell> spellInfo =
new ArrayList<Spell>();
try{
FileReader f12 =
new FileReader(sf);
BufferedReader
br2 = new BufferedReader(f12);
String
currentLine = br2.readLine();
while(currentLine != null){
String[] items = currentLine.split("
");
String name = items[0];
double minimumDamage =
Double.parseDouble(items[1]);
double maximumDamage =
Double.parseDouble(items[2]);
double chanceOfSuccess =
Double.parseDouble(items[3]);
Spell f = new Spell(name, minimumDamage,
maximumDamage, chanceOfSuccess);
spellInfo.add(f);
currentLine = br2.readLine();
}
br2.close();
f12.close();
return
spellInfo;
} catch (FileNotFoundException
e){
throw new
IllegalArgumentException("File not find :" + sf);
} catch (IOException e){
throw new
IllegalArgumentException("Error in the file :" + sf);
}
}
//Definition of the writeCharacter
public static void writeCharacter (Character who,
String sf){
try{
FileWriter f2 =
new FileWriter(sf);
BufferedWriter
b2 = new BufferedWriter(f2);
b2.write(who.getName() + " ");
b2.write(who.getAttack() + " ");
b2.write(who.getmaximumHealth() + " ");
b2.write(who.getnoOfwins() + " ");
b2.close();
f2.close();
}
catch (IOException e)
{
throw new
IllegalArgumentException("Error in the file :" + sf);
}
}
}
-------------
//Spell.java
//import the packages
import java.util.*;
//Implementation of the spell class
public class Spell
{
//declare the private variables
private double minumDamage;
private double maxumDamage;
private double chanceOfSuccess;
private String name;
// constructor
public Spell(String name, double minumDamage, double
maxumDamage, double chanceOfSuccess)
{
if (minumDamage < 0 ||
minumDamage > maxumDamage || chanceOfSuccess < 0 ||
chanceOfSuccess > 1)
{
throw new
IllegalArgumentException("Wrong input");
}
this.name = name;
this.minumDamage =
minumDamage;
this.maxumDamage =
maxumDamage;
this.chanceOfSuccess =
chanceOfSuccess;
}
// Getters
public String getName()
{
return this.name;
}
public double getDamage()
{
double random = 0,x,y,z;
Random r1 = new Random();
x = 0;
y = 1;
z = y - x;
double s = 0;
random = r1.nextDouble();
s = x + (random * (z));
if(s > chanceOfSuccess)
{
return 0;
}
else
{
return s;
}
}
// toString method
public String toString()
{
return "Name of the spell : " +
name + " " + " [minum Damage : "
+ minumDamage + "] [maxum Damage : "
+ maxumDamage +
"] [Success of chanceOfSuccess : "
+ chanceOfSuccess*100 +"%] ";
}
}
(a) FileIO In the FileIO class add a public static method named writeCharacter. This method takes...
HIGHEST SUBMISSION Vlew All Submissions Submission 17 Submitted on 6/10/2019 12 35 PM by Jenna Saleh DESCRIPTION Objectives To write a classes based on sets of specifications To write a main class to be used in a multi-class Java program To use inheritance to extend a class (optional, EC) To override methods in subclasses (optional, EC) Groups You may work with a partner on this assignment. A header comment (In every Java file) should include authors (group members) and collaborators...
Problem 5: Monster Factory (10 points) (Game Dev) Create a Monster class that maintains a count of all monsters instantiated and includes a static method that generates a new random monster object. In software engineering, a method that generates new instances of classes based on configuration information is called the Factory pattern. UML Class Diagram: Monster - name: String - health: int - strength: int - xp: int + spawn(type:String): Monster + constructor (name: String, health: int, strength: int, xp:...
Summary task: C++ language; practice combining tools(functions, arrays, different kind of loops) to solve somewhat complex problem. Description A Valiant Hero is about to go on a quest to defeat a Vile Monster. However, the Hero is also quite clever and wants to be prepared for the battle ahead. For this question, you will write a program that will simulate the results of the upcoming battle so as to help the hero make the proper preparations. Part 1 First, you...
*q3: Write a public static method named q3 that takes no parameters and has return type void. In this method, you may assume there is a file named "properties.csv" with lines in the format "name, opposed, pure,glad" where "name" is a String and all other values are well-formed integers. There is no header line in this file. This method will create a new * file named "output.csv" in the format "name, pure" containing only these two columns from "properties.csv" and...
Base Class enum HeroType {WARRIOR, ELF, WIZARD}; const double MAX_HEALTH = 100.0; class Character { protected: HeroType type; string name; double health; double attackStrength; public: Character(HeroType type, const string &name, double health, double attackStrength); HeroType getType() const; const string & getName() const; /* Returns the whole number of the health value (static_cast to int). */ int getHealth() const; void setHealth(double h); /* Returns true if getHealth() returns an integer greater than 0, otherwise false */ bool isAlive() const; virtual void...
in JAVA Write a new class, Game, that have a main method and instantiates and uses the above class. Create (at least) one Hero, one Monster, and one Potion(that you equip the hero with). Use repetition to have the monster attack the hero multiple time! Have the hero try to drink a potion whenever their health gets low(say below 10). Finally -- have there be an end-game condition. Maybe the game ends when the hero's health is equal to 0....
This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static void main(String args[]) throws IOException { Scanner inFile = new Scanner(new File(args[0])); Scanner keyboard = new Scanner(System.in); TwoDArray array = new TwoDArray(inFile); inFile.close(); int numRows = array.getNumRows(); int numCols = array.getNumCols(); int choice; do { System.out.println(); System.out.println("\t1. Find the number of rows in the 2D array"); System.out.println("\t2. Find the number of columns in the 2D array"); System.out.println("\t3. Find the sum of elements...
Question 1. (Magician.java, Healer.java, Fighter.java, HeroTester.java) Consider the abstract hero class and the three subclasses shown below. Review the hero class to see how it works (it’s in the project/package for you already). Your job is to implement the following subclasses. Each of the subclasses has an extra data field that relates to their specific hero talent. Some help with these special talents and other methods are below. Fighter: ‐The fighter has an extra data field called Strength and a...
Question 1[JAVA] Add a method in the Main class named getLines() that takes a filename as a String and returns each line in the file in an array. Have each element of the array be a String. Do not include the newline at the end of each line. Use a BufferedReader object to read the file contents. Note, the contents of input.txt will be different (including the number of lines) for each test case. Example: getLines( "input.txt" ) returns (an...
C++ Trek Wars Project: 100% code coverage unit testing is required for this project. once a ship has reached 0 health it is considered blown up -throw an exception if the move method is called on it. -repair ships cannot repair ships at 0 health There will be no chaotic corvette ships Trek Wars Purpose: classes, inheritance, class diagrams, virtual, testing Description Universal Merriment Development (UMD) is creating an online space battle game called (Trek Wars) You are tasked with...