'Ground' object has no attribute 'rect'

Viewed 28

I am new to pygame and coding in general and I am getting an error message that is confusing me.

I want detect collision between my player sprite and any of the sprites in the Ground() class. I try to use spritecollideany but I am getting the error message 'Ground' object has no attribute 'rect.'

My player class

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.x = x
        self.y = y
        self.image = pygame.image.load("marioLeft.png")
        self.rect = self.image.get_rect(midtop = (self.x, self.y))

    def Move(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_RIGHT]:
            self.x += 5
        if keys[pygame.K_LEFT]:
            self.x -= 5

    def Draw(self, surface):
        surface.blit(self.image, (self.x, self.y))

My ground class

class Ground(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.x = x
        self.y = y
        self.width = width
        self.height = height

        self.ground_surf = pygame.Surface((self.width, self.height))
        self.ground_rect = self.ground_surf.get_rect(midtop = (self.x, self.y))
        self.ground_surf.fill('White')

    def DrawGround():
        for entity in ground_sprites:
            screen.blit(entity.ground_surf, entity.ground_rect)

The code that is giving me an error message.

if pygame.sprite.spritecollideany(player, ground_sprites):
        pass
1 Answers

pygame.sprite.spritecollideany (and all other collision detection functions) uses the rect attributes of the pygame.sprite.Sprite objects to detect the collision. So each object needs to have a rect attribute. A sprite should also always have an image attribute which is needed for pygame.sprite.Group.draw.

Change the class Ground:

class Ground(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.rect = self.image.get_rect(midtop = (x, y))
        self.image.fill('White')

    def DrawGround():
        for entity in ground_sprites:
            screen.blit(entity.image, entity.rect)
Related