Python康威的生活游戏在滑翔枪设计中表现不佳

2024-10-01 17:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python复制康威的生活游戏。 这个模拟的规则和它正常工作的版本可以在这里找到:https://bitstorm.org/gameoflife/

在我的版本中,当我在一开始就随机地将细胞指定为“活着”时,它的行为似乎很正常,典型的不规则的细胞团会在屏幕上展开。在

然而,当我复制“滑翔枪”的布局(也可以在链接的网站上看到)时,这些细胞并没有得到适当的更新:结构轻微衰退,然后细胞的运动仍然停滞。在

如果我的代码有任何逻辑错误,我会很感激的!在

这是我的Cell类中更新的代码部分 它的存活取决于它的neighbors(它周围的八个细胞):

def update(self, neighbors):
    numAliveNeighbors = 0
    for neighbor in neighbors:
        if neighbor.isAlive:
            numAliveNeighbors+=1

    if numAliveNeighbors <= 1 or numAliveNeighbors >=4:
        self.isAlive = False
    elif not self.isAlive and numAliveNeighbors is 3:
        self.isAlive = True

这是我的代码部分,它查找每个cell的所有neighbors,并对它们调用update方法:

^{pr2}$

Tags: 代码httpsself版本游戏if规则neighbors
1条回答
网友
1楼 · 发布于 2024-10-01 17:32:25

就地更新

您正在进行就地更新;也就是说,您单独更新每个单元。您需要做的是创建一个克隆网格,每次更新迭代中的单元时,更新克隆的网格,然后将游戏板设置为克隆的网格。否则,单元格将根据当前迭代进行更新,这是没有意义的。在

你可以这样做:

def isAlive(alive, neighbours):
    return (alive and 2 <= neighbours <= 3) or (not alive and neighbours == 3)

def update(cells):
    grid = [[0] * len(row) for row in cells]
    for row in range(len(cells)):
        for col in range(len(cells[row])):
            neighbours = 0
            for tr in range(row - 1, row + 2):
                for tc in range(col - 1, col + 2):
                    if (tr != row or tr != col) and cells[tr][tc]:
                        neighbours += 1
            grid[row][col] = isAlive(cells[row][col], neighbours)
return grid

然后可以在循环中调用cells = update(cells)。在

相关问题 更多 >

    热门问题