One cannot always decorate that cake

I was very excited about the Decorator Pattern, right up until I wasn’t.

Being new to design patterns, and OO programing, and Java, and programming in general, the Decorator Pattern looked like an effective (and entertaining) solution to a particular challenge: applying effects (i.e. feats, buffs, equipment bonuses) to actors in order to change their properties (i.e. ability scores, to hit, AC). Also known as a ‘Wrapper’, this pattern “… allows behavior to be added to an individual object… without affecting the behavior of other objects from the same class.”

Perfect! So, if the hero casts Bless, for example, just wrap her in a Decorator like this:

// Abstract decorator class for Hero
public abstract class HeroDecorator implements HeroInterface {

    protected final Hero decoratedHero;

    public HeroDecorator(Hero hero) {
        this.decoratedHero = hero;
    }

    // Implement interface method
    public int getToHit() {
        return decoratedHero.getToHit();
    }
}

// Decorator wraps the Hero in a Bless spell
class Bless extends HeroDecorator {

    public Bless(Hero hero) {
        super(hero);
    }

    // Overriding method defined in abstract superclass
    public int getToHit() {
        return super.getToHit() + 1; // +1 to hit bonus from spell
    }
}

To ‘Bless’ the hero, just do this: hero = new Bless(hero);. Now hero.getToHit() will return the original ‘to hit’ with a +1 bonus. Done! If the hero picks up a magic sword that adds another +1 to ‘to hit’, hero = new MagicSword(hero); where class MagicSword extends HeroDecorator. If the hero becomes cursed, and takes a penalty on ‘to hit’, you can still do hero = new Curse(hero);. Decorators can also be stacked, so you can just keep wrapping and wrapping. hero = new Bless(new MagicSword(new Curse(hero))); will work.

There are reasons, however, why all of this is a bad idea.

Removing the frosting

The first problem with the Decorator Pattern is that once you wrap an object you cannot unwrap it, at least not without a hack. The Bless spell above is eventually going to expire, at which point the hero no longer gets the bonus, so what do you do?

One option is to implement a way to ‘deactivate’ the decoration. Perhaps the Decorator itself would have a timer that, after a certain duration, would stop adding the bonus. Or perhaps you could implement a method enabling the toggle of a boolean active; within the Decorator. Regardless, this is going to be a terrible approach as the object will continually grow in size, forever, as it’s wrapped, re-wrapped and wrapped again. Imagine what your hero will look like by level 20.

Generally, you cannot remove the wrapping. According to this amazing post on StackOverflow, “You cannot un-decorate a function. (There are hacks to create decorators that can be removed, but nobody uses them.) So once a function is decorated, it’s decorated for all the code.” The ‘hack’ being referred to here essentially involves treating the Decorators like a Linked List: each Decorator keeps track of both the immediately outer Decorator, in addition to the immediately inner Decorator, so that when it expires it can ‘decouple’ itself by linking the two of them.

Keeping track of the ingredients

Nevertheless, even if you implement the hack for ‘decoupling’ Decorators you are probably going to still have the headache of keeping track of all of the decorated methods. Notice the HeroInterface above. It looks like this:

public interface HeroInterface {

    public int getToHit(); // Returns d20 to hit roll
}

It exists to make sure that any decorated method gets ‘passed through’ all of the layers of Decorators so it can end up at the base object. This means that every Decorator, even those that do not affect ‘to hit’ (e.g. override public int getToHit()), must implement the method and pass along the functionality to the super method, like public int getToHit() { return super.getToHit(); }. Furthermore, every decorated method needs to be in the interface, which could end up looking like this:

public interface HeroInterface {

    public int getToHit(); // Returns d20 to hit roll
    public int getAC(); // Returns AC
    public int getAbility(Abilities ability); // Returns Str, Int, etc.
    public int getSavingThrow(Saves save); // Returns saving throw
    // and on, and on, and on...
}

