在胜利屏幕上显示最后时间

Show final time on victory screen

在我的游戏中我有一个计时器运行。计时器在 'Play' class 中定义(用于与玩家何时控制角色相关的所有内容),而不是在 'Victory' class 中(目的是当你通过关卡时显示图像)。两个 classes 都在 main.py 文件中定义。我想在最终胜利屏幕上打印(当角色到达确定位置时玩家获胜)玩家到达该位置所花费的时间。我该怎么做?谢谢。不幸的是,我无法显示代码。

我编写了一小段代码可以帮助您构建这个计时器。

import pygame

pygame.init() # init is important there because it starts the timer

screen = pygame.display.set_mode((500, 500))
running = True
victory = False


class Play:

    def __init__(self):

        # all infos about player
        self.time = pygame.time.get_ticks()
        self.end_time = 0

    def update_timer(self):

        # here we get the actual time after 'init' has been executed
        self.time = pygame.time.get_ticks() 
        
        # we divide it by 1000 because we want seconds instead of ms
        self.end_time += self.time / 1000
        return self.end_time


class Victory:

    def __init__(self):

        self.play = Play()

    def pin_up_timer(self):

        # Here I chose to print it inside of the console but feel free to pin it up wherever you want.
        print(self.play.update_timer())


vic = Victory()
pl = Play()

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            running = False
        
        # here I chose to end the game when I press KeyUp but you can do something else to stop it
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                victory = True
    
    # I update timer every frame and BEFORE checking if victory is True in order to get a result more accurate
    pl.update_timer()
    
    # if victory is True, I pin up the timer and I end the code
    if victory:
        vic.pin_up_timer()
        running = False
    
    pygame.display.flip()

pygame.quit()

如果您希望计时器仅在玩家移动时开始,检测按键并添加如下变量:

# (this variable outside of the main loop)
moved = False

# left or anything else
if event.key == pygame.K_LEFT:
    moved = True

if moved:
    pl.update_timer()