public void AddLinkTo(string toState, StateDelegate logic)
    {
        if(logic == null && !links.ContainsKey(toState))
        {Debug.Log("Add StateLink Error"); return;}

        links.Add (toState, logic);
    }
 protected virtual void AttackingState()
 {
     stateIndicator = "attacking";
     UpdateAssistTargetting();
     if (attackTarget == null)
     {
         stateDelegate = IdleState;
     }
     else
     {
         if (TargetInRange())
         {
             setRails(false);
             // TODO use coroutine for attack cooldown
             if (ReadyToAttack())
             {
                 Attack();
             }
         }
         else
         {
             setRails(true);
             // Move towards the enemy
             //navigationController.registerClick(this, attackTarget.transform.position);
             Move();
         }
     }
 }
Exemple #3
0
 public void UnsetStateDelegate(int state, StateDelegate @delegate)
 {
     if (_delegates.ContainsKey(state))
     {
         _delegates[state].Remove(@delegate);
     }
 }
Exemple #4
0
    public virtual float UpdateActiveState()
    {
        float thefloat = -1;

        if (!IsEmpty() && !blockStateMachine)
        {
            StateDelegate active_state = m_stateStack[m_stateStack.Count - 1];
            bool          resumeLoop   = true;
            while (resumeLoop)
            {
                resumeLoop = false;

                thefloat = active_state();

                if (active_state != m_stateStack[m_stateStack.Count - 1] && KnightContext.instance.AutonomousUnits)
                {
                    //  TODO aherrera : is there some sort of "exit state" function I should call?

                    Debug.Log("FSM -- Resuming FSM loop");
                    active_state = GetActiveState();
                    resumeLoop   = true;
                }
            }
        }

        return(thefloat);
    }
Exemple #5
0
 public State(int enumIndex, StateDelegate enterD, StateDelegate updateD, StateDelegate exitD)
 {
     key = enumIndex;
     enter = enterD;
     update = updateD;
     exit = exitD;
 }
 public void DisconnectToDelegate(string key, StateDelegate value)
 {
     if (ContainsKey(key))
     {
         Values[Keys.IndexOf(key)] -= value;
     }
 }
Exemple #7
0
 /// <summary>
 /// Push a new state to the Top of the stack
 /// </summary>
 /// <param name="newActiveState"></param>
 public void Push(StateDelegate newActiveState)
 {
     if (GetActiveState() != newActiveState)
     {
         Debug.Log("FSM -- Adding new ActiveState: " + newActiveState.ToString());
         m_stateStack.Add(newActiveState);
     }
 }
Exemple #8
0
 void OnPrintingProgress(float amount)
 {
     if (Mathf.Approximately(amount, 1.0f))
     {
         HandleMenu = NormalMenu;
         Dispatcher <float> .RemoveListener(PrinterController.kOnPrintingProgress, OnPrintingProgress);
     }
 }
Exemple #9
0
 protected virtual void Start()
 {
     _rb   = GetComponent <Rigidbody2D>();
     _anim = GetComponent <Animator>();
     SetPatrolState();
     SetChaseState();
     State = Patrol;
 }
Exemple #10
0
 protected virtual void CheckDeath()
 {
     if (_hp <= 0)
     {
         State        = CheckDeath;
         _rb.velocity = Vector2.up * _rb.velocity.y;
         _anim.Play("Dying");
     }
 }
Exemple #11
0
        public void SetDelegateForState(int state, StateDelegate @delegate)
        {
            if (!_delegates.ContainsKey(state))
            {
                _delegates[state] = new List <StateDelegate>();
            }

            _delegates[state].Add(@delegate);
        }
Exemple #12
0
        //
        // State utility function implementations
        //

        /**
         * Initialise a simplehsm state machine.
         *
         * @param topState The topmost (and initial) state of the hierarchy
         *
         */
        protected void Initialize(StateDelegate topState)
        {
            // init top state
            this.topState = topState;
            // init deep history table
            deepHistoryTable.Clear();
            // transition to initial top state
            InitTransitionState(topState);
        }
Exemple #13
0
        protected void Add(StateDelegate state)
        {
            var index = IndexOf(state.Method);

            if (index == Const.INDEX_NONE)
            {
                states.Add(new StateInfo(state));
            }
        }
Exemple #14
0
 public void StateDeadUpdate(GameTime gameTime)
 {
     if (gameTime.TotalGameTime.Seconds - _timer.Seconds >= 3)
     {
         _timer                 = gameTime.TotalGameTime;
         _stateDelegate         = StateInvincibleUpdate;
         PlayerAnimation.Active = true;
         PlayerAnimation.Color  = Color.Red;
     }
 }
