Farengar
Farengar

Reputation: 33

Discovering a region with no mines on minesweeper

I am new in this page, it hope get to some help, basically I am doing a minesweeper game on Java but it have a problem with a function: discover the region with no mines and no numbers like in the game on windows, when you click in one place and all withe cells appear. I tried make recursive but I can't, some help?

Sorry for the code, the original is in spanish but i tried make a pseudocode: Matriz = multidimensional Array (the minesweeper) min and max returns the index min and max to iterate (8 sorroud cells)

private void discoverWitheCell(int x, int y) {
    if(matriz[x][y].getdiscovered() == false){
        matriz[x][y].setDiscovered(true);
    }
    else{
        if(matriz[x][y].getNumberOfMinesArround() == 0){
            for(int i=min(x);i<max(x);i++)
                for(int j=min(y);j<max(y);j++)
                    discoverWhiteCell(i,j);
        }
    }
}

Upvotes: 1

Views: 554

Answers (1)

Loren Pechtel
Loren Pechtel

Reputation: 9083

There's not a lot of code here but I feel like you're coming at it backwards.

Sorry, I'm not a Java speaker so I'm guessing at some of the syntax. Note that this can go out of bounds--personally, I would add a layer of empty cells around my map so I never need to concern myself with bounds checking.

private void ClickSquare(int x, int y)
{
   // Did the user click an already exposed square?  If so, ignore
   if (matriz[x][y].getDiscovered()) return;
   matriz[x][y].SetDiscovered(true);
   if (matriz[x][y].getNumberOfMinesAround != 0) return;
   // If empty, click all the neighbors
   for (int xloop = x - 1; xloop <= x + 1; xloop++)
       for (int yloop = y - 1; yloop <= y + 1; yloop++)
           ClickSquare(xloop, yloop);
}

I believe you have the discovered test messed up and your version appears to be able to go into infinite (until the stack overflows) recursion as if the neighbor is also zero it will come back to the original cell. My version stops this recursion by only processing a cell if it hasn't already been processed.

Upvotes: 2

Related Questions