我可以帮助我的Java程序,我已经创建了下面的方法,我只是想知道如何在下面将这个应用到我的程序中。
在模型类中要做的最后一件事是向雷区添加更多值,以确定与任何给定方格相邻的多少个地雷。创建了一个名为addNumbers的公共方法,该方法具有void返回并且不带参数。之前,the_minefield中的值只有两个值,0(EMPTY_SQUARE)和10(MINE_SQUARE)。现在,与矿井广场相邻的任何空方块将不再具有零值 - 它现在存储其旁边的地雷数量。这可以是1(仅一个矿)和8(完全包围)之间的任何值。包含矿的方块仍然具有值10(MINE_SQUARE),无论它们旁边是什么。
//程序中较早的方块声明:
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;
//需要调整的方法。
public void addNumbers() {
}
答案 0 :(得分:0)
当调用上面的方法时,它会遍历当前单元格周围的周围单元格,如果邻居是我的,则递增当前单元格的编号。所以在伪代码中:
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或最大高度行或最大列时,您需要知道该怎么做山坳。当我为MineSweeper应用程序完成此操作时,我会将forts声明为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