/
Fsm.go
88 lines (74 loc) · 1.3 KB
/
Fsm.go
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
87
88
package base
// 状态机
type (
FsmHandle func()
State struct {
OnEnter FsmHandle
OnExec FsmHandle
OnExit FsmHandle
}
Fsm struct {
preState int
curState int
maxState int
states []State
}
IFsm interface {
Init(int)
SetStateHandle(state int, st *State)
SetState(int)
GetState() int
GetPreState() int
Update()
}
)
func (f *Fsm) Init(_maxState int) {
f.curState = 0
f.maxState = _maxState
f.states = make([]State, _maxState)
}
func (f *Fsm) SetStateHandle(state int, st *State) {
if st == nil {
return
}
if st.OnEnter != nil {
f.states[state].OnEnter = st.OnEnter
}
if st.OnExec != nil {
f.states[state].OnExec = st.OnExec
}
if st.OnExit != nil {
f.states[state].OnExit = st.OnExit
}
}
func (f *Fsm) GetState() int {
return f.curState
}
func (f *Fsm) SetState(state int) {
Assert(state >= 0 && state < f.maxState, "invalid state")
if state >= f.maxState {
return
}
if f.curState != state {
s := f.states[f.curState]
if s.OnExit != nil {
s.OnExit()
}
}
f.preState = f.curState
f.curState = state
s := f.states[state]
if s.OnEnter != nil {
s.OnEnter()
}
}
// 获取前面的一个状态
func (f *Fsm) GetPreState() int {
return f.preState
}
func (f *Fsm) Update() {
s := f.states[f.curState]
if nil != s.OnExec {
s.OnExec()
}
}