3

皆様、

いわゆる「人生ゲーム」をプログラムしようとしています。誰が発明したかは忘れましたが、とても興味深いと思います。ゲームのプログラミングに関連するリンクを投稿しないでください。私のモチベーションが損なわれます ;)

その重要な部分は遊び場です。全方向に拡張可能な 2 次元配列が必要です。

たとえば、最初に 10*10 フィールドの配列があります。array[-1][-1] の方向と array[11][11] の方向に同時に新しいフィールドを追加できるようにする必要があります。フィールド array[-1][10] または array[10][-10] に新しいアイテムを追加できる必要さえあります。可能なすべての 2D 方向に配列にアクセスできる必要があります。

この投稿を書いているのと同時に、私はちょうどアイデアを思いつきました:北、東、南、西のすべての方向を指す4つの配列を持つことはどうですか? すべての配列を隣り合わせに配置するだけで、指定された方向を仮想的に指します。以下の例のように。すべての配列は、私の遊び場を形成します。それは効率的でしょうか、それとももっと簡単な方法がありますか?

[][][] | [][][]
[][][] | [][][]
[][][] | [][][]
_______|_______
[][][] | [][][]
[][][] | [][][]
[][][] | [][][]

ありがとう。

4

1 に答える 1

2

プリミティブ配列を使用していると仮定すると、固定数のセルで行列を拡張すると、次のようになります。

boolean[][] gameBoard = new boolean[3][3];

public boolean[][] expandMatrixBy(boolean[][] matrix, int number) {
  int oldSize = matrix.length;
  int newSize = oldSize + 2 * number;
  boolean[][] result = new boolean[newSize][newSize];

  // Assume new cells should be dead, i.e. false..
  for (int row = number; row < oldSize + number; row++) {
    for (int col = number; col < oldSize + number; col++) {
      // ..copy only the existing cells into new locations.
      result[row][col] = matrix[row - number][col - number];
    }
  }
  return result;
}

// Calling this on a 3x3 matrix will produce 5x5 matrix, expanded by 1 on each side.
gameBoard = expandMatrixBy(gameBoard, 1);

そしてジョン・コンウェイのライフゲームです:-)

オプション: このソリューションは、次のようにカスタマイズして、選択した側で拡張を有効にすることができます。

enum Side { Left, Right, Top, Bottom };

public boolean[][] expandMatrixBy(boolean[][] matrix, int number, Set<Side> sides) {
  int oldSize = matrix.length;
  int newSize = oldSize + number * sides.size();
  boolean[][] result = new boolean[newSize][newSize];

  for (Side side : sides) {
    switch(side) {
      case Left:
        // Add number of columns on the left.

      case Right:
        // Add "number" of columns on the right.
    }
  }
  return result;
}

Set<Side> expandOnTheseSides = EnumSet.of(Side.Left, Side.Top);
gameBoard = expandMatrixBy(gameBoard, 1, expandOnTheseSides);

幸運を。

于 2013-04-14T09:41:27.150 に答える