The Coder's Handbook

Game States


For more detailed information, look at the GameState, BasicGameState and StateBaseGame classes in the Slick 2D Javadoc

Your Game States

  • Your game will often want to change into different modes that have different behaviors

  • For example:

    • Your Title state might display a name and ask the user to press "space" to start.

    • Your Gameplay state might render the action and has the user move around and shoot stuff.

    • Your Pause gameplay might display everything, but no objects actually move.

Adding Game States

In the Engine class...

// These integer constants store the codes for each state.

public static final int TITLE_ID = 0;

public static final int GAME_ID = 1;

// We declare a BasicGameState for each state

private BasicGameState title;

private BasicGameState game;

// In our constructor we initialize the game states with a code.

public Engine(String name)


title = new Title(TITLE_ID);

game = new Game(GAME ID);


// Add states to our list. The first state we add is the starting state.

void initStatesList(GameContainer gc) throws SlickException





Adding the Title Class

If you're working with the Template... your program will probably have an error at this point.

  • It knows about the main gameplay state, but it doesn't know about title.

  • You'll need to add a "Title" game state to your project

  • To do so, click in the package explorer. Copy and Paste "" and name it ""

Label the Game States

Your project is a lot easier to read if we make both Game and Title have code displaying their states in render.

Here's the example code for Title. You'll want to do the same for Game.

public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException

// It makes it easier to tell what state we're in if we label it!

// This code draws the word "Title" near the top left corner of the screen.

g.drawString("TITLE", 50, 50);


Changing Game States

To change a Game State, we'll need to:

  • Have a reference to the Engine object. We'll call this sbg.

  • Switch states on a key press event

// Add a new instance field named sbg. This is a reference to the main Engine.
StateBasedGame sbg;

public void init(GameContainer gc, StateBasedGame sbg) throws SlickException

// Update our reference to the game Engine

this.sbg = sbg;


public void keyPressed(int key, char c)


// If the user presses ANY key, we switch to the Gameplay state




The New Boston - Defining Game States

The New Boston - Adding Game States To Container

The New Boston - Main Method

The New Boston - Implementing Each Game State

The New Boston - How To Change States