Make: getting started with processing.py download pdf






















There's not much to it; the large area is the Text Editor, and there's a row of buttons across the top; this is the toolbar.

Below the editor is the Message Area, and below that is the Console. The Message Area is used for one line messages, and the Console is used for more technical details. In the editor, type the following: ellipse 50, 50, 80, 80 ; This line of code means "draw an ellipse, with the center 50 pixels over from the left and 50 pixels down from the top, with a width and height of 80 pixels.

If you've typed everything correctly, you'll see a circle on your screen. If you didn't type it correctly, the Message Area will turn red and complain about an error. If this happens, make sure that you've copied the example code exactly: the numbers should be contained within parentheses and have commas between each of them, and the line should end with a semicolon.

One of the most difficult things about getting started with programming is that you have to be very specific about the syntax. The Processing software isn't always smart enough to know what you mean, and can be quite fussy about the placement of punctuation. You'll get used to it with a little practice. Next, we'll skip ahead to a sketch that's a little more exciting. When a mouse button is pressed, the circle color changes to black.

We'll explain more about the elements of this program in detail later. For now, run the code, move the mouse, and click to see what it does. The Present option clears the rest of the screen when the program is run to present the sketch all by itself. Example Draw with Color To move beyond grayscale values, you use three parameters to specify the red, green, and blue components of a color.

Run the code in Processing to reveal the colors: This is referred to as RGB color, which comes from how computers define colors on the screen. The three numbers stand for the values of red, green, and blue, and they range from 0 to the way that the gray values do.

Select a color, and then use the R, G, and B values as the parameters for your background , fill , or stroke function. Processing Color Selector. Example Set Transparency By adding an optional fourth parameter to fill or stroke , you can control the transparency. This fourth parameter is known as the alpha value, and also uses the range 0 to to set the amount of transparency. Example Draw an Arrow The beginShape function signals the start of a new shape.

The vertex function is used to define each pair of x- and y-coordinates for the shape. Finally, endShape is called to signal that the shape is finished. Processing can draw thousands and thousands of lines at a time to fill the screen with fantastic shapes that spring from your imagination. Comments are parts of the program that are ignored when the program is run.

If others are reading your code, comments are especially important to help them understand your thought process. Comments are also especially useful for a number of different options, such as when trying to choose the right color. You can also comment out many lines at a time with the alternative comment notation introduced in Appendix A.

There are eight different programs to draw and animate him in the book—each one explores a different pro- gramming idea. The first robot program uses the drawing functions introduced in the pre- vious chapter. The parameters to the fill and stroke functions set the gray values. The variable can be used many times within a single program, and the value is easily changed while the program is running.

The primary reason we use variables is to avoid repeating ourselves in the code. If you are typing the same number more than once, consider mak- ing it into a variable to make your code more general and easier to update. When comparing Examples and , notice how the bottom three lines are the same, and only the middle two lines with the variables are different.

For instance, if you place variables that control colors and sizes of shapes in one place, then you can quickly explore different visual options by focusing on only a few lines of code. Making Variables When you make your own variables, you determine the name, the data type, and the value. The name is what you decide to call the variable.

Choose a name that is informative about what the variable stores, but be consistent and not too verbose. The range of values that can be stored within a variable is defined by its data type. For instance, the integer data type can store numbers without decimal places whole numbers.

In code, integer is abbreviated to int. There are data types to store each kind of data: integers, floating-point decimal numbers, characters, words, images, fonts, and so on. When declaring a variable, you also need to specify its data type such as int , which indicates what kind of information is being stored.

For instance, the width and height of the window are stored in variables called width and height. These values are set by the size function. They can be used to draw elements relative to the size of the window, even if the size line changes. Example Adjust the Size, See What Follows In this example, change the parameters to size to see how it works: Other special variables keep track of the status of the mouse and key- board values and much more.

These are discussed in Chapter 5. A Little Math People often assume that math and programming are the same thing. Al- though knowledge of math can be useful for certain types of coding, basic arithmetic covers the most important parts. When placed between two values, they create an expression. These rules define the order in which the code is run. Last, because the assignment operator the equal symbol has the lowest precedence, the value 24 is assigned to the variable x. This is clarified with parentheses, but the result is the same: If you want to force the addition to happen first, just move the parentheses.