Exemple #15
0
        public void Initialize(Game1 game, Animation animation, Vector2 position)
        {
            PlayerAnimation = animation;


            _position      = position;
            Health         = 100;
            _stateDelegate = StateAliveUpdate;
            _game          = game;
        }
 protected virtual void MovingState()
 {
     stateIndicator = "moving";
     setRails(true);
     Move();
     if (path == null && navTarget == Vector3.zero)
     {
         stateDelegate = IdleState;
     }
 }
Exemple #17
0
        private static void HellowLambda()
        {
            StateDelegate stateDelegate = str =>
            {
                string s = str += "Lambda";
                MessageBox.Show(s);
            };

            stateDelegate("Hello  ");
        }
        public DelegateTriggerMachine <TTrigger, TEnumComparer> Connect(StateDelegate source, TTrigger trigger, StateDelegate destination)
        {
            Add(source);
            Add(destination);

            var transitions = connections.SafeGet(source.Method);

            transitions[trigger] = destination.Method;

            return(this);
        }
Exemple #19
0
 private void StateAliveUpdate(GameTime gameTime)
 {
     if (Health <= 0)
     {
         _timer = gameTime.TotalGameTime;
         _game.AddExplosion(_position);
         PlayerAnimation.Active = false;
         _stateDelegate         = StateDeadUpdate;
     }
     PlayerAnimation.Position = _position;
 }
Exemple #20
0
        public void StateInvincibleUpdate(GameTime gameTime)
        {
            if (gameTime.TotalGameTime.Seconds - _timer.Seconds >= 3)
            {
                PlayerAnimation.Color = Color.White;
                Health         = 100;
                _stateDelegate = StateAliveUpdate;
            }

            PlayerAnimation.Position = _position;
        }
Exemple #21
0
 /**
  * Check is one state is the parent of another.
  *
  * @param parentState The parent state to check
  * @param childState The child state to check
  * @return True if the parentState parameter is a parent to the childState parameter
  *
  */
 protected Boolean IsParent(StateDelegate parentState, StateDelegate childState)
 {
     do
     {
         childState = childState(new StateEvent(Signal.Null));
         if (childState == parentState)
         {
             return(true);
         }
     }while (childState != null);
     return(false);
 }
Exemple #22
0
 /**
  * Record deep history psuedostate.
  *
  * @param historyParent The parent state of the deep history psuedostate
  * @param historyState The state to return to if transitioning to the deep history psuedostate
  *
  */
 void RecordDeephist(StateDelegate historyParent, StateDelegate historyState)
 {
     for (int i = 0; i < deepHistoryTable.Count; i++)
     {
         if (deepHistoryTable[i].Parent == historyParent)
         {
             deepHistoryTable[i] = new DeepHistoryEntry(historyParent, historyState);
             return;
         }
     }
     deepHistoryTable.Add(new DeepHistoryEntry(historyParent, historyState));
 }
 protected virtual void FollowingState()
 {
     stateIndicator = "following";
     if (assistTarget == null || LeaderInRange())
     {
         stateDelegate = IdleState;
     }
     else
     {
         UpdateAssistTargetting();
         Move();
     }
 }
Exemple #24
0
        /**
         * Check if a state machine is currently in a certain state.
         *
         * @param state The state to check
         * @return True if the state machine is currently in the specified state
         *
         */
        protected Boolean IsInState(StateDelegate state)
        {
            StateDelegate parentState = curState;

            do
            {
                if (state == parentState)
                {
                    return(true);
                }
                parentState = parentState(new StateEvent(Signal.Null));
            }while (parentState != null);
            return(false);
        }
Exemple #25
0
    public StateDelegate GetActiveState()
    {
        StateDelegate returnVal = null;

        if (m_stateStack.Count > 0)
        {
            returnVal = m_stateStack[m_stateStack.Count - 1];
        }

        if (returnVal == null)
        {
            Debug.LogWarning("FSM -- returning a null ActiveState");
        }
        return(returnVal);
    }
