* /trunk/code/player.py
[singularity-git.git] / code / clock.py
blobc254302aa362e5b5a1424169e7dd34d5d2583b9e
1 # Copyright (C) 2005 Adam Bark apb_4@users.sourceforge.net
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 """The start of a substitute Clock for pygame"""
19 import time
21 class Clock:
22 """This class is generally used to limit the framerate of a game.
24 Clock().tick(50) called in every frame will limit the framerate to 50
25 frames per second. The tick method returns an int corresponding to the
26 time since the last call to tick in milliseconds.
27 """
28 def __init__(self):
29 self.t = time.time()
31 def tick(self, rate=-1):
32 # rate=-1 will be caught by the except statement if no rate is specified
33 """If rate is specified this will limit the framerate to the
34 specified number per second.
35 """
36 self.rate = rate
37 retVal = int(round((time.time() - self.t) * 1000, 0))
38 self._stop()
39 self.t = time.time()
40 return retVal
42 def _stop(self):
43 try:
44 time.sleep(1.0/self.rate - (time.time() - self.t))
45 except IOError:
46 # This will catch exceptions raised if the actual framerate is less
47 # than self.rate or if no rate was passed to tick.
48 pass
50 if __name__ == "__main__":
51 import timeit
52 timer = timeit.Timer('c.tick(50)', 'from __main__ import Clock; c = Clock()')
53 print timer.timeit(5000)