Chapter 5. Handling Game States

When we first start up a game, we expect to see a splash screen showing any branding for publishers and developers, followed by a loading screen as the game does its initial setup. After this, we are usually faced with a menu screen; here, we can change settings and start the game. Starting the game leads us to another loading screen, possibly followed by a cut scene, and finally, we are in the game. When we are in the game, we can pause our play (allowing us to change any settings), exit the game, restart the level, and so on. If we fail the level, we are shown either an animation or a game over screen depending on how the game is set up. All of these different sections of a game are called Game States. It is very important that we make the transition between these states as easy as possible.

In this chapter we will cover:

  • Two different ways of handling states, starting with a really simple implementation and gradually building our framework implementation
  • Implementing Finite State Machines (FSM)
  • Adding states to the overall framework

A simple way for switching states

One of the simplest ways to handle states is to load everything we want at the game's initialization stage, but only draw and update the objects specific to each state. Let's look at an example of how this could work. First, we can define a set of states we are going to use:

enum game_states
{
  MENU = 0,
  PLAY = 1,
  GAMEOVER = 2
};

We can then use the Game::init function to create the objects:

// create menu objects
m_pMenuObj1 = new MenuObject();
m_pMenuObj1 = new MenuObject();

// create play objects
m_pPlayer = new Player();
m_pEnemy = new Enemy();

// create game over objects…

Then, set our initial state:

m_currentGameState = MENU;

Next, we can change our update function to only use the things we want when in a specific state:

void Game::update()
{
  switch(m_currentGameState)
  {
    case MENU:
      m_menuObj1->update();
      m_menuObj2->update();
      break;

    case PLAY:
      m_pPlayer->update();
      m_pEnemy->update();

    case GAMEOVER:
      // do game over stuff…
  }
}

The render function would do something similar. These functions could of course still loop through arrays and use polymorphism as we originally had done, but on a state-by-state basis. Changing states is as simple as changing the value of the m_currentGameState variable.

If you can see issues with this method, then it is very encouraging that you are starting to think in an object-oriented way. This way of updating states would be a bit of a nightmare to maintain and the scope for error is quite large. There are too many areas that need to be updated and changed to make this a viable solution for any game larger than a simple arcade game.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.241.250