Because parentheses have a higher precedence than multiplication, the order is changed and the calculation is affected: An acronym for this order is often taught in math class: PEMDAS, which stands for Parentheses, Exponents, Multiplication, Division, Addition, Subtraction, where parentheses have the highest priority and subtraction the lowest. The complete order of operations is found in Appendix C.

A code structure called a for loop makes it possible to run a line of code more than once to con- dense this type of repetition into fewer lines. This makes your programs more modular and easier to change. The code between the braces is called a block.

This is the code that will be repeated on each iteration of the for loop. Inside the parentheses are three statements, separated by semicolons, that work together to control how many times the code inside the block is run. From left to right, these statements are referred to as the initialization init , the test, and the update: The init typically declares a new variable to use within the for loop and assigns a value.

Figure shows the order in which they run and how they control the code statements inside the block. Flow diagram of a for loop. The test statement requires more explanation. Because the code inside the block is typically run multiple times, a change to the block is magnified when the code is run.

Example is a good base for exploring many types of repeating visual patterns. In Example , the code draws a line from each point in the grid to the center of the screen. In Example , the ellipses shrink with each new row and are moved to the right by adding the y-coordinate to the x-coordinate. For instance, the neck can be drawn based on the body- Height variable. The group of variables at the top of the code control the aspects of the robot that we want to change: location, body height, and neck height.

You can see some of the range of possible variations in the figure; from left to right, here are the values that correspond to them: When altering your own code to use variables instead of numbers, plan the changes carefully, then make the modifications in short steps. For instance, when this program was written, each variable was created one at a time to minimize the complexity of the transition.

To make this happen, place the lines that update inside a Processing function called draw. Each trip through draw is called a frame. The default frame rate is 60 frames per second, but this can be changed. See Example for more information. The text appears in the Console, the black area at the bottom of the Processing editor window. In a typical program, the code inside setup is used to define the starting values. The first line is always the size function, often followed by code to set the starting fill and stroke colors, or perhaps to load images and fonts.

This is clearer when we list the order in which the code is run: 1. Variables declared outside of setup and draw are created. Code inside setup is run once. Code inside draw is run continuously. Example setup , Meet draw The following example puts it all together: Follow Now that we have code running continuously, we can track the mouse position and use those numbers to move elements on screen.

Because the fill is set to be partially transparent, denser black areas show where the mouse spent more time and where it moved slowly.

The circles that are spaced farther apart show when the mouse was moving faster. Example The Dot Follows You In this example, a new circle is added to the window each time the code in draw is run. To refresh the screen and only display the newest circle, place a background function at the beginning of draw before the shape is drawn: The background function clears the entire window, so be sure to always place it before other functions inside draw ; otherwise, the shapes drawn before it will be erased.

Example Draw Continuously The pmouseX and pmouseY variables store the position of the mouse at the previous frame.

Like mouseX and mouseY, these special variables are updated each time draw runs. When combined, they can be used to draw continuous lines by connecting the current and most recent location: Example Set Thickness on the Fly The pmouseX and pmouseY variables can also be used to calculate the speed of the mouse.

This is done by measuring the distance between the current and most recent mouse location. If the mouse is moving slowly, the distance is small, but if the mouse starts moving faster, the distance grows.

A function called dist simplifies this calculation, as shown in the following example. But sometimes you want the values to follow the mouse loosely—to lag behind to create a more fluid motion. This tech- nique is called easing. With easing, there are two values: the current value and the value to move toward see Figure At each step in the pro- gram, the current value moves a little closer to the target value: The value of the x variable is always getting closer to targetX.

The speed at which it catches up with targetX is set with the easing variable, a number be- tween 0 and 1. A small value for easing causes more of a delay than a larger value. With an easing value of 1, there is no delay. When you run Example , the actual values are shown in the Console through the println func- tion.

When moving the mouse, notice how the numbers are far apart, but when the mouse stops moving, the x value gets closer to targetX. All of the work in this example happens on the line that begins. There, the difference between the target and current value is calculated, then multiplied by the easing variable and added to x to bring it closer to the target. Example Smooth Lines with Easing In this example, the easing technique is applied to Example Example Map Values to a Range The mouseX variable is usually between 0 and the width of the window, but you might want to remap those values to a different range of coordi- nates.

