I am designing a game in Python and would like to know how to make an efficient timer that can run along side my game.
Note: I am using Pygame.
I currently have a timer like so:
seconds = 60
while seconds > 0:
seconds -= 1
If you're using PyGame, it has its own time functionality that you should be using.
If you're using an event-loop or hybrid design, where you loop over
pygame.event.get() or similar and call "event handlers" for different events like mouse-click or key-down, you can use
set_timer to create an event that fires every second. For example:
TIMER1_EVENT = pygame.USEREVENT + 1 def start_timer1(): global seconds seconds = 60 pygame.time.set_timer(TIMER1_EVENT, 1000) def on_timer1(): global seconds print seconds seconds -= 1 if seconds < 0: pygame.time.set_timer(TIMER1_EVENT, 0) # elsewhere, inside your main event loop elif event.type == TIMER1_EVENT: on_timer1()
There are very simple example programs linked in the docs for each function; if you look at the examples for
set_timer you'll see how easy it is to use.
If you're using a pure frame loop instead, you're presumably already calling
Clock.tick or similar, and you're going to have to use the return value from that to count down milliseconds since the last time and decide whether you've passed another integral number of seconds and when you're passed 0.