adaptive-ai/helper.lua
2018-06-26 19:20:49 +02:00

135 lines
2.5 KiB
Lua

--adaptive_ai.chat_log = function() end
-- Localize math functions
local floor = math.floor
local ceil = math.ceil
local sqrt = math.sqrt
local random = math.random
-- Helper calculation functions
local calc = {}
calc.sum = function(vector)
local total = 0
for i = 1, #vector do
total = total + vector[i]
end
return total
end
calc.round = function(x)
if x>=0 then
if (x - floor(x)) >= 0.5 then
return ceil(x)
else
return floor(x)
end
else
if (ceil(x) - x) >= 0.5 then
return floor(x)
else
return ceil(x)
end
end
end
calc.normalize = function(vector)
local total = calc.sum(vector)
for i = 1, #vector do
vector[i] = vector[i]/total
end
end
calc.dist_manhattan = function(pos1, pos2)
local dist = abs(pos1.x - pos2.x) + abs(pos1.y - pos2.y) + abs(pos1.z - pos2.z)
return dist
end
calc.dist_euclidean = function(a, b)
local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
return sqrt(x * x + y * y + z * z)
end
calc.average = function(t, to_num)
local avg, cnt = 0, 0
for _,v in ipairs(t) do
if to_num then
avg = avg + to_num(v)
else
avg = avg + v
end
cnt = cnt + 1
end
avg = avg/cnt
return avg
end
calc.truncate = function(n)
return floor(n*100 + 0.5)/100
end
adaptive_ai.calc = calc
-- Helper generic functions
local helper = {}
helper.adjacent = {
{x=-1, z=-1},
{x=-1, z= 0},
{x=-1, z= 1},
{x= 0, z=-1},
--{x= 0, z= 0}, -- Center
{x= 0, z= 1},
{x= 1, z=-1},
{x= 1, z= 0},
{x= 1, z= 1},
}
helper.sort_nils_out = function(a, b)
if not a then return false end
return true
end
helper.compare_pos = function(p1, p2)
return p1.x == p2.x and p1.y == p2.y and p1.z == p2.z
end
helper.pop = function(t, i)
if #t <= 0 then return nil end
local i = i or 1
local res = t[i]
for i=i,#t do
t[i] = t[i+1]
end
return res
end
helper.shuffle = function(t, n)
n = n or #t
for i = 1, n+1 do
local j = random(n)
local k = random(n)
t[j], t[k] = t[k], t[j]
end
end
helper.load_file = function(filename, decompressing)
local file = io.open(filename, "r")
if file then
local t = file:read("*all")
file:close()
if decompressing then
t = minetest.decompress(t)
end
t = minetest.deserialize(t)
return t
elseif not filename:find("tribe") then
error(filename)
end
end
--helper.dist_euclidean = get_distance
adaptive_ai.helper = helper