M1D26 – Conditional Logic
Date: July 11, 2023
else
and elseif
var name;
function setup()
{
createCanvas(512,512);
name = "Simon";
if(name == "Simon")
{
console.log("Hello Simon!");
}
else if(name == "Samantha")
{
console.log("Hello Samantha");
}
else if(name == "Scott")
{
console.log("Hello Scott");
}
else if(name == "Sabina")
{
console.log("Hello Sabina");
}
else
{
console.log("Hey I don't know you");
}
}
if(gameState == 0)
{
gameState = 1;
countdown = 1000;
}
else if(gameState == 1)
{
if(key == secretKey)
{
gameState = 3;
}
else if(key == hotKey)
{
countdown += 15;
}
else
{
if(floor(random(0,5)) == 0)
{
gameState = 2;
}
}
}
else if(gameState == 2)
{
gameState = 0;
}
else if(gameState == 3)
{
gameState = 0;
}
else if
Allows us to set up multiple conditions for a chain together
if(/*condition*/)
{
//action 1
}
else if(/*condition 2*/)
{
//action 2
}
else if(/*condition 3*/)
{
//action 3
}
else //other conditions
//action 4, if no conditions are met
}
Rule in nesting – if the first action happens, it will no longer check the succeeding conditions. If two conditions is mandatory, nest the second set of conditions separately.
||
and &&
Logical operation || (OR)
if(A || B) //A or B
}
//action
{
//example
if(gameState == 0)
{
gameState = 1;
countdown = 200;
}
else if(gameState == 1)
{
if(key == secretKey)
{
gameState = 3;
}
else if(key == hotKey || key == hotKey1 || key == hotKey2)
{
countdown += 15;
}
else if(random() > 0.5)
{
//
}
}
else if(gameState == 2)
{
gameState = 0;
}
else if(gameState == 3)
{
gameState = 0;
}
When working on same conditions, full conditions must be written. role == A || role == B
and not role == A || B
Logical Operator && (or)
if(role == A && role == B)
{
//action
}
Variables normally cannot have two values at the same time.
Leave a Reply