-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
126 lines (104 loc) · 2.39 KB
/
node.go
File metadata and controls
126 lines (104 loc) · 2.39 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package behavior
import (
"fmt"
"github.com/billyplus/behavior/config"
)
// Node 用来表示树的一个节点
type Node interface {
CreateMemo() Memory
Initialize(cfg *config.BH3Node) error
Enter(bb *Blackboard, memo Memory)
Tick(bb *Blackboard, memo Memory) BehaviorStatus
// Exit 每次完成节点时触发
Exit(bb *Blackboard, memo Memory)
AddChild(n *Wrapper)
String() string
}
// type NodeWrapper interface {
// Execute(bb *Blackboard) BehaviorStatus
// }
// func wrapNode(node Node) *Wrapper {
// n := &Wrapper{
// Node: node,
// }
// return n
// }
var (
_ Node = &BaseNode{}
)
type BaseNode struct {
}
func (node *BaseNode) CreateMemo() Memory {
return &BaseMemo{}
}
func (node *BaseNode) Initialize(cfg *config.BH3Node) error {
return nil
}
func (node *BaseNode) Enter(bb *Blackboard, memo Memory) {
}
func (node *BaseNode) Tick(bb *Blackboard, memo Memory) BehaviorStatus {
return StatusFailed
}
func (node *BaseNode) Exit(bb *Blackboard, memo Memory) {
}
func (node *BaseNode) AddChild(n *Wrapper) {
}
func (node *BaseNode) String() string {
return "BaseNode"
}
type Wrapper struct {
Node
name string
index int
}
func (w *Wrapper) String() string {
return fmt.Sprintf(`%s: %s`, w.name, w.Node.String())
}
// Execute execute node
func (wrapper *Wrapper) Execute(bb *Blackboard) BehaviorStatus {
if wrapper.Node == nil {
return StatusFailed
}
memo := bb.GetNodeMemo(wrapper.index)
// get running state
st := memo.GetStatus()
if st != IsRunning {
wrapper.Node.Enter(bb, memo)
if logger != nil {
logger.Println("Enter " + wrapper.String())
}
st = IsRunning
memo.SaveStatus(st)
}
if st == IsRunning {
status := wrapper.Node.Tick(bb, memo)
if logger != nil {
logger.Println("Tick " + wrapper.String() + " status=" + status.String())
}
if status != StatusRunning {
wrapper.Node.Exit(bb, memo)
// save running state
if logger != nil {
logger.Println("Exit " + wrapper.String())
}
memo.SaveStatus(IsReady)
}
return status
}
return StatusFailed
}
// Stop stop node if it is running
func (wrapper *Wrapper) Stop(bb *Blackboard) {
memo := bb.GetNodeMemo(wrapper.index)
// get running state
st := memo.GetStatus()
if st == IsRunning {
memo := bb.GetNodeMemo(wrapper.index)
wrapper.Node.Exit(bb, memo)
if logger != nil {
logger.Println("Exit " + wrapper.String())
}
// save running state
memo.SaveStatus(IsReady)
}
}