Getting Started with Pygame

This tutorial is the first tutorial in a series of five Pygame tutorials:

Learning Objectives

These instructions will guide you through the first few steps required to set up the foundation for a Pygame project.

Now that you have learned the basics of Python you are most likely willing to start creating your own games. Pygame is one of the best libraries to create mainly 2D retro arcade games such as Tetris, PacMan or Space Invaders.

Let’s see what are the first few steps needed to create your first game in Python.

Installing Pygame

Make sure you have access to the Pygame library. If not you will need to download and install it following the instructions provided on the Pygame website:

Step 1: Importing and initialising the Pygame library

Your Python code will need to start with the following two lines of code:

Step 2: Define the colours you will use in your game

You will have to declare a constant for each of the main colours used within your game. To help you identify colour codes you may use a colour picker.

Step 3: Open a new window

Your game will run in its own window, for which you can decide of a title, a width and a height.

Step 4: The main program loop

The main program loop is the key wrapper for your game.

The main program loop will contain 3 main sections:

  • Capturing Events: Used to constantly “listen” to user inputs and react to these. It could be when the user use the keyboard or the mouse.
  • Implementing the Game Logic. What happens when the game is running? Are cars moving forward, aliens falling from the sky, ghosts chasing you, etc.
  • Refreshing the screen by redrawing the stage and the sprites.

The main program loop will also use a frame rate to decide how often should the program complete the loop (& refresh the screen) per second. To implement this we will use the clock object from the pygame library.

The main program loop will use a timer to decide how many times it will be executed per second.

Your Challenge

Use the code above to create your first Pygame project.

Complete the code to draw the following background:

Next Step?

Your background is ready? Let’s add the first sprite to your project by completing the next tutorial:
Adding a Sprite using PyGame(Tutorial 2/5)
Share Button
Tagged with: , ,