Archive for the ‘Other’ Category

I dare you! I Ludum Dare you!

The Horseman recently gave a presentation on the 2DToolKit sprite animation library and toolchain at his local Unity 3D Users Group. As it happens, one of the attendees asked The Horseman if he’d ever heard of Ludum Dare and its 48 hour game competition. I had to admit that I was not familiar with it, which might be somewhat surprising given its connection to Minecraft. However, upon reading about what Ludum Dare is and upon hearing that the next competition was starting the very next night, The Horseman did a quick check on his calender to make sure he wasn’t about to blow off any engagements and then declared his intention to enter the competition. It was high time to determine whether he could create a game from the ground up using Unity 3D and the 2D Toolkit in 48 hours. What follows is a summary of the experience.


(The tl;dr version : “Yes, The Horseman can do such a thing and the resulting entry is here under the name dr_soda. There also exists a post-competition build with some improved jumping controls, new levels, and new features that is playable at www.hug-monster.com.)

– Ideation –

When you have 48 hours to create a game you don’t have a lot of time to waste coming up with the perfect idea. Coming into the competition completely blind, I did not have any idea what the theme could be (and indeed nobody really knew what it would be until it was announced) so I did not prepare in any way for what might come. As it turns out the theme for this competition was simply Alone. That was my sole guidance for the direction of the resulting game. After about an hour spent thinking of ideas that were at best “maybe” in terms of fun and at worst “too ambitious” in terms of scope, I came across the idea of the player wishing to be left alone by a lovable, excitable, and adorable emoticon named “Hug Monster” and rendered as such : (-o^_^)-o. Considering this to be both the most interesting take on the theme, and also the most achievable concept in the remaining 47 hours, I sat down to refine the elevator pitch version of the game.

The Hug-Monster (-o^_^)-o can never get enough love or hugs, and is always happy to see you. Unfortunately, it’s a little too excitable and at times doesn’t seem to know its own strength.

You on the other hand are small and fragile, and most definitely want nothing more than to be left alone, especially from the big, scary Hug-monster!

How long can you avoid its warm, snuggly, and loving arms of death? Find out in this classic platformer!

– Artistry –

Since I wanted to keep the mood of the game upbeat in the face of the otherwise bleak theme of “Alone” I decided to make the graphics consist of cute emoticons that would be relatively easy to animate with 3 – 5 frame walk cycles. The Hugmonster flails its arms joyfully as it slides across the stage in perpetual persuit of the player. The player itself is merely a “letter” from the Wingdings font set, the skull and crossbones, rendered at 12px size such that it looks more like a little man than what it actually is. Both of these concepts took very little time to render once I’d settled on the proper font sets on which to base them. Once I had my sprite sheets, it was a quick trip into Unity3D and the 2DToolKit and I had (almost) all the sprite animations I would need. Later, once I decided that the levels needed more interactivity, I went back to Photoshop to create a set of switches, again using glyphs from the standard font set available with any Photoshop install.

– Development –

Being no stranger to side-scrolling mechanics from years of writing ActionScript for Flash games, and even a few little experiments on the subject in C# for Unity in the month prior, writing my own implementation of the walk/run mechanics was no large task. I decided that I would let Unity handle the physics for me this time, rather than write my own physics engine. I’d learned some valuable lessons on what works and what really doesn’t work when using Unity’s physics and felt confident that I could get what I wanted out of it. Rather than use Unity’s built-in CharacterController module, I chose to write my own Ambulator class with its own movement logic and use that for both the player and the Hug Monster. Partly this was because I’d forgotten that CharacterController exists, but also even if I’d remembered I may still have opted to create my own Ambulator simply because I wanted to minimize the amount of Unity-isms that I’d have to remember how to work with, and I already know very well how to write the kind of code I was aiming for without relying on Unity’s help to do it.

It turns out that this combination of decisions was simultaneously the best choice I could make and the worst choice. I liked (and still like) the simplicity of the Ambulator, and I feel it does exactly what it needs to with no overhead or extra API functionality to worry about. Then by letting Unity handle the physics of falling objects, there was a whole class of code I did not have to write in order to make the characters collide which saved valuable time. On the other hand, there are many idioms for working with the physics engine in Unity that aren’t always the most conducive to the traditional 2D platformer physics that players expect, and this expressed itself in how the character handles jumping face-first into a wall or obstruction. The difficulties can be worked around, and to a large degree I did manage to work around them (though not to the degree I wanted to by the end of the 48 hours), and after the end of the competition I have discovered yet more ways to work around them. I think this was possibly one of the most valuable technical lessons I took away from the experience of making a Ludum Dare game. If I were to do it again, I would probably choose to implement more of the physics on my own rather than to use the CharacterController component, but I think there’s a good case to be made for trying both approaches just to see where the limits are.

