Search code examples
javaminesweeper

Calling a method within the same method?


I am trying to make MineSweeper for a project and I am stuck on a certain part. the explode method below works fine but It seems that I cannot call the method within the method. Without posting all the code, I wanted to see if anyone knew if this is a known illegal thing in Java and/or how to bypass it.

public void explode(int row, int col) {
    if(board[row][col].mCount==0 && !board[row][col].isMine()) {
        for (int r = row - 1; r <= row + 1; r++) {
            for (int c = col - 1; c <= col + 1; c++)                        
            if ((r >= 0 && r < user.userRow) && (c >= 0 && c < user.userCol)) {
                board[r][c].setExposed(true);
                if(board[r][c].mCount == 0) {
                    explode(r,c); // <======= PROBLEM LINE
                }
            }
        }
    }
}

It is not giving me a compilation error, but it throws an error when I run the game.


Solution

  • I think I see what's going on. You have your neighbors loops and those I think are correct except you are not excluding the "current" index. That is, in the inner loop, when r == row and c == col the method calls itself with the same indexes.

    Another thing is that subsequent calls will "loop back" and check the previous indexes. For example if you are checking row == 6, col == 7, moving on to row == 6 + 1, col == 7 + 1 will then check row == 7 - 1, col == 8 - 1. This might be solved by just checking if the grid position has been already revealed.

    public void explode(int row, int col) {
        if (board[row][col].mCount==0 && !board[row][col].isMine()) {
            for (int r = row - 1; r <= row + 1; r++) {
                for (int c = col - 1; c <= col + 1; c++) {
    
                    if (c == col && r == row) { // make sure it's
                        continue;               // not the current index
                    }
    
                    if ((r >= 0 && r < user.userRow)
                            && (c >= 0 && c < user.userCol)
                            && (!board[r][c].isExposed())) { // check if
                                                             // already shown
                        board[r][c].setExposed(true);
    
                        if(board[r][c].mCount == 0) {
                            explode(r,c);
                        }
                    }
                }
            }
        }
    }
    

    You could probably do to refactor that so the logic is more clear but anyhow I think that's the cause of the exception.

    Also just as a side note, you have this syntax here where the for loop is not a block:

    for(/* ... ... ... */)
    if(/* ... ... ... */) {
    
    }
    

    That's probably something you can do without. When you have some code that can potentially crash the program you should keep your syntax as clear and conventional as possible.