首页 \ 问答 \ IndexError:列表索引超出范围?(IndexError: list index out of range? Python)

IndexError:列表索引超出范围?(IndexError: list index out of range? Python)

所以我创造了一个游戏,将宝箱和土匪放在一个网格中,让玩家可以穿过它。 基本上,如果玩家落在随机放置在网格内的宝箱中,他们的硬币总数上升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()

So I have created a game that places treasure chests and bandits within a grid and allows the player to move through it. Essentially, if the player lands on a treasure chest, which are randomly placed within the grid, their coin total goes up by 10, and if the player lands on a bandit, the coin total is reset to 0.

However, I have attempted to get the program to turn a specific treasure chest into a bandit if it has been visited 3 times. I have used the lists visit[] and visited[] to do so, however I keep getting the error:

IndexError: list index out of range

and I don't know why? I have attached all my code for reference and outlined the section that seems to be causing the problem. How do I get rid of the error so that the chest turns into a bandit after it's third visit?(on it's fourth)

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]

The section below is where the lists that are bringing up the error are used

        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()

原文:https://stackoverflow.com/questions/43646586
更新时间:2022-04-03 13:04

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。