States

A program that behaves differently depending on what happened before

Recap

  • “the program is in one of a few states” is a useful way to think about interactive work, physical or on-screen
  • input handling needs debouncing and edge-detection, or the same button press fires the transition three times
  • today’s crit looks at Studio Brief 2 — the loop closed all the way from sensor to microcontroller to program to physical effect
  • next week composes today’s single state machine into something bigger

Name your states before you write any logic

A state machine starts with a fixed, small list of states — IDLE, WAITING, TRIGGERED, whatever your behaviour actually needs. Write that list down before any logic uses it.

const STATE = { IDLE: "IDLE", WAITING: "WAITING", TRIGGERED: "TRIGGERED" };

One variable, one truth

Hold the current state in exactly one variable. If two variables can disagree about what state you’re in, you don’t have a state machine yet — you have a bug waiting to happen.

The update step decides transitions

function update(state, input) {
  switch (state) {
    case STATE.IDLE:
      return input.triggered ? STATE.WAITING : STATE.IDLE;
    case STATE.WAITING:
      return input.confirmed ? STATE.TRIGGERED : STATE.WAITING;
    default:
      return state;
  }
}

Given the current state and the input this tick, decide whether to transition, and to what. This is the only place state is allowed to change.

Debounce the input, keep render read-only

if (pressed && !wasPressed) transition();

React to the moment a button becomes pressed, not to every tick it’s held down, or one physical press becomes several transitions. Keep the render step read-only too — it only shows what the current state is, and never changes it, so rendering order or frame timing never quietly become part of your logic.

What this can build toward: a prop that cycles named states

A turnstile, a traffic-light-style light, or any small physical or on-screen prop that visibly steps through a named sequence of states on each trigger — the whole build is one variable and one update step.

What this can build toward: a character with idle, walk and jump

An on-screen character whose state machine has exactly three states — IDLE, WALK, JUMP — with input deciding the transitions and the render step just drawing whichever one is current.