• 12
• 12
• 9
• 10
• 13

# Managing Game State/Screens without Managers and Singletons

This topic is 2019 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello forum!

Something that has been quite a hassle for me too wrap my head around is the managing of screens/states.
Basically I have a base class called "State" or "Screen" that each State/Screens inherit from.

Each screen has a boolean called "finished" that returns true if the state is done and should be deleted/switched with another state. The state must also have support for childs, better known as states withing states such as InventoryState that acts within the WorldState ( Actual game ) or PauseState that is another state above WorldState.

Childstates are small states and pieces of game logic inside a the State stack that tells the Game-Loop to NOT de-allocate the states before itself, ( Seeing as it's a child of it and is supposed to go back to it soon ) as well as having the ability to determine if the parent state should update and/or render itself WHILE the childstate is active! Think a small popup window when you level up inside a battlestate, the battlestate still renders but does not update logic other than animations.

This is roughly the system I'm trying to achieve, coding it isn't very hard it's more how I grant access to the states to push new states into the stacks.

I think the best way would be to pass the stack wrapped inside a class with the method only to push new states into the the stack, that way a class only have access to the feature they SHOULD and WILL use.

But I'm not sure, is this unnecessary? Is their a cleaner way to do it?
Thanks beforehand!

##### Share on other sites
One way is to have a class that is responsible for managing the stack of states (main, popup, pause, etc) and allocating/deallocating states and state progress.

But another possibility is to treat the main states and popup windows as different concepts, and have exactly one main state active and zero or one popup screens. This simplifies state management, but would prevent you from having popup screens in popup screens (but that might only be good thing).

Pausing could also be an state attribute rather that a state in itself. Also to give you simpler state management, although the state themselves get slightly more complex.

Anyway, the concept of a game state is kind of singular and managed, meaning the game will always be in *a* state (not none or several), and that state switches are very "global" in nature. So some form of manager or single point of access is not entirely inappropriate.

##### Share on other sites
I usually use state classes that use the run and return successor pattern. Basically every function called on a state object returns a smart pointer to the state that the system should be in now. This can be a pointer to the original state. This allows inter-relation of states to happen without whatever is holding the state to explicitly know what's going on. For example, a state can go to a pause mode by constructing a pause state object and passing itself to the pause state constructor and returning a smart pointer to that pause state. When the appropriate event occurs, the pause state can return the original state object to transfer control back. Similarly, your level up state could be constructed with a pointer to the previous battle state; then the level up state's render code can call the battle state's render code first before rendering on top of what the battle state displayed. This avoids needing anything like a singleton or a manager class.

##### Share on other sites
I think you are talking about an abstraction called "Finite State Machine" (http://en.wikipedia....e-state_machine). If the states itself run as FSM, then you are talking about "Hierarchical FSM".

I usually prefer separating the FSM logic from the game/app logic, using a pattern called "Delegate" (http://en.wikipedia....egation_pattern): each State delegates its execution on another object. In http://github.com/pacobarter/LibSHFSM I use (java) Interfaces for State and Transition, so being less intrusive in the Screen/Game/... object hierarchy. I mean, using Interfaces in this way, you can forget about the FSM logic and concentrate on your Game logic. Edited by pacobarter

##### Share on other sites

Basically every function called on a state object returns a smart pointer to the state that the system should be in now. This can be a pointer to the original state. This allows inter-relation of states to happen without whatever is holding the state to explicitly know what's going on. For example, a state can go to a pause mode by constructing a pause state object and passing itself to the pause state constructor and returning a smart pointer to that pause state.

I've done this myself and it works very well. However the one thing you want to watch for, especially on Android, is how frequently you allocate for new instances. A more efficient way could be to have state behavior classes stateless, and any state information needed is held elsewhere in a long-lived structure associated with your agents/entities/game objects/whatever you want to call them. If the state behavior class is stateless, then you can reuse the same instance during the entire simulation for any entity. This may be a premature optimization using C++ targeting x86, but it netted me quite a bit of performance on Dalvik.

##### Share on other sites
I I really liked your answer of the Run and Return Successor pattern!

But I have a few questions, you say that it should return a smart pointer? How would that work? Look like?
Since if you "reset()" a smart pointer it will release it's current pointer. So the passed state would be invalid, since the smart pointer will call delete on it. ( I'm currently talking about the pointer residents in the context ( "Game-class Main-loop" ).

Also I'm a bit confused overall, but I'm guessing that it means "returns a smart pointer" is basically the ( using SFML-library )
"State::update()" && "State::updateEvent()" would return a smart pointer, as a reference? or a full scaled copy of it?

Maybe you could provide a snippet of how it could "look like" game-loop wise that is, it would be great! I'v searched on google but fund very little, more so in C++ code.

EDIT:
To clarify a bit of my question!

Ex:
We go from Overworld-state into the Pause-state, it's constructed from inside the Overworld-state's like:
return unique_ptr<State>(new PauseState(this));
Then later we come back and go back to the Overworld state from the PauseState like:
return unique_ptr<State>(overworldState);
THIS TIME HOWEVER, we want Pause-state to be de-allocated, when we switch back to the Overworld-state, how can that be determined?

Kind regards, Victor Karlsson aka Moonkis

##### Share on other sites
For run and return successor, unique_ptr isn't a very good choice. Being able to return this is helps reduce the number of special cases. So you can use std::/boost::shared_ptr with enable_shared_from_this or boost::intrusive_ptr. I'm not familiar with SFML so I can't really comment on that, but I can show you how it might look with SDL. Start with what your state interface might look like:
 struct IState; typedef std::shared_ptr<IState> StatePtr; struct IState { virtual StatePtr update(double frame_time) = 0; virtual void render(SDL_Surface * surface) = 0; virtual StatePtr on_key_up(SDLKey keysym) = 0; virtual StatePtr on_key_down(SDLKey keysym, Uint16 unicode) = 0; virtual StatePtr on_mouse_down(Uint8 button, Uint16 x, Uint16 y) = 0; virtual StatePtr on_mouse_up(Uint8 button, Uint16 x, Uint16 y) = 0; virtual StatePtr on_mouse_motion(Uint8 state, Uint16 x, Uint16 y, Sint16 xrel, Sint16 yrel) = 0; virtual ~IState() {} }; 
Obviously your state can be fancier. You might have joystick events, for example. I usually have both a regular update() and a render_update() function so that a paused state can do things like idle animations despite being paused. Here's a really simple concrete state:
 struct BlueState : IState, std::enable_shared_from_this<BlueState> { virtual StatePtr update(double frame_time) { return shared_from_this(); } virtual void render(SDL_Surface * surface) { SDL_Rect rect = { 0, 0, surface->w, surface->h }; SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format, 0, 0, 255)); } virtual StatePtr on_key_up(SDLKey keysym) { return shared_from_this(); } virtual StatePtr on_key_down(SDLKey keysym, Uint16 unicode) { return shared_from_this(); } virtual StatePtr on_mouse_down(Uint8 button, Uint16 x, Uint16 y) { return shared_from_this(); } virtual StatePtr on_mouse_up(Uint8 button, Uint16 x, Uint16 y) { return shared_from_this(); } virtual StatePtr on_mouse_motion(Uint8 state, Uint16 x, Uint16 y, Sint16 xrel, Sint16 yrel) { return shared_from_this(); } }; 
All it does is fill the surface it gets with blue and otherwise just sits there. Not too useful, but does demonstrate about the bare minimum for a concrete state type. A slightly more complex state:
 struct PauseState : IState, std::enable_shared_from_this<PauseState> { StatePtr next_state; PauseState(StatePtr next) : next_state(next) {} virtual StatePtr update(double frame_time) { return shared_from_this(); } virtual void render(SDL_Surface * surface) { next_state->render(surface); SDL_Rect rect = { 100, 100, surface->w - 200, surface->h - 200 }; SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format, 0, 0, 0)); } virtual StatePtr on_key_up(SDLKey keysym) { return shared_from_this(); } virtual StatePtr on_key_down(SDLKey keysym, Uint16 unicode) { if (keysym == SDLK_ESCAPE) return next_state; return shared_from_this(); } virtual StatePtr on_mouse_down(Uint8 button, Uint16 x, Uint16 y) { return shared_from_this(); } virtual StatePtr on_mouse_up(Uint8 button, Uint16 x, Uint16 y) { return shared_from_this(); } virtual StatePtr on_mouse_motion(Uint8 state, Uint16 x, Uint16 y, Sint16 xrel, Sint16 yrel) { return shared_from_this(); } }; 
