The Coder's Handbook   

Game States

WHAT IS A GAME STATE?

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

Your Game States


Adding Game States


In the Main 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) 

{
  super(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

{

addState(title);

addState(game);

}


Adding the Title Class


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

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:


// 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

sbg.enterState(Engine.GAME_ID), 

}


RESOURCES

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