I just picked up Java a few days ago, and started coding a Minesweeper game. The problem is, when I try to cascade the surrounding blocks and reveal blocks, either blank or with numbers depending on the amount of adjacent bombs, my recursion fails and gives me a stack over flow error. My code is as follows:
public void revealCell(int row, int col)
{
if(mAnswerBoard.get (row, col).equals ("1")||mAnswerBoard.get (row, col).equals("2")||
mAnswerBoard.get (row, col).equals("3")||mAnswerBoard.get (row, col).equals("4")||
mAnswerBoard.get (row, col).equals("5"))
{
mMinesweeperBoard.set (row, col, mAnswerBoard.get (row, col));
return;
}
else if(mAnswerBoard.get (row, col).equals("0"))
{
mMinesweeperBoard.set (row, col, " ");
for(int i = row - 1; i <= row + 1; i++)
{
if (i == -1)
{
i = 0;
}
for(int j = col - 1; j <= col + 1; j++)
{
if (j == -1)
{
j = 0;
}
if (mAnswerBoard.get (i, j).equals ("0") == false)
{
mMinesweeperBoard.set (i, j, mAnswerBoard.get (i, j));
}
else if (mAnswerBoard.get (i, j).equals (("0")))
{
if (mMinesweeperBoard.get (j, i).equals ("."))
{
mMinesweeperBoard.set(i, j, " ");
revealCell(i, j);
}
}
}
}
}
}
I have been staring at this for hours, and I really can't grasp my head around why it doesn't stop looping. My initial gameboard holds "." in not revealed spots, and if 0, the board will hold a whitespace. I try to check if the answer key holds a 0 in the spot, and if it does and if the actual board still holds a"." in the spot, I can set a whitespace. For some reason, revealCell gets called over and over again, and I really can't figure it out. Am I doing something completely wrong?
Side note: I have to set i and j to 0 if they are -1 because my code allows the user to enter in 0,0 as a valid coordinate.
Thank you for the help, and I am sorry if the answer is right in front of my face...
if (mMinesweeperBoard.get (j, i).equals ("."))
You switched i
and j
here, so you're testing the wrong cell. Switch them back and see if that fixes it.