Search code examples
javaminesweeper

Blank space expansion in text-based Minesweeper clone in Java


I'm making a text-based Minesweeper clone in Java when an issue came up. I'm on the part where if you click a black space, it should reveal all of the blank spaces around that blank space and all blank spaces around that blank space, etc.

Code I have so far:

  public void exposeAround(){
    //Row = inputRow and Column = inputColumn
    for(int row = Row-1; row < Row+1; row++){
        for(int col = Column-1; col < Column+1; col++){
            if((row < 0) || (row > 8) || (col < 0) || (col < 8)){
                continue;
            } else{
                if(mines[row][col] == '.'){
                    board[row][col] = mines[row][col];
                    System.out.println("Test");
                    exposeAround();
                } else{
                    board[row][col] = mines[row][col];
                }
            }   
        }
    }
}

It doesn't throw any errors, but it doesn't do anything after this method is run, even after I run printBoard(); method

If you have any questions about other sections of my code, let me know. I have tried to find to find this answer, but the only things I can find are for a GUI-based Minesweeper

EDIT: Thanks everyone for help, I have solved my problem.


Solution

  • You can use a simple floodfill algorithm to open up the empty spaces.

    It will look something like this:

    public void exposeAround(int x1, int y1){
        //if position (x1, y1) is a bomb or number
        //    return
        //if outOfBounds(x1, y1)
        //    return
        //open up location (x1, y1)
        //exposeAround(x1-1, y1)    - flood north
        //exposeAround(x1+1, y1)    - flood south
        //exposeAround(x1-1, y1-1)  - flood west
        //exposeAround(x1-1, y1+1)  - flood east
    }
    

    So it will "flood" all 4 directions. 1 direction at a time. When it hits a boundary (bomb, number, bounds of your 2D array), it backtracks to the last good position to continue the "flooding" process.