Additional Processing exercises

More little Processing exercises. Not obligatory, just for rehearsing the topics we’ve covered. Example solutions included, but try first on your own.

  • Simple graphics. Create the familiar smiley face using the graphical capabilities offered by Processing. smileyface.pde
  • Variables. Declare two int variables with values 100 and 200. Print them, swap their values using a third variable and print again. swap.pde
  • Using the mouse. Make a crosshair that moves with the mouse. crosshair.pde
  • Loop and compare. Print all even numbers from 0 to 30, except 10 and 20. forbidden.pde
  • Animate and compare. Move a circle smoothly across the screen and change it to a rectangle in the middle. changemidway.pde
  • Arrays. For the first 100 frames, store the sum of mouse x and y coordinate in an array. savecoords.pde
  • Strings and arrays. Put five names into an array and print them on separate lines together with the line numer. names.pde
  • Functions. Turn the smiley face into a function that lets you plot it at any given location on the screen. Plot three of them to test it. smileys.pde
  • Return value. Make a function that takes two numbers as parameters and returns the bigger one. greater.pde
  • Random numbers, graphical text and type conversion. Create a font and load it. Each frame get a random number and display it at a random position. randomtext.pde
Posted in Processing | Comments Off on Additional Processing exercises

6. Types and conversions

Let’s start with a nice little trick: instead of running your sketch, present it to make it fullscreen (shift-command-r).

Decimal numbers (desimaaliluvut)

So far we’ve used only int type for our calculations. Often the precision is not enough: for example if you divide one by two you get zero instead of 0.5. For more precision we can employ floating point numbers (liukuluvut), which can store decimal numbers. Instead of int, declare your variable float:

float mynumber;

An example illustrating the difference between the two: intvsfloat.pde

Type conversion (tyyppimuunnos)

Processing is very strict about mixing variables and functions of different types. You can’t directly assign a variable of float into an int. For example random numbers in Processing are floats, and that’s why you can’t assign them to int variables without conversion. Fortunately, type conversion is easy to do:

int a=0;
float b;

A few more conversions here: typeconversion.pde

One type more

Often it’s handy to have variables that contain yes/no values. For them we have type boolean, which can only have values true or false. You can’t do any mathematical calculations with booleans.

boolean truth=true;

Displaying text

We’ve output text with println already, but to display text inside the sketch window we need to use PFont together with loadFont, textFont and text. Processing has its own bitmap font format. Save your sketch first and then click Tools – Create Font. How to do all of it: graphicaltext.pde. A bit more advanced: graphicalnumbers.pde

Sample project

Finally, let’s make a complete program that puts everything we’ve learned so far into use. First, we start by thinking of the needs and requirements, then proceed to designing the overall structure of the sketch, and only after that we start typing anything — do the same with your exercise task! paintprogram.pde

Posted in Processing | Comments Off on 6. Types and conversions

Tools for the JavaScript part

For the second part of the course, where you’ll learn JavaScript, install the following programs on your computer:

They can be found on school computers already, so if you use the classroom Macs, then no need to care about this.

Posted in HTML5-JS | Leave a comment

5. Functions, keyboard, images

Functions (Funktiot)

Also known as procedures or subroutines (aliohjelma) in many languages. They are a way to structure your programs to meaningful wholes for the sake of readability, and to avoid unnecessary copypasting of the same code over and over (you can also break your sketch to multiple files and have functions there separately). Like variables, functions too have a name, type and a scope. In addition to that they may have a return value and parameters. We’ve already defined two functions, setup and draw. We can create other functions exactly the same way:

void myfunc()
  println("Here we go!");

The function can be called by giving its name and parenthesis: myfunc(); This is exactly what we’ve been doing when we write things like size(640,480); or smooth(); How to make a simple function: simplefunction.pde


Parameters are a way to pass information to functions. When defining a function the parameters go inside the parentheses: type and name. Inside the function they are visible as any variables.

void printsum(int a,int b)

A complete example with parameters: parameters.pde

Return value

When the type of a function is void, it doesn’t return anything back to the caller. In many cases we need to get something back, such as information about whether there was a problem. If we define a function with a type (e.g. int), we can return things from it with return. Return will also stop the function and jump back to the caller. See returnvalue.pde


Like with the mouse, the simplest way to read the keyboard is to check the global variable keyPressed. If it’s true, key will contain the pressed key. It can be either a character in single quotes or a special value such as ENTER or BACKSPACE. However, when you get serious about it, both the mouse and keyboard are better supported using event handlers such as mouseClicked. A simple keyboard example: keyboard.pde. An advanced example of the use of event handlers: eventhandlers.pde


