Change color of one rect in grid

Hi everyone!

I created a grid of rects using a 2d array. I now want to be able to click on a rect and have it change its color. With the code I have now, all rects change color when clicked. What am I doing wrong?

int no = 16;
int rectW;
int rectH;
int cols = no / 2;
int rows = no / 2;
int[][] rects; 
color p = 255;

void setup() {
  size(600,600); 
  background(150);
  rectW = width / rows;
  rectH = height / cols;
  rects = new int[cols][rows];
}

void draw() {
  background(150);
  drawGrid();
}

void drawGrid() {
  for (int i=0; i<cols; i++) {
    for (int j=0; j<rows; j++) {
      fill(p);
      rect(i*rectW,j*rectH, rectW, rectH, 5);
    }
  }
}

void mouseClicked() {
  for (int i=0; i<cols; i++) {
    for (int j=0; j<rows; j++) {
      int x = i*rectW;
      int y = j*rectH;
      if(mouseX >= x && mouseX <= (x+rectW) && mouseY >= y && mouseY <= (y+rectH)) {
          p = 0; }
    }
  }
}
1 Like

Without OOP it’s a little bit confuse but you can try this

int no = 16;
int rectW;
int rectH;
int cols = no / 2;
int rows = no / 2;
int[][] rects = new int[cols][rows];
color[] p = new color[cols*rows];
void setup() {
  size(600,600); 
  background(150);
  rectW = width / rows;
  rectH = height / cols; 
  for(int i=0; i<p.length; i++) p[i] = 255;
}
void draw() {
  background(150);
  drawGrid();
}
void drawGrid() {
  for (int i=0; i<cols; i++) {
    for (int j=0; j<rows; j++) {
      fill(p[i+j*cols]);
      rect(i*rectW,j*rectH, rectW, rectH, 5);
    }
  }
}
void mouseClicked() {
  for (int i=0; i<cols; i++) {
    for (int j=0; j<rows; j++) {
      int x = i*rectW;
      int y = j*rectH;
      if(mouseX >= x && mouseX <= (x+rectW) && mouseY >= y && mouseY <= (y+rectH)) {
          p[i+j*cols] = 0; }
    }
  }
}
1 Like

Could also be a 2D array - would be easier to read

1 Like

Studio.ProcessingTogether.com/sp/pad/export/ro.9L5jAtga7SpyF
Studio.ProcessingTogether.com/sp/pad/export/ro.9ABG0RKl9D2Bx

1 Like