Yangbo's Blog!

Artificial Intelligence Board Game.
Browsing AI

Bitboards

April8

AS3 BitBoard(based-on BitVector) preview:
This is our ChineseChess as3 bitboard:
[R][K][B][O][M][O][B][K][R]
[0][0][0][0][0][0][0][0][0]
[0][C][0][0][0][0][0][C][0]
[P][0][P][0][P][0][P][0][P]
[0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0]
[p][0][p][0][p][0][p][0][p]
[0][C][0][0][0][0][0][C][0]
[0][0][0][0][0][0][0][0][0]
[r][k][b][o][m][o][b][k][r]
Operations:

and

public function and(value:BitBoard):BitBoard
		{
			var bb:BitBoard =
new BitBoard(this.column,this.row);
			for(var h:int=0;h<_row;h++)
			{
				for(var w:int=0;w<_column;w++)
				{
					bb.setBitt(h,w,
Boolean((value.getBitt(h,w)&this.getBitt(h,w))));
				}
			}
			return bb;
		}


xor

public function xor(value:BitBoard):BitBoard
		{
			var bb:BitBoard =
new BitBoard(this.column,this.row);
			for(var h:int=0;h<_row;h++)
			{
				for(var w:int=0;w<_column;w++)
				{
					bb.setBitt(h,w,
Boolean((value.getBitt(h,w)^this.getBitt(h,w))));
				}
			}
			return bb;
		}


or

public function or(value:BitBoard):BitBoard
		{
			var bb:BitBoard =
new BitBoard(this.column,this.row);
			for(var h:int=0;h<_row;h++)
			{
				for(var w:int=0;w<_column;w++)
				{
					bb.setBitt(h,w,
Boolean((value.getBitt(h,w)|this.getBitt(h,w))));
				}
			}
			return bb;
		}


not

public function not():BitBoard
		{
			var bb:BitBoard =
new BitBoard(this.column,this.row);
			for(var h:int=0;h<_row;h++)
			{
				for(var w:int=0;w<_column;w++)
				{
					bb.setBitt(h,w,
!Boolean(this.getBitt(h,w)));
				}
			}
			return bb;
		}


rotate

public function rotate90():BitBoard
		{
			var bb:BitBoard =
new BitBoard(_row,_column);
			for(var w:int=0;w<_row;w++)
			{
				for(var h:int=0;h<_column;h++)
				{
					bb.setBitt(h,w,
Boolean(this.getBitt(w,h)));
				}
			}
			return bb;
		}


reverse

public function reverse():BitBoard
		{
			var bb:BitBoard =
new BitBoard(this.column,this.row);
			for(var w:int=0;w<_column;w++)
			{
				for(var h:int=0;h<_row;h++)
				{
					bb.setBitt(h,w,
Boolean(this.getBitt(_row-h-1,w)));
				}
			}
			return bb;
		}
This page is wiki editable click here to edit this page.

Programming game AI(ArtificalNerualNetwork) by (as3)example

December28

Warning: preg_match_all() expects parameter 2 to be string, array given in /home/content/g/o/d/godpaper/html/blog/wp-content/plugins/wordpress-wiki/wordpress-wiki.php on line 394

Warning: preg_match_all() expects parameter 2 to be string, array given in /home/content/g/o/d/godpaper/html/blog/wp-content/plugins/wordpress-wiki/wordpress-wiki.php on line 394

ArticicalNerualNetwork :?:

Example:

First off,let's overview this simple as3-based ArticicalNerualNetwork :
1.Neruron;
2.Nerurons;
3.NerualNetwork;

Next,

Code snippet

1.Neruron;

