Detecting Mouse Click For every Sprites or Object in a Group

Viewed 72

I was a Making a Color Grid with random color using pygame.Color(random.choice(color_list)), putting all the cubes inside a group so i can just <GROUPNAME>.draw(screen), but I want to detect if a sprite is clicked in the group, here is my code:

import pygame
import sys
import os
import time
from asset import CreateAsset

pygame.init()
screen_size = screen_width, screen_height = 508, 436
screen = pygame.display.set_mode(screen_size)
running = True
count = 0
cubes = pygame.sprite.Group()
pox = 5
poy = 5
for i in range(19):
    for i in range(14):
        time.sleep(0.1)
        cubex = CreateAsset(pox, poy, 30)
        pox += 36
        cubes.add(cubex)
        count += 1
    pox -= pox
    pox += 5
    poy += 3

while running:

    screen.fill(pygame.Color("Black"))
    cubes.draw(screen)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    pygame.display.flip()
pygame.quit()
sys.exit()

The 'asset' is from onother file, it makes cubes, the poy and pox is the box's xy location. QUESTION: How to detect if a sprite is clicked in a group in pygame

1 Answers

Iterate through the pygame.sprite.Groupof pygame.sprite.Sprite objects and test if the mouse position is in the area (.rect attribute) of the Sprite with pygame.Rect.collidepoint:

while running:

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            cube_list = cubes.sprites()
            for i, cubex in enumerate(cube_list):
                if cubex.rect.collidepoint(event.pos):
                    print(f"clicked: {i}")
Related