首页 > 解决方案 > 为什么在 Pygame 中clock.tick() 不能准确测量时间?

问题描述

我在 Pygame 中创建了一个简单的游戏,它在 x 时间内显示某种情绪的图像,然后让参与者有机会通过按下按钮来选择显示哪种情绪。但是,我无法维持图像的显示时间。我使用 clock.tick() 来获取增量时间的值,但它似乎比它应该慢了 3 倍。例如,如果我将计时器设置为 1000 毫秒,则图像显示约 3 秒,而我只希望它显示 1 秒。我总是可以将显示时间除以 3 以使其大致正确,但我想了解是什么原因造成的。这是主要的游戏循环:

def mainGame(images):
dt = 0    #delta time is set to 0 to begin
timer = displayTime #displayTime by default is 1000ms
imageNumber = 0
gameState = States.VIEWING    #this is the game state where a participant views a question
running = True
while running:
    mouse = pygame.mouse.get_pos()
    screen.fill((255, 255, 255))
    mainDisplay()             #this displays the answer buttons
    clock = pygame.time.Clock()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False


    if ( gameState == States.VIEWING):
        dt = clock.tick_busy_loop(30)   #should increase delta time by however many ms have passed
        timer -= dt                     #minus delta time from the timer
        if timer >= 0:                  #if the timer remains above 0, continue displaying image
            askQuestion(images, imageNumber)
        else:                           #when timer reaches 0, stop displaying image and move to answering state
            gameState = States.ANSWERING
            

    elif (gameState == States.ANSWERING):     #this is where participants select their answer
        timer = displayTime                   #reset the timer
        screen.fill((255, 255, 255))
        mainDisplay()                         #displays answer buttons
        for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not
            if event.type == pygame.MOUSEBUTTONDOWN:
                if rects.collidepoint(mouse):            #if a button is clicked
                    gameState = States.VIEWING           #switch back to viewing state
                    answers.append(emotion)                 #add answer to answer list
                    imageNumber += 1                    #move to the next image
                elif not any(rect.collidepoint(mouse) for rect in rectList):   #if a button is not clicked
                    print("You did not select an answer")
                    break

    if practice == True:   #if in practice mood, stop when number of practice questions is reached
        if len(answers) == pnumberofQuestions:
            break
    elif practice == False: #if in main game loop, stop when number of questions is reached
        if len(answers) == numberofQuestions:
            break

    pygame.display.update()

标签: pythonpygame

解决方案


每次通过while循环时,您都在创建一个新时钟。

移动

    clock = pygame.time.Clock()

从你的

while running:

并把它放在它上面的某个地方。


推荐阅读