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 …
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:
- Finite State Machine article in GDevelop wiki by @Wendigo How to handle complex logic – The finite state machine (FSM) [GDevelop wiki] (mandatory reading)
- State Chapter from the book Game Programming Patterns (read online for free) by Robert Nystrom
- Chapter “The State Pattern” from the book Head First - Design Patterns
- Images from this post, including GDevelop code without notes: https://imgur.com/a/NskBOcB
- Board walk with Raycast example (GDevelop source included): GDevelop example: board walk with Raycast by Paulo Amaral