# AI state machine a classical patrol / chase / attack / return enemy ```{raw} html ▶ Run in browser ``` **Tags:** `ai` `state-machine` `2d` A finite-state machine drives an enemy through four plain-Python states: PATROL walks a waypoint loop, CHASE closes in while the player is inside the vision radius with clear line of sight (a smoke cloud blocks sight, not movement), ATTACK strikes on a cooldown at close range, and RETURN walks back to the route once the player escapes. The live state hangs above the enemy and every transition lands in an on-screen log. WASD or arrows move the player. ## What it demonstrates - A hand-rolled FSM: one small class per state with enter/update hooks, and a dict of named states on the enemy. No behaviour trees, no LLM, no engine magic; this is the classical counterpoint to the LLM examples beside it. - Transitions as data: each update returns the next state's name (or None), and the enemy logs every edge through a callback. - Perception with hysteresis: a vision radius to acquire, a larger radius to lose, and a segment-vs-rect line-of-sight test through a sight blocker. Controls: WASD / arrow keys - move the player ESC - quit Run: uv run python examples/features/ai/state_machine.py Headless self-check: uv run python examples/features/ai/state_machine.py --test ## Source ```{literalinclude} ../../examples/features/ai/state_machine.py :language: python :linenos: ```