I am trying to make a "space invaders" game in pygame...I have much of the game already running, but I ran into an annoying problem I cannot solve myself (it is the first programming course I have taken). Here is the code in question:
for enemy in enemies:
if hero.sprite.rect.colliderect(enemy.sprite.rect) or enemy.posy>400:
hero.health-=1
initgame()
break
else:
enemy.moveBy(enemyPos, ENEMYVERT)
enemy.draw()
So what this should supposedly do is:
- check for every item in a list named "enemies" (where I have appended all my enemy instances)
- if it collides with the hero sprite or if they have reached the bottom of the screen
- then remove one life from the player, initialise the game (remake the enemy list, reset positions)
- and break the "for" loop.
- Else, move the enemies and blit them as usual.
However, what this does is actually remove ALL lives from the player on touch. Shouldn't it stop calculating since I used break? I think it keeps calculating if any in enemies has reached 400px thus keeps removing lives from my player.
This is my initgame function
def initgame():
enemies=[]
createEnemies("1.png", 50, 250)
createEnemies("2.png", 50, 190)
createEnemies("3.png", 50, 130)
createEnemies("4.png", 50, 70)
createEnemies("5.png", 50, 10)
enemyPos=0
enemyDir=-1
hero.score=0
restartFlag=False
for enemy in enemies:
enemy.draw()
initgame()? I suspect you error lies there.