Keeping it Small and Simple

2007.05.25

Pygame tutorial #1: getting started

Filed under: Game Programming, Graphics Programming, Pygame, Pygame Tutorial, Python Programming — Lorenzo E. Danielsson @ 02:22

This is the first part of my pygame tutorial, aimed at beginners. I will keep it small and simple, meaning I will proceed very slowly. I am not going to go into too much detail. I will explain just about as much as is necessary to get you started. You will need to have the pygame documentation available. Always keep it open while you are going through this tutorial.

One little thing before we begin. I am chronically lazy. It is amazing that I even manage to get out of bed every day. So please don’t expect this to be a regular thing. I will write tutorials as and when my eyes are open.

What you will need

  • Python: I am using Python 2.4 which is the default Python version on Debian Etch. Other versions will work as well.
  • Pygame: There really isn’t much point in programming in pygame unless you have it installed.
  • A text editor: I recommend Vim a powerful editor with an unfortunately bad reputation for being complex. Don’t believe the rumors. They are not true.

If you are on Debian or one of its derivates, try this (as root):

# aptitude install python-pygame

That will install pygame and all dependencies for you. Other distros and operating systems: both Python and pygame are most likely available in your repositories. Figure out how to install them and you are ready to go.

What you should know already

It is a good idea if you at least have some basic knowledge of Python. I guess you could be learning it as you go along, but I will assume that you know how to program in Python already.

Getting started

First of all, let us look at creating a pygame application that does absolutely nothing. Well, nearly absolutely nothing. It actually does display a window. It also does some very rudimentary event handling. You can see this as a template for the next few programs that we will write.

Here is the code:

1 #! /usr/bin/env python
2 
3 import pygame
4 
5 screen = pygame.display.set_mode((640, 400))
6 
7 while 1:
8     pass

First of all, to use pygame we have to import it. Then we create a Surface that is 640 pixels wide and 400 pixels high. There are a lot more things you can do with set_mode, but we will keep it simple at this point.

Next we enter into an infinite loop. We need this because otherwise the window will
If you run this program it should display a 640×400 window. That wasn’t too difficult was it. If you try to close this application by clicking on the window’s close button, you will notice that it does nothing. You will have to go activate the terminal that you started the program from and
hit CTRL+C to stop the program. We will fix that soon.

Exercises

  1. Create a window that is 320 pixels wide and 200 pixels high.
  2. Create a program where the user can specify the width and the height as command line arguments.
  3. Create a program that asks the users for the width and the height and then displays the window.
  4. Write a program that calls pygame.display.set_mode twice with different sizes. What do you expect should happen? Run the program. What actually happens? Can you explain why?

Adding an event loop

Our first example was maybe a little too simple. Staring at a completely blank window soon gets boring. Also, having to go to the terminal and hit CTRL+C to close the window seems a little awkward. Let’s add a bit of code!

Here is an updated version of the first program:

 1 #! /usr/bin/env python
 2 
 3 import pygame
 4 
 5 screen = pygame.display.set_mode((640, 400))
 6 running = 1
 7 
 8 while running:
 9     event = pygame.event.poll()
10     if event.type == pygame.QUIT:
11         running = 0
12 

What is new is that I have added a simple event loop. The loop is controlled by a flag called running. As long as the flag is set the loop keeps running. Inside the loop we use the poll method to grab the next event from the event queue. There are other ways of doing this, but polling works just fine for now.

There are several different event types that pygame knows about and can respond to. One of these is QUIT, which gets triggered when the user clicks on the window’s close button. All we do if we get an event of this type is clear the running flag, which will exit the loop and cause the program to terminate. Still simple, isn’t it.

Exercises

  1. Adapt each of the programs you wrote for the exercises in the previous section to use an event loop.
  2. Rewrite the program to do away with the running flag. Make sure that the program still jumps out of the event loop on the QUIT event.

Finishing touches to the template

As a final step before we start doing real things, let’s add just a little bit more so that we have a complete template for what follows. We will paint the our Surface and we will learn how to do a bit of screen flipping. First the code:

 1 #! /usr/bin/env python
 2 
 3 import pygame
 4 
 5 screen = pygame.display.set_mode((640, 400))
 6 running = 1
 7 
 8 while running:
 9     event = pygame.event.poll()
10     if event.type == pygame.QUIT:
11         running = 0
12     screen.fill((0, 0, 0))
13     pygame.display.flip()
14 

We have added just two lines of code. The first one sets a background color for the Surface. We have passed in a sequence of three values: red, green and blue. Each one can be a value between 0 and 255. Since we set all to zero, we get a black screen. You should experiment with different values for red, green and blue.

The next thing that is new is that we call pygame.display.flip. Drawing directly to the screen is usually a very bad idea. Instead, we have a invisible buffer that we draw onto. When we have finished drawing we make the buffer visible. That way we get flicker-free animations (when we get to that).

