1

我正在构建一个 Hangman 游戏作为我的第一个 Pygame 项目。游戏结束后,我希望屏幕暂停一秒钟,然后显示结果消息几秒钟,然后退出游戏。我有以下功能:

def display_result_msg(win):
    pygame.time.delay(1500)
    if win:
        msg = 'You win!'
    else:
        msg = 'You lose.'
    screen.fill(BLACK)
    msg_text = MESSAGE_DISPLAY_FONT.render(msg, True, WHITE)
    msg_width, msg_height = msg_text.get_size()
    msg_x, msg_y = (WIDTH - msg_width)/2, (HEIGHT - msg_height)/2
    screen.blit(msg_text,(msg_x, msg_y))
    pygame.display.update()
    pygame.time.delay(10000)

直到最后一次正确/错误的猜测,游戏都按预期运行,但是在显示结果消息时,游戏开始缓冲整个延迟持续时间,并且结果消息仅在退出游戏之前在屏幕上短暂闪烁。无论我设置什么延迟时间,都会发生这种情况。请帮助我了解我在这里缺少什么。谢谢你。

4

1 回答 1

1

我怀疑问题是你阻塞了事件循环。最好不要有这些硬性延迟。

如果你必须做一个硬延迟,做一个等待的函数,但也倾向于事件循环:

def waitFor( milliseconds ):
    """ Wait for the given time period, but handling some events """
    time_now    = pygame.time.get_ticks()   # zero point
    finish_time = time_now + milliseconds   # finish time

    while time_now < finish_time:
        # Handle user-input
        for event in pygame.event.get():
            if ( event.type == pygame.QUIT ):
                # re-post this to handle in the main loop
                pygame.event.post( pygame.event.Event( pygame.QUIT ) )      
                break
            elif ( event.type == pygame.KEYDOWN ):
                if ( event.key == pygame.K_ESCAPE ):
                    break
            # TODO handle any other important events here

        pygame.display.update()            # do we need this?
        pygame.time.wait( 300 )            # save some CPU for a split-second
        time_now = pygame.time.get_ticks()   

给你类似的东西:

def display_result_msg(win):
    #pygame.time.delay(1500)
    if win:
        msg = 'You win!'
    else:
        msg = 'You lose.'
    screen.fill(BLACK)
    msg_text = MESSAGE_DISPLAY_FONT.render(msg, True, WHITE)
    msg_width, msg_height = msg_text.get_size()
    msg_x, msg_y = (WIDTH - msg_width)/2, (HEIGHT - msg_height)/2
    screen.blit(msg_text,(msg_x, msg_y))
    waitFor( 10*1000 )
于 2020-07-19T22:47:50.043 回答