Dave Drohan (SETU)

BACK NEXT

Variable scope (local and global)

In this step, we will implement the code examples 4.1 - 4.4 from your lectures.

Understanding variable scope

Create a new Processing sketch and call it Example_4_4. Note that we will be working through fixing the bugs we discussed in lectures and finish by saving just the completed, bug free version (i.e. 4.4).

Enter the following code into your sketch (one again, try avoid the temptation to cut and paste the code…the more mistakes you make when writing out code, the more you learn!):

void setup() 
{
  size(500,400);
  background(0);
  stroke(255);
  fill(45,45,45);
}

void draw() {
  int diameter = 100;
  if (mousePressed) 
  {
    diameter = diameter  10;
    background(0);
  }
  ellipse(mouseX, mouseY, diameter, diameter);
}

Run your code. Is your circle reducing in size? Repeatedly press the mouse button…do you see a bug?

To fix this, change your code so that the diameter variable is now global scope:

//The diameter variable is now global scope
int diameter = 100;

void setup() 
{
  size(500,400);
  background(0);
  stroke(255);
  fill(45,45,45); 
}

void draw() 
{
  if (mousePressed) 
  {
    diameter = diameter - 10;
    background(0);
  }
  ellipse(mouseX, mouseY, diameter, diameter);
}

Run your code. Does it work as you would expect now?

There is a problem with the code. In the ellipse method, the width and height are absolute values (the negative sign is dropped…processing only cares about the magnitude).

To handle this logic bug, we need to stop reducing the diameter by 10 when we reach a certain value, say 20.

Implement this code boolean condition in your code and test it again:

int diameter = 100;

void setup() 
{
  size(500,400);
  background(0);
  stroke(255);
  fill(45,45,45); 
}

void draw() 
{
  //boolean condition added to stop reducing the diameter when it reaches 20.
  if ((mousePressed) && (diameter > 20))
  {
    diameter = diameter - 10;
    background(0);
  }
  ellipse(mouseX, mouseY, diameter, diameter);
}

Did you notice that it seems the reduction appears larger than 10 when we press the mouse?

Why? The default frame rate is 60 refreshes of the screen per second i.e. draw() is called 60 times per second.

You can change the frame rate by calling the frameRate() function and passing a parameter of, say, 20. This will mean draw() will only be called 20 times in a second.

Make the change to the framerate:

int diameter = 100;

void setup() {
  size(500,400);
  background(0);
  stroke(255);
  fill(45,45,45); 
  frameRate(20);   //slowed down to 20 refreshes per second.
}

void draw() {
  if ((mousePressed) && (diameter > 20)){
    diameter = diameter - 10;
    background(0);
  }
  ellipse(mouseX, mouseY, diameter, diameter);
}

Now your code should run as expected.

Save and close your sketch.