Prerequisites

For making a game of your choice there are 3 main questions that need answering. They are as follows:

What sort of game do you want to build?

What sort of language do you want to program in?

What sort of platform do you want to deploy your game to?

Most of the time you can answer each of these questions and find a perfect framework that fits your requirements. Other times, it might not be possible. Consider for example, there aren’t many HTML5 frameworks that allow you to write a high-performance 3D game that you can build.

For PyGame, let’s assume you gave the following answers to the previous 3 questions:

The game you want to create is graphical, but not 3D.

You want to program in Python. Also, you already know a little bit of Python

You want to create a client application that can potentially be wrapped in a standalone executable.

So, next up on this PyGame Tutorial blog let us look at how we can set up PyGame.

Installing PyGame

Installing PyGame is pretty straightforward and easy. But the first prerequisite is to install Python 2.7. Installing Python on both Windows and Linux is very easy and simple.

Next up would be download the official PyGame installer and run the corresponding files and follow the on-screen instructions.

Installation is simple. Just follow through and the defaults are considered fine.

I personally use PyCharm and install all of these addons there and work using that for my Python requirements. Just use whichever IDE you are comfortable with and start along with that.

Simple PyGame Application

The following is a very simple app that is built using PyGame pipeline. Check it out:

import pygame – This is of course needed to access the PyGame framework.

pygame.init() – This initializes all the modules required for PyGame.

pygame.display.set_mode((width, height)) – This will launch a window of the desired size. The return value is a Surface object which is the object you will perform graphical operations on.

pygame.event.get() – This empties the event queue. If you do not call this, the windows messages will start to pile up and your game will become unresponsive in the opinion of the operating system.

pygame.QUIT – This is the event type that is fired when you click on the close button in the corner of the window.

pygame.display.flip() – PyGame is double-buffered so this swaps the buffers. All you need to know is that this call is required in order for any updates that you make to the game screen to become visible.

So what is the output like, when we execute the above code? It looks something like this:

Looks rather plain, right? Let us start adding some content to our screen. We can begin by drawing a rectangle. It is simple and we use pygame.draw.rect for this purpose.

As you can imagine, this will draw a rectangle. It takes in a few arguments, including the surface to draw on , the color and the coordinates/dimensions of the rectangle.

# Add this somewhere after the event pumping and before the display.flip()
pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60))

As you can see there are 3 arguments:

The first argument is the surface instance to draw the rectangle to.

The second argument is the (red, green, blue) tuple that represents the color to draw with.

The third argument is a pygame.Rect instance. The arguments for this constructor are the x and y coordinates of the top left corner, the width, and the height.

So what is it that we can see after adding that tiny piece of code?

Well, here is the output:

Seems to be nothing fancy just yet. But we can always start somewhere, right?

So next up on this PyGame Tutorial blog, let us look at how we can make the game more interactive.

Interactivity

The point of a game is to be interactive. Right now, the only thing you can interact with is the close button. Which isn’t a very fun game, right? All user input events come through the event queue. Simply add more if statements to that for loop to add more interactivity.

Let us check the output when we try to move the rectangle to the right:

So that is not what we were expecting, right?

Two things are wrong.

Each time you draw a rectangle, the rectangle from the previous frames remains on the screen.

It moves really really really fast.

For the first, you simply need to reset the screen to black before you draw the rectangle. There is a simple method on Surface called fill that does this. It takes in an RGB tuple.

screen.fill((0, 0, 0))

Secondly, the duration of each frame is as short as your super fancy computer can make it. The framerate needs to be throttled at a sane number such as 60 frames per second. Luckily, there is a simple class in pygame.time called Clock that does this for us. It has a method called tick which takes in a desired fps rate.

clock = pygame.time.Clock()
...
while not done:
...
# will block execution until 1/60 seconds have passed
# since the previous time clock.tick was called.
clock.tick(60)

Next up on this PyGame tutorial blog we will see how we can work with images and how we can integrate them into our game.

Adding Images

You can instantiate a blank surface by simply calling the Surface constructor with a width and height tuple.

surface = pygame.Surface((100, 100))

This will create a blank 24-bit RGB image that’s 100 x 100 pixels. The default color will be black. Blitting such an image on a white background will result in this:

However, if you want a 32-bit RGBA image, you can also include an optional argument in the Surface constructor. Just add the following line in the code:

surface = pygame.Surface((100, 100), pygame.SRCALPHA)

This will create a 100 x 100 image that’s initialized to transparent. Rendering such an image on a white background will result in this:

Solid color images and rectangles aren’t very interesting. Let’s use an image file:

Consider a PNG image of a ball. The fine name is ‘ball.png’. This is the image, check it out:

To load an image from file, there is a simple call to pygame.image.load()

Check out the following syntax:

image = pygame.image.load('ball.png')

Replacing the pygame.Surface((100, 100)) code with the code above will result in an output such as this. Check it out:

Do not use pygame.image.load repeatedly on the same image within your game loop. That is not an efficeint way to code. The best way to do it is to initialize it just once and use it any number of times later.

The best thing you could do is to create a string-to-surface dictionary in one centralized location. And then write a function called get_image that takes in a file path. If the image has been loaded already, then it returns the initialized image.

If not, it does the initialization. The beauty of this is that it is fast and it removes the clutter of initializing images at the beginning of key areas of the game logic. You can also use it to centralize the abstraction of directory separators for different operating systems. But a code snippet is worth a thousand words.

