Skip to main content
GameDev.net gamedev.net
🔒 Locked 🎮 Unity

Problem with Pygame sprites

Started by Zyndrof Jul 4, 2007 at 3:24 PM 4 replies 2.2k views
Original Post
Zyndrof
Zyndrof
Hi there! I have some problems with viewing a sprite on a black screen with pygame. I want to make a pacman clone as my first project since I belive it is about hard enough. I have two modules, one that creates the pacman and one that at the moment only tries to show him on the screen. When I run the program I see a black screen that instantly dissapears, and I can't see a trace of my Pacman in there. Could you show my whats wrong and please tell me why it's wrong. Thanks in advance. pacman.py
""" The pacman module, containing info
    about mr. Pacman himself. """
import pygame
pygame.init()

class Pacman(pygame.sprite.Sprite):
    """ The class that creates Pacman """
    
    location = "data/pacman.gif"

    def __init__(self, posX, posY):
        """ Creates the creature """
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(location)
        self.image = self.image.convert()
        self.rect = self.image.get_rect()
        self.rect.centerx = posX
        self.rect.centery = posY
game.py
""" pacman clone by Christoffer Lejdborg
    http://zyngame.wordpress.com/ """

import pygame
pygame.init()

def main():
    # set up the display
    screen = pygame.display.set_mode((390, 390))
    pygame.display.set_caption("Pacman clone")

    # set up the background
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((0, 0, 0))
    screen.blit(background, (0, 0))

    hero = pacman.Pacman.__init__(100, 150)

    # set up tha main loop
    keepGoing = True
    clock = pygame.time.Clock()
    pygame.mouse.set_visible(False)

    allSprites = pygame.sprite.Group(hero)

    while keepGoing:
        clock.tick(30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False

        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)

        pygame.display.flip()

    pygame.mouse.set_visible(True)

if __name__ == "__main__":
    main()
Vorpy
Vorpy
Try running the program from the command line. If there's an uncaught python exception, then python will catch it and print it out just before exiting. In this case I think the problem is that "pacman" is undefined in game.py. Another problem: do not explicitly call __init__ when you are creating an object. The only time you should explicitly call __init__ is to call the constructor of a parent class (or maybe if you're doing something really tricky, but that sort of trickiness is usually frowned upon in python unless there's a darned good reason for it). The class itself functions as the constructor, and it does some stuff before it calls its __init__ method.

Add the line "import pacman" at the top of game.py, and change "hero = pacman.Pacman.__init__(100, 150)" to "hero = pacman.Pacman(100, 150)".
daviangel
daviangel
Quote:
Original post by Vorpy
Try running the program from the command line. If there's an uncaught python exception, then python will catch it and print it out just before exiting. In this case I think the problem is that "pacman" is undefined in game.py. Another problem: do not explicitly call __init__ when you are creating an object. The only time you should explicitly call __init__ is to call the constructor of a parent class (or maybe if you're doing something really tricky, but that sort of trickiness is usually frowned upon in python unless there's a darned good reason for it). The class itself functions as the constructor, and it does some stuff before it calls its __init__ method.

Add the line "import pacman" at the top of game.py, and change "hero = pacman.Pacman.__init__(100, 150)" to "hero = pacman.Pacman(100, 150)".


Yup you pretty much got everything except for the image variable location needs to be moved inside the constructor since otherwise program will still fail due to location not defined error.
Another way to do it if you don't want to make all them changes and don't want to use multiple files is to do it this way you are first learning:
""" pacman clone by Christoffer Lejdborg    http://zyngame.wordpress.com/ """import pygamepygame.init()class Pacman(pygame.sprite.Sprite):    """ The class that creates Pacman """            def __init__(self, posX, posY):        """ Creates the creature """        pygame.sprite.Sprite.__init__(self)        location = "data/pacman.gif"        self.image = pygame.image.load(location)        self.image = self.image.convert()        self.rect = self.image.get_rect()        self.rect.centerx = posX        self.rect.centery = posYdef main():    # set up the display    screen = pygame.display.set_mode((390, 390))    pygame.display.set_caption("Pacman clone")    # set up the background    background = pygame.Surface(screen.get_size())    background = background.convert()    background.fill((0, 0, 0))    screen.blit(background, (0, 0))    hero = Pacman(100, 150)    # set up tha main loop    keepGoing = True    clock = pygame.time.Clock()    pygame.mouse.set_visible(False)    allSprites = pygame.sprite.Group(hero)    while keepGoing:        clock.tick(30)        for event in pygame.event.get():            if event.type == pygame.QUIT:                keepGoing = False        allSprites.clear(screen, background)        allSprites.update()        allSprites.draw(screen)        pygame.display.flip()    pygame.mouse.set_visible(True)if __name__ == "__main__":    main()

Good luck on your game and pygame since it really is the easiest/fastest way to make games!
Later on when you get the basics down you can start adding error checking and more functions to your game like the following useful one:
def load_image(name):  fullname = os.path.join('data',name)    try:      image = pygame.image.load(fullname)    except pygame.error, message:      print 'Cannot load:', name      raise SystemExit, message    image = image.convert()return image, image.get_rect()

[size="2"]Don't talk about writing games, don't write design docs, don't spend your time on web boards. Sit in your house write 20 games when you complete them you will either want to do it the rest of your life or not * Andre Lamothe
Zyndrof
Zyndrof
After using the code that deviangel gave me i get these errors:

C:/Python25/pythonw.exe -u "C:/Documents and Settings/Christoffer/Skrivbord/pygame/_Projects/Pacman clone/game.py"
Traceback (most recent call last):
File "C:/Documents and Settings/Christoffer/Skrivbord/pygame/_Projects/Pacman clone/game.py", line 55, in
main()
File "C:/Documents and Settings/Christoffer/Skrivbord/pygame/_Projects/Pacman clone/game.py", line 31, in main
hero = Pacman(100, 150)
File "C:/Documents and Settings/Christoffer/Skrivbord/pygame/_Projects/Pacman clone/game.py", line 13, in __init__
location = LoadImage("data/pacman.gif")
NameError: global name 'LoadImage' is not defined

Could you help me decifer and solve this one?
Oluseyi
Oluseyi
a.) Decipher.

b.) You changed daviangel's code. His read:
location = "data/pacman.gif"self.image = pygame.image.load(location)


Yours reads:
location = LoadImage("data/pacman.gif")


Why did you add LoadImage()? Do you have a function named LoadImage()? Do you randomly add pieces of code that you don't understand and just expect them to work?

daviangel's code creates a local variable named location to store the file path, and then calls pygame.image.load() to load that image into the instance variable self.image. If you want to change anything, do this:
self.image = pygame.image.load("data/pacman.gif")

His local variable, strictly speaking, is unnecessary right now.
Zyndrof
Zyndrof
Thanks, that did the trick! And sorry for my falty use of the word dechiper, I will just say it is because English is only my second language ;)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.