SotK's Python Tutorials - Part 6: Introduction to Pygame

Started by Son of the King, July 17, 2013, 12:06:36 PM

Previous topic - Next topic

Son of the King

SotK's Python Tutorials
Part 6: Introduction to Pygame




What is Pygame?

Pygame is one method of creating a user interface in Python. It is used when you are aiming to make a game, which is the direction we are going to take with these tutorials. You can get Pygame from here. If you're on Windows you'll want "pygame-1.9.2a0.win32-py3.2.msi".

Pygame provides simple methods for drawing things into a window on screen, as well as support for sound and video.

Initialisation:

The first thing we need to do is import the pygame module. At the very top of your program, type import pygame to do this. With the module imported, we can use pygame's functionality. The following code will get us ready to make a window for you to draw things on!


pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Hello, world!')


The first line initialises pygame, and must be called before any other pygame functionality is used in your program. The second line creates a variable called screen. This is a 600 x 600 "Surface". A surface is basically an image that can be drawn to the monitor. screen will be our main surface, and the rest of our program will eventually be drawn on top of it. The third line sets the caption at the top of the window to be Hello, world!.

The next step to creating our blank window is to make an infinite loop, as we did in the last tutorial. This will be our game loop and will be where all of the functionality in the game is implemented. to do this we simply make a boolean variable, and use a while loop to create infinite repetition:


running = True
while running:
    # do stuff


Events:

We will also need a way to get out of this loop, so that we aren't stuck with an unresponsive program. To do this we will use another piece of functionality provided to us by pygame; the event loop.


for event in pygame.event.get():
    if event.type == pygame.QUIT:
        # Terminate on window closure
        running = False


pygame.event.get() returns a list of events that have occurred since the last time it was called, such as mouse movement, key presses, the close button being clicked, etc. This example is created when the close button is clicked. It is pretty much the same idea as the quit command we had in the calculator in the last tutorial. As an example, here is the code to close the program when the escape key is pressed:


elif event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
    # Terminate on Esc keypress
    self.running = False


As you can see here, events involving key presses have an attribute key, which you can use to determine which key was pressed. In a later tutorial we will use this to let us control things with the arrow keys. The pygame.KEYUP event occurs when a key is released. Similarly, pygame.KEYDOWN occurs when a key is pressed down.

Drawing:

Now we can keep our program running for as long as we want, its time to learn how to actually draw something on the screen. We'll start just by filling the screen with a colour:


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


This will fill the window with black. This is a good place to start as it is the simplest method of drawing things available to us. We could just create a number of surfaces of different sizes and colours to represent different things in our game.

Once all your drawing code has executed, you will need to 'flip' the display. This will update all your changes made by drawing and show them on screen. This is equivalent to swapping buffers when using OpenGL, which I will go into at a later date.


pygame.display.flip()


Putting it together:

Now we know all the different elements we need to open a (600 x 600) pygame window on our screen, lets go ahead and do it. First we import pygame, then initialise it and set up the screen surface. Then we need our game loop, which will contain both the pygame event loop and our drawing code. This means that each frame consists of one pass through the game loop.


# import pygame modules
import pygame

# initialise pygame
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption('Hello, world!')

# game loop
running = True
while running:
    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            # Terminate on window closure
            running = False
        elif event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
            # Terminate on Esc keypress
            self.running = False

    # drawing code
    screen.fill((0, 0, 0))

    pygame.display.flip()


Next time we will put something on this display, and have a little bit of user interaction!

Jubal

Yay! I need to learn to use pygame properly... AoS just uses tkinter which is a bit crap really.  :P
The duke, the wanderer, the philosopher, the mariner, the warrior, the strategist, the storyteller, the wizard, the wayfarer...

Son of the King

I never learnt to use tkinter xD . Pygame has its own drawbacks though, biggest of all a lack of any easy support for textboxes, sliders and other such things. There are toolkits out there, but I've got no experience using them (I wrote my own when I was working on Township in python).