package
{
	/**
	 * A Neuron is the basic building block of a Neural Network
	 *
	 * @author Knight.zhou
	 *
	 */
	public class Neuron
	{
//--------------------------------------------------------------------------
//
//  Constructor
//
//--------------------------------------------------------------------------
		public function Neuron(layer:int,index:int)
		{
			this.layer = layer;
			this.index = index;
		}
//--------------------------------------------------------------------------
//
//  Properties
//
//--------------------------------------------------------------------------
		//----------------------------------
		//  layer(native)
		//----------------------------------
		/// Internal storage for Neuron.Layer public property
		private var _layer:int;
		public function get layer():int
		{
			return _layer;
		}
		/// INPUT LAYER = 0, HIDDEN LAYER = 1, OUTPUT LAYER = 2
		public function set layer(value:int):void
		{
			_layer = value;
		}
		//----------------------------------
		//  index(native)
		//----------------------------------
		/// Internal storage for Neuron.Index public property
		private var _index:int;
		public function get index():int
		{
			return _index;
		}
		/// Identifies a Neuron or the position of a Neuron in a LAYER
		public function set index(value:int):void
		{
			_index = value;
		}
		//----------------------------------
		//  input(native)
		//----------------------------------
		/// Internal storage for Neuron.Input public property
		private var _input:int;
		public function get input():int
		{
			return _input;
		}
		/// Input data fed to the Neural Network
		public function set input(value:int):void
		{
			_input = value;
			if(this.layer==0)
			{
				this.output = this.input;
			}else
			{
				this.output = this.logisticFunction(this.input);
				//System.Diagnostics.Debug.WriteLine("Layer : " + this.player + " Input " + this.pinput + " Output " + this.poutput);
			}
		}
		//----------------------------------
		//  output(native)
		//----------------------------------
		/// Internal storage for Neuron.Output public property
		private var _output:int;
		public function get output():int
		{
			return _output;
		}
		/// Calculated Ouput from the INPUT, HIDDEN or OUTPUT LAYER
		public function set output(value:int):void
		{
			_output = value;
		}
		//----------------------------------
		//  outputTraning(native)
		//----------------------------------
		/// Internal storage for Neutron.OutputTraining public property
		private var _outputTraning:int;
		public function get outputTraning():int
		{
			return _outputTraning;
		}
		/// Expected or Target or Learning output for a neutron
		/// in the OUPUT LAYER
		public function set outputTraning(value:int):void
		{
			_outputTraning = value;
		}
		//----------------------------------
		//  weight(native)
		//----------------------------------
		/// Internal storage for Network.Weight public property
		protected var _weight:Array=[];
		/// Storage for array of weights from OUTPUT to
		/// HIDDEN LAYER and from HIDDENLAYER TO INPUT
		/// LAYER. Each Neuron in the OUTPUT and HIDDEN
		/// LAYER is connected to an array of Neurons
		public function get weight():Array
		{
			return _weight;
		}
		//----------------------------------
		//  bias(native)
		//----------------------------------
		/// Internal storage for Network.Bias public property
		private var _bias:Number;
		public function get bias():Number
		{
			return _bias;
		}
		/// Varies the OUTPUT of a Neuronin a HIDDEN or OUTPUT LAYER
		public function set bias(value:Number):void
		{
			_bias = value;
		}
		//----------------------------------
		//  error(native)
		//----------------------------------
		/// Internal storage for Network.Error public property
		private var _error:Number;
		public function get error():Number
		{
			return _error;
		}
		/// Error = (ACTUALOUTPUT * (1 - ACTUALOUTPUT) * (EXPECTEDOUTPUT - ACTUALOUTPUT))
		public function set error(value:Number):void
		{
			_error = value;
		}
//--------------------------------------------------------------------------
//
//  Methods:
//
//--------------------------------------------------------------------------
		//----------------------------------
		//  logisticFunction(native)
		//----------------------------------
		/// Sigmoid Function or Logistic Function or Activation Function
		/// is applied to the INPUT to a NETWORK LAYER to get an OUTPUT
		/// The value to calculate a Sigmoid or Logistic Function for
		/// System.Double datatype of the Logistic or Sigmoid Function result
		public function logisticFunction(val:Number):Number
		{
			var tempExp:uint = Math.exp(-val);
			trace("tempExp:",tempExp);
			var logisticFunctionResult:Number = 1.0 / (1.0 + tempExp );
			trace("logisticFunctionResult:",logisticFunctionResult);
			return logisticFunctionResult;
		}
		//------------------------------------
		//  logisticFunctionDerivative(native)
		//------------------------------------
		/// Derivative of the Sigmoid Function or Logistic Function or Activation Function
		/// The value to calculate the derivative of the Sigmoid Function for
		/// System.Double datatype of the numeric result
		public function logisticFunctionDerivative(val:Number):Number
		{
			return val * (1 - val);
		}
	}
}

