Question

yes_box = Rectangle(Point(200, 150),Point(350,50))
yes_box.setOutline('blue')
yes_box.setWidth(1)
yes_box.draw(graphics_win)









def mouse_check(arg1): 
     ??????

Hey, have a quick question that is probably really obvious, but has me really stumped. So I am writing a program(a game) that requires you to click inside the boungs of the yes_box(as shown above). I am required to write a function that will check to see if the mouse click is inside the bounds of the rectangle, and return 'y' if it is, and 'n' if it isn't.

I know that you need to use the win.getMouse() and win.checkMouse() function, but I am not sure how to get python to determine if that click is in the bounds of the rectangle object? Any help would be greatly appreciated!

No correct solution

OTHER TIPS

You just need to get the point returned by win.getMouse() and make sure the x and y values are in bounds. I do that below in the inside function, then use this boolean value to display 'y' or 'n' on the window

from graphics import *      

def inside(test_Point, P1, P2):
    ''' 
    determines if the test_Point is inside
    the rectangle with P1 and P2 at opposite corners

    assumes P1 is upper left and P2 is lower right
    '''
    tX = test_Point.getX()
    tY = test_Point.getY()

    # first the x value must be in bounds
    t1 = (P1.getX() <= tX) and (tX <= P2.getX())

    if not t1:
        return False
    else:
        return (P2.getY() <= tY) and (tY <= P1.getY())


win = GraphWin("Box", 600, 600)

yes_box = Rectangle(Point(200, 150), Point(350, 50))
yes_box.setOutline('blue')
yes_box.setWidth(1)
yes_box.draw(win)

# where was the mouse clicked?
t = win.getMouse()

# is that inside the box?
if inside(t, yes_box.getP1(), yes_box.getP2()):
    text = 'y'
else:
    text = 'n'

# draw the 'y' or 'n' on the screen
testText = Text(Point(200,300), text)
testText.draw(win)

exitText = Text(Point(200,350), 'Click anywhere to quit')
exitText.draw(win)

win.getMouse()
win.close()

you could use this function:

p1 = rectangle.getP1()
rx1 = p1.getX()
ry1 = p1.getY()

p2 = rectangle.getP2()
rx2 = p2.getX()
ry2 = p2.getY()

x1 = point.getX()
y1 = point.getY()


if x1>=rx1 and y1<=ry1 and x1<=rx2 and y1>= ry2:

    return y
else: 
    return n 

where point should be the point in which the user has clicked. and rectangle is the rectangle in which you want to know if the user clicked or not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top