Creative Coding · Session c12

State & Modes

Teach a program to remember what is happening right now.

A room behaves differently when its light switch is on or off. A game behaves differently when it is playing, paused, won, or lost. That remembered situation is called state. State is just data that answers: what mode are we in right now?

See the idea before the code
☀️ DAY
bright sky
sun visible
tap →
← tap
🌙 NIGHT
dark sky
moon visible
Only one state is active at a time. An event — here, a tap — causes a transition to the other state.

Live sketch — switch the whole world

Tap the scene. One variable changes, but that one change controls the sky, stars, ground, and label.

let mode = 'day'; function setup() { createCanvas(420, 260); } function draw() { if (mode == 'day') { background(120, 210, 255); fill(255, 210, 50); circle(335, 60, 55); } else { background(15, 24, 55); fill(245, 245, 210); circle(335, 60, 48); } fill(mode == 'day' ? '#55a630' : '#183d2d'); rect(0, 185, width, 75); fill(mode == 'day' ? 30 : 255); text('mode: ' + mode, 18, 28); } function mousePressed() { if (mode == 'day') { mode = 'night'; } else { mode = 'day'; } }

Why not use lots of booleans?

A boolean is perfect for one yes/no fact: let paused = false. But a game with playing, won, and lost should use one string such as gameState = 'playing'. If you used three booleans, your program could accidentally be winning and losing at the same time.

Quick check — predict before opening

Question: If mode is currently 'night', what is it after one tap? What about two taps?

Answer: After one tap it is 'day'. After two taps it is back to 'night'. Each event follows one arrow in the diagram.

Challenges — change behaviour, not just colour
  1. Add stars that appear only during 'night'. Put their drawing code inside the night branch.
  2. Add a third state called 'sunset'. Draw its box and arrows on paper before editing the code.
  3. Replace tap-to-toggle with keys: pressing D sets day and pressing N sets night. Use keyPressed().
  4. Add let paused = false. Press the space bar to toggle it, and only move a cloud when paused == false.
  5. Bug hunt: change one comparison from == to =. Observe the strange behaviour, then explain why c11 warned about this exact typo.
Next session → c13: Collisions & Score
State lets a program remember its mode. Next you will make objects notice when they touch and turn that event into a score.
← All lessons
25:00

Ask your tutor