Last active
July 19, 2016 01:37
-
-
Save mattvr/11148511c8ef9d1eca7ec994d7447c9b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| public class StateMachine<S> where S : struct | |
| { | |
| private Dictionary<S, Action> beginCallbacks; | |
| private Dictionary<S, Action> continueCallbacks; | |
| private Dictionary<S, Action> endCallbacks; | |
| private bool started = false; | |
| private S? previousState = null; | |
| public S CurrentState { get; private set; } | |
| public StateMachine( | |
| Dictionary<S, Action> beginCallbacks, | |
| Dictionary<S, Action> continueCallbacks, | |
| Dictionary<S, Action> endCallbacks) | |
| { | |
| CurrentState = default(S); | |
| this.beginCallbacks = beginCallbacks; | |
| this.continueCallbacks = continueCallbacks; | |
| this.endCallbacks = endCallbacks; | |
| Step(); | |
| } | |
| public void Step() | |
| { | |
| if (!started) | |
| { | |
| started = true; | |
| ChangeState(); | |
| } | |
| else | |
| { | |
| ContinueState(); | |
| } | |
| } | |
| public void TransitionTo(S state) | |
| { | |
| CurrentState = state; | |
| ChangeState(); | |
| } | |
| private void ChangeState() | |
| { | |
| if (previousState.HasValue) | |
| { | |
| TryEndCallback(previousState.Value); | |
| } | |
| TryBeginCallback(CurrentState); | |
| previousState = CurrentState; | |
| } | |
| private void ContinueState() | |
| { | |
| TryContinueCallback(CurrentState); | |
| } | |
| private void TryBeginCallback(S state) | |
| { | |
| if (beginCallbacks != null && beginCallbacks.ContainsKey(state)) | |
| { | |
| beginCallbacks[state](); | |
| } | |
| } | |
| private void TryContinueCallback(S state) | |
| { | |
| if (continueCallbacks != null && continueCallbacks.ContainsKey(state)) | |
| { | |
| continueCallbacks[state](); | |
| } | |
| } | |
| private void TryEndCallback(S state) | |
| { | |
| if (endCallbacks != null && endCallbacks.ContainsKey(state)) | |
| { | |
| endCallbacks[state](); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment