使用Python来验证鼠标位置是圆圈,圆圈内的任何地方,当点击之内。 [英] Using Python to verify the mouse position is within the circle, when clicking anywhere within the circle.

查看:1849
本文介绍了使用Python来验证鼠标位置是圆圈,圆圈内的任何地方,当点击之内。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作Python中的一个项目,是决定一个人的多任务处理的效率。该项目的一部分,是有使用鼠标,屏幕上的事件响应用户。我决定有一个球内的用户点击。不过我有上验证鼠标光标实际上是圆的范围内与我的code的问题。

I am working on a project within Python that is to determine the multi-tasking efficiency of a person. Part of the project is to have a user respond to an event on screen using the mouse. I have decided to have the user click within a ball. However I am having issues with my code on verifying that the mouse cursor is actually within the confines of the circle.

的code所讨论的方法如下。圆的半径为10。

The code for the methods in question are below. Radius of the circle is 10.

    #boolean method to determine if the cursor is within the position of the circle
    @classmethod
    def is_valid_mouse_click_position(cls, the_ball, mouse_position):
        return (mouse_position) == ((range((the_ball.x - 10),(the_ball.x + 10)), 
                                 range((the_ball.y + 10), (the_ball.y - 10))))

    #method called when a pygame.event.MOUSEBUTTONDOWN is detected.
    def handle_mouse_click(self):
    print (Ball.is_valid_mouse_click_position(self.the_ball,pygame.mouse.get_pos))

不管在哪里我点击圆圈内,布尔仍然返回False。

No matter where I click within the circle, the boolean still returns False.

推荐答案

我不知道pygame的,但也许你想是这样的:

I don't know pygame, but perhaps you want something like this:

distance = sqrt((mouse_position.x - the_ball.x)**2 + (mouse_position.y - the_ball.y)**2)

这是标准的距离公式来获得鼠标的位置和球的中心之间的距离。然后你会想要做的:

This is the standard distance formula to get the distance between the mouse position and the center of the ball. Then you'll want to do:

return distance <= circle_radius

另外,对于开方工作,你需要去从数学进口开方

请注意:你的 的可以这样做:

NOTE: you could do something like:

x_good = mouse_position.x in range(the_ball.x - 10, the_ball.x + 10)
y_good = mouse_position.y in range(the_ball.y - 10, the_ball.y + 10)
return x_good and y_good

这是沿着你写什么,线条更 - 但是,给你一个允许的区域是的正方形的。为了得到一个圆,你需要计算距离,如上图所示。

which is more along the lines of what you have written - but that gives you an allowable area which is a square. To get a circle, you need to calculate distance as shown above.

注意:我的答案假定mouse_position具有属性x和y。我不知道,因为我不知道pygame的实际上是真实的,正如我提到的。

NB: My answer assumes that mouse_position has properties x and y. I don't know if that's actually true because I don't know pygame, as I mentioned.

这篇关于使用Python来验证鼠标位置是圆圈,圆圈内的任何地方,当点击之内。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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