-2

I am making a MineSweeper game and am having trouble with the "clearing of all the blank tiles" when you click a blank tile. So far this is my method for clearing tiles.

public void clearTiles(int row, int col) {
    int newRow, newCol;       //up = 0, down = 1, right = 2, left = 3
    if (row < 0 && row > flipGrid.length && col < 0 && col > flipGrid[0].length) {
        System.out.println("stop");
    } else {
        if (finalGrid[row - 1][col] == 0 && direction != 1) {     //up
            flipGrid[row - 1][col] = true;
            newRow = row - 1;
            newCol = col;
            direction = 0;
            clearTiles(newRow, newCol);
        }
        if (finalGrid[row + 1][col] == 0 && direction != 0) {       //down
            flipGrid[row + 1][col] = true;
            newRow = row + 1;
            newCol = col;
            direction = 1;
            clearTiles(newRow, newCol);
        }
        if (finalGrid[row][col + 1] == 0 && direction != 3) {       //right
            flipGrid[row][col + 1] = true;
            newRow = row;
            newCol = col + 1;
            direction = 2;
            clearTiles(newRow, newCol);
        }
        if (finalGrid[row][col - 1] == 0 && direction != 2) {      //left
            flipGrid[row][col - 1] = true;
            newRow = row;
            newCol = col - 1;
            direction = 3;
            clearTiles(newRow, newCol - 1);
         }
    }
}

Right now I only have a function for clearing tiles above, below, right, and left of the base tile. The variable direction makes sure that the recursion doesn't go back and forth between up and down or right and left, etc. When I tried the code I got an ArrayIndexOutOfBoundsException: -1. Can anyone tell me how to fix my clear Tiles method? If you want the full code, contact me and I'll send it to you to try out. Right now, without my clearTiles method, it works but you have to click each individual tile.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

0

Your if should have OR operator, because there don't have to be fulfilled all statements when you want it to stop. You can write your recursion much easier :)

public void clearTiles(int row, int col) { 
    if (isOutsideGrid(row,col)) 
        return;

    if(isTakenTile(row, col))
        return;

    if(!isItNewTile(row, col))
        return;

    flipGrid[row][col] = true;

    clearTiles(row, col + 1);
    clearTiles(row, col - 1);
    clearTiles(row + 1, col);
    clearTiles(row - 1, col);
}


boolean isOutsideGrid(row, col){
    return (row < 0 || row >= flipGrid.length || col < 0 || col >= flipGrid[0].length) ;
}

What is more, i think now you should add these methods ;)

boolean isItTakenTile(int row, int col){
    return finalGrid[row][col] != 0;
}

boolean isItNewTile(int row, int col){
    return flipGrid[row][col] == false;
}
Hubert Bratek
  • 894
  • 10
  • 30