Swap it like it's hot
Ever since watching stumbling upon a few videos where people hot-swap code in order to demonstrate game physics tweaking, I wanted to know how they do it. Turns out in Python it's really easy*. Just reload(module) and the magic starts happening. See some random guy demonstrating this here.It comes with a few pitfalls, though:
- You gotta remember to import your modules, not their symbols
- You gotta make one main class as stupidly simple and as crash-resistant as you can
- To simplify swapping, you gotta work with smart modules, rather than smart classes
I'm like 70% through the process of making my game updateable while running, the last steps I can think about ahead of time are:
- Make the game state JSON serializable (that unfortunately means working with few classes and more modules)
- Add hotkeys to dump the gamestate or to reload a gamestate
- Make the game initialization initiate the game with serialized JSON data
Today is (hopefully) probably the only day in which I'm going to focus on trying to make this happen. If I end up stuck in developing this feature it's best I just dump it, as it will probably not pay off in the timespan of a week. I'm sure there's better ways to do this, but this is my first try at this. :)
My current engine model is as follows:
- Game object, which contains a basic loop, and functions to handle input, simulate and render, all which are delegated to an "engine" module, which receives the object itself as well as the game data. All of those functions are written to prevent crashes, as I might want to preserve data that was created as a result of swapped-in data. As well as a swap requester function, which causes the engine try to swap the "engine" module.
- An "engine" module, which actually handles the pygame stuff, such as initializing, polling for events, rendering stuff on the screen, as well as attempting to perform arbitrary game data upgrades upon swap.
- The "gamestate", which is a dict of primitive objects intended to be serialized in JSON and passed around to smarter modules.
If you want to look at the atrocious in-development code, see here: https://github.com/shundread/pyweek24