# Finite State Machine (FSM)

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

**Field:** Software Development  
**Category:** Game Development  
**Also known as:** FSM, State Machine, Finite-State Machine, Finite Automaton

## Think of it like

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

## 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

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

## 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.

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Non-Player Character (NPC)](https://learn.benibix.com/term/development/non-player-character)
- [Pathfinding](https://learn.benibix.com/term/development/pathfinding)
- [Algorithm](https://learn.benibix.com/term/development/algorithm)
- [Graph (Data Structure)](https://learn.benibix.com/term/development/graph)

![Two panels. On the left, a finite state machine has three states: Patrol, Chase (lit up) and Attack. Patrol goes to Chase when the guard sees the player, Chase goes to Attack when close, and Chase goes back to Patrol when the guard loses sight. A note says one state at a time, with a rule for each change. On the right, a grid with a dark wall in the middle shows a path from G, the guard, up, across the top and down to P, the player, going round the wall.](https://learn.benibix.com/diagrams/dev2-npc-brain.svg)

---

Source: https://learn.benibix.com/term/development/finite-state-machine
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
