如何计算我在嵌套的循环网格内单击哪个"cell"



>我目前正在尝试返回一个"单元格"编号,具体取决于我在由鼠标单击函数内的嵌套循环组成的网格中单击的位置。我已经做了一个 if 语句来检查鼠标是否在整个网格内被单击,但现在我希望如果我单击左上角的第八个单元格,我希望能够返回一个数字示例 9。

问题: 将网格中的单元格视为从 0 开始从顶部编号 左到 右下角。 如果单击了某个单元格,则需要确定单击了哪个单元格并返回该单元格编号。您将需要使用整数除法和模来计算单元格数

我不知道该怎么做。我已经为网格和鼠标单击功能包含了我的 for 循环函数。

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);
  }
}

如何计算像 1 或 2(左上角(这样的整数? 我尝试使用mouseX和mouseY,但它永远不会保持不变

要计算单元格的行和列索引(从 0 开始(,您必须计算鼠标相对于网格左上角原点的位置(mouseX - 100mouseY - 60 (并除以单元格的大小:

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

单元格的数量(从 1 开始(可以按如下方式计算:

int n = row * COLUMNS + col + 1;

mouseClicked回调可能如下所示:

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);
    }
}

试试这个:

int cellNumber = (((mouseX - 100)/tileSize) + 1)
        + (((mouseY - 60)/tileSize) * COLUMNS);

最新更新