Creating a Game in Python Using PyGame – Part One


Prerequisites

In order to follow along with this tutorial you will need Python 2.4 and PyGame 1.7.0+ installed. Since I’m doing this all on a Mac and Python 2.4.2 is not available from MacPython or any other site as a disk image I decided to install from source.

If you are try to build Python on a Mac as well you should probably install into the /Library/Frameworks path as explained by this site.

Basically once you have downloaded the source from python.org unpack the tar ball as follows:

tar -zxvf Python-2.4.2.tgz

Once that has finished change to the Python-2.4.2 directory that was just created and install it by issuing the following commands:

./configure --enable-framework
make
sudo make frameworkinstall

For Windows or Linux you should be able to install easily given the instructions on the Python site.

This will install Python in the /Library/Frameworks path, and create a symlink to the python executable in /use/local/bin, which is not part of the PATH environment variable on new OS X builds, so you will probably want to add it:

export PATH=/usr/local/bin:$PATH

Part One

The full source of this tutorial can be downloaded here.

Python SnakeSo let’s actually start creating this game using PyGame. For our snake image in the game I’m going to use the snake to the left for now. As you can see I’m not artist, but I was able to install the gimp on my Mac and get that image to a point that I think is relatively acceptable. If anyone out there has any graphics skills and can whip me up a better looking python in a 64×64 png I’d gladly use it!

So the first thing we are going to do is create a new PyDev project in Eclipse. I’m going to use Python 2.4 for this project because it is the version that is compatible with my PyGame Installation.

Python foldersThen I’m going to create a new file called PyMan.py, this will be the main file of our game for now. The architecture may change as I go through this and discover better ways to use the files in my projects but for now this will work as a main file. In the directory that I create my project I will also create a subfolder entitled “data” and in that subfolder I will have another folder entitled “images” where I will store the above snake.png image.

Note: A lot of the information in this post was taken from the Pete Shinner’s great Line by Line Chimp and Python Pygame Introduction tutorials.

Now the first thing that we are going to have to do is import the libraries that we are going to need, we’ll also warn the user if the font or sound mixers are not available:

import os, sys
import pygame
from pygame.locals import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

Then we’re going to create a class called PyManMain, this is going to be the main class of our game, it will handle all of the main functions in our game, things like the game loop, the screen creation, and keeping track of all of our sprites:

class PyManMain:
    """The Main PyMan Class - This class handles the main 
    initialization and creating of the Game."""
    
    def __init__(self, width=640,height=480):
        """Initialize"""
        """Initialize PyGame"""
        pygame.init()
        """Set the window Size"""
        self.width = width
        self.height = height
        """Create the Screen"""
        self.screen = pygame.display.set_mode((self.width
                                               , self.height))

As you can see our __init__ function takes two optional parameters height and width, this will be the height and the width of the screen that we create. The __init__ function basically initializes pygame (pygame.init()) and then creates our main screen using the pygame.display.set_mode function.

So far so good! The next thing that we are going to need is a game loop, this is the loop that will process all of the events that PyGame sends our way. To do that, we’re going to add a function to our PyManMain class called MainLoop:

def MainLoop(self):
    """This is the Main Loop of the Game"""
    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: 
                sys.exit()

We’ll also add the code to our class that will start out game:

if __name__ == "__main__":
    MainWindow = PyManMain()
    MainWindow.MainLoop()

PyGame WindowIf you run this now you will be with a very uninspiring black screen. It may not be much but for the amount of code that we’ve written it’s pretty good.

The next thing that we need to create is out snake sprite. We are going to wrap our snake sprite in it’s own class called snake (of course) and it will be based off of the pygame.sprite.Sprite class. If you want to read more about PyGames sprite and group classes you should read piman’s great sprite tutorial:

class Snake(pygame.sprite.Sprite):
    """This is our snake that will move around the screen"""
    
    def __init__(self):
        pygame.sprite.Sprite.__init__(self) 
        self.image, self.rect = load_image('snake.png',-1)
        self.pellets = 0

As you can see the Snake class really isn’t doing much besides initializing the Sprite base class and loading the snake image. It also sets pellets to zero, this variable isn’t used yet but it is the number of pellets that our snake has eaten.

You’ll notice that we use load_image to load our snake image. This function is taken from the Line by Line Chimp tutorial. I created a new file for my project called helpers.py which will contain all helper functions. I put load_image in this file and added the following to the top of PyMan.py:

from helpers import *

