Question

I'm working on an astronomy project, making one of those gravity simulator programs. I have a Uni class, which represents a universe filled with celestial bodies (instances of the Body class).

This Uni class is capable of updating itself, adding new bodies, and removing bodies by their id. It's completely math-based, and should work alone.

Around it, I'm planning to build the program that uses PyGame to optionally display the simulation in real time and MatPlotLib to analyze the results. However, I am a bit confused over how to keep my computation (Uni) and rendering (Renderer) decoupled!

I envisioned it like this:

The main program:

  1. Imports PyGame, initializes it, and creates a screen.
  2. Instantiates a universe, fills it with bodies, etc (actually done by a FileManager, which reads JSON specs for a uni).
  3. Creates a Renderer
  4. Enters a while run: loop:

    1. uni.update(dt)
    2. #Listen to PyGame events, respond
    3. r.render(screen, uni, ui) #The UI class has a list of UI elements.

However, the renderer needs to keep a persistent list of PyGame surfaces and images that need to be drawn, and there's the problem. Neither the Uni nor Body instances must be aware of PyGame, so they can't keep those themselves.

The renderer, on the other hand, is only there for its render method, which can't just create and destroy PyGame surfaces as needed (I guess that would be performance-heavy).


One possible solution would be to have the renderer have a dictionary of PyGame objects, all identified by body ids. Then, it would iterate over it, remove any gone bodies, and add any new ones each frame.

Is this the right way to go?

Was it helpful?

Solution

Instead of body ID's why not add the Bodys themselves to the dictionary of pygame objects instead of an ID? After all, a Python variable is just a label, so the renderer wouldn't need to know about what the variable represents. And it might save you having to look-up IDs.

A related option is to add one or multiple viewport objects to your universe. Because no matter what the implementation of the viewing mechanism, you typically don't want to show the whole universe, so a viewport would be a proper attribute of the universe. With that viewport would go a couple of methods (except from creating and sizing). First a method to get all Bodys in the viewport (that could just return a list you'd keep in the viewport object). Second a method to get a tuple containing two lists; one of Bodys that have appeared in the viewport, and second a list of Bodys that gone out of the viewport since the last update. The viewport should also have an update method that is called by the universe's update method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top