我正试图让一个“生活游戏”在python中运行,但我似乎无法让程序的邻居计数方面正常工作。我正在尝试使用多个if语句来避免数组中出现任何“越界”错误,这已经奏效了。然而,该项目正在寻找不存在的“邻居”,导致该项目在不应该的情况下到处产生活细胞。任何帮助都将不胜感激,我真的被困在这件事上了
额外信息:列表为10x10,单元格检查所有八个方向
谢谢
def checkNeighbours(newWorld, row, column):
neighboursCount = 0
if(column > 0):
if(newWorld[row][column-1] == ALIVE): #checks cell to left
neighboursCount = neighboursCount + 1
if(row < 9):
if(newWorld[row+1][column] == ALIVE): #checks cell below
neighboursCount = neighboursCount + 1
if(row < 9 and column < 9):
if(newWorld[row+1][column+1] == ALIVE): #checks cell to bottom right
neighboursCount = neighboursCount + 1
if(row < 9 and column > 0):
if(newWorld[row+1][column-1] == ALIVE): #checks cell to bottom left
neighboursCount = neighboursCount + 1
if(column < 9):
if(newWorld[row][column+1] == ALIVE): #checks cell to right
neighboursCount = neighboursCount + 1
if(row > 0 and column > 0):
if(newWorld[row-1][column-1] == ALIVE): #checks cell to top left
neighboursCount= neighboursCount + 1
if(row > 0):
if(newWorld[row-1][column] == ALIVE): #checks cell above
neighboursCount = neighboursCount + 1
if(row != 0 and column != 9):
if(newWorld[row-1][column+1] == ALIVE): #checks cell to top right
neighboursCount = neighboursCount + 1
return(neighboursCount)
def birthsAndDeaths(newWorld, row, column, neighboursCount):
if(neighboursCount == 3 and newWorld[row][column] == DEAD):
return(ALIVE)
elif(neighboursCount == 2 or neighboursCount == 3 and newWorld[row][column] == ALIVE):
return(ALIVE)
elif(neighboursCount <= 1):
return(DEAD)
elif(neighboursCount >= 4):
return(DEAD)
def turnChanger(turn, newWorld):
turn = turn + 1
row = 0
while (row < SIZE): # Each iteration accesses a single row
column = 0
while (column < SIZE): # Each iteration accesses a single column in the given row
neighboursCount = checkNeighbours(newWorld, row, column)
print(neighboursCount, "for cell", row, column)
newWorld[row][column] = birthsAndDeaths(newWorld, row, column, neighboursCount)
column = column + 1
row = row + 1
return(turn, newWorld)
def start():
choice = 0
choice = selection()
world = worldChooser(choice)
oldWorld = []
newWorld = []
turn = 0
oldWorld = world
newWorld = world
turn, newWorld = turnChanger(turn, newWorld)
display(turn, oldWorld, newWorld)
world = newWorld
start()
问题就在
birthsAndDeaths
函数中,在这一行:由于操作的顺序,必须确保首先计算
or
,因此在该部分周围使用括号任何
and
运算符都是在or
之前计算的,因此在代码中,当任何单元格旁边有两个相邻单元格时,它都会将单元格设置为活动的根据你当前的代码,假设我们有两个邻居在一个死囚的旁边,它就会消失
然后
然后
然后
并且
elif
的主体返回一个ALIVE
结果在
or
周围使用括号会导致首先计算这些括号的内容。在这种情况下,内容是一个or
操作。使用括号意味着我们将得到然后
然后
然后
这是您在这里询问的特定问题的解决方案。然而,Carcigenicate指出了另一个主要问题。如果你试图解决这个问题,但仍然有问题,你可以发布一个新问题
相关问题 更多 >
编程相关推荐