【问题标题】:Using Python to verify the mouse position is within the circle, when clicking anywhere within the circle.当单击圆圈内的任意位置时,使用 Python 验证鼠标位置是否在圆圈内。
【发布时间】:2011-11-04 00:40:07
【问题描述】:

我正在使用 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。

【问题讨论】:

  • 我不确定您如何相信给定的代码会起作用...
  • 我不确定您是否真的觉得您的评论对我有用。我对 Python 不太熟悉。
  • 这个水平远低于“懂Python”。

标签: python boolean mouseevent pygame


【解决方案1】:

我不知道 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,正如我所提到的。

【讨论】:

  • 稍微弄乱了一些完美运行的代码!谢谢。
  • 还要注意,mouse_position 从 pygame.mouse.get_pos 中获取值,它返回一个元组 (x,y)。解压缩该元组后,我可以继续计算。
【解决方案2】:

您不应使用== 来确定您的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

【讨论】:

  • 这是我在代码中出错的地方之一。非常感激。不知道为什么我以前看不到。
【解决方案3】:

免责声明。我也不知道pygame,但是,

我假设mouse_position 是鼠标指针的x,y 坐标,其中xy 是整数,但您将它们与range 返回的lists 进行比较。这与比较它们是否在列表中不同。

【讨论】:

  • 谢谢,下面的评论完全显示了您的解释,我不知道为什么我以前看不到。从未使用 range() 并假设它以明显没有的方式工作。谢谢指点。
猜你喜欢
  • 2017-10-06
  • 2015-07-02
  • 1970-01-01
  • 2012-08-29
  • 2015-07-22
  • 2021-06-09
  • 1970-01-01
  • 2021-08-11
  • 2020-03-26
相关资源
最近更新 更多