与数组中的特定元素交互;处理3



我正试图创建一个正方形网格,当键入正确的键时"打开",然后当用鼠标单击时"关闭"。在我的程序中,会生成一个随机索引号,该索引号对应于特定键的Unicode值,当您按下该键时,网格上的一个随机正方形将显示为绿色。重新着色后,会为不同的键生成一个新的索引号,依此类推。鼠标单击最后一个着色的正方形可以"取消着色"(变为黑色(,但不能取消任何其他先前着色的正方形。

问题似乎是mousePressed代码与数组中最后一个着色的元素绑定在一起,但我不知道如何使它与数组中任何一个着色过的元素进行交互。这可能吗?我考虑过更改数组,使数组中每个元素的位置都被打乱,但它创建的形状仍然排列在网格中,然后每次鼠标单击都向后迭代。但我似乎不知道如何在不进入java的情况下打乱数组,这是我不熟悉的。这是一个可以解决的问题,还是我应该以某种方式调整我的代码?到目前为止,我拥有的是:

主要脚本:

int cols = 16;
int rows = 10;
boolean light = false;
Box[][] boxes = new Box[cols][rows];
int keyIndex = int(random(97, 122));
int randI = (int)random(0, cols);
int randJ = (int)random(0, rows);
void setup() {
size (800, 600);
background (0);
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
boxes[i][j] = new Box(i, j);
}
}
println(keyIndex);
}

void draw() { 
if (light == true) {
boxes[randI][randJ].rollover(mouseX, mouseY);
boxes[randI][randJ].displayOn();
} else {
boxes[randI][randJ].displayOff();
}
}
void mousePressed() {
if (boxes[randI][randJ].onPress(mouseX, mouseY)) {
println("yes");
light = false;
} else {
println("no");
}
}
void keyPressed() {
if (boxes[randI][randJ].keyRight()) {
light = true;
randI = (int)random(0, cols);
randJ = (int)random(0, rows);
keyIndex = int(random(97, 120));
println(keyIndex);
}
}

"盒子"类:

class Box {
float x, y;
color c;
int size = 50;
Box (int valX, int valY) {
x = valX * size;
y = (int) random(0, valY) * size;
}
void displayOn() {
fill(c);
rect(x, y, size, size);
c = #b1f64d;
}
void displayOff() {
fill(c);
rect(x, y, size, size);
c = #000000;
}
void rollover(float mx, float my) {
if (mx > x && mx < x + size && my > y && my < y + size) {
c = 126;
}
}
boolean onPress(float mx, float my) {
if (mx > x && mx < x + size && my > y && my < y + size) {
return true;
} else {
return false;
}
}
boolean keyRight() {
if (key == keyIndex) {
return true;
} else {
return false;
}
}
}

您需要Box:类的成员变量,而不是单个变量boolean light = false;

boolean light = false;

class Box {
boolean light = false;
float x, y;
color c;
int size = 50;
Box (int valX, int valY) {
x = valX * size;
y = valY * size;
}
.....
}

现在,无论是否"点亮",每个长方体对象都可以保存信息。

draw函数中,您必须绘制所有框,每个框都取决于其状态
boxes[i][j].light为此使用2个嵌套的for循环:

void draw() { 
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if (boxes[i][j].light == true) {
boxes[i][j].rollover(mouseX, mouseY);
boxes[i][j].displayOn();
} else {
boxes[i][j].displayOff();
}
}
}
}

mousePressed中,您必须检查状态为boxes[i][j].light的所有Box对象,mouseXmouseY是否打开:

void mousePressed() {
boolean hit = false;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if (boxes[i][j].light == true && boxes[i][j].onPress(mouseX, mouseY)) {
boxes[i][j].light = false;
hit = true;
}
}
}
println(hit ? "yes" : "no");
} 

最后,您必须在函数keyPressed中设置成员boxes[randI][randJ].light,而不是不再存在的变量light

void keyPressed() {
if (boxes[randI][randJ].keyRight()) {
boxes[randI][randJ].light = true;
randI = (int)random(0, cols);
randJ = (int)random(0, rows);
keyIndex = int(random(97, 120));
println(keyIndex, char(keyIndex));
}
}