Now place the player on the screen and add it to the all_sprites list using the .add() method.
player = Player()
Do the same for the enemies.
enemies = pygame.sprite.Group()
Spawn 2 enemies at a time using a for loop. Note thatirepresents avariable. You can change the number of enemies onscreen by using a different number instead of 2. Try it out! We’ll also add enemy to bothall_spritesandenemylists.
for i in range(2):
enemy = Enemy()
For loopsare used to repeat code in a program.While loopsuse true/false conditions whereasfor loopsdepend on the elements it has to iterate (repeat).
At the beginning of our game, our score should begin at 0. Set the score variable to that.
score = 0
Now we can code the main game loop! Set the frame rate of the game.
Next, tell the computer to check for events. If the player has quit the game then it should end the run loop.
if event.type == pygame.QUIT:
running = False
The next event to check is if a key is pressed then which one? Use two more if statementsfor this. We’ll use the spacebar as the key to shoot the projectiles.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
If you attack an enemy, then another enemy should replace that one and your score should go up! Incrementyour score variable by 1 for each enemy you take down.