Using Python to verify the mouse position is within the circle, when clicking anywhere within the circle.

喜你入骨 提交于 2020-01-04 03:16:13

问题


I am working on a project within Python that is to determine the multi-tasking efficiency of a person. Part of the project is to have a user respond to an event on screen using the mouse. I have decided to have the user click within a ball. However I am having issues with my code on verifying that the mouse cursor is actually within the confines of the circle.

The code for the methods in question are below. Radius of the circle is 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))

No matter where I click within the circle, the boolean still returns False.


回答1:


I don't know pygame, but perhaps you want something like this:

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

This is the standard distance formula to get the distance between the mouse position and the center of the ball. Then you'll want to do:

return distance <= circle_radius

Also, for sqrt to work, you'll need to go from math import sqrt

NOTE: you could do something like:

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

which is more along the lines of what you have written - but that gives you an allowable area which is a square. To get a circle, you need to calculate distance as shown above.

NB: My answer assumes that mouse_position has properties x and y. I don't know if that's actually true because I don't know pygame, as I mentioned.




回答2:


You should not be using == to determine if your mouse_position is within that expression computing the allowable positions:

>>> (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:


Disclaimer. I also don't know pygame, but,

I assume mouse_position is the x,y co-ordinates of the mouse pointer, where x and y are integers but you are comparing them against the lists returned by range. This isn't the same as comparing whether they are in the lists.



来源:https://stackoverflow.com/questions/8003728/using-python-to-verify-the-mouse-position-is-within-the-circle-when-clicking-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!