PImages let us load and display bitmap images (jpg/png/gif/tga). You can add images to your sketch through Sketch – Add File. You can also download them directly from URLs, but then they obviously won’t work, if you don’t have an Internet connection. Example images for today: player.jpg and football.png. How to load images and display them on screen: images.pde. A somewhat convoluted example with bouncing and all: bouncingball.pde.

Posted in Processing | Comments Off on 5. Functions, keyboard, images

4. Arrays, loops, types, random

Arrays (taulukot)

So far we’ve used variables, which let you store single values and work with them. Often we need to process large amounts of data, and single variables aren’t enough for that. Arrays let you store multiple values of similar type. Like variables, arrays too have: a name, a type, value(s), and a scope. In addition to that they have size, which is the amount of member in the array. So, if a variable is a box, an array would be a pile of those boxes.

An array can be declared the following way:

int ourstuff[] = {2,4,6,7,8};

After this line ourstuff is at our disposal and contains five numbers. It’s possible to create arrays also without assigning any values, only specifying their size. An array with 100 members:

int ourstuff[] = new int[100];

Array members (also known as items) can be used exactly like variables, through referencing (viittaus):

ellipse(ourstuff[1],ourstuff[2], 10,10);

The number inside the brackets is known as index. The first index in C-like languages such as Java and Processing is zero. So, for ourstuff the indices are in the range 0..4

Arrays and loops

In general, arrays go together with loops, especially for loops. With a loop you can walk through all the members of the array when needed. The loop counter is used as the index. Two examples: arrayloop.pde and circlesfromarrays.pde

Often we don’t know the size of the array beforehand, or its size might change. A safe way to go through all the items is to use the length property that all arrays have:

for(i=0; i<ourstuff.length; i++)

Strings (merkkijonot)

A new type coming up. Type int lets us use integer numbers, but there’s many situations when other types are needed. Textual information can be stored in type String. You declare a string as any other variable.

String mytext;

Assignment is the same. A string is enclosed in double quotes:

mytext="Never gonna give you up";

You can’t directly assign variables of one type to another type. You need type conversion.

Debugging exercise

Download the following sketch: mousefollowbuggy.pde and fix it! There are ten errors altogether: some of them just minor typos and some more conceptual problems. Here’s the fixed one: mousefollowfixed.pde

Random numbers (satunnaisluvut)

Random numbers are essential for many purposes, for example games where enemies appear at random positions at random intervals. They can be generated using the random function. A random number from 0 to 100 (excluding number 100) is generated by random(100):

line(random(100),random(100), random(100),random(100));

A larger example

Let’s combine most of the things we’ve learned so far. A sketch that draws squares that can be removed with a mouse click: clicktokill.pde

Posted in Processing | Comments Off on 4. Arrays, loops, types, random

3. Flow control

Flow control

In numerous cases we need to do things conditionally, a number of times, or until something happens. For those sort of purposes we have different flow control statements:

  • if – do something if a condition is true
  • if-else – do something if a condition is true, otherwise do something else. See ifelse.pde
  • for – repeat something a certain number of times. Consists of the initial counter value, condition and increment. See forloop.pde
  • while – repeat something as long as a condition is true. Quite rare in Processing because of the way interactive sketches work, but common in other languages and environments.

These statements start a compound statement, which is a block of code enclosed in braces. Anything you put in there will be run or repeated, according to the statements above. You can also nest the compound statements, placing them inside each other. Nesting example: nestedloops.pde

Comparison operators (vertailuoperaattorit)

All of the above need conditionals. Comparison operators are used for comparing two things, such as numbers or variables. Some of the most common ones we’ll use in the future are:

  • Equal: == (very easy to mix up with assignment, beware!)
  • Not equal: !=
  • Greater than: >
  • Less than: <

Grouping conditionals

Conditionals can be grouped, if you want to do more comparisons in the same time:

  • And: &&
  • Or: ||

For example: if(mouseX>100 && mouseX<200). A complete example: exitbutton.pde

Indentation (sisennys)

It’s a good common practice to indent the contents of compound statements a few characters to the right, so that they are visually aligned. This way you can instantly spot the statements that are on the same level. Processing will do most of it for you automatically, but if your code has gotten ugly, you can clean it up by selecting it and then clicking Tools – Auto Format.

One more nitty detail: to quit your sketch use command exit()

Posted in Processing | Comments Off on 3. Flow control

2. Variables (2), math, interaction

