Skip to content
BENIBIX Learn

Finite State Machine (FSM)

Development🎮 Game DevelopmentGame AI

Also known as FSM, State Machine, Finite-State Machine, Finite Automaton

A thing that is always in one of a few states. Rules say when it changes.

Think of it like

Think of it like a traffic light. It is always in one colour, and it changes by fixed rules.

Example

Jack's enemy has three states. Patrol becomes chase when it sees the player, and chase becomes attack when close.

Why it matters

It keeps behaviour simple to read and debug. You always know what state a thing is in.

Definition

A finite state machine is a way to model something that is always in exactly one of a few states. Rules say when it moves from one state to another. A guard might patrol, chase or attack. Seeing the player moves it from patrol to chase. Games use them for enemies, menus and the player's moves. They are used well beyond games too.

Example code

python
if state == "patrol" and sees_player:
    state = "chase"
elif state == "chase" and close:
    state = "attack"
Each rule moves the guard from one state to the next.
The left panel: the guard's three states and the rules between them.

Common mistake

Adding states until it is a tangle. Past a dozen or so, other tools fit better.

Key takeaways

  1. 1
    One state at a time. It is always in exactly one state.
  2. 2
    Clear rules. Each change has a reason.
  3. 3
    Not just games. Menus, parsers and traffic lights use them.