我尝试使用以下代码在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并且不会消失。
有人可以告诉我,我的代码中的问题是什么以及如何解决它?
答案 0 :(得分: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了解详情。