Exemple #26
0
    /// <summary>
    /// 初始化代委托理事件
    /// </summary>
    private void InitDelegateEvent()
    {
        m_JoyStick = GameObject.FindObjectOfType<JoyStick>();
        m_JoyStick.OnJoyStickTouchBegin += OnTouchBegin;
        m_JoyStick.OnJoyStickTouchMove += OnTouchMove;
        m_JoyStick.OnJoyStickTouchEnd += OnTouchEnd;

        m_ButtonEvent = GameObject.FindObjectOfType<FightButtonEvent>();
        m_ButtonEvent.OnAttack += OnAttack;
        m_ButtonEvent.OnJump += OnJump;
        m_ButtonEvent.OnSkill += OnSkill;

        m_PlayerState = GameObject.FindObjectOfType<StateDelegate>();
        m_PlayerState.OnStateChange += SwitchPlayerState;
    }
    //Take Damage
    public virtual void Hit(UnitController attacker)
    {
        health -= attacker.attackStr;
        anim.flinchAnim();
        if (attackTarget == null)
        {
            attackTarget  = attacker;
            stateDelegate = AttackingState;
        }

        if (!attackers.Contains(attacker))
        {
            attackers.Add(attacker);
        }
    }
Exemple #28
0
 /**
  * Retrive deep history psuedostate.
  *
  * @param historyParent The parent state of the deep history psuedostate
  * @return The state to transition to via the deep history psuedostate
  *
  */
 private StateDelegate RetrieveDeephist(StateDelegate historyParent)
 {
     for (int i = 0; i < deepHistoryTable.Count; i++)
     {
         if (deepHistoryTable[i].Parent == historyParent)
         {
             StateDelegate res = deepHistoryTable[i].Child;
             // remove history state from deep history table
             deepHistoryTable.RemoveAt(i);
             // return deep history target
             return(res);
         }
     }
     return(null);
 }
Exemple #29
0
 /**
  * Send a signal to the state machine.
  *
  * @param e The event to send to the state machine
  *
  */
 public void SignalCurrentState(StateEvent e)
 {
     if (curState != null)
     {
         StateDelegate parentState = curState;
         do
         {
             parentState = parentState(e);
         }while (parentState != null);
     }
     else
     {
         System.Console.WriteLine("SignalCurrentState: ERROR - current state is invalid!\n");
     }
 }
Exemple #30
0
        public void AddState(string stateName, StateDelegate begin, StateDelegate tick, StateDelegate end)
        {
            StateInfo info = new StateInfo();

            info.OnBegin = begin;
            info.OnTick  = tick;
            info.OnEnd   = end;

            states.Add(stateName, info);

            // If no states have been set yet, this state becomes the initial state.
            if (currentStateName == null)
            {
                State = stateName;
            }
        }
Exemple #31
0
        public void SubscribeState(StateDelegate stateDelegate)
        {
            if (StateDelegatesList == null)
            {
                StateDelegatesList = new List <StateDelegate>();
            }

            if (!StateDelegatesList.Contains(stateDelegate))
            {
                StateDelegatesList.Add(stateDelegate);
            }
            else
            {
                Debug.Log("Already subscribed: " + stateDelegate.ToString());
            }
        }
Exemple #32
0
        public void UnsubscribeState(StateDelegate stateDelegate)
        {
            if (StateDelegatesList == null)
            {
                Debug.Log("Nothing subscribed yet, subscribe first!");
            }

            if (StateDelegatesList.Contains(stateDelegate))
            {
                StateDelegatesList.Remove(stateDelegate);
            }
            else
            {
                Debug.Log("Already removed: " + stateDelegate.ToString());
            }
        }
Exemple #33
0
 /**
  * Initiate an initial transition to a new state (this function should only be used from a #SimpleHsm::Signal::Init state event).
  *
  * @param newState The state to transition to
  *
  */
 protected void InitTransitionState(StateDelegate newState)
 {
     // set new state
     curState = newState;
     if (curState != null)
     {
         // entry signal to current state
         curState(new StateEvent(Signal.Entry));
         // init signal to current state
         curState(new StateEvent(Signal.Init));
     }
     else
     {
         System.Console.WriteLine("InitTransitionState: ERROR - current state is invalid!\n");
     }
 }
Exemple #34
0
	public void SwitchStates(StateDelegate enter, StateDelegate update, StateDelegate exit, string name){
		string switchDebug = "STATE TRANSITION: ";

		if (this.exit != null){
			switchDebug += this.currentState + " ";
			this.exit(); //exit the current state
		}
		
		//set up the new state
		this.enter = enter;
		this.update = update;
		this.exit = exit;
		this.currentState = name;
		
		if (this.enter != null){
			switchDebug += "--> " + name;
			this.enter(); //enter the new state
		}

		Debug.Log(switchDebug);
	}
Exemple #35
0
 //
 // State utility function implementations
 //
 /**
 * Initialise a simplehsm state machine.
 *
 * @param topState The topmost (and initial) state of the hierarchy
 *
 */
 protected void Initialize(StateDelegate topState)
 {
     // init top state
     this.topState = topState;
     // init deep history table
     deepHistoryTable.Clear();
     // transition to initial top state
     InitTransitionState(topState);
 }
