我正在尝试使用 pygame for gui 在 python 中创建一个反应时间测试游戏。因为,我对这项技术相当陌生,所以我被困在部分代码上,即如何注册更多按键,然后相应地记录时间。
这是我到目前为止的代码:
import pygame
from datetime import datetime
import time
import random
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Reaction Time Test")
font = pygame.font.SysFont(None, 30)
text = font.render("PRESS ANY KEY TO START TEST", 0, (255,255,255))
w = font.render("PRESS ANY KEY",0,(0,255,0))
count = 0
screen.blit(text, (150,240))
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if count <= 5 and event.type == pygame.KEYDOWN:
screen.fill(pygame.Color("black"))
pygame.display.flip()
wait_time = random.randint(1,4)
time.sleep(wait_time)
reaction_start = datetime.now()
print(reaction_start)
screen.blit(w,(225,200))
count = count + 1
if event.type == pygame.KEYDOWN:
reaction_end = datetime.now()
print(reaction_end)
t = reaction_end - reaction_start
print(t)
f = font.render("REACTION TIME: "+ str(t),0,(255,255,255))
screen.blit(f,(225,300))
if count > 5:
screen.fill(pygame.Color("black"))
pygame.display.flip()
s = font.render("AVERAGE REACTION TIME IS: ",0,(255,255,255))
screen.blit(s,(150,200))
pygame.display.flip()
我坚持的部分是这个代码片段
if count <= 5 and event.type == pygame.KEYDOWN:
screen.fill(pygame.Color("black"))
pygame.display.flip()
wait_time = random.randint(1,4)
time.sleep(wait_time)
reaction_start = datetime.now()
print(reaction_start)
screen.blit(w,(225,200))
count = count + 1
if event.type == pygame.KEYDOWN:
reaction_end = datetime.now()
print(reaction_end)
t = reaction_end - reaction_start
print(t)
f = font.render("REACTION TIME: "+ str(t),0,(255,255,255))
screen.blit(f,(225,300))
它将几乎同时注册reaction_start 和reaction_end,并且不会等待按键。
这目前将“PRESS ANY KEY”和“REACTION TIME:”这两个语句一起打印,但是当我将 screen.fill(pygame.Color("black") 和 pygame.display.flip() 的语句放在屏幕之前.blit(f),它只会显示反应时间:而不是“按下任何键”