Now we have to create an instance of our snake sprite and display it. To do this I created another function in the PyManMain class called LoadSprites, this function will take care of loading all of our sprites:

def LoadSprites(self):
    """Load the sprites that we need"""
    self.snake = Snake()
    self.snake_sprites = pygame.sprite.RenderPlain((self.snake))

This function creates the sprite (self.snake = Snake) and then creates a group that contains our snake sprite (self.snake_sprites = pygame.sprite.RenderPlain((self.snake))).

We are also going to have to make some changes to the MainLoop function, we are going to have to load all of our sprites before we enter the while loop:

"""Load All of our Sprites"""
self.LoadSprites();

Then after our event for loop but within the while loop we need to tell PyGame to draw our sprit:

self.snake_sprites.draw(self.screen)
pygame.display.flip()

Python SnakeNow we’re getting somewhere! We’ve got our little PyMan snake displaying himself in the top left corner of our screen. Not too bad.

The next thing that we’re going to want to do is create and display all of our pellets, this isn’t very difficult if you understood the snake sprite above you’ll understand this:

class Pellet(pygame.sprite.Sprite):
        
    def __init__(self, rect=None):
        pygame.sprite.Sprite.__init__(self) 
        self.image, self.rect = load_image('pellet.png',-1)
        if rect != None:
            self.rect = rect

Python pelletThe only difference you’ll see in the pellet class is the fact that we have an optional rect parameter, which lets us place the pellet where ever we want. The pellets I’ve created aren’t the best pellets that I’ve ever seen but just like the snake.png they’ll do for this example.

We then need to load the pellet sprites in our LoadSprites function:

"""figure out how many pellets we can display"""
nNumHorizontal = int(self.width/64)
nNumVertical = int(self.height/64)       
"""Create the Pellet group"""
self.pellet_sprites = pygame.sprite.Group()
"""Create all of the pellets and add them to the 
pellet_sprites group"""
for x in range(nNumHorizontal):
    for y in range(nNumVertical):
        self.pellet_sprites.add(Pellet(pygame.Rect(x*64, y*64, 64, 64)))

Then we have to draw the pellets in out MainLoop:

self.pellet_sprites.draw(self.screen)
self.snake_sprites.draw(self.screen)
pygame.display.flip()

Now it’s time to make that snake move, to do so we’re going to have to look at the event loop in our MainLoop. ( for event in pygame.event.get():) What we are going to do is move the snake around when the arrow keys are pressed. To do that we are going to check to see if the event is a KEYDOWN event, and if it is a key down event whether the key being pressed is one of the arrow keys:

if event.type == pygame.QUIT: 
    sys.exit()
elif event.type == KEYDOWN:
    if ((event.key == K_RIGHT)
    or (event.key == K_LEFT)
    or (event.key == K_UP)
    or (event.key == K_DOWN)):
        self.snake.move(event.key)

Then we have to add a move function to our snake class that will actually move our snake:

def move(self, key):
    """Move your self in one of the 4 directions according to key"""
    """Key is the pyGame define for either up,down,left, or right key
    we will adjust ourselves in that direction"""
    xMove = 0;
    yMove = 0;
    
    if (key == K_RIGHT):
        xMove = self.x_dist
    elif (key == K_LEFT):
        xMove = -self.x_dist
    elif (key == K_UP):
        yMove = -self.y_dist
    elif (key == K_DOWN):
        yMove = self.y_dist
    self.rect.move_ip(xMove,yMove);

You’ll notice that the move function references self.x_dist and self.y_dist, these are basically two integers that I set in the snake’s __init__ function, they are the number of pixels that we want the snake to move in the x or y direction. I set mine to 5.

To move the snake we adjust it’s rect so that the next time it is displayed it will be drawn in a different direction. To do that we call the rect.move_ip function with the amount of pixels in the x and y directions to move.

Now we are going to have to add some collision detection to make our snake eat our pellets. Thankfully the spirt and group classes have built in collision detection that we are able to use:

"""Check for collision"""
lstCols = pygame.sprite.spritecollide(self.snake
                                     , self.pellet_sprites
                                     , True)
"""Update the amount of pellets eaten"""
self.snake.pellets = self.snake.pellets + len(lstCols)

We use the pygame.sprite.spritecollide function to see if our snake sprite collided with any of the pellet sprites. If they did we kill which ever pellet that was hit by passing True as the third parameter. pygame.sprite.spritecollide basically goes through all of the sprites in the group passes and sees if the sprites rect intersects with the sprit passed in as parameter one.

