IndexError:列表索引超出范围?蟒蛇

时间:2017-04-27 00:15:30

标签: python list runtime-error

所以我创造了一个游戏,将宝箱和土匪放在一个网格中,让玩家可以穿过它。基本上,如果玩家落在随机放置在网格内的宝箱中,他们的硬币总数上升10,如果玩家落在强盗上,则硬币总数将重置为0.

然而,如果已经访问了3次,我试图让程序将特定的宝箱变成强盗。我已使用列表visit[]visited[]来执行此操作,但我不断收到错误:

IndexError: list index out of range

我不知道为什么?我附上了所有代码以供参考,并概述了似乎导致问题的部分。我如何摆脱错误,以便在第三次访问后胸部变成强盗?(在它的第四次)

Traceback: 
line 130, in <module>
    visits[i] += 1
IndexError: list index out of range

choice = 0
b = 0
player_location = ' X '
x = 8
y = 0
coins = 0
bandits = 5
treas_chests = 10
a = 1
import random
x_move = 0
y_move = 0
no_of_bands = 5
size_of_grid = 8
chests = []
bandits = []
size_of_grid_n = 0
visits = []
visited = []
def menu(): 
    print('If you would like to play the Treasure Hunt , press 1') 
    choice = input('If not, press any key to exit \n') 
    if choice == '1': 
        print('Great! You have made the right choice :)') 
    else: 
        print('Goodbye.') 
        quit() 
menu() 
def board(): 
    new_board = [ ]
    top_row = [' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 ']

    new_board.append(top_row)

    for x in range(0, 8):
        row = [' 0 '] * size_of_grid
        new_board.append(row)

    return new_board

def print_board(b):
  row_numbers = [' ', '1', '2', '3', '4', '5', '6', '7', '8']
  i = 0
  for row in b:
    print (row_numbers[i], ''.join(row))
    i = i + 1
current_x_loc = 0
current_y_loc = size_of_grid

def update_board(b, current_y_loc, current_x_loc):
    #b[current_y_loc-y_move][current_x_loc+x_move] = player_location
    while (-1 >= current_y_loc-y_move) or (current_y_loc -y_move > size_of_grid):
        print('INVALID INPUT')
        get_move()
    while (-1 >= current_x_loc + x_move) or (current_x_loc + x_move > size_of_grid):
        print('INVALID INPUT')
        get_move()
    b[current_y_loc - y_move][current_x_loc + x_move] = player_location
    current_y_loc -= y_move
    current_x_loc += x_move
    print("current location = ", current_x_loc, current_y_loc)
    return current_y_loc, current_x_loc

def chests_and_bandits():
    num = 0
    while num < treas_chests:
        y_c = random.randint(1, size_of_grid)  
        x_c = random.randint(1, size_of_grid)
        location = [y_c, x_c]
        while (location in location) or (location == [size_of_grid, 0]):
            y_c = random.randint(1, size_of_grid)
            x_c = random.randint(1, size_of_grid)
            location=[y_c, x_c]
        chests.append(location)
        num = num + 1

    num = 0
    print(chests)
    while num < no_of_bands:
        y_b = random.randint(1, size_of_grid)
        x_b = random.randint(1, size_of_grid)
        location=[y_b, x_b]
        while (location in location) or (location in chests) or (location == [size_of_grid, 0]):
            y_b = random.randint(1, size_of_grid)
            x_b i= random.randint(1, size_of_grid)
            location = [y_b, x_b]
        bandits.append(location)
        num = num + 1
    print(bandits)

while a == 1:
    chests_and_bandits()
    def get_move():
        advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space.  Use positive numbers for up and right, negative for down and left.'
        example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
        move = input(advice + example)
        coor=move.split()
        while len(coor) != 2:
            print('Invalid input- too many or too few co-ordinates')
            print('')
            advice = 'Please enter your move in two integers, vertical, then horizontal, separated by a space.  Use positive numbers for up and right, negative for down and left.'
            example = 'For example, an input of \'2 2\' would be 2 moves vertically, and 2 moves horizontally.'
            move = input(advice + example)
            coor = move.split()
        move = move.split()
        y_move, x_move = move
        x_move = int(x_move)
        y_move = int(y_move)
        return x_move, y_move

    while True:
        new_board = board()
        current_y_loc, current_x_loc = update_board(new_board, current_y_loc, current_x_loc)
        print_board(new_board)
        print(' ')
        print(current_x_loc, current_y_loc)
        cur_loc = [current_x_loc, current_y_loc]
  

以下部分是使用错误的列表

        for i in range (0, len(chests)):
            if cur_loc == chests[i]:
                coins += 10
                print('You have found a treasure chest')
                print('Number of coins: ',coins)
                print('')
                visits[i] += 1
                if visits[i] > 3:
                    visited[i] = True
                    bandits.append(chests[i])
                    var = chests[i]
            for i in range(0, len(visited)):
                chests.remove
                if visits[i] == 3:
                    treas_chests -= 1
                    no_of_bands += 1
                    bandits.append(chests[i])
                    var = chests[i]
        for i in range (0, len(bandits)):
            if cur_loc == bandits[i]:
                coins = 0
                print('You have hit a bandit')
                print('Number of coins: ', coins)
                print('')


        x_move, y_move = get_move()

1 个答案:

答案 0 :(得分:1)

您对visits[i] += 1进行迭代,之后在行chests中出现错误。看起来visitsappends的长度不等。我无法在visits列表中看到任何for i in range (0, len(chests)): ... # you override the i value here for i in range(0, len(visited)): ,因此它基本上是空的。

另外,您是在嵌套循环中混合计数器:

j

只需做内循环其他其他计数器,例如for i in range (0, len(chests)): ... for j in range(0, len(visited)):

len(visited)

此外,您使用的是visits[i],但请查看{{1}},但无法保证这两个数组的长度相等。