在pygame中按下鼠标按钮

时间:2016-11-08 17:37:12

标签: python pygame

我想检查按下左键的时间。在我的代码中,我检查click = pygame.mouse.get_pressed()然后通过检查单击[0] == 1来检查是否按下了左键。 这意味着我作为鼠标单击操作传入的内容发生这么长时间点击[0] == 1。我希望它只发生在ONCE。任何帮助将不胜感激!

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)

1 个答案:

答案 0 :(得分: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
    ...