Space Invaders

Note

Requires: session 7 finished.

Aliens are lined up in a 4×9 formation. They move back and forth, drop down at every edge and shoot back at random. You have one ship and three lives. Shoot them all down before they land.

Getting started

Download the starter code and unpack the ZIP. Open main.py in Thonny and click Run. You see the ship and the alien formation. The controls and the images are already there. You fill in the movement, the shooting and the collisions.

How does it work?

All the aliens are pygame.Rect objects in one list. Every frame you move them all by the same number of pixels. When the formation touches an edge, you reverse the direction and drop every alien by ALIEN_VAL pixels.

for alien in aliens:
    alien.x += snelheid * alien_richting

rechts = max(a.right for a in aliens)
links  = min(a.left  for a in aliens)
if rechts >= BREEDTE or links <= 0:
    alien_richting *= -1
    for alien in aliens:
        alien.y += ALIEN_VAL

Bullets are pygame.Rect objects too. Player bullets go up (k.y -= KOGEL_SNL), alien bullets go down (k.y += ALIEN_SNL). You check collisions with k.colliderect(alien).

✅ Basic

  • Draw the background (use random.seed(42) for fixed stars), the ship and all the aliens.
  • Move the ship left/right with the arrow keys.
  • Let the formation move back and forth and drop down at an edge.
  • Fire a bullet upwards when the player presses space. Use COOLDOWN_MS to stop insanely fast shooting.

⭐ Stretch

  • Player bullet hits an alien: remove both, score += 10.
  • Every alien shoots back at random: if random.random() < SCHIET_KANS.
  • Alien bullet hits the player: levens -= 1; game over at 0 lives.
  • Show the score and the lives in the top left.

🔥 Expert

  • The formation speeds up as fewer aliens are left: 1 + 3 * (1 - restant). From 1 pixel/frame at the start to 4 pixels/frame with the last alien.
  • Game over when an alien reaches the bottom (alien.bottom >= HOOGTE - 50).
  • Game over (won) when the list is empty.
  • Restart with R: set all the variables again through a reset() function.

Downloads

  • Starter code: main.py with the window, images and alien grid ready; you fill in the logic.
  • Images: ship.png, enemy.png and laser.png if you start without the starter code.

Images: Kenney Space Shooter Redux, CC0 (public domain). kenney.nl