Flood-clearing routine for a JavaFx Minesweeper
Iterating through adjacents

There are two main approaches to take while iterating through the neighbors in Minesweeper.

The first and most common option is to use a nested for loop:

for (int y = -1; y &lt;= 1; y++) {
    for (int x = -1; x &lt;= 1; x++) {
        if (x == 0 &amp;&amp; y == 0) {
            continue; // We don't want to consider the field itself as a neighbor
        }
        increaseAdjacentMineCounter(mineX + x, mineY + y);
    }
}


The second approach, and the one that I normally use and like better, is to use an array to define which fields should be used as your neighbors.

int[][] neighbors = {{ -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, -1 },
    { 0, 1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }};
for (int[] neighbor : neighbors) {
    int x = neighbor[0];
    int y = neighbor[1];
    increaseAdjacentMineCounter(mineX + x, mineY + y);
}


The reason for why I like the second approach better is because it becomes more data-oriented. You can change the way you consider neighbors without changing your code. Changing the way your neighbors are considered can be a bit entertaining but very confusing :)