2014-12-03 25 views
0

所以我試圖讓我的主菜單「按鈕」。這不是所有的代碼,但它的部分我認爲可能是相關的。我已經通過打印語句/值進行了測試,當我按下按鈕時,它正在註冊鼠標,並且我知道文本的矩形(在這種情況下爲play_game_rect),所以通過跟隨另一個線程,我決定分配鼠標.get_pos()給變量mouse_position。然後我嘗試了collidepoint()並傳入了mouse_position變量。我覺得碰撞點()可能是這樣做的正確方法。我還證實,mouse_position確實包含我想要的x,y值。我認爲這可能只是一兩行來解決,但我被卡住了。點擊pygame中的呈現文字

for event in pygame.event.get(): 
     if event.type == QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type == MOUSEBUTTONDOWN: 
      mouse_position = pygame.mouse.get_pos() 

    if game_state == "Menu": 
     #Create Button Text 
     menu_main = headlines.render("Main Menu", True, WHITE) 
     play_game = standard.render("Play Game", True, WHITE) 
     instructions = standard.render("Instructions", True, WHITE) 
     # Get Button Dimensions 
     menu_main_rect = menu_main.get_rect() 
     play_game_rect = play_game.get_rect() 
     instructions_rect = instructions.get_rect() 
     #Blit Buttons 
     myWindow.blit(menu_main, (MENUX, MENUY)) 
     myWindow.blit(play_game, (MENUX, MENUY + 120)) 
     myWindow.blit(instructions, (MENUX, MENUY + 150)) 
     print play_game_rect 
     if play_game_rect.collidepoint(mouse_position): 
      game_state == "Game" 

回答

0

我認爲,這裏有在此仔細一看: http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect 會回答你的問題!

如果不是這樣,這裏的解決方案:

你get_rect得到的矩形總是有(0,0),x和y的值。但是,當你對錶面進行blit處理時,你會移動它們而不是rect。因此,按鈕矩形在那裏(嘗試點擊左上角的某處,看看會發生什麼),但不在按鈕圖像的相同位置。

爲了解決這個問題,你必須在RECT太轉移:

play_game_rect = play_game.get_rect() 
play_game_rect.x = MENUX 
play_game_rect.y = MENUY 

這樣做對每個按鈕,它應該工作。如果您不明白問題所在,請再問一次,這是您經常遇到的重要問題。

+0

我沒有注意到在打印我的矩形時在x和y上讀出了0。對於這個例子中的任何人,我必須做play_game_rect.y = MENUY + 120(因爲這是實際的play_game attritbute)。使用你的例子,它會觸發我的主菜單文本。無論哪種方式,這解決了它,並通過提供文檔中的位置,我會花更多的時間閱讀該部分,以確保我真的明白。我正在閱讀字體中的get_rect,並認爲這是我正在做的電話。謝謝一堆!我有點開始猜測這可能是一個問題,但我不確定。謝謝 – 2014-12-03 21:05:14

+0

當然,MENUY + 120,我忽略了這一點,對不起:)但現在一般的做法很明確,對吧?否則隨時問,很高興我可以幫助! – 2014-12-04 09:32:56