Every Decorator will then have to implement every one of these methods, which will get ugly. Add a decorated method and you’ll have to then update every Decorator. According to Michael Feldman, “For longer classes, a programmer must choose the lesser of two evils: implement many wrapper methods and keep the type of decorated object or maintain a simple decorator implementation and sacrifice retaining the decorated object type.” In other words: hassle.

Remarkably, however, this, too, can be ‘hacked’. This StackOverflow question describes the exact problem of a implementing an interface for a class with lots of methods to decorate. My answer involves eliminating the interface by implementing the bytecode generation library, CGLIB. Using a proxy solution Decorators are then able to implement just the methods they want to override while simply passing through everything else. There’s a performance hit, but it works. You can try my code for yourself.

Eat ice cream instead

While with a Linked List style Decorator and a bytecode generation library proxy solution you could, in the end, decorate your cake and eat it, too (you’re welcome), there’s a better way.

As helpfully pointed out in a StackOverflow chat room, Anubian Noob suggested storing the ‘to hit’ bonus (and all other parameters that could be affected by an effect) in the base class, loading all of the effects into a list and simply iterating through all of them during updates. My Bless class now looks something like this:

public class Bless extends Effects {

    private Actor actor;

    public Bless(Actor actor) {
        this.actor = actor;
    }

    @Override
    public update() {
        actor.toHit += 1;
    }
}

When the Bless is complete, just remove it from List<Effects> effects = new ArrayList<>();. Easy. Alternatively, which is what I chose to do, you can iterate through the collection of Effects whenever a value, such as ‘to hit’, is required. It looks something like this:

public class Hero {

    private List<Effects> effects = new ArrayList<>();
    private int toHitBonus = 0;
    private Random rand = new Random();

    public int getToHit() {
        for (Effects effect : effects) effect.updateValues();
        return rand.nextInt(20) + 1 + toHitBonus;
    }
}

As one of the design patterns laid out in the Gang of Four’s famous tome, the Decorator Pattern must certainly have important utility. At least for me, however, despite no lack of effort, I decided that it just wasn’t helpful in this case.

Building the game engine from scratch

In October ’14 I attended a “Share Your Projects: Lightning Talks” event where mobile developers demoed their personal projects. While chatting beforehand someone asked me what ‘engine’ I was using to develop my game. As I was looking confused, he offered, “Unity?” along with a couple other suggestions. I had no idea what he was talking about.

Demonstrating a very early Alpha version for a particularly interested individual
Demonstrating a very early Alpha version for a particularly interested individual

A game engine is, I learned, simply “a software framework designed for the creation and development of video games.” They exist for Android and most everything else. Core functionality, such as UI, rendering, physics, AI, logic, etc., are all already provided, obviating the need to reinvent any wheels. With a multitude of different off-the-shelf game engines available, why write your own? According to Michael Kissner, “Don’t, if you can avoid it.”

Michael then goes on, contrary to his own advice, to write a four-part series on building game engines, because, as he points out, some people might “want to learn how an engine works.” This was my motivation from the beginning. (Although, frankly, I didn’t know any better.) For anyone else interested in doing likewise, there is a myriad of instructive blog posts (I found this one particularly helpful) and I would highly recommend Game Programming Patterns. Perhaps I’ll eventually post some helpful tips on this blog.

In any event, the answer to the question asked of me at the Lightening Talk turned out to be, “I’m writing directly to the Canvas using my own engine.” Today I stumbled across this Quora answer to What is considered as the most difficult level in programming?: “I’d say developing a game engine.” I’m not sure if she’s right, but it’s enjoyable to hear.

Formula for computing ability modifiers

Here’s something that should interest… almost no one… but I’m sharing nonetheless. Since the game is based on ability scores, I need to compute an ability modifier for a given score. One could brute force it with a table, but I think the following is more elegant:

private static int abilityModifer(int abilityScore) {
    return (abilityScore / 2 - 5);
}