Recap of variables. Properties, declaration, assignment. Conflict with reserved words.

Simple mathematics in Processing

We can use variables for many kinds of calculations, such as addition (+), division (/), subtraction (-) and multiplication (*). In the mathematical statements we can use variables as well as numbers:


Optionally you can insert spaces to make it a bit more readable:

a = b/3 + a*3 -40 + c*b;

To see the number (will appear in the black box of the processing window) use print or println: println(a);

I’d rather not talk about these for now, but in a lot of tutorials and examples you will find things like this:


They’re only shorthand for a=a+1; and b=b-1; Use them only when you need to increment or decrement a variable by one, not in mathematic statements.

Interactive software

So far we’ve only made small sketches that are run once. For most uses we need to have the sketch running continuously. For this we need two things: setup (run once when the sketch starts) and draw (runs all the time). Things that you need once, like opening the window go under setup, things that are done continuously go under draw. This is a bit different to many other environments. An example program with setup and draw: setupdraw.pde

Comments (kommentit)

For the sake of clarity it’s essential to use comments. They serve both you and others reading your code. Comments are free-form and start with two slashes: // The rest of the line is ignored. Edit – Comment/Uncomment will do it automatically for you. Another use for comments is disabling a piece of code for testing purposes. comments.pde

Using the mouse

There are global variables named mouseX, mouseY, mousePressed and mouseButton, which you can use for simple interaction. Their values are updated automatically and they don’t need to be declared (they’re declared somewhere else). Their values can be used normally:

ellipse(mouseX, mouseY, 100,100);

An example doing something almost useful with a mouse: mousepaint.pde

Variable scope (näkyvyys)

Global variables, Local variables. Global variables are visible to all parts of the sketch. As a rule of thumb: the scope is the block enclosed in braces { }. Declaration must be done before use, too. Why are global variables bad? Different variable scopes in this example: variablescopes.pde

Posted in Processing | Comments Off on 2. Variables (2), math, interaction

1. Introduction, graphics, variables

Course structure, aims, assessment. A brief history and overview of programming languages (slides). Walkthrough of the Processing user interface.

Special characters

… and how to type them on a Finnish Mac keyboard. We’ll need many of these when typing in our programs, since they have special meanings. Finnish translations for the non-obvious ones included:

  • parentheses ( )
  • square brackets (hakasulut) [ ] – alt-8, alt-9
  • braces/curly brackets (aaltosulut) { } – alt-shift-8, alt-shift-9
  • asterisk *
  • slash (kauttaviiva) /
  • pipe (putki) | – alt-7
  • ampersand &
  • equal sign, “is” =
  • colon :
  • semicolon ;
  • comma ,
  • hash (“risuaita”) #
  • tilde (“mato”) ~ – alt-^-space
  • single quote (heittomerkki) – note that this is not the same as accent ´
  • double quote (lainausmerkki)
  • less/greater than < >

Program flow

Statements are executed (“run”) sequentially line by line. The order of the statements is crucial: changing it will result in completely different end results. Comparable to a cake recipe: there’s ingredients (data) and instructions what to do (program code, statements).

Basic graphics with Processing

size, background, point, ellipse, rect, fill etc. See the Processing reference for a complete list of graphical primitives supported by the language – there’s a lot at your disposal. An example sketch: simplegraphics.pde

Variables (muuttujat)

We could consider variables “boxes”, where you can store things. During the following lectures they will be used for several purposes such as counters, for holding status information such as mouse coordinates and for making the code more readable. In Processing every variable has a type, a name, a value and a scope. Before we can use a variable we need to declare (esitellä) it, which looks like this:

int whatever;

The type in this case is int, an integer number (kokonaisluku). The name we can choose freely, except that it can’t overlap with reserved words of the language. The value is set through assignment (sijoitus):


Finally, the scope is the area where a variable is visible. It can be global (yleinen) or local (paikallinen). More about that later. An example with a variable declaration and use: onevariable.pde

Posted in Processing | Comments Off on 1. Introduction, graphics, variables

Starting up again

Yet another round of Software Studies for Media Designers is about to begin. These pages will be updated throughout the course with examples, lecture material and so on. For now, you can check the MyCourses page for information on the schedule.

The course consists of two parts. First, there will be six mornings of programming basics with Markku Reunanen and Processing (if you wish to use your own computer, the tool can be downloaded for free from the website). The second half will be taught by Jukka Eerikäinen in JavaScript.

Welcome onboard, and as we like to put it: Programming is for everyone!

Posted in Uncategorized | Comments Off on Starting up again