Stack based game states

I recently read an article about programming a RPG, and one interesting part I took from it was the idea of managing the game states with a stack.

Before I’ve always handled it by either having a single mainloop and using a switch statement, selecting which state’s code to run or having each state as an object with a update and render loop, swapping the objects when the state is changed.

The problem with the first one is that with enough states, the mainloop can start getting cluttered and difficult to navigate. The issue with the second is that because the states are created and deleted when changed, data that could be important could end up being forgotten. For example, when going back from a battle state to the world map state, the data of where the player was could end up being forgotten.

But by managing the game states using a stack, when returning from a battle state to the world map state, since the world map wasn’t deleted for the battle state, all the data is preserved.

While std::stack exists, I decided to write my own to add some extra functionality, also because I’ve not programmed any templates in a while and wanted to get some practice doing so.

#include <stack>

template<class T>
class Stack{
public:
void Pop() { delete Top();
_stack.pop(); }

void Push(T t) { _stack.push(t); }

void Replace(T t) { Pop();
Push(t); }

T Top() { return _stack.top(); }
void Clear() { for( unsigned int x = 0; x < _stack.size(); ++x){ Pop(); }}
private:
std::stack<T> _stack;
};

Next I give the Game object a stack containing game states

Stack<iGameState*> *_state_stack;

From then on I just need to push new states to the stack for example when going from a world map state to a battle state or menu state, then pop the state off when wanting to go back.