This month there isn’t really anything visual that’s changed with my turn-based dungeon crawler. Instead, this past month has been a lot of invisible structural work. For example, there hadn’t been any way to complete a dungeon and start a new one, so I added in an end location to reach. Meanwhile, I’ve also been doing a lot of refactorings and code cleanup, one of which I want to highlight in this post.
Specifically, I created an interface for the various interactive objects to share. While it’s not where I learned of this programming construct, the following video is a pretty good explanation of what I did:
As you can see in the screen recording from last month, the dungeon already had both enemies to attack and treasure chests to open, both interacted with by running into them. As I contemplated adding other interactive objects (I’m calling those actors btw) I realized I should streamline the code for interacting with them.
The first pass implementation was simply a branching if/else statement whenever the player runs into something. The code checks what kind of actor it is, and then runs different code for each type.
That works fine for just a couple different kinds of actors, but gets increasingly unwieldy as more actors get added to the game. Plus every branch amounted to “run the interaction for this actor”, which meant a lot of duplicated code.
So I refactored things to work with a common interface for all actors. That is, both EnemyActor and TreasureActor implement IActor. Meanwhile, IActor has a method called DoMainInteraction for all actors to implement. Now the player code can simply call DoMainInteraction on whatever actor it ran into (no more checking what kind first) and it’s up to the individual actor to define its main interaction as an attack, or opening it, or whatever.
Nice elegant code!