Java Vs小游戏

2022-09-27 19:43:22 浏览数 (2)

英雄类:

代码语言:javascript复制
import java.util.Random;
/**
 * 名字,技能,技能伤害,英雄初始化hp
 */
public class Hero {
    private String name;
    private String[] skill;
    private int[] hurt;
    private int Hp;
    public Hero(){ //空的构造器
        super();
    }
    public Hero(String name, String[] skill, int[] hurt, int hp) {
        super();
        this.name = name;
        this.skill = skill;
        this.hurt = hurt;
        Hp = hp;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String[] getSkill() {
        return skill;
    }
    public void setSkill(String[] skill) {
        this.skill = skill;
    }
    public int[] gethurt() {
        return hurt;
    }
    public void sethurt(int[] hurt) {
        this.hurt = hurt;
    }
    public int getHp() {
        return Hp;
    }
    public void setHp(int hp) {
        Hp = hp;
    }
    public void Skillhurt(Hero otherhero){ //攻击行为 otherhero谁调用谁就是otherhero
        // 创建Random获取随机数
        Random random = new Random();
        int i = random.nextInt(skill.length);
        String skill = this.skill[i]; // 通过随机数获取随机技能
        int n = otherhero.hurt[i]; //伤害
        otherhero.Hp = otherhero.Hp - n;
        System.out.println(this.name() "使用" skill "技能," "对" otherhero.getName() "造成了" n "伤害," otherhero.getName() "还剩" otherhero.getHp() "血量"); // this 猪八戒 otherhero
    }
    private String name() {
        return name;
    }
}

英雄游戏类:

代码语言:javascript复制
/**
 * 1.创建两个hero
 * 2.使用if语句判断第一个攻击者
 * 3.调用攻击方法
 * 4.判断血量,分出胜负
 */
import java.util.Random;
public class VsHero {
 public static void main(String[] args) {
            hero();
 }
 public static void hero(){
 String[] skill = {"肉弹蹦床", "倒打一耙", "圈养时刻", "九齿钉耙"};
 int[] hart = {20, 30, 40, 60};
 Hero zbj = new Hero("猪八戒", skill, hart, 500);
 String[] skill1 = {"护身咒法", "斗战冲锋", "大圣神威", "如意金箍"};
 int[] hart1 = {20, 30, 40, 60};
 Hero swk = new Hero("孙悟空", skill1, hart1, 500);
 System.out.println("------Welcome to this Game!------");
 Random rd = new Random();
 int a = rd.nextInt(2);
 System.out.println("VS开始");
 // [0 2)包括0,但不包括2  0 1
 if (a == 0) { // 猪八戒先攻击
 System.out.println("猪八戒开始攻击");
 while (true) {
 if (swk.getHp() <= 0) {
 System.out.println(swk.getName()   "血量小于0,"   zbj.getName()   "获胜");
 break;
 }
                zbj.Skillhurt(swk);
 if (zbj.getHp() <= 0) {
 System.out.println(zbj.getName()   "血量小于0,"   swk.getName()   "获胜");
 break;
 }
                swk.Skillhurt(zbj);
 }
 } else if (a == 1) {
 System.out.println("孙悟空开始攻击");
 while (true) {
 if (zbj.getHp() <= 0) {
 System.out.println(zbj.getName()   "血量小于0,"   swk.getName()   "获胜");
 break;
 }
                swk.Skillhurt(zbj);
 if (swk.getHp() <= 0) {
 System.out.println(swk.getName()   "血量小于0,"   zbj.getName()   "获胜");
 break;
 }
                zbj.Skillhurt(swk);
 }
 }
 }
}

  1. 效果图:

0 人点赞