I created a game space invaders with multiple enemies

Viewed 131

I wanted to create 1 extra enemy.I have a problem of looping through lists.But I keep getting this error when I do this:

   enemyX[i] += enemyX_change[i]
   IndexError: list index out of range

Here is my code:

num_of_enemies = 10
number = 1 
enemyX = []
enemyX_change = []
for i in range(num_of_enemies):
        enemyX.append(i)
        enemyX_change.append(3)

print(len(enemyX))
print(len(enemyX_change))
num_of_enemies += number
for i in range(num_of_enemies):
        enemyX[i] += enemyX_change[i]
1 Answers

I am not sure I fully understand your code.
However, you never append elements to your enemyY list, but your num_of_enemies keep increasing.
Thus, because at time zero, len(enemyY) = num_of_enemies, you just need to add one to num_of_enemies (did after the first collision occurs),for looking at enemyY[len(enemyY)]... obviously this is out of range.

If your number of enemies keep being constant, consider removing the variable num_of_enemies (or let it be a constant).
If your number of enemies changes, do not forget to append / pop elements to your list.

Was this clear or helpful?

Related