二维阵列可在所有方向上扩展

时间:2013-04-14 09:22:23

标签: java arrays multidimensional-array game-physics

Gday所有人,

我只是想编写所谓的“生活游戏”。忘了谁发明了它,但我发现它非常有趣。请不要发布与游戏编程相关的任何链接,因为这会破坏我的动机;)

它的基本部分是操场。我需要一个二维数组,它可以在所有方向上扩展。

E.g。我在开始时有一个包含10 * 10个字段的数组。我需要能够在数组[-1] [ - 1]的方向以及数组[11] [11]的方向同时添加新字段。我甚至需要能够将新项添加到字段数组[-1] [10]或数组[10] [ - 10]。我需要能够将数组访问到所有可能的2D方向。

在写这篇文章的同时,我刚才有了一个想法:四个阵列指向北方,东方,南方和西方的所有方向怎么样?只需将所有阵列放在一起,实际上指向指定的方向。就像下面的例子一样。所有阵列组合在一起形成我的游乐场。它会有效率,还是有更简单的方法?

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

感谢。

1 个答案:

答案 0 :(得分: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);

John Conway的生命游戏: - )

方法 可以自定义此解决方案,以便在选定方面进行扩展,具体如下:

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);
祝你好运。