So, I've been working on some code for java for minesweeper. I'm working on trying to get the cells that are empty to reveal the coinciding cells next to them recursively. Here is the function that does this.
The "cell" is a button that I'm using for the cells in the game.
private void showCells(int x, int y) {
//checks out of bounds
if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0) {
return;
}
//function to look at each surrounding cell and see if it is a mine,
//has nMines as a global variable to keep track of the number of mines
findMines(x, y);
//if there are mines around the cell that was selected
if (nMines > 0) {
//set the text of that cell to the number of mines around it
cell[x][y].setText(String.valueOf(nMines));
//if cell is not already disabled, disable it
if (!cell[x][y].isDisabled()) {
cell[x][y].setDisable(true);
}
} else {
//if there are no mines, recursively show the surrounding mines
showCells(x + 1, y);
showCells(x - 1, y);
showCells(x, y + 1);
showCells(x, y - 1);
}
//resets the mine count for the next search
nMines = 0;
}
I know I have some other issues with the code as far as functionality goes, but I'm trying to figure out this recursive thing. What is happening as I debug, is that when I get to the end of the 'x' bound, it returns, but then immediately jumps into the next recursive call, which takes it to the same 'x' location.
showCells(x + 1, y);
showCells(x - 1, y);
I'm wondering what kind of qualifier I need and where I need to place it to make sure that it doesn't search in the same spot twice. Thanks in advance!
You're creating an infinite loop, since each cell will recur to every neighboring cell, and then each of those that is empty will recur back to the original cell, etc.
You can fix this by adding a condition to your first if statement:
if (x >= SIZE || y >= SIZE || x <= 0 || y <= 0 || cell[x][y].isDisabled()) {
return;
}
Because of a handy feature called short-circuiting, the check of isDisabled()
won't even throw an error if x
or y
is out of bounds, because it will never be evaluated.
EDIT: to answer your follow-up about where to put the setDisabled(true)
- you always want to disable a cell after it's been clicked on, right? So put it right under findMines()
, before the if
statement.