How to implement gamestates

Started by
8 comments, last by SiCrane 11 years, 1 month ago

I'm making a pong game with c++ that currently has two states, GameState and MenuState. The way it is now, both states are methods of the Game class. The Game class has all the instance data that both methods/states use (so paddles, ball, menu buttons, etc). Is it bad practice to make a gamestate a method rather than its own class?

This is how my main function is right now


#include "Game.h"

int main( int argc, char* args[] )
{
	Game game;

	game.Run();

    return 0;
}

And the Run function


int Game::Run()
{
	if (error)
	{
		return 1;
	}

    //The frame rate regulator, passed to GameState
    Basic_SDL::Timer fps;

	//Which player scored (left or right), passed to GameState
	int scoreKeeper = 0;

	rightPaddle.setAI(true);
	
	//While the suer hasn't quit
	while (quit == false)
	{
		if (!paused)
		{
			GameState(fps, scoreKeeper);
		}
		else
		{
			MenuState();
		}
	}
	
    //Clean up
    clean_up();
}

It works fine this way, I'm just not sure if making each state a method is looked down upon. Any other advice on how to implement game states would be appreciated also smile.png.

Advertisement

Its simple create an enum, I used the c++11 style here. Then do a switch over the possible enums that repesent state. Inside each case begin the code that handles that state, a simple example is below. Consider creating a function/method for entering and exiting a state, this can handle code that needs to be run when a state starts or ends.

One other possibility is using a class and inheritance/polymorphism to create State class that does something similar, to this, but using inheritance and polymorphism to handle your state. Doing it that way would give you the ctor and dtor to handle entering and exiting state as well as the object's fields to hold related data.

If you have a simpler game use the enum system, if its more complex consider using a polymorphic state class.


enum class GameStates
{
State_None = 0,
State_Menu,
State_Playing,
State_Loading,
State_Paused,
};
 
class Game
{
public:
GameState mState;
};
 
// inside your Game class's Run function ( or inside the GameState() ) do this 
switch (mState)
{
case GameState::Menu
    {
    UpdateMenuState();
    DrawMenuState();
    break;
    }
 
case GameState::Playing:
    {
    UpdatePlayingState();
    DrawPlayingState();
    break;
    }
case GameState::Paused:
    {
    // don't update playing state
    DrawPlayingState();
    break;
    }
default:
    {
    // error
    break;
    }
 
}
 

If this post or signature was helpful and/or constructive please give rep.

// C++ Video tutorials

http://www.youtube.com/watch?v=Wo60USYV9Ik

// Easy to learn 2D Game Library c++

SFML2.2 Download http://www.sfml-dev.org/download.php

SFML2.2 Tutorials http://www.sfml-dev.org/tutorials/2.2/

// Excellent 2d physics library Box2D

http://box2d.org/about/

// SFML 2 book

http://www.amazon.com/gp/product/1849696845/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1849696845&linkCode=as2&tag=gamer2creator-20

I like to actually have a base class called State and derive from that to push and pop different states, but that might be a bit much for a pong game. For pong I'd just go with the enums above haha.

I have a StateManager that you can push and pop states to/fro, and the Game class just calls the update function for the current state in its own main loop. A small game engine I wrote demonstrates it: https://github.com/DrSuperSocks/Fission

Hope that helps!

Current Project

World Storm

out our Android app! (My roommate and I)

https://play.google.com/store/apps/details?id=com.drsupersocks.ninja

Is it bad practice to make a gamestate a method rather than its own class?

For games with only a handful of states and simple transitions between states, it isn't bad practice at all.

When you start developing more advanced games with a large number of states, state machines within states, and complex interactions between states, it becomes more important to develop a more advance state machine framework.

Have you looked at Lazy Foo's article on State Machines? It's uses enums and a case/switch function, and is relatively simple to understand.

Basically, you have a base GameState class that is abstract. It has three virtual functions - handleInput(), logic(), and draw().

Then, your other states - in this case, the Menu and the actual Pong state - will inherit from this base class. They'll inherit the three vital functions, and then you can put what you want in each respective state (e.g; a c_Player in the Pong state, or a c_Button in the Menu state).

The states are switched first by preparing the change with a set_next_state() function, then calling change_state() to actually change states.

I'd recommend going through the article, it really simplifies the whole state machine topic (at least it did for me tongue.png)

http://lazyfoo.net/articles/article06/index.php

You can even apply the same guidelines for an AI state machine too, which is pretty neat.

Also, a more slimmed down version of the game state system does away with the game state manager or a similar concept. Instead, it just uses a group of GameStates, and each returns a GameState object at the end of the Update() function.

The game state can return itself, so it continues running every frame, or a different state if game conditions require that you switch to a different one. It's a bit harder to wrap your head around if you're still learning OOP, but for many games it can work pretty well without the overhead of coding a manager class.

New game in progress: Project SeedWorld

My development blog: Electronic Meteor

I prefer the run and return successor pattern for game states myself. An older thread illustrating this with code in SDL.

Thanks, all the answers are great! I don't think I'll need the more complicated state machines for a while, but it's nice to at least have an idea of how people do it. I can see from the responses that there're a lot of ways to implement game states. Are there reasons to use one way over another in specific situations, or is it more just a matter of preference?

To me implementing a state-machine feels equivalent to making a Rube-Goldberg-Machine. There are variables already in a programming language, why implement a god-variable to combine various things from the whole program only to try to interpret its value in a huge switch case statement a moment later to separate the things you just combined to essentially just simulate how a variable works using a variable? Or even worse build dozens of vapor classes with virtual methods, one per case, to disguise that switch?

Why not just make decisions at those points where they naturally appear with a bit of local data?

Because games naturally tend to have macro states that frequently have little shared behavior between them. There isn't that much common code between the higher logic of a loading screen and your main game play state. Not to mention mini-games, setting game options, and possible genre specific states like diplomacy screens for a 4X, inventories for RPGs and so on.

This topic is closed to new replies.

Advertisement