我是python的初学者,我试图将生命游戏编程为课堂练习。我此时正试图调试代码,并且我遇到了一个问题,即无论起始布局如何,所有单元格在第一次迭代时都显示为死亡。
示例运行:
启动委员会:
00000
00000
000X0
000X0
000X0
迭代1:
00000
00000
00000
00000
00000
我怀疑问题在于两个功能之一。
这是调用我所做的nextIteration
函数的代码:
numIters = int(input("How many iterations should I run?: "))
print("Starting Board:")
printBoard(myBoard)
for t in range(1,numIters+1):
myBoard = nextIteration(myBoard)
print("Iteration ",t,":")
printBoard(myBoard)
这里是nextIteration
功能:
def nextIteration(board):
board2 = board
for i in range(len(board)):
for v in range(len(board[0])):
myNum = numAlive(i,v,board)
if(board[i][v] == "X"):
if(myNum < 2):
board2[i][v] = 0
elif(myNum > 3):
board2[i][v] = 0
elif(board[i][v] == 0):
if(myNum == 3):
board2[i][v] = "X"
return board2
这是我用来计算生活邻居的功能(AKA numAlive
):
def numAlive(row,col,board):
count = 0
#Row exits above cell
if(row != 0):
if(board[row-1][col] == "X"):
count = count + 1
#Column exists to left of cell
if(col != 0):
if(board[row-1][col-1] == "X"):
count = count + 1
#Column exists to right of cell
if(col != (len(board[0])-1)):
if(board[row-1][col+1] == "X"):
count = count + 1
#Row exists below cell
if(row != (len(board)-1)):
if(board[row+1][col] == "X"):
count = count + 1
#Column exists to left of cell
if(col != 0):
if(board[row+1][col-1] == "X"):
count = count + 1
#Column exists to right of cell
if(col != (len(board[0])-1)):
if(board[row+1][col+1] == "X"):
count = count + 1
#Column exists to left of cell
if(col != 0):
if(board[row][col-1] == "X"):
count = count + 1
#Column exists to right of cell
if(col != (len(board[0])-1)):
if(board[row][col+1] == "X"):
count = count + 1
return count
我现在重写了几次,但没有效果。任何建议将不胜感激!