Exercises

  1. Create a window with a white background color.
  2. Create a window with a red background color.
  3. Experiment with setting different background colors. If you are not familiar with RGB values then spend a little extra time to figure out how to get colors like yellow, brown, cyan etc.
  4. Create a program that asks the user to specify the values for red, green and blue. Check that the values are in the valid range (0-255) and then use these for the background color.
  5. Create a program that upon start-up checks the time of the day and sets the brightness of the background color accordingly. Use a blue scale. If it is midnight, the screen should be black. If it is midday, the screen should be bright blue. Any other time the background should be something in between corresponding to the brightness outside.

Conclusion

So what have you learned so far? Not an awful lot, by the looks of it. But in a way you have. You have acquired some basics that you will need to understand the next tutorial, which will come soon. In the meantime, try your hands on a few of the exercises. If you complete all you can make up a few of your own.

17 Comments »

  1. Great help and a good job.

    Only I would like some help on Exercise 2 part 1

    I have got:

    import sys, pygame
    size = width, height = sys.argv[1], sys.argv[2]
    screen = pygame.display.set_mode(size)

    while 1:
    pass

    But it will not work it says

    “TypeError: an integer is required”

    I see no reason why it wont work.
    Any ideas?
    Thanks for the great turotial

    Comment by Pete — 2007.06.02 @ 15:01

  2. The problem is simply that argv is an array of strings, whereas the width and the height need to be specified as integers. Python is different from Perl in this regard, it doesn’t do automagic type conversion for you. Try:

    size = width, height = int(sys.argv[1]), int(sys.argv[2])

    And thanks for the comment about the tutorial. I’m trying to write something that will be useful for people with a little bit (but not much) of Python experience, and pretty much no graphics programming experience. Feel free to also off suggestions that could help me improve the tutorial in that direction.

    Comment by Lorenzo E. Danielsson — 2007.06.03 @ 13:10

  3. Hey im 14years old and im just starting out programming and i thank u guys for showing me how to make pixels but i just wanted to let u know that, some of this information doesnt work and i spent like 30minutes trying to figuer out what i did wrong copying it and then i realized that most other people had problems with this programming, and then i asked my brother who has pretty much mastered programming and he said though some of this is helpful it wasnt done correctly, so i just wanted to let u know that u probably should look over ur guys’s programming. TY for the info on the creating a game screen, i thank u for that. pice

    Comment by Mark T. — 2007.06.29 @ 04:08

  4. hey lorenzo if u get on this again cna u tell me tat it maybe a little simpler begginer programming talk because i sitll dont quiet understand to my full knollege all the basic names of everything though i do pretty much understand how to do them, picew.

    Comment by Mark T. — 2007.06.29 @ 04:10

  5. Mark T,

    First of all thank you for your comments. Now let’s look at your issues. I’m not really sure why some of the samples don’t work for you. It is actually quite difficult for me to know since you don’t provide any information. What program(s) doesn’t work? What are the actual error messages? This information would help me to help you.

    It could very well be indentation issues, if you copied and pasted. Didn’t anybody tell you copy-and-paste is next to useless ;-). Seriously, I try to keep the tutorials very simple, but it does require at least some basic knowledge of Python. Without that, it would be a Python tutorial, not a pygame tutorial.

    You say you spent 30 minutes trying to get things to work. Well, if you want to have a future in programming you’re going to have to get used to spending much more than that. You won’t be able to learn how to be an accomplished programmer in minutes, hours or days. Patience is a virtue that you should begin to cultivate.

    That also relates to your next point, that certain things are done wrong. That is absolutely correct, if you mean “not done the best way”. You code works (unless I made some mistake in copying my working code into the WordPress post. But there are several things that I am doing initially that are suboptimal (to say the least). There is a master plan behind this, one that you can agree or disagree with. If you read the very end of tutorial #3, you will see that there is an indication that I will look into the problems of polling events in tutorial #4. By the time you do tutorial #4 you will know that there is a poll() method, how to use it and you will hopefully understand why it’s not a good idea.

    Fortunately, I’m not the only one writing pygame tutorials. Do check out some of the other good tutorials on the ‘Net. You learn better from multiple sources than from one. Each person who tries to teach something will be good at explaining some things, poor at others. I don’t think I am any different in that regard.

    In your second comment you ask for something more aimed at beginners. I have that in mind, but also remember that programming pygame is not really for absolute beginners. You need to know Python first.

    Right now I’m a bit short of time, because I’ve got a project I need to try to finish up. But I will try to post something aimed at beginner programmers when I have a bit of spare time.

    Finally, a little piece of advice, please don’t take it the *wrong* way. You could really work on your spelling. English may not be your first language. It’s not my first language either. But, I still try to make the effort to compose my sentences. If I were to write in another language, say French for instance, I would make an effort to write correctly in that language as well. It is easy for people to look at the way you write and come to the conclusion that you are sloppy. And sloppy people don’t usually make good programmers..

    Comment by Lorenzo E. Danielsson — 2007.06.29 @ 09:44

  6. im having probelms with the

    event = pygame.event.poll()
    10 if event.type == pygame.QUIT:
    11 running = 0

    It doesnt seem to work. It is supposed to stop the string of code spamming like mad right? I copy and paste your data into a blank shell, run the module, and it works. I see the vertical line moving up and down, but when i type the code down in the the IDLE shell and press enter after pygame.draw.line(screen …ect..ect on turtorial two it starts spamming all that code. So i cant enter y+=dir after that, so i cant get it to work. Even when i did the X picture, it spammed the code. I dont know what to do, thank you.

    Comment by Cameorn — 2007.07.18 @ 06:05

  7. Great tutorial, thanks. It was a help for me, trying to get pygame to work.

    Comment by josh — 2007.07.18 @ 22:09

  8. @Cameorn: I’m not sure if IDLE might have issues with pygame’s event loop. I’ll have to test it and see.

    Also, poll() is known to eat CPU in extra large chunks. In tutorial #4 I will discuss alternatives to polling events. I’m not sure if that will make a difference..

    Comment by Lorenzo E. Danielsson — 2007.07.30 @ 03:48

  9. Hey man,

    thanks for the tutorial. i chose it after seeing a lot of other stuff that didn’t seem to cut it.

    I have a similar problem, I’m using IDLE on Python 2.5 and clicking the close button is not quitting the window. Just like Cameorn’s issue.

    any tips?

    Comment by DJ Fadereu — 2007.10.04 @ 11:24

  10. Correction. So I added a line to test what happens while closing the window:

    if event.type == pygame.QUIT:
    print “ho!”
    running = 0

    This time, it printed ho! in the IDLE interpreter and quit the window, but after a delay of about 5 seconds.

    What gives?

    Comment by DJ Fadereu — 2007.10.04 @ 11:27

  11. the window always hangs when I try to close it 😦

    It’s difficult to program anything this way..

    Comment by DJ Fadereu — 2007.10.07 @ 08:58

  12. I believe IDLE has a problem with pygame or something like that. I also have the hanging issue when executing the program in IDLE.

    Try running the program from the command line:

    python excercise1.py

    For me the window closes immediately and there are no issues.

    Comment by Lucian — 2007.11.30 @ 20:48

  13. […] feel rushed at all when checking out his tutorials.  Step by Step for total beginners.  Check out PyGame Tutorial Part 1 – Getting Started :: PyGame Tutorial Part 2 – Drawing Lines :: PyGame Tutorial Part 3 – Mouse Events :: PyGame […]

    Pingback by Python/PyGame Tutorials for Newbs | Newbie Game Programmers — 2008.01.03 @ 18:06

  14. IDLE has issues with pygame. I found that simply creating the scripts in a text editor and saving them as a .py file then running them from the command line (i.e. in windows cmd ‘python tut1.py’) allows things to work properly.

    You may also want to look at using a IDE such as eclipse with the pydev module

    Comment by DocBone — 2008.02.15 @ 17:04

  15. Would like to take a second just to thank you for this brilliant set of basic tutorials on the pygame lib, i’ve tried to learn pygame in the past, and found it did not inherit/learn anything from python except maybe its simplicity, but its a messy libary as it is..

    also would like to suggest adding afew links at the beginning of your tutorial for further reading, as i’ve noticed from reading through the comments that some people who are using these tutorials dont seem to have (maybe) the common sense that a coder gains through practice, and come across more like a coder with teething problems still (no offence) either way, your patience is appreciated and your effort even more so ^_^

    Comment by oOJINxOo — 2008.02.26 @ 11:51

  16. oOJINxOo: I think you’re right. I’ll put together a few links, both to gfx/game programming stuff, but also to general Python/Programming tutorials.

    I have a bit of a problem. On the one hand I realize that people should have a bit of programming background *before* they get started with game programming. On the other hand, it was specifically gfx and game programming that got me into coding (many, many years ago, on a VIC-20).

    I have always been an advocate of teaching people to program in a way that is fun and stimulating. Game programming is both. Writing business applications is dreadfully boring and turns people off programming.

    When I was a kid, we all new that to become good a programming, we had to write loads and loads of code. Nowadays, many people seem to have been seduced by this “Teach Yourself X in 24 hours” mentality. I try to add exercises as way to get my readers to write and learn to think beyond what I show them. But of course, to become really good the reader also needs to come up with their own challenges.

    In the end, I have a feeling that there are people who naturally challenge themselves and they will learn. The others will try out coding for a while and eventually give up.

    Comment by Lorenzo E. Danielsson — 2008.02.26 @ 12:47

  17. i think i know why pygame isnt working for you, it might be because you havent downloaded pygame off of pygame.org i think its pygame.org, i might be wrong… i am only 11, so, do u have an email, mark, so we could help eachother?

    Comment by person — 2008.07.28 @ 19:47


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.