我正在使用python编写Conway的生活游戏,到目前为止我的代码是这样的:

时间:2015-07-17 17:20:40

标签: python arrays

def initial_board(row, col, array):

    firstList = [[0] * col for i in range(row)]
    for i in firstList:
        i.append(-1)
        i.insert(0,-1)
    firstList.insert(0, [-1] * (col + 2))
    firstList.append([-1] * (col + 2))

    while True:
        coordinateInput = input('Enter the coordinates of a seed cell as \"r c\": ')
        if coordinateInput == '':
            break
        point = coordinateInput.split(' ', 1)
        row = int(point[0])
        col = int(point[1])
        firstList[row][col] = 1

    return firstList

def next_board(row, col, current, new):

    for i in range(1, row - 1):
        for j in range(1, col - 1):
            new[i][j] = live_conditions(i, j, current)

def live_conditions(x, y, array):

    cellCount = 0
    for j in range(y - 1, y + 1):
        for i in range(x - 1, x + 1):
            if not(i == x and j == y):
                if array[i][j] != -1:
                    cellCount += array[i][j]
    if array[x][y] == 1 and cellCount < 2:
        return 0
    if array[x][y] == 1 and cellCount > 3:
        return 0
    if array[x][y] == 0 and cellCount == 3:
        return 1
    else:
        return array[x][y]

def print_board(row, col, array):

    for i in range(row + 2):
        for j in range(col + 2):
            if array[i][j] == 1:
                print('*', end =' ')
            else:
                print(' ', end =' ')
        print()

def game_board():

    while True:
        try:
            row = int(input('What size board? '))
            if row > 0:
                col = row
                break
            else:
                continue
        except ValueError or dimension <= 0:
            pass
    firstList = []
    nextlist = []
    firstList = initial_board(row, col, firstList)
    nextList = [row[:] for row in firstList]

    print()

    generations = int(input('How many generations?: '))
    for gen in range(generations):
        print('Gen: ', gen)
        print_board(row, col, firstList)
        next_board(row, col, firstList, nextList)
        firstList, nextList = nextList, firstList

game_board()

然而,当我运行它时,输入5​​ 5我得到了这个:

What size board? 5
Enter the coordinates of a seed cell as "r c": 5 5
Enter the coordinates of a seed cell as "r c": 

How many generations?: 3
Gen:  0





          *   

Gen:  1





          *   

Gen:  2





          *   

我觉得问题出在我的函数live_conditions中,而cellCount无法正常工作。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为这是你的问题,或者无论如何都是一个问题:

for j in range(y - 1, y + 1):

当你编写范围时,它会迭代列表[y-1,y],而不是像你想象的那样[y-1,y,y + 1]。来自文档:

  

最后一个元素是最大的开始+ i *步骤小于停止

然而,很难看出这个错误如何导致你所看到的确切问题;对于单个活细胞,它应该仍然计算零邻居,并将其扼杀。我将提出我的通用建议:添加一堆打印语句,看看代码在运行时的作用。

编辑添加:实际上你在next_board中遇到了类似的问题 - 你只是更新范围[0,row-1]。因此,右下角永远不会更新。建议您检查每个调用范围,以确定是否有错误。