Processing: Functions, Maths and Pseudocode

void setup(){
  size(800, 400);
  background(0);
}

void draw(){
  if(mousePressed){
    if(mouseButton==LEFT){
      fill(255,0,0);
    }else{
      fill(0, 0, 255);
    }
  ellipse(mouseX, mouseY, 10, 10);
  }
  
  
}

Press the mouse buttons in the sketch to create red and blue circles

In the last lesson we learned about using functions to create conditions to an action. In the above code the conditional statement if is used to make the code react from the user’s mouse being pressed. If any of the mouse buttons are pressed, blue dots follow the mouse, however if the left button is pressed red dots appear.

To break down this function it would be easier to write it in pseudocode on paper first before actually coding it.
In pseudocode this would be:

if MOUSEPRESSED{
MAKE CIRCLES follow the mouse
if MousePressed is LEFT{
CIRCLES ARE RED
}
ELSE CIRCLES ARE BLUE
}

Pseudocode is useful as it allows a programmer to break down a problem before coding. It helps to visualize the problem into smaller chunks and allows the programmer to see what problems need to be addressed. There is no need to use proper syntax or to do things such as declare variables but it is very helpful especially with very complex programs.

Next in class we played with using mathematical expressions to create different patterns. Here the rectangles are rotated each time by using the rotate function and the expression r + 4 to rotate the square each frame. Size is controlled by (s+2)%200 . The % called modulo, calculates the remainder when (s+2) is divided by 200.

void setup(){
size(600,600);
colorMode(HSB, 100);
}
 int r = 0;
 int s = 1;

void draw(){
fill(55,100,100,10);
translate(width/2, height/2);
rotate(r);
rect(0, 0, s, s);
r= r+4;
s=(s+2)%200;
//saveFrame();
}

There is also the saveFrame command (which is commented out) which would save each frame of the code into the folder of the processing sketch, and can be used to create videos from Processing.

Princeton.edu, 2014. Pseudocode. [online] Available at: https://www.princeton.edu/~achaney/tmve/wiki100k/docs/Pseudocode.html [Accessed 18 Nov. 2014].

Leave a Comment