Java中交互攻击精简版代码(使用继承来简化)
作者:互联网
先上效果(同时添加构造方法)
先创一个名为first的英雄大类
package demo1212;
public class first {
//属性
private String name;
private int blood;
private int attack;
public first() {
}
public first(String name, int blood, int attack) {
this.blood = blood;
this.attack=attack;
this.name=name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setBlood(int blood) {
this.blood = blood;
}
public int getBlood() {
return blood;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getAttack() {
return attack;
}
}
然后创建名为HY的类来继承first父类的性质
package demo1212;
public class HY extends first{
public HY() {
}
public HY(String name, int blood, int attack) {
super(name, blood, attack);
}
}
创建名为YS的类来继承first父类的性质
package demo1212;
public class YS extends first {
public YS() {
}
public YS(String name, int blood, int attack) {
super(name, blood, attack);
}
}
测试类别
package demo1212;
import java.util.Random;
import java.util.Scanner;
public class project {
public static void main(String[] args) {
//输入语句,选择英雄
Scanner jh=new Scanner(System.in);
System.out.println("请选择英雄A:");
String mingzi= jh.nextLine();
Scanner ljh=new Scanner(System.in);
System.out.println("请选择英雄B:");
String mingzi1= ljh.nextLine();
HY houyi=new HY();
houyi.setName(mingzi);
houyi.setBlood(100);
YS ys=new YS();
ys.setName(mingzi1);
ys.setBlood(100);
while(ys.getBlood()>=0&&houyi.getBlood()>=0) {
Random ran=new Random();
int attack= ran.nextInt(10);
houyi.setAttack(attack);
Random ran1=new Random();
int attack1= ran1.nextInt(10);
ys.setAttack(attack1);
ys.setBlood(ys.getBlood()- houyi.getAttack());
houyi.setBlood(houyi.getBlood()-ys.getAttack());
System.out.println( houyi.getName() +"正在攻击" + ys.getName()+ "导致其血量减少" +houyi.getAttack()+ ys.getName()+","+ys.getName()+"现在的血量是" + ys.getBlood());
System.out.println( ys.getName() +"正在攻击" + houyi.getName()+ "导致其血量减少" + ys.getAttack()+houyi.getName()+","+houyi.getName()+"现在的血量是" + houyi.getBlood());
}
if( houyi.getBlood()>ys.getBlood()){
System.out.println(houyi.getName()+"赢了");
}else {
System.out.println(ys.getName()+"赢了");
}
}
}
标签:Java,精简版,int,attack,blood,houyi,ys,交互,public 来源: https://blog.csdn.net/weixin_64625868/article/details/122015624