Calling Class Methods Homework
Homework: Ultimate Battle
Scenario
You are programming a game where 2 objects of your choosing (e.g., Robots, Dinosaurs, People) battle. Each object has health and power.
Instructions
-
Create a class representing your object with:
Instance variables:
String nameint powerint healthMAKE YOUR OWN
Static variables:
double fightDuration
Instance methods:
void attack()void printStatus()MAKE YOUR OWN
Class methods:
static int strongerFighter()static void beginBattle()MAKE YOUR OWN
-
In
main:- Create two objects.
- Use instance methods to attack and print status.
- Use static methods to compare, print a fact, and start the battle.
// Code Here
class Robot {
String name;
int power;
int health;
String weapon;
public Robot(String name, int power, int health, String weapon) {
this.name = name;
this.power = power;
this.health = health;
this.weapon = weapon;
}
static double fightDuration = 0.0;
public void attack(Robot enemy) {
System.out.println(name + " attacks " + enemy.name + " with " + weapon);
enemy.health -= power;
if (enemy.health < 0) {
enemy.health = 0;
}
}
public void printStatus() {
System.out.println(name + " has: " + health + " health, " + power + " power, and " + weapon);
}
public void heal() {
System.out.println(name + " heals for 10");
health += 10;
}
public static Robot strongerFighter(Robot r1, Robot r2) {
if (r1.power > r2.power) {
return r1;
} else {
return r2;
}
}
public static void beginBattle(Robot r1, Robot r2) {
System.out.println(r1.name + " fights " + r2.name);
double fightDuration = 0.0;
while (r1.health > 0 && r2.health > 0) {
r1.attack(r2);
if (r2.health <= 0) break;
r2.attack(r1);
fightDuration += 5;
}
System.out.println("The battle has ended");
if (r1.health > 0) {
System.out.println(r1.name + " won");
} else {
System.out.println(r2.name + " won");
}
}
public static void printFact(Robot r1, Robot r2) {
int combinedPower = r1.power + r2.power;
int combinedHealth = r1.health + r2.health;
System.out.println("Fact: Combined power = " + combinedPower + ", combined health = " + combinedHealth);
}
}
public class Main {
public static void main(String[] args) {
Robot alpha = new Robot("Alpha", 20, 100, "Laser");
Robot beta = new Robot("Beta", 15, 100, "Missile");
alpha.printStatus();
beta.printStatus();
Robot stronger = Robot.strongerFighter(alpha, beta);
System.out.println("Stronger fighter: " + stronger.name);
Robot.printFact(alpha, beta);
Robot.beginBattle(alpha, beta);
}
}
Main.main(new String[]{});
Alpha has: 100 health, 20 power, and Laser
Beta has: 100 health, 15 power, and Missile
Stronger fighter: Alpha
Fact: Combined power = 35, combined health = 200
Alpha fights Beta
Alpha attacks Beta with Laser
Beta attacks Alpha with Missile
Alpha attacks Beta with Laser
Beta attacks Alpha with Missile
Alpha attacks Beta with Laser
Beta attacks Alpha with Missile
Alpha attacks Beta with Laser
Beta attacks Alpha with Missile
Alpha attacks Beta with Laser
The battle has ended
Alpha won