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

时间秒杀一切 提交于 2019-12-07 17:48:46

问题


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 


来源:https://stackoverflow.com/questions/16636250/python-pygame-how-do-i-know-if-a-mouse-clicked-on-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!