Space invaders game in python – Part 1

Written by

In this tutorial, we will create a Space Invaders game in Python 3 with PyGame.

Virtual environment

To start building our space invaders game in Python, we create a new project, as well as a virtual environment and a folder that will contain the game’s source code. 

A virtual environment is an isolated environment in which a specific version of Python can be installed.
The libraries installed within the environment will be accessible only inside it.

# Create folder for new project
mkdir -p spaceship-game/source
cd spaceship-game
# Create virtual environment
virtualenv -p python3.4 virtualenv
# Enable virtual environment, pour Disable virtual environment with deactivate
source virtualenv/bin/activate
# Go to project folder
cd source

Clone the project squelet

To retrieve the project in source, use this command.

git clone -b step-0 https://github.com/blancheta/spaceship-game.git

Project structure

The following structure appears in the project.

# source
- run.py
- resources # Images et Sons
- classes # Contient les modèles pour créer Spaceship, Invaders, Bullet, Life
- screens # Ecrans de jeu
- tests # Fichier de tests

Resources

If you want to modify the resources, simply replace the existing file with the desired one.

Game window

Tout d’abord, nous configurons la fenêtre de jeu avant la boucle mainloop.

# run.py
...
pygame.init()

# Create the game window
# set_mode(resolution=(width, height), flags=0, depth=0)
screen = pygame.display.set_mode((640, 480), 0, 32)

# Window colors
bg_color = (0, 0, 0)

# The title of the window
pygame.display.set_caption('Game Menu')
menu_selected = True

# Init the views
menu_items = ('Start', 'Settings', 'Quit')
gm = GameMenu(screen, menu_items)
gs = GameSettings(screen)
# GameMenu dynamically created to allow restart
g = None
# By default, the loop is infinite.
mainloop = True

Main game loop

In order to launch the game from the run file, we will add a few elements to the main loop.
This part contains the core of the game, used to navigate between the different screens.

while mainloop:

# Refresh screen to full back for each loop
screen.fill(bg_color)

# Starts the menu screen by default or after pressing ESC.
if menu_selected or g.escape_selected:
gm.run()
if g is not None:
g.escape_selected = False
gs.escape_selected = False

# Start the game screen
if gm.start_selected:
g = Game(screen)
g.run()
gm.start_selected = False
gm.quit_select = False

# Start the configuration screen
if gm.settings_selected:
gs.run()
gm.settings_selected = False

# Close window is Quit is selected
if gm.quit_select is True:
mainloop = False

pygame.display.flip()

This part of the tutorial comes to an end.

In part 2, we will create the Menu and Settings views.

Sources:
– https://www.pygame.org/docs/