GameState Management

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • GameState Management

      Hello everyone,

      first off: thanks for writing such a great book Mike and Rez!

      second:
      Is there a specific reason for not handling changes of the game state via events?

      Also I have thought about/tried to introduce a GameState class into the engine. The more i progress on that effort, the more obsolete becomes the GameLogic it seems. Like there's really only one state - "ingame" - where I need to keep track of Actors. The rest is menus, splash screens, cut scenes etc. so that GameLogic becomes a StateManager. Is there any reason not to take this approach?

      And a general question to everyone: How are you going about managing and animating state changes?
      In terms of GCC I'm using the Processes to animate ScreenElements flying in/popping into existence. (btw: I'm quite amazed by the SC2 menus, seems more like a fancy browser than anything else)

      Hopefully you're all having a fun day!
      ~Peachboy
    • RE: GameState Management

      Originally posted by Peachboy
      first off: thanks for writing such a great book Mike and Rez!

      You're welcome, I'm glad you're enjoying it. :)


      second:
      Is there a specific reason for not handling changes of the game state via events?

      No, not really. You can handle them as events if you prefer. I've worked on a number of games that do the same thing. The game states are handled as an enum right now for simplicity. A better way, which you propose below, is to use the State design pattern.


      Also I have thought about/tried to introduce a GameState class into the engine. The more i progress on that effort, the more obsolete becomes the GameLogic it seems. Like there's really only one state - "ingame" - where I need to keep track of Actors. The rest is menus, splash screens, cut scenes etc. so that GameLogic becomes a StateManager. Is there any reason not to take this approach?

      Refactoring game states into self-contained objects that handle game logic is great and a number of games do it. To be clear, you're actually getting rid of the game logic. Conceptually, your game states act as the game logic. As long as you follow all the same rules that the game logic follows (specifically in terms of architectural separation), then you should be fine. This is how the engine at Planet Moon worked, as well as here on The Sims. It's a pretty common approach. :)


      And a general question to everyone: How are you going about managing and animating state changes?
      In terms of GCC I'm using the Processes to animate ScreenElements flying in/popping into existence. (btw: I'm quite amazed by the SC2 menus, seems more like a fancy browser than anything else)

      We're not, since there are no animations in the game. ;) To add animations into GCC, I would create an AnimationComponent that's attached to any animated actors that handles all the resource loading, animation updates, etc. It will likely need to talk to the renderable component, but a simple animation system should slot in fairly easily.

      By SC2 do you mean Starcraft 2? If so, I'm pretty sure the use Scaleform, which is a way of embedding flash into your game. Many triple-A games use this for their UI, though it's fairly expensive.

      -Rez
    • Hi guys,

      The concepts of game management have bothered me for quite a while. I just want to share my thoughts to confirm (or not) that they are correct.

      On the very high level the game could be divided into screens (similar to what Chapter 10 says). The screen is the collection of the various game entities. There should be screen manager, controlling screen transition, many screens could be active at a given time (stack of screens). If the screen is modal, then user input only goes to it.

      However, this is not the only division. I found that it's sometimes necessary to break screen even further into the states (some kinda 'game state' you are talking about). Most of the screens will have only 1 state, but game screen can have tons of them. Taking e.g. space game, we can have 3 states: space, base, paused. Another transition manager should control transitions between those states inside the screen. This probably should be organized similarly to the screen management.

      That's it :) What you can say on this? Is is an over-design or not? I've actually tried to implement this scheme once, although what I got was far from nice and clean code, so I suspect this design is hard to do right.
      Looking for a job!
      My LinkedIn Profile
    • my new state system uses classes as well, each state class actually manages its own set of actors/views which comes in really handy.
      PC - Custom Built
      CPU: 3rd Gen. Intel i7 3770 3.4Ghz
      GPU: ATI Radeon HD 7959 3GB
      RAM: 16GB

      Laptop - Alienware M17x
      CPU: 3rd Gen. Intel i7 - Ivy Bridge
      GPU: NVIDIA GeForce GTX 660M - 2GB GDDR5
      RAM: 8GB Dual Channel DDR3 @ 1600mhz
    • Hey there,

      just wanted to thank you guys for your input.

      devast3d if I follow correctly I quite like your idea. I'm kind of thinking of Final Fantasy 7, running around the world map and entering a fight. There you have
      "Intro -> MainMenu -> InGame -> GameOver" as like the Screens and InGame you come across situations like this:
      "World -> Transition -> Fight -> Transition -> Loot -> World". :)

      I guess one issue about this is when to stop hardcoding and introducing state management via XML or some such thing. I feel like sticking to architectural separation also becoming harder and harder the more I hardcode States... it's just so easy to let a state really own a view (instead of just providing the prefered subclass) and then stacking states for modal dialog and all of a sudden you have 2 RemoteViews communicating to the same client about the same actor...

      Not that I would do such a thing *cough*

      Have a good day!
      ~Peachboy
    • Hello everyone!

      I try to deal with GameState management and have some questions about.

      Suppose, we have simple platformer (side-scroller) game, with three possible screens: "Main menu", "In game", "Character's inventory".
      And we have StateManager object, who store map, or stack or whatsoever structure of GameStates and manages theirs life cycle.

      Questions:

      1. Suppose, we have some levels in our game. It is means that we have not one "InGame" state object during lifetime of a game, but several, like "Level1", "Level2" and so on and so forth?
      Or we should make some LevelManager for InGame state?

      2. Who owns map (or list, or...) of Actors?
      If every game state would have its own list of Actros, that how to share changes between states, like what if we checkout to invetory state, change some character params and then checkout back to the InGame state?
      Or maybe we should make shares structure of Actors? But there is a questions: where we must store shit stucture?

      3. Who owns ans inits game components like physics system?
      It seems, that every game state who need subsystem, create its own instanse of it. For example, suppose our inventory have physics too. We need to run physics simulation in Inventory state when we checkout into it, and stop simulation in InGame state this moment.

      I undestand, that have this proplems has different solutions, but maybe there is some best practices or you can give some useful tips about state managing.
      If you, guys, give some links to the articles about this subject, it would be great too.

      Regards.
      ~Mulberg
    • I had to come to these same realizations when I switched to an object base state system, and here is how I did things.

      - I decided that one state would manage the 'game' state, which could be modified to accommodate various gameplay styles (multiplayer, arcade, challenge etc). And also could be loaded with different 'scenes' for each level.

      - Each State has its own separate Actor and View sets, I did this because I figured that an AI actor with an AI view has no business running in the main menu, or splash screens. One benefit to this is that if you want to have your menu accessible by pressing escape, it is really snappy to switch back and forth between states. If you want the game state to dump its actors and views when you return to the menu ie. 'Exit the game mode', than you could switch states, and than clear it out once switched.

      - I also had the ability to have a physics system attached to each state, if one isn't set up for a particular state, it simply won't run. I don't know where I would use physics aside from the main game state, but I figured that it was the best place, and would allow for anything to be possible, like maybe an interactive splash screen, or credits like in some of the super smash bros. games.

      I didn't find any particular articles on this subject, but I can tell you it works pretty well, the only thing you will have to take into account is that instead of having the ability to have a global pointer to your game logic for actor/view access, you will need to pass the 'owner' state to things like Actors/views to make sure they know who they belong to, I did this with a base class that I additionally inherit from, but only had to on my actor and view classes.
      PC - Custom Built
      CPU: 3rd Gen. Intel i7 3770 3.4Ghz
      GPU: ATI Radeon HD 7959 3GB
      RAM: 16GB

      Laptop - Alienware M17x
      CPU: 3rd Gen. Intel i7 - Ivy Bridge
      GPU: NVIDIA GeForce GTX 660M - 2GB GDDR5
      RAM: 8GB Dual Channel DDR3 @ 1600mhz
    • Originally posted by andjey
      I try to deal with GameState management and have some questions about.

      Suppose, we have simple platformer (side-scroller) game, with three possible screens: "Main menu", "In game", "Character's inventory".
      And we have StateManager object, who store map, or stack or whatsoever structure of GameStates and manages theirs life cycle.

      As I said above, the key piece of fitting game state objects into the GCC architecture is to replace the Game Logic with the state pattern.


      1. Suppose, we have some levels in our game. It is means that we have not one "InGame" state object during lifetime of a game, but several, like "Level1", "Level2" and so on and so forth?
      Or we should make some LevelManager for InGame state?

      You should have a single InGame state that loads the appropriate level. Levels are really just data, so the only thing that should change in code is which level file you're loading.


      2. Who owns map (or list, or...) of Actors?
      If every game state would have its own list of Actros, that how to share changes between states, like what if we checkout to invetory state, change some character params and then checkout back to the InGame state?
      Or maybe we should make shares structure of Actors? But there is a questions: where we must store shit stucture?

      Yes, each state would have its own list of actors (though really, the InGame state is probably the only state that needs actors). Each state should be self-contained, so actors and other objects aren't usually shared. If two states need to share a lot of data, that's a sign that they shouldn't be split into two states. For example, I wouldn't make inventory into a separate state. Inventory is really just a UI screen overlayed over the game world. You'll probably change the input mode, but you shouldn't change the game state.


      3. Who owns ans inits game components like physics system?
      It seems, that every game state who need subsystem, create its own instanse of it. For example, suppose our inventory have physics too. We need to run physics simulation in Inventory state when we checkout into it, and stop simulation in InGame state this moment.

      Depends on the system. Global systems are created globally by something like the Application while game systems like the Physics system would be created and used by the state. If you end up needing physics outside of the InGame state, I would initialize it globally. Otherwise, keep it local to the gamestate.

      I haven't read any articles on game states specifically, but there's nothing special about them. They are just an implementation of the State Pattern:
      en.wikipedia.org/wiki/State_pattern

      One thing you might want to consider is a hierarchical state machine, which is basically a state machine within a state machine (each state can have its own substates). This is one way to implement something like an InGame state with a number of substates, like inventory.
      eventhelix.com/realtimemantra/…emachine.htm#.UW2zPLVJN30

      -Rez
    • mholley519 and Rez, thank you for reply!

      But there I see another problem:

      In GGC we initialize and store physics system in GameLogic, which we can unambiguously get, and then get Physics from it. Like this:

      Source Code

      1. // PhysicsComponent.cpp
      2. bool PhysicsComponent::VInit(TiXmlElement* pData)
      3. {
      4. m_pGamePhysics = g_pApp->m_pGame->VGetGamePhysics();
      5. ...
      6. }

      But what if we implement some sort of state machine:

      Source Code

      1. class GameState
      2. {
      3. public:
      4. virtual void VOnUpdate(float elapsedTime) = 0;
      5. };
      6. //Menu state doesn't aware about physics cause it doesn't need it
      7. class MenuState : public GameState
      8. {
      9. public:
      10. virtual void VOnUpdate(float elapsedTime) { // do something }
      11. }
      12. // But Gameplay state aware
      13. class GameplayState : public GameState
      14. {
      15. std::shared_ptr<IGamePhysics> m_pPhysics;
      16. public:
      17. virtual void VOnUpdate(float elapsedTime) { // do something }
      18. std::shared_ptr<IGamePhysics> VGetGamePhysics(void) { return m_pPhysics; }
      19. }
      20. class StateManager
      21. {
      22. public:
      23. GameState* GetCurrentState();
      24. };
      25. class App
      26. {
      27. StateManager* m_StateManager;
      28. public:
      29. GameState* GetCurrentState() { return m_StateManager->GetCurrentState(); }
      30. };
      31. // And now we can't simple get physics
      32. g_pApp->GetCurrentState()->VGetGamePhysics(); // NO! Base game state doesn't aware about Physics!
      Display All

      And this problem rises for Actors map, and other things that consist not in all game states.
      We could make base GameState aware about physics and Actors and just set empty actors list and NullPhysics...
      If you end up needing physics outside of the InGame state, I would initialize it globally.

      This is the case, right? )

      Or maybe there is more appropriate approach exists?

      Regards.

      The post was edited 5 times, last by andjey ().

    • Honestly whatever works for you, If you only need physics in one state than that works fine, same with the actors, just move your code up from the base state to your game state class, I chose not to do this mainly to have flexability in any situation, because really what is the cost of having an empty actor list and a blank physics system? A few virtual function calls and what not seems reasonable to not have to implement things more than once in my opinion.

      One situation where this worked out great for me was my splash screen state, I used my actor system to quickly throw up our game logo which needs animation, having a sprite component and animation component handy makes this really easy to do, sure I could have done it another way, but it made the most sense to me to do it this way.
      PC - Custom Built
      CPU: 3rd Gen. Intel i7 3770 3.4Ghz
      GPU: ATI Radeon HD 7959 3GB
      RAM: 16GB

      Laptop - Alienware M17x
      CPU: 3rd Gen. Intel i7 - Ivy Bridge
      GPU: NVIDIA GeForce GTX 660M - 2GB GDDR5
      RAM: 8GB Dual Channel DDR3 @ 1600mhz

      The post was edited 1 time, last by mholley519 ().

    • There are a number of ways you can handle this. The way I typically do it is with singletons for my major systems. So, I'd do something like this:

      Source Code

      1. class PhysicsSystem
      2. {
      3. static PhysicsSystem* s_pSingleton;
      4. public:
      5. // singleton functions
      6. static void Set(PhysicsSystem* pPhysicsSystem);
      7. static void Destroy(void);
      8. static PhysicsSystem* Get(void) { return s_pSingleton; }
      9. // The rest of this class would be pure virtual functions which are implemented
      10. // in the subclass.
      11. // .....
      12. };
      Display All


      Then accessing the physics system is trivial, you just call PhysicsSystem::Get(). There are number of advantages to this, many of which I go over in this post:
      mcshaffry.com/GameCode/thread.php?threadid=1805

      Major systems which have a large spin-up & spin-down time are typically done this way. I also tend to split the concept of initializing and loading for certain systems. Or, to put it another way, I have a three-stage initialization pattern. The first stage is the constructor which sets everything to a neutral state and can't fail, the second is initialization which actually initializes the object, and the third is loading (or a second init stage) which sets up context-specific stuff. As an example, here are three functions pulled directly from my World class that illustrate what I mean (yes, these comments are unchanged and representative of how much I actually comment):

      Source Code

      1. // Initializes the world. This function is only called once during the program's initialization.
      2. virtual bool Init(unsigned int renderStage, Scene* pScene) = 0;
      3. // Loads the world based on the world file. The world file is typically loaded synchronously though it is
      4. // ultimately up to each World implementation. Note that once the world has been loaded, a single call to
      5. // the Update() function is made and followed by a call to signal the loader thread and wait for processing.
      6. // This allows the world to set up a full scene while a loading screen is up.
      7. virtual bool LoadWorld(const char* worldFilePath) = 0;
      8. // Destroys a loaded world. This puts the world back into an "initialized but not loaded" state. You can
      9. // call LoadWorld() again to load a new world.
      10. virtual void DestroyWorld(void) = 0;
      Display All


      So my world singleton is initialized right away, but the world isn't loaded until we try to enter the actual game.

      Here's the same concept applied to graphics, this one coming from my Scene class:

      Source Code

      1. // This function initializes the object and gives the implementation class a chance to instantiate / initialize
      2. // anything it needs. It's called once in Application::Init().
      3. virtual bool InitScene(void) = 0;
      4. // This function initializes the renderer. It is called once automatically by Application::Init() but may be
      5. // called anytime during execution, as long as DestroyRenderer() is called first. This allows the application
      6. // to reinitialize the renderer after destroying it, such as when the graphic settings change.
      7. virtual void InitRenderer(void) = 0;
      8. // This function destroys the renderer, but NOT the Scene object (which is only destroyed in the destructor).
      9. // It is called by Application::Destroy(). The purpose of this function is to allow the application to explicitly
      10. // destroy the renderer at any time, modify some graphical settings, and call InitRenderer() to bring it back up
      11. // again.
      12. virtual bool DestroyRenderer(void) = 0;
      Display All


      Hopefully that makes sense. Let me know if you have questions. :)

      -Rez
    • Originally posted by Rez
      Hopefully that makes sense.

      Yes it does.
      I'm a web-developer and develop buisness application (C++ and gamedev is my hobby for the time being).
      And we usually use DI and service locators for the same purposes.
      http://www.mcshaffry.com/GameCode/thread.php?threadid=1805

      Thanks. I will read that thread. Maybe will find something usefull fro me.

      Originally posted by mholley519
      I chose not to do this mainly to have flexability in any situation, because really what is the cost of having an empty actor list and a blank physics system?

      Sounds reasonable. I'll try to follow this way and see what happens.

      Thank you again, guys!

      The post was edited 3 times, last by andjey ().

    • Originally posted by Rez
      Hopefully that makes sense.

      Yes it does.
      I'm a web-developer and develop buisness application (C++ and gamedev is my hobby for the time being).
      And we usually use DI and service locators for the same purposes.
      http://www.mcshaffry.com/GameCode/thread.php?threadid=1805

      Thanks. I will read that thread. Maybe will find something usefull to me.

      Originally posted by mholley519
      I chose not to do this mainly to have flexability in any situation, because really what is the cost of having an empty actor list and a blank physics system?

      Sounds reasonable. I'll try to follow this way and see what happens.

      Thank you again, guys!

      The post was edited 1 time, last by andjey ().

    • Hey guys,

      I've finally refactored my engine to use the State pattern which has resulted in the GameLogic class becoming a state machine. It handles a couple events that result in application state change, then sets the current IApplicationState pointer to the appropriate state. This pointer is then used to perform HandleInput, Update and Render operations which results in the state machine class being very small which is awesome. Thanks for the tip!

      However, I'm still having the dreaded View vs Screen Element problem and I know you're sick of hearing about it but I've gotta try and wrap my head around it one more time. When my player dies, I want to present a GameOver screen with the option of restarting. This screen will be very simple, all black background with a single "New Game" button and some Game Over text. At first I was going to implement this as a new state but I decided 2 other approaches are probably better...

      1) Have the InGame state handle the event and swap in a new View

      2) Have the InGame View handle it and swap in a new screen element.

      I'm lost at this point as I don't which approach is better.

      Can anyone help me understand the difference between a View and Screen Element? Maybe with an example?

      Thanks!!
      -bullgoose

      The post was edited 1 time, last by bullgoose311 ().