黑马 ---- 文字版格斗游戏
//测试类
public class gameTest {
public static void main(String[] args) {
//1.创建第一个角色
Role r1 = new Role("周健",100);
//2.创建第二个角色
Role r2 = new Role("翁雁姿",100);
//3.开始格斗,回合制游戏
while(true){
//r1开始攻击r2
r1.attack(r2);
//判断r2的剩余血量
if(r2.getHP() == 0){
System.out.println(r1.getName() + "K.O." + r2.getName());
break;
}
//r2开始攻击r1
r2.attack(r1);
//判断r1的剩余血量
if(r1.getHP() == 0){
System.out.println(r2.getName() + "K.O." + r1.getName());
break;
}
}
}
}
//游戏角色
public class Role {
private String name;
private int HP;
//空参
public Role() {
}
//带全部参
public Role(String name, int HP) {
this.name = name;
this.HP = HP;
}
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 void attack(Role role){
//计算伤害 1-20
Random r = new Random();
int hurt = r.nextInt(20) + 1;
//计算剩余血量
int fiHP = role.getHP() - hurt;
//对剩余血量做一个验证,如果为负数了,就修改为0
fiHP = fiHP < 0 ? 0 : fiHP;
//修改挨揍的人的血量
role.setHP(fiHP);
System.out.println(this.getName() + "打了" + role.getName() +
"一下,造成了" + hurt + "点伤害" + role.getName() + "还剩下" +
fiHP + "点血量");
}
}