dark mode light mode Search Menu
Search

Getting Started with pygame

Horst Jens on Flickr

Everyone loves a good game. And when it comes to learning to program, making games is quite appealing. But most introductions to text-based programming still look more similar to math than to games. Even relatively simple guessing games require quite a bit of brainpower for the programmering newbie, and are not entirely satisfying for those hoping to jump in and create new worlds to explore and enemies to defeat

While it is important to keep in mind that commercial games are made by teams of tens, if not hundreds or thousands, of experienced programmers, on multi-million dollar budgets, creating simple animations in a standard text-based language is no longer out of reach to beginning programmers.

Pygame is a code library with modules that can be used to make games in the Python programming. Though using pygame is more challenging than using a drag and drop language such as Scratch or Blockly, it has the noteworthy advantage of working with one of the most commonly used, as well as one of the most friendly, programming languages. While typing is required and syntax counts in Python, when questions arise, there is a community of programmers who have likely answered these questions and posted their responses online.

Import pygame

What exactly does it take to get a basic animation setup using pygame? First, Python must be installed on your computer. Although there exist sites that allow one to code in the cloud, it is still primarily done on the actual computer. Fortunately, Python can be downloaded and installed for free, and without much hassle.

Once Python is set up, the pygame library also needs to be downloaded and installed. Again, this is free and fairly straightforward. The quickest way to find Python and pygame online and then download them is probably to search for each using your favorite web browser. A query along the lines of ‘download Python’ or ‘download pygame’ should do the trick. Be sure that the version of pygame that you download corresponds with the version of Python you installed. For example, if you plan to use Python 2.7 on a Windows machine, you might choose the version of pygame that looks something like pygame-1.9.1.win32-py2.7.msi.

There is something fun and exciting about writing a program that produces an image or animation. To save the time of creating your own .png images, you might consider downloading already-made game tiles. If you already have game tiles, you can likely use them with pygame. If not, try search for Planet Cute game tiles. Again, they can be downloaded for free.

Once Python is set up, the pygame libraries have been installed, and you have game tiles to work with, you are ready to go. Just to be sure you are set, open Python’s IDLE window, and in the shell enter the following:

import pygame, sys

Here’s what your IDLE or command line interface (CLI) software should display:

projects-pygame-screen1-import-pygame
Import pygame and sys libraries to your project

If no red error messages appear, your setup is likely a success. Test out one more line of code:

from pygame.locals import *

Here’s what your IDLE or command line interface (CLI) software should display:

projects-pygame-screen2-import-pygame
Import all (*) functionality from pygame.locals portion of pygame library

In the case that Python spits out red error messages stating that it cannot locate pygame, you may need to try installing it again. Otherwise, you can now test out the game tiles.

To get started coding, from IDLE’s file menu, choose New Window. This is where you will type your code. There is plenty of pygame code available online to test out, as well as in the book Making Games with Python and Pygame, however, the following is a quick example to play with. Before typing anything, it is helpful to create a new folder for your soon-to-be code. Be sure that any tiles you refer to in your code are saved in this folder.

pygame Code Snippet 1

import pygame, sys
from pygame.locals import *

# below is code that will make a game tile appear on the screen

pygame.init()

WHITE = (255, 255, 255) # set the red, green, and blue values all to 255 in order to create white

DISPLAYSURF = pygame.display.set_mode((600, 800), 0, 32) # create a window with dimensions 600 pixels across and 800 pixels down

pygame.display.set_caption('My Bug')

tile = pygame.image.load('Enemy Bug.png') # load an image called Enemy Bug that is saved in the same folder as this file

while True:
    DISPLAYSURF.fill(WHITE) # create a white background
    DISPLAYSURF.blit(tile, (100, 200)) # place the enemy bug tile 100 pixels over and 200 pixels down from the top left corner
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

Expected Result from Code Snippet 1

projects-pygame-screen3-my-bug
The My Bug.png tile output display

If Python has trouble displaying the tile My Bug.png, double check to make sure it is in the same folder that the rest of the code is saved in. If not, it can either be moved there, or you will need to specify the path name to its current location.

The above is somewhere around the least amount of Python code that you can get away with to create a program that displays an image. Once you get the image to appear, you can add animation and event handlers with just a few more lines of code. Setting up a matrix of tiles that covers the background with an intriguing land made from game tiles doesn’t take all that much more learning either. These are all good next steps as you get a feel for working with pygame. Code for each of these challenges can be found below.

