Search code examples
actionscript-3classartificial-intelligenceframeenter

Programming a simple AI in AS3


I'm trying to create a little game where you can control a movieclip around the board with arrows keys and at the same time there are little characters walking around.

I have an event listener for enterframe which constantly updates the user-controlled character that can move around the board. What I'm really hoping for is the ability to create an AI class to assign to the characters that walk around. This AI class would be responsible for their movement without me having to add additional code other than the code to initially create/add the AI movieclip instance to the stage.

So far I have an AI class which all character classes extend as their base class. Is there maybe a way to add another enterframe event listener in this AI class so the AI class can handle all the AI movement? Am I going in the wrong direction?

Thanks!

Mike


Solution

  • I'd say it's a good direction. In your AI class, create an addedToStage listener, and in that handler create an ENTER_FRAME handler that is either protected or public, then you can override parts of its behavior if you have slightly different needs for different character types.

    public class CharacterBase extends Sprite {
    
        public function CharacterBase():void {
            this.addEventListener(Event.ADDED_TO_STAGE,addedToStage,false,0,true);
            this.removeEventListener(Event.REMOVED_FROM_STAGE,removedFromStage,false,0,true);
        }
    
        private function addedToStage(e:Event):void {
            this.addEventListener(Event.ENTER_FRAME,enterFrameHandler, false,0,true);
        }
    
        private function removedFromStage(e:Event):void {
            this.removeEventListener(Event.ENTER_FRAME,enterFrameHandler);
        }
    
        protected function enterFrameHandler(e:Event):void {
            //do your AI moving around logic
            walk();
        }
    
        protected function walk():void {
            this.x += 2;  //the default walk behavior
        }
    }
    

    A Character overriding the default movement:

    public class Character1 extends CharacterBase {
        public function Character1():void {
            super();
        }
    
        override protected function walk():void {
            this.x += 5; //this character needs to be faster than default
        }
    }