Pygame中的计时器显示相同的值

时间:2016-12-22 09:32:33

标签: python pygame

我正在尝试在Pygame中制作一个反应时间测试器,但是每次尝试的计时器都显示为0.当屏幕为红色时,按下向下键应该记录所花费的时间。我不确定我应该放置计时器的确切位置,因为我很难理解事件循环是如何工作的。

import pygame, sys
import random
from random import randint
import time
from time import sleep
from pygame.locals import *
FPS = 30
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Test')

WHITE = (255, 255, 255)
RED = (255, 0, 0)
y = False
x = 0

while True:


    if y is False:
        y = True
        DISPLAYSURF.fill(WHITE)

        start = time.time()
        sleep(randint(1,3))

    else:
        y = False
        DISPLAYSURF.fill(RED)
        time.sleep(2)



    for event in pygame.event.get():

        if x < 5:
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if y is True:
                    end = time.time()
                    print(end - start)
                    x += 1



        else:
            pygame.quit()
            sys.exit()



    pygame.display.update()
    fpsClock.tick(FPS)

1 个答案:

答案 0 :(得分:1)

我不确定它是否完全符合您的预期,但它会以毫秒为单位检查红色的时间反应,并且无法time.sleep()

import pygame
import random

# --- constants ---

FPS = 30

WHITE = (255, 255, 255)
RED   = (255,   0,   0)

# --- main ---

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Test')

repeats = 5

testing = False
color = WHITE

current_time = pygame.time.get_ticks()

# random time to start test 
start_test = current_time + random.randint(1, 3)*1000 # 1000ms = 1s

# - mainloop -

fps_clock = pygame.time.Clock()

while True:

    # - events -

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        elif event.type == pygame.KEYDOWN:
            if testing:
                end = pygame.time.get_ticks()
                print(end - start, 'ms')
                repeats -= 1

    # - other

    if repeats == 0:
        pygame.quit()
        exit()

    current_time = pygame.time.get_ticks()

    # is it time to start displaying red color
    if not testing and current_time >= start_test:
        testing = True
        color = RED
        start = pygame.time.get_ticks()
        # display white color
        stop_test = current_time + 2*1000 # 1000ms = 1s

    # is it time to stop displaying red color
    if testing and current_time >= stop_test:
        testing = False
        color = WHITE
        # random time to start next test 
        start_test = current_time + random.randint(1, 3)*1000 # 1000ms = 1s

    # - draws -

    screen.fill(color)
    pygame.display.flip()

    fps_clock.tick(FPS)