2.Nerurons;

package
{
	import mx.collections.ArrayCollection;

	/**
	 *A Neural Network Layer or collection of cells or neurons
	 *
	 * @author Knight.zhou
	 *
	 */
	public class Neurons extends ArrayCollection
	{
//--------------------------------------------------------------------------
//
//  Constructor
//
//--------------------------------------------------------------------------
		public function Neurons()
		{
		}
//--------------------------------------------------------------------------
//
//  Methods:
//
//--------------------------------------------------------------------------
		//----------------------------------
		//  add(native)
		//----------------------------------
		/// Adds a neuron to a Neural Network Layer or collection of cells
		/// The neuron to add to a Neural Network Layer
		public function add(newNeuron:Neuron):void
		{
			this.addItem(newNeuron);
		}
		//----------------------------------
		//  insert(native)
		//----------------------------------
		public function insert(index:int,newNeuron:Neuron):void
		{
			this.addItemAt(newNeuron,index);
		}

		/// ReadOnly indexer - retrieves the neuron at a
		/// specific position orlocation in the Neural
		/// Network Layer or Neural Network Collection
		//----------------------------------
		//  gett(native)
		//----------------------------------
		public function gett(index:int):Neuron
		{
			return this.getItemAt(index) as Neuron;
		}

	}
}

3.NerualNetwork;

