<aside> ⭐ We demonstrate how we take a state transition diagram → write working p5.js code with it.
</aside>
We will use Rain, Edith, and Ashlyn’s state transition diagram from last year as the example:
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.
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 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 happiness = 0; //neutral happiness
let lightLevel = 255; //max brightness
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:
NORMAL
<> SLEEPY
<> SLEEPING
HAPPY
<> NORMAL
<> ANGRY
<> APPEASED
NORMAL
<> DANCING
lightLevel
for NORMAL
<> SLEEPY
<> SLEEPING