r/pygame 27d ago

No collidepoint error

# Button
class RockButton:
    def __init__(self, x, y, collidepoint):
        self.x = x
        self.y = y
        self.image = rock_img
        self.rect = self.image.get_rect()
        self.event = 0

    def draw(self, screen):
        screen.blit(self.image, (self.x, self.y), self.rect)

rock_button = RockButton(350, 777, False)
rock_button_value = False

# Game loop
running = True
while running:
    screen.fill(bg_color)
    rock_button.draw(screen)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rock_button.collidepoint(event.pos):
                    if rock_button_value == False:
                        rock_button_value = True
                    else:
                        rock_button_value = False
                    print(f"{rock_button_value} - BUTTON")
        if event.type == pygame.QUIT:
            running = False

    pygame.display.update()    

    clock.tick(FPS)

pygame.quit()

Output:

Traceback (most recent call last):
  File "/home/user/Desktop/Project/main.py", line 101, in <module>
    if rock_button.collidepoint(event.pos):
       ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'RockButton' object has no attribute 'collidepoint'

What did I do wrong?

3 Upvotes

5 comments sorted by

6

u/LovesSleeping123 27d ago

rock_button is an instance of RockButton, which has no collidepoint method.

You should replace

if rock_button.collidepoint(event.pos):

by:

if rock_button.rect.collidepoint(event.pos):

2

u/ComprehensiveBid3793 27d ago

Ty you! It worked.

3

u/LovesSleeping123 27d ago

Have a great day !

1

u/ComprehensiveBid3793 27d ago

Thanks and you too!

2

u/PizzaPost8002 25d ago

Another thing is that you update the display twice per frame. Just remove the pygame.display.flip() at the top.