Daniel Petersen's Blog

Documenting my struggle to make a videogame, amongst other nonsense


Home Projects

Refactoring Code

Posted on 2017-07-14

I’ve been refactoring the codebase lately with the goal of increasing performance, mostly from multithreading it.

Prior to now everything was a single thread. I had no proper experience with multithreading, but I knew that it added a lot of complexity and I honestly thought that I could get away with the entire game being one thread.

I think if this game was strictly turn based then it’d have been fine, but it’s not. You press one of the speed buttons up top, and then turns start happening automatically on a set interval depending on the speed chosen.

As I’ve started to add in more complex AI behavior and the number of units and cities grew, it became clear that I’d need to make the game multithreaded. On the fastest speed, turns happen about once every 600 milliseconds, so when the game was a single thread those 600 milliseconds were essentially wasted, as the game was waiting until the 600 milliseconds were up in order to calculate the next state of the game world. It led to a noticable pause every time a new turn occurred.

So that’s how I’ve been spending my time lately. Truthfully it’s not as bad as I thought it’d be, though I do wish I did this sooner.

Since I’m refactoring the codebase to allow for that, I’ve also taken this opportunity to improve other aspects of the code. The grid for instance is something that I wrote in 2012 when I was much worse at programming than I am now, and it could really be better. Notably I had entangled it too much with code specific for this project. What I want is something independent which can be reused in other projects. It’d also be nice if it supported multiple grid types (square, isometric, hex).

So I spent some time working on that and it’s been a pleasant success. It’s now faster, more flexible, and you can set the grid type at initialization. Currently supports square, isometric, and I spent about an hour last night adding in hex support. The game is mostly agnostic to what type of grid it takes place on, so I can now generate a world using any of those grid types, which is pretty cool. I’d have to do some work to make it truly playable on a hex grid (for instance, some AI code would need to account for the different grid type), but curiosity of how this would look as a hexmap got the better of me.

I’m hoping to get back to actually implementing more gameplay soon.


Copyright © - Daniel J. Petersen