How to detect when a rectangular object, image or sprite is clicked

I'm trying to tell when a sprite, which must be part of a particular group (pygame.sprite.Group()), is clicked on. Currently I've tried creating a sprite which is just the mouses position and totally invisible, adding it to its own group, and using this code:

clickedList = pygame.sprite.spritecollide(guess1, mice, False)

where guess1 is the sprite getting clicked on and mice is the group containing the sprite that has the position of the mouse.

When I try this, I am told that "Group has no attribute rect". Where do I go from here?


Solution 1:

If you've a sprite (my_sprite) and you want to verify if the mouse is on the sprite, then you've to get the .rect attribute of the pygame.sprite.Sprite object and to test if the mouse is in the rectangular area by .collidepoint():

mouse_pos = pygame.mouse.get_pos()
if my_sprite.rect.collidepoint(mouse_pos):
    # [...]

The Sprites in a pygame.sprite.Group can iterate through. So the test can be done in a loop:

mouse_pos = pygame.mouse.get_pos()
for sprite in mice:
    if sprite.rect.collidepoint(mouse_pos):
        # [...]

Or get a list of the Sprites within the Group, where the mouse is on it. If the Sprites are not overlapping, then the list will contain 0 or 1 element:

mouse_pos = pygame.mouse.get_pos()
clicked_list = [sprite for sprite in mice if sprite.rect.collidepoint(mouse_pos)]

if any(clicked_list):
    clicked_sprite = clicked_list[0]
    # [...]