Search code examples
pythonpygamerect

Pygame Collision script: AttributeError: 'pygame.Rect' object has no attribute 'rect'


So I have been making a small game using Pygame. This is just a test, and I am trying to make the player stand on the grass. However, when I run it I get AttributeError: 'pygame.Rect' object has no attribute 'rect'.

What's wrong? I've looked at other forums but no-one seems to have the same type of script.

import os


WIDTH, HEIGHT = 900, 500
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("cul game")

FPS = 60

PERSON_IMAGE = pygame.image.load(os.path.join("Character.png"))
PERSON = pygame.transform.scale(PERSON_IMAGE, (100, 100))

GRASS_IMAGE = pygame.image.load(os.path.join("Grass.png"))
GRASS = pygame.transform.scale(GRASS_IMAGE, (80, 80))

SPEED = 5


def collision(person, grass):
    collisions = pygame.sprite.collide_rect(person, grass)


def draw_window(person, grass):
    WINDOW.fill((30, 30, 30))
    WINDOW.blit(PERSON, (person.x, person.y))
    WINDOW.blit(GRASS, (grass.x, grass.y))
    pygame.display.update()


def main():
    person = pygame.Rect(-8, 300, 100, 100)
    grass = pygame.Rect(-8, 429, 80, 80)

    clock = pygame.time.Clock()
    run = True
    while run:
        collision(person, grass)
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys_pressed = pygame.key.get_pressed()

        if keys_pressed[pygame.K_a]:
            person.x -= SPEED
        if keys_pressed[pygame.K_d]:
            person.x += SPEED
        if keys_pressed[pygame.K_w]:
            person.y -= SPEED
        else:
            person.y += SPEED

        draw_window(person, grass)
    pygame.quit()


if __name__ == "__main__":```
    main()

Solution

  • person and grass are pygame.Rect objects. Hence you have to use pygame.Rect.colliderect, instead of pygame.sprite.collide_rect. pygame.sprite.collide_rect, is for the use with pygame.sprite.Sprite objects.

    colliderect is a method. Therefore either:

    collisions = pygame.sprite.collide_rect(person, grass)

    collisions = pygame.Rect.colliderect(person, grass)
    

    or

    collisions = person.colliderect(grass)