VISUAL/interactive programming

This page teaches you the basics of programming. We are using the framework P5JS to do so. P5JS is designed to experiment with interactivity, art and technology in creative ways. It can be used online through their website (link can be found below) and it can be used for making apps.

It is an online version of Processing that runs in your browser. The major difference is that P5.js uses javascript instead of java as programming language and syntax. However, for basic interactive things, they are very similar.

To start

Relevant offical links and ressources

  • P5.JS references (https://p5js.org/reference/): Use this to look up different syntax commands.
  • P5.JS editor (https://editor.p5js.org/): This is the online editor we will use.
  • P5.JS examples (https://p5js.org/examples/): Look through the different examples and get a sense of what they do. The examples can also be found in the drop down meny in the P5 editor (link above).
  • Also, do take a look at Daniel Shiffmans videos. They are very good and informative.

P5JS IDE

Introduction to the P5JS IDE

  • Make sure to login.
  • Make sure to save.
  • Notice that you can debug with print("hello") and it will show in the console.



p5js_ide.mov

(screenshot of p5js ide)

Long example: Programming PONG

Core_programming_session_one.mov

In this video I go through the core concepts of programming with P5.JS by programming a simple pong game.

The video is a bit fast paced, so do make sure to pause and scroll back and forth.

Also, it may be helpful to start with some of the more simple videos below.

Template

I have made my own template. This template differs from the base template in P5.JS in the following ways:

  • It has a simple gui element that allows you to create a debugging panel.
  • If you press "f" you switch to fullscreen mode.
  • It is prepared to work in fullscreen mode on mobile phones.

Click the link and duplicate the project for you to use it. Make sure to be logged in to be able to save.


setup() and draw()

Setup and draw are two functions. Setup runs once you start the app and draw runs for everyframe. This draw runs 60 frames pr. second, generating a frame each time.

function setup() {
  //runs once at startup.
}

function draw() {
  //runs for each frame
}

Notice how the curly brackets define start and end of each function.

Read more about p5js setup here and draw here.

p5js_drawsetup.mov

The canvas

The canvas defines the area in which you can draw when running the program. Notice:

  • It starts in the top left corner. The same as the reading direction, but opposite of normal graphs.
  • The x axis is left to right. The y axis is top to bottom.

The size of the canvas is typically defined in the setup function. Here it has a width of 500 and a height of 400:

createCanvas(500, 400);

Read more about createCanvas here.

p5js_canvas.mov

Drawing on the canvas

Drawing on the canvas can be done by calling different commands. E.g. ellipse(x,y,width,height) will place a circle. fill(255,0,0) will define its fill color. In this case the circle will be red.

function setup() {
  //runs once at startup.
}

function draw() {
  fill(255,0,0);
  ellipse(100,100,20,20);
}

Read more about how to use fill here, and how to draw basic shapes such as an ellipse, a square or a triangle.

p5js_drawing.mov

The core concepts of programming in P5JS

Most programming languages consists of the same set of elements. Below I try to introduce you to the coding syntax and concepts of them. The core concepts are:

  • Decisions: Making choices on the fly.
  • Scopes: Grouping multiple commands.
  • Memory: A way to store information (variables) dynamically.
  • Repetition: A way to repeat groups of code.
  • Macros: A way to reuse code and structure the logic.
  • Lists: A way to store lists of information.
  • Objects: Grouping information and macros together.

Below I made short videos for each core concept and its syntax.


Programming Core Concepts
This google slide presentation on the right presents them in a compressed manner. It is essentially the different concepts and syntax you will typically need to know. You can use it to get an overview of what you need to learn, and also to look up when you are going to write similar code yourself.

In the video guide below we are going to build a litttle tree generator. You can find the code for it here:

https://editor.p5js.org/hobyedk/sketches/nF3ALb7OJ

Decisions with if statements

Interactive programming is essentially about making decisions. If x happens then do y. The basic syntax making decisions is:

if (2==2) {
   ellipse(200, 200, 70, 70);
} 

If the condition 2 equals 2 is met then the ellipse will be drawn on the screen.

Further, "else" can be used to execute something if the condition is not met:

if (2==3) {
    ellipse(200, 200, 70, 70);
} else {
    rect(200, 200, 70, 70);
} 

In the above case 2 is not equal to 3 so the ellipse will not be drawn, but the rectangle will.

Multiple if statements can be combined with "else if":

  if (2==2 && 2>1) {
    ellipse(200, 200, 70, 70);
  } else if (true) {
    rect(200, 200, 70, 70);
  } else {
    // do something here
  }

Only the first condition which is true will run.

Different formulas can be made with: <, >, ==, != and conditions can be combined with && (and), II (or).

Read more about p5js setup here and draw here.

p5js_if.mov
A common mistake is to put semicolon after if statements. This will not result in an error but the scope beneath will always execute. Leading to utter confusion. See the following section about commands and scopes.

Grouping commands with scopes

A command is e.g. when you write print("xx"); to write into the console. A command typically ends with ";" EXCEPT when it is followed by a scope. E.g.:

print("hello world");
if(2==2)
{ // start of scope
  print("Two does equals two");
  print("Second command");
} // end if statement and scope

Notice where the ";" and the curly brackets are placed.

A scope is multiple commands grouped together. Scopes start and ends with curly brackets. They define a group of code that is executed when a certain condition is met. In the previous you learned about if statments. Notice how the scope after the command "if" is only executed when the condition of the if statement is met. And also notice that there is no semicolon at the end of the if statement.

Also, scopes can be nested. A scope can have scope inside itself. This allows conditions to be more complex. E.g. if you are at the supermaket then buy milk if they have a low fat version. This is two scopes nested inside each other.

if(inSuperMakert==true)
{// first scope start
   if(hasLowFatMilk==true)
   { // nested scope
      print("buying milk!");
   }
}

It can be difficult to wrap your head around this concept. I often wonder if this is the most essential part to be able to program.

Read a detailed description about how to understand scopes here. This link presents some different versions of scopes that may come in handy.

p5js_scopes.mov

Common mistakes and how to fix them

When starting out programming you will make a few common mistakes. This lists some of them and how to fix them:

  • Forgetting a semicolon: If you forget to put a semicolon at the end of a line the program will not run. Add the semicolon where missing (usually the line above the one that throws and error).
  • Adding a semicolon after an if statement: There should newer be a semicolon after an if statement. This one is hard to detect because the program will run, but it will always run the code inside the curly braces {}.
  • Too many or too few curly braces. Be very carefull with your curly braces if you add too many or have to few the program will not run. Make sure to indent your code properly so you are able to read it. Everything inside a curly brace should be indented.

Memory: Storing information with variables

A variables is a container of information that can be changed during runtime.

var x = 200;

In the above case we have declared a variable with the name "x" and given it a value of 200. We can then change the value by:

x = 300;

To incriment it by one:

x = x+1;

This also incriments by one:

x++;

There are different kinds of variable types. They are defined implicitly by adding content to it. E.g. a boolean (true or false) can be defined like this:

var playMusic = true;

Through variables we can execute different parts of the program with if statements:

if(playMusic == true)
{
// code to play music here
}

If playMusic is true, the code inside the curly brackets will run.

Notice how we use one equal sign (=) when defining variables and two equal signs (==) when comparing a variable to a value.

We typically declare a variable at the top. This way we have global access to them since they are in the global scope. If we place the definition inside e.g. function draw() we will only have access to it inside the scope of the function and it will be reset everytime we run the function.

Read more about different data types here. In this link you can find descriptions of booleans, numbers, strings, and more.

p5js_variables.mov
These are typical variables types:

Repetition with loops

If we want to reapeat a piece of code more than once we can use different kinds of loops to do so. The most common is "for" loops. It is usually used when you have a specific amount of repetition you want to do:

for(var i = 0; i < 10; i = i +1)
{
  print(i);
}

The above code will repeat itself ten times. "i" will be the counter that will increment one for each repetition as long as i is less than 10. Since the starting value is zero (a common logic in programming) the loop will repeat ten times until it reaches 9 (not ten, which is a common confusion, as it has to be less than 10).

for(Initialization; condition; incrementation)

A for loop has three parameters seperated with a semicolon:

  • Initialization: Sets the initial value.
  • Condition: Choose when to stop the repetion.
  • Incrementation: Defines how much the variable should incriment.

Another loop used for repetition is a while loop. The following code will loop endlessly:

while(true)
{
// this loop will repeat itself forever.
}


Read more about for loops here and while loops here.

p5js_for.mov
A for loop can be converted to a while loop. This does the same as the for loop mentioned.

Macros with functions

When programming you often have a sequence of commands you want to run at different times in the duration of your code. This can be small macros like converting from inches to mm and it can be more complex elements. These sequences are grouped in function. Let us say that we have an application the needs to draw a lot of houses. Instead of copying multiple drawing commands for each house, we can make a function to draw a house an call it multiple times:

function drawAHouse()
{
  rect(50,50,20,20);
}

The house is in this case just a square. The problem is now that we do not have a way to place the house in different places. E.g. the house will always be drawn in position (50,50). We solve this by adding parameters to the function:

function drawAHouse(x,y)
{
  rect(x,y,20,20);
}

x and y are local variables, which we could give these values:

drawAHouse(40,30)

This house will now be drawn in position (40,30) and we call it multiple time with different parameters .

Functions can also return something. Let's say that we want to have a function which converts from meters to milimeters:

function mToMM(length)
{
  return length*1000;
}

print(mToMM(10.2));

Calling mToMM(10.2) will convert the 10.2m to 10200 MM.

Read more about creating functions here or in more detail here.

p5js_function.mov

Lists' of variables with arrays

Often one wants to have a list of elements. This can be particles in a particles system or a list of employees in a company. For this to work we need to group variables together in a list that we can iterate through. This is called an array. An array is a variable containing a list of variables. Square brackets are used to define it as a list:

var names = [];

This is a empty list. We can predifine it with content:

var names = ["Peter","Lisa", "Olga"];

If we want to get the first name:

print(names[0]);

This prints "Peter".

We can add a name to the list like this:

names.push("Mads");

If we want to print out all the names in our list, we can use a for loop:

for(var i = 0; i < names.length; i=i+1)
{
   print(names[i]);
}

Notice that the for loop repeats until it has reached the length of the list and the "i" from the for loop is used to retrieve the individual names.

Read more about arrays here or in more detail here.

p5js_list2.mov

Objects with groups of functions and variables

This is by far the most complex thing to understand. To simplify we need to make an analogy. Put simply, I have a Toyota Car. My Toyota is an object like any other object in this world (chairs, gloves, plants). My Toyota is of the classification "car", and not of the type "plant". So if we want to create my car as an object in code, we need to create a classification that we can make it from. A classification can then be used to create an instance as an object (e.g. "my car" is made from the classification "a car"). We define a classification as follows:

class car()
{
   constructor()
   {
     this.name="";
     this.wheels=4;
     this.topSpeed=200;
   }
}

Notice the function "constructor". This is a special function that constructs the different variables that makes up the car. "This" refers to the car class.

If we want to create an instance (object) of the classification car:

var myCar = new Car();

This executes the constructor that defines the variables (name, wheels and topSpeed).

We can then access and change the variables in our newly created car object:

print(myCar.wheels);

This will print the number of wheels (in this case four).

p5js_class2.mov

Let us say that myCar has three wheels then we can set it to three:

myCar.wheels = 3;

The "." is called dot notation and is a central part of many programming languages. Dot notation allows os to acces variables inside objects and also objects inside objects, etc.

We can embed functions inside an object like this:

class car()
{
   honk()
   {
      //Play honk sound here.
   }
}

This would be executed by calling:

myCar.honk();

Read more about class and constructors here or here.