Exemple #36
0
 public DeepHistoryEntry(StateDelegate parent, StateDelegate state)
 {
     Parent = parent;
     Child = state;
 }
Exemple #37
0
 /**
 * Check if a state delegates method has the DeepHistory attribute
 *
 * @param state The state to check
 * @return True if the method refered to by the delegate has the DeepHistory attribute
 *
 */
 protected bool HasDeepHistAttrib(StateDelegate state)
 {
     return state.Method.GetCustomAttributes(typeof(DeepHistory), false).Length > 0;
 }
Exemple #38
0
 // Utility method for performing the state delegate swapping logic based on an enum value
 void SwitchCurrentState(MState state)
 {
     this.mState = state;
     switch (mState) {
     case MState.None:
         currentStateMethod = null;
         break;
     case MState.Entering:
         currentStateMethod = this.enter;
         break;
     case MState.Exiting:
         currentStateMethod = this.exit;
         break;
     case MState.Updating:
         currentStateMethod = this.update;
         break;
     }
 }
Exemple #39
0
    // A single state may be stored at any given time. If you need to queue more than
    // one state, you could conceivably replace ChangeState() with AddState() and append
    // the three state parameters to a list. As its currently written, changing the state
    // immediatley calls the current 'exit' state, then overwrites the cached enter/run/exit
    // states with these new states.
    public void ChangeState(StateDelegate enter, StateDelegate update, StateDelegate exit)
    {
        bool isStateCurrentlyRunning = currentStateMethod != null;

        // If a state is currently running, it should be allowed to gracefully exit
        // before the next state takes over
        if (isStateCurrentlyRunning) {
            SwitchCurrentState (MState.Exiting);
        }

        // Cache the given state values
        this.enter = enter;
        this.update = update;
        this.exit = exit;

        // If a state isn't currently running, we can immediately switch to our entering
        // state using the state delegates we cached a few lines above
        if (!isStateCurrentlyRunning) {
            SwitchCurrentState (MState.Entering);
        }

        if (immediateMode) {
            Execute();
        }
    }
Exemple #40
0
 /**
 * Check if a state machine is currently in a certain state.
 *
 * @param state The state to check
 * @return True if the state machine is currently in the specified state
 *
 */
 protected Boolean IsInState(StateDelegate state)
 {
     StateDelegate parentState = curState;
     do
     {
         if (state == parentState)
             return true;
         parentState = parentState(new StateEvent(Signal.Null));
     }
     while (parentState != null);
     return false;
 }
Exemple #41
0
    // Call this during
    public void Execute()
    {
        if (currentStateMethod == null)
            return;

        _shouldQuit = false;

        int loops = 0;

        while(!_shouldQuit) {
            // Execute the current state method
            bool finished = currentStateMethod ();

            // If we've reached the end of the current enter/run/exit, advance to the next one
            if (finished && !_shouldQuit) {
                switch (mState) {
                case MState.None:
                    SwitchCurrentState (MState.Entering);
                    break;
                case MState.Entering:
                    SwitchCurrentState (MState.Updating);
                    enter = null;
                    _shouldQuit = true;
                    break;
                case MState.Updating:
                    SwitchCurrentState (MState.Exiting);
                    update = null;
                    break;
                case MState.Exiting:
                    // If an Enter behavior exists, it must have been added by ChangeState. We should
                    // start running again from the top instead of coming to a halt.
                    if (enter != null) {
                        SwitchCurrentState (MState.Entering);
                    } else {
                        SwitchCurrentState (MState.None);
                        exit = null;
                        _shouldQuit = true;
                    }
                    break;
                }
            } else {
                _shouldQuit = true;
            }

            loops++;
            if (loops >= maxLoops) {
                _shouldQuit = true; // This keeps us from freezing due to an infinite exit/enter cycle
                Debug.LogError("A statemachine has reached the maximum loop count!");
            }

            if (!immediateMode) {
                _shouldQuit = true;
            }
        }
    }
Exemple #42
0
 /**
 * Initiate a transition to a new state.
 *
 * @param newState The state to transition to
 *
 */
 protected void TransitionState(StateDelegate newState)
 {
     TransitionState(newState, false);
 }
