test test - 2 months ago 19
Python Question

Python Game Timer (Threads?)

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:

import time

seconds = 60

def start_timer():
global seconds
while seconds > 0:
print seconds
seconds -= 1
time.sleep(1)


However, when run in my main game function my game hangs because of the
timer.sleep
.

def main(self):
Timer.start_timer()


I'm pretty sure my issue has something to do with not using threading, although I'm not 100% sure. Can somebody help explain to me what the proper solution is?

Answer

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.

Comments