Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should not remove items from a list you are looping over. Create a copy instead:</p> <pre><code>for a in aliens[:]: </code></pre> <p>and</p> <pre><code>for b in bolts[:]: </code></pre> <p>Modifying a list while looping over it, affects the loop:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3] &gt;&gt;&gt; for i in lst: ... print i ... lst.remove(i) ... 1 3 &gt;&gt;&gt; lst [2] </code></pre> <p>Removing items from a list you are looping over twice makes things a little more complicated still, resulting in a ValueError:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3] &gt;&gt;&gt; for i in lst: ... for a in lst: ... print i, a, lst ... lst.remove(i) ... 1 1 [1, 2, 3] 1 3 [2, 3] Traceback (most recent call last):   File "&lt;stdin&gt;", line 4, in &lt;module&gt; ValueError: list.remove(x): x not in list </code></pre> <p>When creating a copy of the lists you are modifying at <em>each</em> level of your loops, you avoid the problem:</p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3] &gt;&gt;&gt; for i in lst[:]: ... for i in lst[:]: ... print i, lst ... lst.remove(i) ... 1 [1, 2, 3] 2 [2, 3] 3 [3] </code></pre> <p>When you have a collision, you only need to remove the <code>b</code> bolt <em>once</em>, not in the loop where you hurt the aliens. Clean out the aliens separately later:</p> <pre><code>def manage_collide(bolts, aliens): for b in bolts[:]: for a in aliens: if b['rect'].colliderect(a['rect']) and a['health'] &gt; 0: bolts.remove(b) for a in aliens: a['health'] -= 1 for a in aliens[:]: if a['health'] &lt;= 0: aliens.remove(a) return bolts, aliens </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload