2

I'm having some trouble understanding how colliderect works with sprites. I have a good idea about it, but whenever I try to implement it into my game, I just get the error message "attributeError:'pygame.surface' object has no attribute 'rect'"

ufo_lvl_1 = pygame.image.load("ufo1.png") 
bullet = pygame.image.load("bullet.png")

class Bullet(pygame.sprite.Sprite):

    def __init__(self):
    # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self) 

        self.image = bullet
        self.damage = 5
        self.rect = self.image.get_rect()

    def update(self):
        if 1 == 1:
            self.rect.x += 15
        if self.rect.x >1360:
            self.kill()

class ufo1(pygame.sprite.Sprite):

    def __init__(self):

        pygame.sprite.Sprite.__init__(self)

        self.image = ufo_lvl_1
        self.health = 10
        self.rect = self.image.get_rect()
    def update(self):
        if 1==1:
            self.rect.x  -= 10
            if self.rect.colliderect(bullet.rect):
                self.health -= bullet.damage
                if self.health >= 0:
                    self.kill()
                bullet.kill()            

Basically all my sprites work (excluding ufo1), but the moment I create a ufo1 sprite it crashes and I don't know how to fix it.

Thanks in advance.

Nathaniel Mallet
  • 401
  • 2
  • 10
user2116429
  • 21
  • 1
  • 3
  • 1
    What is 'bullet' and where is it initialised? I ask because you have a line in the Bullet class that says "self.image = bullet", leading me to think that bullet is a Surface object, yet in the ufo1 class you're assuming that 'bullet' has a rect attribute. If bullet is a Surface at this point, then that's probably your problem. – R Hyde Feb 28 '13 at 22:25
  • oh right probaly should have included that in the question ill just edit the question – user2116429 Feb 28 '13 at 22:31
  • First, I would try to fix indentation in ufo1 class. – clime Feb 28 '13 at 22:40
  • 1
    My point is that your collision code in ufo1.update() is expecting to see a sprite called bullet, but it is instead seeing an image (Surface) called bullet. In effect, you're trying to make the sprite collide with an image, but you need to be colliding it with another sprite. – R Hyde Feb 28 '13 at 22:42
  • oh well its right in the code i just keeps having problems whenever i copy paste the code into questions – user2116429 Feb 28 '13 at 22:43

1 Answers1

0

you called your class Bullet and your surface for that class bullet. When you are calling colliderect you are having it check bullet instead of Bullet or whatever you named the object of class Bullet

Chachmu
  • 7,725
  • 6
  • 30
  • 35