From refactor to library
Or how to refactor the code from your last game to build up your reusable libs.
First and foremost, thanks to the people at FGL chat that brainstormed a jolly good topic to write about. This post also helps me to rethink my strategy about an issue I have with our core libs that I’ll hopfully address in the future as soon as I make sense.
Basic question is how do I handle the code I used in the previous game to reuse it… I’ll give several examples of how our core classes appeared or changed hoping that you find something useful for your own code and games.
In the beggining there was music
When we wrote Tech Wars, I had to write a music manager that would know when to change tracks. There are three tracks in Tech Wars, all with the same beats per minute, two share the melody but with different instruments and one has a slight variation of the melody. Each track served a part of the game, such has menus, level, and post-level.
Our current music manager has code from Tech Wars. That code evolved from a game specific class to a generic sound manager class and then to two separate classes: sound manager and music manager. These shifts occured as the next games needed or between projects.

What started with Tech Wars is now what we call the core, which is simply a bunch of abstract, cross-project oriented organization of directories and classes that goes from one project to another. It is not something you do, it is something you keep doing, building and evolving. That sound manager class was a bad case of refactoring, but a good start since we had no reusable AS code.
Generalization
To create your libs you should make each class abstract from the game code. This maybe trickier than it sounds. For instance, we have a Scene Manager. What it does is quite simple:
1. ensures that one and only one scene is running
2. ensures that one and only one dialog is running
3. ensures that when a scene is started the current scene and current dialog are closed
4. ensures that when a dialog is started the current dialog is closed
And this has to work in every game. To be sure that it works in every game I made sure that a scene or a dialog is always a movie clip that is linked in the fla library and that I can pass up to five arguments to it. I also made sure that the Scene Manager is a singleton.
Get yourself organized
To be sure that your code is generic, organize it! Create a structure outside your game logic, as an example, when I start a project I copy the core directory from the previous project to the root of the current project and I create a separate directory “game” where all the game specific classes go.
It’s that simple.
Refactoring
Refactoring plays a big role in all of this. Now that the core classes are a few and that most of the nasty work is done, the process of refactoring tunes it and adds to it.
Again… an example. Some hours ago I was using a static method MathKit.AngleBetweenPoints(p1, p2) which is pretty obvious, but for some reason the code did not produce the results I predicted, so I wrote a bit of code to ensure the output I was looking for.
The issue was that MathKit.AngleBetweenPoints(p1,p2) returns an angle in radians and I wanted degrees. I already have two static methods in the MathKit class to convert radians in degrees and vice-versa, so in the next refactoring session I’ll rename MathKit.AngleBetweenPoints to MathKit.RadiansBetweenPoints and create a new DegreesBetweenPoints.
The refactoring will eliminate generic code from game specific code, it will reuse static methods we already have in the MathKit class, make the method already there more intuitive and create an additional method for other uses.
Managers = Singletons
Managers are classes that take care of a specific aspect of your game. Scenes, music, sound and so on. You should be sure that your managers are singletons and that you can access them everywhere. To be sure of it, all our managers are loaded by the Application Manager which is what all our document classes extend. Neat trick and quite useful.
Tools = Static
All our tools are static methods. We don’t want our tools to be instantiated. We don’t want our tools to hold data. We want our tools to do something specific and produce an output.
At the end of the day
Like I said, when we start a new game I copy the core directory of the latest game to the new one. Usually I take a look a t it or look for //TODO remarks for something I want to review. While the code base was growing this was very useful, right now it’s a matter of tunning some details since most work is done while refactoring.
I do have a damn project to go though… writing the graphic handling classes… but I still have a load of doubts to sort first.
Oooops… big one… Vlad out!
Posted: June 30th, 2009
at 11:40pm by Vlad
Tagged with Bold Pixel Engine, Design Patterns, FlashGameBlogs
Categories: The code of VGS
Comments: 1 comment
Model… revisited…
Hi everyone, it’s Vlad again.
It’s 10:52AM, 30 degrees Celsius if you stand in the shadow and just a couple of hours ago I hit an issue with our current project. Basically static data regarding gameplay was becoming completely unmanageable. Before moving forward I decided to rethink and drew how my classes were organized.

Let me tell you what this is… Data and Gameplay are folders, packages in AS3 terms. Tokentype1, Tokentype2 and Constants are classes that hold data in the form of static functions and constants. LevelController, LevelView, TokenController and TokenView are classes that are either controllers or views of my gameplay objects.
This is how I’ve organized most projects until now, so what’s the problem? For starters, all games until now have only one token type. This game has two but it will have more. I was about to actually copy/paste a method from TokenType1 class to the TokenType2 class… you know how bad this is right?
On top of that a new problem was present for a couple of days. Some variables names, class names and query methods conflicted, not logically but in terms of what I was reading while coding. Building, IsBuilding, buildings, building and so on… variables like type, code and state also weren’t 100% clear.
So I decided that it was time to redesign and refactor before it became too nasty. Here’s the result:

