views:

142

answers:

3

I'm currently working on sprite sheet tool in python that exports the organization into an xml document but I've run into some problems trying to animate a preview. I'm not quite sure how to time the frame rate with python. For example, assuming I have all of my appropriate frame data and drawing functions, how would I go about coding the timing to display it at 30 frames per second (or any other arbitrary rate).

+3  A: 

The easiest way to do it is with Pygame:

import pygame
pygame.init()

clock = pygame.time.Clock()
# or whatever loop you're using for the animation
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    clock.tick(30)

The second easiest way to do it is manually:

import time

FPS = 30
last_time = time.time()
# whatever the loop is...
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    new_time = time.time()
    # see how many milliseconds we have to sleep for
    # then divide by 1000.0 since time.sleep() uses seconds
    sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0
    if sleep_time > 0:
        time.sleep(sleep_time)
    last_time = new_time
Daniel G
Thank you, very helpful. I'm new to Python, but working hard to become more familiar with it.
M3RPHY
A: 

There is a Timer class in the threading module. It may be more convenient than using time.sleep for some purposes.

>>> from threading import Timer
>>> def hello(who):
...    print 'hello %s' % who
... 
>>> t = Timer(5.0, hello, args=('world',))
>>> t.start()      # and five seconds later...
hello world
Matt Anderson
A: 

You could use select ? It's commonly used for waiting on I/O completion, but take a look at the signature:

select.select(rlist, wlist, xlist[, timeout])

so, you could do something like:

timeout = 30.0
while true:
    if select.select([], [], [], timeout):
        #timout reached
        # maybe you should recalculate your timeout ?        
dzen