Sequential programming

If you program games or real time simulation you probably found yourself trying to achieve sequential executions(do this, then this, wait to finish this…) in the step/update function of your code. How many times have you write code that checked if you are at the end of an animation to do something else after that? You can overcome this problem using ifs and flags, if your list of things to do sequentially is short. But we all know that short term solutions can turn into horrible nightmares if the extrapolate the same pattern of adding more ifs and variables.

THE PROBLEM

Generate an easy way to execute functions sequentially. Execute one function, wait until it’s done, execute the next function until there are no more functions to execute.

PROPOSE SOLUTION(for haxe/as3)

Generate a class that handles the problem! So my solution is quite simple, just create a class that store the functions to be executed and execute them one at a time.
The first thing we need to know is when a function has finish. To do this we simply return a bool in all the functions. If we finish doing what we needed to do in the function we return true, if not we return false.

Here an example how to manually loop an animation using the SequenceCode class

var mSequencer:SequenceCode=new SequenceCode();
mSequencer.addFunction(loop);

public function update(aDt:Float):Void
{
mSequencer.update(aDt);
}

and here the functions…

private function loop(aDt:Float):Bool
{
  mSequencer.addFunction(resetAnimation);
  mSequencer.addFunction(animationFinish);
  mSequencer.addFunction(loop);
}
private function animationFinish(aDt:Float):Bool
{
  return mCurrentAnimation.totalFrames==mCurrentAnimation.currentFrame;
}
private function resetAnimation(aDt:Float):Bool
{
  mCurrentAnimation.goToAndPlay(0);
return true;
}

You can even create simple animations sequences with a variable target and a function moveToTarget(aDt) that returns true once it reach the target.

You can use it to create simple AI :

private think(aDt:Float):Boolean
{
if(player is far away)
{
 mSequence.addWhile(notNear,follow);
 mSequence.addFunction(think);
}else{
 mSequence.addWait(1);
 mSequence.addFunction(attackSequence);
 mSequence.addFunction(think);
}
 return true;
}

The logic code gets far more readable using this approach vs the ifs and the flags.

The full code of the SequenceCode class can be found here https://github.com/juakob/SequenceCode/tree/master/utils

Fell free to write me back =)

In my next post I will show you how to use my implementation of a behavior tree https://github.com/juakob/BehaviorTreeHaxe