我目前正在研究康威的生命游戏,并且已经陷入困境.我的代码不起作用.
当我在GUI中运行我的代码时,它说:
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 53, in
b= apply_rules(a)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 14, in apply_rules
neighbours=number_neighbours(universe_array,iy,ix)
File "C:\Users\Documents\Physics\Python\MainProject\conway.py", line 36, in number_neighbours
neighbours+=1
UnboundLocalError: local variable 'neighbours' referenced before assignment
这是我的代码:
'''If a cell is dead at time T with exactly three live neighbours, the cell will be alive at T+1
If a cell is alive at time T with less than two living neighbours it dies at T+1
If a cell is alive at time T with more than three live neighbours it dies at T+1
If a cell is alive at time T with exactly two or three live neighbours it remains alive at T+1'''
import numpy
def apply_rules (universe_array):
height, width = universe_array.shape
# create a new array for t+1
evolved_array = numpy.zeros((height, width),numpy.uint8)
for iy in range(1, height-1):
for ix in range(1,width-1):
neighbours=number_neighbours(universe_array,iy,ix)
if universe_array[iy,ix]==0 and neighbours==3:
evolved_array[iy,ix]==1
elif universe_array[iy,ix]==1 and neighbours<2:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours>3:
evolved_array[iy,ix]==0
elif universe_array[iy,ix]==1 and neighbours==2 or neighbours==3:
evolved_array[iy,ix]=universe_array[iy,ix]
return evolved_array
def number_neighbours(universe_array,iy,ix):
neighbours=0 #fixed this line,thanks:)
if universe_array[iy-1,ix-1]==1:
neighbours+=1
if universe_array[iy,ix-1]==1:
neighbours+=1
if universe_array[iy+1,ix-1]==1:
neighbours+=1
if universe_array[iy-1,ix]==1:
neighbours+=1
if universe_array[iy+1,ix]==1:
neighbours+=1
if universe_array[iy-1,ix+1]==1:
neighbours+=1
if universe_array[iy,ix+1]==1:
neighbours+=1
if universe_array[iy+1,ix+1]==1:
neighbours+=1
else:
neighbours=neighbours
return neighbours
if __name__ == "__main__":
a = numpy.zeros((4,4),numpy.uint8)
a[1,1]=1
a[1,2]=1
a[2,1]=1
print a
b= apply_rules(a)
print b
Run Code Online (Sandbox Code Playgroud)
我是Python的初学者,我不知道如何修复错误.我是一个有点困惑约import "neighbours"到function "apply_rules",是正确的方式做到这一点?
Sva*_*nte 13
好吧,我想你对编程本身也很陌生,否则你在解释这个简单的错误信息时应该没有任何问题.
我会帮你解剖一下:
number_neighboursneighbours+=1UnboundLocalError: local variable 'neighbours' referenced before assignment这是什么意思?让我们看一下+=运算符的作用:它为当前值增加了一些东西neighbours.这意味着它会读取当前值,向其中添加内容,最后将其存储回来."阅读"在变量方面被称为"参考".
目前的价值是neighbours多少?好吧,它以前从未使用过,所以它没有任何价值 - 从来没有分配给它的值.添加"无价值"的东西不是明智之举.我想你希望它的值为0,但你必须告诉你的翻译.为此,请在函数开头之前添加以下语句: neighbours = 0