PYTHON- PYGAME: How do I know if a mouse clicked on an image?

Maia F. picture Maia F. · May 19, 2013 · Viewed 12.1k times · Source

I'm making a basic level game where if i click a card, a picture will show. The pictures are randomly chosen. and so far, I have assigned random pictures to a card and the cards are shown face down. So if i click the card, i want the assigned picture (which is in a dictionary) to show.

I want to know how I can detect if I've clicked on an image (of the card) because the x,y coordinates of the image is on the top left. Right now, I'm trying to figure out a way to use the xy coordinates of the mouse click to detect if the image has been clicked on. Is there a way I could use 'collide' or is that making things too complicated? I'm a beginner programmer so I'm still trying to learn python and pygame :|

Answer

ninMonkey picture ninMonkey · May 21, 2013

Instead of hardcoding coords / using range, use the collision functions:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if ball.get_rect().collidepoint(x, y):
                # do swap