我正在使用 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))
无论我在圆圈内的哪个位置单击, boolean 值仍然返回 False。
最佳答案
我不知道 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。
关于python - 单击圆圈内的任意位置时,使用 Python 验证鼠标位置是否在圆圈内。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003728/