I'm trying to create a simple game where the point is to collect as many blocks as you can in a certain amount of time, say 10 seconds. How can I get a timer to begin ticking at the start of the program and when it reaches 10 seconds, do something (in this case, exit a loop)?
A timer in Python is a time-tracking program. Python developers can create timers with the help of Python's time modules. There are two basic types of timers: timers that count up and those that count down.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With