5

Conditionals

That language is an instrument of human reason, and not merely a medium for the expression of thought, is a truth generally admitted.

—George Boole

The way I feel about music is that there is no right and wrong. Only true and false.

—Fiona Apple

In this chapter:

 Boolean expressions

 Conditional statements: How a program produces different results based on varying circumstances

 If, else if, else

 Relational and logical operators

5-1 Boolean expressions

What’s your favorite kind of test? Essay format? Multiple choice? In the world of computer programming, one only takes one kind of test: a boolean test — true or false. A boolean expression (named for mathematician George Boole) is an expression that evaluates to either true or false. Let’s look at some common language examples:

 My favorite color is pink. → true

 I am afraid of computer programming. → false

 This book is a hilarious read. → false

In the formal logic of computer science, relationships between numbers are tested.

 15 is greater than 20 → false

 5 equals 5 → true

 32 is less than or equal to 33 → true

In this chapter, I will show how to use a variable in a boolean expression, allowing a sketch to take different paths depending on the current value stored in the variable.

 x > 20 → depends on current value of x

 y == 5 → depends on current value of y

 z <= 33 → depends on current value of z

The following operators can be used in a boolean expression.

Relational operators

>greater than
<less than
>=greater than or equal to
<=less than or equal to
==equal to
!=not equal to

5-2 Conditionals: if, else, else if

Boolean expressions (often referred to as “conditionals”) operate within the sketch as questions. Is 15 greater than 20? If the answer is yes (i.e., true), you can choose to execute certain instructions (such as draw a rectangle); if the answer is no (i.e., false), those instructions are ignored. This introduces the idea of branching; depending on various conditions, the program can follow different paths.

In the physical world, this might amount to instructions like so:

If I am hungry then eat some food, otherwise if I am thirsty, drink some water, otherwise, take a nap.

In Processing, you might have something more like:

If the mouse is on the left side of the screen, draw a rectangle on the left side of the screen.

Or, more formally, with the output shown in Figure 5-1,

f05-01-9780123944436

Figure 5-1

if (mouseX < width/2) {

 fill(255);

 rect(0, 0, width/2, height);

}

The boolean expression and resulting instructions in the above source code is contained within a block of code with the following syntax and structure:

if (boolean expression) {

 // code to execute if boolean expression is true

}

The structure can be expanded with the keyword else to include code that is executed if the boolean expression is false. This is the equivalent of “otherwise, do such and such.”

if (boolean expression) {

 // code to execute if boolean expression is true

} else {

 // code to execute if boolean expression is false

}

For example, I could say the following, with the output shown in Figure 5-2

f05-02-9780123944436

Figure 5-2

.

If the mouse is on the left side of the screen, draw a white background, otherwise draw a black background.

if (mouseX < width/2) {

 background(255);

} else {

 background(0);

}

Finally, for testing multiple conditions, you can employ an else if. When an else if is used, the conditional statements are evaluated in the order presented. As soon as one boolean expression is found to be true, the corresponding code is executed and the remaining boolean expressions are ignored. See Figure 5-3.

f05-03-9780123944436

Figure 5-3

if (boolean expression #1) {

 // code to execute if boolean expression #1 is

true

} else if (boolean expression #2) {

 // code to execute if boolean expression #2 is

true

} else if (boolean expression #n) {

 // code to execute if boolean expression #n is

true

} else {

 // code to execute if none of the above

 // boolean expressions are true

}

Taking the simple mouse example a step further, I could say the following, with results shown in Figure 5-4

f05-04-9780123944436

Figure 5-4

.

If the mouse is on the left third of the window, draw a white background, if it’s in the middle third, draw a gray background, otherwise, draw a black background.

if (mouseX < width/3) {

 background(255);

} else if (mouseX < 2*width/3) {

 background(127);

} else {

 background(0);

}

Exercise 5-1

Consider a grading system where numbers are turned into letters. Fill in the blanks in the following code to complete the boolean expression.

in05-01-9780123944436

u05-01-9780123944436

It’s worth pointing out that in Exercise 5-2 on page 71 when I tested for equality I had to use two equal signs. This is because, when programming, asking if something is equal is different from assigning a value to a variable.

Exercise 5-2

Examine the following code samples and determine what will appear in the message window. Write down your answer and then execute the code in Processing to compare.

