Search code examples
pygamepygame-clock

Show final time on victory screen


In my game I have a chronometer running. The chronometer is defined in the 'Play' class(which is used for everything related to when the player is controlling the character), not in the 'Victory' class(which purpose is to show an image when you pass the level). Both classes are defined in the main.py file. I want to print on the final victory screen(the player wins when the character gets to a determinate position) the time that has taken the player to get to that position. How would I do that? Thanks. Unfortunately, I cannot show code.


Solution

  • I made a little piece of code that could help you building this timer.

    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()
    

    If you want the timer begin only if the player has moved, detects the key and add a variable like:

    # (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()