JS files for day 2


More or less what we had at the end of day 1, plus library bug fix.

Posted in Uncategorized | Comments Off on JS files for day 2

Introduction to Javascript

JS, ie. JavaScript, is in a lot of ways quite similar to Processing…

…But not quite.

JS is a general-purpose web programming language with dynamic “duck” typing, leaning heavily towards object-oriented paradigm, with a C-like syntax.

This is going to get a bit jargon-heavy, no matter which way we slice the cake here, sorry about that. We’ll talk about all this, so no need to try to absorb everything from here.

1) General-purpose, meaning that the language is suited for pretty much any kind of programs, ranging from simple interactions on a web page, to 2D and 3D games and desktop programs.

2) Web programming, in the sense that most of the JS still runs in the browser, on a web page. These days, you can use JS to build desktop applications, too.

3) Dynamic typing, meaning that the types of variables are not bound to what they were originally. You can declare a variable as an integer, and later on use that exact same variable as a, say, string, without converting it manually. This is both a burden and a joy, depending on how you think. The “duck” part comes from the expression: “If it walks like a duck and it quacks like a duck, then it must be a duck” – basically, when it comes to variables, this means that if we can use a shoe to hammer in a nail, to JS that shoe is a hammer.

4) Programming language, in the sense that it is a language we use to program computers.

5) Object-oriented, meaning that the language has built-in capabilities for *objects*. We’ll talk about that a bit later on this course, but for now it suffice to say that OOP – object-oriented programming – tends to be the most common way of conceptualizing software development these days. An *object* in OOP is just an aggregation of data and functionality. Don’t worry, it’s going to make more sense soon.

6) C-like syntax means just that the conventions with respect to delineating things like control flow, code blocks, et cetera, resemble the C language. This means we’ll be using a lot of curly braces and semicolons.

The practical implications here are, then, respectively:
1) We need to be a bit more careful about which parts of the whole language to use. As a rather complicated general-purpose language, there are some parts that are outright scary.
2) Development of JS is a bit different: Instead of some sort of JS environment (compare: Processing IDE), we’ll be using a text editor and a web browser.
3) We don’t need to (and can’t!) declare variable types. This will inflict all sorts of horrible suffering upon you at some point, if you’re not careful. When you get used to it, though, it’s actually pretty nice.
4) We gon’ learn to program computers.
5) Processing is even more object-oriented than JS. A lot of the stuff you’ll learn here about objects is relevant also in Processing, as well as languages like Java, C++, C# (used in Unity), and openFrameworks.
6) It’s almost like writing two dialects of the same language. Once you get used to the semicolons, they’re equally useful here as in Processing or any other C-family languages.

Apart from the language differences, there’s also cultural differences, especially with respect to things like libraries. JS developers tend to rely heavily on libraries: No matter what you want to do, somebody has usually done something quite similar to that, and it’s often quick and easy to use some already existing code. Furthermore, the libraries themselves are often updated on a very fast pace. This is a good thing, in the sense that you get the newest developments almost immediately, but the drawback is that larger projects are a pain to manage.

Posted in JS | Comments Off on Introduction to Javascript

Code files for JS day 1


Posted in JS | Comments Off on Code files for JS day 1

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 | Comments Off on Tools for the JavaScript part

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