I simply took the MVC pattern seriously and created models for both level and tokens. On top of that I changed all ambiguous variables, states and methods to be named consistently throughout the project.
The LevelModel is nothing more than the old Constants class. There’s no big difference for now except that when gameplay is closed and we move to other stuff, I’ll have to create models for all the other stuff instead of having all constants inside one “global” constants class.
The TokenModel is the big change! It holds all the stuff from TokenType1 and TokenType2 classes, but now I can guarantee that there are no duplication of methods, arrays and so on. Big part of this arrangement was to deal with the inconsistent naming of variables and so on.
I’m very happy with the solution, now, if you excuse me, I’ll get back to coding game functionalities.
Posted: June 19th, 2009
at 10:25am by Vlad
Tagged with Design Patterns, FlashGameBlogs, Software Engineering
Categories: The code of VGS
Comments: No comments
Model View Controller
I learnt about the MVC pattern when I was presented to the book Game Coding Complete. Although the implementation of this pattern on a game development related environment can take some pre-planning, using it allows a much cleaner implementation of your objects with particular relevance for those that have a visual implementation, such as a level or a game token.
I’m saying object, not as an instance of a class, but rather as an abstract game object from a design point of view.
Let’s break the pattern down into manageable parts… after all, that’s exactly what the pattern does.
Model
The model is the data representation of your object. Outside game development, model refers to the data model, usually supported by a database engine. From a game development perspective, model is what your object is, like a level, a platform, the player character, an enemy and so on. If you coded a class that represents something, you have already created a model already.
The main difference with application development is that the data models you use are not persistent and are discarded when they’re not needed.
The idea you should retain game development wise is that your “typical” class design, considering variables, constants and so on is your model, even if this is not 100% accurate from the pattern point of view.
View
The view is the visual representation of your object, which would be any display object, from a movie clip to a bitmap. It is nothing more than this.
Controller
The controller glues everything together! It is the logic behind the actions of your object. Imagine a player character that moves with WASD for the actions Jump, Crouch, Move Left and Move Right. If the player presses W the controller will receive the event and order the view to run the jump animation. Now imagine that some enemy shoots the player character while it is jumping. The controller receives the information that the player was shot, informs the model to subtract damage to player’s life and orders the view to run the hurt animation.
Encapsulating all together
The easiest way to implement OOP on your AS3 game is to simply extend some movie clip to a class and write all code there. With MVC, you need to encapsulate a bit. There are many ways to do this, but this is how I do it.
My controller and view are only one class: the main object class. The view is separated which allows me to have a cleaner interface when I’m working and the possibility of extending or not the view class. This offers a wide range of possibilities since the view class can hold a large ammount of functionality, such as movement patterns, pathfinding and so on or it can simply be the display object.
Controller and view work together regarding data and logic. As I see it they’re not even separarated as a proper implementation of MVC. This often means that a simple state machine is at work, like in the example below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package
{
// This is my controller/model class
public class PlayerController
{
public function PlayerController()
{
// Creates the view
playerView = new PlayerView();
// Code to add it to the level movie clip goes here
}
public function Update()
{
// This method is called from the gameloop
// Depending on the state, chooses actions
switch(state)
{
case IDLE:
playerView.UpdateAnimation(IDLE);
break;
case WALK:
playerView.UpdateAnimation(WALK);
break;
case HURT:
playerView.UpdateAnimation(HURT);
break;
case NONE:
SetState(IDLE);
break;
}
}
public function SetState(newState:int)
{
// No point in doing something that
if (newState == state) return;
// Only does something different if the player is hurt
if (newState == HURT) life--;
// And assigns the new state
state = newState;
}
// Vars ---------------------------------------------------------------
private var life:int = 100; // Hit points
private var state:int = NONE; // Current state
private const NONE:int = 0;
private const IDLE:int = 1;
private const WALK:int = 2;
private const HURT:int = 3;
private var playerView:PlayerView; // The view (displayObject)
}
} |
A word of caution
MVC is very powerful, easy and intuitive, but use it when your game asks for it. If you have an object that only needs a couple of methods, by all means, simply extend the movie class or whatever you are extending. Use it to break the complex objects into manageable parts.
Posted: March 18th, 2009
at 12:00am by Vlad
Tagged with Design Patterns, FlashGameBlogs
Categories: The code of VGS
Comments: No comments
Opening files and URLs

URL
I don’t know about you, but I really hate those little bits of code that you will use in every single game but not during the actual development of it. As far as I’m concerned, even if not the most noble usage of the “reuse your code” rule, getting rid of these pesky little pieces of code is the single most useful usage of object oriented programming, not because I read it somewhere but because I’ll never have to worry about it again!
Opening files and URLs are two examples those pesky bits of code and to me both are perfect candidates to our framework Toolkit class! So here’s the code of the two static functions that were created to deal with it.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/*Opens an external file. Upon completing the task, callbacks to the
*given function.*/
public static function OpenFile(filename:String, callback:Function)
{
var ldr:URLLoader = new URLLoader();
ldr.load(new URLRequest(filename));
ldr.addEventListener(Event.COMPLETE, callback);
}
/*Opens a URL on a new window.*/
public static function OpenURL(url:String)
{
var urlReq:URLRequest = new URLRequest(url);
navigateToURL(urlReq, "_blank");
} |
Posted: March 11th, 2009
at 12:00am by Vlad
Tagged with FlashGameBlogs, Snippets
Categories: The code of VGS
Comments: No comments
Factory

