你如何计算 KEYDOWN 的运行时间。 (Python)

How do you compute elapsed time for KEYDOWN. (Python)

我想知道如果按住某个键的时间更长,如何增加变量。我正在使用 Python 和 PyGame。 这是我的代码示例(速度、圈数和距离在前几行中定义):

distance_control = 1
for i in range(amount):
    x[i] += speedx[i]
    if x[i] >= 800:
        x[i] -= 800
        lap[i] += 1
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            x[2] += 1
    distance[i] = (lap[i] - 1)*800 + x[i]

我想知道如何让Space Bar按住的时间越长,speed_control就越高,最大speed_control为5,最好使用某种流逝的时间。

您可以使用 pygame.time.get_ticks() function which returns the time since the program start to compute the elapsed time. Set the start_time to the current time in the event loop when the user presses the key and in the while loop you can check if it is still held down with pygame.key.get_pressed() 并计算经过的时间。

import pygame as pg


def main():
    screen = pg.display.set_mode((320, 240))
    clock = pg.time.Clock()
    start_time = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    start_time = pg.time.get_ticks()

        keys = pg.key.get_pressed()
        if keys[pg.K_SPACE]:  # The spacebar is held.
            current_time = pg.time.get_ticks()
            elapsed_time = current_time-start_time  # milliseconds
            print(elapsed_time)

        screen.fill((30, 30, 30))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

如果您只想计算帧数:

import pygame as pg


def main():
    screen = pg.display.set_mode((320, 240))
    clock = pg.time.Clock()
    counter = 0

    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_SPACE:
                    counter = 0 # Set it back to 0.

        keys = pg.key.get_pressed()
        if keys[pg.K_SPACE]:  # The spacebar is held.
            # Increment the counter every frame.
            counter += 1
            print(counter)

        screen.fill((30, 30, 30))
        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()