Skip to content

Instantly share code, notes, and snippets.

@golanlevin
Created October 24, 2017 15:04
Show Gist options
  • Save golanlevin/0909e9208fc6abd1307e8021a1995e1b to your computer and use it in GitHub Desktop.
Save golanlevin/0909e9208fc6abd1307e8021a1995e1b to your computer and use it in GitHub Desktop.
Modulo Example from Golan's Coding Train
var nElements = 7;
var myCounter = 0;
var ping = 0;
function setup() {
createCanvas(600, 500);
}
function draw() {
background((255*(1-(ping*=0.95))), 255,255);
displayText();
displayElements();
}
// Increment the counter whenever the user presses a key
function keyPressed() {
myCounter = myCounter + 1;
handleSpecialEvent();
}
// Display each of the elements as little rectangles
function displayElements() {
for (var i = 0; i < nElements; i++) {
var rectX = 100 + (i * 50);
var rectY = height * 0.7;
var rectW = 30;
var rectH = 30;
// Draw one element "specially" --
// the one whose order is equal to the modded counter
if (myCounter % nElements == i) {
rectH = 60;
line(rectX + 15, rectY - 42, 492, 210);
}
fill(0);
rect(rectX, rectY, rectW, rectH);
text(i, rectX + 25, rectY - 10);
}
}
// Display the text
function displayText() {
textSize(30);
textAlign(RIGHT);
fill(140);
text("Press a Key", 500, 50);
text("nElements: " + nElements, 500, 100);
text("myCounter: " + myCounter, 500, 150);
fill(0);
text("myCounter % " + nElements + ": " + (myCounter % nElements), 500, 200);
}
function handleSpecialEvent() {
if (myCounter % nElements == 0) {
// Do something special whenever the modded counter is equal to zero.
// For example you could: Play a bell every n'th keypress!
// In this case, I cause the screen to flash cyan.
print ("SPECIAL THING HAPPENED!");
ping = 1.0;
} else {
print ("normal thing happened.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment