PyGame tutorial
PyGame is a series of Python modules specially designed to make game creation a breeze. We’re only going to skim the surface in the next couple of weeks but I hope you will be encouraged to do some exploration on your own! Read more about the package on its website.
We’ll start today by going through a line-by-line tutorial. Do your best to understand what is going on and experiment as much as possible. As you go through, think about how this compares to Turtle Graphics. What is easier? Harder? More elegant? Similar?
A lot of this is “stolen” from http://rene.f0o.com/mywiki/LectureThree – thanks!!
Import Modules
The first thing you’ll need to do is bring all the pygame code into your program by importing the appropriate modules. Recall, modules are a grouping of code, or a library.
For the rest of the tutorial, I’ll assume you’re working at the prompt, but feel free to open a new program and work in there instead. You will need the following lines whenever you want to use pygame:
>>> import pygame, sys,os >>> from pygame.locals import *
You can look up the documentation for these modules: pygame, os, sys.
You may also want to try using dir() and help() functions on those modules to learn more.
>>> dir(pygame) >>> help(pygame)
Initializing pygame
Next we initialize all imported pygame modules. This is done with the pygame.init() function.
>>> pygame.init() (6,0)
We’ve now initialized the video, the sound, and a number of other pygame modules. If you type it into the interpreter you’ll see that 6 modules have initialized correctly, and none have failed.
Setting up the screen
We need to create a window by giving it a width and height. For example, I’ll create a wide, short window of 500 pixels in width and 100 in height.
window = pygame.display.set_mode((500, 100))
Check out the documentation for pygame.display.set_mode.
Now we set a caption on the window. The caption is the text in the middle of the window bar. Set the text to what ever you like!
pygame.display.set_caption('Go Bulldogs!!")
Check out the documentation for pygame.display.set_caption.
Finally we get the display surface representing a screen.
screen = pygame.display.get_surface()
A surface represents either the screen or an area in memory where images are held.
Check out the documentation for pygame.Surface.
Loading an image
Loading an image in pygame is much easier and awesome than in Turtle Graphics. First of all, pygame supports many formats including jpg, png, bmp…
Find an image of your choice and load it:
>>> bulldog_pic = "bulldog.jpg" >>> bulldog_surface = pygame.image.load(bulldog_pic)
Have a look at the documentation for the pygame.image.load function.
Drawing the image onto the screen.
screen.blit(monkey_surface, (0,0))
What we are doing on this line is drawing the image, which in this case is contained in the bulldog_surface variable, onto the screen. blit is just another word for draw.
The second argument to the function is telling blit to draw the monkey at coordinates (0,0). The top left of the screen.
Pygame uses a coordinate system for the screen where x= 0, y=0 is the top left of the screen. (0,20) is twenty pixels below the top of the screen. Careful — this is not the same as Turtle Graphics!!
Fliping the display
pygame.display.flip()
Here is where we flip the display surface. This updates the whole screen.
There are more complicated things which you can do with updating the display, which you will discover soon. If you want to learn more about updating the display you can find out here – http://pygame.org/docs/ref/pygame_display.html#flip
Why do you have to flip the display? To see your graphics drawn. Flipping the display is your way of telling pygame that you have finished making changes for that frame, now please show the changes.
For now just be content that you should flip the display after having drawn to it.
Adding a way to quit.
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
else:
print event
We are defining a function with this code. This function does two things:
- looks for a quit event.
- prints other events.
An event is:
- Something that takes place; an occurrence.
- A significant occurrence or happening.
Our games may be told that the mouse has moved, that certain keys have been pressed or the joystick has been moved.
These are the types of events that happen within our program.
The input() function above loops over the input sequence events, and does a test on each event.
Once a quit event happens the program exits. A quit event can happen by clicking on the close window, or pressing ALT+F4.
If it is not a quit event it prints the event to the console(command line window).
The main loop
while True: input(pygame.event.get())
Here we have an infinite loop. While True is true it will keep looping. As true is going to stay true for a long time, it will keep going on(probably until the program exits).
pygame.event.get is used to see what is happening in the program. It returns a list of events. We pass this list to the input function we defined above.
All the code together.
Once you’ve successfully put the program together, run it, and see all the events fly by on the console! Try pressing a few keys. You will notice the events being printed out to the console. If you press a mouse button you will get events for that.
Read the pygame docs for events — http://pygame.org/docs/ref/event.html
Things to try at this point
- Place your image in a different location.
- Load two images.
- See if you can figure out how to make your program quit when the user presses any keyboard key. You’ll need to look at the events documentation.
Adding music
my_music = "crazybeats.wav" sound = pygame.mixer.Sound(my_music) sound.play()
Sounds are loaded by creating pygame.mixer.Sound objects. One of the Sound objects’ methods is play(). Unfortunately, pygame is limited to OGG and WAV files.
What if you wanted to make your sond play every time the user clicked the mouse? Add a condition to your event testing as follows. This code should go after the if statement that allows the user to quit.
elif event.type == MOUSEBUTTONDOWN: sound.play()
Drawing text
Drawing text is pretty involved in pygame! I’ll explain it line by line. Try typing these in somewhere in your program (probably after drawing your image(s)) to see how it works.
font = pygame.font.Font(None, 36)
Load a particular font in a set size. Usually, using the default font by passing in None will be good enough.
text = font.render("YEAH AWESOME!", 1, (0, 0, 255))
To actually create the text, pass it in along with a one and a color. The color is three values for red, green and blue between 0 and 255.
textpos = text.get_rect()
We need to get the rectangle the text will occupy in order to position it.
textpos.centerx = screen.get_rect().centerx
You can center the text on the window by setting the text’s center to be equal to the screen’s center.
background.blit(text, textpos)
Finally, you’re ready to draw the text!
Play around for now — more next time!!