– Sound Design –

You’ll notice that there are no sounds or music. I’ll come out and say it, my history has not included much in the way of sound design. That isn’t to say I didn’t give it a shot, however. I followed the advice of fellow Ludum Dare entrants and traveled on over to BFXR to see if I could cobble together some nice sound effects, and maybe even the rudimentary beginnings of a music loop. After 3 hours of fiddling around with settings and sound generation I realized that I was getting nowhere. Nothing really sounded like I wanted it to and I was beginning to feel that I wouldn’t have the time to really test out every combination of sounds such that I would know how to achieve the effect I was after. This being the case, I chalk it up to a lesson learned even though it ultimately did not advance the state of the final build. I won’t make that mistake again. By the next Ludum Dare I will either know enough to make my own sounds to my satisfaction or I won’t even make the effort and save the time for design or programming. Speaking of design…

– Level Design –

A consequence of my decision to make a game in which a little person flees from the loving embrace of an oversized monster is that level design is critical in selling the idea, because what you are creating amounts to an action-puzzle game. As you might expect then, all the time that was not spent generating art, music, programming, or concepts, was spent designing levels. By the time the competition ended, I had created seven of them. They all had been tested to make sure they were beatable, but also that they could not be cheated. This took time… lots of it. Inherent in creating all these levels was also the playtesting of them all. Any time I wanted to add a switch, a door, move the goal, move a platform, I had to test the entire level from the beginning. As such the levels are short. What they lack in length though, they tend to make up for in difficulty. I’m still finding the appropriate balance here. I think I could have done a better job easing the player into the rules and logic of the game world rather than throw them to the wolves immediately.

– Flair –

You can’t have a game without a title screen or an ending, right? Well, this game had to have both. The most fun part about this was the the title screen and the ending movie both are programmatically animated using the same logic that the characters use in the game. They appear to be acting “intelligently” but in reality are simply doing nothing more than following the logical results of the input supplied as though they were doing their normal business. Astonishingly, I feel like this was possibly the most fun part of the process for me : taking the engine and assets I’d built for use in a game and re-purposing it all to make a set of little movies.

– In Conclusion –

The competition was easily one of the most fun and rewarding weekends The Horseman has spent in the past year. Creating a game under such tight constraints was exhilarating and the knowledge that there were hundreds of other people attempting the same thing was incredibly motivating. When taking breaks from the action, The Horseman would look back at the Ludum Dare blogs to see how other people were progressing, and take heart at the progress of others and admiration at their interpretations of the theme. Would he do it again? The Horseman says : “Verily.”

As well, he says : Play Hug Monster! (-o^_^)-o

Tags: , , , ,

6 Comments


Putting Your Best Font Forward

No, the Horseman isn’t about to give you a lesson in typography (like traditional graphic design, it’s not exactly his forte). What the Horseman does intend to do however, is extol upon you the benefits of selecting the correct font for coding.

FlashDevelop is an incredible ActionScript IDE with very few things I feel left to be desired (linting, possibly… but Eclipse’s linting is just as bothersome as it is helpful so I’m on the fence here). The biggest problem I have with FlashDevelop is a flaw that is not unique to it but is shared by virtually every code editor I’ve used.

The default fonts are horrible.

In FlashDevelop and Eclipse both, the default font manages to break a cardinal rule of good programming typography. It’s difficult to distinguish at a glance the difference between 1, l, | and 0, O. Beyond that though, I just find the typefaces to be… clunkysuffocating, even.* I honestly never knew just how suboptimal the default fonts were for these editors until I stumbled across a discussion about a programmer’s font choice several years ago. That’s when the Horseman leapt upon his black stallion and sallied forth in search of a better font, to see just whether there was anything to this notion. After finding several worthy candidates, I finally settled on a font family known as Proggy. The creator wrote a short description of the thought process and design choices he made when designing Proggy, and I think he succeeded rather well.

