This site requires JavaScript, please enable it in your browser!
Greenfoot back
moekler wrote ...


Ending a Game

moekler moekler


I'm trying to find the simplest way to end a game with the following conditions: the game should end when no enemies are left in the world; there is not a preset number of enemies (you can add as many as you like, so no counters); there must have been at least one enemy for the game to end. Thanks for any help.
JL235 JL235


You can achieve that by using some boolean flags, and getting the number of actors in the world. For example...
public class Game  extends World
    private boolean isGameOver;
    private boolean isGameRunning;
     * Constructor for objects of class Game.
    public Game()
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1);
        isGameOver = false;
        isGameRunning = false;
    public void act()
        if ( ! isGameOver ) {
            int numEnemies = getObjects( Enemy.class ).size();
            if ( !isGameRunning && numEnemies > 0 ) {
                isGameRunning = true;
            } else if ( isGameRunning && numEnemies == 0 ) {
                isGameOver = true;
    public void onEndGame()
        System.out.println( "game has ended" );
The first boolean flag 'isGameOver' is to ensure the whole process is only ever run once. The second boolean flag 'isGameRunning' is to tell if the game is in the pre-running state (when there are no enemies) or if there are enemies in the game. You can get all enemies using 'getObjects' which returns an collection containing them all. Retrieving it's size allows you to see how many enemies there are.
You need to login to post a reply.