gpt4 book ai didi

python - 如何计算 KEYDOWN 的耗时。 (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:53 26 4
gpt4 key购买 nike

我想知道如果按住某个键较长时间如何增加变量。我正在使用 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,最好使用某种耗时的东西。

最佳答案

您可以使用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()

关于python - 如何计算 KEYDOWN 的耗时。 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47764623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com