python鼠标点击后画圆,使用Python来验证鼠标位置是圆圈,圆圈内的任何地方,当点击之内。...

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值