1

I just wanted to know how I can check if a copy of an image is clicked in pygame. I know how to do this with a single picture, but I don't know how to do this efficiently with multiple copies of the same picture at the same time. This is the code I have right now but when I click on one of the images it doesn't print out the message:

import pygame

pygame.init()

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

random_rect = pygame.image.load('boomp.jpeg')
random_rect = pygame.transform.scale(random_rect, (150, 150))

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if random_rect.get_rect().collidepoint(x, y):
                print('clicked on image')

    screen.fill((255, 255, 255))

    screen.blit(random_rect, [70, 50])
    screen.blit(random_rect, [270, 50])
    screen.blit(random_rect, [470, 50])
    screen.blit(random_rect, [70, 250])
    screen.blit(random_rect, [270, 250])
    screen.blit(random_rect, [470, 250])
    screen.blit(random_rect, [70, 450])
    screen.blit(random_rect, [270, 450])
    screen.blit(random_rect, [470, 450])

    pygame.display.flip()

pygame.quit()

1 Answers1

1

Your current code will only check collision at <0, 0, 150, 150>

You should instead store the value returned by Surface.blit in a list and then iterate through all of them to check if there is a collision.

Example:

import pygame

pygame.init()

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

random_rect = pygame.image.load('boomp.jpg')
random_rect = pygame.transform.scale(random_rect, (150, 150))

lst = []
running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos
            if any(rect.collidepoint(x, y) for rect in lst):
                print('clicked on image')

    screen.fill((255, 255, 255))
    lst = []

    lst.extend([
    screen.blit(random_rect, [70, 50]),
    screen.blit(random_rect, [270, 50]),
    screen.blit(random_rect, [470, 50]),
    screen.blit(random_rect, [70, 250]),
    screen.blit(random_rect, [270, 250]),
    screen.blit(random_rect, [470, 250]),
    screen.blit(random_rect, [70, 450]),
    screen.blit(random_rect, [270, 450]),
    screen.blit(random_rect, [470, 450])
    ])

    pygame.display.flip()

pygame.quit()

note: if your points are going to remain the same then its better to define the rect and store them in a list outside the while loop

Art
  • 2,836
  • 4
  • 17
  • 34