pygame Code Snippet 2

Modify Pygame Code Snippet 1 so that we can control the tile using the arrow keys. Line 17, from Code Snippet 1, has been commented out of the original file and do not run; highlighted code (line 13, lines 23-33) has been added in.

import pygame, sys
from pygame.locals import *

pygame.init()

WHITE = (255, 255, 255) # set the red, green, and blue values all to 255 in order to create white

DISPLAYSURF = pygame.display.set_mode((600, 800), 0, 32) # create a window with dimensions 600 pixels across and 800 pixels down

pygame.display.set_caption('My Bug')

tile = pygame.image.load('Enemy Bug.png') # load an image called Enemy Bug that is saved in the same folder as this file
tilePos = [0, 0]

while True:
    DISPLAYSURF.fill(WHITE) # create a white background
    #DISPLAYSURF.blit(tile, (100, 200)) # place the enemy bug tile 100 pixels over and 200 pixels down from the top left corner
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if(event.key == K_RIGHT) and tilePos[0] < 500:
                tilePos[0] += 5
            elif(event.key == K_LEFT) and tilePos[0] > 0:
                tilePos[0] -= 5
            elif(event.key == K_UP) and tilePos[1] > 0:
                tilePos[1] -= 5
            elif(event.key == K_DOWN) and tilePos[1] < 740:
                tilePos[1] += 5
                    
    DISPLAYSURF.blit(tile, (tilePos[0],tilePos[1]))
    pygame.display.update()

pygame Code Snippet 3

Modify pygame Code Snippet 2 so that the tile moves across the window without pressing any keys. In this example, code from Code Snippet 1 (line 21) and Code Snippet 2 (lines 15 and 32-42) have been commented out and do not run. Lines 5-6, 22-25, and 44 have been added.

import pygame, sys
from pygame.locals import *
pygame.init()

FPS = 33 #sets the number of frames per second; referred to in the last line of code
fpsClock = pygame.time.Clock()

WHITE = (255, 255, 255) # set the red, green, and blue values all to 255 in order to create white

DISPLAYSURF = pygame.display.set_mode((600, 800), 0, 32) # create a window with dimensions 600 pixels across and 800 pixels down

pygame.display.set_caption('My Bug')

tile = pygame.image.load('Enemy Bug.png') # load an image called Enemy Bug that is saved in the same folder as this file
#tilePos = [0, 0]
tileX = 100
tileY = 600

while True:
    DISPLAYSURF.fill(WHITE) # create a white background
    #DISPLAYSURF.blit(tile, (100, 200)) # place the enemy bug tile 100 pixels over and 200 pixels down from the top left corner
    if tileX >= 0: #set image position between 0 and 700
        tileX += 5
        if tileX == 700:
            tileX = 0
  
    DISPLAYSURF.blit(tile, (tileX, tileY))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        """elif event.type == KEYDOWN:
            if(event.key == K_RIGHT) and tilePos[0] < 500:
                tilePos[0] += 5
            elif(event.key == K_LEFT) and tilePos[0] > 0:
                tilePos[0] -= 5
            elif(event.key == K_UP) and tilePos[1] > 0:
                tilePos[1] -= 5
            elif(event.key == K_DOWN) and tilePos[1] < 740:
                tilePos[1] += 5
                    
    DISPLAYSURF.blit(tile, (tilePos[0],tilePos[1]))"""
    pygame.display.update()
    fpsClock.tick(FPS) #activates fpsClock with FPS setting from lines 5-6 above

 

A good test to measure the success of a programming activity is whether or not it sparks questions about how to modify the code to suit your own ideas. If the snippets of code above leave you yearning to learn more, continuing with pygame is a great idea. The book Making Games with Python and pygame, the pygame website, and searching the web are all next steps in the right direction.

Learn More

Python

https://www.python.org/downloads/
https://www.python.org/doc/

Pygame

http://pygame.org/hifi.html

Pygame Tutorials

http://www.pygame.org/wiki/tutorials

Making Games with Python and Pygame (Book)

http://inventwithpython.com/pygame/chapters/

Invent with Python/Pygame

In same folder as python program that refers to them.
http://inventwithpython.com/pygame/downloads/

Planet Cute Game Tiles

http://www.lostgarden.com/search?q=tiles

Making Games with Python and Pygame

https://inventwithpython.com/makinggames.pdf

Create Worlds with Tiles

http://usingpython.com/pygame-tilemaps/