Search code examples
javarecursionminesweeper

Can't figure out why recursion never resolves


My friend is making a minesweeper clone and he asked me to help with the part where when you click on a non-mine/non-number 'blank' square it reveals all adjacent blanks. The following is the code I wrote. I can't figure out why it never resolves.

My base case should be when the for loops completely execute and the if statement never returns true.

Is there something I'm missing?

This is in java, by the way. Also, I told him the whole slew of button state changing should be assigned to a method :p

public void revealAdjacentNulls(int r, int c)
{
    int ir, ic;

    //literal edge cases :P

    int rmax = (r == 15) ? r : r + 1;
    int cmax = (c == 15) ? c : c + 1;

    //check all spaces around button at r,c

    for(ir = (r==0) ? 0 : r-1; ir <= rmax; ir++){

        for (ic = (c==0) ? 0 : c-1; ic <= cmax; ic++){

            //if any are blank and uncovered, reveal them, then check again around the blanks

            if (buttons[ir][ic].value == 0 && buttons[ir][ic].isCovered == false)
            {
                buttons[ir][ic].setEnabled(false);  //number uncovered
                buttons[ir][ic].setBackground(Color.blue);
                buttons[ir][ic].setText(Character.toString(buttons[ir][ic].value));
                buttons[ir][ic].isCovered = false;
                revealAdjacentNulls(ir, ic);
            }
        }
    }

}

Solution

  • Well for one thing, it will always keep recursing for revealAdjacentNulls(r, c). Your condition is that isCovered must be false - but then you're setting isCovered to false as well. Did you mean to write:

    buttons[ir][ic].isCovered = true;
    

    ? Or possibly your check should be:

    if (buttons[ir][ic].value == 0 && buttons[ir][ic].isCovered)
    

    (It depends on what you mean by "is covered".)