Python “随机”;ValueError:list。删除(x):x不在列表中;pygame中的错误
所以我有一个用python编写的小游戏,如果你看到我前面的问题,你就会知道这是一个“太空入侵者”的克隆 所以现在几乎所有的事情都进展顺利,除了偶尔会出现一个随机错误。这是完全随机的,可能发生在一些子弹发射后,也可能根本不会发生 我有以下代码:Python “随机”;ValueError:list。删除(x):x不在列表中;pygame中的错误,python,pygame,Python,Pygame,所以我有一个用python编写的小游戏,如果你看到我前面的问题,你就会知道这是一个“太空入侵者”的克隆 所以现在几乎所有的事情都进展顺利,除了偶尔会出现一个随机错误。这是完全随机的,可能发生在一些子弹发射后,也可能根本不会发生 我有以下代码: for bullet in bullets: bullet.attack() if bullet.posy<=-20: bullet_draw=False if bull
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
对于项目符号中的项目符号:
子弹攻击
如果bullet.posy你的子弹击中了多个敌人。您需要中断循环。尝试将其更改为以下内容:
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
尽管代码看起来应该从列表中删除每个元素,但它只会删除其他元素,因为列表索引在迭代过程中不断变化。从OP正在迭代的列表中删除项目也会导致问题。@DSM:True,但这很容易处理<代码>用于项目符号中的项目符号[:]:
完成!顺便说一句,continue
紧跟在bullet\u draw=True
下缩进的中的bullet-in-bullets
对吗?@IgnacioVazquez Abrams:当然可以,但当我按下enter键时,我没有看到F.J.的更新,它修复了它。^)通常,捕获错误,然后使用事后调试程序(import pdb;pdb.post_-mortem()
)是一种很好的解决方法。在开发过程中,我通常在程序的入口点周围有一个catch-all-try-except子句,这样我就可以立即调试甚至是不可预见的问题。
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
>>> data = range(10)
>>> for x in data:
... data.remove(x)
...
>>> data
[1, 3, 5, 7, 9]