pygame中的鼠标按钮向下处理

问题描述:

我想检查左按钮何时被按下。在我的代码中,我检查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

保持一个鼠标按钮状态变量,并只计算点击,如果它以前没有关闭。

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 
    ...