调用上述方法时,它会遍历当前单元格周围的周围单元格,如果邻居是地雷,则增加当前单元格的编号。所以在伪代码中:
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
}
请注意,您必须注意边缘情况——这意味着您需要知道当当前单元格位于第 0 行或 col 或最大高度行或最大列 col 时该怎么做。当我为我的 MineSweeper 应用程序完成此操作时,我会将 int 声明为 for 循环上方嵌套 for 循环的起点和起点,并使用 Math.min、Math.max 来帮助选择我的 for 循环限制。所以新方法是这样的:
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
}
请注意,对于我的 MineSweeper 应用程序,我做了完全相反的事情:我遍历了所有单元格,如果我找到了一个已挖掘的单元格,我将添加其所有邻居的地雷计数,但最终结果将是相同的:
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();
}
}
}
}
}
}
我的代码的链接在这里:Minesweeper Action Events