Haxe – AI in applications

The intelligent Haxe Main class

Some time ago I dealt with the term AI. I got stuck on the finite state machine pattern. This pattern is about defining states and, e.g. letting and enemy react to these states. In a game for example your enemy is in standby state.

When you walk by the enemy will activate the attack state and attack you. If he defeats you, he will switch back to the standby state.
When he realizes that he is running out of health he switches in the flee state and runs away.

Why not try to adapt this pattern in the structure of my modules?

I like the idea of let the Main class react to actions like clicks or coditional expressions.

Let’s set a few states for this main class. Init, standby, foo and bar.
This way the code is becoming cleaner and more readable.

class Main {
	
    public static var fsm:FiniteStateMachine;
    
    static function main(){
    	fsm = new FiniteStateMachine();
        fsm.addState(new SFMState("init", initHandler));
        fsm.addState(new SFMState("standby", standbyHandler));
        fsm.addState(new SFMState("foo", footHandler));
        fsm.addState(new SFMState("bar", barHandler));
        ...
        fsm.changeState("init");
    }
	...
    public static function initHandler():Void{
    	...
        // Here is only the code that belongs to the init state
        ...
        if( condition ){
        	fsm.changeState("foo");
        }else if( condition ){
        	fsm.changeState("bar");
        }else{
        	fsm.changeState("standby");
        }
    }
    
    public static function standbyHandler():Void{
    	...
        // Here is only the code that belongs to the standby state
        // Waiting for action
        ...
    }
    
    public static function fooHandler():Void{
    	...
        // Here is only the code that belongs to the foo state
        ...
        fsm.changeState("standby");
    }
    
    public static function barHandler():Void{
    	...
        // Here is only the code that belongs to the bar state
        ...
        fsm.changeState("standby");
    }
}

A cool feature would be a kind of event mechanism, so you could listen for state changes taking place somewhere else.

Or you can handle the states in a store locator module (init, mapview, detailview).

Much room for ideas…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>