Intermediate

State Machines

Finite state machines are one of the simplest and most widely used AI patterns in games, defining character behavior as a set of states and transitions.

Finite State Machines (FSM)

A finite state machine consists of a finite set of states, transitions between those states, and actions associated with each state. An agent is always in exactly one state at a time and transitions between states based on conditions.

Python - Simple FSM
class StateMachine:
    def __init__(self):
        self.states = {}
        self.current_state = None

    def add_state(self, name, state):
        self.states[name] = state

    def set_state(self, name):
        if self.current_state:
            self.current_state.exit()
        self.current_state = self.states[name]
        self.current_state.enter()

    def update(self, agent):
        if self.current_state:
            self.current_state.execute(agent)

class PatrolState:
    def enter(self): print("Starting patrol")
    def execute(self, agent):
        agent.move_to_next_waypoint()
        if agent.can_see_enemy():
            agent.fsm.set_state("chase")
    def exit(self): print("Stopping patrol")

class ChaseState:
    def enter(self): print("Chasing enemy!")
    def execute(self, agent):
        agent.move_toward_enemy()
        if agent.in_attack_range():
            agent.fsm.set_state("attack")
        elif not agent.can_see_enemy():
            agent.fsm.set_state("patrol")
    def exit(self): pass

Hierarchical State Machines (HFSM)

As FSMs grow, the number of transitions explodes. Hierarchical FSMs solve this by nesting state machines within states. A "Combat" super-state might contain sub-states like "Aiming", "Shooting", and "Reloading".

  • Super-states: High-level states that contain their own sub-state machines.
  • Shared transitions: Transitions defined at the super-state level apply to all sub-states (e.g., "if health is zero, go to Dead").
  • History states: Remember which sub-state was active when leaving a super-state, so you can resume where you left off.

When to Use FSMs vs Behavior Trees

CriteriaUse FSMUse Behavior Trees
ComplexitySimple AI with few statesComplex AI with many behaviors
Team sizeSmall teams, quick prototypingLarger teams, designers editing AI
ReactivityEvent-driven transitionsPriority-based re-evaluation each tick
ExamplesDoors, elevators, simple enemiesSquad AI, boss fights, companion NPCs

Common Game AI State Patterns

  • Patrol → Alert → Chase → Attack: Classic stealth game enemy loop.
  • Idle → Wander → Interact: Civilian NPC in an open world.
  • Spawn → Approach → Attack → Retreat → Die: Wave-based enemy lifecycle.
  • Search → Engage → Disengage → Resupply: Tactical shooter AI with resource management.
Key takeaway: FSMs are simple, intuitive, and perfect for straightforward AI behaviors. Use hierarchical FSMs to manage complexity, and consider switching to behavior trees when the number of states and transitions becomes difficult to manage.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.