Arranging an array of objects in a grid

Hi @Chrisir,

  1. I made the changes as outlined above regarding the variable color colRect and it now looks as below. And I now understand where I went awry…

Thank you for your guidance with this! :grinning:

int gridX = 5; 
int gridY = 5;
int many = gridX*gridY; // 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));

color background = color ( r1, g1, b1) ;  //!!!!!!!!!!!!!!!!!!!!!!!!


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

  int x = 40 + 50, 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 < gridX; i++) { // counter for xpos on grid
    for (int i2 = 0; i2 < gridY; i2++) { // counter for ypos on grid
      myButtons [k] = new Button ( x + i * (w+off), y + i2 * (h+off), 
        w, h, 
        color (random(255), random(255), random(255)), // random colors
        color (random(255), random(255), random(255)), // new random colors when on / off toggle 
        random(50, 125)); // random sizes
      k++;
    }
  }
}
void draw() {

  background (background);  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

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

void mouseClicked() { 
  
  background = color(random(255), random(255), random(255));
  
  }

void mousePressed() {

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

Button Class ///////////////////

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

  Button (float tempX, float tempY, 
    float tempW, float tempH, 
    color tempColor, color tempColor2,
    float tempSz) {
    x = tempX;
    y = tempY;

    w = tempW;
    h = tempH;

    colRect = tempColor;
    colRect2 = tempColor2;
    
     sz = tempSz;
  }

  void display() {
    if (on) {
      fill (colRect2);
      noStroke();
    } else {
      fill (colRect);
      noStroke();
    }

    rectMode(CENTER);
    rect(x, y, sz, sz);
  }

  void click() {
    
    if (mouseX > x - sz/2  &&   // !!!!!!!!!!!!!!!!
      mouseX < x + sz/2  &&
      mouseY > y - sz/2  &&
      mouseY < y + sz/2  )

      on = !on; // toggle on / off
  }
}
3 Likes