public class BattleGame {
public static void main(String[] args) {
// Create two objects
Fighter fighter1 = new Fighter("Dragon", 50, 200);
Fighter fighter2 = new Fighter("Knight", 40, 180);
// Use instance methods to attack and print status
fighter1.attack(fighter2);
fighter2.printStatus();
fighter2.attack(fighter1);
fighter1.printStatus();
// Use static methods to compare, print a fact, and start the battle
int stronger = Fighter.strongerFighter(fighter1, fighter2);
System.out.println("Stronger fighter: " + (stronger == 1 ? fighter1.getName() : fighter2.getName()));
Fighter.beginBattle(fighter1, fighter2);
}
}
class Fighter {
private String name;
private int power;
private int health;
// Static variable
private static double fightDuration = 0;
// Constructor
public Fighter(String name, int power, int health) {
this.name = name;
this.power = power;
this.health = health;
}
// Instance methods
public void attack(Fighter opponent) {
System.out.println(this.name + " attacks " + opponent.name + " with power " + this.power);
opponent.health -= this.power;
if (opponent.health < 0) {
opponent.health = 0;
}
}
public void printStatus() {
System.out.println(this.name + " - Health: " + this.health + ", Power: " + this.power);
}
public String getName() {
return name;
}
public int getHealth() {
return health;
}
// Static methods
public static int strongerFighter(Fighter f1, Fighter f2) {
return f1.power > f2.power ? 1 : 2;
}
public static void beginBattle(Fighter f1, Fighter f2) {
System.out.println("The battle begins between " + f1.name + " and " + f2.name + "!");
fightDuration = Math.random() * 10; // Simulate fight duration
System.out.println("The battle lasted " + fightDuration + " minutes.");
}
}
BattleGame.main(null);
Dragon attacks Knight with power 50
Knight - Health: 130, Power: 40
Knight attacks Dragon with power 40
Dragon - Health: 160, Power: 50
Stronger fighter: Dragon
The battle begins between Dragon and Knight!
The battle lasted 6.3373861310215815 minutes.