使用time.time()和Keydown测量时间 [英] Measure the time with time.time() and Keydown

查看:56
本文介绍了使用time.time()和Keydown测量时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从名为 sounds 的列表中播放声音.它播放声音,在 start 中存储声音播放的时间,等待6秒钟,然后播放列表中的下一个声音.现在,我想通过按下按键来捕获这6秒之间的反应时间.如果条件为true,则单击按钮,它将捕获时间并将其存储在 end 中.然后, end start 之间的区别应该给我结果.问题是,它无法正确衡量时间.即使单击之前我走了更长的路,它也总是给我千分之一.我想知道我在这里做错了吗?

I got sounds that I play from a list called sounds. It plays a sound, store the time when the sound is played in start, waits 6 seconds and plays the next sound from the list. Now I want to capture a reaction time between these 6 seconds with a keydown. If the condition is true then I click the button and it captures the time and store it in end. Then, the difference between end and start should give me the result. The problem is, that it does not measure the time right. It always gives me millisconds, even if I way longer bfore I click. I wonder what I am doing wrong here?

start = time.time()

    for i in range(len(arr)):
        pygame.mixer.music.load(sounds[i])
        pygame.mixer.music.play()

            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_RIGHT:

                        if condition:
                            end = time.time()
                            diff = end - start

            while pygame.mixer.music.get_busy():
                  time.sleep(6)

推荐答案

我认为最简单的解决方案是在下一个声音开始播放时重置开始时间.

I think the simplest solution would be to reset the start time when the next sound starts playing.

import time
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
SOUND = pg.mixer.Sound('a_sound.wav')

start = time.time()

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_RIGHT:
                diff = time.time() - start
                print(diff)

    passed_time = time.time() - start
    pg.display.set_caption(str(passed_time))
    if passed_time > 6:
        start = time.time()  # Reset the start time.
        SOUND.play()

    screen.fill(BG_COLOR)
    pg.display.flip()
    clock.tick(60)

pg.quit()

这篇关于使用time.time()和Keydown测量时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