Creating a clickable dynamic grid

Hi @Reynaert98,

This is a simple example that I made for better understanding.
The main idea is the following:

    • A card class represents a card, which has determined position and dimensions.
    • To draw a card, I used a rectangle centered in x and y using the dimensions below. So I draw the rectangle and consider the spacing for the margin

image
3) - By knowing the dimensions of each card I can know if the mouse is on top of the card (hover() method).
4) - An ArrayList of cards has as many cards as you want. So setting n, in the beginning, allows choosing the number of cards to make a grid

Thus, when the mouse is pressed I check which card had the mouse on top of it and so I set a new Color for the card

int n = 3;
ArrayList<Card> cards;
void setup() {
  size(600, 600);
  cards = new ArrayList();
  for (int i = 1; i <= 2*n; i++) {
    for (int j = 1; j <= 2*n; j++) {
      if (i % 2 == 1 && j%2 ==1) cards.add(new Card(i*width/(2*n), j*height/(2*n), width/n, height/n));
    }
  }
}

void draw() {
  for (int i = 0; i < cards.size(); i++) {
    cards.get(i).display();
  }
}

void mousePressed() {
  for (int i = 0; i < cards.size(); i++) {
    if (cards.get(i).hover()) {
      cards.get(i).setColor(color(0, 255, 0));
    }
  }
}

class Card {
  int xpos, ypos, cardWidth, cardHeight;
  color c1;
  int spacing;
  Card(int _x, int _y, int _w, int _h) {
    xpos = _x;
    ypos = _y;
    cardWidth = _w;
    cardHeight = _h;
    c1 = color(255, 0, 0);
    spacing = 30;
  }

  void display() {
    stroke(255);
    fill(c1);
    rectMode(CENTER);
    rect(xpos, ypos, cardWidth - spacing, cardHeight - spacing);
    noFill();
    noStroke();
  }

  boolean hover() {
    return (mouseX > xpos - cardWidth/2 && mouseX < xpos + cardWidth/2 
      && mouseY > ypos - cardHeight/2 && mouseY < ypos + cardHeight/2);
  }

  void setColor(color newColor) {
    c1 = newColor;
  }
}

Hope this helps or at list gives you a hint to solve your problem :slight_smile:

Best regards