我试图在python中编写生命的游戏程序。我不断得到错误的结构,产生后,并指出了我的错误的功能如下。
我想要程序做的事情:
它应该遍历一个数组,以确定该细胞在下一代中是活的还是死的,并将它们放入数组“cell”输入:(.-死单元x活着的单元格)。
..。
xxx
..。
输出
.x。
.x。
.x。
现在正在发生的事情:程序遍历单元格并修改它们。然后,它使用新值而不是原始值来确定下一个单元格是否还活着。
投入:
..。
xxx
..。
输出
.xx
x.x
..。
附加信息:
这两个数组的周围都有一个永久死亡的单元格框架。
def nextGen(matrice):
cells = matrice
size = np.shape(matrice)
for i in range(1,size[0]-1):
for j in range(1,size[1]-1):
if matrice[i][j] > 0:
alive = True
else:
alive = False
neighbours = 0
neighbours += matrice[i-1,j+1]
neighbours += matrice[i-1,j]
neighbours += matrice[i-1,j -1]
neighbours += matrice[i,j+1]
neighbours += matrice[i,j -1]
neighbours += matrice[i+1,j+1]
neighbours += matrice[i+1,j]
neighbours += matrice[i+1,j -1]
if alive:
if neighbours != 2 and neighbours !=3:
cells[i,j] = 0
#print("Cell has died", i, j, "Neighbours: ", neighbours)
else:
if neighbours == 3:
cells[i,j] = 1
#print("Cell was born", i, j,"Neighbours: ", neighbours)
neighbours = 0
return cells发布于 2022-10-25 12:48:33
问题在于@ copy 2357112建议cells = matrice不复制。要解决这个问题,我需要将其更改为cells = np.copy(matrice)。
https://stackoverflow.com/questions/74194250
复制相似问题