如何计算KEYDOWN的已用时间。 (蟒蛇)

时间:2017-12-12 02:48:11

标签: python pygame elapsedtime

我想知道如果按键按下的时间更长,如何增加变量。我正在使用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]

我想知道如何制作它以便按住空格键的时间越长,speed_control越高,最大speed_control为5,最好使用某种经过时间的东西。

1 个答案:

答案 0 :(得分:1)

您可以使用pygame.time.get_ticks()函数返回自程序启动以来计算经过时间的时间。当用户按下键时,在事件循环中将start_time设置为当前时间,在while循环中,您可以检查它是否仍然按下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()