我正在致力于在一个名为“处理”的程序中创建一款战舰风格的游戏,现在我正在努力与棋盘进行简单的交互。我希望网格单元在单击时改变颜色,并将其坐标打印到控制台中。我不确定我在这里做错了什么,它不是改变颜色,而是将整个事物改变为那种颜色。
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/