I have this piece of code written in python using pygame to display objects on the screen and then detect collisions and remove the objects when a collision takes place.
When I have the code written like this everytime a collision occurs I get this error:
Code:
for i in range(len(asteroids)):
asteroidObj = asteroids[i]
asteroidObj['rect'] = pg.Rect((asteroidObj['x'],
asteroidObj['y'],
asteroidObj['width'],
asteroidObj['height']))
screen.blit(asteroidObj['surf'], asteroidObj['rect'])
asteroidObj['x']+= asteroidObj['xChange']
asteroidObj['y']+= asteroidObj['yChange']
if asteroidObj['rect'].colliderect(shipObj['rect']):
del asteroids[i]
Error:
asteroidObj = asteroids[i]
IndexError: list index out of range
However if I change the for loop to be:
for i in range(len(asteroids)-1, -1, -1):
The code works as intended and I no longer get an error.
One of the loops iterates from item 0-49 and the other from 49-0 so I am confused as to why one works and one doesn't. Does anyone know why this might be?