Think of it as a switch. Press the button, turn the switch on. We just used a boolean variable in Example the built-in variable mousePressed. 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 it is false, black. Conditionals 71 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.
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. 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. This code will go inside mousePressed. If it is false, we should set it to true. If the value of button is true, set it equal to false.
Otherwise, it must be false, so set it equal to true. Not false is true! 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. Try moving this code to draw like in the rollover example.
See Exercise 5—7. Change the sketch so that the circle only starts moving once the mouse has been pressed. Use a boolean variable. 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. 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! 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. In our previous example Zoog always moved one pixel.
But what if we want it to move to the left? Easy, right? Yes, bells are ringing. 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. Now, in order for the ball to move, the value of its x location should change each cycle through draw. In order for it to turn around, we need a conditional statement. Or more formally. If x is greater than width, reverse speed. Conditionals 75 Reversing the Polarity of a Number When we want to reverse the polarity of a number, we mean that we want a positive number to become negative and a negative number to become positive.
This is achieved by multiplying by —1. If x is greater than width or if x is less than zero, reverse speed. Example puts it all together. 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? For example, just as a square moves from left to right, a color can go from less red to more red. Example takes the same bouncing ball algorithm and applies it to changing color.
Start by incrementing c1. Start by decrementing c2. When this happens, just like with the bouncing ball, the direction is reversed. For example, consider a rectangle that follows the edges of a window. 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.
If, while the state is 0, it reaches the right side of the window, change the state to 1. Repeat this same logic for all states! And in fact, armed with variables and conditionals, you are now ready for this moment. The bouncing ball sketch taught us that an object moves by altering its location according to speed. 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.
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. We use a relatively small number 0. Try changing this number to 2. Exercise Continue with your design and add some of the functionality demonstrated in this chapter. Can you make it bounce off all edges of the window? Here is a simple version with Zoog. Identical logic is applied to the y direction as well.
I mean, what is iteration? Seriously, what is iteration? Iteration is the generative process of repeating a set of rules or steps over and over again.
It is a fundamental concept in computer programming and we will soon come to discover that it makes our lives as coders quite delightful. For the moment, think about legs. Lots and lots of legs on our little Zoog. If we had only read Chapter 1 of this book, we would probably write some code as in Example Sure, the code accomplishes this, however, having learned variables in Chapter 4, we can make some substantial improvements and eliminate the hard-coded values.
Note that for each leg drawn, only the x value changes. All other variables stay the same but they could change if we wanted them to! Add spacing so the next leg appears 10 pixels to the right. And what if we wanted to draw legs? For every leg, we need two lines of code.
To avoid this dire, carpal-tunnel inducing problem, we want to be able to say something like: Draw one line one hundred times. Aha, only one line of code! A loop structure is similar in syntax to a conditional Loops 83 see Chapter 5. However, instead of asking a yes or no question to determine whether a block of code should be executed one time, our code will ask a yes or no question to determine how many times the block of code should be repeated.
This is known as iteration. For one thing, the only loop you really need is while. The for loop, as we will see, is simply a convenient alternative, a great shorthand for simple counting operations. Do-while, however, is rarely used not one example in this book requires it and so we will ignore it.
If the test evaluates to true, the instructions enclosed in curly brackets are executed; if it is false, we continue on to the next line of code. See Figure 6. Assuming the following variables. We then enclose all of the code for the class inside curly brackets after the name declaration.
Class names are traditionally capitalized to distinguish them from variable names, which traditionally are lowercase. These variables are often referred to as instance variables since each instance of an object contains this set of variables. It is where you give the instructions on how to set up the object. These are done in the same way as described in Chapter 7, with a return type, name, arguments, and a body of code.
This code for a class exists as its own block and can be placed anywhere outside of setup and draw. Include a function called sleep or make up your own function. Follow the syntax of the Car example. There are no right or wrong answers in terms of the actual code itself; it is the structure that is important. Car myCar; Step 1. Declare an object. Initialize object. Call methods on the object. Declaring an object variable. Declaring a variable that holds onto an object is quite similar.
This is because they store multiple pieces of information: data and functionality. Primitives only store data. Initializing an object. Again, you may recall from Chapter 4 that in order to initialize a variable i. An object is made with the new operator. What we are really doing here is initializing a Car object.
When you initialize a primitive variable, such as an integer, you just set it equal to a number. But an object may contain multiple pieces of data. If you forget to initialize an object, Processing will give it the value null. Not zero. Not negative one.
Utter nothingness. See the Appendix for more details. Using an object Once we have successfully declared and initialized an object variable, we can use it. Using an object involves calling functions that are built into that object. A human object can eat, a car can drive, a dog can bark. Calling a method inside of an object is accomplished via dot syntax: variableName.
Exercise Assume the existence of a Human class. You want to write the code to declare a Human object as well as call the function sleep on that human object.
Operate the car object in draw by calling object methods using the dots syntax. Technically speaking, the order does not matter, as long as the blocks of code contained within curly brackets remain intact. The Car class could go above setup or it could even go between setup and draw. Though any placement is technically correct, when programming, it is nice to place things where they make the most logical sense to our human brains, the bottom of the code being a good starting point.
In your Processing window, look for the arrow inside a square in the top right-hand corner. Although you can pick any name you like, it is probably a good idea to name the tab after the class you intend to put there. Toggling between the tabs is simple, just click on the tab name itself, as shown in Figure 8. Also, it should be noted that when a new tab is created, a new.
The program has both an objectExample. Try to get the Car example to run without any errors. Nonetheless, there is a rather serious problem with the above code. What if we wanted to write a program with two car objects?
However, if you study the Car class, you will notice that these two cars will be identical: each one will be colored white, start in the middle of the screen, and have a speed of 1. In English, the above reads: Make a new car. We want to instead say: Make a new red car, at location 0,10 with a speed of 1. So that we could also say: Make a new blue car, at location 0, with a speed of 2. We can do this by placing arguments inside of the constructor method.
Please do not blame yourself. But for now, it may feel painful. See Figure 8. In the examples, they have one purpose only, to initialize the variables inside of an object. This allows us to make a variety of objects using the same constructor. You might also just write the word temp in your argument names to remind you of what is going on c vs. You will also see programmers use an underscore c vs. You can name these whatever you want, of course.
However, it is advisable to choose a name that makes sense to you, and also to stay consistent. We can now take a look at the same program with multiple object instances, each with unique properties. No matter how many cookies we make, only one cookie cutter is needed. Include two instances of a Ball object. The original example is included here for your reference with a framework to help you get started.
The examples in this chapter all use just one class and make, at most, two or three objects from that class. Nevertheless, there are no actual limitations. A Processing sketch can include as many classes as you feel like writing. If you were programming the Space Invaders game, for example, you might create a Spaceship class, an Enemy class, and a Bullet class, using an object for each entity in your game.
And since classes are made up of data, an object can therefore contain other objects! Moving on to a PlaceSetting class, you would likely include variables for both a Fork object and a Spoon object inside that class itself.
This is perfectly reasonable and quite common in object-oriented programming. In the Space Invaders game example, if the spaceship shoots the bullet at the enemy, we would probably want to write a function inside the Enemy class to determine if the Enemy had been hit by the bullet. With objects, this is not the case, and the result is a bit more intuitive. This is known as pass by reference since instead of a copy, a reference to the actual object itself is passed into the function.
As we move forward through this book and our examples become more advanced, we will begin to see examples that use multiple objects, pass objects into functions, and more. The next chapter, in fact, focuses on how to make lists of objects. And Chapter 10 walks through the development of a project that includes multiple classes. For now, as we close out the chapter with Zoog, we will stick with just one class. Objects allow you to organize the concepts inside of a software application into Objects modular, reusable packages.
You will see this again and again throughout the course of this book. However, it is not always convenient or necessary to start out every project using object-orientation, especially while you are learning.
For any Processing project you want to make, my advice is to take a step-by-step approach. You do not need to start out writing classes for everything you want to try to do. Nail down the logic of what you want to do as well as how you want it to look. This is exactly what we have been doing with cosmonaut Zoog from Chapter 1 until now. Now that we have something, we can take the time to refactor by making Zoog into an object. And so it is time to take the plunge and make a Zoog class.
Our little Zoog is almost all grown up. All of the variables and all of the functions from Example are now incorporated into the Zoog class with setup and draw containing barely any code. Zoog is given initial properties via the constructor. Can you vary their appearance? Consider adding color as a Zoog variable.
Objects Lesson Three Project Step 1. Take your Lesson Two Project and reorganize the code using functions. Reorganize the code one step further using a class and an object variable. Car myCar1; Car myCar2; This was indeed an exciting moment in the development of our lives as computer programmers. It is likely you are contemplating a somewhat obvious question.
How could I take this further and write a program with car objects? It will not be a pleasant endeavor. I am certainly not about to leave you any workbook space in this book to practice.
An array will allow us to take these lines of code and put them into one line. Instead of having variables, an array is one thing that contains a list of variables. Any time a program requires multiple instances of similar data, it might be time to use an array.
Exercise Looking at all of the sketches you have created so far, do any merit the use of an array? From Chapter 4, you may recall that a variable is a named pointer to a location in memory where data is stored. In other words, variables allow programs to keep track of information over a period of time.
An array is exactly the same, only instead of pointing to one singular piece of information, an array points to multiple pieces. See Figure 9. A list, it should be noted, is useful for two important reasons.
Number one, the list keeps track of the elements in the list themselves. This is a crucial point since in many programs, the order of information is just as important as the information itself.
In an array, each element of the list has a unique index, an integer value that designates its position in the list element 1, element 2, etc. In all cases, the name of the array refers to the list as a whole, while each element is accessed via its position. Notice how in Figure 9. Numbering the elements starting at 0 also makes many array operations the process of executing a line of code for every element of the list a great deal more convenient.
As we continue through several examples, you will begin to believe in the power of counting from zero. Arrays Exercise If you have an array with 1, elements, what is the range of index values for that array? We can have arrays of any data type, and we will soon see how we can make an array of objects. A list of 10 integers can never go to It is not. To do this, we use the new operator, in a similar manner as we did in calling the constructor of an object. See array declaration in Figure 9.
We write this statement as follows: the new operator, followed by the data type, followed by the size of the array enclosed in brackets. This size must be an integer. Not only did we successfully declare the existence of an array, but we have given it a size and allocated physical memory for the stored data. A major piece is missing, however: the data stored in the array itself!
Arrays 9. The syntax for this is the name of the array, followed by the index value enclosed in brackets. Initialize each spot in the array with a Zoog object via its index. In fact, neither initialization method has really solved the problem posed at the beginning of the chapter.
Imagine initializing each element individually with a list of or gasp 1, or gasp gasp! The solution to all of our woes involves a means for iterating through the elements of the array. Ding ding ding. Hopefully a loud bell is ringing in your head. If you are lost, revisit Chapter 6. B Initialize every element of that array with a random number between 0 and Part A we already know how to do. We have, nonetheless, taken a big leap forward.
By using a variable n to describe an index in the array, we can now employ a while loop to initialize every n element. We can exploit the same technique for any type of array operation we might like to do beyond simply initializing the elements. For example, we could take the array and double the value of each element we will use i from now on instead of n as it is more commonly used by programmers.
Striving to be better programmers, we should always question the existence of a hard-coded number. In this case, what if we wanted to change the array to have 2, elements? If our program was very long with many array operations, we would have to make this change everywhere throughout our code.
Fortunately for us, Processing gives us a nice means for accessing the size of an array dynamically, using the dot syntax we learned for objects in Chapter 8. This will involve resetting every value to 0. Skip the last value in the array.
The solution requires an array, which will serve to store the history of mouse locations. We will use two arrays, one to store horizontal mouse locations, and one for vertical.
First, we declare the two arrays. The length of the array is 50, meaning index values range from 0— The the last spot is index 49, or the length of the array minus one. Arrays Now comes the hard part. We want to keep only the last 50 mouse locations. By storing the current mouse location at the end of the array, we are overwriting what was previously stored there. Page Count. Daniel Shiffman, Daniel Shiffman,. A friendly start-up guide to Processing, a free, open-source alternative to expensive software and daunting programming languages No previous experience required—this book is for the true programming beginner!
Step-by-step examples, thorough explanations, hands-on exercises, and sample code supports your learning curve. Download e-Book Pdf. Variables 47 Exercise Consider the game Pong. What variables would you need to program the game? For now, we are just going to worry about primitives—we will get to objects and arrays in a later chapter.
Primitive values are the building blocks of data on the computer and typically involve a singular piece of information, like a number or character. Variable names must be one word no spaces and must start with a letter they can include numbers, but cannot start with a number. A type is the kind of data stored in that variable. This could be a whole number, a decimal number, or a character. Characters are useful when determining what letter on the keyboard has been pressed, and for other uses involving Strings of text see Chapter Other possible data types are listed below.
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. However, it is good to get into the habit of always initializing variables in order to avoid confusion.
In other words, do not call your variable mouseX, there already is one! This may seem obvious, but it is an important point. Words that start with capitals are reserved for classes Chapter 8. Variables 49 A variable can also be initialized by another variable x equals y , or by evaluating a mathematical expression x equals y plus z, etc. Exercise Write out variable declaration and initialization for the game Pong. They are variables! However, because they are built into the Processing environment note how they are colored red when you type them in your code , they can be used without being declared.
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.
Rule of Thumb: When to Use a Variable There are no hard and fast rules in terms of when to 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!
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.
In the above code, circleX starts with a value of If we want to increment circleX by one, we say circleX equals itself plus one. What happens? If you run 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. This may seem overly simple and obvious, but it is key to our understanding of the principles of programming motion.
Run setup. Run draw. And so on and so forth! Be one with the computer. Exercise Change Example 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? 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. 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.
Is a key pressed? Is the mouse 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. In other words, no matter what you specify for size , the result should look identical. Variables 55 4.
So, you may have noticed that the examples in this book 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 all goes back to the driving principle behind this book: incremental development. 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, for a moment, Example , whose output is shown in Figure 4. Remember, the fourth ellipse x,y,diam,diam ; argument for a color is transparency.
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.
We have encountered this before. In Exercise we used the function abs to calculate the absolute value of a number. The idea of a function that calculates a value and returns it will be explored fully in Chapter 7, 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. 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. Listen, I was wondering, could you give me a random number between 1 and ? Random: Like, no problem. How about the number 63? Gotta draw a rectangle 63 pixels wide, OK? Now, how would this sequence look in our slightly more formal, Processing environment?
The function random also works with one argument by assuming a range between zero and that argument. However, if you want a random integer, you can convert the result of the random function to an int.
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 output is shown in Figure 4. Here, we will add two pieces of functionality to Zoog. Feature 1 is solved by simply taking the previous program that used mouseX and mouseY and substituting our own variables in their place.
Example Variable Zoog float zoogX; Declaring variables. Hint: this requires the use of random in combination with zoogX. Only true and false. 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. Is 15 greater than 20? If the answer is yes i. 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 the output shown in Figure 5. If the mouse is on the left side of the screen, draw a white background, otherwise draw a black background.
As soon as one boolean expression is found No Yes to be true, the corresponding code is executed and the remaining boolean expressions are ignored. See Figure 5. Do this. And this. Taking our simple mouse example a step further, we could say the else following, with results shown in Figure 5. If the mouse is on the left third of the window, draw a white And this. Fill in the blanks in the following code to complete the boolean expression. 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 Conditionals 63 Problem 2: If a number is 5, change it to 6.
It is worth pointing out that in Exercise when we test for equality we must use two equal signs. Our pseudocode is below.
Create variables to hold on to red, green, and blue color components. Call them r, g, and b. Continuously draw the background based on those colors. 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 This pseudocode is implemented in Processing in Example Draw stuff. If r is greater than , set it to Here, we do not want color values to increase to unreasonable extremes. Remember what it means for a function to return a value?
See our discussion of random. Conditionals 65 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. 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.
Start the shape at x coordinate 0 and use an if statement to have it stop at coordinate Rewrite the sketch to use constrain instead of the if statement. Fill in the missing code. Sometimes, however, simply performing a task based on one condition is not enough.
For example: If my temperature is greater than 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.
If my temperature is NOT greater than Boolean variables will be explored in greater detail in Section 5. Notice this example could also be written omitting the not, saying: If the mouse is pressed, draw a square, otherwise draw a circle.
A bitwise operation compares each bit 0 or 1 of the binary representations of two numbers. It is used in rare circumstances where you require low-level access to bits. In other words, if the mouse is over a rectangle, the rectangle changes color. Here is some code to get you started.
Consider the four screenshots shown in Figure 5. A white square is displayed in one of four quadrants, according to the mouse location. Setup: 1. Draw: 1. Draw a white background. Draw horizontal and vertical lines to divide the window in four quadrants.
If the mouse is in the top left corner, draw a black rectangle in the top left corner. If the mouse is in the top right corner, draw a black rectangle in the top right corner. If the mouse is in the bottom left corner, draw a black rectangle in the bottom left corner. If the mouse is in the bottom right corner, 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 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. 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. Press the button, turn the switch on. We just used a boolean variable in Example the built-in variable mousePressed. 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 it is false, black. 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.
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. This code will go inside mousePressed. If it is false, we should set it to true. Not false is true! 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. See Exercise 5—7. Change the sketch so that the circle only starts moving once the mouse has been pressed.
Use a boolean variable. 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. 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! 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. In our previous example Zoog always moved one pixel. But what if we want it to move to the left? Easy, right? Yes, bells are ringing.
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.
Now, in order for the ball to move, the value of its x location should change each cycle through draw. In order for it to turn around, we need a conditional statement. Or more formally. If x is greater than width, reverse speed.
This is achieved by multiplying by —1. If x is greater than width or if x is less than zero, reverse speed. 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? For example, just as a square moves from left to right, a color can go from less red to more red.
Example takes the same bouncing ball algorithm and applies it to changing color. Start by decrementing c2. For example, consider a rectangle that follows the edges of a window. 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.
And in fact, armed with variables and conditionals, you are now ready for this moment. The bouncing ball sketch taught us that an object moves by altering its location according to speed. 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. 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. We use a relatively size , ; small number 0.
Try changing this number to 2. Exercise Continue with your design and add some of the functionality demonstrated in this chapter. Can you make it bounce off all edges of the window? Here is a simple version with Zoog.
I mean, what is iteration? Seriously, what is iteration? Iteration is the generative process of repeating a set of rules or steps over and over again. It is a fundamental concept in computer programming and we will soon come to discover that it makes our lives as coders quite delightful. For the moment, think about legs. Lots and lots of legs on our little Zoog.
If we had only read Chapter 1 of this book, we would probably write some code as in Example Sure, the code accomplishes this, however, having learned variables in Chapter 4, we can make some substantial improvements and eliminate the hard-coded values. Note that for each leg drawn, only the x value changes. All other variables stay the same but they could change if we wanted them to! And what if we wanted to draw legs? For every leg, we need two lines of code. To avoid this dire, carpal-tunnel inducing problem, we want to be able to say something like: Draw one line one hundred times.
Aha, only one line of code! However, instead of asking a yes or no question to determine whether a block of code should be executed one time, our code will ask a yes or no question to determine how many times the block of code should be repeated. This is known as iteration. For one thing, the only loop you really need is while.
The for loop, as we will see, is simply a convenient alternative, a great shorthand for simple counting operations. Do-while, however, is rarely used not one example in this book requires it and so we will ignore it.
If the test evaluates to true, the instructions enclosed in curly brackets are executed; if it is false, we continue on to the next line of code. See Figure 6. Assuming the following variables. In addition, we can change the spacing variable to generate more legs. The results are shown in Figure 6. What is the initial condition for your loop?
When should your loop stop? Since we want to display rectangles all the way to the bottom of the window, the loop should stop when y is greater than height.
Share this:. Top learningprocessing. Top www. Best learningprocessing. Save www. Online media. Online www. Hot readyforai. Hot livreepubgratuitz. Online epdf. Top ardhindie. Save heavenlybells. Good processing. Online classes are no easier than classes offered in the traditional classroom setting and in some cases can be even be more difficult. There are several reasons for this. Online courses require more self-motivation. It can be hard for some students to stay motivated when they'd rather be doing something else.
We offer a massive number of online courses, most of them are free.
0コメント