package
{
	import mx.collections.ArrayCollection;

	public class NeuralNetWork
	{
//--------------------------------------------------------------------------
//
//  Variables
//
//--------------------------------------------------------------------------
		/// Static variable for random numbers
		static private var random:Number = 0.5;
		/// Static variable for number of neurons or cells in INPUT LAYER
		static private var input_count:int = 3;
		/// Static variable for number of neurons or cells in HIDDEN LAYER
		static private var hidden_count:int = 2;
		/// Static variable for number of neurons or cells in OUTPUT LAYER
		static private var output_count:int = 1;
		/// Static variable for the number of processing cycles of the Neural Network
		static public var iterations:int = 5;
		/// Represents the LEARNING RATE used in gradient descent to
		/// prevent weights from converging at sub-optimal solutions.
		public var learning_rate:Number = 0.8;
		/// A two dimensional array of input data from a training sample
		/// An INPUT represented as double [,] inputDataArray = new Double [,]
		/// {{0.20, 0.80}, {0.80, 0.4}} would represent 2 training instances
		/// for an INPUT LAYER with 2 NEURONS or CELLS
		public var input_data:ArrayCollection;
		/// A two dimensional array of output data from a training sample
		/// An OUTPUT represented as double [,] outputDataArray = new Double [,]
		/// {{0}, {1}} would represent 2 training instances
		/// for an OUTPUT LAYER with 1 NEURON or CELL
		public var output_data:ArrayCollection;
		/// A collection of neurons representing the input layer
		private var inputNeurons:Neurons;
		/// A collection of neurons representing the hidden layer
		private var hiddenNeurons:Neurons;
		/// A collection of neurons representing the output layer
		public var outputNeurons:Neurons;

//--------------------------------------------------------------------------
//
//  Constructor
//
//--------------------------------------------------------------------------
		public function NeuralNetWork()
		{
		}
//--------------------------------------------------------------------------
//
//  Properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
//  Methods
//
//--------------------------------------------------------------------------
		/// Initializes the LAYERS in the NEURAL NETWORK
		/// INPUTS data for the NEURONS in the INPUT LAYER
		/// OUTPUT data for the NEURONS in the OUTPUT LAYER
		/// The number of neurons in the HIDDEN LAYER
		//----------------------------------
		//  initialize(native)
		//----------------------------------
		public function initialize(inputData:ArrayCollection,outputData:ArrayCollection,hidden_layer_count:int):void
		{
			this.input_data = inputData;
			input_count = (this.input_data.length+1);//

			hidden_count = hidden_layer_count;

			this.output_data = outputData;//
			output_count = this.output_data.length+1;

			inputNeurons = new Neurons();
			for(var i:int=0;i<input_count;i++)
			{
				var a:Neuron = new Neuron(0,i);
				inputNeurons.add(a);
			}

			hiddenNeurons = new Neurons();
			for(var j:int=0;j<hidden_count;j++)
			{
				var b:Neuron = new Neuron(1,j);
				hiddenNeurons.add(b);
			}

			outputNeurons = new Neurons();
			for(var k:int=0;k<output_count;k++)
			{
				var c:Neuron = new Neuron(2,k);
				outputNeurons.add(c);
			}
		}
		//----------------------------------
		//  feedForward(native)
		//----------------------------------
		/// Initializes the NEURAL NETWORK with training data input
		/// or a real world data input for classification.
		/// FeedForward feeds the INPUT to the INPUT LAYER neurons
		/// FeedForward feeds the OUTPUT from the INPUT LAYER to the HIDDEN LAYER
		/// FeedForward feeds the OUTPUT from the HIDDEN LAYER to the OUTPUT LAYER
		/// FeedForward uses the Sigmoid Function or Logistic Function to calculate
		/// the OUTPUT from the INPUT in the HIDDEN and OUTPUT LAYERS

		/// A numeric ordered value representing the training or
		/// classification instance. If the dataset contains 10
		/// instances or rows, the first row has a sampleNumber = 0
		/// and the last row or instance has a sample number = 9
		public function feedForward(sampleNumer:int):void
		{
			var total:Number;
			var ch:Neuron = null;
			var ci:Neuron = null;
			var co:Neuron = null;
			//feed the input data to the input Neurons layer
			trace("input_data.length:",input_data.length);
			for(var i:int=0;i<inputNeurons.length;i++)
			{
				ci = inputNeurons.gett(i);
				ci.input = this.input_data.getItemAt(sampleNumer)[i];
			}
			//feedforward from input to hidden Neurons
			for(var h:int=0;h<hiddenNeurons.length;h++)
			{
				total = 0.0;
				ch = hiddenNeurons[h];
				for(var j:int=0;j<inputNeurons.length;j++)
				{
					ci = inputNeurons[j];
					total += ci.output*ci.weight[j];
				}
				ch.input = total+ch.bias;
			}
			//feedforward from hidden to output Neurons
			for(var o:int=0;o<outputNeurons.length;o++)
			{
				total = 0.0;
				co = outputNeurons.getItemAt(o) as Neuron;
				//feed the expected training result to the output Neurons layer
				co.outputTraning = this.output_data.getItemAt(sampleNumer)[o];
				for(var k:int=0;k<hiddenNeurons.length;k++)
				{
					ch = hiddenNeurons[k];
					total += ch.output*co.weight[k];
				}
				co.input = total+co.bias;
			}
		}
		//----------------------------------
		//  backPropagate(native)
		//----------------------------------
		/// Recalculates the BIAS and ERROR in the HIDDEN LAYER
		/// and OUTPUT LAYER. Adjustes the WEIGHTS between the
		/// OUTPUT LAYER and HIDDEN LAYER and between the HIDDEN
		/// LAYER and the INPUT LAYER using the derivative of
		/// the Sigmoid Function or Logistic Function
		public function backPropagate():void
		{
			var total:Number;
			var ch:Neuron = null;
			var ci:Neuron = null;
			var co:Neuron = null;
			//calculate error rate for Output layer
			for(var o:int;o<outputNeurons.length;o++)
			{
				co = outputNeurons[o];
				co.error = co.logisticFunctionDerivative(co.output)*(co.outputTraning-co.output);
			}
			//error from output to hidden layer
			for(var h:int=0;h<hiddenNeurons.length;h++)
			{
				total = 0.0;
				ch = hiddenNeurons[h];
				for(var o:int;o<outputNeurons.length;o++)
				{
					co = outputNeurons[o];
					total += co.error*co.weight[o];
				}
				ch.error = ch.logisticFunction(co.output)*total;
			}
			//update all weights in the network
			//from output Neurons to hidden Neurons
			for(var o:int=0;o<outputNeurons.length;o++)
			{
				co = outputNeurons[o];
				for(var h:int=0;h<hiddenNeurons.length;h++)
				{
					ch = hiddenNeurons[h];
					co.weight[h] += this.learning_rate*co.error*co.output;
				}
				co.bias += this.learning_rate*co.error;
			}
			//update all weights in the network
			//from hidden Neurons to input Neurons
			for(var h:int=0;h<hiddenNeurons.length;h++)
			{
				ch = hiddenNeurons[h];
				for(var i:int=0;i<inputNeurons.length;i++)
				{
					ci = inputNeurons[i];
					ch.weight[i] += this.learning_rate*ch.error*ci.output;
				}
				ch.bias += this.learning_rate*ch.error;
			}
		}
	}
}
internal class Random
{
	/// Generates random double values between -1.0 and +1.0
	/// System.Double data type between -1.0 and +1.0
	public static function gett(minLimit:Number=-1000,maxLimit:Number=1000):Number
	{
		return (Math.random()*(maxLimit-minLimit+1)+minLimit);
	}
}


