如何计算康威生命游戏中一个细胞的活邻居?

时间:2012-09-19 09:42:38

标签: java conways-game-of-life

我正在实施康威的生活游戏。我已经阅读了inittal板,现在我需要对它进行编程以计算一个单元的实时邻居。

一些基本规则

  

任何活着的邻居少于两个的活细胞都会死亡,就像人口不足一样。   任何有两三个活邻居的活细胞都会留在下一代。   任何有三个以上活着的邻居的活细胞都会死亡,就像过度拥挤一样。   具有正好三个活邻居的任何死细胞变成活细胞,就好像通过繁殖一样。

这是我已经拥有的代码。

更新:这是在一些初步建议后改变的代码。

/**
 * Write your comments here following the javadoc conventions
 */
public static int countNeighbours(boolean[][] board, int row, int col)
{
    int neighbours = 0; 
    int x = -1;
    while (x <= 1) {
        int y = -1;
        while (y <= 1) {
            if (board[row][col] == true) {

                neighbours++; 
            }
            // Given a 2D boolan array and a cell location given by its
            // row and column indecies, count the number of live cells
            // immediately surrounding the given cell. Remember that you
            // mustn't count the cell itself.

        }


    }
    return neighbours;
}

这是在正确的轨道上吗?

3 个答案:

答案 0 :(得分:2)

我想你想做

if (board[row][col] == true) {

相同
if (board[row][col]) {

答案 1 :(得分:2)

因为我知道这是一个典型的学校作业,我想给你完整的答案,但是你不应该在方法的开头重新划分行,把它称为别的,并且循环应该从row-1row+1col-1col+1

答案 2 :(得分:0)

如果你可以让你的电路板全局化,这可能适用于带有环绕的单个电池:

public Cell[] getNeighbours(int i, int j) {
int i2 = i - 1, i3 = i + 1, j2 = j - 1, j3 = j + 1;
if (i2 == -1) i2 = board.length - 1;
if (i3 == (board.length)) i3 = 0;
if (j2 == -1) j2 = board[i].length - 1;
if (j3 == (board[i].length)) j3 = 0;
return new Cell[]{board[i2][j2], board[i2][j], board[i2][j3], board[i][j2], board[i][j3], board[i3][j2], board[i3][j], board[i3][j3]};

}

然后只计算这些细胞中有多少活着并返回。

相关问题