每次点击一次如何使事情发生?

时间:2019-06-13 02:46:28

标签: python python-3.x pygame

当我将鼠标悬停在按钮上时,它会更改颜色,但是当我单击它时,我也想在列表中添加一个数字。我可以添加数字,但我希望每次点击只发生一次,

def button():
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if mouse[0] < 300 and mouse[1] < 300:
        topleft.color = (255, 0, 0)
        if click[0]:
            playerpattern.append(1)
    else:
        topleft.color = (100, 0, 0)

playerpattern = []

while playing:

    print(str(playerpattern))        

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

    button()
    win.fill((0, 0, 0))
    pygame.display.update()

pygame.quit()

如果按住该点击,则只会发送1的垃圾邮件。因此,如果您单击1秒钟太长时间,则会添加两个1。

2 个答案:

答案 0 :(得分:2)

这是@TheLazyScripter的代码的刺...

def button_hover():
    mouse = pygame.mouse.get_pos()

    if mouse[0] < 300 and mouse[1] < 300:
        topleft.color = (255, 0, 0)
    else:
        topleft.color = (100, 0, 0)

def clicky_button():
    mouse = pygame.mouse.get_pos()
    if mouse[0] < 300 and mouse[1] < 300:
        playerpattern.append(1)

playerpattern = []

while playing:

    print(str(playerpattern))        

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            playing = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            clicky_button()

    button_hover()
    win.fill((0, 0, 0))
    pygame.display.update()

pygame.quit()

实质上,您可以在for循环中检查多种事件类型。将悬停代码与点击代码隔离开来,因为您无需单击即可悬停。悬停时,请进行颜色更改。单击时,请单击代码。

答案 1 :(得分:0)

我认为通常会发生KEYDOWNKEYUP事件。如果您的问题是单击的时间可能太长,则可以使用计时器来忽略多个KEYDOWN事件,这些事件短于半秒。我认为,为了容错,您可以同时尝试侦听KEYUP事件和为多个KEYDOWN事件设置计时器。

我在PyGame网站上找到了一些示例代码:

def check_events(settings, screen, tile_map):
    """Watch for keyboard and mouse events"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(settings, event, screen, tile_map)
        elif event.type == pygame.KEYUP:
            check_keyup_events(settings, event, screen, tile_map)