This is a pause state that pauses the game until the escape key is pressed. It keeps rendering whatever state will be next after you leave the pause, but with an overlay, but doesn't forward any other events to the state, so that state is effectively paused. If you had a render_update() function, you could invoke the held state's render_update() to do idle animations.

The game loop for this would look something like:
 StatePtr base_state(/* whatever your initial state is */); double old_ticks = SDL_GetTicks(); for (;;) { double new_ticks = SDL_GetTicks(); SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_MOUSEMOTION: base_state = base_state->on_mouse_motion(event.motion.state, event.motion.x, event.motion.y, event.motion.xrel, event.motion.yrel); break; case SDL_MOUSEBUTTONDOWN: base_state = base_state->on_mouse_down(event.button.button, event.button.x, event.button.y); break; case SDL_MOUSEBUTTONUP: base_state = base_state->on_mouse_up(event.button.button, event.button.x, event.button.y); break; case SDL_KEYUP: base_state = base_state->on_key_up(event.key.keysym.sym); break; case SDL_KEYDOWN: base_state = base_state->on_key_down(event.key.keysym.sym, event.key.keysym.unicode); break; case SDL_QUIT: return 0; break; } } base_state = base_state->update(new_ticks - old_ticks); base_state->render(screen_surface); SDL_Flip(screen_surface); old_ticks = new_ticks; } 

##### Share on other sites
This is amazing!
I'v tried googling the pattern but haven't find anything or very little about it, maybe you know some good resources?

Also is this possible to do without the shared pointers and still receive the same functionality?
I'd really like to know!

Thanks again for that awesome explanation!

##### Share on other sites
It's not a complicated pattern, which is why there isn't much literature on it. This should be sufficient to explain it. You could do it without shared_ptr. As I mentioned, something like intrusive_ptr would also work, as would hand rolling your own reference counting scheme. Or you can use raw pointers and somehow deal with the ownership problems manually. I don't really see much point when there are existing solutions that work out of the box.