PYTHON- PYGAME:我如何知道鼠标是否单击了图像? [英] PYTHON- PYGAME: How do I know if a mouse clicked on an image?

查看:870
本文介绍了PYTHON- PYGAME:我如何知道鼠标是否单击了图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个基本关卡游戏,如果单击卡,将会显示一张图片.图片是随机选择的.到目前为止,我已经为一张卡分配了随机图片,并且这些卡面朝下显示.因此,如果我单击该卡片,我希望显示指定的图片(在词典中).

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.

我想知道如何检测我是否单击了图像(卡上的图像),因为图像的x,y坐标位于左上方.现在,我正在尝试找出一种方法来使用鼠标单击的xy坐标来检测是否单击了图像.有没有一种方法可以使用碰撞",或者使事情变得过于复杂?我是一个初学者,所以我仍在尝试学习python和pygame:|

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

推荐答案

使用碰撞函数代替硬编码坐标/使用范围,

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 

这篇关于PYTHON- PYGAME:我如何知道鼠标是否单击了图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