Dave Drohan (SETU)

BACK NEXT

Writing your own methods (1)

In this step, you will work on reproducing the code examples 5.2 to 5.5 inclusive from your lectures.

Example 5.2

Create a new Processing sketch in your workspace and call it Example_5_2.

Write a method called drawRedSquare that takes no parameters.

The return type for this method is void.

The method body should include the following processing:

The drawRedSquare method should be called from the draw() method.

Run your code; a red square should be drawn on the display window.

The solution code is:

void setup()
{
  size(200,200);
  background(20,70,105);
}

void draw()
{
   drawRedSquare();
}

void drawRedSquare()
{
  fill(255,0,0);
  rect(70,70,60,60);
}

Example 5.3

Create a new Processing sketch in your workspace and call it Example_5_3.

Write a method called drawRedSquare that takes one parameter of type int. This parameter will be used to set the length of the square.

The return type for this method is void.

The method body should include the following processing:

The drawRedSquare method should be called from the draw() method, passing the value 60 as its argument.

Run your code; a red square should be drawn on the display window.

The solution code is:

void setup()
{
  size(200,200);
  background(20,70,105);
}

void draw()
{
   drawRedSquare(60);
}

void drawRedSquare(int length)
{
  fill(255,0,0);
  rect(70,70,length, length);
}

Example 5.4

Create a new Processing sketch in your workspace and call it Example_5_4.

Write a method called drawRedSquare that takes three parameters. Each of the parameters is of type int:

The return type for this method is void.

The method body should include the following processing:

The drawRedSquare method should be called from the draw() method, passing the values 60, 70, 40 as its arguments.

Run your code; a red square should be drawn on the display window.

The solution code is:

void setup()
{
  size(200,200);
  background(20,70,105);
}

void draw()
{
   drawRedSquare(60,70,40);
}

void drawRedSquare(int length, int xCoord, int yCoord)
{
  fill(255,0,0);
  rect(xCoord,yCoord,length, length);
}

Example 5.5

Create a new Processing sketch in your workspace and call it Example_5_5.

Enter the following code into the sketch (don’t cut and paste, write it out):

void setup() 
{ 
    size(200,200); 
    background(20,70,105); 
}

void draw()
{
    for (int i = 1; i < 7; i++)
    {
        drawRedSquare(25, i*25, i*20);
    }
}

void drawRedSquare(int length, int xCoord, int yCoord)
{
    fill(255,0,0);
    rect(xCoord,yCoord, length, length);
}

This code calls the drawRedSquare method multiple times (using a for loop).

Run your code. Does it work as you would expect? Are 6 red squares drawn on the display window?

Now try re-write the for loop so that it is a while loop. Run and test your code again. There should be no changes in the display window.