随机“值错误:列表.删除(x) :x not in list“pygam错误

2024-04-30 01:11:49 发布

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

所以我有一个用python编写的小游戏,如果你看到我之前的问题,你就会知道它是一个“太空入侵者”的克隆。在

所以现在几乎所有的事情都很顺利,只是偶尔会出现一个随机错误。这是完全随机的,它可能发生在一些子弹发射后,也可能根本不会发生。在

我有这个代码:

    for bullet in bullets:
        bullet.attack()
        if bullet.posy<=-20:
            bullet_draw=False
        if bullet_draw==True:
            bullet.draw()
        for enemy in enemies:
            if bullet.sprite.rect.colliderect(enemy.sprite.rect):
                enemy.health-=1
                bullets.remove(bullet)
                bullet_draw=False
            else:
                bullet_draw=True

有时它会给我以下错误。在

^{pr2}$

请注意,这个错误是完全随机的;即使不是,我也无法追踪它的来源。有什么办法可以消除它吗?在


Tags: inrectfalsetrueforif错误太空
2条回答

尝试将其更改为以下内容:

    for bullet in bullets[:]:    # this is changed, iterating over a copy
        bullet.attack()
        if bullet.posy<=-20:
            bullet_draw=False
        if bullet_draw==True:
            bullet.draw()
        for enemy in enemies:
            if bullet.sprite.rect.colliderect(enemy.sprite.rect):
                enemy.health-=1
                bullets.remove(bullet)
                bullet_draw=False
                break            # this is added, prevents multiple removes
            else:
                bullet_draw=True

注意我添加的两个注释显示了这些变化,break是必需的,因为一颗子弹可能会击中多个敌人,这将导致bullets.remove(bullet)被调用两次,这将导致您看到的回溯。在

第一个更改是必需的,因为在迭代时从列表中删除元素可能会导致一些意外的结果,因为在迭代过程中您将跳过某些元素。以下代码说明了这一点:

^{pr2}$

尽管代码看起来应该从列表中删除每个元素,但它只删除其他元素,因为列表索引在迭代过程中会发生变化。在

你的子弹击中了多个敌人。您需要break退出enemies循环。在

相关问题 更多 >