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 | Leave a comment

8. Reading text files and recap

Reading text files

When creating data visualizations you often need to read a text file containing various values, interpret the contents and plot the result on the screen, mapping numerical values to size, color, location and so on. CSV (Comma Separated Values) is a common way of distributing open data or exporting numbers from Excel/OpenOffice/whatever to your own programs. Processing makes it easy to read all the rows of a text file into an array of strings with loadStrings:

String rows[]=loadStrings("datafilu.txt");

Again, you either need to add the file to the sketch first, or alternatively specify a URL instead of a filename (in case your data is online). After reading a text file consisting of numbers you usually need to convert the resulting strings to actual numbers (real or int) to do calculations with them. filereading.pde and asylumseekers.txt.

The above example is a very simple one: typically you have multiple values of different types on the same row. For more complex data, get familiar with split and splitTokens.

Recap

One more chance to rehearse everything we’ve covered throughout the course so far. There will also be small extra exercises posted here after the lecture. As I said at the beginning: this is not a Processing or JavaScript course, but a programming course. Instead of learning the quirks of a particular language, it’s much more useful to learn principles and concepts that apply in a number of contexts. Therefore, in the following list, we start with a problem, then present a general solution to it, and only then show what’s the syntax in Processing.

  • Storing things – variables and arrays – int, float, boolean, String …
    • Single variables are used for storing single values of a certain type. When we need to store multiple, we make an array. Each item of the array can be thought of as a variable of its own. In C, Processing and their relatives, brackets [] are used with arrays.
  • Assigning across types – type conversion – int(), str() …
    • A square peg won’t fit a round hole and vice versa. For assigning values between different types, we need type conversion. Note that at times you lose information when doing that.
  • Conditional doing – if and if-else
    • Very often we need to do something only if a certain condition is true: the mouse has been clicked, the player’s time is up, or the number we read was bigger than ten. An if statement will do that. Should we want to do something else instead, there’s if-else that tackles both cases.
  • Repeating things – loops – for and while
    • Instead of copy pasting the same code over and over again, we can use loops to repeat something multiple times: drawing multiple objects, walking through array items, and much more.
  • Documenting code – comments – //
    • Comments serve two main functions: first of all, they are there to make the sketch more readable for yourself  and especially for others who need to figure out what is going on. Another use is to temporarily take out lines of code to try out different variations.
  • Grouping code – functions
    • When dealing with large sketches, it doesn’t make sense to put everything under draw or setup. Lines of code that do something useful together and clearly constitute a whole can be turned into a function. Parameters are a way of passing information to a function, and a return value is something that comes back from it.
Posted in Processing | Leave a comment

7. Various bits

Because of the lack of time, we’ve had to skip a couple of topics, so let’s check random numbers and keyboard reading from previous days.

Constants

Constants look almost exactly like variables, but you can’t modify their content. With the keyword final a variable will turn into a constant, after which you can’t reassing new values to it. It is perfectly ok to use the value, though:

final int MYNUMBER=10;
int a;

a=MYNUMBER; // We can do this
MYNUMBER=11; // But not this

It’s a matter of taste and style, but writing constant names in ALL CAPS makes it immediately evident that they are not variables. But why do we need these constants? Some examples are fixed values that should never change, like PI. Another typical use is to replace numbers, such as screen coordinates or array sizes with a descriptively named constant that can be reassigned as needed in one go, instead of touching the code everywhere.

Building a little toolbox

Let’s put functions into good use again and build a couple of useful functions that will probably come in handy for your assignment, too. toolbox.pde

Circular and oscillating motion

Time to go back to your high school math and use sin/cos for drawing circles, ellipses and spirals. cos(angle) gives the x coordinate for a circle and sin(angle) the y coordinate. A couple of things to note: a full circle is 2*PI – Processing uses radians instead of angles. Another quirk is that, unlike with mathematical coordinates, the y axis points down, not up. circularmotion.pde

Posted in Processing | Leave a comment

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 type int to a float. 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;
b=float(a);

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;
truth=false;

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 | 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

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)
{
  print(a+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

Keyboard

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

PImage

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

Posted in Processing | Leave a comment

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):

ourstuff[1]=2;
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";
println(mytext);

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 | Leave a comment

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 | Leave a comment

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:

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

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:

a++;
b––;

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 | Leave a comment

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):

whatever=100;

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 | Leave a comment

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 Hung-Han Chen in JavaScript.

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

Posted in Uncategorized | Leave a comment