Studio 1: State Machines

In this post I’ll be explaining how our game Snofyr used state machines for our rounds system in the Game Manger.

What are Finite State Machines?

According to this blog written by Mark Shead, FSM are ” a mathematical abstraction used to design algorithms. In simple terms, a state machine will read a series of inputs.”
A finite state machine, as the name implies, only has a finite number of states that it can be in. These states have different effects depending on what you are creating, but the FSM simply churns between different states, executing the relevant code.

In c# the various states that a FSM can be are a series of enums that is changed as the machine changes.

Image result for what are state machines
Example of AI behaviour in a FSM

In Snofyr we used a state machine called MonsterLove, a tool that automatically processes the different states that your system needs and executes that code. What made MonsterLove an interesting tool is that you don’t need to call any functions after or before changing your state, it automatically updates the state and calls the relevant functions.

In Snofyr we used MonsterLove to transition between the game states:

statemachine.png

Snofyrs GameManager FSM

MonsterLove allows you to execute code when you enter a state, stay in a state, and leave a state. We primarily used these states for setting up the information required for the game. For example, in”BeforeNewRound” we set the  camera target to where the kids are at the top of the mountain, and check if the player has pressed a or not. As the gamemanager is a singleton, it was really easy to change the states without having to call code from external scripts, making functionality easier.

If I where to use this again

If I was to use this tool again, I would ensure that states properly called within the game manager. The diagram above says that EndRound checks if the game is won or lost, but this technically isn’t true. When the lighthouse is hit by the snowball, the Lighthouse checks if the its health is less than zero. If it is, it directly calls the “WindGame” state, and if it isn’t it calls the EndRound state, which THEN checks if the game is lost. This is essentially making “HitLighthouse” an invisible state of the game without officially making it a state. This doesn’t make sense in a programmical way, and this easily could lead to other special cases that could make finding when and where states are called a pain.

One thought on “Studio 1: State Machines

Leave a comment