pygame.sprite.spritecollide also returns a list of all the sprites that were collided by our snake, so we use that to update the number of pellets that we have eaten.

The last thing that we our going to do in this tutorial is display the number of pellets that we have eaten to the user:

if pygame.font:
    font = pygame.font.Font(None, 36)
    text = font.render("Pellets %s" % self.snake.pellets
                        , 1, (255, 0, 0))
    textpos = text.get_rect(centerx=self.width/2)
    self.screen.blit(text, textpos)

This code is taken from the line by line chimp example with very few changes. Instead of telling the user to hit the chimp for cash, we’re telling them how many pellets that the snake has eaten so far. We need to put the code right right before we draw our sprites in the game loop.

Python SnakeThat’s about it for this example, there is a bit of code in the finished “product” that I didn’t discuss but if you download the full source it the new code should be pretty self explanatory. Now this isn’t a full example by any means and probably isn’t something that you’d really want to base any game off of, but it does give you a pretty basic idea about what is required to create a game in using Python and PyGame.

If you are really interested in creating a game I’d suggest you download the full source and play around with it a bit. I’m also suggest (insist?) that you read the documentation and tutorials provided for you on the main PyGame site, if it wasn’t for them I would have been unable to write this simple tutorial.

Whew, that was a lot a typing, it’s time for me to go make some dinner and have a glass of wine.

