Pygame pop()类崩溃

问题描述 投票:1回答:1

在我尝试使用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)
python python-3.x pygame
1个回答
1
投票

问题是,您删除(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
© www.soinside.com 2019 - 2024. All rights reserved.