   Managing Game States
  What are the best ways to manage different states in a game?  I.e., so when player dies in-game send them to the menu-screen, when they select "start" on the menu, send them to the in-game code?  Doing this all C-style seems rather messy, with booleans or enums for what state the game is in; I've tried making a State Manager that controls several polymorphed States, but the way I wrote it each different kind of state manager must have its own class because the constructors are hardcoded and the different states cannot request a change to another state without explicitly naming that state, at least the way I've made it.  Function pointers on a stack strike me as even uglier than ... anything I can think of offhand, perhaps even moreso than using GOTOs.  I don't know how a message-passing system would work or if it would be smart.This is how things are happening at this point:class State{public:State();virtual ~State();virtual bool Run() = 0;};enum StateSet { START, PLAY, GAMEOVER };// PlayState etc. are all children of the State classclass StateManager{public:StateManager(cGraphics *GfxSystem, cInput *Input, Timer *BBTimer);~StateManager();// sets tatevoid SetState(StateSet newState);// returns the current state in enumerated formStateSet GetCurrentState() { return CurrentEnum; }// asks the current state to Run(), returns the value of that Run()bool RunCurrentState();protected:   // pointers to stuff used by some or all statescGraphics *GfxSystem;cInput *Input;Timer *BBTimer;// the current state that is being runState *CurrentState;   // current state in enumeration form - used to switch between statesStateSet CurrentEnum;// list of states - I believe these could all be State*'s instead, but I don't know what difference it would makeStartState *Start;PlayState *Play;GameOverState *GameOver;};Looking at it again I think it's pretty clear this is a suboptimal way to do things, but what is the cleanest, most flexible way?Thanks GD.   
  I've done it both ways, with a lot of details each way. On the one hand, a big ol' switch statement in the main loop is pleasantly simple and flexible. You can get a LOT of mileage out of it. On the other hand, it leads to code repetition. By using a virtual class to encapsulate state, you can avoid much of this repetition. This is particularly useful if you're doing a lot of invariant stuff, and the only real changes between states are the "update world" code and the "render" code. On the other hand, states like "initializing" and "changing resolution" can often require a lot of complexity from the state interface, which essentially turns it back into a (convoluted) switch statement.There are some other advantages to a polymorphic state pattern, like separation of responsibilities. Blah, blah, blah. That code will be touched so seldom that it doesn't matter, IMHO. At this point my opinion is that a switch statement is perfectly suitable for top-level state control. Remember the KISS principle.   ;  Big ol' switch sounds like a plan.  I guess at this point, with 3-4 states, anything large and fancy will just be a lot of overhead.  Thanks!   ;  You don't even need to use enums. If you set up a class factory, you can create each state instance in that factory and 'ask' for the desired state from there. For instance, if the user presses ESC and you want the menu, you can ask for the menu game state from the class factory and pass that into your state handler.The state handler here really should work by running it's current state and monitoring any inherited errors that it might receive from the state that is being run.Note though, that if you are programming this in a language such as C#, there is no real need for a class factory because with C#, all classes are global to their entire namespace (if they are public or internal).   ;  I generally create an abstract GameState class and have a globally static GameState instance to act as the currentGameState.  During an update/tick, you'd call currentGameState.Update(). When the window has to render, you'd call currentGameState.Render().  Another added feature is that if you serialize the game state object, it allows you to let the player save their game and load it later on right where they left off since there's only one game state object that has to be loaded.Using this method saves yourself from just having a huge ugly switch statement and allows you to seperate your game state code into classes rather then just a bunch of methods.   ;  You should check out Mat Buckland's State Driven Game Agent system.  I think he based pretty much every late examples in his book on this system.Hope this helps   ;  Id go with polymorphic states for anything bigger than pong/tetris/etc.Some people add a state stack to the manager (where you can push states in and pop the current state out).  Im not sure how useful it is but maybe its an elegent solution to some problems Im not seeing right now.(perhaps its more useful for a sprite's state machine?)Iftah.   ;  A state stack is useful if you implement your menus and configuration dialogues as states, because you can then have your basic game state at the 'bottom' and have a console, a menu and an options screen spawned from the menu all on the screen at once, and you can Esc out of them one by one.   ;  Great posts and a lot to think about!RPG: I read something in Washu's journal about Factories/ConcreteFactories and from what I understand it's sort of like...a container for multiple singletons, except they're not globally visible because they can only be accessed when the ConcreteFactory is around.  I looked at something on the design pattern on Google but it was way over my head early in the morning; maybe I'll try again later.Rob: All my states have their own classes right now and this IS really nice; however, I don't think I understand how one could easily switch states like this.  Perhaps an enum return value or a pointer to a different state via a 'factory' as above?Eric: I happen to have purchased that book not long ago!  Unfortunately I haven't had much a use for complex AI yet and though I read that chapter, it was quickly because I didn't have an immediate use for it and was just sort of brushing over.  Maybe I'll look at it again; I remember it went over message-passing systems not long after, too.Iftah: This is true, though I would be concerned about pushing states like "Menu -> Game -> End" and having someone pop "end" off with escape and ending back in-game.Janova: Sounds interesting.  I think I used something like this for an awful menu system once, might be more useful if I made a system less awful! [smile]r++ing all around.   ;Quote:Original post by FrequencyIftah: This is true, though I would be concerned about pushing states like "Menu -> Game -> End" and having someone pop "end" off with escape and ending back in-game.I second a stack based state system. It allows context sensitive state machines. It gives you the ease of use of a switch statement without the complexity of a huge state machine.The problem you mention above is easily solved by having each state have a pointer to the stack controller. What you would simply do is something like thiscase GAME_STATE: {// -- pops off the game state so the stack looks like this// -- [root]->[menu]state->pop();  state->push(new EndState);// -- now the stack looks like// -- [root]->[menu]->[end]}Here you pop off the state and add a new state. As long as the pop/push are deferred from running until the next game update it will work fine. - Dave