在我尝试使用pygame制作的游戏中,我的播放器能够拍摄从数组中的类实例创建的“子弹”(称为“子弹”),但是当我尝试删除它们时,程序崩溃。下面是我的代码,我在做什么错而导致崩溃?
for i in range(len(shots)):
shots[i].shoot()
shots[i].drawBullet()
if shots[i].x > swidth or shots[i].x < 0:
shots.pop(i)
问题是,您删除(pop
)个项目时遍历列表。当您删除列表的最后一项时,该项的索引仍包含在range(len(shots))
范围内,但对shots[i]
的访问将失败。一个简单的解决方法是以相反的顺序遍历列表。通过reversed
反转范围:
reversed
另一种选择是迭代列表的浅表副本([:])并从原始列表中删除元素。参见for i in reversed(range(len(shots))):
shots[i].shoot()
shots[i].drawBullet()
if shots[i].x > swidth or shots[i].x < 0:
shots.pop(i)
:
Data Structures