kingBook

导航

状态机

 

package framework.fsm{
    public class Fsm{
        
        protected var _curState:State;
        protected var _callbackChangeState:Function;
        /**
         * 状态机
         * @param    defaultState 默认状态
         * @param    callbackChangeState 改变状态回调函数 function(state:State):void;
         */
        public function Fsm(defaultState:State,callbackChangeState:Function){
            _callbackChangeState=callbackChangeState;
            changeState(defaultState);
        }
        
        public function changeState(state:State):void{
            if(_curState)_curState.dispose();
            _curState=state;
            _callbackChangeState(_curState);
        }
        
        public function update():void{
            _curState.execute();
        }
        
        public function dispose():void{
            _curState=null;
            _callbackChangeState=null;
        }
        
        public function get curState():State{return _curState;}
    };
}

 

package framework.fsm{
    public class State{
        public function execute():void{}
        public function dispose():void{}
    };
}

 

package app{
    import framework.fsm.Fsm;
    import framework.fsm.State;
    public class StatePlayerIdle extends State{
        
        private var _player:Player;
        public function StatePlayerIdle(player:Player){
            _player=player;
        }
        
        override public function execute():void{
            //这个状态切换到其他状态的条件
            if(_player.isDeath){
                _player.fsm.changeState(new StatePlayerDeath(_player));
            }else if(_player.isInAir){
                if(_player.vy<0){
                    _player.fsm.changeState(new StatePlayerJumpUp(_player));
                }else{
                    _player.fsm.changeState(new StatePlayerJumpDown(_player));
                }
            }else if(!_player.isInAir && _player.isPressLR){
                _player.fsm.changeState(new StatePlayerWalk(_player));
            }
        }
        
        override public function dispose():void{
            _player=null;
        }
    };

}

 

 

private var _fsm:Fsm;
_fsm=new Fsm(new StatePlayerIdle(this),changeStateHandler);

private function changeStateHandler(state:State):void{
    if(state is PlayerStateIdle){
        //改变外观代码
    }
}

private function update():void{
    _fsm.update();
}

 

posted on 2016-06-16 09:43  kingBook  阅读(212)  评论(0编辑  收藏  举报