Precise framerate calculation, scheduling and framerate limiting.
The tick and get_fps functions can be used in conjunction to fulfil most games’ basic requirements:
from glumpy.app import clock while True: dt = clock.tick() # ... update and render ... print 'FPS is %f' % clock.get_fps()
dt value returned gives the number of seconds (as a float) since the
The get_fps function averages the framerate over a sliding window of
approximately 1 second. (You can calculate the instantaneous framerate by
taking the reciprocal of
Always remember to tick the clock!
The framerate can be limited:
This causes clock to sleep during each tick in an attempt to keep the number of ticks (frames) per second below 60.
The implementation uses platform-dependent high-resolution sleep functions to achieve better accuracy with busy-waiting than would not be possible using just the time module.
You can schedule a function to be called every time the clock is ticked:
def callback(dt): print '%f seconds since last callback' % dt clock.schedule(callback)
The schedule_interval method causes a function to be called every “n” seconds:
clock.schedule_interval(callback, .5) # called twice a second
The schedule_once method causes a function to be called once “n” seconds in the future:
clock.schedule_once(callback, 5) # called in 5 seconds
All of the schedule methods will pass on any additional args or keyword args you specify to the callback function:
def animate(dt, velocity, sprite): sprite.position += dt * velocity clock.schedule(animate, velocity=5.0, sprite=alien)
You can cancel a function scheduled with any of these methods using unschedule:
The ClockDisplay class provides a simple FPS counter. You should create an instance of ClockDisplay once during the application’s start up:
fps_display = clock.ClockDisplay()
Call draw on the ClockDisplay object for each frame:
There are several options to change the font, color and text displayed within the __init__ method.
Using multiple clocks¶
The clock functions are all relayed to an instance of Clock which is initialised with the module. You can get this instance to use directly:
clk = clock.get_default()
You can also replace the default clock with your own:
myclk = clock.Clock() clock.set_default(myclk)
Each clock maintains its own set of scheduled functions and FPS limiting/measurement. Each clock must be “ticked” separately.
Multiple and derived clocks potentially allow you to separate “game-time” and “wall-time”, or to synchronise your clock to an audio or video stream instead of the system clock.