好的,我来为您完成这个任务。
首先,我会创建一个名为Fighter的JavaBean类,并在其中定义角色的属性:姓名、血量和性别。代码实现如下:public class Fighter {
private String name;
private int hp;
private String gender;
public Fighter() {}
public Fighter(String name, int hp, String gender) {
this.name = name;
this.hp = hp;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
然后,我会创建一个测试类FightGame,包括了随机伤害的实现。具体代码如下:import java.util.Random;
public class FightGame {
public static void main(String[] args) {
Fighter fighter1 = new Fighter("张三", 100, "男");
Fighter fighter2 = new Fighter("李四", 100, "女");
Random random = new Random();
while (fighter1.getHp() > 0 && fighter2.getHp() > 0) {
int damage = random.nextInt(20) + 10; // 产生10~30的随机伤害
if (random.nextBoolean()) {
fighter2.setHp(fighter2.getHp() - damage);
System.out.println(fighter1.getName() + "打了" + fighter2.getName() + "一下,造成了" + damage + "点伤害," + fighter2.getName() + "还剩" + fighter2.getHp() + "点血量");
} else {
fighter1.setHp(fighter1.getHp() - damage);
System.out.println(fighter2.getName() + "打了" + fighter1.getName() + "一下,造成了" + damage + "点伤害," + fighter1.getName() + "还剩" + fighter1.getHp() + "点血量");
}
}
if (fighter1.getHp() <= 0) {
System.out.println(fighter2.getName() + " KO了" + fighter1.getName());
} else {
System.out.println(fighter1.getName() + " KO了" + fighter2.getName());
}
}
}
以上就是我的代码实现,您可以在此基础上进行测试和修改。 |