-
var currentState:String = "";
-
-
var functionList:Vector.<Function> = new Vector.<Function>();
-
-
function clearFunctions():void{
-
functionList = new Vector.<Function>();
-
}
-
function addFunction(f:Function):Function {
-
functionList.push(f);
-
return addFunction;
-
}
-
-
function removeFunction(f:Function):void {
-
for (var i:int = 0 ; i<functionList.length; i++){
-
if (f == functionList[i]){
-
functionList.splice(i, 1);
-
}
-
}
-
}
-
-
function runProgram():void {
-
-
currentState = "current: ";
-
-
for (var i:int = 0; i<functionList.length; i++){
-
functionList[i]();
-
}
-
-
trace(currentState);
-
}
-
-
function one():void{
-
currentState += " one";
-
}
-
-
function two():void {
-
currentState += " two";
-
}
-
-
function three():void {
-
currentState += " three";
-
}
-
-
function dot():void{
-
currentState += ".";
-
-
}
-
-
// test it:
-
addFunction(one);
-
addFunction(two);
-
addFunction(three);
-
-
runProgram();
-
-
removeFunction(one);
-
-
runProgram();
-
-
addFunction(dot)(dot)(dot);
-
-
runProgram();
-
-
clearFunctions();
-
-
addFunction(dot)(dot)(dot);
-
-
addFunction(three)(two)(one)(dot)(dot)(dot);
-
-
runProgram();
-
-
/* outputs:
-
current: one two three
-
current: two three
-
current: two three...
-
current: ... three two one...
-
*/
This is a very quick implementation of a pattern that I use sometimes. The idea of this pattern is very simple and can easily be implemented in OOP or procedural style programming. The idea is to have a Vector/Array of functions or Class instances. Loop through this Vector/Array and run each function (or a given method of each Class instance). During runtime your client code can alter this list to change what the program does.
I use this technique for games quite often. All enemies get added to an enemy list - this list is looped through and each enemies run() method is called. If an enemy dies it dispatches an event that tells the enemy manager to remove it from the list. Some pseudo code:
-
function onMainLoop():void{
-
if (!paused){
-
-
runWorld();
-
runKeys();
-
runChar();
-
-
enemyManager.runEnemies();
-
-
runPickups();
-
-
}else{
-
// show pause screen
-
}
-
}
-
-
//... inside EnemyManager class
-
function onRunEnemies():void{
-
for (var i:int = 0; i<enemyList.length; i++){
-
enemyList[i].run(i);
-
}
-
}
I use the same technique for pickups (coins, lives etc....).
I first used this technique in Director with a list of parent scripts.
I'm aware of other more refined patterns that are meant to do similar things, but for small to medium sized apps this has worked very nicely for me.
2 Comments
Wow, we got a bonus by an extra post today Thanks for keeping it fresh :), and running my fav blog.
Glad you enjoy the blog, thanks for the kind words.