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

标签 java multidimensional-array 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() 想象为更换铅笔:更换铅笔后执行的每个操作都将使用这支铅笔。

在这里,我修改了您的代码,以便您有一个数组只是为了“记住”哪种颜色在哪里。我对其进行了评论,以便您了解我修改的所有内容以及原因。

如果您有疑问,请随时提问。

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

玩得开心!

关于java - java处理中与二维数组的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59112457/

相关文章:

java - 测试 restful 时出错

java - 无法使用 Jersey 解析模板

java - 多维数组 : Java

java - 在 Swing 中将 AnimationThread 作为后台任务处理

java - 访问二维数组中的索引时返回空指针异常

java - 使用 Processing 在 Web 上显示动画 Java 程序

c# - ASP.NET 和 Java Web 应用程序的相似之处

java日期格式与xquery xs :date format,不兼容如何解决?

javascript - 从 2 个数组创建新的多维关联数组

java - 如何从 Java 中的二维数组中删除特定行和特定列?