首页 > 解决方案 > 如何修复此列表超出范围?

问题描述

我正在制作一个玩家可以在 8x8 网格上移动的游戏,但是我收到了一个错误,其中的值超出了范围。

这是我的代码:

def player_movement():
    grid0 = [] 
    grid1 = []
    i = 0
    n = 0
    while i < 8: #this makes the grid
        grid0.append("0")
        i += 1
    while n < 8:
        grid1.append(grid0.copy())
        n += 1

    grid1[0][0] = "X" # this places the player on the top left of the grid

    for l in grid1:
        print(l)

    while True:
        player_movex = int(input("Move right how many?"))# instructions to move the player
        player_movey = int(input("Move down how many??"))

        for y, row in enumerate(grid1): #this finds the player on the grid
            for x, i in enumerate(row):
                if i == "X":
                    grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]

        for j in grid1: #prints out the grid in the 8x8 format
            print(j)

我正在输入列表范围内的值,即 0-7。

这是我屏幕上出现的错误:

Traceback (most recent call last):
  File "D:\Python\Treasure Hunt game.py", line 83, in <module>
    player_movement()
  File "D:\Python\Treasure Hunt game.py", line 78, in player_movement
    grid1[y][x], grid1[y + player_movey][x + player_movex] = grid1[y + player_movey][x + player_movex], grid1[y][x]
IndexError: list index out of range

标签: python

解决方案


我宁愿编码如下:

def player_movement():
    n = 8
    grid = [['0'] * n for _ in range(n)]
    m = 'x'
    grid[0][0] = m  # this places the player on the top left of the grid

    for i in grid:
        print(i)

    while True:
        # instructions to move the player
        player_movex = int(input("Move right how many? "))
        player_movey = int(input("Move down how many?? "))

        move(grid, m, n, player_movey, player_movex)
        for j in grid:  # prints out the grid in the 8x8 format
            print(j)


def move(grid, m, n, move_y, move_x):
    for y, row in enumerate(grid):  # this finds the player on the grid
        for x, i in enumerate(row):
            if i == m:
                a, b = y + move_y, x + move_x
                if a >= n:
                    print(f'Sorry, move {move_y} down will out of range!\n')
                    return
                if b >= n:
                    print(f'Sorry, move {move_x} right will out of range!\n')
                    return
                grid[y][x], grid[a][b] = grid[a][b], grid[y][x]
                return


player_movement()

推荐阅读