【问题标题】:All cells in Conway's game of life are alive康威生命游戏中的所有细胞都是活的
【发布时间】:2018-01-24 15:32:21
【问题描述】:

我尝试使用以下代码在 Python-3.6 中实现 Conway 的生活游戏:

import numpy as np
import time

screen = np.zeros((25,25),dtype=np.int)
while True:
    print(screen)
    command = input('command?')
    if command[0] == 'x':
        command = command.split(' ')
        x = int(command[0][1:])
        y = int(command[1][1:])
        if screen[x][y] == 0:
            screen[x][y] = 1
        else:
            screen[x][y] = 0
    elif command == 'start':
        break

while True:
    for x in range(len(screen)):
        for y in range(len(screen[x])):
            neighbors = 0
            if x != len(screen)-1:
                neighbors += screen[x+1][y]
            if x != 0:
                neighbors += screen[x-1][y]
            if y != len(screen[x])-1:
                neighbors += screen[x][y+1]
            if y != 0:
                neighbors += screen[x][y-1]
            if x != len(screen)-1 and y != len(screen[x])-1:
                neighbors += screen[x+1][y+1]
            if x != 0 and y != 0:
                neighbors += screen[x-1][y-1]
            if 0 and y != len(screen[x])-1:
                neighbors += screen[x-1][y+1]
            if x != len(screen)-1 and y != 0:
                neighbors += screen[x+1][y-1]

            if screen[x][y] == 0 and neighbors == 3:
                screen[x][y] = 1
            elif screen[x][y] == 1 and neighbors < 2:
                screen[x][y] == 0
            elif screen[x][y] == 1 and neighbors > 3:
                screen[x][y] == 0
            elif screen[x][y] == 1 and neighbors == 2 or 3:
                screen[x][y] = 1
    print(screen)
    time.sleep(0.1)

问题是,当我尝试使用任何图形运行此代码时,所有单元格在第一代立即设置为 1,并且不会消亡。

谁能告诉我代码中的问题是什么以及如何解决?

【问题讨论】:

标签: python conways-game-of-life cellular-automata


【解决方案1】:

您的问题似乎在这里:

        elif screen[x][y] == 1 and neighbors == 2 or 3:

你不能这样做(好吧,你可以,但它并没有达到你的预期)。而是尝试:

        elif screen[x][y] == 1 and neighbors in (2 , 3):

(或in {2, 3})。

查看this question了解更多信息。

【讨论】:

  • 现在当我尝试这个数字时:[0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 1 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] 10 代后变成这个:[0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 1 1 0 0 0] [0 0 0 0 0 1 1 1 1 0] [0 0 0 0 0 1 1 1 1 0] [0 0 0 0 0 1 1 1 0 0] [0 0 0 0 0 1 1 1 1 0] [0 0 0 0 0 1 1 1 1 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多