...
We use logical operations in everyday life, here are some examples:
When I'm hungry or thirsty, I go to the kitchen and get something
If I have enough money and I have time, then I'll make a trip to India
In p5.js programming language the spelling is different but the logic behind it remains the same.
equal to ===
not equal !=
greater than >
less than <
greater than or equal to >=
less than or equal to <=
logical And &&
logical Or ||
In code it looks like this:
...
Code Block |
---|
let x = true; // Testing if a boolean value is "true" if (test) { stroke(0); point(width / 3, i); } // Testing if a boolean value is "false" // The expression "if(!test)" is equivalent to "if(test == false)" if (!test) { stroke(255); point(width / 4, i); } |
If the first condition is false, we can test new condition with else if. We can keep doing this indefinitely.
Code Block |
---|
const x=10; // Here is a conditional with multiple cases // pay attention to the use of 'else if' if(x === 10) { print("x is the same as 10"); } else if(x === 9) { print("x is the same as 9"); } else if(x === 8) { print("x is the same as 8"); } else { print("x is not 10,9 or 8"); } |
...
For the multiple alternative cases, there is also the switch statement:
Code Block | ||||
---|---|---|---|---|
| ||||
let mode = 0; function setup() { createCanvas(400, 400); } function draw() { switch (mode) { case 0: background(255); break; case 1: background(25); break; case 2: background(92); break; case 3: background(144); break; default: // } //or alternatively using if conditionals /* if (mode == 0) { // ready } else if (mode == 1) { background(25); } else if (mode == 2) { background(92); } else if (mode == 3) { background(144); } */ } |
...
Exercise
Program a drawing app. The colour can be changed with the buttons '1' - '5'. The left mouse button draws and the right mouse button erases the drawing.A possible solution to exercise 4:
Example Solution
Code Block | ||
---|---|---|
| ||
color myColor = color(255, 0, 0);// red by default void setup() { size(600, 600); // def. window size noStroke(); background(255); } void draw() { if (mousePressed && mouseButton == LEFT) { fill(myColor); ellipse(mouseX, mouseY, 15, 15); } if (mousePressed && mouseButton == RIGHT) { fill(255); // white ellipse(mouseX, mouseY, 15, 15); } } void keyPressed() { switch(key) { case '1': myColor = color(255, 0, 0);// red break; case '2': myColor = color(0, 255, 0);// green break; case '3': myColor = color(0, 0, 255);// blue break; case '4': myColor = color(0, 0, 0);// black break; case '5': myColor = color(255, 255, 0);// yellow break; default: println("wrong key"); break; } } |