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

标签 python pygame

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

event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT

但是我怎样才能检查他们是否双击了呢?还有什么方法可以检查用户是否向前或向后移动了滚轮?

最佳答案

我只是使用 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()

关于python - 如何检测用户是否在 pygame 中双击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918808/

相关文章:

python - 从服务器而非浏览器访问 API 时出现 403 错误

python - 仅包含 -1 和 1 的随机列表

python - AttributeError:元组对象没有属性移动(OOP)

python - Pygame错误: not able to open . wav文件

python - 使用 pandas 和 bokeh 创建带有分组的堆叠条形图

python - 在python和mysql中插入特定日期范围内的csv数据

python - 如何在导入的 3D 波前 OBJ 文件上实现对象碰撞

python - 当我点击移动时,如何为 pygame 角色行走设置动画

python - 如何在 Pygame 中插入 slider ?

python - while 循环无条件工作