Working with Game States and Finite State Machine

Have you ever found yourself struggling because your game got too complicated, with flag variables all over the place? When you add one new feature, many places have to be refactored because bugs and glitches are easily introduced? Changing one place and breaking another became routine?

If the scenario above, described with code examples in the introduction “We’ve All Been There” of the State Chapter from the book Game Programming Patterns (read online for free) by Robert Nystrom, I wrote this for you.

By defining clear states and how conditions and interactions make the game transit from one state to another, you have better control of game behaviour, especially when it scales and start getting too complex. You can make changes to the logic of one state without affecting the others. This reduces the chance of bugs, glitches, and code-merge-hell. It is also better for scalability and working as a team.

You can learn more about it studying the State Design Pattern and Finite State Machine theory.

PRACTICAL EXAMPLE

The example below is from a board game implementation. The player starts with 0 actions left, roll the dice, then move around the board with arrows for the number of times from the dice roll. When actions left are zero again, the only thing the player can do is to roll the dice again. Then, with actions left, the player moves again with arrows. And so on …

game-states-implementation-example-gameplay

The player moves with arrow keys. The player rolls a number by clicking the “Roll” button when it is visible.

This is the States Diagram for this implementation:

This is how it was implemented in GDevelop:





References:

10 Likes

This is a good reference for people dealing with complexity in their games. I have reached this point and using an FSM has helped a great deal.

Thank you for sharing this post!

I know I probably shouldn’t be replying to old threads, but this is so incredibly useful, that I’ll break the rule!

1 Like