Skip to content
RoboLearn
Not completed

State machines

Control & autonomyIntermediate30 minBuild a sumo state machine ↓Before this: Conditional logic (if / else)

What you’ll learn

  • What a state machine is
  • How to draw one and turn it into code
  • Why it beats a pile of nested ifs

States and transitions

A robot is always in one state: SEARCH, ATTACK, ESCAPE. Each state has its own simple behaviour. Transitions are the rules for moving between states: “if I see the opponent, go from SEARCH to ATTACK”.

sees opponent
SEARCH ─────────────► ATTACK
▲ ▲ │
│ │ edge clear │ sees edge
│ └──── ESCAPE ◄─────┘
│ ▲
└──────────┘ (from any state: sees edge → ESCAPE)

In code

let state = 'SEARCH';
function loop() {
const edge = !lineLeft() || !lineRight();
if (edge) state = 'ESCAPE'; // top priority transition
if (state === 'SEARCH') {
motors(30, -30);
if (distance() < 180) state = 'ATTACK';
} else if (state === 'ATTACK') {
motors(80, 80);
if (distance() >= 180) state = 'SEARCH';
} else if (state === 'ESCAPE') {
motors(-60, -20);
if (!edge) state = 'SEARCH';
}
}

Why it helps

  • Each state is short and easy to understand.
  • You can print the state to see exactly what the robot thinks it’s doing.
  • Adding a behaviour means adding a state, not untangling ifs.

Finished this lesson?