forked from 0xABAD/behavior_tree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbehaviorTreeFunctionality.js
More file actions
80 lines (74 loc) · 2.22 KB
/
behaviorTreeFunctionality.js
File metadata and controls
80 lines (74 loc) · 2.22 KB
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
class BehaviorTree {
constructor(root) {
/** @property {Node} root node. */
this.root = root;
/** @property {Map<string, Action[]>} actions list of actions grouped by name */
this.actions = new Map();
/** @property {Map<string, Condition[]>} conditions list of conditions grouped by name */
this.conditions = new Map();
/** @property {Set<String>, Node[]} nodes list of unique nodes */
this.nodes = new Map();
if (this.root) {
this.extractActionsAndConditions(this.root);
}
}
/**
*
* @param {Map<string, Node[]>} map map to insert to
* @param {string} key map key
* @param {Node} value value to insert for the given _key_
*/
addToArrayMap(map, key, value) {
if (map.has(key)) {
map.get(key).push(value);
} else {
map.set(key, [value]);
}
}
/**
* Recursively extracts action and condition nodes from the sub-tree.
* @param {Node} node tree node
* @returns {void}
*/
extractActionsAndConditions(node) {
if (node instanceof Action) {
this.addToArrayMap(this.actions, node.name, node);
} else if (node instanceof Condition) {
this.addToArrayMap(this.conditions, node.name, node);
} else if (node instanceof Sequence) {
this.addToArrayMap(this.nodes, "Sequence", node);
} else if (node instanceof Parallel) {
this.addToArrayMap(this.nodes, "Parallel", node);
} else if (node instanceof Fallback) {
this.addToArrayMap(this.nodes, "Fallback", node);
}
if (node.children) {
node.children.forEach(c => this.extractActionsAndConditions(c));
}
}
/**
* Updates tree with new condition value.
* @param {string} name condition name
* @param {number} status new status
*/
setConditionStatus(name, status) {
if (this.conditions.has(name)) {
this.conditions.get(name).forEach((/** @type {Condition} */ c) => c.setStatus(status));
}
}
/**
* Updates tree with new action status.
* @param {string} name action name
* @param {number} status new status
*/
setActionStatus(name, status) {
if (this.actions.has(name)) {
this.actions.get(name).forEach((/** @type {Action} */ a) => a.setStatus(status));
}
}
tick() {
if (this.root) {
this.root.tick();
}
}
}