以下是我正在使用的模块:http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf
我想知道用户的点击是否在一个形状内。我使用了in运算符,但我知道这是不正确的。下面是我的一大块代码:
win = GraphWin("Click Speed", 700, 700)
theTarget = drawTarget(win, random.randrange(0,685), random.randrange(0,685))
while theTarget in win:
click = win.getMouse()
if click in theTarget:
print("Good job")
我省略了绘制目标形状的代码,因为它是长度且不必要的。 这是一个动人的圈子。
我正在使用while循环,因此它可以让我不断获得用户的点击。
如何使用getMouse()命令检查用户的点击是否在指定的目标形状中?
我将来必须使用它来获得更抽象的形状(不是简单的圆圈)。
答案 0 :(得分:0)
对于圆的简单情况,您可以使用距离公式确定鼠标是否在内部。例如:
# checks whether pt1 is in circ
def inCircle(pt1, circ):
# get the distance between pt1 and circ using the
# distance formula
dx = pt1.getX() - circ.getCenter().getX()
dy = pt1.getY() - circ.getCenter().getY()
dist = math.sqrt(dx*dx + dy*dy)
# check whether the distance is less than the radius
return dist <= circ.getRadius()
def main():
win = GraphWin("Click Speed", 700, 700)
# create a simple circle
circ = Circle(Point(350,350),50)
circ.setFill("red")
circ.draw(win)
while True:
mouse = win.getMouse()
if inCircle(mouse,circ):
print ("Good job")
main()
对于椭圆的更高级示例,我们需要使用找到here的公式。这是实现的功能:
def inOval(pt1, oval):
# get the radii
rx = abs(oval.getP1().getX() - oval.getP2().getX())/2
ry = abs(oval.getP1().getY() - oval.getP2().getY())/2
# get the center
h = oval.getCenter().getX()
k = oval.getCenter().getY()
# get the point
x = pt1.getX()
y = pt1.getY()
# use the formula
return (x-h)**2/rx**2 + (y-k)**2/ry**2 <= 1
对于abitrary形状的多边形,我们需要引用this。我已经将它转换为python等效的你。检查链接,了解它的工作原理,因为我老实说不确定
def inPoly(pt1, poly):
points = poly.getPoints()
nvert = len(points) #the number of vertices in the polygon
#get x and y of pt1
x = pt1.getX()
y = pt1.getY()
# I don't know why this works
# See the link I provided for details
result = False
for i in range(nvert):
# note: points[-1] will give you the last element
# convenient!
j = i - 1
#get x and y of vertex at index i
vix = points[i].getX()
viy = points[i].getY()
#get x and y of vertex at index j
vjx = points[j].getX()
vjy = points[j].getY()
if (viy > y) != (vjy > y) and (x < (vjx - vix) * (y - viy) / (vjy - viy) + vix):
result = not result
return result