State Machines
Games are full of things that behave differently depending on what they're doing. The game itself is on the title screen, playing, paused or showing "game over". The player is idle, running, jumping or dead. A round is in warm-up, live or finished. Writing this with flags (isJumping, isPaused, isDead, isAttacking) quickly produces impossible combinations: a dead player who is also jumping. A finite state machine (FSM) fixes that: an object is in exactly one state at a time, and it changes state only through defined transitions.
Game flow as a state machine
start pause
Title ────────► Playing ◄──────────► Paused
▲ │ resume │
│ │ die │ quit
│ restart ▼ │
└────────── GameOver ◄───────────────┘Each arrow is a transition triggered by an event. Anything not drawn is not allowed: you can't pause on the title screen or die while paused. A transition table makes that explicit:
using System;
using System.Collections.Generic;
var transitions = new Dictionary<(GameState, string), GameState>
{
[(GameState.Title, "start")] = GameState.Playing,
[(GameState.Playing, "pause")] = GameState.Paused,
[(GameState.Paused, "resume")] = GameState.Playing,
[(GameState.Paused, "quit")] = GameState.GameOver,
[(GameState.Playing, "die")] = GameState.GameOver,
[(GameState.GameOver, "restart")] = GameState.Title,
};
var state = GameState.Title;
string[] events = { "pause", "start", "pause", "die", "resume", "die", "start", "restart" };
foreach (string e in events)
{
if (transitions.TryGetValue((state, e), out var next))
{
Console.WriteLine(quot;{state,-8} --{e}--> {next}");
state = next;
}
else
{
Console.WriteLine(quot;{state,-8} ignores '{e}'");
}
}
enum GameState { Title, Playing, Paused, GameOver }Title ignores 'pause'
Title --start--> Playing
Playing --pause--> Paused
Paused ignores 'die'
Paused --resume--> Playing
Playing --die--> GameOver
GameOver ignores 'start'
GameOver --restart--> Title
The table is data, so you can print it, draw it, test it, or load it from a file. Invalid events are ignored in one place instead of being guarded by if statements all over the code.
States with enter, update and exit
For characters, each state needs its own behavior every frame, plus setup and cleanup when you enter and leave it (start an animation, play a sound, reset a timer). The State pattern gives each state its own class with Enter, Update and Exit:
using System;
var player = new Player();
string[] inputs = { "", "move", "move", "jump", "", "", "", "", "", "", "", "" };
for (int frame = 0; frame < inputs.Length; frame++)
player.Update(frame, inputs[frame]);
class Player
{
public double Height, VelocityY;
IState state = new Idle();
public Player() => state.Enter(this);
public void Update(int frame, string input)
{
IState next = state.Update(this, input);
Console.WriteLine(quot;frame {frame}: {state.Name,-7} height {Height:F1}");
if (next != state)
{
state.Exit(this);
state = next;
state.Enter(this);
}
}
}
interface IState
{
string Name { get; }
void Enter(Player p) { }
IState Update(Player p, string input);
void Exit(Player p) { }
}
class Idle : IState
{
public string Name => "Idle";
public IState Update(Player p, string input) =>
input == "move" ? new Running() : input == "jump" ? new Jumping() : this;
}
class Running : IState
{
public string Name => "Running";
public void Enter(Player p) => Console.WriteLine(" (start run animation)");
public IState Update(Player p, string input) =>
input == "jump" ? new Jumping() : input == "move" ? this : new Idle();
}
class Jumping : IState
{
public string Name => "Jumping";
public void Enter(Player p) { p.VelocityY = 3; Console.WriteLine(" (play jump sound)"); }
public IState Update(Player p, string input)
{
p.Height += p.VelocityY;
p.VelocityY -= 1;
if (p.Height > 0) return this;
p.Height = 0;
return new Idle();
}
public void Exit(Player p) { p.VelocityY = 0; Console.WriteLine(" (landing dust)"); }
}frame 0: Idle height 0.0
frame 1: Idle height 0.0
(start run animation)
frame 2: Running height 0.0
frame 3: Running height 0.0
(play jump sound)
frame 4: Jumping height 3.0
frame 5: Jumping height 5.0
frame 6: Jumping height 6.0
frame 7: Jumping height 6.0
frame 8: Jumping height 5.0
frame 9: Jumping height 3.0
frame 10: Jumping height 0.0
(landing dust)
frame 11: Idle height 0.0
Jumping can't be entered twice (there's no "jump" transition out of Jumping), so the double-jump bug is impossible by construction. Adding a double jump later means adding a DoubleJumping state with its own rules, not another flag.
Note: The state change happens after the frame is printed, so a state's first update runs on the next frame. Engines differ on whether a new state also updates in the frame it was entered; pick one rule and keep it.
Where state machines appear
| Where | States |
|---|---|
| Game flow | boot, title, loading, playing, paused, game over, credits |
| A round or match | warm-up, countdown, live, overtime, results |
| Characters | idle, run, jump, fall, attack, hurt, dead |
| Enemy AI | patrol, chase, attack, flee (see A State-Machine Boss) |
| UI | closed, opening, open, closing |
| Animation | engines' animation state machines: Unity's Animator, Unreal's Animation Blueprints, Godot's AnimationTree |
When one machine grows to dozens of states, split it: a hierarchical state machine nests states (a "Grounded" super-state containing Idle and Running), and AI often moves on to behavior trees; Game AI covers both.
Test yourself
What does a finite state machine guarantee that a set of boolean flags doesn't?
- Faster code
- The object is in exactly one state, and only allowed transitions happen
- Less memory
- Thread safety
In the game-flow table, what happens when 'die' arrives in the Paused state?
- The game goes to GameOver
- The event is ignored because no transition is defined
- The game crashes
- It resumes
What is the Exit method of a state for?
- Quitting the game
- Cleanup when leaving the state, like resetting values or stopping effects
- Choosing the next state
- Rendering