Space Invaders Game Development: Free Python Course Online Module 3

88 / 100
Reading Time: 9 minutes

Welcome to an exciting journey into the world of game development using the powerful Pygame library. In this article, we will dive deep into the process of creating a Space Invaders game from scratch. By the end of this adventure, you’ll have a solid understanding of game development basics, interactive game windows, animations, collision detection, scoring systems, and more. Whether you’re a beginner or just looking to expand your skills, get ready to embark on a captivating coding expedition!

Thank you for reading this post, don't forget to share! website average bounce rate Buy traffic for your website

 

DOWNLOAD THE CODE AND REQUIRED IMAGE FILES HERE
game development

Understanding the Fundamentals of Game Development

Before we jump into the coding realm, let’s grasp the fundamental components of game development. A game is a complex interplay of graphics, audio, physics, and user interaction. Designing a game involves meticulous planning, creative visualization, and attention to detail. As you set out on your game development journey, keep in mind that every decision you make will shape the player’s experience.

Creating Interactive Game Windows and Managing Events

To kick off our Space Invaders project, let’s start by setting up an interactive game window using Pygame. The game window serves as the canvas on which our game will come to life. By managing events such as user keyboard input and mouse clicks, we can create responsive and engaging gameplay.

Importing Libraries

import pygame
import random
import sys

In this part of the code, we import three Python libraries: pygame for creating the game, random for generating random numbers, and sys for system-level operations.

Initializing Pygame

pygame.init()

This line initializes the Pygame library, preparing it for use in creating a game.

Setting Constants

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
PLAYER_SPEED = 5
ENEMY_INITIAL_SPEED = 2
ENEMY_SPEED_INCREMENT = 0.1
NUM_ENEMIES = 5

Here, we define several constants that will be used throughout the game. These constants include screen dimensions, player speed, initial enemy speed, speed increment for enemies, and the initial number of enemies.

Defining Colors

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

These lines define color constants using RGB values, which will be used for drawing various game elements.

Creating the Game Window

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Space Invaders")

Here, we create the game window with the specified dimensions (800×600 pixels) and set the window’s title to “Space Invaders.”

Player Initialization

player_img = pygame.image.load("player.png")
player_x = SCREEN_WIDTH // 2 - 32
player_y = SCREEN_HEIGHT - 64
player_x_change = 0

This snippet initializes the player character. It loads the player’s image, sets its initial position, and initializes the horizontal movement (player_x_change).

Enemy Initialization

enemy_imgs = [pygame.image.load("enemy.png") for _ in range(NUM_ENEMIES)]
enemy_x = [random.randint(0, SCREEN_WIDTH - 64) for _ in range(NUM_ENEMIES)]
enemy_y = [random.randint(50, 150) for _ in range(NUM_ENEMIES)]
enemy_x_change = [ENEMY_INITIAL_SPEED] * NUM_ENEMIES
enemy_y_change = [40] * NUM_ENEMIES

This code initializes multiple enemies using lists. It loads enemy images, sets random initial positions, and initializes their movements.

Bullet Initialization

bullet_img = pygame.image.load("bullet.png")
bullet_x = 0
bullet_y = SCREEN_HEIGHT - 64
bullet_y_change = 10
bullet_state = "ready"

This snippet initializes the bullet that the player can shoot. It loads the bullet image, sets its initial position below the player, and manages its movement and state.

Score and Fonts

score = 0
font = pygame.font.Font("freesansbold.ttf", 32)
text_x = 10
text_y = 10

These lines initialize the score and define a font for displaying the score on the game screen.

Game Over Font

game_over_font = pygame.font.Font("freesansbold.ttf", 64)

This line defines a larger font for displaying the “GAME OVER” message when the game ends.

Player, Enemy, and Bullet Functions

def player(x, y):
    screen.blit(player_img, (x, y))