It converts a variable from one range of numbers to another. The first parameter is the variable to be converted, the second and third param- eters are the low and high values of that variable, and the fourth and fifth parameters are the desired low and high values. The map function hides the math behind the conversion. Example Map with the map Function This example rewrites Example using map : The map function makes the code easy to read, because the minimum and maximum values are clearly written as the parameters.

Click In addition to the location of the mouse, Processing also keeps track of whether the mouse button is pressed. The mousePressed variable has a different value when the mouse button is pressed and when it is not. The mousePressed variable is a data type called boolean, which means that it has only two possible values: true and false. The value of mousePressed is true when a button is pressed. When a button is not pressed, this code is ignored. The computer determines whether the test is true or false by evaluating the expression inside the parentheses.

Example Detect When Not Clicked A single if block gives you the choice of running some code or skipping it. You can extend an if block with an else block, allowing your program to choose between two options. The code inside the else block runs when the value of the if block test is false.

They can be chained together into a long series with each testing for something different, and if blocks can be embedded inside of other if blocks to make more complex decisions. The if and else structure makes decisions about which blocks of code to run. Location An if structure can be used with the mouseX and mouseY values to deter- mine the location of the cursor within the window.

Example Find the Cursor For instance, this example tests to see whether the cursor is on the left or right side of a line and then moves the line toward the cursor: To write programs that have graphical user interfaces buttons, check- boxes, scrollbars, and so on , we need to write code that knows when the cursor is within an enclosed area of the screen.

The following two ex- amples introduce how to check whether the cursor is inside a circle and a rectangle. The code is written in a modular way with variables, so it can be used to check for any circle and rectangle by changing the values. Example The Bounds of a Circle For the circle test, we use the dist function to get the distance from the center of the circle to the cursor, then we test to see if that distance is less than the radius of the circle see Figure Circle rollover test.

Example The Bounds of a Rectangle We use another approach to test whether the cursor is inside a rectangle. We make four separate tests to check if the cursor is on the correct side of each edge of the rectangle, then we compare each test and if they are all true, we know the cursor is inside. This is illustrated in Figure Four individual tests e. Type Processing keeps track of when any key on a keyboard is pressed, as well as the last key pressed. Like the mousePressed variable, the keyPressed vari- able is true when any key is pressed, and false when no keys are pressed.

Rectangle rollover test. Example Tap a Key In this example, the second line is drawn only when a key is pressed: The key variable stores the most recent key that has been pressed.

Unlike a string value see Example , which is distinguished by double quotes, the char data type is specified by single quotes. The following example uses the value of key to draw the charac- ter to the screen.

Each time a new key is pressed, the value updates and a new character draws. Example Draw Some Letters This example introduces the textSize function to set the size of the letters, the textAlign function to center the text on its x-coordinate, and the text function to draw the letter.

These functions are discussed in more detail on pages 84— By using an if structure, we can test to see whether a specific key is pressed and choose to draw something on screen in response. We combine the two tests together with a logical OR, the symbol. Keys like Shift, Alt, and the arrow keys are coded and require an extra step to figure out if they are pressed. The code inside the draw block runs many times each second. At each frame, the variables defined in the program change in response to the mouseX and mousePressed variables.

The mouseX value controls the position of the robot with an easing tech- nique so that movements are less instantaneous and therefore feel more natural. When a mouse button is pressed, the values of neckHeight and bodyHeight change to make the robot short.

Processing uses a folder named data to store such files, so that you never have to think about their location when making a sketch that will run on the desktop, on the Web, or on a mobile device. Download this file, unzip it to the desktop or somewhere else conve- nient , and make a mental note of its location. On Windows, double-click the media. In that window, drag the media folder to the desktop. Create a new sketch, and select Add File from the Sketch menu.

Find the lunar. You should see a folder named data, with a copy of lunar. When you add a file to the sketch, the data folder will automatically be created. Instead of using the Add File menu command, you can do the same thing by dragging files into the editor area of the Processing window. The files will be copied to the data folder the same way and the data folder will be created if none exists. You can also create the data folder outside of Processing and copy files there yourself.

