-
Notifications
You must be signed in to change notification settings - Fork 0
/
state_machine.js
93 lines (80 loc) · 2.05 KB
/
state_machine.js
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
89
90
91
92
93
'use strict';
// TODO: Rename StateMachine into BehavioralTree
/**
* State definition (all optionals):
* {
* priority: [int],
* canTrigger: [function],
* start: [function],
* update: [function],
* end: [function],
* next: [state]
* }
*/
let newMachine = function() {
let machine = {};
let currentState = null;
let states = [];
let assertState = function(state) {
state.priority = state.priority || 0;
state.next = state.next || null;
state.canTrigger = state.canTrigger || function() {return true;};
state.start = state.start || function() {};
state.update = state.update || function() {return true;};
state.end = state.end || function() {};
};
machine.update = function() {
let replacingState, state, i;
if (currentState) {
if (currentState.update.apply(currentState, arguments) === false) {
currentState.end();
if (currentState.next) {
assertState(currentState.next);
currentState = currentState.next;
currentState.start();
return true;
} else if (states.length == 0) {
return false;
}
currentState = null;
}
}
replacingState = currentState;
for (i = 0; i < states.length; ++i) {
state = states[i];
if (state == currentState)
continue;
if (state.canTrigger() && (!currentState || state.priority >= replacingState.priority)) {
replacingState = state;
}
}
if (replacingState !== currentState) {
if (currentState)
currentState.end();
currentState = replacingState;
currentState.start();
}
return currentState;
};
machine.addState = function(state) {
assertState(state);
states.push(state);
};
machine.end = function() {
if (!currentState) {
return;
}
currentState.end();
}
machine.setState = function(state) {
if (currentState) {
currentState.end();
}
currentState = state;
currentState.start();
}
return machine;
}
module.exports = {
newMachine: newMachine,
}