in05-01-9780123944436

Problem #1: Determine if a number is between 0 and 25, 26 and 50, or greater than 50.

int x = 75;int x = 75;
if (x > 50) {if(x > 25) {
 println(x + “ > 50!”); println(x + “ > 25!”);
} else if (x > 25) {} else if (x > 50) {
 println(x + “ > 25!”); println(x + “ > 50!”);
} else {} else {
 println(x + “ <= 25!”); println(x + “ <= 25!”);
}}
OUTPUT: ___________________OUTPUT: ___________________

Although the syntax is correct, what is problematic about the code in column two above?

Problem #2: If a number is 5, change it to 6. If a number is 6, change it to 5.

int x = 5;int x = 5;
println(“x is now: “ + x);println(“x is now: “ + x);
if (x == 5) {if (x == 5) {
 x = 6; x = 6;
}} else if (x == 6) {
if (x == 6) { x = 5;
 x = 5;}
}
println(“x is now: “ + x);println(“x is now: “ + x);
OUTPUT: ___________________OUTPUT: ___________________

Although the syntax is correct, what is problematic about the code in column one above?

u05-02-9780123944436

5-3 Conditionals in a sketch

Let’s look at a very simple example of a program that performs different tasks based on the result of certain conditions. The pseudocode is below.

Step 1. Create variables to hold on to red, green, and blue color components. Call them r, g, and b.

Step 2. Continuously draw the background based on those colors.

Step 3. If the mouse is on the right-hand side of the screen, increment the value of r, if it’s on the left-hand side decrement the value of r.

Step 4. Constrain the value r to be within 0 and 255.

This pseudocode is implemented in Processing in Example 5-1.

Example 5-1

Conditionals

u05-04-9780123944436
u05-03-9780123944436

Figure 5-5

Constraining the value of a variable, as in Step 4, is a common problem. Here, I do not want color values to increase to unreasonable extremes. In other examples, you might want to constrain the size or location of a shape so that it does not get too big or too small, or wander off the screen.

While using if statements is a perfectly valid solution to the constrain problem, Processing does offer a function entitled constrain() that will get you the same result in one line of code.

u05-05-9780123944436

constrain() takes three arguments: the value you intend to constrain, the minimum limit, and the maximum limit. The function returns the “constrained” value and is assigned back to the variable r. (Remember what it means for a function to return a value? See the discussion of random().)

Getting into the habit of constraining values is a great way to avoid errors; no matter how sure you are that your variables will stay within a given range, there are no guarantees other than constrain() itself. And someday, as you work on larger software projects with multiple programmers, functions such as constrain() can ensure that sections of code work well together. Handling errors before they happen in code is emblematic of good style.

Let’s make my first example a bit more advanced and change all three color components according to the mouse location and click state. Note the use of constrain() for all three variables. The system variable mousePressed is true or false depending on whether the user is holding down the mouse button.

Example 5-2

More conditionals

u05-07-9780123944436
u05-06-9780123944436

Figure 5-6

Exercise 5-3

Move a rectangle across a window by incrementing a variable. Start the shape at x coordinate 0 and use an if statement to have it stop at coordinate 100. Rewrite the sketch to use constrain() instead of the if statement. Fill in the missing code.

in05-01-9780123944436

// Rectangle starts at location x

float x = 0;

void setup() {

 size(200, 200);

}

void draw() {

 background(255);

 // Display object

 fill(0);

 rect(x, 100, 20, 20);

 // Increment x

 x = x + 1;

 ___________________________

 ___________________________

 ___________________________

}

5-4 Logical operators

You have conquered the simple if statement:

If my temperature is greater than 98.6, then take me to the doctor.

Sometimes, however, simply performing a task based on one condition is not enough. For example:

If my temperature is greater than 98.6 OR I have a rash on my arm, take me to the doctor.

If I am stung by a bee AND I am allergic to bees, take me to the doctor.

The same idea applies in programming.

If the mouse is on the right side of the screen AND the mouse is on the bottom of the screen, draw a rectangle in the bottom right corner.

Your first instinct might be to write the above code using a nested if statement, like so:

if (mouseX > width/2) {

 if (mouseY > height/2) {

  fill(255);

  rect(width/2,height/2,width/2,height/2);

 }

}