Supply interpretation

This page is wiki editable click here to edit this page.

Programming game AI(Steering behaivor) by (as3)example

November29

Steering behavior :?:

Example:

First off,let's overview this simple as3-based Steering behavior System:
1.Vehicle;
2.Steering Vehicle;
3.Behaviors;

Next,how to construct Steering Behavior using AS3?

Code snippet:


IVehicle;

/**
	 * The interface of vechicle type.
	 * all kinds of monster's type is vechicle.
	 *
	 * @author Knight.zhou
	 *
	 */
	public interface IVehicle
	{
		/**
		 * Sets / gets what will happen if character hits edge.
		 */
		function set edgeBehavior(value:String):void;
		function get edgeBehavior():String;
		/**
		 * Sets / gets mass of character.
		 */
		function set mass(value:Number):void;
		function get mass():Number;
		/**
		 * Sets / gets maximum speed of character.
		 */
		function set maxSpeed(value:Number):void;
		function get maxSpeed():Number;
		/**
		 * Sets / gets position of character as a Vector2D.
		 */
		function set position(value:Vector2D):void;
		function get position():Vector2D;
		/**
		 * Sets / gets velocity of character as a Vector2D.
		 */
		function set velocity(value:Vector2D):void;
		function get velocity():Vector2D;
		/**
		 * Sets x position of character. Overrides Sprite.x to set internal Vector2D position as well.
		 */
		function set x(value:Number):void
		/**
		 * Sets y position of character. Overrides Sprite.y to set internal Vector2D position as well.
		 */
		function set y(value:Number):void
		/**
		 * update vehicle 's properties.
		 */
		function update():void;
	}


ISteeringVehicle;

/**
	 *
	 * @author Knight.zhou
	 *
	 */
	public interface ISteeredVehicle extends IVehicle
	{
		function set maxForce(value:Number):void;
		function get maxForce():Number;

		function set inSightDist(value:Number):void;
		function get inSightDist():Number;

		function set tooCloseDist(value:Number):void;
		function get tooCloseDist():Number;

		function inSight(vehicle:VehicleSample):Boolean;
		function tooClose(vehicle:VehicleSample):Boolean;
	}


Behaviors;

IArrive

/**
	 *
	 * @author Knight.zhou
	 *
	 */
	public interface IArrive
	{
		function set arriveThreshold(value:Number):void;
		function get arriveThreshold():Number;

		function arrive(target:Vector2D):void;
	}


Supplmentary interpretation


Arrival

