2011-04-21 134 views
0

是的,那個標題根本沒有措辭。PyGame MOUSEBUTTONDOWN事件的菜單問題

好的,下面是我們所得到的 - 一個使用pyGame庫的Python程序,我們正在製作一款遊戲。我們從菜單環境main.py開始。當用戶點擊其中一個菜單按鈕時,執行一個動作。該程序將檢查使用下面的代碼上的菜單項點擊:

if event.type == pygame.MOUSEBUTTONDOWN: 
      mousePos = pygame.mouse.get_pos() 
      for item in buttons: # For each button 
       X = item.getXPos() # Check if the mouse click was... 
       Y = item.getYPos() # ...inside the button 
       if X[0] < mousePos[0] < X[1] and Y[0] < mousePos[1] < Y [1]: 
        # If it was 
        item.action(screen) # Do something 

當上了「玩遊戲」按鈕,用戶點擊,它會打開一個子模塊,playGame.py。在這個子模塊中是另一個pyGame循環等。

遊戲的一部分是讓鼠標左鍵在當前位置(「這是一個益智遊戲,它在上下文中有意義)」成長出來。這是我做這個代碼:

mouseIsDown == False 
r = 10 
circleCentre = (0,0) 

[...other code...] 

if mouseIsDown == True: 
    # This grown the circle's radius by 1 each frame, and redraws the circle 
    pygame.draw.circle(screen, setColour(currentColourID), circleCentre, r, 2) 
    r += 1 

for event in pygame.event.get(): 
    if event.type == pygame.QUIT: 
     runningLevel = False 

    elif event.type == pygame.MOUSEBUTTONDOWN: 
     # User has pressed mouse button, wants to draw new circle 
     circleCentre = pygame.mouse.get_pos() 
     mouseIsDown = True 

    elif event.type == pygame.MOUSEBUTTONUP: 
     # Stop drawing the circle and store it in the circles list 
     mouseIsDown = False 
     newCircle = Circle(circleCentre, r, currentColourID) 
     circles.append(newCircle) 
     circleCount += 1 
     r = 10 # Reset radius 

我的問題是,從主菜單中的用戶的點擊鼠標左鍵是堅持到playGame.py模塊,並導致它來創建並存儲一個新的圓,半徑10和位置(0,0)。這兩個都是默認值。

這隻發生在菜單後的一幀。

有什麼辦法可以防止這種情況發生,還是在我的代碼中存在缺陷?

一如既往,非常感謝所有幫助。如果您需要更多代碼或解釋這些片段,請告訴我。

如果您想要完整的代碼,它是on GitHub

回答

2

您可以在菜單中使用MOUSEBUTTONUP而不是MOUSBUTTONDOWN。

1

是否將pygame.event.clear()添加到Play的頂部修復它?

+0

雖然這是一個有效的答案,但我擔心它在我的項目中不起作用,因爲在之後立即創建了一個新的MOUSEBUTTONDOWN事件,因爲用戶在單擊菜單後仍然「握住」鼠標按鈕。雖然謝謝! – nchpmn 2011-04-22 00:19:54