<aside> ⭐ We demonstrate how we take a state transition diagram → write working p5.js code with it.

</aside>

The State Transition Diagram

We will use Rain, Edith, and Ashlyn’s state transition diagram from last year as the example:

Untitled

What makes a good state transition diagram? A good state transition diagram clearly describes all the possible states of your system, and how states change from one to another. It also does not leave any loose ends. A good state transition diagram enables you to identify the variables (properties) and functions (methods) you will need to write in your program.


1—Identifying variables

Let’s list down the variables we need for this system.

Variable Values
state NORMAL ANGRY APPEASED SLEEPY SLEEPING HAPPY DANCING Use this variable to keep track of the agent’s state.
stateBG DEFAULT DIM DARK DISCO Use this variable to keep track of the background’s state.
lightLevel 0 to 255
value from micro:bit light sensor Use this variable as a property to determine if agent’s state is NORMAL SLEEPY or SLEEPING
timestamp store a time using https://p5js.org/reference/#/p5/millis Some state transitions occur based on timing. We need to use this variable to keep track of time.

We can declare and initialize these variables with the default values when we start the system:

let state = "NORMAL";
let stateBG = "DEFAULT";
let lightLevel = 255; //max brightness
let timestamp = 0;

2—Defining functions

Let’s write some functions to control the state of the agent. These functions make use of the variables we defined earlier. The state transition can be deconstructed into three separate cycles:

  1. NORMAL <> SLEEPY <> SLEEPING
  2. HAPPY <> NORMAL <> ANGRY <> APPEASED
  3. NORMAL <> DANCING

Control lightLevel for NORMAL <> SLEEPY <> SLEEPING