4.1 What is a Variable?
The computer has memory. Why do we call it memory? Because it is what the computer uses to remember stuff it needs.
Technically speaking, a variable is a named pointer to a location in the computer’s memory ( “memory address ” ) where data is stored. Since computers only process information one instruction at a time, a variable allows a programmer to save information from one point in the program and refer back to it at a later time. For a Processing programmer, this is incredibly useful; variables can keep track of information related to shapes: color, size, location. Variables are exactly what you need to make a triangle change from
blue to purple, a circle fly across the screen, and a rectangle shrink into oblivion.
Out of all the available analogies, I tend to prefer the piece of paper approach: graph paper .
Imagine that the computer’s memory is a sheet of graph paper and each cell on the graph paper has an address. With pixels, we learned how to refer to those cells by column and row numbers. Wouldn’t it be nice if we could name those cells? With variables, we can.
The computer has memory. Why do we call it memory? Because it is what the computer uses to remember stuff it needs.
Technically speaking, a variable is a named pointer to a location in the computer’s memory ( “memory address ” ) where data is stored. Since computers only process information one instruction at a time, a variable allows a programmer to save information from one point in the program and refer back to it at a later time. For a Processing programmer, this is incredibly useful; variables can keep track of information related to shapes: color, size, location. Variables are exactly what you need to make a triangle change from
blue to purple, a circle fly across the screen, and a rectangle shrink into oblivion.
Out of all the available analogies, I tend to prefer the piece of paper approach: graph paper .
Imagine that the computer’s memory is a sheet of graph paper and each cell on the graph paper has an address. With pixels, we learned how to refer to those cells by column and row numbers. Wouldn’t it be nice if we could name those cells? With variables, we can.
Let’s name one “ Billy’s Score ” (we will see why we are calling
it that in the next section) and give it the value 100. That way, whenever we want to use Billy’s score in a program, we do not have to remember the value 100. It is there in memory and we can ask for it by name. See Figure 4.2 . The power of a variable does not simply rest with the ability to remember a value. The whole point of a variable is that those values vary, and more interesting situations arise as we periodically alter that value. Consider a game of Scrabble between Billy and Jane. To keep track of the score, Jane takes out paper and pencil, and scrawls down two column names: “ Billy’s Score ” and “ Jane’s Score. ” As the two play, a running tally is kept of each player’s points below the headings. If we imagine this game to be virtual Scrabble programmed on a computer, we suddenly can see the concept of a variable that varies emerge. That piece of paper is the computer’s memory and on that paper, information is written— “ Billy’s Score ” and “ Jane’s Score ” are variables, locations in memory where each player’s total points are stored and that change over time. See Figure 4.3 . |
In our Scrabble example, the variable has two elements—a name (e.g., “ Jane’s Score ” ) and a value (e.g., 101). In Processing , variables can hold different kinds of values and we are required to explicitly define the type of value before we can use a given variable.
Task:
Consider the game Pong. What variables would you need to program the game? (If you are not familiar with Pong, see
http://en.wikipedia.org/wiki/Pong ).
Task:
Consider the game Pong. What variables would you need to program the game? (If you are not familiar with Pong, see
http://en.wikipedia.org/wiki/Pong ).
4.2 Variable Declaration and Initialization
Variables can hold primitive values or references to objects and arrays . For now, we are just going to worry about primitives—we will get to objects and arrays later. Primitive values are the building blocks of data on the computer and typically involve a singular
piece of information, like a number or character.
Variables are declared by first stating the type, followed by the name. Variable names must be one word (no spaces) and must start with a letter (they can include numbers, but cannot start with a number). They cannot include any punctuation or special characters, with the exception of the underscore: “_” .
A type is the kind of data stored in that variable. This could be a whole number, a decimal number, or a character. Here are data types you will commonly use:
• Whole numbers, such as 0, 1, 2, 3, -1, -2, and so on are stored as “integers ” and the type keyword for integer is “ int ” .
• Decimal numbers, such as 3.14159, 2.5, and –9.95 are typically stored as “ floating point values ” and the type keyword for floating point is “ float ”.
• Characters, such as the letters ‘ a ’ , ‘b ’ , ‘ c ’ , and so on are stored in variables of type “ char ” and are declared as a letter enclosed in single quotes, that is, ‘ a ’ . Characters are useful when determining what letter on the keyboard has been pressed, and for other uses involving Strings of text
Don’t Forget
• Variables must have a type. Why? This is how the computer knows exactly how much memory should be allocated to store that variable’s data.
• Variables must have a name.
All Primitive Types
• boolean : true or false
• char : a character, ‘ a ’ ,‘b ’ ,‘c ’ , etc.
• byte : a small number, –128 to 127
• short : a larger number, –32768 to 32767
• int : a big number, –2147483648 to 2147483647
• long : a really huge number
• float : a decimal number , such as 3.14159
• double : a decimal number with a lot more decimal places (only necessary for advanced programs requiring mathematical precision).
Once a variable is declared, we can then assign it a value by setting it equal to something. In most cases, if we forget to initialize a variable, Processing will give it a default value, such as 0 for integers, 0.0 for floating points, and so on. However, it is good to get into the habit of always initializing variables in order to avoid confusion.
You initialize variables as the first lines of your code (BEFORE DRAW AND SETUP) and by one of the following ways:
int count;
count = 50; \\This initializes the variable "count" as an integer and sets the value to 50. This is over two lines.
Another way:
int count = 50; \\This does the same as above but only uses one line (THE WAY I PREFER!)
What’s in a name? Tips for choosing good variable names
• Avoid using words that appear elsewhere in the Processing language. In other words, do not call your variable mouseX , there already is one!
• Use names that mean something. This may seem obvious, but it is an important point. For example, if you are using a variable to keep track of score, call it “ score ” and not, say, “ cat. ”
• Start your variable with a lowercase letter and join together words with capitals. Words that start with capitals are reserved for classes (Chapter 8). For example: “ frogColor ” is good, “ Frogcolor ” is not. this canTake some gettingUsedTo but it will comeNaturally soonEnough.
A variable can also be initialized by another variable ( x equals y ), or by evaluating a mathematical expression ( x equals y plus z , etc.). Here are some examples:
When should you use a variable?
Some programmers say that if a number appears three or more times, it should be a variable. Personally, I would say if a number appears once, use a variable. Always use variables!
Example 4-1: Variable declaration and initialization examples
int count = 0; // Declare an int named count, assigned the value 0
char letter = ' a'; // Declare a char named letter, assigned the value 'a'
double d = 132.32; // Declare a double named d, assigned the value 132.32
boolean happy = false; // Declare a boolean named happy, assigned the value false
float x = 4.0; // Declare a float named x, assigned the value 4.0
float y; // Declare a float named y (no assignment)
y = x + 5.2; // Assign the value of x plus 5.2 to the previously declared y
float z = x *y + 15.0; // Declare a variable named z, assign it the value which
// is x times y plus 15.0.
Task:
Write out variable declaration and initialization for the game Pong.
Variables can hold primitive values or references to objects and arrays . For now, we are just going to worry about primitives—we will get to objects and arrays later. Primitive values are the building blocks of data on the computer and typically involve a singular
piece of information, like a number or character.
Variables are declared by first stating the type, followed by the name. Variable names must be one word (no spaces) and must start with a letter (they can include numbers, but cannot start with a number). They cannot include any punctuation or special characters, with the exception of the underscore: “_” .
A type is the kind of data stored in that variable. This could be a whole number, a decimal number, or a character. Here are data types you will commonly use:
• Whole numbers, such as 0, 1, 2, 3, -1, -2, and so on are stored as “integers ” and the type keyword for integer is “ int ” .
• Decimal numbers, such as 3.14159, 2.5, and –9.95 are typically stored as “ floating point values ” and the type keyword for floating point is “ float ”.
• Characters, such as the letters ‘ a ’ , ‘b ’ , ‘ c ’ , and so on are stored in variables of type “ char ” and are declared as a letter enclosed in single quotes, that is, ‘ a ’ . Characters are useful when determining what letter on the keyboard has been pressed, and for other uses involving Strings of text
Don’t Forget
• Variables must have a type. Why? This is how the computer knows exactly how much memory should be allocated to store that variable’s data.
• Variables must have a name.
All Primitive Types
• boolean : true or false
• char : a character, ‘ a ’ ,‘b ’ ,‘c ’ , etc.
• byte : a small number, –128 to 127
• short : a larger number, –32768 to 32767
• int : a big number, –2147483648 to 2147483647
• long : a really huge number
• float : a decimal number , such as 3.14159
• double : a decimal number with a lot more decimal places (only necessary for advanced programs requiring mathematical precision).
Once a variable is declared, we can then assign it a value by setting it equal to something. In most cases, if we forget to initialize a variable, Processing will give it a default value, such as 0 for integers, 0.0 for floating points, and so on. However, it is good to get into the habit of always initializing variables in order to avoid confusion.
You initialize variables as the first lines of your code (BEFORE DRAW AND SETUP) and by one of the following ways:
int count;
count = 50; \\This initializes the variable "count" as an integer and sets the value to 50. This is over two lines.
Another way:
int count = 50; \\This does the same as above but only uses one line (THE WAY I PREFER!)
What’s in a name? Tips for choosing good variable names
• Avoid using words that appear elsewhere in the Processing language. In other words, do not call your variable mouseX , there already is one!
• Use names that mean something. This may seem obvious, but it is an important point. For example, if you are using a variable to keep track of score, call it “ score ” and not, say, “ cat. ”
• Start your variable with a lowercase letter and join together words with capitals. Words that start with capitals are reserved for classes (Chapter 8). For example: “ frogColor ” is good, “ Frogcolor ” is not. this canTake some gettingUsedTo but it will comeNaturally soonEnough.
A variable can also be initialized by another variable ( x equals y ), or by evaluating a mathematical expression ( x equals y plus z , etc.). Here are some examples:
When should you use a variable?
Some programmers say that if a number appears three or more times, it should be a variable. Personally, I would say if a number appears once, use a variable. Always use variables!
Example 4-1: Variable declaration and initialization examples
int count = 0; // Declare an int named count, assigned the value 0
char letter = ' a'; // Declare a char named letter, assigned the value 'a'
double d = 132.32; // Declare a double named d, assigned the value 132.32
boolean happy = false; // Declare a boolean named happy, assigned the value false
float x = 4.0; // Declare a float named x, assigned the value 4.0
float y; // Declare a float named y (no assignment)
y = x + 5.2; // Assign the value of x plus 5.2 to the previously declared y
float z = x *y + 15.0; // Declare a variable named z, assign it the value which
// is x times y plus 15.0.
Task:
Write out variable declaration and initialization for the game Pong.
4.3 Using a Variable
Though it may initially seem more complicated to have words standing in for numbers, variables make our lives easier and more interesting. Let’s take a simple example of a program that draws a circle onscreen.
First without variables:
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(100,100,50,50);
}
Now we have already learned how to use mouseX and mouseY. What we want to do now is create our own variables by following the syntax for declaring and initializing outlined above, placing the variables at the top of our code. You can declare variables elsewhere in your code and we will get into this later. For now to avoid any confusion, all variables should be at the top.
Here is the same code with variables:
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(100);
stroke(255);
fill(0);
ellipse(circleX,circleY,50,50);
}
Running this code, we achieve the same result as in the fi rst example: a circle appears in the middle of the screen. Nevertheless, we should open our hearts and remind ourselves that a variable is not simply a placeholder for one constant value. We call it a variable because it varies . To change its value, we write an assignment operation , which assigns a new value.
Up until now, every single line of code we wrote called a function: line( ), ellipse( ), stroke( ), etc . Variables introduce assignment operations to the mix. Here is what one looks like (it is the same as how we initialize a variable, only the variable does not need to be declared).
variable name =expression
x = 5;
x = a + b;
x = y - 10 * 20;
x = x * 5;
You can also increment a variable:
A common example is incrementation. In the above code, circleX starts with a value of 100. If we want to increment circleX by one, we say circleX equals itself plus one. In code, this amounts to“ circleX = circleX+1; ” .
Let’s try adding that to our program (and let’s start circleX with the value of 0).
Incrementing circle:
int circle X = 0;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(circleX,circleY,50,50);
circleX = circleX + 1;
}
What happens? If you run the example in Processing , you will notice that the circle moves from left to right. Remember, draw( ) loops over and over again, all the while retaining the value of circleX in memory.
Practising how to follow the code step-by-step will lead you to the questions you need to ask before writing your own sketches. Be one with the computer.
Task:
Change the code so that instead of the circle moving from left to right, the circle grows in size. What would you change to have the circle follow the mouse as it grows? How could you vary the speed at which the circle grows? Show an example of an answer to each question.
Here is a "starter code"
int circleSize = 0;
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
fill(175);
____________________________________
____________________________________
}
Though it may initially seem more complicated to have words standing in for numbers, variables make our lives easier and more interesting. Let’s take a simple example of a program that draws a circle onscreen.
First without variables:
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(100,100,50,50);
}
Now we have already learned how to use mouseX and mouseY. What we want to do now is create our own variables by following the syntax for declaring and initializing outlined above, placing the variables at the top of our code. You can declare variables elsewhere in your code and we will get into this later. For now to avoid any confusion, all variables should be at the top.
Here is the same code with variables:
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(100);
stroke(255);
fill(0);
ellipse(circleX,circleY,50,50);
}
Running this code, we achieve the same result as in the fi rst example: a circle appears in the middle of the screen. Nevertheless, we should open our hearts and remind ourselves that a variable is not simply a placeholder for one constant value. We call it a variable because it varies . To change its value, we write an assignment operation , which assigns a new value.
Up until now, every single line of code we wrote called a function: line( ), ellipse( ), stroke( ), etc . Variables introduce assignment operations to the mix. Here is what one looks like (it is the same as how we initialize a variable, only the variable does not need to be declared).
variable name =expression
x = 5;
x = a + b;
x = y - 10 * 20;
x = x * 5;
You can also increment a variable:
A common example is incrementation. In the above code, circleX starts with a value of 100. If we want to increment circleX by one, we say circleX equals itself plus one. In code, this amounts to“ circleX = circleX+1; ” .
Let’s try adding that to our program (and let’s start circleX with the value of 0).
Incrementing circle:
int circle X = 0;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(circleX,circleY,50,50);
circleX = circleX + 1;
}
What happens? If you run the example in Processing , you will notice that the circle moves from left to right. Remember, draw( ) loops over and over again, all the while retaining the value of circleX in memory.
Practising how to follow the code step-by-step will lead you to the questions you need to ask before writing your own sketches. Be one with the computer.
Task:
Change the code so that instead of the circle moving from left to right, the circle grows in size. What would you change to have the circle follow the mouse as it grows? How could you vary the speed at which the circle grows? Show an example of an answer to each question.
Here is a "starter code"
int circleSize = 0;
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
fill(175);
____________________________________
____________________________________
}
4.4 Many Variables
Let’s take the example one step further and use variables for every piece of information we can think of. We will also use floating point values to demonstrate greater precision in adjusting variable values.
Here is a basic layout of 8 variables (THIS WILL NOT WORK AS CODE AS I HAVE USED THE WORDS "change" to represent any number)
float circleX = 0;
float circleY = 0;
float circleW = 50;
float circleH = 100;
float circleStroke = 255;
float circleFill = 0;
float backgroundColor = 255;
float change = 0.5;
// Your basic setup
void setup() {
size(200,200);
smooth();
}
void draw() {
// Draw the background and the ellipse
background(backgroundColor);
stroke(circleStroke);
fill(circleFill);
ellipse(circleX,circleY,circleW,circleH);
// Change the values of all variables
circleX = circleX + change;
circleY = circleY + change;
circleW = circleW + change;
circleH = circleH - change;
circleStroke = circleStroke - change;
circleFill = circleFill + change;
}
Task:
Step 1 : Write code that draws the following screenshots with hard-coded values. (Feel free to use colors instead of grayscale.)
Step 2 : Replace all of the hard-coded numbers with variables.
Step 3 : Write assignment operations in draw( ) that change the value of the variables. For example, “ variable1 variable1 2; ” . Try different expressions and see what happens!
Let’s take the example one step further and use variables for every piece of information we can think of. We will also use floating point values to demonstrate greater precision in adjusting variable values.
Here is a basic layout of 8 variables (THIS WILL NOT WORK AS CODE AS I HAVE USED THE WORDS "change" to represent any number)
float circleX = 0;
float circleY = 0;
float circleW = 50;
float circleH = 100;
float circleStroke = 255;
float circleFill = 0;
float backgroundColor = 255;
float change = 0.5;
// Your basic setup
void setup() {
size(200,200);
smooth();
}
void draw() {
// Draw the background and the ellipse
background(backgroundColor);
stroke(circleStroke);
fill(circleFill);
ellipse(circleX,circleY,circleW,circleH);
// Change the values of all variables
circleX = circleX + change;
circleY = circleY + change;
circleW = circleW + change;
circleH = circleH - change;
circleStroke = circleStroke - change;
circleFill = circleFill + change;
}
Task:
Step 1 : Write code that draws the following screenshots with hard-coded values. (Feel free to use colors instead of grayscale.)
Step 2 : Replace all of the hard-coded numbers with variables.
Step 3 : Write assignment operations in draw( ) that change the value of the variables. For example, “ variable1 variable1 2; ” . Try different expressions and see what happens!
4.5 System Variables
As we saw with mouseX and mouseY , Processing has a set of convenient system variables freely available. These are commonly needed pieces of data associated with all sketches (such as the width of the window, the key pressed on the keyboard, etc.). When naming your own variables, it is best to avoid system variable names, however, if you inadvertently use one, your variable will become primary and override the system one. Here is a list of commonly used system variables (there are more, which you can find in the
Processing reference).
• width —Width (in pixels) of sketch window.
• height —Height (in pixels) of sketch window.
• frameCount —Number of frames processed.• frameRate —Rate that frames are processed (per second).
• screen.width —Width (in pixels) of entire screen.
• screen.height —Height (in pixels) of entire screen.
• key —Most recent key pressed on the keyboard.
• keyCode —Numeric code for key pressed on keyboard.
• keyPressed —True or false? Is a key pressed?
• mousePressed —True or false? Is the mouse pressed?
• mouseButton —Which button is pressed? Left, right, or center?
Following is an example that makes use of some of the above variables; we are not ready to use them all yet, as we will need some more advanced concepts to make use of many features. TRY IT!
void setup() {
size(200,200);
frameRate(30);
}
void draw() {
background(100);
stroke(255);
fill(frameCount/2);
rectMode(CENTER);
rect(width/2,height/2,mouseX + 10,mouseY + 10);
}
void keyPressed() {
println(key);
}
TASK:
Exercise 4-5: Using width and height, recreate the following screenshot. Here’s the catch: the shapes must resize themselves relative to the window size. (In other words, no matter what you specify for size( ) , the result should look identical.)
As we saw with mouseX and mouseY , Processing has a set of convenient system variables freely available. These are commonly needed pieces of data associated with all sketches (such as the width of the window, the key pressed on the keyboard, etc.). When naming your own variables, it is best to avoid system variable names, however, if you inadvertently use one, your variable will become primary and override the system one. Here is a list of commonly used system variables (there are more, which you can find in the
Processing reference).
• width —Width (in pixels) of sketch window.
• height —Height (in pixels) of sketch window.
• frameCount —Number of frames processed.• frameRate —Rate that frames are processed (per second).
• screen.width —Width (in pixels) of entire screen.
• screen.height —Height (in pixels) of entire screen.
• key —Most recent key pressed on the keyboard.
• keyCode —Numeric code for key pressed on keyboard.
• keyPressed —True or false? Is a key pressed?
• mousePressed —True or false? Is the mouse pressed?
• mouseButton —Which button is pressed? Left, right, or center?
Following is an example that makes use of some of the above variables; we are not ready to use them all yet, as we will need some more advanced concepts to make use of many features. TRY IT!
void setup() {
size(200,200);
frameRate(30);
}
void draw() {
background(100);
stroke(255);
fill(frameCount/2);
rectMode(CENTER);
rect(width/2,height/2,mouseX + 10,mouseY + 10);
}
void keyPressed() {
println(key);
}
TASK:
Exercise 4-5: Using width and height, recreate the following screenshot. Here’s the catch: the shapes must resize themselves relative to the window size. (In other words, no matter what you specify for size( ) , the result should look identical.)
4.6 Random: Variety is the spice of life.
So, you may have noticed that the examples so far are a bit, say, humdrum. A circle here. A square here. A grayish color. Another grayish color. There is a method to the madness (or lack of madness in this case). It is much easier to learn the fundamentals by looking at the individual pieces, programs that do one and only one thing. We can then begin to add functionality on top, step by step.
Nevertheless, we have waited patiently through four chapters and we have arrived at the time where we can begin to have a bit of fun. And this fun will be demonstrated via the use of the function random( ) . Consider the code:
float r = 100;
float g = 150;
float b = 200;
float a = 200;
float diam = 20;
float x = 100;
float y = 100;
void setup() {
size(200,200);
background(255);
smooth();
}
void draw() {
// Use those variables to draw an ellipse
stroke(0);
fill(r,g,b,a);
ellipse(x,y,diam,diam);
}
There it is, our dreary circle. Sure, we can adjust variable values and move the circle, grow its size, change its color, and so on. However, what if every time through draw( ) , we could make a new circle, one with a random size, color, and position? The random( ) function allows us to do exactly that.
random( ) is a special kind of function, it is a function that returns a value. We have encountered this before when we used the function abs( ) to calculate the absolute value of a number. Th e idea of a function that calculates a value and returns it will be explored fully later, but we are going to take some time to introduce the idea now and let it sink in a bit. Unlike most of the functions we are comfortable with (e.g., line( ), ellipse( ), and rect( ) ), random( ) does not draw or color a shape on the screen. Instead, random( ) answers a question; it returns that answer to us. Here is a bit of dialogue. Feel free to rehearse it with your friends.
Me : Hey random, what’s going on? Hope you’re well. Listen, I was wondering, could you give me a random number between 1 and 100?
Random : Like, no problem. How about the number 63?
Me : That’s awesome, really great, thank you. OK, I’m off . Gotta draw a rectangle 63 pixels wide, OK?
Now, how would this sequence look in our slightly more formal, Processing environment? The code below the part of “ me ” is played by the variable “ w ” .
float w = random(1,100);
rect(100,100,w,50);
The random( ) function requires two arguments and returns a random floating point number ranging from the first argument to the second. The second argument must be larger than the first for it to work properly. Th e function random( ) also works with one argument by assuming a range between zero and that argument.
In addition, random( ) only returns floating point numbers. This is why we declared “ w ” above as a float. However, if you want a random integer, you can convert the result of the random function to an int .
int w = int(random(1,100));
rect(100,100,w,50);
Notice the use of nested parentheses. This is a nice concept to get used to as it will be quite convenient to call functions inside of functions as we go. The random( ) function returns a float, which is then passed to the int( ) function that converts it to an integer. If we wanted to go nuts nesting functions, we could even condense the above code into one line:
rect(100,100,int(random(1,100)),50);
Incidentally, the process of converting one data type to another is referred to as “ casting. ” In Java (which Processing is based on) casting a float to an integer can also be written this way:
int w = (int) random(1,100);
OK, we are now ready to experiment with random( ) .Below shows what happens if we take every variable associated with drawing the ellipse (fill, location, size) and assign it to a random number each cycle through draw( ) .
Try the code
So, you may have noticed that the examples so far are a bit, say, humdrum. A circle here. A square here. A grayish color. Another grayish color. There is a method to the madness (or lack of madness in this case). It is much easier to learn the fundamentals by looking at the individual pieces, programs that do one and only one thing. We can then begin to add functionality on top, step by step.
Nevertheless, we have waited patiently through four chapters and we have arrived at the time where we can begin to have a bit of fun. And this fun will be demonstrated via the use of the function random( ) . Consider the code:
float r = 100;
float g = 150;
float b = 200;
float a = 200;
float diam = 20;
float x = 100;
float y = 100;
void setup() {
size(200,200);
background(255);
smooth();
}
void draw() {
// Use those variables to draw an ellipse
stroke(0);
fill(r,g,b,a);
ellipse(x,y,diam,diam);
}
There it is, our dreary circle. Sure, we can adjust variable values and move the circle, grow its size, change its color, and so on. However, what if every time through draw( ) , we could make a new circle, one with a random size, color, and position? The random( ) function allows us to do exactly that.
random( ) is a special kind of function, it is a function that returns a value. We have encountered this before when we used the function abs( ) to calculate the absolute value of a number. Th e idea of a function that calculates a value and returns it will be explored fully later, but we are going to take some time to introduce the idea now and let it sink in a bit. Unlike most of the functions we are comfortable with (e.g., line( ), ellipse( ), and rect( ) ), random( ) does not draw or color a shape on the screen. Instead, random( ) answers a question; it returns that answer to us. Here is a bit of dialogue. Feel free to rehearse it with your friends.
Me : Hey random, what’s going on? Hope you’re well. Listen, I was wondering, could you give me a random number between 1 and 100?
Random : Like, no problem. How about the number 63?
Me : That’s awesome, really great, thank you. OK, I’m off . Gotta draw a rectangle 63 pixels wide, OK?
Now, how would this sequence look in our slightly more formal, Processing environment? The code below the part of “ me ” is played by the variable “ w ” .
float w = random(1,100);
rect(100,100,w,50);
The random( ) function requires two arguments and returns a random floating point number ranging from the first argument to the second. The second argument must be larger than the first for it to work properly. Th e function random( ) also works with one argument by assuming a range between zero and that argument.
In addition, random( ) only returns floating point numbers. This is why we declared “ w ” above as a float. However, if you want a random integer, you can convert the result of the random function to an int .
int w = int(random(1,100));
rect(100,100,w,50);
Notice the use of nested parentheses. This is a nice concept to get used to as it will be quite convenient to call functions inside of functions as we go. The random( ) function returns a float, which is then passed to the int( ) function that converts it to an integer. If we wanted to go nuts nesting functions, we could even condense the above code into one line:
rect(100,100,int(random(1,100)),50);
Incidentally, the process of converting one data type to another is referred to as “ casting. ” In Java (which Processing is based on) casting a float to an integer can also be written this way:
int w = (int) random(1,100);
OK, we are now ready to experiment with random( ) .Below shows what happens if we take every variable associated with drawing the ellipse (fill, location, size) and assign it to a random number each cycle through draw( ) .
Try the code
float r;
float g; float b; float a; float diam; float x; float y; void setup() { size(200,200); background(0); smooth(); } void draw() { // Fill all variables with random values r = random(255); g = random(255); b = random(255); a = random(255); diam = random(20); x = random(width); y = random(height); // Use values to draw an ellipse noStroke(); fill(r,g,b,a); ellipse(x,y,diam,diam); } |
4.7 Variable Zoog
We are now ready to revisit Zoog, our alien friend, who was happily following the mouse around the screen when we last checked in. Here, we will add two pieces of functionality to Zoog.
• New feature #1 —Zoog will rise from below the screen and fly off into space (above the screen).
• New feature #2 —Zoog’s eyes will be colored randomly as Zoog moves.
Feature #1 is solved by simply taking the previous program that used mouseX and mouseY and substituting our own variables in their place.
Feature #2 is implemented by creating three additional variables eyeRed, eyeGreen, and eyeBlue that will be used for the fi ll( ) function before displaying the eye ellipses.
Try the following code:
float zoogX;
float zoogY;
float eyeR;
float eyeG;
float eyeB;
void setup() {
size(200,200);
zoogX = width/2; // Zoog always starts in the middle
zoogY = height + 100; // Zoog starts below the screen
smooth();
}
void draw() {
background(255);
// Set ellipses and rects to CENTER mode
ellipseMode(CENTER);
rectMode(CENTER);
// Draw Zoog's body
stroke(0);
fill(150);
rect(zoogX,zoogY,20,100);
// Draw Zoog's head
stroke(0);
fill(255);
ellipse(zoogX,zoogY - 30,60,60);
// Draw Zoog's eyes
eyeR = random(255);
eyeG = random(255);
eyeB = random(255);
fill(eyeR,eyeG,eyeB);
ellipse(zoogX - 19,zoogY - 30,16,32);
ellipse(zoogX + 19,zoogY - 30,16,32);
// Draw Zoog's legs
stroke(150);
line(zoogX - 10,zoogY + 50,zoogX - 10,height);
line(zoogX + 10,zoogY + 50,zoogX + 10,height);
// Zoog moves up
zoogY = zoogY - 1;
}
TASK:
1) Rewrite the code for your character so he slides upwards on the screen, as well as he shakes left and right. HINT: you will have to use random() with zoogX.
2) Using variables and the random( ) function, revise your design from the Lesson One Project to move around the screen, change color, size, location, and so on.
We are now ready to revisit Zoog, our alien friend, who was happily following the mouse around the screen when we last checked in. Here, we will add two pieces of functionality to Zoog.
• New feature #1 —Zoog will rise from below the screen and fly off into space (above the screen).
• New feature #2 —Zoog’s eyes will be colored randomly as Zoog moves.
Feature #1 is solved by simply taking the previous program that used mouseX and mouseY and substituting our own variables in their place.
Feature #2 is implemented by creating three additional variables eyeRed, eyeGreen, and eyeBlue that will be used for the fi ll( ) function before displaying the eye ellipses.
Try the following code:
float zoogX;
float zoogY;
float eyeR;
float eyeG;
float eyeB;
void setup() {
size(200,200);
zoogX = width/2; // Zoog always starts in the middle
zoogY = height + 100; // Zoog starts below the screen
smooth();
}
void draw() {
background(255);
// Set ellipses and rects to CENTER mode
ellipseMode(CENTER);
rectMode(CENTER);
// Draw Zoog's body
stroke(0);
fill(150);
rect(zoogX,zoogY,20,100);
// Draw Zoog's head
stroke(0);
fill(255);
ellipse(zoogX,zoogY - 30,60,60);
// Draw Zoog's eyes
eyeR = random(255);
eyeG = random(255);
eyeB = random(255);
fill(eyeR,eyeG,eyeB);
ellipse(zoogX - 19,zoogY - 30,16,32);
ellipse(zoogX + 19,zoogY - 30,16,32);
// Draw Zoog's legs
stroke(150);
line(zoogX - 10,zoogY + 50,zoogX - 10,height);
line(zoogX + 10,zoogY + 50,zoogX + 10,height);
// Zoog moves up
zoogY = zoogY - 1;
}
TASK:
1) Rewrite the code for your character so he slides upwards on the screen, as well as he shakes left and right. HINT: you will have to use random() with zoogX.
2) Using variables and the random( ) function, revise your design from the Lesson One Project to move around the screen, change color, size, location, and so on.
5 Conditionals5.1 Boolean Expressions
What’s your favorite kind of test? Essay format? Multiple choice? In the world of computer programming, we only take 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:
• I am hungry. → true
• I am afraid of computer programming. → false
• Mr. Martin is hilarious. → true
In the formal logic of computer science, we test relationships between numbers.
• 15 is greater than 20 → false
• 5 equals 5 → true
• 32 is less than or equal to 33 → true
Now we will learn how to use a variable in a boolean expression, allowing our 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.
What’s your favorite kind of test? Essay format? Multiple choice? In the world of computer programming, we only take 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:
• I am hungry. → true
• I am afraid of computer programming. → false
• Mr. Martin is hilarious. → true
In the formal logic of computer science, we test relationships between numbers.
• 15 is greater than 20 → false
• 5 equals 5 → true
• 32 is less than or equal to 33 → true
Now we will learn how to use a variable in a boolean expression, allowing our 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.
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), we 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 , we 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 .
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), we 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 , we 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:
if (mouseX < width/2) {
fill(255);
rect(0,0,width/2,height);
}
How does this work?
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. Th is 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, we could say the following, 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);
}
if (mouseX < width/2) {
fill(255);
rect(0,0,width/2,height);
}
How does this work?
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. Th is 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, we could say the following, 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, we 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 picture to the right 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 our simple mouse example a step further, we could say the following: If the mouse is on the left third of the window, draw a white background, if it is 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); } |
TASK:
Consider a grading system where numbers are turned into letters. Fill in the blanks in the following code to complete the boolean expression such that it assigns values A,B,C,D,F.
**In one conditional statement, you can only ever have one if and one else . However, you can have as many else if ’s as you like!
float grade=random(0,100);
if (_______) {
println( "Assign letter grade A. ");
} else if (________) {
println (________);
} else if (________) {
println(________);
} else if (________) {
println(________);
} else {
println(________);
}
Consider a grading system where numbers are turned into letters. Fill in the blanks in the following code to complete the boolean expression such that it assigns values A,B,C,D,F.
**In one conditional statement, you can only ever have one if and one else . However, you can have as many else if ’s as you like!
float grade=random(0,100);
if (_______) {
println( "Assign letter grade A. ");
} else if (________) {
println (________);
} else if (________) {
println(________);
} else if (________) {
println(________);
} else {
println(________);
}
Task:
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.
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.
Problem #1: Determine if a number is between 0 and 25, 26 and 50, or greater than 50.
int x = 75;
if (x > 50) { println(x + " is greater than 50! " ); } else if (x > 25) { println(x + " is greater than 25! " ); } else { println(x + " is 25 or less! " ); } OUTPUT:____________________ |
int x = 75;
if(x > 25) { println(x + " is greater than 25! " ); } else if (x > 50) { println(x + " is greater than 50! " ); } else { println(x + " is 25 or less! " ); } OUTPUT:____________________ |
Explain why the outputs are different.
Problem #2: If a number is 5, change it to 6. If a number is 6, change it to five.
int x = 5;
println("x is now: " + x); if (x = = 5) { x = 6; } if (x = = 6) { x = 5; } println( "x is now: " + x ); OUTPUT:____________________ |
int x = 5;
println("x is now: " + x); if (x = = 5) { x = 6; } else if (x = = 6) { x = 5; } println( "x is now: " + x); OUTPUT:____________________ |
Explain the differences and any problems with either code.
It is worth pointing out that when we test for equality we must use two equal signs. This is because, when programming, asking if something is equal is different from assigning a value to a variable.
if (x = = y) { \\This would test if x equals y
x = y; \\This makes x equal to y
if (x = = y) { \\This would test if x equals y
x = y; \\This makes x equal to y
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. Our 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 is on the left-hand side decrement the value of r.
Step 4. Constrain the value r to be within 0 and 255.
This turns into the following code:
float r = 150;
float g = 0;
float b = 0;
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(255);
line(width/2,0,width/2,height);
if(mouseX > width/2) {
r = r + 1;
} else {
r = r - 1;
}
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
}
Constraining the value of a variable, as in Step 4, is a common problem. Here, we do not want color values to increase to unreasonable extremes. In other examples, we 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 us the same result in one line of code.
We could constrain with an if and else if statements
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
We could constrain with a constrain function.
r = constrain(r,0,255);
constrain( ) takes three arguments: the value we 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 our 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 our 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.
Try the following code:
float r = 0;
float b = 0;
float g = 0;
\\Three variables for the background color.
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(0);
\\Color the background and draw lines to divide the window into quadrants.
line(width/2,0,width/2,height);
line(0,height/2,width,height/2);
if(mouseX > width/2) {
r = r + 1;
} else {
r = r - 1;
}\\If the mouse is on the right-hand side of the window, increase red. Otherwise, it is on the left-hand side and decrease red.
if (mouseY > height/2) {
b = b + 1;
} else {
b = b - 1;
}\\If the mouse is on the bottom of the window, increase blue. Otherwise, it is on the top and decrease blue.
if (mousePressed) {
g = g + 1;
} else {
g = g - 1;
}\\If the mouse is pressed (using the system variable mousePressed) increase green.
r = constrain(r,0,255);
g = constrain(g,0,255);
b = constrain(b,0,255);
}\\Constrain all color values to between 0 and 255.
Move your mouse around the screen, and try clicking and unclicking.
TASK
Move a rectangle across a window by incrementing a variable. Start the shape at x coordinate 0 and
1)use an if statement to have it stop at coordinate 100.
2)Rewrite the sketch to use constrain( ) instead of the if statement. Fill in the missing code.
// 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;
______________________________________________
______________________________________________
______________________________________________
}
Let’s look at a very simple example of a program that performs different tasks based on the result of certain conditions. Our 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 is on the left-hand side decrement the value of r.
Step 4. Constrain the value r to be within 0 and 255.
This turns into the following code:
float r = 150;
float g = 0;
float b = 0;
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(255);
line(width/2,0,width/2,height);
if(mouseX > width/2) {
r = r + 1;
} else {
r = r - 1;
}
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
}
Constraining the value of a variable, as in Step 4, is a common problem. Here, we do not want color values to increase to unreasonable extremes. In other examples, we 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 us the same result in one line of code.
We could constrain with an if and else if statements
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
We could constrain with a constrain function.
r = constrain(r,0,255);
constrain( ) takes three arguments: the value we 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 our 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 our 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.
Try the following code:
float r = 0;
float b = 0;
float g = 0;
\\Three variables for the background color.
void setup() {
size(200,200);
}
void draw() {
background(r,g,b);
stroke(0);
\\Color the background and draw lines to divide the window into quadrants.
line(width/2,0,width/2,height);
line(0,height/2,width,height/2);
if(mouseX > width/2) {
r = r + 1;
} else {
r = r - 1;
}\\If the mouse is on the right-hand side of the window, increase red. Otherwise, it is on the left-hand side and decrease red.
if (mouseY > height/2) {
b = b + 1;
} else {
b = b - 1;
}\\If the mouse is on the bottom of the window, increase blue. Otherwise, it is on the top and decrease blue.
if (mousePressed) {
g = g + 1;
} else {
g = g - 1;
}\\If the mouse is pressed (using the system variable mousePressed) increase green.
r = constrain(r,0,255);
g = constrain(g,0,255);
b = constrain(b,0,255);
}\\Constrain all color values to between 0 and 255.
Move your mouse around the screen, and try clicking and unclicking.
TASK
Move a rectangle across a window by incrementing a variable. Start the shape at x coordinate 0 and
1)use an if statement to have it stop at coordinate 100.
2)Rewrite the sketch to use constrain( ) instead of the if statement. Fill in the missing code.
// 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
We have conquered the simple if statement:
If my temperature is greater than 98.6, then take me to see 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 see the doctor .
If I am stung by a bee AND I am allergic to bees, take me to see the doctor .
We will commonly want to do the same thing in programming from time to time. 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 .
Our 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, we would have to bypass two if statements before we can reach the code we want to execute. Th is works, yes, but can be accomplished in a simpler way using what we will call a “ logical and, ” written as two ampersands ( “ & & ” ). A single ampersand ( “ & ” ) means something else 1 in Processing so make sure you include two!
|| (logical OR)
&& (logical AND)
! (logical NOT)
A “ logical or ” is two vertical bars (AKA two “ pipes ” ) “ || ” . If you can’t fi nd the pipe, it is typically on the keyboard as shift-backslash.
if (mouseX > width/2 & & mouseY > height/2) {
fill(255);
rect(width/2,height/2,width/2,height/2);
}\\If the mouse is on the right side and on the bottom.
In addition to & & and ||, we 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, do not worry!
A Processing example is:
if (!mousePressed) {
ellipse(width/2,height/2,100,100);
} else {
rect(width/2,height/2,100,100);
}\\If the mouse is NOT pressed, draw a circle, otherwise draw a square .
**! means not. “mousePressed” is a boolean variable that acts as its own boolean expression. Its value is either true or false (depending on whether or not the mouse is currently pressed).
Task:
1) Are the following boolean expressions true or false? Assume variables x =5 and y=6.
!(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) _______________________________
2) 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.
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
if (_______ & & _______ & & _______ & &
_______) {
______
} ______ {
_______
}
rect(x,y,w,h);
}
We have conquered the simple if statement:
If my temperature is greater than 98.6, then take me to see 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 see the doctor .
If I am stung by a bee AND I am allergic to bees, take me to see the doctor .
We will commonly want to do the same thing in programming from time to time. 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 .
Our 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, we would have to bypass two if statements before we can reach the code we want to execute. Th is works, yes, but can be accomplished in a simpler way using what we will call a “ logical and, ” written as two ampersands ( “ & & ” ). A single ampersand ( “ & ” ) means something else 1 in Processing so make sure you include two!
|| (logical OR)
&& (logical AND)
! (logical NOT)
A “ logical or ” is two vertical bars (AKA two “ pipes ” ) “ || ” . If you can’t fi nd the pipe, it is typically on the keyboard as shift-backslash.
if (mouseX > width/2 & & mouseY > height/2) {
fill(255);
rect(width/2,height/2,width/2,height/2);
}\\If the mouse is on the right side and on the bottom.
In addition to & & and ||, we 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, do not worry!
A Processing example is:
if (!mousePressed) {
ellipse(width/2,height/2,100,100);
} else {
rect(width/2,height/2,100,100);
}\\If the mouse is NOT pressed, draw a circle, otherwise draw a square .
**! means not. “mousePressed” is a boolean variable that acts as its own boolean expression. Its value is either true or false (depending on whether or not the mouse is currently pressed).
Task:
1) Are the following boolean expressions true or false? Assume variables x =5 and y=6.
!(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) _______________________________
2) 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.
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
if (_______ & & _______ & & _______ & &
_______) {
______
} ______ {
_______
}
rect(x,y,w,h);
}
5.5 Multiple Rollovers
Let’s solve a simple problem together, a slightly more advanced version. Consider the four screenshots shown from one single sketch. A black square is displayed in one of four quadrants, according to the mouse location.
Let’s solve a simple problem together, a slightly more advanced version. Consider the four screenshots shown from one single sketch. A black square is displayed in one of four quadrants, according to the mouse location.
Let’s first write the logic of our program in pseudocode (i.e., English).
Setup:
1. Set up a window of 200x200 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 through 6, we have to ask ourselves the question: “ How do we know if the mouse is in a given corner? ” To accomplish this, we need to develop a more specific if statement. For example, we would say: “ If the mouse X location is greater than 100 pixels and the mouse Y 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. Here is an example of such code
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
line(100,0,100,200);
line(0,100,200,100);
// Fill a black color
noStroke();
fill(0);
if (mouseX < 100 & & mouseY < 100) {
rect(0,0,100,100);
} else if (mouseX > 100 & & mouseY < 100) {
rect(100,0,100,100);
} else if (mouseX < 100 & & mouseY > 100) {
rect(0,100,100,100);
} else if (mouseX > 100 & & mouseY > 100) {
rect(100,100,100,100);
}
}
TASK:
Rewrite the code so that the squares fade from black to white when the mouse leaves their area. Hint: you need four variables, one for each rectangle’s color.
Setup:
1. Set up a window of 200x200 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 through 6, we have to ask ourselves the question: “ How do we know if the mouse is in a given corner? ” To accomplish this, we need to develop a more specific if statement. For example, we would say: “ If the mouse X location is greater than 100 pixels and the mouse Y 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. Here is an example of such code
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
line(100,0,100,200);
line(0,100,200,100);
// Fill a black color
noStroke();
fill(0);
if (mouseX < 100 & & mouseY < 100) {
rect(0,0,100,100);
} else if (mouseX > 100 & & mouseY < 100) {
rect(100,0,100,100);
} else if (mouseX < 100 & & mouseY > 100) {
rect(0,100,100,100);
} else if (mouseX > 100 & & mouseY > 100) {
rect(100,100,100,100);
}
}
TASK:
Rewrite the code so that the squares fade from black to white 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 are thinking: “ Can’t I just select ‘ Add Button ’ from the menu or something? ” For us, right now, the answer is no. Yes, we are going to eventually
learn how to use code from a library (and you might use a library to make buttons in your sketches more easily), but there is a lot of 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, we are going to look at how we 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 . We just used a boolean variable: the built-in variable mousePressed . mousePressed is true when the mouse is pressed and false when the mouse is not.
And so our button example will include one boolean variable with a starting value of false (the assumption being that the button starts in the off state).
boolean button = false; \\A boolean variables is either true of false.
In the case of a rollover, any time the mouse hovered over the rectangle, it turned white. Our sketch will turn the background white when the button is pressed and black when it is not.
if (button) {
background(255);
} else {
background(0);
}\\If the value of button is true, the background is white. If it is false, black.
We 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:
boolean button = false;
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h && mousePressed) {
\\The button is pressed if (mouseX, mouseY) is inside the rectangle and mousePressed is true.
button = true;
} else {
button = false;
}
if (button) {
background(255);
stroke(0);
} else {
background(0);
stroke(255);
}
fill(175);
rect(x,y,w,h);
}
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 is not what we are really going for in this
section. What we 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 is on, it turns off.
For this to work properly, we 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. When the mouse is clicked, we want the switch to turn on or off (once and only once).
We 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, we should set it to false. If it is false, we should set it to true.
if (button) {
button = false;
} else {
button = true;
}\*The explicit way to toggle a boolean variable. If the value of button is true, set it equal to false. Otherwise, it must be false, so set it equal to true. *\
There is a simpler way to go which is the following:
button = !button; \\Not true is false. Not false is true!
Here, the value of button is set to “ not ” itself. In other words, if the button is true then we set set it to not true (false). If it is false then we set it to not false (true). Armed with this odd but effective line of code, we are ready to look at the button in action
boolean button = false;
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
if (button) {
background(255);
stroke(0);
} else {
background(0);
stroke(255);
}
fill(175);
rect(x,y,w,h);
}
void mousePressed() {
if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h){
\\When the mouse is pressed, the state of the button is toggled.
button = !button;
}
}
Task:
1) Why doesn’t the following code work properly when it is moved to draw( )?
if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h && mousePressed){
button = !button;
}
2) Before you created an example of a circle moving across a window, Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable.
Here is some starter code:
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() {
___________________________________
}
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 are thinking: “ Can’t I just select ‘ Add Button ’ from the menu or something? ” For us, right now, the answer is no. Yes, we are going to eventually
learn how to use code from a library (and you might use a library to make buttons in your sketches more easily), but there is a lot of 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, we are going to look at how we 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 . We just used a boolean variable: the built-in variable mousePressed . mousePressed is true when the mouse is pressed and false when the mouse is not.
And so our button example will include one boolean variable with a starting value of false (the assumption being that the button starts in the off state).
boolean button = false; \\A boolean variables is either true of false.
In the case of a rollover, any time the mouse hovered over the rectangle, it turned white. Our sketch will turn the background white when the button is pressed and black when it is not.
if (button) {
background(255);
} else {
background(0);
}\\If the value of button is true, the background is white. If it is false, black.
We 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:
boolean button = false;
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h && mousePressed) {
\\The button is pressed if (mouseX, mouseY) is inside the rectangle and mousePressed is true.
button = true;
} else {
button = false;
}
if (button) {
background(255);
stroke(0);
} else {
background(0);
stroke(255);
}
fill(175);
rect(x,y,w,h);
}
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 is not what we are really going for in this
section. What we 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 is on, it turns off.
For this to work properly, we 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. When the mouse is clicked, we want the switch to turn on or off (once and only once).
We 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, we should set it to false. If it is false, we should set it to true.
if (button) {
button = false;
} else {
button = true;
}\*The explicit way to toggle a boolean variable. If the value of button is true, set it equal to false. Otherwise, it must be false, so set it equal to true. *\
There is a simpler way to go which is the following:
button = !button; \\Not true is false. Not false is true!
Here, the value of button is set to “ not ” itself. In other words, if the button is true then we set set it to not true (false). If it is false then we set it to not false (true). Armed with this odd but effective line of code, we are ready to look at the button in action
boolean button = false;
int x = 50;
int y = 50;
int w = 100;
int h = 75;
void setup() {
size(200,200);
}
void draw() {
if (button) {
background(255);
stroke(0);
} else {
background(0);
stroke(255);
}
fill(175);
rect(x,y,w,h);
}
void mousePressed() {
if (mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h){
\\When the mouse is pressed, the state of the button is toggled.
button = !button;
}
}
Task:
1) Why doesn’t the following code work properly when it is moved to draw( )?
if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h && mousePressed){
button = !button;
}
2) Before you created an example of a circle moving across a window, Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable.
Here is some starter code:
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 is time again to return to our friend Zoog. Let’s review what we have done so far. First, we learned to draw Zoog with shape functions available from the Processing reference. Afterward, we realized we could use variables instead of hard-coded values. Having these variables allowed us 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 we 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 us 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 material on variables, we know we need global variables to keep track of Zoog’s location.
int x = 0;
Is this enough? No. In our previous example Zoog always moved one pixel.
x = x + 1;
This tells Zoog to move to the right. But what if we 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, we need another variable : speed.
int x = 0;
int speed = l;
\\A variable for Zoog’s speed. When speed is positive Zoog moves to the right, when speed is negative Zoog moves to the left.
Now that we have our variables, we can move on to the rest of the code. Assuming setup( ) sets the size of the window, we can go directly to examining the steps required inside of draw( ) . We can also refer to Zoog as a ball in this instance since we are just going to draw a circle.
background(0);
stroke(255);
fill(100);
ellipse(x,100,32,32); \\For simplicity, Zoog is just a circle.
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 we 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. In order for it to turn around, we need a conditional statement. If the ball goes off the edge, turn the ball around . Or more formally . .
if (x > width) {
speed = speed * -1;
}\\If x is greater than width, reverse speed.
Running the sketch, we now have a circle that turns around when it reaches the right-most edge, but runs off the left-most edge of the screen. We’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 > width) || (x < 0)) {
speed = speed * -1;
}\\If x is greater than width or if x is less than zero, reverse speed.
Running the sketch, we now have a circle that turns around when it reaches the right-most edge, but runs off the left-most edge of the screen. We’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 > width) || (x < 0)) {
speed = speed * -1;
} \\If x is greater than width or if x is less than zero, reverse speed .
\\Remeber || means or
Putting it all together
int x = 0;
int speed = 1;
void setup() {
size(200,200);
smooth();
}
void draw() {
background(255);
x = x + speed;\\Add the current speed to the x location.
if ((x > width) || (x < 0)) {
speed = speed * -1; \\If the object reaches either edge,multiply speed by -1 to turn it around.
}
// Display circle at x location
stroke(0);
fill(175);
ellipse(x,100,32,32);
}
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.
TASK
Rewrite the above code 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?
It is time again to return to our friend Zoog. Let’s review what we have done so far. First, we learned to draw Zoog with shape functions available from the Processing reference. Afterward, we realized we could use variables instead of hard-coded values. Having these variables allowed us 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 we 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 us 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 material on variables, we know we need global variables to keep track of Zoog’s location.
int x = 0;
Is this enough? No. In our previous example Zoog always moved one pixel.
x = x + 1;
This tells Zoog to move to the right. But what if we 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, we need another variable : speed.
int x = 0;
int speed = l;
\\A variable for Zoog’s speed. When speed is positive Zoog moves to the right, when speed is negative Zoog moves to the left.
Now that we have our variables, we can move on to the rest of the code. Assuming setup( ) sets the size of the window, we can go directly to examining the steps required inside of draw( ) . We can also refer to Zoog as a ball in this instance since we are just going to draw a circle.
background(0);
stroke(255);
fill(100);
ellipse(x,100,32,32); \\For simplicity, Zoog is just a circle.
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 we 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. In order for it to turn around, we need a conditional statement. If the ball goes off the edge, turn the ball around . Or more formally . .
if (x > width) {
speed = speed * -1;
}\\If x is greater than width, reverse speed.
Running the sketch, we now have a circle that turns around when it reaches the right-most edge, but runs off the left-most edge of the screen. We’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 > width) || (x < 0)) {
speed = speed * -1;
}\\If x is greater than width or if x is less than zero, reverse speed.
Running the sketch, we now have a circle that turns around when it reaches the right-most edge, but runs off the left-most edge of the screen. We’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 > width) || (x < 0)) {
speed = speed * -1;
} \\If x is greater than width or if x is less than zero, reverse speed .
\\Remeber || means or
Putting it all together
int x = 0;
int speed = 1;
void setup() {
size(200,200);
smooth();
}
void draw() {
background(255);
x = x + speed;\\Add the current speed to the x location.
if ((x > width) || (x < 0)) {
speed = speed * -1; \\If the object reaches either edge,multiply speed by -1 to turn it around.
}
// Display circle at x location
stroke(0);
fill(175);
ellipse(x,100,32,32);
}
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.
TASK
Rewrite the above code 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?
Bouncing Color: putting it all together
float c1 = 0; //Two variables for color.
float c2 = 255;
float c1dir = 0.1; //Start by incrementing c1. Start by decrementing c2.
float c2dir = -0.1;
void setup() {
size(200,200);
}
void draw() {
noStroke();
// Draw rectangle on left
fill(c1,0,c2);
rect(0,0,100,200);
// Draw rectangle on right
fill(c2,0,c1);
rect(100,0,100,200);
// Adjust color values
c1 = c1 + c1dir;
c2 = c2 + c2dir;
// Reverse direction of color change
if (c1 < 0 || c1 > 255) {
c1dir *= -1;
}
if (c2 < 0 || c2 > 255) {
c2dir *= -1;
}
}
Having the conditional statement in our 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.
• State #0: left to right.
• State #1: top to bottom.
• State #2: right to left.
• State #3: bottom to top.
We can use a variable to keep track of the state number and adjust the x , y coordinate of the rectangle according to the state. For example:
“ If the state is 2, x equals x minus 1. ”
Once the rectangle reaches the endpoint for that state, we can change the state variable. “ If the state is 2:
(a) x equals x minus 1.
(b) if x less than zero, the state equals 3. ”
The following example implements this logic .
int x = 0; // x location of square
int y = 0; // y location of square
int speed = 5; // speed of square
int state = 0; /* A variable to keep track of the square’s“state.” Depending on the value of its state,
it will either move right, down, left, or up. */
void setup() {
size(200,200);
}
void draw() {
background(100);
// Display the square
noStroke();
fill(255);
rect(x,y,10,10);
if (state == 0) { //If the state is 0, move to the right.
x = x + speed; //f, while the state is 0, it reaches the rightside of the window, change the state to 1.
if (x > width-10) {
x = width-10;
state = 1;
}
} else if (state == 1) {
y = y + speed;
if (y > height-10) {
y = height-10;
state = 2;
}
} else if (state == 2) {
x = x - speed;
if (x < 0) {
x = 0;
state = 3;
}
} else if (state == 3) {
y = y - speed;
if (y < 0) {
y = 0;
state = 0;
}
}
}
TASK:
Change the code above and explain what you changed and show your changes with comments in the code.
float c1 = 0; //Two variables for color.
float c2 = 255;
float c1dir = 0.1; //Start by incrementing c1. Start by decrementing c2.
float c2dir = -0.1;
void setup() {
size(200,200);
}
void draw() {
noStroke();
// Draw rectangle on left
fill(c1,0,c2);
rect(0,0,100,200);
// Draw rectangle on right
fill(c2,0,c1);
rect(100,0,100,200);
// Adjust color values
c1 = c1 + c1dir;
c2 = c2 + c2dir;
// Reverse direction of color change
if (c1 < 0 || c1 > 255) {
c1dir *= -1;
}
if (c2 < 0 || c2 > 255) {
c2dir *= -1;
}
}
Having the conditional statement in our 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.
• State #0: left to right.
• State #1: top to bottom.
• State #2: right to left.
• State #3: bottom to top.
We can use a variable to keep track of the state number and adjust the x , y coordinate of the rectangle according to the state. For example:
“ If the state is 2, x equals x minus 1. ”
Once the rectangle reaches the endpoint for that state, we can change the state variable. “ If the state is 2:
(a) x equals x minus 1.
(b) if x less than zero, the state equals 3. ”
The following example implements this logic .
int x = 0; // x location of square
int y = 0; // y location of square
int speed = 5; // speed of square
int state = 0; /* A variable to keep track of the square’s“state.” Depending on the value of its state,
it will either move right, down, left, or up. */
void setup() {
size(200,200);
}
void draw() {
background(100);
// Display the square
noStroke();
fill(255);
rect(x,y,10,10);
if (state == 0) { //If the state is 0, move to the right.
x = x + speed; //f, while the state is 0, it reaches the rightside of the window, change the state to 1.
if (x > width-10) {
x = width-10;
state = 1;
}
} else if (state == 1) {
y = y + speed;
if (y > height-10) {
y = height-10;
state = 2;
}
} else if (state == 2) {
x = x - speed;
if (x < 0) {
x = 0;
state = 3;
}
} else if (state == 3) {
y = y - speed;
if (y < 0) {
y = 0;
state = 0;
}
}
}
TASK:
Change the code above and explain what you changed and show your changes with comments in the code.
Physics 101
One of the happiest moments is to come....LEARNING GRAVITY
The bouncing ball sketch taught us 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 we must add to our 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 we just need another line of code:
speed = speed + acceleration
And now we have a simple gravity simulation.
float x = 100; // x location of square
float y = 0; // y location of square
float speed = 0; // speed of square
float gravity = 0.1;
void setup() {
size(200,200);
}
void draw() {
background(255);
//Display the square
fill(0);
noStroke();
rectMode(CENTER);
rect(x,y,10 , 10);
y = y + speed;
speed = speed + gravity; // If square reaches the bottom
// Reverse speed
if (y > height) {
speed = speed * -0.95;
}
}
TASK:
Continue with your design and add some of the functionality demonstrated. Some options:
• 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.
One of the happiest moments is to come....LEARNING GRAVITY
The bouncing ball sketch taught us 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 we must add to our 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 we just need another line of code:
speed = speed + acceleration
And now we have a simple gravity simulation.
float x = 100; // x location of square
float y = 0; // y location of square
float speed = 0; // speed of square
float gravity = 0.1;
void setup() {
size(200,200);
}
void draw() {
background(255);
//Display the square
fill(0);
noStroke();
rectMode(CENTER);
rect(x,y,10 , 10);
y = y + speed;
speed = speed + gravity; // If square reaches the bottom
// Reverse speed
if (y > height) {
speed = speed * -0.95;
}
}
TASK:
Continue with your design and add some of the functionality demonstrated. Some options:
• 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.