Detecting Sequences
Detecting Sequences
This tutorial shows how to detect whether the user has performed a set of actions in sequence — starting with simple if/switch approaches and progressing to array and string-based strategies.
Use the ◀ ▶ buttons or arrow keys to step through the stages. Press keys inside the canvas to interact. Drag any number in the code to adjust it live.
Detect whether the user has performed a set of actions in sequence.
In this example, we will test whether the user is pressing a sequence of keys in order. The same logic can be used to detect other sequences, such as whether the user has clicked on a sequence of buttons, or moved the mouse into a sequence of regions of the canvas, or moved their hand in PoseNet through a sequence of positions.
This step sets up a “mode” variable. Eventually this will be used to display information about whether the user has matched or failed to match the sequence. In this step, it simply displays the most recent key that is pressed.
let mode = "Initial state";
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(100);
translate(width / 2, height / 2);
textAlign(CENTER, CENTER);
textSize(50);
fill(200);
text(mode, 0, 0);
}
function keyPressed() {
mode = key;
} Try it on OpenProcessing: Detecting Sequences