0
votes

I'm trying to implement a game timer for a word memory game. The game has a start screen, so the time should be calculated from when the user presses "play", paused when the user presses "pause" mid game and continued when the user presses "continue" on the pause screen. I understand that the correct implementation of this should be independent(ish) of the ticks as i'm using that to control fps. Also it is suggested to use pygame.time.set_times(), which in most examples takes (USEREVENT+1, 1000) as arguments. What is USEREVENT? I can't grasp the documentation for this function.

Below is my implementation. It starts measuring time at pygame.init(), not whhen i call my game loop although the function call for timer() is in the game loop, and can't be paused. How do i rewrite it in order to be able to control the start/stop state of the timer?

Thanks!

def timer():   
    #isOn =True         
    #while isOn:
    second=round((pygame.time.get_ticks())/1000)
    minute=0
    hour=0    

    minute, second=divmod(second, 60)
    hour, minute=divmod(minute, 60)
    #text=smallfont.render("Elapsed time: "+str(getSeconds), True, WHITE)       
    text=smallfont.render("Elapsed time: "+str("%d" %hour + " : "+"%d" %minute + " : "+"%d" %second), True, WHITE) 
    gameDisplay.blit(text, [0+MARGIN,350])
    return time
1

1 Answers

2
votes

Create your own timer class. Use time.time() (from the regular python time module).

import time

class MyTimer:
    def __init__(self):
        self.elapsed = 0.0
        self.running = False
        self.last_start_time = None

    def start(self):
        if not self.running:
            self.running = True
            self.last_start_time = time.time()

    def pause(self):
        if self.running:
            self.running = False
            self.elapsed += time.time() - self.last_start_time

    def get_elapsed(self):
        elapsed = self.elapsed
        if self.running:
            elapsed += time.time() - self.last_start_time
        return elapsed