Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the Game Window
- Drawing the Player
- Moving the Player
- Drawing the Enemies
- Moving the Enemies
- Shooting Bullets
- Detecting Collisions
- Game Over
- Conclusion
Introduction
In this tutorial, we will create a simple Space Invaders game using Python. Space Invaders is a classic arcade game where the player controls a spaceship and tries to shoot down a fleet of alien invaders. By the end of this tutorial, you will have a working Space Invaders game that you can play and customize.
Prerequisites
Before starting this tutorial, you should have a basic understanding of Python programming. Familiarity with concepts like variables, functions, loops, and conditional statements will be helpful. Additionally, you should have Python 3.x installed on your system.
Setup
To create our Space Invaders game, we will be using the Pygame library, which provides us with tools to easily build games in Python. Start by installing Pygame using pip:
pip install pygame
Once Pygame is installed, we can begin building our game.
Creating the Game Window
The first step in creating our Space Invaders game is to set up the game window. We will be using Pygame’s pygame.display
module to create and manage the game window. Open a new Python file and import the necessary modules:
python
import pygame
from pygame.locals import *
Next, we need to initialize Pygame and create the game window:
python
pygame.init()
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Space Invaders")
In the code above, we initialize Pygame using pygame.init()
and set the dimensions of the game window. We then create the game window using pygame.display.set_mode()
and set the window caption to “Space Invaders” using pygame.display.set_caption()
.
Now, let’s add a main game loop to keep the game window open and responsive: ```python is_running = True
while is_running:
for event in pygame.event.get():
if event.type == QUIT:
is_running = False
pygame.quit()
``` The code above creates a Boolean variable `is_running` that controls whether the game is running or not. Inside the main game loop, we wait for the `QUIT` event, which is triggered when the user closes the game window. When this event occurs, we set `is_running` to False, exiting the game loop.
Drawing the Player
Now that we have our game window set up, let’s draw the player’s spaceship on the screen. The player will control this spaceship throughout the game. Add the following code inside the main game loop: ```python player_color = (255, 255, 255) player_width = 50 player_height = 50 player_x = (window_width - player_width) // 2 player_y = window_height - player_height - 10
pygame.draw.rect(window, player_color, (player_x, player_y, player_width, player_height))
``` In the code above, we define the color, width, and height of the player's spaceship. We calculate the starting position of the spaceship based on the window dimensions. Finally, we use `pygame.draw.rect()` to draw a rectangle representing the player's spaceship on the game window.
Moving the Player
To allow the player to move their spaceship, we need to handle keyboard input. Add the following code inside the main game loop, before the drawing code: ```python keys = pygame.key.get_pressed()
if keys[K_LEFT]:
player_x -= 5
if keys[K_RIGHT]:
player_x += 5
``` The code above uses `pygame.key.get_pressed()` to get a list of all currently pressed keys. We check if the left or right arrow keys are pressed and modify the `player_x` position accordingly. By decreasing or increasing `player_x`, we move the spaceship left or right on the game window.
Update the drawing code to reflect the changes in the player’s position:
python
pygame.draw.rect(window, player_color, (player_x, player_y, player_width, player_height))
With these changes, the player will now be able to move their spaceship left and right using the arrow keys.
Drawing the Enemies
Now it’s time to add some enemies for the player to shoot down. We will create a row of enemies at the top of the game window. Add the following code after the drawing code for the player: ```python enemy_color = (255, 0, 0) enemy_width = 30 enemy_height = 30 enemy_x = (window_width - enemy_width) // 2 enemy_y = 50
pygame.draw.rect(window, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
``` In the code above, we define the color, width, and height of the enemies. We calculate the starting position of the enemy row based on the window dimensions. Finally, we use `pygame.draw.rect()` to draw a rectangle representing an enemy on the game window.
Moving the Enemies
To make the enemies move, we can update their position in each iteration of the game loop. Add the following code inside the main game loop, after the drawing code for the player: ```python enemy_x += 2
if enemy_x > window_width - enemy_width:
enemy_x = 0
pygame.draw.rect(window, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
``` In the code above, we increase the `enemy_x` position by 2 pixels in each iteration of the game loop. If the enemy reaches the right edge of the game window, we reset its position to the left side.
Update the drawing code for the player and the enemies to reflect the changes:
python
pygame.draw.rect(window, player_color, (player_x, player_y, player_width, player_height))
pygame.draw.rect(window, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
With these changes, the enemies will move horizontally across the game window.
Shooting Bullets
Let’s add the ability for the player to shoot bullets to destroy the enemies. We will use a list to keep track of the bullets on the screen. Add the following code before the game loop: ```python bullet_color = (0, 255, 0) bullet_width = 5 bullet_height = 10 bullet_x = player_x + player_width // 2 - bullet_width // 2 bullet_y = player_y - bullet_height bullets = []
def draw_bullets():
for bullet in bullets:
pygame.draw.rect(window, bullet_color, (bullet[0], bullet[1], bullet_width, bullet_height))
def move_bullets():
for bullet in bullets:
bullet[1] -= 5
bullets[:] = [bullet for bullet in bullets if bullet[1] >= 0]
def shoot_bullet():
bullets.append([bullet_x, bullet_y])
while is_running:
# ...
draw_bullets()
move_bullets()
# ...
``` In the code above, we define the color, width, and height of the bullets. We calculate the starting position of the bullets based on the player's spaceship. We also create an empty list called `bullets` to store the bullets on the screen.
We define three functions:
draw_bullets()
iterates over thebullets
list and draws each bullet on the game window.move_bullets()
iterates over thebullets
list and moves each bullet upwards.shoot_bullet()
adds a new bullet to thebullets
list.
Inside the main game loop, we call draw_bullets()
and move_bullets()
to update the bullets on the screen.
To allow the player to shoot bullets, add the following code inside the main game loop, before the drawing code: ```python keys = pygame.key.get_pressed()
if keys[K_SPACE]:
shoot_bullet()
``` The code above checks if the space key is pressed and calls the `shoot_bullet()` function when it is. This will add a new bullet to the `bullets` list.
Update the drawing code for the player, enemies, and bullets to reflect the changes:
python
pygame.draw.rect(window, player_color, (player_x, player_y, player_width, player_height))
pygame.draw.rect(window, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
draw_bullets()
With these changes, the player will now be able to shoot bullets by pressing the space key.
Detecting Collisions
Now that we have bullets and enemies moving on the screen, we need to detect when they collide. Add the following code inside the main game loop, after move_bullets()
and before the drawing code:
```python
def detect_collisions():
for bullet in bullets:
if enemy_x < bullet[0] + bullet_width < enemy_x + enemy_width and enemy_y < bullet[1] < enemy_y + enemy_height:
bullets.remove(bullet)
detect_collisions()
``` In the code above, we define a function `detect_collisions()` that checks if any bullet has collided with an enemy. If a collision is detected, we remove the bullet from the `bullets` list.
The detect_collisions()
function is called inside the main game loop to check for collisions in each iteration.
Update the drawing code for the player, enemies, and bullets to reflect the changes:
python
pygame.draw.rect(window, player_color, (player_x, player_y, player_width, player_height))
pygame.draw.rect(window, enemy_color, (enemy_x, enemy_y, enemy_width, enemy_height))
draw_bullets()
With these changes, bullets that hit the enemies will be removed from the screen.
Game Over
To add a game over condition, we will check if any enemy has reached the player’s spaceship. Add the following code inside the main game loop, after the detection of collisions:
python
if enemy_y + enemy_height >= player_y:
is_running = False
In the code above, we check if the enemy has reached the player’s spaceship by comparing their positions. If a collision is detected, we set is_running
to False, ending the game.
Finally, outside the game loop, add the following code to display a game over message:
python
font = pygame.font.Font(None, 36)
game_over_text = font.render("Game Over", True, (255, 255, 255))
window.blit(game_over_text, (window_width // 2 - game_over_text.get_width() // 2, window_height // 2 - game_over_text.get_height() // 2))
pygame.display.flip()
The code above creates a font object and renders the “Game Over” message. We then center the message on the game window using get_width()
and get_height()
.
Update the main game loop to include this code snippet: ```python while is_running: # …
detect_collisions()
if enemy_y + enemy_height >= player_y:
is_running = False
# ...
# Game over message
font = pygame.font.Font(None, 36)
game_over_text = font.render("Game Over", True, (255, 255, 255))
window.blit(game_over_text, (window_width // 2 - game_over_text.get_width() // 2, window_height // 2 - game_over_text.get_height() // 2))
pygame.display.flip()
``` With these changes, the game will end and display a "Game Over" message when an enemy reaches the player's spaceship.
Conclusion
Congratulations! You have successfully created a simple Space Invaders game with Python. Throughout this tutorial, you learned how to set up the game window, draw and move game elements, handle keyboard input, detect collisions, and add a game over condition. You can use this game as a starting point for your own game development projects or further customize it by adding more features like multiple levels, sound effects, and power-ups.