1
votes

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?

1
Are you 100% sure that guess1 is a Sprite instance? It doesn't look like that. - sloth
@sloth It is a pygame.sprite.Group() Do I need to use the sprite itself? - Nico
@Valentino No, the example linked in the answer is gone, and I don't quite get what the rest of it is saying, because that's pretty much what I'm doing, at least as far as I can tell. - Nico

1 Answers

1
votes

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]
    # [...]