【问题标题】:Game of Life patterns carried out incorrectly生命游戏模式执行不正确
【发布时间】:2015-05-09 21:50:09
【问题描述】:

我的 Conway 在 Python 中实现的生活游戏似乎没有正确遵循规则,我无法弄清楚可能出了什么问题。当我将最终配置放入 Golly 时,它会继续我所做的。

我首先通过将我的程序停止的配置放入 Golly 来识别程序,然后注意到它可以被进一步携带。

我还将我游戏中的整个小棋盘放入 Golly,它的进展与我的配置大不相同。 Golly 是一款被广泛使用的生活模拟器游戏。

我尝试了几种不同的方法来解决我的问题:

  • 我将代码中的逻辑语句分解为不使用 and / or 语句。
  • 我测试了我的 neighbors() 函数,将其插入到自己的程序中,并设置了一些网格配置。
  • 然后我查看了打印出来的网格,我在某个位置调用了neighbors()。效果很好。

查看我的代码,我不明白为什么它不起作用。我没有收到错误,它工作,它只是工作错误。这些模式的进展与它们应该如何发展大不相同。这也是我写的第一个超过 100 行的程序,甚至没有遵循教程甚至松散,所以如果答案很明显,请原谅我。

相关代码如下:

#Function to find number of live neighbors
def neighbors(row, column):
    adjacents = 0

    #Horizontally adjacent
    if row > 0:
        if board[row-1][column]:
            adjacents += 1
    if column > 0:
        if board[row][column-1]:
            adjacents += 1
    if row < thesize-1:
        if board[row+1][column]:
            adjacents += 1
    if column < thesize-1:
        if board[row][column+1]:
            adjacents += 1

    #Diagonally adjacent
    if row > 0 and column > 0:
        if board[row-1][column-1]:
            adjacents += 1
    if row < thesize-1 and column < thesize-1:
        if board[row+1][column+1]:
            adjacents += 1
    if row > 0 and column < thesize-1:
        if board[row-1][column+1]:
            adjacents += 1
    if row < thesize-1 and column > 0:
        if board[row+1][column-1]:
            adjacents += 1

    #Return the final count (0-8)
    return adjacents

这似乎可以完美地返回任何给定单元格的 8 个邻居中有多少是活着的。接下来是逻辑部分,我认为问题出在哪里。它根据游戏规则改变数组。

#Main loop
while 1:

    #Manage the rules of the game
    for r in range(len(board)):
        for c in range(len(board)):
            neighborcount = neighbors(r, c)
            if board[r][c]:
                giveLife(r, c)
                if neighborcount < 2 or neighborcount > 3:
                    board[r][c] = False
            elif not board[r][c]:
                killRuthlessly(r, c)
                if neighborcount == 3:
                    board[r][c] = True

最后,在 pygame 屏幕上,在视觉上打开和关闭方块的部分。这是经过测试的,似乎运行良好,我只是想我会包括它以防万一出现问题。

    for r in range(len(board)):
        for c in range(len(board)):
            if board[r][c]:
                giveLife(r, c)
            if not board[r][c]:
                killRuthlessly(r, c)

giveLife 是一个在给定位置绘制黑色矩形的函数,killRuthlessly 绘制一个白色矩形。这些似乎都可以正常工作。

【问题讨论】:

  • 不是。他们已经解决了我的问题。,
  • 为什么这被否决了??
  • 更好?还是还是代码转储?
  • 小伙子,你才 13 岁,你正在写一个 FSM,你太棒了!你让我想起了我。继续加油!

标签: python conways-game-of-life


【解决方案1】:

对于循环通过电路板并检查相邻单元格的逻辑,它正在打开/关闭单元格,同时继续检查其他单元格。很可能您正在读取相邻的单元格是活的还是死的,不是因为它们在上一个时间步(这很重要),而是因为您已经改变了它们的状态,因为它们已经被循环了。尝试创建一个tmp_board,它会复制当前板并对其进行编辑。循环完所有内容后,将其复制回board

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2016-03-31
    • 2013-11-30
    相关资源
    最近更新 更多