java 处理中与二维数组的交互

Interaction with a 2D array in java processing

我现在正致力于在一个名为 Processing 的程序中创建一款战舰风格的游戏,目前我正致力于与棋盘进行简单的交互。我希望网格单元格在单击时改变颜色,并将其坐标打印到控制台中。我不确定我在这里做错了什么,它没有改变颜色,而是将整个事物改变为那种颜色。

int col = 10;
int row = 10;

int colors = 50;

//rectangle variables
int x;
int y;

int [][] boxes = new int [9][9];

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

  for(int i = 0; i< boxes.length; i++){
    for(int j = 0; j < boxes[i].length; j++){
        boxes[i][j] = j;
    }
  }
}
void draw(){
 for(int i = 0; i< boxes.length; i++){
    for(int j = 0; j < boxes[i].length; j++){
      x = i * 30;
      y = j * 30;

      fill(colors);
      stroke(0);
      rect (x, y, 30, 30);


    }
  }

}
void mousePressed(){
   for(int i = 0; i< boxes.length; i++){
    for(int j = 0; j < boxes[i].length; j++){
      colors = 90;
      fill(colors);
    }
   }
}

考虑使用fill()作为换铅笔:换铅笔后的每一个动作都将使用这支铅笔。

在这里,我修改了你的代码,所以你有一个数组 "remember" 哪个颜色在哪里。我对其进行了评论,以便您了解我修改的所有内容以及原因。

如果您有任何问题,请随时提出。

final int col = 10;
final int row = 10;
final int boxSize = 30;

final color selectedBoxColor = color(90);
final color boxColor = color(50);

//int colors = 50; //use the array instead

//rectangle variables
int x;
int y;

//arrays starts at zero, but are initialized at their "normal" number
int [][] boxes = new int [col][row];
color [][] boxesColor = new color [col][row];

void settings() {
  //this should be here
  size(col * boxSize, row * boxSize);
}

void setup(){
  for(int i = 0; i< boxes.length; i++){
    for(int j = 0; j < boxes[i].length; j++){
        boxes[i][j] = j;
        boxesColor[i][j] = boxColor;
    }
  }
}
void draw(){
 for(int i = 0; i< boxes.length; i++){
    for(int j = 0; j < boxes[i].length; j++){
      x = i * 30;
      y = j * 30;

      fill(boxesColor[i][j]);
      stroke(0);
      rect (x, y, boxSize, boxSize);
    }
  }

}
void mousePressed(){
  //using basic math to know which box was clicked on and changing only this box's color
  boxesColor[mouseX / boxSize][mouseY / boxSize] = selectedBoxColor;

  //no need for these lines
   //for(int i = 0; i< boxes.length; i++){
   // for(int j = 0; j < boxes[i].length; j++){      
   //   colors = 90; 
   //   fill(colors); 
   // }
   //}
}

玩得开心!