Loops tutorial exercises!

Syntax of loops:

Anatomy of a for loop:

for (int y = 0; y < height; y += 15) {
  stroke(0);
  rect(10,y,10,10);
}

Anatomy of a nested loop:

for (int y = 0; y < height; y += 15) {
  for (int x = 0; x < height; x += 25) {
    stroke(0);
    rect(x, y, 10, 10);
  }
}

LOOP EXERCISES!!

For these exercises, you may not use the mouse button, use mouse location system variables mouseX and mouseY. Restrict yourself to black and white.

L1 — Interaction and Iteration: One Line
Develop a composition which in which one (straight) line responds to the position of the cursor.

L2 — Interaction and Iteration: Ten Lines
Develop a composition which in which ten straight lines respond to the cursor.

L3 — Interaction and Iteration: 100 Lines
Develop a composition which in which one hundred lines respond to the cursor.

L4 — Interaction and Iteration: 1000 Lines
Develop a composition which in which one thousand lines respond to the cursor.

REVISION: For loops

Functions tutorial example.

Modify the following example so that the steps: draw ball, move ball and check edges are discrete functions.

float y=50;
float x=200;
float yspeed = 9;  // Speed in y
float xspeed = 2; //Speed in x

float gravity = 0.1;


void setup() {
  size(400, 300);
  noStroke();
  frameRate(60);
}


void draw() {
  background(102);

  //MOVE BALL
  //change x position
  x=x+xspeed;

  //change y position
  y=y+yspeed;


  //CHECK EDGES
  if (y>height || y<0) {
    //multiply it by 0.8 so it looses some speed
    //negative so it changes direction.
    yspeed=yspeed*-1;

    //correct rounding error
    if (y<0) { 
y=0; 
} 
} //check if we get to the sides of the screen 
if (x>width || x<0) { 
xspeed = xspeed*-1; //correct rounding error 
if (x>width) {
      x=width;
    }
    if (x<0) {
      x=0;
    }
  }

  //DRAW BALL
  ellipse(x, y, 30, 30);
}

REVISION MATERIALS: Video tutorials on functions

Conditionals – For loops – Exercise

Conditionals Exercises:

To be done in pairs.

Do each as a separate sketch of 400 x 400 pixels, with a square in the middle.

1) Draw a white square that turns black when the mouse rolls over it. Have it go back to white when the mouse rolls off it.

2) Draw a white square. When it is clicked, have it turn black and stay that way.

3) Create a reactive box, such that each click in the square flips its color from white to black (if it is white), or from black to white (if it is black).

Challenge:
4) Create a reactive square, such that two clicks are required to turn it from white to black, but three clicks are required to turn it from black to white.

For video tutorial review on conditionals: