๐Ÿš€๐Ÿ‘พ Conquer the Galaxy: Learn Game Development by Building Space Invaders ๐ŸŒŸ๐ŸŽฎ (Part 15 of Game Dev Series)

ยท

7 min read

๐Ÿš€๐Ÿ‘พ Conquer the Galaxy: Learn Game Development by Building Space Invaders ๐ŸŒŸ๐ŸŽฎ (Part 15 of Game Dev Series)

Photo by NASA on Unsplash

Learning Game Development Through Building Space Invaders

So, you want to make your first foray into game development? And you're a fan of retro arcade games? Well, strap in because today we're going to embark on an interstellar adventure! By the end of this article, you'll have your own version of the classic arcade game, Space Invaders, up and running. Sounds exciting? Let's blast off!

1. Introduction

Space Invaders, an iconic arcade game released in 1978, set the benchmark for the shooting genre. It's a straightforward game where you control a spaceship and your mission is to destroy waves of aliens before they reach the bottom of the screen.

Before we proceed, make sure you have Python and Pygame installed on your system. If not, here's a quick reminder on how to install Pygame using pip:


pip install pygame

2. Breaking Down the Game

In Space Invaders, we have three main entities:

  1. The Player: A spaceship controlled by the player, capable of moving left or right along the bottom of the screen and shooting lasers.

  2. The Invaders: Rows of aliens moving horizontally across the screen, dropping down a row each time they hit the screen's edge.

  3. Lasers: Projectiles fired by both the player and invaders.

With these basic elements, we can start structuring our game.

3. Setting Up the Screen

First off, let's set up our game window:


import pygame

pygame.init()

# Set up display dimensions
WIDTH, HEIGHT = 800, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))

# Game Loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

This gives us an 800x600 window, which will close properly when we click the 'x' in the corner.

4. Creating the Player

We'll represent our player as a class, with variables for its position, dimensions, and velocity:


class Player:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5

We can then draw the player onto the screen in our game loop:


def draw_window(player):
    win.fill((0,0,0))  # Fill the screen with black
    pygame.draw.rect(win, (255, 0, 0), (player.x, player.y, player.width, player.height))  # Draw the player
    pygame.display.update()  # Update the display

player = Player(WIDTH/2, HEIGHT-60, 50, 50)

# Game Loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

    draw_window(player)

We now have a red square representing the player.

5. Adding Movement

Next, we'll make our player spaceship move. Add the following code to the game loop:


keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    player.x -= player.vel
if keys[pygame.K_RIGHT]:
    player.x += player.vel

This will move the player left or right when the respective keys are pressed.

That's all we have space for in this response, but the process continues with building the Invaders, their movement, and implementing the shooting mechanism. Make sure to keep checking the Pygame documentation if you're unsure about anything and, most importantly, have fun!

we'll be exploring the Invaders' implementation, their movement, shooting lasers, and finalizing our game. Let's keep building our game. We've made a great start!

6. Building the Invaders

Just like we created a Player class, let's create a similar Invader class:


class Invader:
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 1

We can populate our screen with multiple Invaders using a list:


invaders = [Invader(i*100, j*60, 50, 50) for i in range(8) for j in range(5)]

This will create 5 rows of invaders, each with 8 invaders.

7. Drawing the Invaders

Modify the draw_window() function to draw the invaders on the screen:


def draw_window(player, invaders):
    win.fill((0,0,0))  # Fill the screen with black
    pygame.draw.rect(win, (255, 0, 0), (player.x, player.y, player.width, player.height))  # Draw the player

    for invader in invaders:
        pygame.draw.rect(win, (0, 255, 0), (invader.x, invader.y, invader.width, invader.height))  # Draw each invader

    pygame.display.update()  # Update the display

8. Invaders Movement

Invaders should move sideways, and upon touching the screen edge, they should drop down and change direction. Let's add this in our game loop:


for invader in invaders:
    invader.x += invader.vel

    # If an invader hits the edge of the screen, change direction and drop down a row
    if invader.x + invader.width > WIDTH or invader.x < 0:
        invader.vel *= -1
        for i in invaders:
            i.y += 30

9. Shooting Lasers

We need a way for our player and invaders to shoot lasers. Let's define a Laser class:


class Laser:
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.vel = 5 * direction
        self.color = (255,255,255)

The direction variable will be -1 for lasers shot by the player (moving up) and 1 for lasers shot by the invaders (moving down).

To shoot a laser, add the following code to the game loop:


keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
    playerLasers.append(Laser(player.x, player.y, -1))

10. Drawing Lasers

Modify the draw_window() function to draw lasers on the screen:


def draw_window(player, invaders, playerLasers):
    # Previous code...

    for laser in playerLasers:
        pygame.draw.rect(win, laser.color, (laser.x, laser.y, 5, 10))  # Draw each laser

    pygame.display.update()  # Update the display

We are nearing the completion of our Space Invaders game! In the next step, we'll deal with the collision detection and ending the game. So, hang in there, we're almost done!

11. Detecting Collisions

Now we need to determine when a laser hit an invader. For simplicity, we will use rectangle collision detection provided by Pygame. Add the following in your game loop:


for laser in playerLasers:
    for invader in invaders:
        if pygame.Rect(laser.x, laser.y, 5, 10).colliderect(pygame.Rect(invader.x, invader.y, invader.width, invader.height)):
            playerLasers.remove(laser)
            invaders.remove(invader)
            break

Here we iterate through each laser and invader and create a pygame.Rect object for them. The colliderect() function checks if these rectangles overlap (i.e., a hit occurred).

12. Ending the Game

The game should end when an invader reaches the player's level. Add this code to your game loop:


for invader in invaders:
    if invader.y + invader.height > HEIGHT:
        run = False

13. Completing the Game

We have covered the basics. You can now run the game, move the player left and right, shoot lasers, destroy invaders, and the game ends when invaders reach the player's level.

However, there are plenty of improvements you could add. For instance, invaders could shoot lasers back, you could add levels, scores, different types of invaders, power-ups, and much more. The possibilities are limitless, and this is the real joy of game development.

Conclusion

The art of game development can seem intimidating initially, but breaking it down into manageable chunks makes it more approachable. The classic game, Space Invaders, is a perfect starting point for beginner game developers as it covers essential game development aspects such as player input, game objects, collision detection, and game-ending conditions.

Building your own Space Invaders game is not only a great way to learn Python and game development, but it's also a lot of fun. Hopefully, this tutorial has sparked your interest in game development, and you're now equipped with the basic knowledge to explore more complex game ideas. Happy gaming!

FAQs

1. What is Pygame?

Pygame is a cross-platform set of Python libraries designed for creating video games. It includes computer graphics and sound libraries.

2. What is collision detection?

Collision detection in video games is the computational problem of detecting the intersection of two or more objects. In the context of our Space Invaders game, we are checking for the intersection of the player's lasers and the invaders.

3. How can I add more features to this game?

There are limitless possibilities. You can add different types of invaders, power-ups for the player, introduce levels, add a scoring system, or even multiplayer support.

4. What other games can I build as a beginner?

After Space Invaders, you might want to try building other classic games like Pong, Breakout, or Tetris. These games will introduce new challenges and aspects of game development.

5. How can I make my game run at a consistent speed on all computers?

This can be achieved by implementing a game clock to regulate the game's speed. Pygame provides the pygame.time.Clock() class that can be used to control the game's framerate.

Did you find this article valuable?

Support Learn!Things by becoming a sponsor. Any amount is appreciated!

ย