Skip to content

Commit b1e40bd

Browse files
committed
Added handlers and utils
1 parent a93438b commit b1e40bd

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
-- Search tree class handler implementation
2+
3+
local PATH = (...):gsub('handlers.tree_handler$','')
4+
local class = require (PATH .. '.utils.class')
5+
6+
7+
local tree = class ()
8+
9+
-- Tree initialization
10+
function tree:initialize()
11+
self.nodes = {}
12+
end
13+
14+
-- Adds a node in the tree
15+
function tree:addNode(name, parent, value)
16+
assert(not self.nodes[name], 'node already exist')
17+
local node = {
18+
name = name, value = value,
19+
parent = parent, children = {}
20+
}
21+
if parent then
22+
parent = self:getNode(parent)
23+
assert(parent, 'parent not found')
24+
table.insert(parent.children, node)
25+
end
26+
if not self.head then self.head = node end
27+
table.insert(self.nodes, node)
28+
end
29+
30+
-- Get the node by its name
31+
function tree:getNode(name)
32+
for i, node in ipairs(self.nodes) do
33+
if node.name == name then return node end
34+
end
35+
end
36+
37+
-- Checks if a given node is terminal (leaf) in the search tree
38+
function tree:isLeaf(node)
39+
return #node.children == 0
40+
end
41+
42+
-- Returns the node value
43+
function tree:heuristic(node)
44+
return node.value
45+
end
46+
47+
-- Returns the node's children
48+
function tree:children(node)
49+
return node.children
50+
end
51+
52+
return tree

Minimax/Lua/Yonaba/utils/class.lua

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
-- Minimalistic class implementation
2+
3+
local class = function(attr)
4+
local klass = attr or {}
5+
klass.__index = klass
6+
klass.__call = function(_,...) return klass:new(...) end
7+
function klass:new(...)
8+
local instance = setmetatable({}, klass)
9+
if klass.initialize then klass.initialize(instance, ...) end
10+
return instance
11+
end
12+
return setmetatable(klass,{__call = klass.__call})
13+
end
14+
15+
return class

0 commit comments

Comments
 (0)