2011-11-04 44 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(),並假定它的工作方式顯然沒有。感謝指針。 –