How to write reuseable components for pygame

Is there a recommended way to write reuseable components for pygame? Simple example would be a FPS counter. Should I write a class which has an init, update and draw method and call them from inside a game loop?

That would be pretty normal, pass the frame delta to update and pass in a destination surface to draw (which will normally be the screen).

• sounds pretty good. does it makes sense to separate the update and draw logic like it's done in other game frameworks? Mar 22, 2011 at 23:21
• Yes, you might also want to divide update into physics step and game parameter updates. Mar 22, 2011 at 23:24

I'm not sure if there's a recommended way, as such, for writing components but I often reuse buttons and other stuff for the game and pause menu which are initialized with Surfaces for mouse-states (hover, mouse-down, etc) and a function for click-events.

And of course, I have a vector class that I reuse all the time.

You definitely don't really need a module for basic timing and fps calculation though. Pygame's Clock-class is ideal for that. You just create a clock-object, call tick() once per frame and it returns the delta-time and keeps track of fps for you:

def main_loop():
clock = pygame.time.Clock()
counter = 0

while game_is_running:
handle_events()

lapse = clock.tick()
update_physics_and_stuff(lapse * BASE_SPEED_FACTOR)
render()

# once every second, display the fps
counter += lapse
if counter > 1000:
pygame.display.set_caption('fps: %1.2f' % clock.get_fps())
counter = 0

• Thanks for your answer. The fps counter was just an example. What I wanted to know is how you structure your components so that you can reuse them easily in several other projects. Mar 23, 2011 at 19:10