簡體   English   中英

python zelle graphics checkMouse()?

[英]python zelle graphics checkMouse()?

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): 
     ??????

嘿,有一個簡短的問題可能很明顯,但是我真的很困惑。 因此,我正在編寫一個程序(游戲),要求您在yes_box的框內單擊(如上所示)。 我需要編寫一個函數來檢查鼠標單擊是否在矩形的邊界內,如果是,則返回“ y”,如果不是,則返回“ n”。

我知道您需要使用win.getMouse()和win.checkMouse()函數,但是我不確定如何獲取python以確定該單擊是否在矩形對象的邊界內? 任何幫助將不勝感激!

您可以使用以下功能:

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 

點應該是用戶單擊的點。 矩形是您要知道用戶是否單擊的矩形。

您只需要獲取win.getMouse()返回的點,並確保x和y值在范圍內即可。 我在inside函數中執行以下操作,然后使用此布爾值在窗口上顯示“ y”或“ n”

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM