-1

请我对我的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() {


 }
4

1 回答 1

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 或最大高度行或最大列 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

于 2013-03-16T11:33:44.390 回答