在 RPG 游戏中使用对象数组

时间:2021-04-20 11:29:25

标签: java

我正在尝试制作一个简单的 RPG 游戏,其中 Allplayers 类作为超类,firstEnemy、secondEnemy 和thirdEnemy 作为子类。我在主类中创建了一个对象数组,但我必须为每个敌人制定一个“战斗”方法,而不仅仅是一个通用方法。我哪里出错了?

public class Main {
private static EnemyLevelOne firstEnemy;
private static EnemyLevelTwo secondEnemy;
private static EnemyLevelThree thirdEnemy;
private static List<AllPlayers> enemies = new ArrayList<>();

public static void main(String[] args) {
firstEnemy = new EnemyLevelOne();
secondEnemy = new EnemyLevelTwo();
thirdEnemy = new EnemyLevelThree();

public static void addToEnemies() {
        AllPlayers[] enemies = {firstEnemy, secondEnemy, thirdEnemy};
        System.out.println("Enemies that awaits for you are ");
        for (AllPlayers i : enemies) {
            System.out.println(i.name);
        }
    }

当然,代码被缩短了。当我必须与敌人作战时,我必须先调用 FightFirstEnemy,然后再调用 FightSecondEnemy,依此类推。这是它的样子:

  public static void fightTheFirstEnemy() {
        System.out.println("Your level: " + gamer.getLevel());
        System.out.println("Your health: " + gamer.getHealth());
        System.out.println(" ");
        if (firstEnemy.name.equals("Rocksteady")) {
            System.out.println("Rocksteady says: Are you ready to Rock steady?");
        }
        System.out.println("Enemy level: " + enemies.get(0).getLevel());
        System.out.println("Enemy health: " + enemies.get(0).getHealth());
        System.out.println(" ");
        while ((player.getHealth() > 0) || (enemies.get(0).getHealth() > 0)) {
            attackTheEnemy();
            enemyHitsBack();
        }
    }

我在输入 enemies.get(0).getLevel()); 时遇到错误,但如果我输入 firstEnemy.getLevel());,则没有错误。 我想有一种方法可以为所有敌人制作单一的 fight() 方法,但我不知道如何实现。

0 个答案:

没有答案