//----------------------------------
		//  arrive(implement IArrive)
		//----------------------------------
		/**
		 *
		 * @param target type is Vector2D
		 *
		 */
		private var _maxForce:Number = 100;
		private var _steeringForce:Vector2D = new Vector2D();
		public function arrive(target:Vector2D):void
		{
			var desiredVelocity:Vector2D = target.subtract(_position);
			desiredVelocity.normalize();

			var dist:Number = _position.dist(target);
			if(dist > _arriveThreshold)
			{
				desiredVelocity = desiredVelocity.multiply(maxSpeed);
			}
			else
			{
				desiredVelocity = desiredVelocity.multiply(maxSpeed * dist / _arriveThreshold);
			}

			var force:Vector2D = desiredVelocity.subtract(_velocity);
			_steeringForce = _steeringForce.add(force);
		}
		//----------------------------------
		//  update(override)
		//----------------------------------
		override public function update():void
		{
			_steeringForce.truncate(_maxForce);
			_steeringForce = _steeringForce.divide(mass);
			velocity = velocity.add(_steeringForce);
			_steeringForce = new Vector2D();

			//Handles all basic motion. Should be called on each frame / timer interval.

			// make sure velocity stays within max speed.
			velocity.truncate(maxSpeed);

			// add velocity to position
			_position = _position.add(_velocity);

			// handle any edge behavior
			if(edgeBehavior == WRAP)
			{
				wrap();
			}
			else if(edgeBehavior == BOUNCE)
			{
				bounce();
			}

			// update position of sprite
			x = position.x;
			y = position.y;

			// rotate heading to match velocity
//			rotation = _velocity.angle * 180 / Math.PI;
		}
		//----------------------------------
		//  bounce(private)
		//----------------------------------
		/**
		 * Causes character to bounce off edge if edge is hit.
		 */
		private function bounce():void
		{
			if(stage != null)
			{
				if(position.x > stage.stageWidth)
				{
					position.x = stage.stageWidth;
					velocity.x *= -1;
				}
				else if(position.x < 0)
				{
					position.x = 0;
					velocity.x *= -1;
				}

				if(position.y > stage.stageHeight)
				{
					position.y = stage.stageHeight;
					velocity.y *= -1;
				}
				else if(position.y < 0)
				{
					position.y = 0;
					velocity.y *= -1;
				}
			}
		}
		//----------------------------------
		//  wrap(private)
		//----------------------------------
		/**
		 * Causes character to wrap around to opposite edge if edge is hit.
		 */
		private function wrap():void
		{
			if(stage != null)
			{
				if(position.x > stage.stageWidth) position.x = 0;
				if(position.x < 0) position.x = stage.stageWidth;
				if(position.y > stage.stageHeight) position.y = 0;
				if(position.y < 0) position.y = stage.stageHeight;
			}
		}
This page is wiki editable click here to edit this page.

Programming game AI(FiniteStateMachine) by (as3)Example

November24

Finite State Machine(FSM)???

Example:

First off,let's overview this simple as3-based Finite State Machine System:
1.IState;
2.IFiniteStateMachine;
3.Agent;

Next,how to construct Finite State Machine(FSM) using AS3?

Code snippet:


IState;

/**
	 * Each state implements the IState interface.
	 * Each state implements enter and exit metheod
	 * for one-off action that the agent takes
	 * when entering and leaving the state,
	 * in addition to the update method
	 * which is run repeatedly while in the state.
	 * The time parameter in the update method
	 * is the duration of the frame we're excuting.
	 *
	 * @author Knight.zhou
	 *
	 */
	public interface IState
	{
		/**
		 *
		 * @param value is the description of monster's state.
		 *
		 */
		function set description(value:String):void;
		function get description():String;

		function enter():void;//called on entering the state
		function exit():void;//called on leaving the state
		function update(time:Number=0):void;//called every frame while in the state
	}


IFiniteStateMachine

/**
     * Our FiniteStateMachine must implment this interface.
     *
     * @author Knight.zhou
     *
     */
    public interface IFiniteStateMachine
    {
        function set globalState(s:IState):void;
        function get globalState():IState;

        function set currentState(s:IState):void;
        function get currentState():IState;

        function set previousState(s:IState):void;
        function get previousState():IState;

        function set nextState(s:IState):void;
        function get nextState():IState;
    }


Agent;

/**
	 * The agent uses an instance of the FiniteStateMachine class the handle its AI.
	 * The agent class is a lot more manageable without the FSM implementation
	 * and all the states inside it. and must have a single FSM class
	 * that can be used by all agents(who)can even share states across agents too.
	 *
	 * @author Knight.zhou
	 *
	 */
	public class Agent
	{
		private var fsm:FiniteStateMachine;
		public var name:String = "unnamed";
		public var carrier:SWFLoader;
		public var traceTarget:TextArea;
		/**
		 *
		 * @param the name of agent;
		 * @param the carrier of agent;
		 * @param the agen's traceTarget;
		 *
		 */
		public function Agent(name:String,carrier:SWFLoader,traceTarget:TextArea=null)
		{
			fsm = new FiniteStateMachine(this);
			this.name = name;
			this.carrier = carrier;
			this.traceTarget = traceTarget;
		}

		public function update():void
		{
			fsm.update();
		}

		public function getFSM():FiniteStateMachine
		{
			return fsm;
		}
	}


