Mitch Cacciola
Mitch Cacciola

Reputation: 49

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

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.

Upvotes: 3

Views: 3014

Answers (3)

Ord
Ord

Reputation: 5843

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.

Upvotes: 5

tjm
tjm

Reputation: 7550

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.

Upvotes: 1

sarnold
sarnold

Reputation: 104050

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

Upvotes: 1

Related Questions