首页 > 解决方案 > 当所有敌人在电子游戏中死亡时如何改变关卡?

问题描述

我正在实现一个 2d 视频游戏。当你杀死一个级别的所有敌人时,你应该进入下一个级别,但我不知道如何实现它。您对我可以使用的可能设计模式有什么建议吗?

public class GameWorld {
    int aliveEnemies = 3;

    void setAliveEnemies() {
        //omitted by OP
    }

    int getAliveEnemies() {
        if (aliveEnemies == 0) {
            goToNextLevel();
        }
    }
}



public class Level {
    void spawnEntities(){
        // omitted by OP
    }
}

标签: java

解决方案


我想你Gameworld有一个Level属性。当你进入下一个关卡时,你应该调用关卡的 spawnEntity。

public class GameWorld {
    Level currentLevel = null; //Level attribute
    int aliveEnemies = 0;

    //Gameworld constructor
    GameWorld(Level lev) {
        this.currentLevel = lev;
    }

    void setAliveEnemies() {
        this.aliveEnemies = this.currentLevel.spawnEntities(); //Load next enemies
    }

    int getAliveEnemies() {
        if (aliveEnemies == 0) {
            goToNextLevel();
        }
    }

    //goToNextLevel implementation
    private void goToNextLevel() {
        this.level = new Level(); //Load new Level
        this.setAliveEnemies(); // Load enemies of that level
    }
}



public class Level {
    int spawnEntities()  //should return number of enemis spawned
        // omitted by OP
        return 3;
    }
}

推荐阅读