如何检测用户是否在pygame中双击?

Jae*_*Jae 6 python pygame

我知道我可以检查是否有左键单击

event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT
Run Code Online (Sandbox Code Playgroud)

但是如何检查他们是否双击了?还有什么方法可以检查用户是向前还是向后移动滚轮?

skr*_*krx 10

我只是使用clock.tick返回的增量时间值来增加计时器.在此示例中,您需要0.5秒才能双击,否则计时器将重置.

import sys
import pygame as pg


pg.init()

screen = pg.display.set_mode((640, 480))
BLACK = pg.Color('black')
FONT = pg.font.Font(None, 32)


def game():
    clock = pg.time.Clock()
    timer = 0
    dt = 0
    running = True

    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if timer == 0:  # First mouse click.
                        timer = 0.001  # Start the timer.
                    # Click again before 0.5 seconds to double click.
                    elif timer < 0.5:
                        print('double click')
                        timer = 0

        # Increase timer after mouse was pressed the first time.
        if timer != 0:
            timer += dt
            # Reset after 0.5 seconds.
            if timer >= 0.5:
                print('too late')
                timer = 0

        screen.fill(BLACK)
        txt = FONT.render(str(round(timer, 2)), True, (180, 190, 40))
        screen.blit(txt, (40, 40))
        pg.display.flip()
        # dt == time in seconds since last tick.
        # / 1000 to convert milliseconds to seconds.
        dt = clock.tick(30) / 1000


if __name__ == '__main__':
    game()
    pg.quit()
    sys.exit()
Run Code Online (Sandbox Code Playgroud)


Li-*_*Yip 4

我从未使用过pygame- 但是:

  • 检测双击:猜测,不是立即处理每次点击,而是应用 50 毫秒的延迟,看看在那段时间是否收到另一个点击事件。用户可能不会注意到 50 毫秒的延迟。

  • 区分滚轮向上/向下:请参阅本文档页面上的注释。显然定义了五个按钮 - 左、中、右、滚轮向上和滚轮向下。也就是说,您可以像捕获左键单击一样捕获滚轮事件 - 您只需要查找SCROLL_UP或 类似的而不是LEFT

    查阅文档以准确了解其SCROLL_UP名称。