def enemy(x, y, i):
    screen.blit(enemy_imgs[i], (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bullet_img, (x + 16, y + 10))

These are functions used to draw the player, enemies, and bullets on the game screen.

Collision Detection Function

def is_collision(enemy_x, enemy_y, bullet_x, bullet_y):
    distance = ((enemy_x - bullet_x) ** 2 + (enemy_y - bullet_y) ** 2) ** 0.5
    if distance < 27:
        return True
    return False

This function checks for collisions between the bullet and an enemy using the Pythagorean theorem to calculate the distance between their centers.

Game Loop

running = True
level = 1

while running:
    # ... (Game logic and event handling)
    pygame.display.update()

This part initiates the game loop that continuously runs as long as running is True. The game logic and event handling occur within this loop.

Event Handling

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    # ... (Key presses and game events)

This part of the game loop handles various events, such as quitting the game or processing key presses for player movement and shooting.

Player Movement

player_x += player_x_change
if player_x < 0:
    player_x = 0
elif player_x > SCREEN_WIDTH - 64:
    player_x = SCREEN_WIDTH - 64

These lines update the player’s position based on the player_x_change value, which is controlled by player input. It also ensures that the player does not move off the screen.

Enemy Movement and Collision Detection

for i in range(len(enemy_imgs)):
    enemy_x[i] += enemy_x_change[i]
    if enemy_x[i] < 0:
        # ... (Enemy movement logic when reaching left edge)
    elif enemy_x[i] > SCREEN_WIDTH - 64:
        # ... (Enemy movement logic when reaching right edge)
    collision = is_collision(enemy_x[i], enemy_y[i], bullet_x, bullet_y)
    if collision:
        # ... (Handling collision with enemy)
    enemy(enemy_x[i], enemy_y[i], i)

This section updates the position of multiple enemies, handles their movement when they reach the screen edges, checks for collisions with bullets, and draws the enemies.

Bullet Movement and Shooting

if bullet_y <= 0:
    # ... (Resetting the bullet when it reaches the top)
if bullet_state == "fire":
    # ... (Moving and drawing the bullet)

These lines manage the bullet’s movement, including resetting it when it reaches the top of the screen and moving/drawing it when it’s fired by the player.

Player and Score Display

player(player_x, player_y)
score_text = font.render("Score: " + str(score), True, GREEN)
screen.blit(score_text, (text_x, text_y))

This part of the game loop draws the player character and displays the player’s score on the screen.

Game Over Condition

for i in range(len(enemy_imgs)):
    if enemy_y[i] > SCREEN_HEIGHT - 64:
        # ... (Displaying "GAME OVER" and exiting the game)

This section checks if any enemy has reached the bottom of the screen, indicating a game over condition. It then displays the “GAME OVER” message and exits the game if needed.

Level Up Logic

if score >= level * 10:
    # ... (Increasing game level, enemy speed, and adding more enemies)

This code checks if the player’s score has reached a threshold to level up the game. If so, it increases the level, enemy speed, and adds more enemies to make the game progressively challenging.

Quitting the Game

pygame.quit()

Finally, this line of code is used to cleanly quit and close the Pygame window when the game loop exits.

These explanations provide an understanding of each part of the code without using numbers or explicit titles for code snippets.

Final Code

import pygame
import random
import sys

# Initialize Pygame
pygame.init()

# Constants
SCREEN_WIDTH = 630
SCREEN_HEIGHT = 630
PLAYER_SPEED = 5
ENEMY_INITIAL_SPEED = 0.1
ENEMY_SPEED_INCREMENT = 0.01  # Increase in enemy speed per level
NUM_ENEMIES = 5  # Number of enemies to start with

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

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

# Player
player_img = pygame.image.load("player.png")
player_x = SCREEN_WIDTH // 2 - 32
player_y = SCREEN_HEIGHT - 64
player_x_change = 0

# Enemies
enemy_imgs = [pygame.image.load("enemy.png") for _ in range(NUM_ENEMIES)]
enemy_x = [random.randint(0, SCREEN_WIDTH - 64) for _ in range(NUM_ENEMIES)]
enemy_y = [random.randint(50, 150) for _ in range(NUM_ENEMIES)]
enemy_x_change = [ENEMY_INITIAL_SPEED] * NUM_ENEMIES
enemy_y_change = [40] * NUM_ENEMIES

# Bullet
bullet_img = pygame.image.load("bullet.png")
bullet_x = 0
bullet_y = SCREEN_HEIGHT - 64
bullet_y_change = 10
bullet_state = "ready"

# Score
score = 0
font = pygame.font.Font("freesansbold.ttf", 32)
text_x = 10
text_y = 10

# Game Over
game_over_font = pygame.font.Font("freesansbold.ttf", 64)

# Functions
def player(x, y):
    screen.blit(player_img, (x, y))

def enemy(x, y, i):
    screen.blit(enemy_imgs[i], (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bullet_img, (x + 16, y + 10))

def is_collision(enemy_x, enemy_y, bullet_x, bullet_y):
    distance = ((enemy_x - bullet_x) ** 2 + (enemy_y - bullet_y) ** 2) ** 0.5
    if distance < 27:
        return True
    return False

# Game Loop
running = True
level = 1  # Initialize game level

while running:
    screen.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player_x_change = -PLAYER_SPEED
            if event.key == pygame.K_RIGHT:
                player_x_change = PLAYER_SPEED
            if event.key == pygame.K_SPACE and bullet_state == "ready":
                bullet_x = player_x
                fire_bullet(bullet_x, bullet_y)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                player_x_change = 0

    player_x += player_x_change
    if player_x < 0:
        player_x = 0
    elif player_x > SCREEN_WIDTH - 64:
        player_x = SCREEN_WIDTH - 64

    for i in range(len(enemy_imgs)):
        enemy_x[i] += enemy_x_change[i]
        if enemy_x[i] < 0:
            enemy_x_change[i] = ENEMY_INITIAL_SPEED + (level - 1) * ENEMY_SPEED_INCREMENT
            enemy_y[i] += enemy_y_change[i]
        elif enemy_x[i] > SCREEN_WIDTH - 64:
            enemy_x_change[i] = -ENEMY_INITIAL_SPEED - (level - 1) * ENEMY_SPEED_INCREMENT
            enemy_y[i] += enemy_y_change[i]

        collision = is_collision(enemy_x[i], enemy_y[i], bullet_x, bullet_y)
        if collision:
            bullet_y = SCREEN_HEIGHT - 64
            bullet_state = "ready"
            score += 1
            enemy_x[i] = random.randint(0, SCREEN_WIDTH - 64)
            enemy_y[i] = random.randint(50, 150)

        enemy(enemy_x[i], enemy_y[i], i)

    if bullet_y <= 0:
        bullet_y = SCREEN_HEIGHT - 64
        bullet_state = "ready"

    if bullet_state == "fire":
        fire_bullet(bullet_x, bullet_y)
        bullet_y -= bullet_y_change

    player(player_x, player_y)

    # Display Score
    score_text = font.render("Score: " + str(score), True, GREEN)
    screen.blit(score_text, (text_x, text_y))

    # Check for game over
    for i in range(len(enemy_imgs)):
        if enemy_y[i] > SCREEN_HEIGHT - 64:
            game_over_text = game_over_font.render("GAME OVER", True, GREEN)
            screen.blit(game_over_text, (SCREEN_WIDTH // 2 - 200, SCREEN_HEIGHT // 2 - 32))
            pygame.display.update()
            pygame.time.delay(2000)  # Delay for 2 seconds
            sys.exit()  # Exit the game

    # Check for level up
    if score >= level * 10:
        level += 1
        # Increase enemy speed and add more enemies
        for i in range(len(enemy_imgs)):
            enemy_x_change[i] += ENEMY_SPEED_INCREMENT
        NUM_ENEMIES += 1
        enemy_imgs.append(pygame.image.load("enemy.png"))
        enemy_x.append(random.randint(0, SCREEN_WIDTH - 64))
        enemy_y.append(random.randint(50, 150))
        enemy_x_change.append(ENEMY_INITIAL_SPEED + (level - 1) * ENEMY_SPEED_INCREMENT)
        enemy_y_change.append(40)

    pygame.display.update()

# Quit the game
pygame.quit()

Encouraging Hands-On Learning

Don’t just read about it—try it out for yourself! We’ve provided an online compiler where you can experiment with the code snippets from this article. Go ahead, tinker with the code, and watch your Space Invaders game come to life on your screen.

Frequently Asked Questions (FAQ)

What is Pygame?

Pygame is a popular Python library used for game development, offering tools and functionalities to create games with ease.

How do I handle user input in Pygame?

Pygame provides functions to capture keyboard and mouse input events, allowing you to create responsive gameplay.

Why is collision detection important in games?

Collision detection ensures that objects interact realistically, enabling accurate gameplay and dynamic interactions.

Can I add animations to my game using Pygame?

Absolutely! Pygame offers a sprite system that simplifies animation creation and rendering.

How do I integrate sound effects into my game?

Pygame provides functions to load and play sound effects, enhancing the gaming experience with audio cues.

What are game mechanics?

Game mechanics are rules and interactions that govern gameplay, including movement, actions, and interactions between entities.

How can I keep track of player scores in Pygame?

You can implement a scoring system using variables to track scores and display them on the game screen.

Can I customize the appearance of game windows?

Yes, you can customize game windows by setting dimensions, titles, and even adding background images or colors.

Is it possible to create complex games using Pygame?

Absolutely! Pygame provides a versatile set of tools that enable developers to create games of varying complexity.

Where can I find resources to learn more about Pygame?

You can explore the official Pygame documentation and various online tutorials to deepen your knowledge.

Conclusion

Congratulations, you’ve embarked on an exciting journey into the realm of game development with Pygame! Throughout this article, we’ve covered the basics of game development, interactive windows, animations, collision detection, scoring systems, and more. Remember, practice makes perfect, so keep experimenting, learning, and crafting your own game masterpieces. Whether you’re building a Space Invaders game or venturing into new game ideas, the skills you’ve acquired will be your guide to success.

Python Learning Resources

  1. Python.org’s Official Documentation – https://docs.python.org/ Python’s official documentation is a highly authoritative source. It provides in-depth information about the language, libraries, and coding practices. This is a go-to resource for both beginners and experienced developers.
  2. Coursera’s Python for Everybody Course – https://www.coursera.org/specializations/python Coursera hosts this popular course taught by Dr. Charles Severance. It covers Python programming from the ground up and is offered by the University of Michigan. The association with a reputable institution adds to its credibility.
  3. Real Python’s Tutorials and Articles – https://realpython.com/ Real Python is known for its high-quality tutorials and articles that cater to different skill levels. The platform is respected within the Python community for its accuracy and practical insights.
  4. Stack Overflow’s Python Tag – https://stackoverflow.com/questions/tagged/python Stack Overflow is a well-known platform for programming-related queries. Linking to the Python tag page can provide readers with access to a vast collection of real-world coding problems and solutions.
  5. Python Weekly Newsletter – https://www.pythonweekly.com/ The Python Weekly newsletter delivers curated content about Python programming, including articles, news, tutorials, and libraries. Subscribing to such newsletters is a common practice among developers looking for trustworthy updates.

Python projects and tools

  1. Free Python Compiler: Compile your Python code hassle-free with our online tool.
  2. Comprehensive Python Project List: A one-stop collection of diverse Python projects.
  3. Python Practice Ideas: Get inspired with 600+ programming ideas for honing your skills.
  4. Python Projects for Game Development: Dive into game development and unleash your creativity.
  5. Python Projects for IoT: Explore the exciting world of the Internet of Things through Python.
  6. Python for Artificial Intelligence: Discover how Python powers AI with 300+ projects.
  7. Python for Data Science: Harness Python’s potential for data analysis and visualization.
  8. Python for Web Development: Learn how Python is used to create dynamic web applications.
  9. Python Practice Platforms and Communities: Engage with fellow learners and practice your skills in real-world scenarios.
  10. Python Projects for All Levels: From beginner to advanced, explore projects tailored for every skill level.
  11. Python for Commerce Students: Discover how Python can empower students in the field of commerce.

Dr. Honey Durgaprasad Tiwari, both the CTO at INKOR Technologies Private Limited, India, and a dedicated academic researcher, brings a wealth of expertise. With a Post-Doctoral stint at Sungkyunkwan University, Ph.D. in Electronic, Information and Communication Engineering from Konkuk University, Seoul, South Korea, and M.Tech in Embedded Electronic Systems from VNIT Nagpur, his research legacy spans wireless power transfer, medical imaging, and FPGA innovation. Notably, he has authored 40+ SCI papers, conference contributions, and patents, leaving an indelible mark on these fields. Holding pivotal Academic Administrative roles, including Head of Department and IQAC Coordinator, he passionately channels his insights into concise and impactful blogs, enriching the tech discourse. 🚀🔬📚

1 thought on “Space Invaders Game Development: Free Python Course Online Module 3”

Leave a Comment

Space Invaders Game Development: Free Python Cours…

by Dr. Honey Durgaprasad Tiwari time to read: 10 min
1