Arranging an array of objects in a grid

@Chrisir
It took me a while, but I finally got the buttons to work. I had to add +50 to the void click() if-statements in class code to adjust for the translate (50, 50) in the main program.

Now I am trying to add another (“seemingly simple”) element of interactivity with the background color. Background color to randomly change with mouse click.

After numerous approaches have landed on void mouseClicked() function. Though as appears in my current code is not working. Am I on the right track here? Or is there a better / simpler way to do this?

Code begins ////////////////////////////

int grid = 5, many = grid*grid; // cells per row and column, # in total

Button [] myButtons = new Button [many]; // declaring Button class array

int r1 = int(random(255));
int g1 = int(random(255));
int b1 = int(random(255));

int r2 = int(random(255));
int g2 = int(random(255));
int b2 = int(random(255));


void setup() {
  size (600, 600);

  int x = 40, y = x, // dist from screen border
    w = 100, h = w, off = 5; // width and height of one cell, dist btwn cells

  int k = 0; // counter for button objects in array
  for (int i = 0; i < grid; i++) { // counter for xpos on grid
    for (int i2 = 0; i2 < grid; i2++) { // counter for ypos on grid
      myButtons [k] = new Button ( x + i * (w+off), y + i2 * (h+off), 
        w, h, 
        int(random(255)), int(random(255)), int(random(255)), // random colors 
        random(50, 125)); // random sizes
      k++;
    }
  }
}
void draw() {

  background (r1, g1, b1);

  translate (50, 50);

  for (int i = 0; i < many; i++) 
    myButtons[i].display();
}

/*void mouseClicked(){ // I want to change background color when I click mouse...
 if (background == r1,g1,b1) {
 background = r2,g2,b2;
 } else {
 background = r1,g1,b1;
 }*/


void mousePressed() {

  //background(r2, g2, b2);

  for (int i = 0; i < many; i++) 
    myButtons[i].click();
}

////////////////////////////////////////////////////////

class Button {
  float x, y, w, h;
  color r;
  color g;
  color b;
  float sz;
  boolean on = false; // button starts in OFF position

  Button (float tempX, float tempY, float tempW, float tempH, 
    color tempR, color tempG, color tempB, float tempSz) {
    x = tempX;
    y = tempY;
    w = tempW;
    h = tempH;
    r = tempR;
    g = tempG;
    b = tempB;
    sz = tempSz;
  }

  void display() {
    if (on) {
      fill (r/2, g/2, b/2);
      noStroke();
    } else {
      fill (r, g, b);
      noStroke();
    }
    
    rectMode(CENTER);
    rect(x, y, sz, sz);  
  }

  void click() {
    if (mouseX > x - w/2 + 50 &&
      mouseX < x + w/2 + 50 &&
      mouseY > y - h/2 + 50 &&
      mouseY < y + h/2 + 50 )
      on = !on; // toggle on / off
      
  }
}

Any thoughts most welcome!!

1 Like