In other words, you would have to get a true answer for two if statements before the code is executed. This works, yes, but can be accomplished in a simpler way using what is called a “logical and,” written as two ampersands (“&&”). A single ampersand (“&”) means something else1 in Processing so make sure you include two!

u05-08-9780123944436

A “logical or” is two vertical bars (a.k.a. two “pipes”) “||”. If you can’t find the pipe, it’s typically on the keyboard as shift-backslash.

u05-09-9780123944436

In addition to && and ||, you also have access to the logical operator “not,” written as an exclamation point: !

If my temperature is NOT greater than 98.6, I won’t call in sick to work.

If I am stung by a bee AND I am NOT allergic to bees, I’ll be fine!

A Processing example is:

If the mouse is NOT pressed, draw a circle, otherwise draw a square.

u05-10-9780123944436

Notice this example could also be written omitting the not, saying:

If the mouse is pressed, draw a square, otherwise draw a circle.

Exercise 5-4

Are the following boolean expressions true or false? Assume variables int x = 5 and int y = 6.

in05-01-9780123944436

!(x > 6)___________________________

(x == 6 && x == 5)___________________________

(x == 6 || x == 5)___________________________

(x > −1 && y < 10)___________________________

Although the syntax is correct, what is flawed about the following boolean expression?

(x > 10 && x < 5)___________________________

5-5 Multiple rollovers

Let’s solve a simple problem together, a slightly more advanced version of Exercise 5-5 on page 77. Consider the four screenshots shown in Figure 5-7 from one single sketch. A black square is displayed in one of four quadrants, according to the mouse location.

Exercise 5-5

Write a program that implements a simple rollover. In other words, if the mouse is over a rectangle, the rectangle changes color. Here is some code to get you started. (How might you do this for a circle?)

in05-01-9780123944436

int x = 50;

int y = 50;

int w = 100;

int h = 75;

void setup() {

 size(200, 200);

}

void draw() {

 background(255);

 stroke(0);

 if ___________ &&___________ && ___________ && ___________) {

 ______________________

 } ___________ {

 ___________

 }

 rect(x, y, w, h);

}

f05-05-9780123944436

Figure 5-7

Let’s first write the logic of the program in pseudocode (i.e., English).

Setup:

1. Set up a window of 200 × 200 pixels.

Draw:

1. Draw a white background.

2. Draw horizontal and vertical lines to divide the window in four quadrants.

3. If the mouse is in the top left corner, draw a black rectangle in the top left corner.

4. If the mouse is in the top right corner, draw a black rectangle in the top right corner.

5. If the mouse is in the bottom left corner, draw a black rectangle in the bottom left corner.

6. If the mouse is in the bottom right corner, draw a black rectangle in the bottom right corner.

For instructions 3-6, I’ll ask the question: “How do you know if the mouse is in a given corner?” To accomplish this, you need to develop a more specific if statement. For example, you might say: “If the mouseX location is greater than 100 pixels and the mouseY location is greater than 100 pixels, draw a black rectangle in the bottom right corner. As an exercise, you may want to try writing this program yourself based on the above pseudocode. The answer, for your reference, is given in Example 5-3.

Example 5-3

Rollovers

u05-11-9780123944436

in05-01-9780123944436Exercise 5-6: Rewrite Example 5-3 so that the squares fade from white to black when the mouse leaves their area. Hint:you need four variables, one for each rectangle’s color.

5-6 Boolean variables

The natural next step up from programming a rollover is a button. After all, a button is just a rollover that responds when clicked. Now, it may feel ever so slightly disappointing to be programming rollovers and buttons. Perhaps you’re thinking: “Can’t I just select ‘Add Button’ from the menu or something?” For us, right now, the answer is no. Yes, I will eventually cover how to use code from a library (and you might use a library to make buttons in your sketches more easily), but there is value in learning how to program GUI (graphical user interface) elements from scratch.

For one, practicing programming buttons, rollovers, and sliders is an excellent way to learn the basics of variables and conditionals. And two, using the same old buttons and rollovers that every program has is not terribly exciting. If you care about and are interested in developing new interfaces, understanding how to build an interface from scratch is a skill you will need.

