/* jquery */ /* jquery accordion style*/ /* jquery init */

Learn Python - PyGame Screen Drawing

With our PyGame code initialised let's draw something on the screen.

Here's a code snippet:

# get mouse position
pos = pygame.mouse.get_pos()

# define a disc size and colour
discSize = random.randint(5,50)
r = random.randint(100,255)
g = random.randint(100,255)
b = random.randint(100,255)
discCol = [r,g,b]

# draw a disc at the current mouse position
pygame.draw.circle(screen, discCol, pos, discSize)

# update the screen with what we've drawn
pygame.display.flip()

# control the draw update speed
clock.tick(50)

In the first statement we call pygame.mouse.get_pos to return the mouse coordinates and store them in a variable called pos. As we'll see later this code will be called in a endless loop. So, on each loop iteration (which means many times a second) pygame.mouse.get_pos captures the current mouse position.

In this example we draw a simple disc on the screen, so the next five statements set a disc size and colour. Note we're using the random package here to vary the size and colour of the disc each time.

Next we call the pygame.draw.circle function to draw a coloured disc. There are four parameters. The first parameter is our screen object (which we created in the initialisation section) onto which the disc is drawn. The second parameter contains the RGB discCol value we defined earlier. Parameter three contains the mouse position coordinates as stored in the pos variable. And the fourth parameter declares the disc radius using the discSize variable.

Now we come a particularly important function pygame.display.flip. This does the magic necessary to render our graphical elements on the screen. Without this line we'd see nothing. I say magic because there's loads of clever stuff going on under the covers to create smooth, flicker-free animation. This involves many hundreds of lines of Python code, however all we need to do is call a single function.

The final statement is also important. It controls the update speed of the screen display using the function clock.tick. Remember, we created the clock object in the initialisation section. The tick function parameter fixs the update speed. The lower the number the fewer the number of screen updates.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Init Code

Before we can use any of the PyGame module's features we'll need to a few initialisation statements.

Here's a simple example:

pygame.init()
screen = pygame.display.set_mode([500,400])
screen.fill(pygame.Color('black'))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

One the first line there a call to the pygame.init function. This does a whole load of very clever stuff that we don't need to worry about. That's the power of using modules. Suffice to say, after this call we only need a few additional lines of code.

Next a screen object is created using the pygame.display.set_mode function. The parameter is a list (hence the square brackets) which contains two numbers. These numbers correspond to the width and height of the screen in pixels. So, here the screen object created will be 500 pixels wide and 400 pixels high.

Now we have a screen object we can do things with it. As an example the following line calls the screen.fill function to set a background colour to black. We'll be using the screen object again later on.

The pygame.display.set_caption statement simply sets the window title, as defined by the text string parameter.

And finally a clock object is created using the pygame.time.Clock() function. A clock object allows to adjust the timing of drawing events within the game. Once again, we'll see how this is used later.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Colours

There's a number of ways to specify colours in PyGame. So, it's worth examining the options available.

Arguably the simplest option is to specify basic colours is by name, as here:

backgroundCol = pygame.Color('black')
textCol = pygame.Color('white')
lineCol = pygame.Color('magenta')

However, assigning a name (and recalling that name) for every possible colour isn't practical. So, a more flexibility solution is to use RGB colour values.

Here's an example:

backgroundCol = [0,0,0]
textCol = [255,255,255]
lineCol = [255,100,100]

The three numbers relate to the red, green and blue components of a colour. As each RGB number ranges from 0 to 255, the total number of RGB colour combinations is 256 x 256 x 256, or over 16 million.

Setting a value of [0,0,0] means no red, green or blue colour. So the backgroundCol setting will be black. To define white we'd need to set all three colours to their maximum value, namely [255,255,255], as in the textCol variable. While the lineCol variable has pinkish colour value due to the dominance of red.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Event Handling

Just like a GUI program our game will run in an endless loop. On every loop cycle we'll need to check for new events.

So, it's good practice to define a function to hold all your event handling code. Then it's a simple matter to call this function every loop cycle.

Here's a barebones example:

def handleEvents():
  # loop through all events
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.quit()

At any particular moment there may be many different events. We'll need to test them all, so there's a for loop to iterate through the full event list.

In this barebones example we only test for one event, namely the QUIT event. If this has occurred the game is closed using the sys.quit() function call.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Events

A key part of PyGame coding is handling events.

Remember, we've already used events when we explored handling GUI events.

The PyGame module defines a number of events. Here's the list:

QUIT
KEYDOWN
KEYUP
MOUSEMOTION
MOUSEBUTTONUP
MOUSEBUTTONDOWN
JOYAXISMOTION
JOYBALLMOTION
JOYHATMOTION
JOYBUTTONUP
JOYBUTTONDOWN
VIDEORESIZE
VIDEOEXPOSE
ACTIVEEVENT
USEREVENT

As you can see they cover keyboard, mouse and joystick actions plus the quit event generated by closing the game window.

Importantly there's a userevent which allows use to handle our own custom events.

A typical program will use at least one or two of these events. Later we'll create a function to handle these events.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Installation

These PyGame installation instructions presume you're running the official Raspbian images on your Raspberry Pi (and it works for any Debian-flavour Linux image).

First, ensure your Raspberry Pi is connected to the Internet.

Next open an LXTerminal window and type the following command:

sudo apt-get install python-pygame

Enter the password you used to login in with, and reply 'y' to any prompts.

Now you should be able to run any PyGame program, or create your own.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - PyGame Overview

There are many similarities in GUI and game program design concepts, code structure and programming techniques. So, the knowledge we gained earlier while coding GUI programs with Tkinter will be an excellent foundation for games creation.

A fully functioning game will typically involve graphics, animation, collision detection, sound effects, music tracks, scoring and handling user input events. Quite a challenge.

Yet, the PyGame module is more than capable of meeting this challenge.

PyGame can draw lines, shapes and surfaces; write text in a large range of fonts and styles; load, manipulate and move images; play sounds, music tracks and videos; consume keyboard, mouse and joystick input events; interact with files, CDROM disks and cameras; and much more.

The official PyGame website has a comprehensive list of module functionality.

In the next series of posts we'll walk through a very simple animation code listing to identify the key building blocks required by any PyGame app. In the process we'll revisit some Python programming techniques and pick up a few new coding skills.

A post from my Learn Python on the Raspberry Pi tutorial.