python-3.x - IndexError:列表索引超出范围。蟒蛇3。游戏人生项目
问题描述
我试图找出错误发生的原因,但我不知道。我在想可能是因为 WIDTH 和 HEIGHT 的大小并且内存分配不好,所以我降低了值,但它没有改变。
import time, random, copy
WIDTH = 60
HEIGHT = 20
# crate a list of lists for the cells:
nextCells = []
for x in range(WIDTH):
column = [] # create new column
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('#') # add living cell
else:
column.append(' ') # add dead cell
nextCells.append(column) # nextCells is a list of column list
while True:
print('\n\n\n\n\n') # separate each step with newlines.
currentCells = copy.deepcopy(nextCells)
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') # print the # or space
# Calculate the next step's cells based on current step's cells:
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neighboring coordinates:
# `% WIDTH` ensures leftCoord is always between 0 and WIDTH - 1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# count number of living neighbors
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1 # top-left neighbor is alive
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1 # top neighbor is alive
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1 # top-right neighbor is alive
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1 # bottom-left neighbor is alive
if currentCells[x][belowCoord] == '#':
numNeighbors += 1 # bottom neighbor is alive
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1 # bottom-right neighbor is alive
if currentCells[leftCoord][y] == '#':
numNeighbors += 1 # left neighbor is alive
if currentCells[rightCoord][y] == '#':
numNeighbors += 1 # right neighbor is alive
# set the game rules:
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
nextCells[x][y] = '#' # living cells with 2 or 3 neghbors stay alive
elif currentCells[x][y] == ' ' and numNeighbors == 3:
nextCells[x][y] = '#' # dead cells with 3 neighbors
else:
nextCells[x][y] = ' ' # everything else die or stay
time.sleep(1) # add 1-second pause
任何帮助将不胜感激。
解决方案
尝试在 while 循环中更改迭代器的名称 - 从 x,y 到 i,j - 它应该会有所帮助。
推荐阅读
- javascript - 如何将“0,0”“00,0”识别为零输入?
- python - 有没有办法检查列表中的字符串是否包含另一个列表中的任何子字符串?
- vba - 如何获取组合框 (2) 列的旧值?
- python-3.x - 没有名为 virtualenvwrapper 的模块?
- python - 为什么即使在使用“conda install tensorflow”安装 tensorflow 后,我的 jupyter notebook 上的 tensorflow 也无法正常工作?
- ios - 使用 SFSafariViewController 代替 ASWebAuthenticationSession/SFAuthenticationSession 进行 OAuth
- c# - 无法转换类型为“System.Data.Entity.Infrastructure.DbQuery”的对象
- swift - 函数完成处理程序 Swift 4
- excel - VBA - 如何比较同一列中的新条目然后修改另一个单元格
- oracle - Oracle APEX 卡未显示所有数据