索引器错误:列表索引超出范围?Python

2024-05-15 17:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我创造了一个游戏,把宝箱和土匪放在一个格子里,让玩家通过它移动。基本上,如果玩家落在一个宝箱上,这个宝箱被随机放置在格子里,那么他们的硬币总数会增加10,如果玩家落在一个强盗身上,硬币总数将重置为0。在

但是,我已经尝试让程序把一个特定的宝箱变成一个强盗,如果它已经被访问了3次。我使用了列表visit[]visited[]来执行此操作,但是我一直得到错误:

IndexError: list index out of range

我不知道为什么?我已经附上了我所有的代码以供参考,并概述了似乎引起问题的部分。我该如何消除这个错误,使箱子在第三次造访后变成强盗?(在它的第四个)

^{pr2}$

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

Tags: ofinformovelenifrangebandits
1条回答
网友
1楼 · 发布于 2024-05-15 17:41:02

range (0, len(chests))上进行迭代,然后在visits[i] += 1行中得到一个错误。看起来chests和{}的长度不相等。我在visits列表中看不到任何appends,所以它基本上是空的。在

此外,您还在嵌套循环中混合计数器:

for i in range (0, len(chests)):
    ...
    # you override the i value here
    for i in range(0, len(visited)):

只需执行内部循环其他计数器,例如j

^{pr2}$

另外,您使用的是len(visited),但请看一下{},但不能保证这两个数组的长度相等。在

相关问题 更多 >