我正在尝试制作MineSweeper的控制台版本。
尽管我目前做出了努力,但我无法弄清楚MineSweeper的“泛滥”部分,如果所选择的广场附近不包含炸弹,我们现在必须检查那些相邻的方块以找到相邻的炸弹。
下面的代码适用于所选方块与炸弹相邻的情况:
// checking the adjacent cells, I made -1 = to the bomb value, rest of the cells
// are default(0)
public void sweep(int r, int c) {
if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)
return;
int minRow = 0, minCol = 0, maxRow = 0, maxCol = 0, neighborBomb = 0;
// means if I clicked a bomb, end the program
if (grid[r][c] == -1) {
System.out.println("Your selection [" + r + ", " + c + "] contained a bomb. .\nGAME OVER");
System.exit(0);
}
// Series of if/else to find the min & max row col size to avoid going out of
// bounds
if (r == 0)
minRow = 0;
else
minRow = r - 1;
if (r == grid.length - 1)
maxRow = r;
else
maxRow = r + 1;
if (c == 0)
minCol = 0;
else
minCol = c - 1;
if (c == grid[0].length - 1)
maxCol = c;
else
maxCol = c + 1;
//if the selected cell is 0 & has not been searched yet.
if (grid[r][c] == 0 && recurseSearch[r][c] == false) {
recurseSearch[r][c] = true;
// search adjacent cells to see how many bombs surround the cell in question
neighborBomb = 0;
for (int row = minRow; row <= maxRow; row++) {
for (int col = minCol; col <= maxCol; col++) {
if (grid[row][col] == -1) {
neighborBomb++;
}
}
}
}
// cell will now display how many bombs are adjacent
if (neighborBomb > 0) {
grid[r][c] = neighborBomb;
return;
}
//HERE I WANT TO CHECK ALL ADJACENT SQUARES BUT IT WILL ONLY RUN
//sweep(r+1, c) rather than all the surrounding squares
else {
sweep(r + 1, c);
sweep(r - 1, c);
sweep(r + 1, c + 1);
sweep(r + 1, c - 1);
sweep(r - 1, c + 1);
sweep(r - 1, c - 1);
sweep(r, c + 1);
sweep(r, c - 1);
}
}
grid [] []本质上是我的游戏板,recurseSearch [] []是一个布尔值,可以跟踪是否已经搜索过一个单元格。 if / else语句的混乱是我试图得不到任何IndexOutOfBoundErrors。当我试图奔跑并挑选一个没有被炸弹包围的牢房时,我得到了
Exception in thread "main" java.lang.StackOverflowError
它重复了那些线条
sweep(r + 1, c);
sweep(r - 1, c);
任何想法/建议将有助于如何使我的递归实际检查原始r,c选择的每个相邻单元格!