When your method above is called, it iterates through the surrounding cells that are around the current cell and increment the current cell's number if the neighbor is a mine. So in pseudocode:
public void addNumbers() {
loop from current row - 1 to current row + 1 taking care of *edge* cases
loop from current col - 1 to current col + 1 taking care of *edge* cases
if row and col are not both current row and current column
if cell represented by row and col has a mine
increment the current cell's number
}
Note that you must take care with edge cases -- meaning you need to know what to do when the the current cell is on the 0th row or col or on the max height row or max column col. When I've done this for my MineSweeper application, I'd declare ints as the starting and starting points of my nested for loops above the for loops and would use Math.min, Math.max to help choose my for loop limits. So the new method would be something like this:
public void addNumbers() {
declare int rowMin. Use Math.max to compare 0 and row - 1 to assign rowMin
likewise for colMin
likewise for rowMax, but use Math.min instead
likewise for colMax
loop from row = rowMin to rowMax
loop from col = colMin to colMax
if row and col are not both current row and current column
if cell represented by row and col has a mine
increment the current cell's number
}
Note that for my MineSweeper application, I did the exact opposite: I looped through all the cells, and if I found a mined cell, I added the mine count of all of its neighbors, but the end result would be the same:
public void reset() {
buttonsRemaining = (maxRows * maxCols) - mineNumber;
// randomize the mine location
Collections.shuffle(mineList);
// reset the model grid and set mines
for (int r = 0; r < cellModelGrid.length; r++) {
for (int c = 0; c < cellModelGrid[r].length; c++) {
cellModelGrid[r][c].reset();
cellModelGrid[r][c].setMined(mineList.get(r
* cellModelGrid[r].length + c));
}
}
// advance value property of all neighbors of a mined cell
for (int r = 0; r < cellModelGrid.length; r++) {
for (int c = 0; c < cellModelGrid[r].length; c++) {
if (cellModelGrid[r][c].isMined()) {
int rMin = Math.max(r - 1, 0);
int cMin = Math.max(c - 1, 0);
int rMax = Math.min(r + 1, cellModelGrid.length - 1);
int cMax = Math.min(c + 1, cellModelGrid[r].length - 1);
for (int row2 = rMin; row2 <= rMax; row2++) {
for (int col2 = cMin; col2 <= cMax; col2++) {
cellModelGrid[row2][col2].incrementValue();
}
}
}
}
}
}
The link to my code is here: Minesweeper Action Events