Aside from the obvious benefits of total disambiguation of glyphs, the font has a “feel” and “flow” that work well to help me follow easily along with what’s on the screen. It bolds well, it italicises well, and the center-aligned operator symbols stand out clearly and distinctly. No dot operators being subsumed here! The font size works well for me too, hitting a sweet spot that the default fonts can’t quite manage to occupy in terms of letter spacing or line spacing.

The author is a C++ programmer, but Proggy certainly works wonders for ActionScript and thusfar as well for Java (and yeah, for XML as well).

So, one of the first thing I do these days when setting up a new IDE is to seek out Proggy and install my favorite of the variants (currently Proggy Clean). Maybe Proggy isn’t the font for you, but it’s almost certain that somewhere out there is a better font than the one your IDE uses by default. Taking some time to find it will pay dividends as you suddenly find your code easier to read. As I’m sure you know, code is frequently a “write once/read many” type of occupation, and anything that aids the reading aspect carries an unusually large boost to your productivity and peace of mind. Imagine all the hours you’ve spent on debugging that came down to stupid typos in a section of the code that can’t offer intellisense, and then imagine how many of them you’ll never lose again once your font is finally helping you.

 

 

* Not an exaggeration. While working with a default font-set, before actually realizing that the font was a default, I had this unshakable sense of tension that abated only upon seeing a friendlier typeface. I had no clue that I was barely breathing until I took a huge gasp of air after finally seeing my code look “right” again.

 

 

Tags: , , ,

4 Comments


“I put a function in your function, so you can process while you process!”

Maybe you’ve seen this before:

public function foo():void{
    // a function in a function?
    var onLoad:Function = function(e:Event):void{
        addChild(loader);
    }
    var loader:Loader = new Loader();
    loader.addEventListener(Event.COMPLETE, onLoad);
    loader.load(new URLRequest("someSwf.swf"));
}

It appears that the developer in question has written a function inside of a function. They were at least kind enough to assign it to a variable. They could have created one that is completely anonymous.

So, is there something wrong with this? In ActionScript 3 the answer is it kind of depends.

There are legitimate reasons why a developer might wish to do this, and they involve coding around a weakness in the Event model. The most interesting of these reasons is that this style represents the only way you can get away with early binding of variables. In doing so however, it’s easy to create objects that can never be eligible for garbage collection. Notice in the above example that the developer never removed the listener! In the examples to follow, I will exercise due diligence and remove them explicitly.

As an example, I’ve seen developers write code like this, thinking that the value of count will be “fixed” in the event handler to what it was when the handler was assigned:

private var count:int = 0;
private const MAX_COUNT:int = 10;
 
public function foo():void{
    while(count < MAX_COUNT){
 
        var onLoad:Function = function(e:Event):void{
            // offset the loader's x value by width * the number of images loaded.
            loader.x = loader.width * count;
            addChild(loader);
            e.currentTarget.removeEventListener(Event.COMPLETE, onLoad);
        }
        var loader:Loader = new Loader();
        loader.addEventListener(Event.COMPLETE, onLoad);
        loader.load(new URLRequest("someSwf.swf"));
    }
}

Only to discover that the value contained in count is not at all bound at the time the listener is added. They find that *all* their images end up at content.width * 10. Their next impulse is to “find a way to pass the current count to the event handler”, but you cannot do that. This:

// trying in vain to pass 'count' to the listener...
 loader.addEventListener(Event.COMPLETE, onLoad, count);

Is simply not valid AS3 code. There are two ways around this. My preferred method is to keep your real count at the class level, and to increment it in onLoad rather than to rely on the foo() function, and to never use a nested inner function. This gives the class a very plain set of signatures that can be read and interpreted in a list, and whose namespaces can be changed as needed to allow or deny access from both the outside and the inside. I find it worth the extra few lines of code and scrolling in the short term to have something easier to read in the long term.

 
private var count:int = 0;
private const MAX_COUNT:int = 10;
 
public function foo():void{
    // remove the count from foo, and use a local variable.
    var i:int = 0;
    while(i < MAX_COUNT){
        var loader:Loader = new Loader();
        loader.addEventListener(Event.COMPLETE, onLoad);
        loader.load(new URLRequest("someSwf.swf"));
        i++;
    }
}
private function onLoad(e:Event):void{
    var content:DisplayObject = e.currentTarget.content as DisplayObject;    
    content.x = content.width * count;
    this.addChild(content);    
    // increment the count here.
    count++;
    e.currentTarget.removeEventListener(Event.COMPLETE, onLoad);
}