Supplmentary interpretation

Custom state class implement sample:

FiniteStateMachine

/**
	 * The FiniteStateMachine is responsible for
	 * managing the current state.
	 *
	 * Add a number of features to the FSM class to
	 * all chaining of states and returning to previous states.
	 *
	 * @author Knight.zhou
	 *
	 */
	public class FiniteStateMachine implements IFiniteStateMachine
	{
		private static const LOG:ILogger = LogUtil.getLogger(FiniteStateMachine);
	    private var _globalState:IState;//For globally track monster's state.
		private var _currentState:IState;
		private var _previousState:IState;
		private var _nextState:IState;
		protected var owner:Agent;

		public function FiniteStateMachine( owner:Agent,
		                                    currentState:IState=null,
		                                    previousState:IState=null,
		                                    nextState:IState=null
		                                  )
		{
		    this.owner = owner;
			this.currentState = currentState;
			this.previousState = previousState;
			this.nextState = nextState;
		}
		/**
         * Prepare a global state for globally tracking current state.
         *
         * @param s is anew state;
         *
         */
        public function set globalState( s:IState ):void
        {
            _globalState = s ;
        }
        public function get globalState():IState
        {
            return _globalState;
        }
        /**
         * Prepare a state for using the current state.
         *
         * @param s is anew state;
         *
         */
        public function set currentState( s:IState ):void
        {
            _currentState = s ;
        }
        public function get currentState():IState
        {
            return _currentState;
        }
		/**
		 * Prepare a state for use after the current state.
		 *
		 * @param s is anew state;
		 *
		 */
		public function set nextState( s:IState ):void
		{
			_nextState = s ;
		}
		public function get nextState():IState
        {
            return _nextState;
        }
		/**
         * Prepare a state for use before the current state.
         *
         * @param s is anew state;
         *
         */
        public function set previousState( s:IState ):void
        {
            _previousState = s ;
        }
        public function get previousState():IState
        {
            return _previousState;
        }
		/**
		 * Update the FSM.
		 */
		public function update():void
		{
			if(currentState)
			{
				currentState.update();
			}
		}
		/**
		 * Change to another state.
		 *
		 * @param s is anew state.
		 *
		 */
		public function changeState( s:IState ):void
		{
			LOG.info("exited:{0}",currentState);
			currentState.exit();
			previousState = currentState;
			globalState = s;
			currentState = s;
			currentState.enter();
			LOG.info("entered:{0}",currentState);
		}
		/**
		 * Go to the previous state.
		 */
		public function goToPreviousState():void
		{
			changeState( previousState );
		}
		/**
		 * Go to the next state.
		 */
		public function goToNextState():void
		{
			changeState( nextState );
		}


SadLow

/**
	 * Monster's all kinds of talk states
	 *
	 * @author Knight.zhou
	 *
	 */
	public class SadLow implements IState
	{
		private var agent:Agent;
		//----------------------------------
		//  description(native)
		//----------------------------------
		private var _description:String = "STATE_SAD_LOW";
		public function get description():String
		{
			return _description;
		}
		public function set description(value:String):void
		{
			_description = value;
		}
		public function SadLow(monster:Agent)
		{
			this.monster = monster;
		}

		public function enter():void
		{
			//TODO: implement function
		}

		public function exit():void
		{
			//TODO: implement function
		}

		public function update(time:Number=0):void
		{
                       //TODO: implement function
		}
	}


Supple Interpretation

XMLFiniteStateMachine

<?xml version="1.0" ?>
<fsm name="XML FiniteStateMachine">
	<states>
		<state name="stateName">
			<transition input="someInputValue" trigger="triggerName" source="head" next="nextTransition"/>
		</state>
       </states>
</fsm>
This page is wiki editable click here to edit this page.
« Older Entries

BLOG CALENDAR

September 2010
M T W T F S S
« Apr    
 12345
6789101112
13141516171819
20212223242526
27282930