public class BattleGame {
// Define the object class
static class Fighter {
// Instance variables — unique for each object
String name;
int power;
int health;
// Static variable — shared by all fighters
static double fightDuration = 0.0;
// Constructor
public Fighter(String name, int power, int health) {
this.name = name;
this.power = power;
this.health = health;
}
// Instance method: attack another fighter
public void attack(Fighter opponent) {
System.out.println(name + " attacks " + opponent.name + " with power " + power + "!");
opponent.health -= power; // reduce opponent’s health
if (opponent.health < 0) opponent.health = 0;
fightDuration += 1.5; // each attack adds time
}
// Instance method: print current status
public void printStatus() {
System.out.println(name + " → Health: " + health + " | Power: " + power);
}
// Static method: determine stronger fighter (by power)
public static int strongerFighter(Fighter f1, Fighter f2) {
if (f1.power > f2.power) {
return 1; // f1 stronger
} else if (f1.power < f2.power) {
return 2; // f2 stronger
} else {
return 0; // tie
}
}
// Static method: begin the battle
public static void beginBattle(Fighter f1, Fighter f2) {
System.out.println("\n The battle begins between " + f1.name + " and " + f2.name + "! ⚔️");
fightDuration = 0.0;
}
}
public static void main(String[] args) {
Fighter robot = new Fighter("RoboX", 25, 100);
Fighter dino = new Fighter("T-Rex", 20, 120);
Fighter.beginBattle(robot, dino);
robot.attack(dino);
dino.attack(robot);
robot.attack(dino);
System.out.println();
robot.printStatus();
dino.printStatus();
int result = Fighter.strongerFighter(robot, dino);
if (result == 1) {
System.out.println("\n " + robot.name + " is the stronger fighter!");
} else if (result == 2) {
System.out.println("\n " + dino.name + " is the stronger fighter!");
} else {
System.out.println("\n Both fighters are equally strong!");
}
System.out.println("\n Total fight duration: " + Fighter.fightDuration + " seconds.");
}
}
The battle begins between RoboX and T-Rex!
RoboX attacks T-Rex with power 25!
T-Rex attacks RoboX with power 20!
RoboX attacks T-Rex with power 25!
RoboX → Health: 80 | Power: 25
T-Rex → Health: 70 | Power: 20
RoboX is the stronger fighter!
Total fight duration: 4.5 seconds.