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