Python 康威生命游戏中的所有细胞都是活的
我试图用以下代码在Python-3.6中实现Conway的生活游戏:Python 康威生命游戏中的所有细胞都是活的,python,conways-game-of-life,cellular-automata,Python,Conways Game Of Life,Cellular Automata,我试图用以下代码在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(co
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,并且不会消失
有人能告诉我代码中的问题是什么以及如何解决吗?您的问题似乎在这里:
elif screen[x][y] == 1 and neighbors == 2 or 3:
你不能做得很好,你可以,但它没有达到你的期望。相反,请尝试:
elif screen[x][y] == 1 and neighbors in (2 , 3):
或者在{2,3}中
查看更多信息。当我尝试此数字时,可能与现在重复:[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 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 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 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 0 1 0 0 0 0 0 0 0 1 1 1 1 0][0 0 0 0 0 0 0 0 0 0 1 1 1 0 0][0 0 0 0 0 0 0 0 0 0 1 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 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 0 0 0 0 0 0 0 0 0 0 0 0 0