Using the template method pattern

In my last post, I talked vaguely about a project I'm working on. In this post, I'll actually name it. I realized it was foolish to link to my github profile on this site, while not talk about what is clearly available in that github account. The project is a fork of the browser game wpilot. My fork, codenamed wsilent, aims to be a spiritual successor to the old multiplayer game Silent Death Online.

When I began this project, my first step was to refactor the wpilot codebase to be flexible enough to do what wsilent needed to do. Part of that is swappable weapons. The wpilot code doesn't provide much flexibility on weapons. There is a block of code that checks the world rules for weapon reload time and energy cost, and then a bullet is generated (or three, if you have the spread shot powerup) and the bullets are added to the entities table.

I just finished my work extracting all of the weapon logic into separate objects to let each weapon decide its energy cost, reload time and bullets spawned. I used the template method pattern for this, where each object was an extension of a core Weapon object. This Weapon object handled functions like 'can_fire' and 'get_bullets', while abstracting the concrete functionality of 'get_bullets', 'get_reload_time' and 'get_energy' onto the concrete weapons, such as CannonWeapon. CannonWeapon is just a mimic of the original weapon from wpilot, but this encapsulation allows me to swap out the weapon with others, each one handling its own data internally.

Not only does this give me more flexibility on the weapons themselves, but this gives me the option to provide a hotkey for swapping weapons at runtime. That functionality will be very important for my final product.

Also, while I've been writing this, I've been keeping in mind that I plan to use the decorator pattern to handle powerups. The spread shot decorator will simply wrap around the concrete weapon object and do a bit of additional processing in the get_bullets function to add a pair of extra bullets to the side. This usage of the decorator pattern will let me seamlessly layer multiple powerups, like spread shot, ricochet shot and rapid fire.

I'm sure it will be some time before wsilent plays any differently from wpilot. At the moment, my goal is just to adjust the code base to suit my needs so I can make those needed changes.