Exemple #1
0
        public Transition(FSMEvent trigger, State target,
			Guard guard, Action action)
        {
            this.trigger = trigger;
            this.target = target;
            this.guard = guard;
            this.action = action;
        }
 /// <summary>
 /// Add a state.
 /// </summary>
 /// <param name="name">The name of the state</param>
 /// <param name="startState"><code>true</code> if this state is the start state</param>
 /// <param name="tickAction">An action called when the state is ticked</param>
 /// <param name="enterAction">An action called when entering the state</param>
 /// <param name="exitAction">An action called when exiting the state</param>
 public void AddState(string name, bool startState, Action tickAction, Action enterAction, Action exitAction)
 {
     State newState = new State(name, tickAction, enterAction, exitAction);
     states.Add(name, newState);
     if(startState) {
         if(this.startState != null) {
             throw new ArgumentException("Start state already set!");
         }
         this.startState = newState;
     }
 }
        /// <summary>
        /// Enters the start state.
        /// </summary>
        public void Start()
        {
            if(startState == null) {
                throw new InvalidOperationException("No start state set!");
            }

            if(currentState != null) {
                throw new InvalidOperationException("FSM already in a state");
            }

            startState.FireEnterAction();
            currentState = startState;
        }
        /// <summary>
        /// Trigger an event. If a transition exists for this event name in
        /// the current state, the state will change to the transition's
        /// target state.
        /// </summary>
        /// <param name="eventName">The event name.</param>
        public void TriggerEvent(FSMEvent evt)
        {
            if(currentState == null) {
                throw new InvalidOperationException("No current state (you may need to call Start)");
            }

            if(!registeredEvents.ContainsKey(evt.Name)) {
                throw new InvalidOperationException("Event is not registered");
            }

            State newState = currentState.TriggerEvent(evt);
            if(newState != null) {
                currentState = newState;
            }
        }
        /// <summary>
        /// Reset this FSM to the start state.
        /// </summary>
        public void Reset()
        {
            if(currentState != null) {
                currentState.FireExitAction();
                currentState = null;
            }

            Start();
        }