使用Python验证鼠标点击位置是否在圆内。
我正在做一个Python项目,目的是测量一个人的多任务处理效率。这个项目的一部分是让用户用鼠标对屏幕上的一个事件做出反应。我决定让用户在一个圆圈内点击。不过,我在代码上遇到了一些问题,就是无法确认鼠标光标是否真的在这个圆圈里。
下面是相关方法的代码。圆圈的半径是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。
3 个回答
1
免责声明。我也不太懂pygame,不过,
我猜 mouse_position
是鼠标指针的 x,y
坐标,其中 x
和 y
是整数,但你把它们和 range
返回的 list
进行比较。这和判断它们是否在这些列表中是不同的。
1
你不应该用 ==
来判断你的 mouse_position
是否在计算允许位置的表达式内:
>>> (range(10,20), range(10,20))
([10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> (15,15) == (range(10,20), range(10,20))
False
5
我不太了解pygame,但也许你想要的东西像这样:
distance = sqrt((mouse_position.x - the_ball.x)**2 + (mouse_position.y - the_ball.y)**2)
这是一个标准的距离公式,用来计算鼠标位置和球心之间的距离。接下来你需要做的是:
return distance <= circle_radius
另外,要让平方根函数(sqrt)正常工作,你需要加上这行代码:from math import sqrt
注意:你可以做一些类似这样的事情:
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
这更接近你写的内容,但这样做会给你一个允许的区域,这个区域是一个正方形。如果你想要一个圆形,就需要像上面那样计算距离。
另外:我的回答假设mouse_position有x和y这两个属性。我不确定这是否真的成立,因为正如我提到的,我对pygame并不熟悉。