PYTHON- PYGAME: How do I know if a mouse clicked o

2019-05-17 20:33发布

问题:

This question already has an answer here:

  • Pygame mouse clicking detection 3 answers

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 :|

回答1:

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