2016-11-08 49 views
0

我想檢查左按鈕何時被按下。在我的代碼中,我檢查click = pygame.mouse.get_pressed(),然後檢查點擊[0] == 1是否按下左按鈕。 這意味着我作爲鼠標單擊操作傳入的內容發生這麼長時間,點擊[0] == 1。我希望它只發生一次。任何幫助將不勝感激!pygame中的鼠標按鈕向下處理

def button(text, x, y, width, height, inactive_color, active_color, action = None): 
    cur = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()   
    print(click) 
    if x + width > cur[0] > x and y + height > cur[1] > y: 
     pygame.draw.rect(gameDisplay, active_color, (x,y,width,height)) 

    if click[0] == 1 and action != None:   # Button action definitions 

     if action == "quit": 
      print('quit') 
      return 0 
     if action == "intro": 
      print('intro') 
      return 1 
     if action == "play": 
      print('play') 
      return 2 
     if action == "replay":  
      print('replay') 
      #restart timer? 
      return 2 
     if action == "controls":   
      print('controls') 
      return 3 
     if action == "pause": 
      gamePause() 
     if action == "continue":     
      paused=False   

else: 
    pygame.draw.rect(gameDisplay, inactive_color, (x,y,width,height)) 

text_to_button(text,BLACK,x,y,width,height) 
+0

使用'if event.type == pygame.MOUSEBUTTONDOWN'(和'event.button == 1')。當按鈕將位置從「未按下」更改爲「按下」時,此事件僅創建一次,但在您按下時不會創建。但是,這將需要重建這個醜陋的'按鈕'功能到好的類'按鈕'即。 https://github.com/furas/my-python-codes/blob/master/pygame/button-hover/example-1.py – furas

回答

1

保持一個鼠標按鈕狀態變量,並只計算點擊,如果它以前沒有關閉。

mouse_state = pygame.mouse.get_pressed() 
while True: # game loop 
    pressed = pygame.mouse.get_pressed() 
    clicked = [p - s for p, s in zip(pressed, mouse_state)] 
    mouse_state = pressed 
    # now clicked[0] is: 1 if mouse clicked, 0 if no change, -1 is released 
    ...