OK, with that out of the way, I am going to look at how to use a boolean variable to program a button. A boolean variable (or a variable of type boolean) is a variable that can only be true or false. Think of it as a switch. It is either on or off. Press the button, turn the switch on. Press the button again, turn it off. I just used a boolean variable in Example 5-2: the built-in variable mousePressed. mousePressed is true when the mouse is pressed and false when the mouse is not.

And so my button example will include one boolean variable with a starting value of false (the assumption being that the button starts in the off state).

u05-12-9780123944436

In the case of a rollover, any time the mouse hovered over the rectangle, it turned white. The sketch will turn the background white when the button is pressed and black when it is not.

u05-13-9780123944436

I can then check to see if the mouse location is inside the rectangle and if the mouse is pressed, setting the value of button to true or false accordingly. Here is the full example:

Example 5-4

Hold down the button

u05-14-9780123944436

This example simulates a button connected to a light that is only on when the button is pressed. As soon as you let go, the light goes off. While this might be a perfectly appropriate form of interaction for some instances, it’s not what I am really going for in this section. What I want is a button that operates like a switch; when you flip the switch (press the button), if the light is off, it turns on. If it’s on, it turns off.

For this to work properly, I must check to see if the mouse is located inside the rectangle inside mousePressed() rather than as above in draw(). By definition, when the user clicks the mouse, the code inside mousePressed() is executed once and only once (see Section 3-4 on page 42). When the mouse is clicked, I want the switch to turn on or off (once and only once).

I now need to write some code that “toggles” the switch, changes its state from on to off, or off to on. This code will go inside mousePressed().

If the variable button equals true, it should be set to false. If it is false, it should be set to true.

u05-15-9780123944436

There is a simpler way to go which is the following:

u05-16-9780123944436

Here, the value of button is set to not itself. In other words, if the button is true then I set it to not true (false). If it is false then I set it to not false (true). Armed with this odd but effective line of code, you are ready to look at the button in action in Example 5-5.

Example 5-5

Button as switch

u05-18-9780123944436
u05-17-9780123944436

Figure 5-8

Exercise 5-7

Why doesn’t the following code work properly when it’s moved to draw()?

in05-01-9780123944436

if (mouseX > x && mouseX < x+w &&

 mouseY > y && mouseY < y+h && mousePressed) {

  button = !button;

}

Exercise 5-8

Example 4-3 in the previous chapter moved a circle across the window. Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable.

in05-01-9780123944436

boolean ___________ =___________;

int circleX = 0;

int circleY = 100;

void setup() {

 size(200, 200);

}

void draw() {

 background(100);

 stroke(255);

 fill(0);

 ellipse(circleX, circleY, 50, 50);

 ___________________________

 ___________________________

 ___________________________

}

void mousePressed() {

 ___________________________

}

5-7 A bouncing ball

It’s time again to return to my friend Zoog. Let’s review what you have done so far. First, you learned to draw Zoog with shape functions available from the Processing reference. Afterward, you realized you could use variables instead of hard-coded values. Having these variables allowed you to move Zoog. If Zoog’s location is x, draw it at x, then at x + 1, then at x + 2, and so on.

It was an exciting, yet sad moment. The pleasure you experienced from discovering the motion was quickly replaced by the lonely feeling of watching Zoog leave the screen. Fortunately, conditional statements are here to save the day, allowing me to ask the question: Has Zoog reached the edge of the screen? If so, turn Zoog around!

To simplify things, let’s start with a simple circle instead of Zoog’s entire pattern.

Write a program where Zoog (a simple circle) moves across the screen horizontally from left to right. When it reaches the right edge it reverses direction.

From the previous chapter on variables, you know you need global variables to keep track of Zoog’s location.

int x = 0;

Is this enough? No. In the previous example Zoog always moved one pixel.

x = x + 1;

This tells Zoog to move to the right. But what if I want it to move to the left? Easy, right?

x = x − 1;

In other words, sometimes Zoog moves with a speed of “+1” and sometimes “−1.” The speed of Zoog varies. Yes, bells are ringing. In order to switch the direction of Zoog’s speed, I need another variable: speed.

u05-19-9780123944436

Now that I have variables, I can move on to the rest of the code. Assuming setup() sets the size of the window, I can go directly to examining the steps required inside of draw(). I can also refer to Zoog as a ball in this instance since I am just going to draw a circle.

