我正在房间里用鼠标寻找奶酪的项目。 简而言之,我有一个装满0(空),1(随机奶酪)和2(随机鼠标)的棋盘。第一个控制台显示正确,但第二个控制台显示从0变为1。有什么想法吗?
Random random = new Random();
int cheese = 53 + random.nextInt(477);
int mouseX = random.nextInt(23);
int mouseY = random.nextInt(23);
int[][] room = new int[23][23];
for(int i = 0; i< room.length; i++) {
for (int j = 0; j < room.length; j++) {
room[i][j] = 0; //empty room
for (int l = 0; l <= cheese; l++) {
int m = random.nextInt(23);
int n = random.nextInt(23);
room[m][n] = 1; //cheese
}
room[mouseY][mouseX] = 2;// mouse
System.out.print(room[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("Cheese amount: " + cheese);
System.out.println("Mouse position: " + mouseY + ", " + mouseX);
for(int i = 0; i < room.length; i++){
for(int j = 0; j < room.length; j++){
System.out.print(room[i][j] + " ");
}
System.out.println();
答案 0 :(得分:1)
我将从描述开始,代码在逻辑上做了什么。我们将使用2个术语,第一个是tile
(将鼠标,奶酪或什么都不放的单点)和room
(由tiles
组成的2D数组)。
room
room
沿两个方向(X,Y)遍历tile
的完整大小:
tile
设置为0-将其清空(room[i][j] = 0;
)cheese
数):
tile
并将其设置为奶酪(room[m][n] = 1;
)tile
中的下一个room
如果从上到下,您将一次又一次地绕过第二点。这意味着:
tile
设置为0,将随机量tiles
设置为奶酪,设置随机鼠标tile
设置为0,将随机量tiles
设置为奶酪,并设置随机鼠标tile
设置为0,将随机量tiles
设置为奶酪,并设置随机鼠标tile
设置为0,将随机量tiles
设置为奶酪,并设置随机鼠标问题很简单,您应该将填充随机奶酪的代码放在清空字段的for
周期下:
for(int i = 0; i< room.length; i++) {
for (int j = 0; j < room.length; j++) {
room[i][j] = 0; //empty room
}
}
for (int l = 0; l <= cheese; l++) {
int m = random.nextInt(23);
int n = random.nextInt(23);
room[m][n] = 1; //cheese
}
room[mouseY][mouseX] = 2;// mouse
//note that the row above can overwrite already existing cheese, algorithm may need optimization because of that