Fancy lighting for texture and effect

When I put together tiles as I started building the game, it was very exciting. Initially there were only a few (stone walls, stone floors, torches and orcs), but it was amazing to see them come together on the screen. After the initial euphoria faded, however, I was left feeling that the experience was a bit flat. I randomly rotated the tiles to create a little variety in the layouts, but the lighting left things feeling a little too uniform. The solution was to add some variation in intensity with a little flickers to simulate illumination from a torch.

How is it done? Every tile is an object with a local illumination variable which range from 0 (pitch dark) to 100 (maximum light). Every source of light, such as a torch, will then increment the values of the tiles within its range (lumensRange) by an amount relative to the inverse of the square of the distance to that tile, as stipulated by the Inverse Square Law. To make things feel a little more dynamic and “real,” I added a random amount of illumination (randomLumens) to simulate a flicker. This effect is primarily visible near the edge of the illumination radius.

for (int x = -lumensRange; x <= lumensRange; x++) {
	for (int y = -lumensRange; y <= lumensRange; y++) {
		int randomLumens = (flickerAmt != 0) ? rand.nextInt(flickerAmt) : 0;
		if (x == 0 && y == 0) lumensFlickerCache[x + lumensRange][y + lumensRange] = (lumens + randomLumens) / 4;
		else lumensFlickerCache[x + lumensRange][y + lumensRange] = (lumens + randomLumens) / 4 / ((x*x) + (y*y));
	}
}

To save compute, as well as control the frequency of the flicker, these values are not computed at every update, hence the lumensFlickerCache.

The next step is, of course, is to adjust the color effects (brightness, hue, contrast, saturation) of the tiles as a function of the level of illumination. As is frequently the case, someone on Stack Overflow put together a class with a collection of methods to accomplish all of this. To get the desired effect, I experimented with adjusting all of the effects as a function of the level of illumination, but in the end settled on brightness and contrast. As it turned out, adjusting the brightness was not sufficient to dim the tiles with low illumination.

// method from ColorFilterGenerator class
public static ColorFilter adjustColor(int brightness, int contrast, int saturation, int hue){
    cm.reset();
    adjustHue(cm, hue);
    adjustContrast(cm, contrast);
    adjustBrightness(cm, brightness);
    adjustSaturation(cm, saturation);
    return new ColorMatrixColorFilter(cm);
}

// method that adjusts the tile's color filter during rendering
public OverlayImage(Context context, Entities e) {
    super(context);
    entity = e;
    if (!entity.equals(hero)) { // normal brightness for hero
        int brightness = map.getBrightness(entity.getPos());
        p.setColorFilter(ColorFilterGenerator.adjustColor(brightness, brightness, 0, 0));
    }
}

Here is a short video from the early days of development. You can see the illumination radius and, with careful attention, should be able to see the flicker at the edges. It’s worth noting that I prioritized doing this over building the mechanics of the game, such as combat. At the end of the video you can notice that the orc does not hit back.

While this may seem rudimentary, it’s actually an aspect of the game for which I am the most proud. Not only do I love the way it looks, and the feeling it gives to the experience, but it actually took a lot of time and experimentation to get it to the point where it worked and looked right.

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.