擅长:python、mysql、java
<p>尝试将其更改为以下内容:</p>
<pre><code> 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
</code></pre>
<p>注意我添加的两个注释显示了这些变化,<code>break</code>是必需的,因为一颗子弹可能会击中多个敌人,这将导致<code>bullets.remove(bullet)</code>被调用两次,这将导致您看到的回溯。在</p>
<p>第一个更改是必需的,因为在迭代时从列表中删除元素可能会导致一些意外的结果,因为在迭代过程中您将跳过某些元素。以下代码说明了这一点:</p>
^{pr2}$
<p>尽管代码看起来应该从列表中删除每个元素,但它只删除其他元素,因为列表索引在迭代过程中会发生变化。在</p>