u05-20-9780123944436

Elementary stuff. Now, in order for the ball to move, the value of its x location should change each cycle through draw().

x = x + speed;

If you ran the program now, the circle would start on the left side of the window, move toward the right, and continue off the edge of the screen — this is the result I achieved in Chapter 4. In order for it to turn around, I need a conditional statement.

If the ball goes off the edge, turn the ball around.

Or more formally…

If x is greater than width, reverse speed.

u05-21-9780123944436

Reversing the polarity of a number

When I want to reverse the polarity of a number, I mean that I want a positive number to become negative and a negative number to become positive. This is achieved by multiplying by −1. Remind yourself of the following:

 −5 * −1 = 5

 5 * −1 = −5

 1 * −1 = −1

 −1 * −1 = 1

Running the sketch, I now have a circle that turns around when it reaches the right-most edge, but runs off the left-most edge of the screen. I’ll need to revise the conditional slightly.

If the ball goes off either the right or left edge, turn the ball around.

Or more formally…

If x is greater than width or if x is less than zero, reverse speed.

u05-22-9780123944436

Example 5-6 puts it all together.

Example 5-6

Bouncing ball

u05-23-9780123944436

in05-01-9780123944436Exercise 5-9: Rewrite Example 5-6 so that the ball not only moves horizontally, but vertically as well. Can you implement additional features, such as changing the size or color of the ball based on certain conditions? Can you make the ball speed up or slow down in addition to changing direction?

The “bouncing ball” logic of incrementing and decrementing a variable can be applied in many ways beyond the motion of shapes onscreen. For example, just as a square moves from left to right, a color can go from less red to more red. Example 5-7 takes the same bouncing ball algorithm and applies it to changing color.

Example 5-7

“Bouncing” color

u05-25-9780123944436
u05-24-9780123944436

Figure 5-9

Having the conditional statement in your collection of programming tools allows for more complex motion. For example, consider a rectangle that follows the edges of a window.

One way to solve this problem is to think of the rectangle’s motion as having four possible states, numbered 0 through 3. See Figure 5-10.

f05-06-9780123944436

Figure 5-10

 State #0: left to right.

 State #1: top to bottom.

 State #2: right to left.

 State #3: bottom to top.

I can use a variable to keep track of the state number and adjust the (x,y) coordinate of the rectangle according to that state. For example: “If the state equals 2, set x equal to itself minus 1.”

Once the rectangle reaches the endpoint for that state, I can change the state variable. “If the state equals 2: (a) set x equal to itself minus 1, (b) if x is less than zero, set state equal to 3.”

The following example implements this logic.

u05-26-9780123944436

Figure 5-11

Example 5-8

Square following edge, uses a “state” variable

u05-27-9780123944436

5-8 Physics 101

For me, one of the happiest moments of my programming life was the moment I realized I could code gravity. And in fact, armed with variables and conditionals, you are now ready for this moment.

The bouncing ball sketch demonstrated that an object moves by altering its location according to speed.

location = location + speed

Gravity is a force of attraction between all masses. When you drop a pen, the force of gravity from the earth (which is overwhelmingly larger than the pen) causes the pen to accelerate toward the ground. What I must add to the bouncing ball is the concept of “acceleration” (which is caused by gravity, but could be caused by any number of forces). Acceleration increases (or decreases) speed. In other words, acceleration is the rate of change of speed. And speed is the rate of change of location. So I just need another line of code:

speed = speed + acceleration

And now I have a simple gravity simulation.

u05-28-9780123944436

Figure 5-12

Example 5-9

Simple gravity

u05-29-9780123944436

Exercise 5-10

Continue with your design and add some of the functionality demonstrated in this chapter. Some options:

in05-01-9780123944436

 Make parts of your design rollovers that change color when the mouse is over certain areas.

 Move it around the screen. Can you make it bounce off all edges of the window?

 Fade colors in and out.

Here is a simple version with Zoog.

Example 5-10

Zoog and conditionals

u05-30-9780123944436u05-31-9780123944436

1 “&” or “|” are reserved for bitwise operations in Processing. A bitwise operation compares each bit (0 or 1) of the binary representations of two numbers. It’s used in rare circumstances where you require low-level access to bits.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.6.77