Search code examples
pythonpygamerect

self.rect not found?


I have a program that is simply made to move an image around. I try to state the self.rect as part of a load_png() call, but it simply does not like it. THe reason I think this will work is from http://www.pygame.org/docs/tut/tom/games6.html, saying that this should work:

def __init__(self, side):
            pygame.sprite.Sprite.__init__(self)
            self.image, self.rect = load_png('bat.png')
            screen = pygame.display.get_surface()
            self.area = screen.get_rect()
            self.side = side
            self.speed = 10
            self.state = "still"
            self.reinit()

Here is my code, which according to the pygame tutorial from its own website, should work:

def _init_(self):
    pygame.sprite.Sprite._init_(self)
    self.state = 'still'
    self.image =  pygame.image.load('goodGuy.png')
    self.rect = self.image.get_rect()       
    screen = pygame.display.getSurface()

And it gives me this error:

Traceback (most recent call last):
File "C:\Python25\RPG.py", line 37, in <module>
screen.blit(screen, Guy.rect, Guy.rect)
AttributeError: 'goodGuy' object has no attribute 'rect'

If you guys need all of my code, comment blew and I will edit it.


Solution

  • You don't have a load_png function defined.

    You need to create the pygame image object before you can access its rect property.

    self.image = pygame.image.load(file)
    

    Then you can assign the rect value using

    self.rect = self.image.get_rect()
    

    Or you could create the load_png function as per the example you linked.