所以我创造了一个游戏,把宝箱和土匪放在一个格子里,让玩家通过它移动。基本上,如果玩家落在一个宝箱上,这个宝箱被随机放置在格子里,那么他们的硬币总数会增加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()
在}的长度不相等。我在
range (0, len(chests))
上进行迭代,然后在visits[i] += 1
行中得到一个错误。看起来chests
和{visits
列表中看不到任何appends
,所以它基本上是空的。在此外,您还在嵌套循环中混合计数器:
只需执行内部循环其他计数器,例如
^{pr2}$j
:另外,您使用的是},但不能保证这两个数组的长度相等。在
len(visited)
,但请看一下{相关问题 更多 >
编程相关推荐