IndexError:字符串索引超出了Conway的生活游戏教程的范围

我正在跟踪有关Conway生活游戏的基于文本的版本的教程(来自https://automatetheboringstuff.com/2e/chapter4/),我已经按照教程中的说明进行了准确的说明,但仍然会产生IndexError:

错误消息如下:

print(currentCells[x][y],end='')

IndexError:字符串索引超出范围

我的目标是在单元格“处于活动状态”(满足某些要求)时放置空白,而在单元格“处于死亡状态”(满足其他要求)时放置#。 即时通讯感到困惑,为什么即使我直接从教程中复制本教程,也会弄错它。本教程适用于python 3.8

整个代码块如下:

while True:
print('\n\n\n\n\n')
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
    for x in range(WIDTH):
        print(currentCells[x][y],end='')
    print()
for x in range(WIDTH):
    for y in range(HEIGHT):
        leftCoord = (x - 1) % WIDTH
        rightCoord = (x + 1) % WIDTH
        aboveCoord = (y - 1) % HEIGHT
        belowCoord = (y + 1) % HEIGHT
        numNeighbors = 0
        if currentCells[leftCoord][aboveCoord] == '#':
            numNeighbors += 1
        if currentCells[x][aboveCoord] == '#':
            numNeighbors += 1
        if currentCells[rightCoord][aboveCoord] == '#':
            numNeighbors += 1
        if currentCells[leftCoord][y] == '#':
            numNeighbors += 1
        if currentCells[rightCoord][y] == '#':
            numNeighbors += 1
        if currentCells[leftCoord][belowCoord] == '#':
            numNeighbors += 1
        if currentCells[x][aboveCoord] == '#':
            numNeighbors += 1
        if currentCells[rightCoord][belowCoord] == '#':
            numNeighbors += 1

        if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
            nextCells[x][y] = '#'
        elif currentCells[x][y] == ' ' and numNeighbors == 3:
            nextCells[x][y] = '#'
        else:
            nextCells[x][y] = ' '
    time.sleep(1)

我是编码的新手,所以我尝试注释掉这些行,但是当然这只会使使用这些功能的其他部分不可用。另外,与此主题相关的其他问题似乎与该游戏的更高级版本有关。就像我说的那样,这是我的第一个程序。

Swdream2008 回答:IndexError:字符串索引超出了Conway的生活游戏教程的范围

我对使用Python编程太陌生了!这是学习的好语言:-)

无论如何,我认为我发现了代码问题。有个小错误... 如果您查看第25行,它会显示'nextCells是列表'的列表。 因此,应该添加空字符串而不是:

line 25: nextCells.append(column)

enter image description here

本文链接:https://www.f2er.com/2756559.html

大家都在问