【发布时间】:2020-05-03 16:10:53
【问题描述】:
我正在关注康威人生游戏的基于文本版本的教程(来自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)
我是编码新手,所以我尝试注释掉这些行,但当然这只会使使用这些功能的其他部分无法使用。关于这个主题的其他问题似乎也与这个游戏的更高级版本有关。就像我说的,这是我的第一个程序之一。
【问题讨论】:
标签: conways-game-of-life index-error