Given an integer ability score, this Java method returns an integer ability modifier. Easy.

It might be helpful to note that while (x / 2) – 5 is equivalent to (x – 10) / 2, if you go with the latter, which is how I started, the code gets a little more complicated:

private static int abilityModifer(int abilityScore) {
 return (int) Math.floor((float) (abilityScore - 10) / 2);
}

The problem is with the rounding. The trick here, that took me no small amount of time to figure out, is that you need to cast the (abilityScore - 10) / 2 argument to a float before passing it through Math.floor(). If not, the negative modifiers aren’t calculated correctly because the argument gets implicitly cast to an int which, for ability scores less than 10, rounds towards zero, which is the wrong direction. Math.floor() will round the float toward negative infinity, which is what you want.

In the beginning, there was BASIC…

History

Like many nerdy youth, I spent a lot of time on my computer. Like many who were were youths in the ’80s, that computer was an Apple ][+. (Thank you, mom and dad, for chipping in so that I didn’t end up with a TRS80.) I had the RAM expansion board for a full 64K along with dual 5¼” floppies that I modified with hardware switches to toggle write protection.

Most importantly, however, I learned BASIC and devoted considerable effort to writing software, most notably a program I called Function Plot (a utility that graphed functions in Cartesian and Polar coordinates) and games. Being a Dungeons & Dragons fanatic (who wasn’t, right?) and loving the Ultima and Wizardry series, those games were predominantly 2D RPGs. (The logic was in BASIC but I taught myself assembly in order to develop subroutines to quickly render the graphics.)

Apple ][+ Assembly
Apple ][+ Assembly

At one point in high school I learned Pascal, in college I then suffered for four years with Lisp (please don’t explain to me how awesome it is) and in my first job out of school I tinkered with the x486 BIOS and device drivers. I spent some time playing around with Borland C as well, although I never made much progress with that.

Motivation

Then I moved to the dark side (business school) and my days of writing code were behind me. My career has been exclusively in computers and the internet, and I’ve worked closely with software developers, but I didn’t sling the code myself. (Albeit recently I’ve done a considerable amount of scripting in Ruby and R.) Over the years as I followed the evolution of software development I often wondered if I still had the chops. So a few years ago, I decided to find out.

World of Warcraft
World of Warcraft

The idea was to build, once again, a 2D RPG. No single developer could ever build anything approaching the scale of a modern RPG, but perhaps a lone programmer could put together something “old school.” Since mobile was ‘hot’ and smaller devices seemed like they might lend themselves better to a slow, low-res 2D game, and Java was ‘everywhere’, I decided to go with Android. Having never developed in Java, or OO for that matter, or on any framework, in March 2013 I nevertheless signed myself up for a full-day “Introduction to Android” boot camp taught by the amazing Nathan Esquenazi and Tim Lee, founders of CodePath.

That was a very depressing day.

I understood nothing and left convinced that there was no way this would ever happen. Yet in my minuscule amount of free time I persisted. Nathan and Tim were nothing short of fantastic in coaching me along the way, for no other reason than their love for teaching people to write code. My Stack Overflow page views grew. (How did anyone ever do anything without SO?) My wife was amazingly supportive, as always. Teeny, tiny pieces started coming together bit by bit (pun intended) until one day, finally, I got “it.”

Perseverance

Today, 10+k lines of code later, I think I can legitimately say that I have what is beginning to approach a real game, that people might actually be able to play. It may not be coming soon, or perhaps even ever at this rate, but in a relatively bug-free manner you can create a character, move around, do some stuff, kill a few monsters and get wiped out yourself. Fun!

Mortal Wayfare is not publicly available, but this website was put together a couple days ago to share (the very slow) progress and invite a few patient, understanding friends to Alpha test. Check out the Forum and come back periodically for updates. Perhaps one day we’ll meet in the Google Play Store.