上記のメソッドが呼び出されると、現在のセルの周囲にある周囲のセルを反復処理し、隣接セルが地雷の場合は現在のセルの番号を増やします。したがって、擬似コードでは:
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 番目の行または列、または最大の高さの行または最大の列の列にある場合に何をすべきかを知る必要があります。MineSweeper アプリケーションでこれを行った場合、for ループの上にネストされた for ループの開始点と開始点として int を宣言し、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