A Fast Introduction to Pygame

Pygame is a cross-platform game library written in Python. It is the most used library to write games using Python. This tutorial aims to get you started using the Pygame library. After finishing this tutorial you will be able to craft simple Pygame applications, and will be in position of understanding complex Pygame applications written by others. I assume the reader has at least a basic understanding of Python.

If you don’t have Python and/or Pygame installed, make sure you first read this tutorial.

Overview

Pygame is composed of various modules, each dealing with a specific set of tasks. For example, the display module deals with the display window and screen, the draw module provides functions to draw shapes, and the key module works with the keyboard. These are just some of the modules of the library. The pygame documentation contains documentation for all modules.

The home of the Pygame library is at http://pygame.org, and its documentation can be found at http://www.pygame.org/docs.

To make a Pygame application, you follow these steps:

  1. Import the pygame library.
  2. Initialize the pygame library.
  3. Create a window.
  4. Initialize game objects.
  5. Start the game loop.

Step 1: Import the Pygame library

This step is pretty simple, and consists of just the line of code below.

import pygame

Step 2: Initialize the pygame library

This step is also pretty simple. We just call pygame.init(). This function initializes all the pygame modules.

pygame.init()

Step 3: Create a Window

After initializing the pygame library, we create a window that will be used to render the game graphics. See the code below.

screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("First Pygame Application")

First, we call pygame.display.set_mode() to create the window. This function takes as the first parameter, a tuple that specifies the window dimensions. The return value of this function will be used later to draw into the window. Next, we set a title to the window.

Step 4: Initialize game objects

In this step we load images, load sounds, do object positioning, set up some state variables, etc. In this tutorial, we will not cover image and sound processing.

Step 5: Start the Game Loop

The Game Loop is one of most fundamental pieces of any game. It is just a loop where we continuously handle events, check for input, move objects, and draw them. Each iteration of the loop is called a frame. When designing a game loop we must make sure each frame takes exactly the same time on any machine. This avoids the game to run at different speeds depending on the speed of the machine.

To have a smooth animation the game loop must run at least at 30 frames per second (FPS). To lock the frame rate, we use a pygame.time.Clock() object. Below is a basic structure of a game loop:

clock = pygame.time.Clock()
while True
  clock.tick(50)

  # Process events
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()

  # Clear the screen
  screen.fill((0, 0, 0))

  # Check input
  # Move objects ...
  # Draw objects ...

  # Update the screen
  pygame.display.flip()

First, we create the clock object that will be used to lock the frame rate. Next, we start the loop, and then call clock.tick() to lock the frame rate to 50 FPS.  Then, we process the event queue, checking if a QUIT event is pending. This event normally happens when the user closes the window. So, if we catch a QUIT event we call sys.exit() to quit the application.

Next we clear the screen calling screen.fill(). If you remember, we created the  screen variable in Step 3. The fill() function takes as the first parameter the color to fill the window with. Colors in Pygame are represented as RGB tuples.

Then, we should write code to check for input, move objects, and draw objects.  When we draw things into the window, they are not immediately displayed. So, in the last line of the game loop we call  pygame.display.flip() to display all the drawings in the window.

If you assemble together all the lines of code presented in each step, and run them, you will get just a black window. In the next section, we will see an example of a Pygame application that moves a box horizontally in the screen, bouncing off the screen borders.

Example

import sys, pygame

BLACK = 0, 0, 0
WHITE = 255, 255, 255

pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption("Moving Box")

clock = pygame.time.Clock()

box_x = 300
box_dir = 3

while 1:
  clock.tick(50)

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

  screen.fill(BLACK)

  box_x += box_dir
  if box_x >= 620:
    box_x = 620
    box_dir = -3
  elif box_x <= 0:
    box_x = 0
    box_dir = 3

  pygame.draw.rect(screen, WHITE, (box_x, 200, 20, 20))
  pygame.display.flip()

First of all, we import the built-in sys module and the pygame module. Next we define BLACK and WHITE color constants. Then we initialize pygame, and setup the window. After that, we create a clock object, and initialize the box object. We use box_x to track the position of the box, and box_dir to track the direction (left / right) .

Next, we enter the game loop. First, we call clock.tick(50) to lock the frame rate at 50 FPS. Then, we process the event queue, quitting the application if QUIT event is found. After that, we clear the screen with BLACK color. Next, we move the box, making it bounce if it hits the window borders. Then, we draw the box calling pygame.draw.rect(), and finally call pygame.display.flip() to update the window.

The video below shows the code above in action.

To get more details about the Pygame modules and functions, check the Pygame documentation.

Conclusion

As you can see, Pygame is pretty simple. In this tutorial, I gave you just the basics to get started with Pygame. In this blog you can find more tutorials on Pygame that will help you along the way.

  1. Hi,
    i’m wondering if I want to add more than one box ?
    I’m really stuck on it

Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.