🔁 Sprites and Main Game Loop | myBetabox

🔁 Sprites and Main Game Loop

Keyboard Guide

Sprites and Main Game Loop

The Code Explained

Create a list for all the sprites in the game.

all_sprites = pygame.sprite.Group()

Now place the player on the screen and add it to the all_sprites list using the .add() method.

player = Player()
all_sprites.add(player)

Do the same for the enemies.

enemies = pygame.sprite.Group()

Spawn 2 enemies at a time using a for loop. Note that i represents a variable. 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 both all_sprites and enemy lists.

for i in range(2):
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)

🌟For loops are used to repeat code in a program. While loops use true/false conditions whereas for loops depend 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.

clock.tick(FPS)

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 statements for this. We’ll use the spacebar as the key to shoot the projectiles.

elif event.type == pygame.KEYDOWN:
 if event.key == pygame.K_SPACE:
      player.launch()

If you attack an enemy, then another enemy should replace that one and your score should go up! Increment your score variable by 1 for each enemy you take down.

enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
score += 1