2011-11-04 148 views
3

我正在研究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。

+2

我不确定你会如何相信给定的代码会起作用... –

+2

我不确定你真的觉得你的评论对我有用。我不熟悉Python。 –

+0

这比“知道Python”要低得多。 –

回答

5

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

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

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

return distance <= circle_radius 

而且,开方工作,你需要去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,正如我所说的。

+0

有些搞乱了一些完美解决的代码!谢谢。 –

+0

另外需要注意的是,mouse_position从pygame.mouse.get_pos取得了返回元组(x,y)的值。解开这个元组之后,我可以继续进行计算。 –

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 
+0

这是我在代码中出错的地方之一。非常感激。不知道为什么我以前看不到。 –

1

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

我认为mouse_position是鼠标指针,其中xy是整数的x,y坐标,但你对抗range返回list小号比较它们。这与比较是否是中的的列表不一样。

+0

谢谢你,下面的评论完全显示了你解释的内容,我不确定为什么我以前看不到。从未使用过range(),并假定它的工作方式显然没有。感谢指针。 –

相关问题