Factory
I try to use design patterns to the best possible extent of my ignorance about them. I want to set this straight because like anything found on the Internet, everything here is potentially wrong or a lie. ![]()
My view on design patterns and so many other things code wise is much more from my own personal perspective and experience, if you want to know more, there’s much more to learn about it, this is just how I see it.
What is a Factory?
Factory was probably the first I was taught (thanks Diogo!) and one that I used in every single game. From ballons to bullets, every time the need to create objects arises, factory was my choice.
The only purpose of a factory is to create and return objects. From a game development point of view this is useful since the factory is by default reusable code within the game.
If you code a factory class you can use it as a priceless source of objects, from projectiles – as in this example – to enemies or whatever you want really, it’s up to you.
Example
Imagine you are coding a shooter where the player has four possible weapons: machine gun, rocket, missile and mines. Every time the player shoots, the player object would have to decide what to build based on the current weapon. It would be something like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package FactoryExample
{
import flash.display.MovieClip;
public class NoFactoryPlayerClass
{
public function FireWeapon() extends MovieClip
{
switch(currentWeapon)
{
case BULLET: CreateBullet(); break;
case ROCKET: CreateRocket(); break;
// And so on and so forth...
}
}
private function CreateBullet()
{
var bullet:Bullet = new Bullet(rotation);
// Plus, add bullet to level bla bla bla
}
private function CreateRocket()
{
var rocket:Rocket = new Rocket(rotation);
// Plus, add rocket to level bla bla bla
}
private var currentWeapon:int = BULLET;
private const BULLET:int = 1;
private const ROCKET:int = 2;
private const MISSILE:int = 3;
private const MINE:int = 4;
}
} |
By the way, the code here is for clarity, I didn’t even run it to check for errors.
What we have here is bad enough by the way. CreateBullet() and CreateRocket() would roughly have the same construction for instance, but it can get much worse. What if you want to use one, some or all the weapons in different enemies or you want to have more weapons?
I’m guessing… copy/paste?
That’s why you should use a factory from start: because you can manage all your projectiles from a single point and you can extend it to have more weapons without duplicated code which you’d probably maintain with a higly dangerous dosage of copy and paste.
This would be our factory class:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package FactoryExample
{
public class Factory
{
public static function CreateProjectile(type:int, data:* = null)
{
/* Bullets and Rockets only receive an angle from which they'll
* calculate the vector.
* Missiles - see FireMissile method.
* Mines just stand still. */
switch(type)
{
case BULLET: return new Bullet(data); break;
case ROCKET: return new Rocket(data); break;
case MISSILE: return FireMissile(data); break;
case MINE: return new Mine(); break;
}
}
private static function FireMissile(enemy:*)
{
// Gets the angle from the level object to create the missile.
var enemyAngle:Number = LevelObject.GetAngle(enemy);
// Creates the missile with the target enemy and the angle.
return new Missile(enemy, enemyAngle);
}
// Projectile types ---------------------------------------------------
public static const BULLET:int = 1;
public static const ROCKET:int = 2;
public static const MISSILE:int = 3;
public static const MINE:int = 4;
}
} |
In this case, the factory is a class that offers static functions, so you don’t have to instantiate an object from the Factory class. Note that the CreateProjectile receives the type (duh!) and some other data that can be anything or nothing at all.
The purpose of this is to pass angle to bullets and rockets, the target enemy to missiles and nothing to mines.
So now, any class that would need to fire a projectile would need a method like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package FactoryExample
{
import flash.display.MovieClip;
public class WithFactoryPlayerClass extends MovieClip
{
private function Fire()
{
var data:* = null;
switch(currentWeapon)
{
case Factory.BULLET: data = rotation; break;
case Factory.ROCKET: data = rotation; break;
case Factory.MISSILE: data = targetEnemy; break;
}
var projectile:* = Factory.CreateProjectile(currentWeapon, data);
// Do more stuff with projectile
}
private var currentWeapon:int;
private var targetEnemy:*;
}
} |
And to end…
Imagine that the enemies in your game have a predifined weapon… instead of a bunch of code you will only need one line in you enemies classes:
|
1 |
var projectile:* = Factory.CreateProjectile(myWeapon, otherData); |
It can’t get any easier than this!
I hope this helped you sort how factories can help you. Take into consideration that you can use a factory with pools of objects, this is an example that creates all objects on demand. There’s a lot more that can be done, but the rule of thumb is: a factory can be the answer to many object creation needs a bit everywhere, but in game development it really shows what this design pattern is capable of.
Posted: March 9th, 2009
at 12:00am by Vlad
Tagged with Design Patterns, FlashGameBlogs
Categories: The code of VGS
Comments: 4 comments
