Game State: titles, restarting

Screen Shot 2014-10-23 at 8.47.26 AM
You typically don’t want your game to start immediately, you may want a title screen and various states before or after the proper game.

An easy way to implement these features is to use a string to keep track of the game state, e.g gameState:

String gameState = "intro";
 
...
 
void draw() {
 
 //is the state "intro"
  if(gameState == "intro")
  {
  //just draw the image and wait for input, see keyrelease function below
  image(title, 0, 0);
  }
  //update the simulation only if the state is "game"
  if(gameState == "game")
  {
  world.step();
 ...

Restart a game

There’s no straightforward way to reset a game to the initial state (variables, positions…) but there are some best practices I recommend:

1. In the setup function put all the operations that should be done only once forever: size, loading assets (loadImage, sounds, fonts). You can’t call this function again after the launch.

2. Create a game initialization function e.g. newGame() that contains all the operations setting up the game like creating a new Fisica world, creating the initial bodies, setting the score to 0 etc…

void newGame()
{
  score = 0;
  gameState = "game";
  //create a new Fisica world
  world = new FWorld();
...

3. Call the function when you reach a game over state (better if you wait for an input)

...in the draw function
if (gameState == "gameOver")
  {
    println("GAME OVER STATE");
    //press space to restart
    if (keyIsDown(' ')) {
    newGame();
    }
  }

Full example here: example11c – titles

Posted in

Post a comment