Images There are three steps to follow before you can draw an image to the screen: 1. Create a PImage variable to store the image. Load the image into the variable with loadImage. Example Load an Image After all three steps are done, you can draw the image to the screen with the image function. The first parameter to image specifies the image to draw; the second and third set the x- and y-coordinates: Optional fourth and fifth parameters set the width and height to draw the image.

If the fourth and fifth parameters are not used, the image is drawn at the size at which it was created. These next examples show how to work with more than one image in the same program and how to resize an image. Be careful to prepare your images at the sizes they will be used. Most digital cameras save JPEG images, but they usually need to be reduced in size before being used with Processing. A typical digital camera creates an image that is several times larger than the drawing area of most Processing sketches, so resizing such images before they are added to the data folder makes sketches run more ef- ficiently, and can save disk space.

GIF and PNG images support transparency, which means that pixels can be invisible or partially visible recall the discussion of color and alpha values on pages 26— GIF images have 1-bit transparency, which means that pixels are either fully opaque or fully transparent. PNG images have 8-bit transparency, which means that each pixel can have a variable level of opacity. The following examples show the difference, using the clouds. Be sure to add them to the sketch before trying each example.

Also, be sure that the image name is typed exactly as it appears in the file, including the case of the letters. And if you missed it, read the note earlier in this chapter about making sure that the file exten- sions are visible on Mac OS X and Windows. Fonts Processing can display text in many fonts other than the default. Before you display text in a different typeface, you need to convert one of the fonts on your computer to the VLW format, which stores each letter as a small image.

To do this, select Create Font from the Tools menu to open the dialog box Figure Specify the font you want to convert, as well as the size and whether you want it to be smooth anti-aliased. Create Font tool. NOTE: Make the font size selection carefully by considering the following: create the font at the size you want to use it in your sketch or larger , but keep in mind that larger sizes increase the font file size.

Create a PFont variable to store the font. Load the font into the variable with loadFont. Use the textFont command to set the current font. Example Drawing with Fonts Now you can draw these letters to the screen with the text function, and you can change the size with textSize. Notice that the characters are enclosed within quotes.

The second and third parameters set the horizontal and vertical location. The location is relative to the baseline of the text see Figure Typography coordinates.

We can store these words in a variable to make the code more modular. The String data type is used to store text data. They are explained, with examples, in the Typography category of the Processing Reference. Shapes If you make vector shapes in a program like Inkscape or Illustrator, you can load them into Processing directly.

As with images, you need to add them to your sketch before they can be loaded. There are three steps to load and draw an SVG file: 1. Create a PShape variable to store the vector file. Load the vector file into the variable with loadShape. Example Draw with Shapes After following these steps, you can draw the image to the screen with the shape function: The parameters for shape are similar to image.

The first parameter tells shape which SVG to draw and the next pair sets the position. Op- tional fourth and fifth parameters set the width and height. Example Scaling Shapes Unlike raster images, vector shapes can be scaled to any size without losing resolution.

In this example, the shape is scaled based on the mouseX variable, and the shapeMode function is used to draw the shape from its center, rather than the default position, the upper-left corner: NOTE: There are limitations to the type of SVG file that you can load. See the Processing Reference for PShape for more details. Robot 4: Media Unlike the robots created from lines and rectangles drawn in Processing in the previous chapters, these robots were created with a vector draw- ing program.

If the shapes are defined elsewhere and then loaded into Processing, changes are limited to the position, angle, and size.

Mann MD. Chestnut MD. Johnson MD. Flint MD. Cibas MD. McDermott MD. Mettler Jr. MD MPH. Jacobson MD. Helms MD. Bowman MS PhD. VanMeter PhD. Hall PhD. PDF Biomedical uses of lithium ePub. PDF Challenges and prospects of agricultural production and productivity Download. PDF Cloud Computing. Actionable Architecture ePub. PDF Instant Lucene. NET ePub. PDF Ist Fernsehen jetzt ueberall?

Techniques ePub. PDF Leaflet. PDF Logic of Knowledge. PDF Scrum versus Wasserfallmodell. Professional ADO. NET 3. Read Facebook-Kommentare als neue Kommunikationsform. German Edition PDF. Read Getting Started with Processing.



0コメント

  • 1000 / 1000