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?
2 Answers
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).
-
\$\begingroup\$ sounds pretty good. does it makes sense to separate the update and draw logic like it's done in other game frameworks? \$\endgroup\$apparat– apparat2011-03-22 23:21:22 +00:00Commented Mar 22, 2011 at 23:21
-
\$\begingroup\$ Yes, you might also want to divide update into physics step and game parameter updates. \$\endgroup\$coderanger– coderanger2011-03-22 23:24:50 +00:00Commented 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
-
\$\begingroup\$ 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. \$\endgroup\$apparat– apparat2011-03-23 19:10:56 +00:00Commented Mar 23, 2011 at 19:10