首页 > 解决方案 > Pygame pop() 类崩溃

问题描述

在我尝试使用 pygame 制作的游戏中,我的玩家能够射击从数组中的类的实例创建的“子弹”(名为“shots”),但是当我尝试删除它们时,程序会崩溃。下面是我的代码,我做错了什么导致它崩溃?

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)

标签: pythonpython-3.xpygame

解决方案


问题是,您在删除 ( pop) 项时遍历列表。当您删除列表的最后一项时,该项目的索引仍包含在 rangerange(len(shots))中,但访问shots[i]将失败。
一个简单的解决方法是以相反的顺序遍历列表。反转范围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)

另一种选择是迭代列表的浅表副本([:])并从原始列表中删除元素。请参阅数据结构

for shot in shots[:]:
    shot.shoot()
    shot.drawBullet()

    if shot.x > swidth or shot.x < 0:
        shots.remove(shot)

推荐阅读