Conditionals
Teach your code to make decisions.
So far your sketches do the same thing every frame. Conditionals let your program choose what to do based on what's happening — where the mouse is, how many frames have passed, whether a value crossed a line.
The if Statement
An if runs a block of code only when a condition is true:
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Turn the circle coral only on the right half
if mouseX > width / 2 {
fill(coral)
} else {
fill(rgb(100, 180, 250))
}
circle(mouseX, 100, 40)
}Move your mouse across the canvas — the color flips when you cross the middle.
else and else if
Add else for "otherwise", and chain else if to test several cases in order. The first matching branch wins; the rest are skipped.
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
let zone = mouseX / width * 3
if zone < 1 {
fill(coral)
} else if zone < 2 {
fill(rgb(140, 200, 100))
} else {
fill(rgb(100, 180, 250))
}
circle(mouseX, 100, 40)
}else if (two words), not elif. If you slip up, Bloom's error system will gently point you to the right keyword.
Comparisons
Conditions are usually built from comparisons. Each one is either true or false:
==equal to (two equals signs — one is assignment)!=not equal to<less than<=less than or equal>greater than>=greater than or equal
= stores a value; == compares two values. Writing if x = 5 is almost always a mistake, so Bloom catches it during parsing and suggests ==. You can read exactly how that check works on the parser internals page.
Combining Conditions
Use the words and, or, and not to combine conditions. Bloom spells these out as words instead of symbols like && or ||.
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
// Highlight only when the mouse is inside a center box
let insideX = mouseX > 100 and mouseX < 200
let insideY = mouseY > 60 and mouseY < 140
if insideX and insideY {
fill(coral)
} else {
fill(rgb(70, 70, 90))
}
rect(100, 60, 100, 80)
}Booleans
A condition's result is a boolean — the value true or false. You can store one in a variable and use it later, which often makes code easier to read:
let growing = true
let size = 20
fn setup() {
size(300, 200)
}
fn draw() {
background(rgb(30, 30, 40))
if growing {
size = size + 1
} else {
size = size - 1
}
// Flip direction at the edges
if size > 80 or size < 20 {
growing = not growing
}
fill(coral)
circle(150, 100, size)
}nil, false, and 0 as false; everything else (including empty strings and empty arrays) is true. The same rule is shared by both ways Bloom runs your code — see how the two backends agree.