Tutorial on Processing: loadImage, random, MousePressed, text, export This tutorial describes 3 different Processing sketches, each simulating the tossing of a coin. The simplest application performs the simulated flipping once/second. The second sketch displays a head or tail when the player clicks on the mouse. The image is located at the mouse position. Nothing is erased, so more and more images appear in the display window. In the third sketch, when the player presses the mouse button on the display window, an image representing a head or a tail of a coin appears on the screen. Previous images are erased. A tally of the heads and tails is shown in the upper corner. Since the display window is erased, this tally must be displayed again on the screen. Since there is an issue of timing—I don't want to over-count heads or tails if a player's finger is down too long on the mouse button, the looping of the draw function is turned off and on. Developing an application in steps like this is a good way to approach any programming task. The critical parts of these applications are Images Random processing Mouse events Text Images Three steps are necessary to display images. Images are a datatype in Processing. A variable must be declared of type PImage. The second step is to set the variable using loadImage. Use the Sketch/Add File command to add the image files to a special folder called the data folder. [Note: it is possible to manually copy the image files to the folder containing the sketch or to make a relative reference. However, if this is done, it will be necessary to manually add the files when the sketch is exported. See below.] The loadImage function references the image file. The final step is to display the image. This is done using the image command. It takes 5 arguments: a PImage variable, an x and a y position, and a width and a height. Here are examples of these 3 statements: PImage coinh; coinh = loadImage("head.jpg"); image(coinh,10,20,100,100); Exercises: 1. Find any image and make it appear on the display screen. You can use the Basic mode of operation here (no setup function). You need to use size statement, a declaration, loadImage and Image. I did this using relative addressing to use one of the coin images: 2. Amend the code to make two or three copies of the same image appear. Make them different sizes and at different positions. 3. Find images for the head and the tail of a coin. Random processing Random, or more properly termed pseudo-random processing, is necessary for many games and also for applications that simulate conditions involving random activity. Most programming languages have a way of generating numbers within a range where each number occurs with equal probability and there is not discernible pattern. Research is still active in developing good pseudo-random number generation. We will assume that the facility in Processing is good enough. The function random(1) returns a fraction (floating point number) between 0 and 1. My code simulates the flipping of a coin by using a conditional if (.5<random(1)) { make a head image appear} else { make a tail image appear} Exercises: 1. Go to Help/Reference and read about the different ways to use random and also about randomSeed. 2. If you needed to simulate tossing a standard 6 sided die (singular of dice), how would you do it? Hint: look up int() and think about using int(random(6)) to get a random integer. You do need to think about the endpoints so 1+int(random(5)) It is now possible to explain the first sketch in which images of heads or tails appear on the display window. The code consists of the declaration of two variables to hold images, the setup definition in which the display window is sized, the two image variables set and the frame rate set to 1 per second. The definition of the draw function. This is called 1/second. It uses an if statement as just described to produce an image using the head image or the tail image. The code is the following: PImage coinh,coint; void setup() { size(600,600); coinh = loadImage("head.jpg"); coint = loadImage("tail.jpg"); frameRate(1); } void draw() { if (.5<random(1)) { image(coinh,50,50,300,300); } else { image(coint,50,50,300,300); } } Run the program. Exercises: 1. Modify the size of the image. 2. Modify the position of the image. You make heads and tails appear in different places. Notice that this program does not erase (re-do the background), so images appear on top of previous images. 3. Simulate a biased coin. That is, make it so that over time heads will appear twice as often as tails. You need to change .5<random(1) to be something else! Mouse events For the second and third application, the coding must detect that the mouse button has been pressed and also determine the x,y position of the mouse on the display window. Processing appears to recognize just one button; for PC computers, this is the left button. Processing provides the mousePressed() function. This is similar to setup() and draw(). The programmer defines the function, that is, specifies the code between the brackets, and the Processing system invokes it exactly one time whenever the mouse button is pressed. The programming jargon for this is that the event of mouse button being pressed is handled by the mousePress() method, as specified by the programmer. The positions of the mouse are given by the built-in variables mouseX and mousey. One requirement to use mousePressed () is that there must be a draw function defined even if it is empty. Processing provides another way to determine if the mouse button is being pressed, the variable mousePressed. This can be used as a condition. NOTE: the difference between the two is one is a variable and the other is a function, requiring opening and closing parentheses. The code for the second coin application is: PImage coinh,coint; void setup() { size(600,600); coinh = loadImage("head.jpg"); coint = loadImage("tail.jpg"); } void draw() { //necessary to allow mousePressed to work } void mousePressed() { if (.5<random(1)) { image(coinh,mouseX,mouseY,100,100); } else { image(coint,mouseX,mouseY,100,100); } } Exercises: 1. Processing provides 3 other functions for event handling for mouse events: mouseReleased(), mouseMoved(), and mouseDragged(). Look them up in Help/Reference. Write a sketch that makes the background red when the mouse button is pressed and blue when the mouse button is released. 2. See #1. Write a sketch that moves an image (it can be the head or the tail image) to where the mouse is when the mouse moves, no pressing. Write another program that allows the user to drag an object around. 3. Program a sketch that creates an image when the mouse is pressed down and then allows the user to drag it around the display window. Text Processing provides ways to display text in the text area (below the editing panel) as well as in the display window. Typically, the text area is used during debugging (developing and testing) your work. The two functions for printing to the text area are print() and println(). Each call of println will produce a new line of text. Both of these functions take as input numbers or strings (or colors) and you can combine terms using the + sign for concatenating strings. For example, if you wanted to check the value of a variable in your sketch called headc, you could write println("headc is "+headc); Displaying text in the display window can be useful for giving your user information, such as scores of a game. In the third coin application, the running total of heads and tails is displayed. Processing provides the feature that you can use any font available on your computer at any size. The fill() function sets the color of the text. NOTE: there are two ways to access fonts in Processing. One approach is to use the Processing environment to create a font in the Processing format. This font can then be accessed using loadFont(). The other approach is to create a font on the fly, so to speak, during the sketch, from one on your computer. Go to Help/Reference and read about loadFont() and createFont(). The steps for displaying text are: declare a variable of datatype PFont, set the value of that font, using either loadFont() or createFont(); call the textFont function with the font as the argument; lastly use the text() function to display data at a specific x and y location on the display window. The text function also provides for specifying the width and height of the display if it is string data. When working in 3D, you can specify the z coordinate. In the 3rd coin sketch, I use 6 variables: coinh and coint are datatype PImage font is datatype PFont str is datatype String headc and tailc are datatype int my setup function does the work of defining the font and setting it to be what is used by a call to textFont. The draw() function is empty, but required because of the use of mousePressed. The mouthPressed erases everything by invoking background. The next statement is the compound if/then/else that displays one of the two coin images and increments the appropriate counter: headc or tailc. The next statements (outside the if/then/else) display the counts. This is 4 calls to text. The code for the sketch is: PImage coinh,coint; PFont font; String str; int headc,tailc; void setup() { size(600,600); coinh = loadImage("head.jpg"); coint = loadImage("tail.jpg"); headc = 0; tailc = 0; font = createFont("Ariel",20); textFont(font); } void draw() { } void mousePressed() { background(255); if (.5<random(1)) { image(coinh,mouseX,mouseY,100,100); headc = headc +1; } else { image(coint,mouseX,mouseY,100,100); tailc = tailc + 1; } fill(0); text("Heads ",10,20); text(headc,10,50); text(" Tails ",80,20); text(tailc,80,50); } After entering the code into the text editor panel, click on the run arrow to try it. You or your user/player needs to know to click the mouse on the panel. Exercises: 1. Experiment with the colors. In particular, try making the headings Heads and Tails black and the actual counts underneath them red. 2. Provide the user/player instructions: use fill and then text to display a message: "Click the mouse button to toss a coin". Make this part of the setup() function. 3. Implement a biased coin, say one in which tails will come up, over time, 3 times as often as heads. 4. Use println and print to display the headc and tailc counts. Exporting applets and applications The sketches created in this and the previous tutorials were run within the Processing environment. Once a sketch is complete, you may want to produce an application to run independently on your computer or on the Web. The commands to do this are under the File menu. In both cases, the Processing system produces and compiles the sketches as Java programs. Export Application produces folders for Windows, Mac and Linux. Export produces what is called a Java applet: a folder for uploading to the Web. The folder includes a file named index.html. The files in the data folder are carried over to the resulting applet or application.