Search code examples
javagridprocessingcell

How to calculate which "cell" im clicking on inside of a nested for loop grid


I am currently trying to get a "cell" number returned depending on where I click inside a grid made of nesting for loops inside the mouse clicked function. I have already made an if statement to check if the mouse was clicked within the entirety of the grid but now I want to be able to return a number example 9 if I clicked on the eighth cell from the top left.

The question: Think of the cells in the grid as numbered from 0, from the top left to the bottom right. If a cell was clicked on, you need to determine which cell was clicked in and return that cell number. You will want to use integer division and modulo to calculate the cell number

I dont have any clue on how to go about this. I have included my for loop function for the grid and mouse clicked function.

final int COLUMNS = 8;
final int ROWS = 12;

int tileSize = 30;
int ellipseSize = 20;
int ellipseSpacing = 10;
int numMoves;
int selectedCell;
int targetX;
int targetY;
int randomTarget;
int gridX;
int gridY;
int score = 0;
int clickX;
int clickY;

boolean mouseoverColour = false;

void setup(){
  size (700,500);
  background(0);
  //drawTarget();
}

void draw(){
  drawColourgrid();
}

void drawColourgrid(){
   for(int i = 0; i < COLUMNS*tileSize; i+=tileSize){
     for(int j = 0; j < ROWS*tileSize; j+=tileSize){
       noFill();
       stroke(255);
       rect(i + 100,j + 60,tileSize,tileSize);
     }
   }
//fill(255);
//rect(100,60,240,360);
}

void mouseClicked(){
  if(mouseX >= 100 && mouseX <= 340 && mouseY >= 60 && mouseY <= 360){
    mouseoverColour = true;
    clickX = mouseX;
    clickY = mouseY;
    println(clickX, clickY);
  }

}

How can I calculate a whole number like 1 or 2 (for the top left)? I tried using mouseX and mouseY but it would never stay the same


Solution

  • To calculate the row and column index of a cell (starting at 0), you have to calculate the mouse position in relation to the top left origin of the grid (mouseX - 100, mouseY - 60) and to divide by the size of a cell:

    int col = (mouseX - 100) / tileSize;
    int row = (mouseY - 60) / tileSize;
    

    The number of the cell (starting at 1) can be calculated as follows:

    int n = row * COLUMNS + col + 1;
    

    The mouseClicked callback may look as follows:

    void mouseClicked(){
        if (mouseX >= 100 && mouseX <= 100+COLUMNS*tileSize && 
            mouseY >= 60 && mouseY <= 60+ROWS*tileSize){
            mouseoverColour = true;
    
            int col = (mouseX - 100) / tileSize;
            int row = (mouseY - 60) / tileSize;
            int n = row * COLUMNS + col + 1;
    
            println(n, ":", row, col);
        }
    }