test test - 1 year ago 133
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

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

def main(self):

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 Source

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:


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:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download