How to check if an image is pressed pygame

Question:

I’m trying to make a cookie clicker clone, but my code can’t detect when the grandma button is pressed.

Here is my code:

import pygame


pygame.init()


display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Cookie Clicker')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
cookie = pygame.image.load('cookie.png')
grandma = pygame.image.load('grandma.png')
cookies = 0

def car(x,y):
    gameDisplay.blit(cookie, (x,y))

def grandshop(x,y):
    gameDisplay.blit(grandma, (xx,yy))

x =  0
y = 0
xx = 450
yy = 20

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True


        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            mouse_pos = pygame.mouse.get_pos()
            if cookie.get_rect().collidepoint(mouse_pos):
                if event.button == 1:
                    
                    cookies += 1
                    pygame.display.set_caption(f'Cookies: {cookies}')
                else:
                    break
            if grandma.get_rect().collidepoint(mouse_pos):
                print("It actually worked! :)")

    gameDisplay.fill(white)
    car(x,y)
    grandshop(xx,yy)
        
    pygame.display.update()
    
    clock.tick(60)
    
pygame.quit()
quit()

I had expected it to print out "It actually worked! :)" when the grandma image was clicked.

Asked By: omboybread

||

Answers:

Change appropriate lines in your code to:

if cookie.get_rect(topleft=(x,y)).collidepoint(mouse_pos):

and

if grandma.get_rect(topleft=(xx,yy)).collidepoint(mouse_pos):

The .get_rect() method called without parameter gives you the rectangle of the loaded image with the left upper corner set to (0, 0) and not to the actual position of the image on the screen. This was the reason why a click on cookie was also hconsidered to be a click on grandma and a click on grandma gave False as result of .collidepoint().

The .get_rect() method allows passing of a keyword parameter to obtain the rectangle coordinates of the rectangle moved to a with (x,y) specified screen position. The keyword used for this purpose in the code above is ,topleft=(xx,yy). Another known to me keyword parameter allowed in .get_rect() are center and bottomright.

Answered By: Claudio
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.