Though game development with Python and C++ is becoming more popular (take a look at Civilization IV), game development with Python alone is largely limited to hobbyist use. It is possible, however, with PyGame, a library written around the Simple DirectMedia Layer (SDL). PyGame isn't limited to game development, either. It can also be used in applications that require very graphical interfaces. In this article, we'll look into the basics of how PyGame is used.
PyGame may be obtained at its website, which also contains links to a number of projects written in PyGame:
Download and install PyGame, and we'll be ready to begin.
The first thing we'll do with PyGame is open up a PyGame window with a certain size and caption. We'll also fill it up with a background color and keep the window open until the user decides to quit:
import pygame import sys
# Initialize pygame pygame.init()
# Create the drawing screen screen = pygame.display.set_mode((256, 256))
# Set the caption pygame.display.set_caption('Application')
# Set a background color screen.fill((159, 182, 205))
# Update the screen pygame.display.update()
# Wait for the user to quit while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
The above application is pretty simple to understand. We start out by initializing PyGame. Then, we create the window and a drawing screen, passing a tuple with the drawing screen dimensions. Next, we use the set_caption method to set a caption. We then fill the screen with a background color, passing a tuple of values for red, green and blue that generate a nice bluish color. When we make a change to the screen, we have to call update to display the change. Finally, we wait for the user to quit the application. The pygame.event.get method returns a list of events when called, and we examine this list for a pygame.QUIT event.
The pygame.QUIT constant is simply an integer. Each event type—whether it's for a key push or a mouse click—is a unique integer. An Event object returned by pygame.event.get also has other attributes that we can examine, depending on what type of event it is. For example, an Event object that represents a key push, pygame.KEYDOWN, contains a key attribute that contains the key pushed.
It is important to note exactly what screen is in this example. The screen object is a Surface object, which may be drawn on. Here, we fill it with a color, but note that we could also create a Surface and load an image onto it. Every image you create will be a Surface. Knowing this is important because Surface objects will be the building blocks of your applications.