Timer for Python game

import time

now = time.time()
future = now + 10
while time.time() < future:
    # do stuff
    pass

Alternatively, if you've already got your loop:

while True:
    if time.time() > future:
        break
    # do other stuff

This method works well with pygame, since it pretty much requires you to have a big main loop.


I use this function in my python programs. The input for the function is as example:
value = time.time()

def stopWatch(value):
    '''From seconds to Days;Hours:Minutes;Seconds'''

    valueD = (((value/365)/24)/60)
    Days = int (valueD)

    valueH = (valueD-Days)*365
    Hours = int(valueH)

    valueM = (valueH - Hours)*24
    Minutes = int(valueM)

    valueS = (valueM - Minutes)*60
    Seconds = int(valueS)


    print Days,";",Hours,":",Minutes,";",Seconds




start = time.time() # What in other posts is described is

***your code HERE***

end = time.time()         
stopWatch(end-start) #Use then my code

The threading.Timer object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.

The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.


Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).

time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.

Tags:

Python

Time