Building Space Invaders with Python and Pygame in Replit

code space invaders game in JS

SHARE WITH FRIENDS >

Hello there! In this tutorial, we’ll learn how to build a simple Space Invaders game using Python and the Pygame library. We’ll be using Replit, an online IDE, to write and run our code. By the end of this tutorial, you’ll have a fun game that you can play and share with your friends.

Prerequisites: This tutorial assumes that you have some experience with Python programming. If you’re new to Python, you might want to check out a beginner tutorial first.

Setting up Replit:

  1. To get started, open your web browser and go to https://replit.com/.
  2. Click on the “Sign Up” button in the top right corner of the page.
  3. Fill in the required information to create a new account, or sign up using your Google, GitHub, or Facebook account.
  4. After signing up, you’ll be taken to your Replit dashboard. Click on the “New Repl” button to create a new project.
  5. In the “Create a Repl” window, select “Python” as the language, and give your project a name (e.g., “SpaceInvaders”). Then, click on “Create Repl” to set up your new Python environment.

Installing Pygame in Replit:

  1. In the Replit environment, click on the “Packages” icon on the left side of the screen.
  2. In the “Search packages” field, type “pygame” and press Enter.
  3. Click on the “pygame” package, and then click on the “Add” button to install it.

Now we’re ready to start building our Space Invaders game!

Step 1: Importing Libraries and Initializing Pygame First, we need to import the required libraries and initialize Pygame:

import pygame
from pygame.locals import *
import sys

pygame.init()

Step 2: Setting up the Game Window Next, let’s set up the game window with a title, background color, and size:

# Constants for screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Space Invaders')

# Set the background color
bg_color = (0, 0, 0) # Black

Step 3: Creating the Player Class Now, we’ll create a player class to represent our spaceship:

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load("spaceship.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5

    def move_left(self):
        self.rect.x -= self.speed
        if self.rect.x < 0:
            self.rect.x = 0

    def move_right(self):
        self.rect.x += self.speed
        if self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.rect.x = SCREEN_WIDTH - self.rect.width

Remember to upload a “spaceship.png” image to Replit for the player spaceship. You can find free images on websites like https://www.kenney.nl/assets or draw your own using a tool like https://www.piskelapp.com/.

Step 4: Creating the Enemy Class We’ll also create an enemy class to represent the alien invaders:

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load("alien.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 2

    def update(self):
        self.rect.x += self.speed
        if self.rect.x < 0 or self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.speed = -self.speed
            self.rect.y += self.rect.height

Again, remember to upload an “alien.png” image for the enemy sprite.

Step 5: Creating the Bullet Class We’ll need a bullet class for the player to shoot at the enemies:

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((4, 10))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 10

    def update(self):
        self.rect.y -= self.speed

Step 6: Creating Game Objects and Groups Now we’ll create instances of the player, enemies, and bullet groups:

player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100)

enemies = pygame.sprite.Group()
for i in range(5):
    for j in range(5):
        enemy = Enemy(50 + i * 100, 50 + j * 70)
        enemies.add(enemy)

bullets = pygame.sprite.Group()

Step 7: The Main Game Loop Finally, let’s create the main game loop to handle input, updates, and drawing:

clock = pygame.time.Clock()

while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_SPACE:
                bullet = Bullet(player.rect.centerx, player.rect.y)
                bullets.add(bullet)

    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        player.move_left()
    if keys[K_RIGHT]:
        player.move_right()

    # Update game objects
    enemies.update()
    bullets.update()

    # Check for collisions
    pygame.sprite.groupcollide(bullets, enemies, True, True)

    # Draw game objects
    screen.fill(bg_color)
    screen.blit(player.image, player.rect)
    enemies.draw(screen)
    bullets.draw(screen)

    pygame.display.flip()
    clock.tick(60)

That’s it! You should now have a simple Space Invaders game. Of course, there is room for improvement, such as adding sound effects, multiple levels, and a scoring system. Feel free to experiment and make the game your own.

I hope this tutorial has been helpful for you. Enjoy your new Space Invaders game, and happy coding!

Here is the complete code:

import pygame
from pygame.locals import *
import sys

pygame.init()

# Constants for screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# Create the game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Space Invaders')

# Set the background color
bg_color = (0, 0, 0) # Black

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load("spaceship.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 5

    def move_left(self):
        self.rect.x -= self.speed
        if self.rect.x < 0:
            self.rect.x = 0

    def move_right(self):
        self.rect.x += self.speed
        if self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.rect.x = SCREEN_WIDTH - self.rect.width

class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load("alien.png")
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 2

    def update(self):
        self.rect.x += self.speed
        if self.rect.x < 0 or self.rect.x > SCREEN_WIDTH - self.rect.width:
            self.speed = -self.speed
            self.rect.y += self.rect.height

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((4, 10))
        self.image.fill((255, 255, 255))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = 10

    def update(self):
        self.rect.y -= self.speed

player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100)

enemies = pygame.sprite.Group()
for i in range(5):
    for j in range(5):
        enemy = Enemy(50 + i * 100, 50 + j * 70)
        enemies.add(enemy)

bullets = pygame.sprite.Group()

clock = pygame.time.Clock()

while True:
    # Handle events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_SPACE:
                bullet = Bullet(player.rect.centerx, player.rect.y)
                bullets.add(bullet)

    keys = pygame.key.get_pressed()
    if keys[K_LEFT]:
        player.move_left()
    if keys[K_RIGHT]:
        player.move_right()

    # Update game objects
    enemies.update()
    bullets.update()

    # Check for collisions
    pygame.sprite.groupcollide(bullets, enemies, True, True)

    # Draw game objects
    screen.fill(bg_color)
    screen.blit(player.image, player.rect)
    enemies.draw(screen)
    bullets.draw(screen)

    pygame.display.flip()
    clock.tick(60)

SHARE WITH FRIENDS >

Coding Torunament Ideas

Hackathon, Lesson Plans, Tournament

23 Apr 2024

3rd grade Coding Tournament Ideas

IDE options

Education

16 Apr 2024

Ready to Boost Your Teen’s Future with Coding?

Best dev enviroments for learning to code

Education

16 Apr 2024

Top 5 Epic Coding Environments for Teens

review kids coding sites

Education, Learn to Code

16 Apr 2024

Top Learn-to-Code Online Sites and Tools for Kids

Convert USD to other currency program

Advanced Placement, Java, Tutorial

4 Apr 2024

Object-Oriented Programming in Java – AP CS A

learn to use replit IDE

Advanced Placement, Java, Tutorial

4 Apr 2024

Exploring Concurrency in Java – AP Exam

Minecraft Mods in Java

Minecraft

4 Apr 2024

Getting Started with Minecraft Forge

Lesson on functions in computer science programming

Tutorial

4 Apr 2024

Preparing to Teach Coding for the First Time