Today I built a Space Invaders style arcade game using Pygame. It includes a player spaceship, rows of aliens, bullets, explosions, sound effects, and a countdown before the action begins. The game uses sprite groups to manage everything on screen and it tracks win and loss conditions based on whether the player survives or destroys all enemies.
class Spaceship(pygame.sprite.Sprite):
^This class creates the player controlled ship. It loads the ship image, sets its starting position, tracks health, handles movement with the arrow keys, manages shooting with a cooldown timer, and draws a health bar under the ship.
def update(self):
^This function runs every frame. It moves the ship left or right, fires bullets when the spacebar is pressed, updates the collision mask, and draws the health bar. If health reaches zero it creates an explosion and signals that the player has lost.
class Bullets(pygame.sprite.Sprite):
^This class defines the bullets fired by the player. Each bullet moves upward, destroys itself when it leaves the screen, and checks for collisions with aliens. When a collision happens it plays an explosion sound and creates an explosion animation.
class Aliens(pygame.sprite.Sprite):
^This class creates the alien enemies. Each alien loads a random sprite, moves horizontally in a back and forth pattern, and reverses direction after traveling a set distance. They do not shoot on their own. The main loop controls when alien bullets appear.
class Alien_Bullets(pygame.sprite.Sprite):
^This class defines the bullets fired by aliens. These bullets fall downward, damage the player on collision, and create a small explosion effect. They remove themselves when they leave the screen.
class Explosion(pygame.sprite.Sprite):
^This class handles explosion animations. It loads a sequence of images, scales them based on the explosion size, and cycles through them frame by frame. When the animation finishes the explosion sprite deletes itself.
def create_aliens():
^This function generates a grid of aliens using the number of rows and columns defined at the top of the program. It positions them evenly across the screen and adds them to the alien sprite group.
Main Game Loop
^The loop runs at sixty frames per second. It draws the background, handles the countdown timer, updates all sprite groups, creates alien bullets at random intervals, checks for win or loss conditions, and displays messages such as GET READY, GAME OVER, or YOU WIN. It also listens for the quit event so the player can close the game.
Leave a Reply