Building a Simple Spaceship Game in Python with Pygame: A Fun Coding Adventure

Welcome to the exciting world of game development! In this tutorial, we’ll embark on a coding adventure to create a simple spaceship game using Python and the Pygame library. Whether you’re a beginner looking to enhance your programming skills or an experienced developer exploring game development, this step-by-step guide will walk you through the process of building an engaging and interactive game. Join us as we explore the fundamentals of Pygame, handle player input, and bring our game to life with spaceships, bullets, and meteors. Let’s dive in and turn code into entertainment!

Library

Before you start, make sure you have Pygame installed. If you don’t, you can install it using the following command:

pip install pygame

Code

import pygame
import sys
import random

# Initialize Pygame
pygame.init()

# Game settings
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Spaceship Game")

# Colors
black = (0, 0, 0)
white = (255, 255, 255)

# Spaceship
player_size = 50
player_x = width // 2 - player_size // 2
player_y = height - 2 * player_size
player_speed = 5

# Meteor
meteor_size = 50
meteor_speed = 5
meteor_frequency = 25
meteors = []

# Bullet
bullet_speed = 7
bullets = []

# Function to draw the spaceship
def draw_player(x, y):
    pygame.draw.rect(screen, white, [x, y, player_size, player_size])

# Function to draw the meteors
def draw_meteors(meteors):
    for meteor in meteors:
        pygame.draw.rect(screen, white, meteor)

# Function to draw the bullets
def draw_bullets(bullets):
    for bullet in bullets:
        pygame.draw.rect(screen, white, bullet)

# Main game loop
def game():
    global player_x, bullets, meteors

    clock = pygame.time.Clock()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            # Spaceship movement
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player_x -= player_speed
                elif event.key == pygame.K_RIGHT:
                    player_x += player_speed

                # Shoot
                elif event.key == pygame.K_SPACE:
                    bullet = pygame.Rect(player_x + player_size // 2 - 5, player_y, 10, 20)
                    bullets.append(bullet)

        # Bullet movement
        for bullet in bullets:
            bullet.y -= bullet_speed

        # Create random meteors
        if random.randint(1, meteor_frequency) == 1:
            meteor_x = random.randint(0, width - meteor_size)
            meteor_y = -meteor_size
            meteor = pygame.Rect(meteor_x, meteor_y, meteor_size, meteor_size)
            meteors.append(meteor)

        # Meteor movement
        for meteor in meteors:
            meteor.y += meteor_speed

        # Check collisions between bullets and meteors
        for bullet in bullets:
            for meteor in meteors:
                if bullet.colliderect(meteor):
                    bullets.remove(bullet)
                    meteors.remove(meteor)

        # Clear screen
        screen.fill(black)

        # Draw elements
        draw_player(player_x, player_y)
        draw_bullets(bullets)
        draw_meteors(meteors)

        # Update the screen
        pygame.display.flip()

        # Control the frames per second (FPS)
        clock.tick(30)

if __name__ == "__main__":
    game()

This is a very simple game where you control a spaceship with the left and right arrow keys and shoot with the space bar to destroy meteors. Remember that this is just a starting point, and you can expand and improve the game according to your preferences. You can share your code on our Discord.

Conclusion

Congratulations on completing your journey into game development with Python and Pygame! You’ve gained valuable insights into creating a basic spaceship game, from handling player input to managing game elements like bullets and meteors. As you continue to explore the vast realm of game development, remember that this is just the beginning. Feel free to tweak and expand upon the code, experiment with new features, and unleash your creativity to build even more captivating games. Keep coding, keep exploring, and most importantly, have fun on your coding adventures! If you have any questions or insights, share them in the comments below. Happy coding!