To start creating your own games using Python, you’ll need to use the pygame module. This module isn’t bundled with standard distributions of Python, so you’ll need to install it before you start.
Pygame is a library of Python modules designed for writing computer games. Pygame adds functionality to create fully featured games and multimedia applications using the Python language.
This chapter will cover the basic modules and functions that Pygame provides. We’ll use these functions to create a very simple interactive game
Installing Pygame
To install
the module, open a command prompt. Make sure you run this as an administrator. On the command prompt, type
pip install pygame
Once you press Enter, the install will begin.
Allow the pip utility
to download and install the module.
Once the process is complete, you can start using pygame.
Opening a Window
The first thing you’ll need to do is import the pygame module
:
import pygame
Initialize pygame using the .init() method:
pygame.init()
Open a window. This sets the window size 640 pixels wide by 480 pixels high. This could also be 800x600, 1920x1080, and so on.
gamewindow = pygame.display.set_mode((640,480))
Set the window’s title. This is the title that appears in the title bar of the window.
pygame.display.set_caption("Game Window")
You should always end your pygame scripts with the .quit() method:
pygame.quit()
Let’s take a look at the program so far.
If you run this program
, the game window will initialize, open, and then immediately close. This is fine since there is no other code to execute.
Adding an Image
Let’s add an image
to the game window. This is going to be our character in the game. In this case, we’re going to use a space rocket. We can add the image load statement to our program.
sprite = pygame.image.load('rocket.png')
Paste the image (sprite) onto the game window using the .blit() method, and assign the initial position on the screen (x, y):
gamewindow.blit(sprite, (x,y))
Update the display to show the image:
pygame.display.update()
Let’s take a look at the program
.
The Game Loop
Now, let’s get our rocket
ship to actually do something. To do this, we need to create a game loop to draw our sprites, update the screen, and keep the program running.
We can take the following two statements and add them to our game loop. For this bit, we’ll use a while loop.
gamewindow.blit(sprite, (x,y))
Update the display to show the image:
pygame.display.update()
Put these inside the while loop:
while running == 1:
gamewindow.blit(sprite, (x,y))
pygame.display.update()
We’ll also need to initialize some variables – x and y, the initial position
on the screen, and running – to indicate whether the program is running or not:
running = 1
x = 250
y = 280
Let’s take a look at the program.
The Event Loop
In this simple game, we want the rocket ship to move left and right when the user presses the left and right arrow keys on the keyboard. To do this, we need something to handle these events.
To do this, we can put a for loop inside our while loop (the game loop). We’re monitoring for each event that occurs. You can use the .get()method
to read each event.
for event in pygame.event.get():
Now inside the for loop, we need some selection depending on which key is pressed. We can use an ifstatement
for this.
First, we need to check whether a key has been pressed:
if event.type == pygame.KEYDOWN:
Inside this if statement, we need to identify which key has been pressed. You can use another if statement.
if event.key == pygame.K_LEFT:
We do the same for all other keys we’re going to use. Just add elifstatements
to the if statement.
Let’s take a look.
Now, when we run the program
, you’ll see your rocket move left when you press the left key and right when you press the right key.
You’ll also notice something else. The image repeats on the screen. To fix this, you need to clear the screen (refresh) each time you move the object. You can use
gamewindow.fill((0,0,0))
This returns the screen to black at the end of each iteration of the game loop (while loop).
It is also good practice to include a quit event in your event loop, so the program terminates
gracefully:
if event.type == pygame.QUIT:
running = 0
This will set our running variable to 0, meaning the game loop will terminate and the program will close. This event will happen when you click the close icon on the top right of the window.
Let’s take a look at the program
so far.
You’ll also notice that the rocket doesn’t move when you hold the key down. This is because the key-repeat feature is turned off. To turn this on, add the following line before your game loop:
pygame.key.set_repeat(1, 25)
The first parameter
is the delay before the key event is repeated. The second parameter is the interval between repeats.
Shapes
You can add shapes
such as circles, ellipses, rectangles, and other polygons.
To draw a rectangle, use the .rect() method. Specify the surface or window you want to draw on, the color, and then specify the x and y position, followed by the width and length of the rectangle.
pygame.draw.rect(gamewindow, colour,
(x, y, width, length), thickness)
To draw an ellipse, use the .ellipse() method. When drawing an ellipse, you’re actually drawing it inside an invisible rectangle. This is why you specify width and length when drawing your ellipse.
pygame.draw.ellipse(gamewindow, colour,
(x, y, width, length), thickness)
To draw a circle, use the .circle() method. Specify the surface or window you want to draw on, the color, and then specify the x and y position, followed by the radius of the circle.
pygame.draw.circle(gamewindow, colour,
(x, y), radius, thickness)
Have a look at shapes.py.
Basic Animation
To demonstrate basic animation, we’re going to move our ufo object on the screen.
First, we need to load in our image. You can do this using the .load()method
as we’ve done before.
ufo = pygame.image.load('ufo.png')
Now, because an image is loaded onto a surface object by default, we can’t move it or manipulate it. To get around this, we assign the image to a rectangle. You can do this using the .rect()method
.
ufo_rect = ufo.get_rect()
We also need to define some speed
and direction variables. We can do this with a list. This is a list containing the [x, y] coordinates on the screen (speed[0] is x, speed[1] is y).
speed = [10, 0]
To move the object, use the .move_ip()method
:
ufo_rect.move_ip(speed)
Let’s take a look at the program. Have a look at anim02.py.
Now, when you run this program, the ufo will fly from left to right across the screen.
Because we set speed = [10, 0], this means
we move our ufo ten pixels along the x axis each time we execute ufo_rect.move_ ip(speed) in the game loop.
If we set speed = [0, 10], this means we move our ufo ten pixels along the y axis each time we execute ufo_rect.move_ ip(speed) in the game loop.
Try changing the values
in the program anim02.py and see what happens:
speed = [??, ??]
Try larger values.
Let’s take our program a step further. Let’s make the ufo bounce around the screen.
To do this, we need to check whether the left edge, right edge, top edge, and bottom edge of the ufo_rect go beyond the edges
of the screen. We can use if statements for this.
If the left edge of the ufo goes off left edge, reverse x direction.
To reverse the direction
, all you need to do is change the speed[0] to a negative number:
if ufo_rect.left < 0: speed[0] = -speed[0]
If the right edge
of the ufo goes off right edge, reverse x direction.
Again, change the speed[0] to a negative number:
if ufo_rect.right > 640: speed[0] = -speed[0]
Do the same with the top and bottom. Give it a try.
Let’s take a look at the program
. Open anim03.py. Here, you’ll see the ufo bounce around the screen.
When the ufo moves toward the right wall, x (speed[0]) is increasing and y (speed[1]) is increasing.
When the ufo hits the right wall, we change the direction
of x (speed[0]), but not y (speed[1]).
Now x (speed[0]) is decreasing, but y (speed[1]) is still increasing. Similarly for the other three sides.
What happens
if you change the speed[ ] variables?
speed = [??, ??]
How would we add another ufo?
How would we add our rocket ship from the previous section?
To animate a character, you need to load your frames
into a list:
frames = [pygame.image.load('frame1.png'),
pygame.image.load('frame2.png'),
pygame.image.load('frame3.png')]
Now, inside your main game loop, you can draw the frame using the .blit()method
to draw the frame from the frames list:
gamewindow.blit(frames[counter], (x,y))
Select next frame in list, and loop back to first frame at the end of the list. We can do this with the len()function
to return the number of frames in the list and modulus division.
counter = (counter + 1) % len(frames)
Let’s take a look at the program
. Open spriteanim.py.
With this particular animation, we have three frames to animate the flame effect on the rocket.
Summary
In this chapter, you learned that
Pygame is a library of Python modules designed for writing computer games. Pygame adds functionality to create fully featured games and multimedia applications using the Python language.
The game loop is used to draw our sprites, update the screen, and keep the program running.
The event loop checks for events such as a keypress.
The refresh rate is how fast the screen is redrawn.