How to implement a stack of game states in C++
Posted
by
Lisandro Vaccaro
on Game Development
See other posts from Game Development
or by Lisandro Vaccaro
Published on 2013-10-08T16:08:36Z
Indexed on
2013/11/08
10:22 UTC
Read the original article
Hit count: 404
c++
|game-state
I'm new to C++ and as a college proyect I'm building a 2D platformer with some classmates, I recently read that it's a good idea to have a stack of gamestates instead of a single global variable with the game state (which is what I have now) but I'm not sure how to do it.
Currently this is my implementation:
class GameState
{
public:
virtual ~GameState(){};
virtual void handle_events() = 0;
virtual void logic() = 0;
virtual void render() = 0;
};
class Menu : public GameState
{
public:
Menu();
~Menu();
void handle_events();
void logic();
void render();
};
Then I have a global variable of type GameState:
GameState *currentState = NULL;
And in my Main I define the currentState and call it's methods:
int main(){
currentState = new Menu();
currentState.handle_events();
}
How can I implement a stack or something similar to go from that to something like this:
int main(){
statesStack.push(new Menu());
statesStack.getTop().handle_events();
}
© Game Development or respective owner