Finite State Machines (FSM)
The Problem with "If/Else Spaghetti"
When creating a simple enemy, you might start with a bunch of boolean flags: isChasing,
isAttacking, isPatrolling.
Soon, your code looks like a nightmare of nested if statements.
The solution? Finite State Machines. An FSM ensures an enemy can only be in one state at a time, and clearly defines how to switch between them.
The State Pattern
Instead of one giant update function, we split behaviors into separate classes or objects. Each "State" handles its own update logic.
const PatrolState = {
enter: (enemy) => {
enemy.color = 'green';
enemy.findNextWaypoint();
},
update: (enemy) => {
enemy.moveToWaypoint();
// Transition Condition
if (enemy.canSeePlayer()) {
return 'CHASE'; // Switch state!
}
},
exit: (enemy) => {
console.log("Stopped patrolling");
}
};
Interactive AI Demo
Move your mouse (the "Player") near the Bot. Observe how it switches behavior based on distance.
- Patrol (Green): Moves randomly between waypoints.
- Chase (Orange): Detects player and moves towards them.
- Attack (Red): Close range engage.
The State Machine Manager
To glue it all together, we need a simple manager that handles the current state and switching.
class StateMachine {
constructor(initialState, owner) {
this.currentState = initialState;
this.owner = owner;
this.currentState.enter(this.owner);
}
update() {
// Run current state logic
const nextStateName = this.currentState.update(this.owner);
// Handle transition if a new state is returned
if (nextStateName) {
this.changeState(nextStateName);
}
}
changeState(newStateName) {
this.currentState.exit(this.owner);
this.currentState = States[newStateName];
this.currentState.enter(this.owner);
}
}
Before you continue
Direct answer: A finite state machine makes an enemy choose one named behavior at a time, such as patrol, chase, or return.
What you need first
Basic JavaScript functions and conditions.
After this lesson
You can explain the idea, change the supplied example, and choose the next related lesson.
When to use it
Use explicit states when behavior changes are easy to name. Do not use one large nested conditional for every possible behavior.
Common mistake
Changing state without defining what happens on entry or exit.
Try it and check it
This lesson includes its runnable example or code experiment above. Change one value, run it again, and confirm the visible result changes before moving on.
Real game connection
Read the Gomoku AI build note.
Compatibility: Test in a current Chrome, Firefox, Safari, or Edge browser. Canvas and standard input work broadly in current browsers; audio still needs a user action.
Source and update
Reviewed against MDN Web Docs. Updated 2026-07-14. This page does not claim performance results beyond the local example check.