Making Decisions
Learn how to use if, else, and comparisons to make your programs react to what's happening.
An if statement lets your program make decisions. You give it a condition — something that's either true or false — and the code inside only runs when the condition is true. Here we check if mouseX is past the middle of the screen. The > symbol means "greater than".
Try it!Try changing the 200 to 100. Now the color changes much earlier — can you see why?
The else block runs when the condition is false. This gives you two choices: "if this, do A — otherwise, do B." Let's use mouseIsPressed to toggle between two visual states.
Try it!Try making the shape grow bigger when pressed — change the circle radius to 100!
Use else if to check multiple conditions in order. The first one that's true wins! You can also combine conditions with && (and) or || (or). Here we split the screen into three colored zones.
Try it!Add a 4th zone by splitting the screen into quarters instead of thirds!
Let's combine everything to build an interactive button! We check if the mouse is inside the button rectangle using && (and) to combine four conditions: is mouseX between left and right, AND is mouseY between top and bottom? Then we also check mouseIsPressed for the click state.
What to try next
- Make the button change to a different color each time you click it
- Add a second button that resets the click counter to 0
- Create a traffic light that cycles through red, yellow, green when clicked
- Build a simple quiz: show a question and highlight the correct answer on hover