forked from wudeng/lbt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
weight_priority.lua
64 lines (58 loc) · 1.63 KB
/
weight_priority.lua
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
local Const = require "const"
local BTCommon = require "bt_common"
local mt = {}
mt.__index = mt
function mt:open(_, node_data)
node_data.runningChild = 1
if not node_data.indexes then
local indexes = {}
for i = 1, #self.children do
table.insert(indexes, i)
end
node_data.indexes = indexes
end
BTCommon.reorder(node_data.indexes, self.weight, self.total_weight)
end
function mt:run(tick, node_data)
local child = node_data.runningChild
for i = child, #node_data.indexes do
local index = node_data.indexes[i]
local status = BTCommon.execute(self.children[index], tick, node_data.__level + 1)
if status == Const.SUCCESS then
return status
end
if status == Const.RUNNING then
node_data.runningChild = i
return status
end
end
return Const.FAIL
end
function mt:close(tick, node_data)
node_data.runningChild = 1
for _, node in ipairs(self.children) do
local child_data = tick[node]
if child_data and child_data.is_open then
child_data.is_open = false
if node.close then
node:close(tick, child_data)
end
end
end
end
local function new(weight, ...)
assert(type(weight) == "table" and #weight == select("#", ...))
local total_weight = 0
for i = 1, #weight do
total_weight = total_weight + weight[i]
end
local obj = {
name = "weight_priority",
weight = weight,
children = {...},
total_weight = total_weight,
}
setmetatable(obj, mt)
return obj
end
return new