Lesson 3.4

Boolean Variables

Watch: Boolean Variables - p5.js Tutorial

Video for 3.4:

When we assign a value to a variable, does it always have to be a number?

No. It can be different types of data. We started with numbers in these lessons because they are useful and more familiar from our math experience.

Another useful type of data is called a Boolean, and unlike numbers which can have infinitely different values, the Boolean data type can only have one of two possible values, true or false.

In the conditional expressions we used earlier, the conditional statements evaluated to the Boolean data type, true or false.

For example, if (5 > 2) { do something;} becomes if (true) { do something;} and therefore the block of code is evaluated.

Here is a more concrete example. The following code would draw and ellipse.

A more practical example -

Imagine we would like to change the background of a sketch from black to yellow (as if the lights came on) and back to black, every time the user clicks the mouse.

We declare a variable on and initialize it to the value false. We will use the value of this variable, true or false corresponding to on or off, to control the background.

If we want two or more conditions to be met in order to run a block of code we use the logical operator and which is written as &&. The following checks if ball.x is between 10 and 100.

When the program starts the lights are off.

Since we initialized the variable with false the background will be background(0) or black.

We would like to change the variable from false to true with a mouse click. We can do that by calling mousePressed() which changes the value of on from false to true. This turns the lights on. Clicking again turns the value of on back to false and thus turns the lights off.

Example 3.4.1: The background toggles between black and yellow when the mouse is pressed.

Example 3.4.1

We can improve this by having the background only toggle between black and yellow when the mouse is pressed and when the mouse is within the boundaries of a rectangle that acts as a button.

We will also need to add the rectangle that looks like a button in draw().

Here is the completed example.

Example 3.4.1

Example 3.4.2: The background toggles between black and yellow when the mouse is pressed within a button at the center of the canvas.

Example 3.4.2:

Exercise 3.4a: Change the pong game so that the ball is not moving initially, and toggles between moving and not moving with every mouse click.

Exercise 3.4a: