2

experimenting with pygame timer and looking for a way to pause the timer, and start the timer again from the previous time.


Functions like pygame.time.get_ticks() work to record time from the start of the application.

Functions like delay or wait freezes the program. I don't want that.

Is there a simple way to keep track a timer object, pause it when I need to and continue it when I need?

def timer(self):
    self.time = (pygame.time.get_ticks()//1000)  
    self.time = self.time - self.pausetime 
    return self.time

self.pausetime = (pygame.time.get_ticks()//1000)

The above will not work because event if self.pausetime is a different variable defined at a different time, it will still return the amount of time since the start of the application.

I think I need a pause variable that I can set to zero every time I come from a pause.


Any thoughts or easy ways I might have over looked?

lzc
  • 1,645
  • 5
  • 27
  • 41
  • Here's using get_ticks() to add a cooldown on guns: http://stackoverflow.com/a/18856389/341744 – ninMonkey Nov 08 '13 at 23:42
  • Not sure I understand. Do you want the timer to return (the total amount of time elapsed since starting) minus (the sum of time spent paused)? – Cuadue Nov 09 '13 at 00:06
  • Ideally, I would like a timer that saves the amount of time it has ticked on it. It has be pausable and able to start up again from the previous time that I paused at. According to my implementation above, both the pause and the time will start calculate all ticks since the beginning of the application run method. – lzc Nov 09 '13 at 00:26
  • @Cuadue Is there a way to reset `pygame.time.get_ticks()` without exiting the application? – lzc Nov 09 '13 at 00:56

1 Answers1

1

Something like this might work. Haven't tested it, though.

class Timer:
    def __init__(self):
        self.accumulated_time = 0
        self.start_time = pygame.time.get_ticks()
        self.running = True

    def pause(self):
        if not self.running:
            raise Exception('Timer is already paused')
        self.running = False
        self.accumulated_time += pygame.time.get_ticks() - self.start_time

    def resume(self):
        if self.running:
            raise Exception('Timer is already running')
        self.running = True
        self.start_time = pygame.time.get_ticks()

    def get(self):
        if self.running:
            return (self.accumulated_time +
                    (pygame.time.get_ticks() - self.start_time))
        else:
            return self.accumulated_time
Cuadue
  • 3,769
  • 3
  • 24
  • 38