State Design Pattern: Pushdown Automata FSM
- khimleesi
- Mar 1, 2023
- 2 min read
The state design pattern is a behavioural pattern that allows objects to change their behaviour based on internal state changes. It involves creating separate classes for each possible state of an object, which allows the object to switch between states seamlessly. This pattern can be used to handle complex state transitions in game objects, such as character animations or game modes. It helps to improve code organization and maintainability, and can lead to more efficient and flexible game development.
As you progress in game development, you'll encounter various state pattern designs, including the commonly used "Finite State Machine." While a Finite State Machine has its benefits in its simplicity, I'm going to introduce you to the state method I use, which is both powerful and versatile: the Pushdown Automata, an extension of the Finite State Machine that uses a stack to keep track of multiple different states and their history.
To visualize this, think of the stack as a deck of cards, where the top card is the current state, and removing it reveals the previous state underneath. We can achieve this in programming using an std::deque, which allows us to pop the front state off the stack and reveal the state below.
For example, let's say we have a game with two states: a menu state and a play state. The permanent state, which is our main focus regardless of any additional states, would be pushed to the back of the stack, while the temporary state would be pushed to the front, with a reference to the previous state. In this case, the menu state would be the temporary state, and the play state would be the permanent state. We start the program with a temporary state, with no previous state reference. When the player starts the game, we remove the menu state entirely.
In another scenario, we have a pause state and a play state. When the player pauses the game, the play state still exists but is inactive, meaning no updates are happening in the game. We can still render the game graphics behind a semi-transparent pause state, if we wished.
In summary, we want a stack of temporary and permanent states, each with a reference to the previous state and the ability to be active or inactive, alive or dead (as morbid as that sounds). If you want to see an example of a Finite State Machine (FSM) and how we can use it to implement game states in our code, you can check out my implementation on Github at the link below.