Note: Windows is not case sensitive when it comes to file names. All other major operating systems are. If your file is called ball.png and you use pygame.image.load(‘BALL.PNG’) it will work if you are on windows. However, when you give your game to someone running on a mac or Linux, it will not work and might end up with an erroneous output.

Next up on this PyGame tutorial blog, let us check out how we can implement music and sound effects into our game.

Sound and Music

The sound and music API’s are fairly simple. Let us go though the basics and we can work our way from there.

Playing a song once:

pygame.mixer.music.load('foo.mp3')
pygame.mixer.music.play(0)

Playing a song infinitely:

pygame.mixer.music.load('foo.mp3')
pygame.mixer.music.play(-1)

The number being passed in is the number of times to repeat the song. 0 will play it once.

Calling play without a number is like calling it with 0.

pygame.mixer.music.play() # play once

Queuing a song:

pygame.mixer.music.queue('next_song.mp3')

Stopping a song:

pygame.mixer.music.stop()

The stop function will also nullify any entries in the queue.

Shuffle and repeat:

If, for example, you wanted to play randomly from a list of 5 songs, one could create a list of the songs as a global:

def play_next_song():
global _songs
_songs = _songs[1:] + [_songs[0]] # move current song to the back of the list
pygame.mixer.music.load(_songs[0])
pygame.mixer.music.play()

The music API is very centralized. However sounds require the creation of sound objects that you have to hold on to. Much like images. Sounds have a simple .play() method that will start playing the sound.

effect = pygame.mixer.Sound('beep.wav')
effect.play()

Because you can make the mistake of storing sound instances redundantly, I suggest creating a sound library much like the image library:

Note: When you draw a polygon, rectangle, circle, etc, draw it filled in or with 1-pixel thickness. Everything else is not very well implemented.

Acceptable Outlines:

If you must draw a rectangle that has 10-pixel-thick borders, then it’s best that you re-implement the logic yourself with either 10 1-pixel-thick rectangle calls, or 4 10-pixel-thick rectangle calls for each side.

Drawing a Polygon:

This API is pretty straightforward. The point list is a list of tuples of x-y coordinates for the polygon.

Rule #1: You should never assume a certain font is installed on the user’s computer. Even in CSS, there is a way to define a hierarchy of fonts to use. If the best choice for a font isn’t available, an alternate is used. You should follow the same pattern. Luckily, PyGame has a way to enumerate all the fonts available on the machine:

all_fonts = pygame.font.get_fonts()

Additionally, there’s a way to instantiate the default system font:

font = pygame.font.Font(None, size)

And alternatively, you can pass in the name of a font file you include along with your code instead of None to guarantee the existence of the perfect font:

Using any combination of the above, you can write a better font creation function. For example, here’s a function that takes a list of font names, a font size and will create a font instance for the first available font in the list. If none are available, it’ll use the default system font.

You can take it a step further and actually cache the rendered text itself. Storing an image is cheaper than rendering a new one, especially if you plan on having the same text show up for more than one consecutive frame. Yes. That is your plan if you want it to be readable.

Next up on this Pygame tutorial blog, we need to look at how we can consider inputs.

Input Models

There are two basic ways to get the state of any input device. Those are checking the event queue or polling. Every time a key or button is pressed or released, or the mouse is moved, an event is added to the event queue. You must empty this event queue out each frame by either calling pygame.event.get() or pygame.event.pump().

pygame.event.get() will return a list of all the events since the last time you emptied the queue. The way to handle those events depends on the type of event itself. The type of event can be checked by reading the event.type field. Examples of pretty much each type of common event can be seen in the extended code sample below. There are more types, but they are fairly uncommon.

The other way to check for events is to poll for the state of keys or buttons.

pygame.key.get_pressed() – This will get a list of booleans that describes the state of each keyboard key.

pygame.mouse.get_pos() – Returns the coordinates of the mouse cursor. Will return (0, 0) if the mouse hasn’t moved over the screen yet.

pygame.mouse.get_pressed() – Like pygame.key.get_pressed(), returns the state of each mouse button. The value returned is a tuple of size 3 that corresponds to the left, middle, and right buttons.

Here’s a little program that has a bit of everything:

Moving the mouse causes a trail to be drawn after it.

Pressing W while holding Ctrl will close the window. Same for Alt + F4.

Pressing the close button will close the window

Pressing r, g, or b keys will make the trail turn red, green, and blue respectively.

Pressing the left mouse button will cause the trail to become thicker.

Pressing the right mouse button will cause the trail to become thinner.

When you override this class, you have 3 method implementations to fill in.

ProcessInput – This method will receive all the events that happened since the last frame.

Update – Put your game logic in here for the scene.

Render – Put your render code here. It will receive the main screen Surface as input.

Of course, this class needs the appropriate harness to work. Here is an example program that does something simple: It launches the PyGame pipeline with a scene that is a blank red background. When you press the ENTER key, it changes to blue.

This code may seem like overkill, but it does lots of other subtle things as well while at the same time keeps the complexity of your game logic contained into a snazzy OO model. Once you start adding more complexity to your game, this model will save you lots of time from debugging and changing code.

Conclusion

I hope this PyGame tutorial helps you to kickstart your learning on PyGame. After reading this blog on PyGame Tutorial using Python, I am pretty sure you want to know more about Python. To know more about Python you can refer the following blogs: