Huge fan of state machines. I’ve used them for controlling robots and websites and all sorts before.
I think they suit a certain type of game very well, particularly if you have different core loops that are exclusive, and can occur in a number of different orders.
For example, I’m working on a city builder game, containing a few key states:
- Initialisation (including selecting a save slot to load)
- City Running
- Edit Mode
You can transition between any of these states from any of the others depending on the inputs and a few conditions, so a linear structure wouldn’t work.
And within edit mode there are sub states like
- Building placement
- Water network management
- Power network management
Again, you can transition between these sub states in any order you choose.
State machines are super useful because you can have the same inputs, e.g. the user presses X, but the outcome depends on the state. In complex games or games with exclusive loops (e.g. the city is never running while you’re editing it) then state machines really help to organise things.
I don’t really use state machines for UI screens as such, because generally the input is separate. It’s mostly useful for cases where the input is the exact same (e.g. keyboard presses and mouse movements). When you hover over a building in edit mode, the response is entirely different and exclusive to when you hover over it in run mode.
I think your diagram in the original message was confusing, and perhaps a better diagram shows the different ways to transition between states. Here’s an example using a well-known board game:
The quality of a state machine resides in the way you define the transitions and mapping out the conditions or triggers to cause the transition.
In terms of how to code that, well I usually create a state-setting function, and each state has entry and exit code. When you exit run mode, I hide the run-specific stuff. Then when I enter edit mode, I show the edit stuff. That saves you having to spend loads and loads of lines disabling everything that might have ever been visible. Knowledge of the previous state allows you to disable only the things that were enabled by that state. If you have 16 states, you should only ever be disabling one and enabling another, not disabling 15. That’s where the transitions are key.
I think some of the other repliers didn’t really read your post or are unfamiliar with state machines but I hope this helped. It’s important to realise state machines apply to anything you do in life where the sequence can be non-linear. The only question is whether you have enough states or the loop is complex enough to warrant the time spent coding it.