Useful links:

  • http://www.pygame.org
  • http://www.pygame.org/docs/
  • http://www.pygame.org/wiki/tutorials
  • http://www.pygame.org/docs/tut/intro/intro.html
  • http://www.pygame.org/docs/tut/chimp/ChimpLineByLine.html
  • http://kai.vm.bytemark.co.uk/~piman/writing/sprite-tutorial.shtml
  • http://docs.python.org
  • http://www.python.org/
  • If you like this post remember to digg it.

    Note: Whew! Many thanks to James for finding the google cahce for me! I looked for it when I first deleted it but couldn’t fine it. Much appreciated!

    Here are some alternate images that were sent to me by a kind reader named Jordan:

    Python Snake
    Python Snake

    selsine

    del.icio.us del.icio.us

    64 Responses to “Creating a Game in Python Using PyGame – Part One”

    1. import this. » Blog Archive » Learning PyGame
      Says:

      [...] Learning Python has a new tutorial up called Creating a Game in Python Using PyGame. It’s part one of a series, and looks really good. [...]

    2. learning python » Blog Archive » Creating a Game in Python Using PyGame - Part Two - Creating a level
      Says:

      [...] learning python one man’s journey into python… « Creating a Game in Python Using PyGame – Part One [...]

    3. James
      Says:

      Hey, about the rest of your post…
      You should probably grab it from Google ASAP before they cache over it. If your too late, let me know, I’ve grabbed a copy from their cache.

      link.

    4. learning python » Blog Archive » Creating a Game in Python Using PyGame - Part 3 - Adding the bad guys
      Says:

      [...] All right in this section of the tutorial we are going to start adding the bad guys. If you are familiar with the changes that we made in part two it should be pretty clear to you how are are going to create these bad guys. If you haven’t already you should check out part one and part two. If you would like the full source and all of the images you can get it here. [...]

    5. Dr. Gizmo
      Says:

      If you want a good python image, go to the adress below and scale it down to 64 x 64 in GIMP. It actually scales to 67 x 64 or 64 x 61 but from there just resize the window, a few pixels don’t the appearance in this case. That is if your allowed to legally I don’t really know how all of that works…

      http://www.vanille.de/projects/python.spy

    6. izaac
      Says:

      which plugin are you using for syntax highlighting in wordpress ?

    7. selsine

      selsine
      Says:

      Hey Izaac I’m using this plugin right now:

      http://www.chroder.com/archives/2005/04/16/wordpress-codehighlight-plugin/

      There are a bunch of other ones, but this one seemed to work the best for me.

    8. Miguel
      Says:

      Hi!

      First, thanks for the tutorial – it’s very clearly written, and very informative!
      I have a question for you – I am using Mac as well, but I am stumbling upon a very odd problem: the images do not load!
      When I download your example, and try to run pyman.py (with the Python Launcher 2.4, I get a return in Terminal that states:
      “adm6-171:~ miguel$ “/Library/Frameworks/Python.framework/Versions/2.4/bin/python” “/Users/miguel/Desktop/PyMan/PyMan.py” && echo Exit status: $? && exit 1
      Cannot load image: data/images/snake.png
      Couldn’t open data/images/snake.png”
      And that’s it. I am quite puzzled (and a newbie to OSX, and to programming in general).
      Any clue about the reason?
      I am running Python 2.4.3, Pygame 1.7.0 (with py2app, numeric, pyobjc and pyopengl), and OSX 10.4.6 on a PPC machine.

      Thanks a lot for the help!

      /miguel sicart

    9. selsine

      selsine
      Says:

      Hi Miguel,

      First thanks for the kind words about this tutorial!

      If you have downloaded the zip file and unzipped all of its contents onto your desktop does the following file exist: “/Users/miguel/Desktop/PyMan/data/images/snake.png”?

      I think that it’s a problem with the current directory when you use the Python Launcher. To fix the problem try replacing this code in the helpers.py load_image function:

      fullname = os.path.join('data', 'images')
      fullname = os.path.join(fullname, name)

      With this:

      fullname = os.path.dirname(sys.argv[0])
      fullname = os.path.join(fullname, 'data')
      fullname = os.path.join(fullname, 'images')
      fullname = os.path.join(fullname, name)
    10. Miguel
      Says:

      Hi Selsine,

      Thanks for the help … but it does produce an error output:

      “Traceback (most recent call last):
      File “/Users/miguel/Desktop/PyMan/PyMan.py”, line 6, in ?
      from helpers import *
      File “/Users/miguel/Desktop/PyMan/helpers.py”, line 9
      fullname = os.path.join(fullname, ‘data’)
      ^
      SyntaxError: invalid syntax”

      I am wondering, the code you suggested changing – what does it exactly do? So, what would be the problem at hand here? (sorry for the very newbie questions, and thanks a bunch for the help!)

      cheers

      /m

    11. selsine

      selsine
      Says:

      Hi Miguel,

      The problem basically has to do with the working directory and how the relative path to the images is getting resolved. It you were to start a terminal and then browse to the /Users/miguel/Desktop/PyMan/ directory and launch the program using: >python PyMan.py the problem shouldn’t happen because the working directory will be set properly.

      The new code that I sent you is meant to create the full path to the images. I’m not sure why you are getting a syntax error as it’s working properly for me. Here is all of the code from my helpers file:

      #! /usr/bin/env python
      
      import os, sys
      import pygame
      from pygame.locals import *
      
      def load_image(name, colorkey=None):
      
      	fullname = os.path.dirname(sys.argv[0])
      	fullname = os.path.join(fullname, 'data')
      	fullname = os.path.join(fullname, 'images')
      	fullname = os.path.join(fullname, name)
      	try:
      		image = pygame.image.load(fullname)
      	except pygame.error, message:
      		print 'Cannot load image:', fullname
      		raise SystemExit, message
      	image = image.convert()
      	if colorkey is not None:
      		if colorkey is -1:
      			colorkey = image.get_at((0,0))
      		image.set_colorkey(colorkey, RLEACCEL)
      	
      	return image, image.get_rect()

      Don’t feel bad about asking questions!

    12. guiga
      Says:

      in program:
      import sys
      from pygame import *
      init()

      size=width, height= 320,240
      speed=[2,2]
      black=0,0,0
      screen = display.set_mode(size)
      ball = image.load(”ball.bmp”)
      ballrect = ball.get_rect()

      while 1:
      for event in pygame.event.get():
      if event.type == pygame.QUIT:
      sys.exit()
      ballrect = ballrect.move(speed)
      if ballrect.left width:
      speed[0] = -speed[0]
      if ballrect.top height:
      speed[1] = -speed[1]
      screen.fill(black)
      screen.blit(ball, ballrect)
      display.flip()

      when I run this program, the following message apeears:
      Traceback (most recent call last):
      File “C:\Documents and Settings\GUILHERME\Desktop\game.py”, line 9, in ?
      ball = image.load(”ball.bmp”)
      error: Couldn’t open ball.bmp

      which directory should be the file “ball.bmp”?

    13. selsine

      selsine
      Says:

      Hi guiga,

      ball.bmp should be in the same directory as your game.py file, you might want to look at the exmaple code that I created for Miguel, where I create the full path to a file.

    14. Kronos
      Says:

      umm..i get a syntax error

      >>> class PyManMain:
      The Main PyMan Class – This class handles the main initialization and creating of the game.

      SyntaxError: invalid syntax
      and “Main”, in “The Main PyMan Class” is highlighted

      why is this?

    15. selsine

      selsine
      Says:

      Hi Kronos,

      You have to make sure that everything is tabbed properly and that the comment is enclosed withing three quotes “”” i.e.:

      class PyManMain:
          """The Main PyMan Class - This class handles the main 
          initialization and creating of the Game."""

      Is that what your code looks like?

    16. please help me
      Says:

      all programs work as you said to download, but except eclipse. For example it doesn’t vairify “java runtime, or java VM.”
      i went to FAQs and it was very confusing.
      is there another kind of program thats like eclipse or eclipse?
      PLEASE HELP ME THE SUSPENCE IS KILLING ME YOU DON’T KNOW HOW LONG I WANTED TO START MAKING VIDIO GAMES!?

    17. selsine

      selsine
      Says:

      Hey Please Help Me,

      What OS are you trying to run Eclipse on? Depending on your operating system you may have to make different decisions.

      Also keep in mind that you don’t actually need to use Eclipse, you could use any text or python editor that you want.

    18. Oscar
      Says:

      Selsine,

      My only complaint here is that the proper usage of the pyDev Eclipse developement environment isn’t really addressed. You seem to mystically create a .py file outside of a package… etc. I managed to debug through the bitmap issue after using the pyDev debugger… Good work in general and cheers for your efforts.

    19. selsine

      selsine
      Says:

      Hi Oscar,

      You’re right I didn’t go into too much detail on using PyDev and Eclipse, some of that is because it’s not necessary to use those tools and you can get by just fine with a simple text editor if you choose. But perhaps it would be a good idea to outline some of the inner-workings of PyDev and Eclipse in a separate tutorial.

      I’m also not sure what you mean when you say that I “seem to mystically create a .py file outside of a package”? As far as I remember I selected File | New | File in Eclipse to create new *.py files, I haven’t been using Eclipse lately so my memory is a bit fuzzy.

      Now as far as the whole package thing is concerned, I assume that you are referring to Python packages? If so then yes I didn’t use a package since all of the files are located in the same directories you can simply import them with the “Import” command.

      If I’ve misunderstood what you mean please let me know, and I’ll try to improve the tutorial so that future users do not run into the same problems.

    20. paul stout
      Says:

      I think it is a neat program and I would love to use it

    21. Abby
      Says:

      the problem is

      When I press the right-arrow button and hold it, the snake will move right.
      Then I press the down-arrow button and hold it without release right-arrow button, the snake will move down.

      Then I release the right-arrow button ,the snake is stopped moving even the down-arrow button is still holded.(It should continue moving down.)

      How can i fix it.

    22. NKT
      Says:

      Abby,
      this is covered in part 2 of this (pretty cool) tutorial. You need to look at the key up event as well as the key down event.

    23. selsine

      selsine
      Says:

      NKT,

      Thanks for answering Abby’s question! Much appreciated!

    24. Kevin
      Says:

      im using the included IDLE with python 2.4, and have checked the code several times now, however, i keep getting this same msg
      ————————————————————————————-
      Traceback (most recent call last):
      File “C:/Program Files/Python 2.4/PyMan.py”, line 8, in -toplevel-
      class PyManMain:
      File “C:/Program Files/Python 2.4/PyMan.py”, line 27, in PyManMain
      MainWindow = PyManMain()
      NameError: name ‘PyManMain’ is not defined
      ————————————————————————————–
      this is my code

      import os, sys
      import pygame
      from pygame.locals import *

      if not pygame.font: print ‘warning fonts disabled’
      if not pygame.mixer: print ‘warning sound disabled’

      class PyManMain:
      “””main game class”””

      def __init__(self, width=640, height=480):
      “””initialize”””
      “””initialize PyGame”””
      pygame.init()
      “””set the window size”””
      self.width = width
      self.height = height
      “””create the screen”””
      self.screen = pygame.display.set_mode((self.width, self.height))
      def MainLoop(self):
      “””this is the main game loop”””
      while 1:
      for event in pygame.event.get():
      if event.type == pygame.QUIT:
      sys.exit()
      if __name__ == “__main__”:
      MainWindow = PyManMain()
      MainWindow.MainLoop()

    25. Kevin
      Says:

      gah, the spacing got messed up, but the tabulation is correct

    26. selsine

      selsine
      Says:

      Hi Kevin, looking at what you posted (not what showed up here) I can see the tabs, and the problem is that you have the last if block tabbed to be a member of the class:

      def MainLoop(self):
             """this is the main game loop"""
             while 1:
                 for event in pygame.event.get():
                     if event.type == pygame.QUIT:
                         sys.exit()
         if __name__ == "__main__":
             MainWindow = PyManMain()
             MainWindow.MainLoop()

      When it should actuallly be:

      def MainLoop(self):
             """this is the main game loop"""
             while 1:
                 for event in pygame.event.get():
                     if event.type == pygame.QUIT:
                         sys.exit()
      if __name__ == "__main__":
         MainWindow = PyManMain()
         MainWindow.MainLoop()

      Since the if block is supposed to be located outsite of the class.

    27. Kevin
      Says:

      ah cool, thanks selsine

    28. DbOyLeOn
      Says:

      Hey, I’m new to programming in Python, and I just have a simple question: the artwork that you put into python with bitmap(bmp) or .png files, how do you get rid of the extra color behind the picture? say for instance, I am using Gimp(which I am), how do I get rid of the extra white behind the picture? When I put an image into my game that I have made with gimp, it shows the extra area that I didn’t edit, so when my picture shows up in the game, it looks like a man with a white box around it. Any way I can get rid of that?

    29. selsine

      selsine
      Says:

      Hi DbOyLeOn,

      Take a look at the surface.set_colorkey function. It’s what you need to call in order to make the while around your character transparent.

      Actually it will make all the while in your image transparent, which is why people often use that terrible pink colour that I used as their background colour since it isn’t likely to appear in the rest of their image.

      Take a look at the load_image function works:

      def load_image(name, colorkey=None):
      
      	fullname = os.path.dirname(sys.argv[0])
      	fullname = os.path.join(fullname, 'data')
      	fullname = os.path.join(fullname, 'images')
      	fullname = os.path.join(fullname, name)
      	try:
      		image = pygame.image.load(fullname)
      	except pygame.error, message:
      		print 'Cannot load image:', fullname
      		raise SystemExit, message
      	image = image.convert()
      	if colorkey is not None:
      		if colorkey is -1:
      			colorkey = image.get_at((0,0))
      		image.set_colorkey(colorkey, RLEACCEL)
      	
      	return image, image.get_rect()

      If not passed the transparent colour key it tries to get it from the top left corner of the image.

      I hope this helps.

    30. DbOyLeOn
      Says:

      What do I have to edit into the load_image function to make the pink color transparent?

    31. DbOyLeOn
      Says:

      Thanks selsine this helped alot, it didn’t help directly, but I like a challenge. I didn’t work when I took this code and put it into my program, but I played around with it for a few hours, and it all fell into place. Since I want some hands on experience anyway, I’m actually glad it didn’t work right off. Thanks again.

    32. selsine

      selsine
      Says:

      Hi DbOyLeOn,

      Sorry I couldn’t get back to you any earlier I was on a short little trip. It’s also too bad that the code didn’t work for you, it may be because you didn’t have your transparent colour in the top left pixel?

      Either way I’m glad that you were able to figure it out, if you know what the problem was perhaps you could post it here so that it may help some other people in the future.

      Good luck with PyGame!

    33. pepe
      Says:

      Thanks to Selsine source code, Now it works for me

    34. JoeBob
      Says:

      Hi. I seem to be having a major problem with PyGame. I’m no wiz at computers, but I’m using a Dell with python 2.4 and pygame 1.7, yet pygame doesn’t seem to work right. I can get the blank PyGame window to come up, but once I add sprites or anything, and do everything I can to get rid of all the errors, it just closes when I run it! What’s even stranger is some pygame things I download will work, while others(Like the line by line chimp) will just close the instant I try to run them! If you have any idea of what might be going on, I would be very grateful! Thanks!

    35. selsine

      selsine
      Says:

      Hi JoeBob,

      How are you running the python script? If you are not running it from the windows command line, run it from there and see if there is anything (i.e. and error) that is printed out when you run it.

      Hopefully that information will let us know what the problem is.

    36. JoeBob
      Says:

      I’m sorry, but all it does is instantly close. I’ve gotten one thing to work: The Sprite tutorial, with the boxes. For the most part, that’s it. Everything else, if it has no errors, will just pull up the pygame window, wait a millisecond, and then close! I don’t know if there’s anything else I should download or anything, but I would if it could fix the problem. If there is anything, I’d try it! Thanks!

    37. selsine

      selsine
      Says:

      Hmm, so you don’t get any error messages when you run it from the commandline?

      Well then I would suggest adding some debug print messages to the code. For example:

      print "START: import"
      import os, sys
      import pygame
      from pygame.locals import *
      
      if not pygame.font: print 'Warning, fonts disabled'
      if not pygame.mixer: print 'Warning, sound disabled'
      print "END: import"
      if __name__ == "__main__":
          print "Entering Main function"
          MainWindow = PyManMain()
          print "Starting Main Loop"
          MainWindow.MainLoop()
          print "Exiting"

      And in perhaps a few other places. Then when you run from the command line, what the program spits out should let us know how far the execution is going and perhaps why it isn’t working.

    38. potte
      Says:

      THis tutorial is great!! I have learnt a lot with it! Thanks for writing it!! I have a question about loading images : I cant load any image. i tried ur path programme-doesnt work, i tried other programs-doesnt work. pls help i tried all kind of formats, but it allways say:Couldnt open image. pls help

    39. selsine

      selsine
      Says:

      Hi Potte,

      What OS are you running on? How are you launching your pythong applicaction? Can you load any files?

      What happens if you try replacing the load_image function with the following? Does it work? What gets printed out?

      def load_image(name, colorkey=None):
      
      	fullname = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
      	fullname = os.path.join(fullname, 'images')
      	fullname = os.path.join(fullname, name)
      	print fullname
      	try:
      		image = pygame.image.load(fullname)
      	except pygame.error, message:
      		print 'Cannot load image:', fullname
      		raise SystemExit, message
      	image = image.convert()
      	if colorkey is not None:
      		if colorkey is -1:
      			colorkey = image.get_at((0,0))
      		image.set_colorkey(colorkey, RLEACCEL)
      	
      	return image, image.get_rect()
    40. potte
      Says:

      Hi!
      it says global name ‘__file__’ is not defined,though i only tried importing sys and os.
      All the books say that the pic and the prog should be in the current directory,but in doesnt work for me on win xp.
      Also when i try running a script (with the if __name__=’__main__’:)by double-clicking on it, a black window pops up and disappears again. I tried putting raw_input at the end, but it doesnt work
      And for ur quetions: i use win xp , i tried launching it by double-clicking,importing,or running it in the shell , yes, as far as i can remember once i loaded a textfie,i can import and save with no problem. i really dont know what to do know , i read severla books on the issue, but i cant find the problem
      potte

    41. selsine

      selsine
      Says:

      Hi Potte,

      What version of Python are you using? The __file__ attribute was introduced in version 2.2 or 2.3 I believe.

      Did you try this version of the function:

      def load_image(name, colorkey=None):
      
      	fullname = os.path.dirname(sys.argv[0])
      	fullname = os.path.join(fullname, 'data')
      	fullname = os.path.join(fullname, 'images')
      	fullname = os.path.join(fullname, name)
      	try:
      		image = pygame.image.load(fullname)
      	except pygame.error, message:
      		print 'Cannot load image:', fullname
      		raise SystemExit, message
      	image = image.convert()
      	if colorkey is not None:
      		if colorkey is -1:
      			colorkey = image.get_at((0,0))
      		image.set_colorkey(colorkey, RLEACCEL)
      	
      	return image, image.get_rect()
    42. madan
      Says:

      hey man

      just wan to thank you for this post. I had no clue of pygames 4 days back and today i am done creating a cool soccer game with 3 players . your tutorial gave a great start and now i am done with my project!!! wooooh!!!! thanks again

    43. TheRazor
      Says:

      Simple, but nice coding. What about using some AI and place 2 or 3 enemies.

    44. B
      Says:

      where do you add self.LoadSprites();
      it doesnt load the snake image!
      thnx

    45. Jonny
      Says:

      [dude@localhost Game]$ python PyMan.py
      Traceback (most recent call last):
      File “PyMan.py”, line 25, in
      MainWindow.MainLoop()
      AttributeError: PyManMain instance has no attribute ‘MainLoop’
      [dude@localhost Game]$

      Help?

    46. Jord
      Says:

      Great way to learn the basics of Python. Thanks!

    47. Algo de programaciÄ‚Å‚n « El Planeta DistÄ‚Å‚pico
      Says:

      [...] por un buen blog sobre Python (que estĂĄ en inglĂŠs, lamentablemente), encontrĂŠ un interesante tutorial, sobre como hacer un juego (muy muy bĂĄsico, aparentemente) con Python y [...]

    48. Alex
      Says:

      Hey, I found a great python sprite (okay well maybe its a cobra) here:
      http://sdb.drshnaps.com/sheets/Misc/Misc/Mobile/PuzzleWorld2.png

    49. satish yerramsetti
      Says:

      thanx man that helped alot

    50. PyGame, window is not closing, tut not helping | keyongtech
      Says:

      [...] window is not closing, tut not helping im doing this : http://www.learningpython.com/2006/0…game-part-one/ and when closing the program the window stays up and doesnt respond. i tried adding this: [...]

    51. webebe
      Says:

      I just want to say thank you! A great tutorial….nice work. Finally a tutorial which explains things to me in human language so that even I can understand it ;-) Keep up the good work!!

    52. Pygame Tutorials and Pygame Assignment 1 « SCHS - Computer Engineering and Programming
      Says:

      [...] Introduction and Part One [...]

    53. niek
      Says:

      when i try to load the system i get a black screen and an error called: cannot open /data/images/snake.png!

    54. The Aspiring Game Developer’s Web Guide « How to create games
      Says:

      [...] Creating a Game in Python using Pygame Good tutorial with rich code examples. [...]

    55. BirdaoGwra
      Says:

      thanks for the tut. i m a newbee to python, today is my first day with python environment. i just run ur tut and is working fine (windows XP with Python 2.5). just it gets crashed when i close(don’t understand, will know soon). anyway thank u for the tut.

    56. Gilson - Brazil
      Says:

      Hey man, first i wanna congratulate you for the tutorial. I have managed to learn a lot but i still have a few doubts and im wondering if you could help me with then.

      The major one is that, with that kind of movement sometimes the snake aint into the propper position to go into the pellets way you know, so i have to go back and forth to adjust it into the right position to so i can turn to the desire position. Im not sure if im explaining it propperly. So, is it possible for me to make the snake move exactly one block for each movement? Instead of a free movement to any desire position? That would solve the problem im having.

      Thanks for the tutorial and i would appreciate if you could help me out.

    57. stealthcopter.com » Advancing PyMan (using python’s pygame to recreate pacman)
      Says:

      [...] original code from was learningpython.com (not 100% sure) and the following links to the tutorials: Tutorial 1 Tutorial 2 Tutorial [...]

    58. Michael
      Says:

      I love your tutorials. Have you ever considered playing around with a “roguelike” version?

    59. Deepak
      Says:

      Hey Selsine,
      Really very informatic.. nyc job from ur side :)
      But i need some help as we r building a path nevigation system to find the sortest path on a loaded map using pygame , run a car on that path and making map path blocking sensitivity enable and we all(in group) are newbie with pygame and python as well… So how we can proceed v hav python2.6.2 installed on windows7 OS.

      Waiting for ur kind responce!!

    60. Ryan
      Says:

      hey, i have the program written exactly like it should, but when i run it nothing happens. it doesnt say there is an error, but the screen doesn not open at all. i am using python 3.1 so i dont know if the codes are the same? i know this tut is if from a while ago, but i wantes to try it haha :)

    61. Purses For Cheap
      Says:

      Purses For Cheap…

      [...]learning python » Blog Archive » Creating a Game in Python Using PyGame – Part One[...]…

    62. will
      Says:

      I keep getting ‘main()’ not defined-

      import pygame,time,sys,random,os
      from pygame.locals import*

      print “end import”

      WHITE=(255,255,255)

      class main:
      print “main”
      “””main game class”””
      def __init__(self,width=640,height=480):
      print “def _init_”
      “””initialise”””
      “””initialise pygame”””
      pygame.init()
      “””set the window size”””
      self.width=width
      self.height=height
      “””create the screen”””
      self.screen=pygame.display.set_mode((self.width,self.height))

      def mainLoop(self):
      “””game loop(main)”””
      while True:
      for event in pygame.event.get():
      if event.type==pygame.QUIT:
      pygame.quit()
      sys.exit()

      self.screen.fill(WHITE)

      if __name__==”__main__”:
      print “entering main function”
      mainWindow=main()
      print “starting main loop”
      mainWindow.mainLoop

    63. aidan
      Says:

      will,

      Did you put in the tabs after the defs and other loops? From the way my browser sees it, there are no tabs.

    64. Computing Society - Social Hack Day (19th Oct 2013) – PyGame
      Says:

      [...] Creating a Game in Python Using PyGame [...]

    Leave a Reply

     

    Popular Posts