-
Notifications
You must be signed in to change notification settings - Fork 3
/
SimpleStateMachine.cs
86 lines (69 loc) · 2.73 KB
/
SimpleStateMachine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Linq;
namespace SimpleStateMachine {
public class State {
public State(string Key, string Description, string[] transitions) {
this.Key = Key;
this.Description = Description;
this.Transitions = transitions;
}
public string Key { get; private set; }
public string Description { get; private set; }
public string[] Transitions { get; private set; }
public delegate void EventHandler(string State);
public EventHandler OnEnter; //Pass previous state
public EventHandler OnExit; //Pass new state
}
[Serializable]
public abstract class StateMachine {
[NonSerialized]
private Dictionary<string, State> _states = new Dictionary<string, State>();
//This should allow serialization of the state
protected string currentState;
private State getState(string Key) {
if (_states.Count == 0 || string.IsNullOrEmpty(Key))
return null;
return _states[Key];
}
public string State {
get {
return currentState;
}
set {
if (currentState == value)
return;
if (!string.IsNullOrEmpty(currentState) && !Transitions.Contains(value))
throw new ArgumentException("Invalid Transition!");
State tmpState = getState(currentState);
if (null != tmpState && null != tmpState.OnExit) {
foreach (State.EventHandler handler in getState(currentState).OnExit.GetInvocationList()) {
handler(value);
}
}
string prev_state = currentState;
currentState = value;
tmpState = getState(currentState);
if (null != tmpState && null != tmpState.OnEnter) {
foreach (State.EventHandler handler in tmpState.OnEnter.GetInvocationList()) {
handler(prev_state);
}
}
}
}
public string[] Transitions { get { return getState(currentState).Transitions; } }
//Setup functions
protected State[] States {
set {
foreach(State s in value) {
_states.Add(s.Key, s);
}
}
}
protected string InitialState {
set {
State = value; //This makes sure onEnter gets called for the InitialState
}
}
}
}