/
wait.go
94 lines (81 loc) · 2.28 KB
/
wait.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
89
90
91
92
93
94
package task
import (
"time"
"github.com/alkaid/behavior/util"
"github.com/alkaid/behavior/bcore"
)
type IWaitProperties interface {
GetWaitTime() time.Duration
GetRandomDeviation() time.Duration
GetForever() bool
GetResultOnAbort() bool
}
// WaitProperties 等待属性
type WaitProperties struct {
WaitTime util.Duration `json:"waitTime"` // 等待时间
RandomDeviation util.Duration `json:"randomDeviation"` // 随机偏差:允许向 等待时间 WaitTime 属性添加随机时间。 WaitTime = WaitTime + RandomDeviation * [-0.5,0.5)
Forever bool `json:"forever"` // 永久等待直到被外界打断
ResultOnAbort bool `json:"resultOnAbort"` // 中断时返回成功还是失败,默认false
}
func (w *WaitProperties) GetWaitTime() time.Duration {
return w.WaitTime.Duration
}
func (w *WaitProperties) GetRandomDeviation() time.Duration {
return w.RandomDeviation.Duration
}
func (w *WaitProperties) GetForever() bool {
return w.Forever
}
func (w *WaitProperties) GetResultOnAbort() bool {
return w.ResultOnAbort
}
// Wait 等待
//
// 任务节点可以在行为树中使用,使树在此节点上等待,直至指定的 等待时间(Wait Time) 结束。
type Wait struct {
bcore.Task
}
// PropertiesClassProvider
//
// @implement INodeWorker.PropertiesClassProvider
// @receiver n
// @return any
func (w *Wait) PropertiesClassProvider() any {
return &WaitProperties{}
}
func (w *Wait) WaitProperties() IWaitProperties {
return w.Properties().(IWaitProperties)
}
// OnStart
//
// @override Node.OnStart
// @receiver n
// @param brain
func (w *Wait) OnStart(brain bcore.IBrain) {
w.Task.OnStart(brain)
w.Memory(brain).Elapsed = 0
if w.WaitProperties().GetForever() {
return
}
w.Memory(brain).CronTask = brain.After(w.WaitProperties().GetWaitTime(), w.WaitProperties().GetRandomDeviation(), func() {
if w.IsActive(brain) {
w.Finish(brain, true)
}
})
}
// OnAbort
//
// @override Node.OnAbort
// @receiver n
// @param brain
func (w *Wait) OnAbort(brain bcore.IBrain) {
w.Task.OnAbort(brain)
w.stopTimer(brain)
w.Finish(brain, w.WaitProperties().GetResultOnAbort())
}
func (w *Wait) stopTimer(brain bcore.IBrain) {
if w.Memory(brain).CronTask != nil {
w.Memory(brain).CronTask.Stop()
w.Memory(brain).CronTask = nil
}
}