Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer for Python game

Tags:

python

time

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)?

like image 826
purpleladydragons Avatar asked May 04 '11 21:05

purpleladydragons


People also ask

Can I set a timer in python?

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.


2 Answers

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.

like image 108
nmichaels Avatar answered Oct 11 '22 06:10

nmichaels


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.

like image 41
poizan42 Avatar answered Oct 11 '22 05:10

poizan42