So as you can see, there’s no need to use the listener-within-a-function. Why then, does it remain tempting for people? Aside from the fact that it requires less scrolling around the page and you can just write out the function in a place where you can see everything you’re thinking about, there is a special way to do this that allows you to use early binding. Get ready, because we’re about to take it another level down the rabbit hole.

public function foo():void{
    // a function in a function?
   for(count ; count < 10 ; count++){
        var onLoadHandler:Function = function():Function{
            var c:int = count;
            // with another function in a function inside of it???
            var handler:Function = function(e:Event):void{
                var count:int = c;
                var displayObject:DisplayObject = e.currentTarget.content as DisplayObject;
                displayObject.x = displayObject.width * count;
                addChild(loader);
 
                // IMPORTANT: Remember to remove your listener!
                e.currentTarget.removeEventListener(Event.COMPLETE, handler);
            }        
            return handler;
        }
        var loader:Loader = new Loader();
        // Call the function onLoadHandler to get the *real* function that is used as the listener as a return value
        loader.addEventListener(Event.COMPLETE, onLoadHandler());
        loader.load(new URLRequest("someSwf.swf"));
    }
 
}

Once you start nesting functions this deeply and returning the inner functions as values to be used, you’re stepping across the line of Object Oriented Programming into Functional Programming, though it’s a half-baby-step in this case. You’ll notice in this instance that the value of “count” in the innermost function is bound to the value of “count” at the class level as it existed when the originating function was declared in the for loop because of the intermediary “c” variable. This works because of the acrobatics involved in working across so many scopes in a single function call. I’ll come out and admit that while it can be initially confusing to see so many functions nested, it *is* convenient not to have to declare extra class level variables or scroll around looking for other functions in the code. You may wonder then why I prefer not to use them.

  • Function calls are processor intensive. Inside a long loop, calling so many functions adds considerable overhead.
  • It obscures your API. These inner-functions and variables never appear on a class diagram.
  • You can not directly touch these functions from anywhere except the scope in which you create them.

1. In my post about Array Optimization you’ll note that there’s nothing particularly intensive happening in those loops. Imagine however, that there *is* something to do in all those locations. There are no empty array locations, and for each item in the array there is a function call. Now imagine that there are two or three function calls. In fact don’t just imagine it, benchmark it yourself. You’ll find that function calls simply consume a great deal more resources than code written inline.

2. It’s one thing to write OOP code with intentional encapsulation such that objects don’t know much about each other. It’s another thing to write it such that the objects don’t know much about themselves. That’s essentially what’s happening when you rely on multiply nested function-scoped functions. It makes the code harder to understand at a glance from a high level. “I know that there’s a function that says to load images, but I don’t see where that’s being handled and I cannot override it in a subclass without overriding the loading function too.

3. This is the really big one, and the one that has the most room to trip you up in weird ways (hence the “pitfall” categorization of this entry). While Flash does offer you the option to add an event listener as a “weak reference” for aid in garbage collection, that doesn’t mean that once the object is eligible for gc that the object has ceased to exist, or that it will stop dispatching events. Far from it! With asynchronous events such as Event.COMPLETE (in the context of loading external content), TimerEvent (all of them), and even the synchronous Event.ENTER_FRAME, you’ll find that these events still dispatch, even if the references are weak, and even if the dispatching object is eligible for garbage collection. How do you remove an event listener that you don’t have any access to outside the scope in which it’s added? The only answer is “you have to do it inside the handler itself” which may not be practical or even possible under many circumstances. It is possible in the context of the Loader class (as demonstrated above) but the waters become murkier with ENTER_FRAME or TimerEvent(s), as the function now needs to undertake the responsibility of checking whether it should somehow remove itself from its dispatcher every time it executes, and possibly aborting execution if it should be removed.. This of course adds CPU overhead to the code, and if the event is dispatched frequently represents a large amount of needless processing.

You’re probably wondering why The Horseman would even tell people that this is possible if he’s so reluctant to use these nested functions himself. The simple answer is that people are going to do this anyway. No matter my own personal preference, there will always be coders whose first inclination is to use functions inside functions, and that’s fine. There’s a whole paradigm based around passing functions and relying ONLY on function scope, in fact! The problem comes when people who don’t know the risks and the trade-offs are careless about using them, particularly in an otherwise Object Oriented environment. Consider this to be a primer on those risks and the trade-offs, at least in the context of ActionScript 3. There are more to consider, but that’s for another time.

Tags: , , , ,

No Comments