-1

私のJavaプログラムについて助けてもらえますか?私は以下のメソッドを作成しました。これを私のプログラムにどのように適用できるのか疑問に思っていました。

モデルクラス内で最後に行うことは、特定の正方形に隣接する地雷の数を決定するために、地雷原に値を追加することです。addNumbersというパブリックメソッドを作成しました。これはvoidリターンを持ち、パラメーターを取りません。以前は、_minefieldの値は、0(EMPTY_SQUARE)と10(MINE_SQUARE)の2つの値のみを取ります。これで、地雷で埋められた正方形に隣接する空の正方形の値はゼロではなくなり、隣に地雷の数が格納されるようになります。これは、1(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 番目の行または列、または最大の高さの行または最大の列の列にある場合に何をすべきかを知る必要があります。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

于 2013-03-16T11:33:44.390 に答える