Code

/* Draws a 100x100 square in black or white. The color of the square changes from black
 * to white (or visa versa) when the user clicks on it. The background color and
 * position of the square also change to a random value when the user clicks the square.
 */

color bgColor = 0xFF707070;  // Initial background color is gray
color sqColor = 0x000000;    // Initial square color is black

int sqWidth = 100;  // Width of square
int sqX = 200,      // Initial positions of square
    sqY = 200;

void setup() {
  size(400, 400);
  background(bgColor);  
}

void loop() {
  background(bgColor);
  stroke(sqColor);
  fill(sqColor);
  rect(sqX, sqY, sqWidth, sqWidth);  
}

void mouseReleased() {
  if(get(mouseX, mouseY) != bgColor) {//intersected the square
    // Flip color of square
    sqColor = ~sqColor;
    
    // Randomly choose a square position
    sqX = (int)random(width-sqWidth);
    sqY = (int)random(height-sqWidth);
    
    // Randomly choose a background color that is not white or black
    bgColor = color(random(1, 254), random(1, 254), random(1, 254));
  }
}

020 -- Flipping Square I: State Machines

Statement:Assignments numbered 02x will be due February 1.

This exercise tests your ability to maintain system state in some sort of variable, and also asks you to devise a way of testing the containment of a point (the cursor) within a special region (a reactive square).

In a 400x400 canvas, create a 100x100 pixel reactive square, 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). Mouse clicks outside the square should have no effect! This example may be helpful to you.

hide statement