首页 > 解决方案 > 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

任何帮助将不胜感激。

标签: python-3.xindex-error

解决方案


尝试在 while 循环中更改迭代器的名称 - 从 x,y 到 i,j - 它应该会有所帮助。


推荐阅读