Exemple #43
0
 /**
 * Record deep history psuedostate.
 *
 * @param historyParent The parent state of the deep history psuedostate
 * @param historyState The state to return to if transitioning to the deep history psuedostate
 *
 */
 void RecordDeephist(StateDelegate historyParent, StateDelegate historyState)
 {
     for (int i = 0; i < deepHistoryTable.Count; i++)
     {
         if (deepHistoryTable[i].Parent == historyParent)
         {
             deepHistoryTable[i] = new DeepHistoryEntry(historyParent, historyState);
             return;
         }
     }
     deepHistoryTable.Add(new DeepHistoryEntry(historyParent, historyState));
 }
Exemple #44
0
 /**
 * Initiate an initial transition to a new state (this function should only be used from a #SimpleHsm::Signal::Init state event).
 *
 * @param newState The state to transition to
 *
 */
 protected void InitTransitionState(StateDelegate newState)
 {
     // set new state
     curState = newState;
     if (curState != null)
     {
         // entry signal to current state
         curState(new StateEvent(Signal.Entry));
         // init signal to current state
         curState(new StateEvent(Signal.Init));
     }
     else
         System.Console.WriteLine("InitTransitionState: ERROR - current state is invalid!\n");
 }
Exemple #45
0
        /**
        * Initiate a transition to a new state.
        *
        * This function will:
        *   - replace the target state with the deep history target if required
        *   - store a deep history target state if exiting a composite state with a deep history child
        *   - perform the exit/entry chain from the current state to the target state
        *
        * @param newState The state to transition to
        * @param toDeepHist Whether to transition to the states internal deep history psuedostate
        *
        */
        protected void TransitionState(StateDelegate newState, bool toDeepHist)
        {
            // retrive historical state if appropriate
            if (toDeepHist)
            {
                newState = RetrieveDeephist(newState);
                if (newState == null)
                {
                    System.Console.WriteLine("TransitionState: ERROR - RetrieveDeephist failed!");
                    return;
                }
            }

            // exit signal to current state
            if (curState != null)
            {
                StateDelegate parentState;
                // record the deep history state if appropriate
                parentState = curState(new StateEvent(Signal.Null));
                while (parentState != null)
                {
                    // the top state cannot have a history sub state and returns stnone to all
                    // unhandled signals anyhow
                    if (parentState == topState)
                        break;
                    // if the parentState has the DeepHist attribute and is not a parent of the new
                    // state then record the deep history
                    else if (HasDeepHistAttrib(parentState) &&
                             !IsParent(parentState, newState))
                    {
                        RecordDeephist(parentState, curState);
                        break;
                    }
                    parentState = parentState(new StateEvent(Signal.Null));
                }
                // state exit chain
                curState(new StateEvent(Signal.Exit));
                parentState = curState(new StateEvent(Signal.Null));
                while (!IsParent(parentState, newState))
                {
                    parentState(new StateEvent(Signal.Exit));
                    parentState = parentState(new StateEvent(Signal.Null));
                }
                // set current state to parent state
                curState = parentState;
            }
            else
                System.Console.WriteLine("TransitionState: ERROR - current state is invalid!");

            // entry signal to new state
            while (curState != newState)
            {
                StateDelegate parentState = newState;
                StateDelegate lastChild = newState;
                while (true)
                {
                    parentState = parentState(new StateEvent(Signal.Null));
                    if (parentState == curState)
                    {
                        lastChild(new StateEvent(Signal.Entry));
                        // set current state to last child state
                        curState = lastChild;
                        break;
                    }
                    lastChild = parentState;
                }
            }

            // init signal to new state
            newState(new StateEvent(Signal.Init));
        }
Exemple #46
0
 /**
 * Retrive deep history psuedostate.
 *
 * @param historyParent The parent state of the deep history psuedostate
 * @return The state to transition to via the deep history psuedostate
 *
 */
 private StateDelegate RetrieveDeephist(StateDelegate historyParent)
 {
     for (int i = 0; i < deepHistoryTable.Count; i++)
     {
         if (deepHistoryTable[i].Parent == historyParent)
         {
             StateDelegate res = deepHistoryTable[i].Child;
             // remove history state from deep history table
             deepHistoryTable.RemoveAt(i);
             // return deep history target
             return res;
         }
     }
     return null;
 }
Exemple #47
0
 public State(string name, StateDelegate enterMethod)
 {
     _name = name;
     _enter = enterMethod;
 }
Exemple #48
0
 /**
 * Check is one state is the parent of another.
 *
 * @param parentState The parent state to check
 * @param childState The child state to check
 * @return True if the parentState parameter is a parent to the childState parameter
 *
 */
 protected Boolean IsParent(StateDelegate parentState, StateDelegate childState)
 {
     do
     {
         childState = childState(new StateEvent(Signal.Null));
         if (childState == parentState)
             return true;
     }
     while (childState != null);
     return false;
 }