1.先创建一个奥特曼类
//设置奥特曼类
public class AutoMan {
//设置属性
private int blood;
private String name;
//构造方法,通过构造方法设置初始化值
public AutoMan(int blood, String name) {
this.blood = blood;
this.name = name;
}
//设置get/set
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//攻击小怪兽方法,无返回值方法
public void attack(Monster monster) {
//随机数来随机攻击血量0~10
int number = (int)(Math.random()*11);
//攻击怪兽丢失血量
monster.setBlood(monster.getBlood() - number);
System.out.println("小怪兽受伤了,失去了" + number + "点血,还剩" + monster.getBlood());
}
}
2.创建一个怪兽类
//设置怪兽类
public class Monster {
//设置属性
private int blood;
private String name;
//设置构造函数
public Monster(int blood, String name) {
this.blood = blood;
this.name = name;
}
//设置get/set
public int getBlood() {
return blood;
}
public void setBlood(int blood) {
this.blood = blood;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//攻击奥特曼方法,无返回值方法
public void attack(AutoMan automan) {
//随机数Math.random,随机数来随机攻击血量0~10
int number = (int)(Math.random()*11);
//攻击奥特曼丢失血量
automan.setBlood(automan.getBlood() - number);
System.out.println("奥特曼受伤了,失去了" + number + "点血,还剩" + automan.getBlood());
}
}
创建一个PK方法
public class PK {
//设置静态PK方法,通过输入对象进行PK
public static void PK1V1(AutoMan automan,Monster monster) {
//执行1V1,通过do while循环来pk
do {
//设置随机数来判断攻击方
int random = (int)(Math.random()*11);
//调用奥特曼攻击方法和怪兽攻击方法
if(random>5) {
automan.attack(monster);
}else {
monster.attack(automan);
}
//当双方都有血量的时候执行循环
}while(automan.getBlood()>0 && monster.getBlood()>0);
//其中一方没有血量了游戏结束,输出结果
if(automan.getBlood()<=0) {
System.out.println(automan.getName() + "死了" + monster.getName() + "赢了");
}else {
System.out.println(monster.getName() + "死了" + automan.getName() + "赢了");
}
}
}
通过main方法调用PK方法
public class Attack {
//main方法
public static void main(String[] args) {
//new两个对象,初始化双方属性
AutoMan automan = new AutoMan(200,"迪迦奥特曼");
Monster monster = new Monster(200,"哥尔赞");
//调用PK方法判断胜负
PK.PK1V1(automan, monster);
}
}