1local AH = wesnoth.require "ai/lua/ai_helper.lua"
2local M = wesnoth.map
3
4local function get_tusklets(cfg)
5    local tusklets = AH.get_units_with_moves {
6        side = wesnoth.current.side,
7        type = cfg.tusklet_type
8    }
9    return tusklets
10end
11
12local function get_tuskers(cfg)
13    local tuskers = wesnoth.get_units {
14        side = wesnoth.current.side,
15        type = cfg.tusker_type
16    }
17    return tuskers
18end
19
20local ca_forest_animals_tusklet_move = {}
21
22function ca_forest_animals_tusklet_move:evaluation(cfg)
23    -- Tusklets will simply move toward the closest tusker, without regard for anything else
24    -- Except if no tuskers are left, in which case ca_forest_animals_move takes over and does a random move
25
26    if (not cfg.tusker_type) or (not cfg.tusklet_type) then return 0 end
27    if (not get_tusklets(cfg)[1]) then return 0 end
28    if (not get_tuskers(cfg)[1]) then return 0 end
29    return cfg.ca_score
30end
31
32function ca_forest_animals_tusklet_move:execution(cfg)
33    local tusklet = get_tusklets(cfg)[1]
34    local tuskers = get_tuskers(cfg)
35
36    local goto_tusker, min_dist = {}, 9e99
37    for _,tusker in ipairs(tuskers) do
38        local dist = M.distance_between(tusker.x, tusker.y, tusklet.x, tusklet.y)
39        if (dist < min_dist) then
40            min_dist, goto_tusker = dist, tusker
41        end
42    end
43
44    local best_hex = AH.find_best_move(tusklet, function(x, y)
45        return - M.distance_between(x, y, goto_tusker.x, goto_tusker.y)
46    end)
47
48    AH.movefull_stopunit(ai, tusklet, best_hex)
49
50    -- Also make sure tusklets never attack
51    if tusklet and tusklet.valid then AH.checked_stopunit_all(ai, tusklet) end
52end
53
54return ca_forest_animals_tusklet_move
55