Skip to content

Full example: Auto Deer Push

This page holds the full source of the built-in Auto Deer Push feature, exactly as it ships. It is a larger script than the short examples: it reads the world, keeps state across updates, sends orders and checks them, declares options, and draws clickable buttons in the world.

What it does

The feature uses your scout to push deer to your town center. The scout moves to the far side of a deer, then follows it so the deer keeps running ahead of it. The deer is steered along a route around trees, walls, gates, buildings and impassable terrain.

  • A deer is yours when the town center nearest to it, out of every player's, is yours.
  • Hares, chickens, monkeys and prey that hold no food are skipped.
  • With Lock on in its options, each deer shows a Push button. Only the deer you click is pushed, by the scout nearest to it, until it arrives or you click Cancel.

Files

File Role
main.lua The script: Init, Update, Shutdown and Render.
options.lua Its options. The host runs this file at start-up, before the script loads, so the options exist before the feature is first switched on.
route.lua A helper shared with Auto Lamer. It builds a grid of blocked tiles and finds a path from the animal to the town center.
manifest.json Its name, description and main-menu heading.

Run your own copy

Copy the files into a module and rename the entry to match its folder:

%APPDATA%\WololoLabs\modules\my-deer-push\my-deer-push.main.lua   (main.lua)
%APPDATA%\WololoLabs\modules\my-deer-push\options.lua
%APPDATA%\WololoLabs\modules\my-deer-push\route.lua
%APPDATA%\WololoLabs\modules\my-deer-push\manifest.json           (optional)

Then:

  1. In options.lua, change Settings.Module("auto-deer-push") to Settings.Module("my-deer-push") so that your copy keeps its own options.
  2. If you copy the manifest, delete its id, entry, files, order, feature, options and shared keys, and give it your own name. See Manifest.
  3. Switch the built-in Auto Deer Push off. Two copies would both order the same scout.

How it works

Read the source below with these points in mind. Each one is a pattern from Write reliable scripts applied in a real feature.

State is reset in Init. Every table the script keeps (the current push, deer that could not be reached, the locked deer) is cleared in Init, so a new match never starts with stale IDs. The script keeps object IDs between updates, not objects, and fetches each object again with GetObjectById.

Unavailable data stops the update. Update returns early when the game time, the assigned player or the prey list is nil, and when GetPlayerCount is unavailable. isDeer rejects a deer whose held food cannot be read and logs that once.

Orders use tracked commands. issue sends each order with its tracked form (UnitsMoveTracked, SetUnitStanceFollowTracked, UnitsStopTracked) and keeps the receipt. settleReceipts runs at the start of every update. It logs failed receipts, then releases them once they are final. A refused order is logged once per reason and is not retried at once. See Command receipts.

Timing uses game time. Orders are spaced by commandSpacingMs, and a new follow gets followGraceMs before it is judged. Both are compared with GetGameTimeMs, so they hold at any frame rate and game speed.

One small state machine. A push is either positioning (the scout moves to a free spot behind the deer) or following (the scout follows the deer). advance picks the step for the current state. A follow that ended or drifted out of line goes back to positioning.

A target is kept until it is done. chooseDeer keeps the deer being pushed while it still qualifies. Without that, the nearest deer changed as the herd moved, and the push restarted every few seconds.

Logs say why nothing happens. noteIdle logs the idle reason only when it changes, with counts that show why no deer qualified. Progress is logged every 10 seconds. Every line starts with [AutoDeerPush], so it is easy to filter.

Drawing happens only in Render. Render reads the prey list and draws one Push button per deer with RenderWorldButton. Button IDs start with auto-deer-push:. Update collects the clicks with TakeButtonClicks(buttonPrefix) and acts on them, so Render never changes state.

Shutdown releases the scout. When the feature is switched off, the scout is stopped if this script left it following a deer.

main.lua

-- Pushes your own deer to your town centre with your scout: the scout moves to the far
-- side of the deer, then follows it, so the deer keeps fleeing ahead of it. The deer is
-- steered along a route round trees, walls, gates, buildings and impassable terrain.
-- A deer is yours when its nearest town centre, among every player's, is yours.
-- With the Lock on option, only the deer whose Push button is clicked is pushed instead.

local Route = require("route")

local options = require("options")

-- How far the scout may sit off the town-centre line and still count as behind the deer.
local alignmentTolerance = 0.55
local minimumRearDistance = 0.15
-- Timings are match milliseconds so they hold at any frame rate and game speed.
local commandSpacingMs = 400
-- A new follow gets this long to close in before its line is judged.
local followGraceMs = 1700

-- How far ahead along the route the deer is steered, at most.
local steeringLookaheadTiles = 6
-- A deer with no route, or no free spot behind it for the scout, waits this long.
local unreachableRetryMs = 30000
-- Stand-off angles tried, in degrees either side, when the spot straight behind is blocked.
local standOffAngles = { 0, 20, -20, 40, -40, 60, -60 }

-- Every Gaia prey animal is a deer to push except these, by master name. Maps bring their
-- own deer-like huntables (live: mouflon and wild horses), so a type list misses some.
local excludedPreyNames = { "HARE", "CHICKEN", "MONKEY" }
-- Units that can push deer besides the scout class: by master name, within a class.
local pusherNamesByClass = {
    [UnitClass.INFANTRY] = { "EAGLE", "CHAMPIR" },
    [UnitClass.CAVALRY] = { "CAMELSC" },
}

local pusherClasses = { UnitClass.SCOUT, UnitClass.INFANTRY, UnitClass.CAVALRY }

-- Lock on's world buttons: ids carry this prefix so TakeButtonClicks returns only ours.
-- Placed as Auto Lamer's are, clear of the unit so the unit stays clickable.
local buttonPrefix = "auto-deer-push:"
local pushButtonStyle = { offsetX = 26, offsetY = -26 }
local cancelButtonStyle = { offsetX = 38, offsetY = 0 }
local noticeDurationMs = 3000
local labelOffsetPixels = -42
local labelSize = 14
local targetMarkerRadius = 0.9
local colors = {
    text = Color("#FFFFFF"),
    background = Color("#000000B4"),
    target = Color("#FF8C1A"),
}

local State = {
    Positioning = "positioning",
    Following = "following",
}

local push = nil
local unreachableUntil = {}
-- Once per match, how many town centres ownership is judged against.
local townCentresLogged = false
-- Once per match, that the held-food query was unavailable.
local heldFoodUnavailableLogged = false

-- Every order goes through its tracked form so a refused or failed order is logged, not
-- silently retried. Receipts are watched until terminal, then released.
local pendingReceipts = {}
local lastRefusal = nil
local failedStates = { rejected = true, cancelled = true, indeterminate = true }
local terminalStates = { submitted = true, rejected = true, cancelled = true, indeterminate = true }

local function issue(label, trackedCommand, ...)
    local accepted, receipt = trackedCommand(...)
    if not accepted then
        local reason = receipt and receipt.reason or "unknown"
        if lastRefusal ~= label .. reason then
            LogWarn(string.format("[AutoDeerPush] %s refused: %s", label, reason))
            lastRefusal = label .. reason
        end
        return false
    end
    lastRefusal = nil
    pendingReceipts[#pendingReceipts + 1] = { id = receipt.id, label = label }
    return true
end

local function settleReceipts()
    local stillPending = {}
    for _, pending in ipairs(pendingReceipts) do
        local receipt = CommandReceipt(pending.id)
        if receipt == nil or not terminalStates[receipt.state] then
            stillPending[#stillPending + 1] = pending
        else
            if failedStates[receipt.state] then
                LogWarn(string.format("[AutoDeerPush] %s %s: %s", pending.label, receipt.state, tostring(receipt.reason)))
            else
                LogDebug(string.format("[AutoDeerPush] %s submitted", pending.label))
            end
            if not ReleaseCommandReceipt(pending.id) then
                stillPending[#stillPending + 1] = pending
            end
        end
    end
    pendingReceipts = stillPending
end

local function positionOf(object)
    local position = object:GetPosition()
    if position == nil then
        return nil
    end
    return { x = position.x, y = position.y }
end

local function distance(left, right)
    local dx, dy = left.x - right.x, left.y - right.y
    return math.sqrt(dx * dx + dy * dy)
end

local function nameContainsAny(name, needles)
    for _, needle in ipairs(needles) do
        if string.find(name, needle, 1, true) then
            return true
        end
    end
    return false
end

-- Food the animal holds, or nil when the native query is unavailable.
local function heldFood(object)
    local amount, available = XsGetUnitAttributeHeld(object:GetId(), ResourceType.FOOD)
    if not available then
        return nil
    end
    return amount
end

-- Some prey carry no food (live: wild camels), so pushing them home gains nothing.
local function isDeer(object)
    if not object:IsAlive() or nameContainsAny(object:GetMasterName(), excludedPreyNames) then
        return false
    end
    local food = heldFood(object)
    if food == nil then
        if not heldFoodUnavailableLogged then
            LogWarn("[AutoDeerPush] held food unreadable; no deer qualifies until it reads")
            heldFoodUnavailableLogged = true
        end
        return false
    end
    return food > 0
end

local function isLiveTownCentre(object)
    return object:IsAlive() and object:GetUnitObjectType() == UnitObjectType.TOWN_CENTER
end

local function isPusher(object)
    if not object:IsAlive() then
        return false
    end
    local unitClass = object:GetClass()
    if unitClass == UnitClass.SCOUT then
        return true
    end
    local names = pusherNamesByClass[unitClass]
    return names ~= nil and nameContainsAny(object:GetMasterName(), names)
end

local function livePositions(objects, keep)
    local result = {}
    for _, object in ipairs(objects) do
        if keep(object) then
            local position = positionOf(object)
            if position then
                result[#result + 1] = { object = object, position = position }
            end
        end
    end
    return result
end

local function nearestTo(point, candidates)
    local best, bestDistance = nil, math.huge
    for _, candidate in ipairs(candidates) do
        local candidateDistance = distance(point, candidate.position)
        if candidateDistance < bestDistance then
            best, bestDistance = candidate, candidateDistance
        end
    end
    return best, bestDistance
end

-- Every player's live town centres, each tagged with whether it is ours; nil when the
-- player count is unreadable, since ownership can't be judged without it.
local function allTownCentres(ownPlayerId)
    local count, available = GetPlayerCount()
    if not available then
        return nil
    end
    local centres = {}
    -- The count leaves Gaia (player 0) out: a 1v1 reads 2, live.
    for playerId = 1, count do
        local buildings = GetIndexedObjects(playerId, UnitClass.BUILDING)
        if buildings ~= nil then
            for _, centre in ipairs(livePositions(buildings, isLiveTownCentre)) do
                centre.own = playerId == ownPlayerId
                centres[#centres + 1] = centre
            end
        end
    end
    if not townCentresLogged then
        local described = {}
        for _, centre in ipairs(centres) do
            described[#described + 1] = string.format("%s(%.1f,%.1f)", centre.own and "ours" or "other",
                centre.position.x, centre.position.y)
        end
        LogInfo(string.format("[AutoDeerPush] players=%d town centres: %s", count, table.concat(described, " ")))
        townCentresLogged = true
    end
    return centres
end

-- Why no deer qualifies, as counts, for the idle log.
local function describeDeer(now, deer, townCentres, arrivalRadius)
    local ours, waiting, arrived = 0, 0, 0
    for _, candidate in ipairs(deer) do
        local centre, centreDistance = nearestTo(candidate.position, townCentres)
        if centre and centre.own then
            ours = ours + 1
            if (unreachableUntil[candidate.object:GetId()] or 0) > now then
                waiting = waiting + 1
            elseif centreDistance <= arrivalRadius then
                arrived = arrived + 1
            end
        end
    end
    local positions = {}
    for index, candidate in ipairs(deer) do
        if index > 8 then
            break
        end
        local nearestOwn, nearestOther = math.huge, math.huge
        for _, centre in ipairs(townCentres) do
            local centreDistance = distance(candidate.position, centre.position)
            if centre.own then
                nearestOwn = math.min(nearestOwn, centreDistance)
            else
                nearestOther = math.min(nearestOther, centreDistance)
            end
        end
        positions[#positions + 1] = string.format("%s(%.0f,%.0f) ours %.0f other %.0f",
            candidate.object:GetMasterName(), candidate.position.x, candidate.position.y, nearestOwn, nearestOther)
    end
    return string.format("%d deer, %d ours, %d waiting, %d arrived [%s]", #deer, ours, waiting, arrived,
        table.concat(positions, "; "))
end

-- Gaia's prey animals by master name and type, to show a deer type the list misses.
local function describePrey(prey)
    local counts = {}
    for _, animal in ipairs(prey) do
        local key = string.format("%s/%d", animal:GetMasterName(), animal:GetUnitObjectType())
        counts[key] = (counts[key] or 0) + 1
    end
    local described = {}
    for key, count in pairs(counts) do
        described[#described + 1] = key .. ":" .. count
    end
    table.sort(described)
    return "{" .. table.concat(described, " ") .. "}"
end

-- Our deer nearest our town centres that has not arrived yet and is not waiting out an
-- unreachable spell, and its town centre. The deer being pushed keeps the push while it
-- still qualifies: deer graze in a group, so the nearest one changes as they move, and
-- switching restarted the push every few seconds live.
local function chooseDeer(now, deer, townCentres, arrivalRadius, currentDeerId)
    local bestDeer, bestCentre, bestDistance = nil, nil, math.huge
    for _, candidate in ipairs(deer) do
        local centre, centreDistance = nearestTo(candidate.position, townCentres)
        local waiting = (unreachableUntil[candidate.object:GetId()] or 0) > now
        if centre and centre.own and not waiting and centreDistance > arrivalRadius then
            if candidate.object:GetId() == currentDeerId then
                return candidate, centre
            end
            if centreDistance < bestDistance then
                bestDeer, bestCentre, bestDistance = candidate, centre, centreDistance
            end
        end
    end
    return bestDeer, bestCentre
end

-- Unit vector from the goal through the deer, or nil when they overlap.
local function awayFromGoal(deerPosition, goal)
    local dx, dy = deerPosition.x - goal.x, deerPosition.y - goal.y
    local length = math.sqrt(dx * dx + dy * dy)
    if length < 0.001 then
        return nil
    end
    return { x = dx / length, y = dy / length }
end

local function rotate(vector, degrees)
    local radians = math.rad(degrees)
    local cosine, sine = math.cos(radians), math.sin(radians)
    return { x = vector.x * cosine - vector.y * sine, y = vector.x * sine + vector.y * cosine }
end

-- A free spot for the scout on the far side of the deer from the goal: straight behind
-- when open, else the nearest open angle either side; nil when every angle is blocked.
local function standOffPoint(grid, deerPosition, goal)
    local away = awayFromGoal(deerPosition, goal)
    if away == nil then
        return nil
    end
    local standOff = options:GetFloat("StandOffDistance", 1.6)
    for _, degrees in ipairs(standOffAngles) do
        local direction = rotate(away, degrees)
        local point = { x = deerPosition.x + direction.x * standOff, y = deerPosition.y + direction.y * standOff }
        if not Route.isBlocked(grid, math.floor(point.x), math.floor(point.y)) then
            return point
        end
    end
    return nil
end

local function isBehindDeer(scoutPosition, deerPosition, goal)
    local away = awayFromGoal(deerPosition, goal)
    if away == nil then
        return true
    end
    local sx, sy = scoutPosition.x - deerPosition.x, scoutPosition.y - deerPosition.y
    local rearDistance = sx * away.x + sy * away.y
    if rearDistance < minimumRearDistance then
        return false
    end
    return math.abs(sx * away.y - sy * away.x) <= alignmentTolerance
end

local function newPush(scoutId, deerId)
    return {
        scoutId = scoutId,
        deerId = deerId,
        state = State.Positioning,
        commandIssued = false,
        nextCommandAt = 0,
        followedAt = 0,
        progressLoggedAt = 0,
        route = Route.newTracker(),
    }
end

local function setState(state, reason)
    LogDebug(string.format("[AutoDeerPush] %s -> %s: %s", push.state, state, reason))
    push.state = state
end

local function markUnreachable(now, reason)
    unreachableUntil[push.deerId] = now + unreachableRetryMs
    LogDebug(string.format("[AutoDeerPush] deer %d skipped for %d s: %s",
        push.deerId, unreachableRetryMs / 1000, reason))
end

-- Keeps the push's grid and route current. Returns true when the deer has a route; false
-- when routing is unavailable this update or the deer has none (then it is marked).
local function refreshRoute(now, deerPosition, centrePosition)
    local gridReady, unsized = Route.refreshGrid(push.route, now, deerPosition, centrePosition)
    if not gridReady then
        return false
    end
    if unsized > 0 then
        LogWarn(string.format("[AutoDeerPush] %d obstacles had no readable size; only their own tile is blocked", unsized))
    end
    local goal = { x = centrePosition.x, y = centrePosition.y, radius = options:GetFloat("ArrivalRadius", 4.0) }
    if Route.refreshPath(push.route, deerPosition, goal) == nil then
        markUnreachable(now, "no route to the town centre: " .. Route.describe(push.route.grid, deerPosition, goal))
        return false
    end
    return true
end

local function position(now, scout, scoutPosition, deer, deerPosition, goal)
    if now < push.nextCommandAt then
        return
    end
    if push.commandIssued and scout:GetActionType() ~= nil then
        return
    end

    if isBehindDeer(scoutPosition, deerPosition, goal) then
        push.commandIssued = issue("follow", SetUnitStanceFollowTracked, scout, deer)
        if not push.commandIssued then
            return
        end
        push.nextCommandAt = now + commandSpacingMs
        push.followedAt = now
        setState(State.Following, "behind the deer")
        return
    end

    local standOff = standOffPoint(push.route.grid, deerPosition, goal)
    if standOff == nil then
        markUnreachable(now, "no free spot behind it")
        return
    end
    push.commandIssued = issue("move", UnitsMoveTracked, scout, standOff)
    if push.commandIssued then
        push.nextCommandAt = now + commandSpacingMs
    end
end

-- The follow keeps the deer fleeing ahead of the scout. A follow that ended, or a scout
-- off the line to the steering point, goes back to positioning; the next move replaces
-- the follow.
local function follow(now, scout, scoutPosition, deerPosition, goal)
    if now - push.followedAt < followGraceMs then
        return
    end
    if scout:GetActionType() == nil then
        push.commandIssued = false
        setState(State.Positioning, "follow ended")
        return
    end
    if not isBehindDeer(scoutPosition, deerPosition, goal) then
        push.commandIssued = false
        setState(State.Positioning, "drifted out of line")
    end
end

local function advance(now, scout, deer, centrePosition)
    local scoutPosition, deerPosition = positionOf(scout), positionOf(deer)
    if scoutPosition == nil or deerPosition == nil then
        return
    end
    if not refreshRoute(now, deerPosition, centrePosition) then
        return
    end
    local goal = Route.steeringPoint(push.route.grid, push.route.path, deerPosition, steeringLookaheadTiles)
    -- A one-tile route leaves the deer at its own steering point: aim at the centre itself.
    if distance(goal, deerPosition) < 0.5 then
        goal = centrePosition
    end
    if push.state == State.Positioning then
        position(now, scout, scoutPosition, deer, deerPosition, goal)
    else
        follow(now, scout, scoutPosition, deerPosition, goal)
    end
end

-- Stops the scout if this push left it following a deer that is no longer the target.
local function releaseScout(reason)
    if push == nil then
        return
    end
    local scout = GetObjectById(push.scoutId)
    if scout and scout:IsAlive() and push.state == State.Following and push.commandIssued then
        issue("stop", UnitsStopTracked, scout)
    end
    LogDebug("[AutoDeerPush] push ended: " .. reason)
    push = nil
end

-- Logs why nothing is being pushed, each time the reason changes.
local idleReason = nil
local function noteIdle(reason)
    if reason ~= idleReason then
        LogDebug("[AutoDeerPush] idle: " .. reason)
        idleReason = reason
    end
end

-- Lock on (opt-in): only the deer whose Push button was clicked is pushed, to our nearest
-- town centre whoever's deer it is, until it arrives, dies, has no route or is cancelled.
local lockedDeerId = nil
-- A short message over a unit or the screen corner: { text, objectId or nil, untilMs }.
local notice = nil
local lastNow = 0

local function isLockOn()
    return options:GetBool("LockOn", false)
end

local function showNotice(text, objectId)
    notice = { text = text, objectId = objectId, untilMs = lastNow + noticeDurationMs }
end

local function liveObject(objectId)
    if objectId == nil then
        return nil
    end
    local object = GetObjectById(objectId)
    if object and object:IsAlive() then
        return object
    end
    return nil
end

local function releaseLock(reason, noticeText)
    if lockedDeerId == nil then
        return
    end
    LogInfo(string.format("[AutoDeerPush] lock on deer %d released: %s", lockedDeerId, reason))
    if noticeText then
        showNotice(noticeText, push and push.scoutId)
    end
    lockedDeerId = nil
    releaseScout(reason)
end

local function onPushButton(deerId)
    if liveObject(deerId) == nil then
        return
    end
    if lockedDeerId ~= nil and lockedDeerId ~= deerId then
        releaseScout("locked onto another deer")
    end
    lockedDeerId = deerId
    -- A click is the player's call: a deer resting after an unreachable spell is tried now.
    unreachableUntil[deerId] = nil
    LogInfo(string.format("[AutoDeerPush] locked onto deer %d", deerId))
end

-- Clicks arrive as "auto-deer-push:<kind>:<object id>".
local function handleButtonClicks()
    for _, buttonId in ipairs(TakeButtonClicks(buttonPrefix)) do
        -- The prefix is cut off as plain text: its "-" is a Lua pattern operator.
        local kind, objectId = string.match(string.sub(buttonId, #buttonPrefix + 1), "^(%a+):(%d+)$")
        if kind == "push" then
            onPushButton(tonumber(objectId))
        elseif kind == "cancel" then
            releaseLock("cancelled by the player", nil)
        else
            LogWarn("[AutoDeerPush] unknown button click: " .. buttonId)
        end
    end
end

local function ownPushers(playerId)
    local pushers = {}
    for _, unitClass in ipairs(pusherClasses) do
        for _, candidate in ipairs(livePositions(GetIndexedObjects(playerId, unitClass) or {}, isPusher)) do
            pushers[#pushers + 1] = candidate
        end
    end
    return pushers
end

local function ownTownCentres(townCentres)
    local own = {}
    for _, centre in ipairs(townCentres) do
        if centre.own then
            own[#own + 1] = centre
        end
    end
    return own
end

-- A push this update: the deer, its town centre and the scout, each { object, position }
-- (the centre as allTownCentres gives it); or nil with why, for the release and idle logs.
local function noPush(endReason, idleText)
    return nil, { endReason = endReason, idleText = idleText }
end

-- The automatic choice: our deer nearest our town centres, pushed by the pusher nearest
-- that town centre.
local function chooseAutomaticPush(now, playerId, deer, townCentres)
    local arrivalRadius = options:GetFloat("ArrivalRadius", 4.0)
    local target, centre = chooseDeer(now, deer, townCentres, arrivalRadius, push and push.deerId)
    if target == nil then
        return noPush("no deer of ours left to push",
            "no deer to push: " .. describeDeer(now, deer, townCentres, arrivalRadius))
    end
    local scout = nearestTo(centre.position, ownPushers(playerId))
    if scout == nil then
        return noPush("no scout", "no scout")
    end
    return { target = target, centre = centre, scout = scout }
end

-- The push's own scout while it lives, else the pusher nearest the deer.
local function lockedScout(playerId, deerPosition)
    local pushers = ownPushers(playerId)
    for _, candidate in ipairs(pushers) do
        if push and candidate.object:GetId() == push.scoutId then
            return candidate
        end
    end
    return nearestTo(deerPosition, pushers)
end

-- The locked choice: the clicked deer and our town centre nearest it. The lock ends when
-- the deer dies or arrives.
local function chooseLockedPush(playerId, townCentres)
    if lockedDeerId == nil then
        return noPush("nothing locked", "lock on: no deer locked")
    end
    local deerObject = liveObject(lockedDeerId)
    local deerPosition = deerObject and positionOf(deerObject)
    if deerPosition == nil then
        releaseLock("locked deer gone", "Deer gone")
        return noPush("locked deer gone", "lock on: locked deer gone")
    end
    local centre, centreDistance = nearestTo(deerPosition, ownTownCentres(townCentres))
    if centre == nil then
        return noPush("no town centre of ours", "lock on: no town centre of ours")
    end
    if centreDistance <= options:GetFloat("ArrivalRadius", 4.0) then
        releaseLock("locked deer delivered", "Deer delivered")
        return noPush("locked deer delivered", "lock on: deer delivered")
    end
    local scout = lockedScout(playerId, deerPosition)
    if scout == nil then
        return noPush("no scout", "lock on: no scout")
    end
    return { target = { object = deerObject, position = deerPosition }, centre = centre, scout = scout }
end

local function startOrKeepPush(scoutId, deerId)
    if push ~= nil and push.scoutId == scoutId and push.deerId == deerId then
        return
    end
    -- The push only leaves a deer that arrived, died, stopped being ours or lost its scout.
    releaseScout(push and push.deerId ~= deerId and "deer delivered or gone; next deer" or "scout changed")
    push = newPush(scoutId, deerId)
    LogDebug(string.format("[AutoDeerPush] push started: scout %d, deer %d", scoutId, deerId))
end

function Init()
    push = nil
    unreachableUntil = {}
    townCentresLogged = false
    heldFoodUnavailableLogged = false
    idleReason = nil
    lockedDeerId = nil
    notice = nil
    lastNow = 0
end

function Update()
    settleReceipts()
    local now = GetGameTimeMs()
    local player = GetAssignedPlayer()
    local prey = GetIndexedObjects(0, UnitClass.PREY_ANIMAL)
    if now == nil or player == nil or prey == nil then
        return
    end
    lastNow = now
    local lockOn = isLockOn()
    if lockOn then
        handleButtonClicks()
    else
        releaseLock("lock on turned off", nil)
    end
    local townCentres = allTownCentres(player:GetId())
    if townCentres == nil then
        return
    end

    local deer = livePositions(prey, isDeer)
    local chosen, none
    if lockOn then
        chosen, none = chooseLockedPush(player:GetId(), townCentres)
    else
        chosen, none = chooseAutomaticPush(now, player:GetId(), deer, townCentres)
    end
    if chosen == nil then
        releaseScout(none.endReason)
        local idleText = none.idleText
        if #deer == 0 then
            idleText = idleText .. "; prey " .. describePrey(prey)
        end
        noteIdle(idleText)
        return
    end
    idleReason = nil

    local target, centre, scout = chosen.target, chosen.centre, chosen.scout
    local deerId = target.object:GetId()
    startOrKeepPush(scout.object:GetId(), deerId)
    advance(now, scout.object, target.object, centre.position)
    -- Whether the push is working: the deer's distance to its town centre over time.
    if push and now - push.progressLoggedAt >= 10000 then
        push.progressLoggedAt = now
        LogDebug(string.format("[AutoDeerPush] progress: deer %d is %.1f tiles from the town centre, scout %.1f from the deer, %s",
            deerId, distance(target.position, centre.position), distance(scout.position, target.position), push.state))
    end
    if push and (unreachableUntil[deerId] or 0) > now then
        if lockedDeerId == deerId then
            releaseLock("locked deer unreachable", "No route for this deer")
        else
            releaseScout("deer unreachable")
        end
    end
end

function Shutdown()
    lockedDeerId = nil
    releaseScout("feature disabled")
end

local function drawLabel(text, object, color)
    local objectPosition = object:GetPosition()
    if objectPosition then
        RenderWorldLabel(text, objectPosition, labelSize, color, colors.background, labelOffsetPixels)
    end
end

local function drawButton(kind, object, text, style)
    local objectPosition = object:GetPosition()
    if objectPosition then
        RenderWorldButton(string.format("%s%s:%d", buttonPrefix, kind, object:GetId()), text, objectPosition, style)
    end
end

local function drawNotice()
    if notice == nil or lastNow > notice.untilMs then
        notice = nil
        return
    end
    local anchor = liveObject(notice.objectId)
    if anchor then
        drawLabel(notice.text, anchor, colors.text)
    else
        RenderTopRightText(notice.text, 16, 120, labelSize, colors.text, true)
    end
end

-- The locked deer circled and its scout labelled, with Cancel beside the scout (beside the
-- deer until a scout is on it).
local function drawLock(lockedDeer)
    local deerPosition = lockedDeer:GetPosition()
    if deerPosition then
        RenderWorldCircle(deerPosition, targetMarkerRadius, colors.target, 2)
    end
    local scout = push and push.deerId == lockedDeer:GetId() and liveObject(push.scoutId)
    if scout then
        drawLabel("Deer push: " .. push.state, scout, colors.text)
        drawButton("cancel", scout, "Cancel", cancelButtonStyle)
    else
        drawButton("cancel", lockedDeer, "Cancel", cancelButtonStyle)
    end
end

-- Lock on only: a Push button over every deer but the locked one.
function Render()
    if not isLockOn() then
        return
    end
    for _, animal in ipairs(GetIndexedObjects(0, UnitClass.PREY_ANIMAL) or {}) do
        if animal:GetId() ~= lockedDeerId and isDeer(animal) then
            drawButton("push", animal, "Push", pushButtonStyle)
        end
    end
    local lockedDeer = liveObject(lockedDeerId)
    if lockedDeer then
        drawLock(lockedDeer)
    end
    drawNotice()
end

options.lua

See Declare options before the script runs.

-- The options auto-deer-push shows in Settings. The host also runs this file on its own at
-- start-up, before the feature is first turned on, so it may use nothing but Settings.

local options = Settings.Module("auto-deer-push")
options:AddFloat("StandOffDistance", 1.6, 0.5, 4.0, "Scout stand-off behind the deer (tiles)")
-- At least 3: the town centre's own footprint reaches 2 tiles from its centre.
options:AddFloat("ArrivalRadius", 4.0, 3.0, 15.0, "Stop pushing within this distance of the town centre (tiles)")
-- Off: every deer of ours is pushed in turn. On: only the deer whose Push button you click,
-- like Auto Lamer's Lure, with the nearest scout picked for you.
options:AddBool("LockOn", false, "Lock on: push only the deer you click")

return options

route.lua

The route helper reads blocked terrain with GetPlacementTile and static obstacles with GetObjectsInArea, then runs A* on that grid. Route.steeringPoint returns the point a few tiles ahead along the path, and the scout pushes the deer toward it.

-- Routes for a Gaia animal driven or lured to a town centre, shared by auto-deer-push and
-- auto-lamer: a blocked-tile grid around the animal and the town centre from terrain and
-- static objects, kept current as the animal moves; an A* path from the animal to the ring
-- round the town centre; and points and directions along that path.

local Route = {}

-- XS unit attributes: the object's collision half-widths in tiles.
local sizeXAttribute = 3
local sizeYAttribute = 4
-- Gates open only for their owner and allies, so Gaia animals cannot pass them.
local gatesPassForAnimals = false

local obstacleClasses = {
    [UnitClass.TREE] = true,
    [UnitClass.GOLD_MINE] = true,
    [UnitClass.STONE_MINE] = true,
    [UnitClass.BERRY_BUSH] = true,
    [UnitClass.TERRAIN] = true,
    [UnitClass.WALL] = true,
    [UnitClass.GATE] = not gatesPassForAnimals,
}
local buildingObjectType = 1
-- Objects smaller than this (plants, skeletons, flags) are walked through. Live, class 914
-- decorations read a half-width of 0.01.
local decorationHalfWidth = 0.2
-- The grid covers the animal and the town centre plus this margin, and is rebuilt this
-- often as trees fall and buildings rise.
local gridMarginTiles = 10
local gridRefreshMs = 10000
-- An animal this far off its route gets a new one.
local offRouteTiles = 1.5
-- The path's direction at a point is taken across this many tiles either side of it, so
-- the 8-way tile steps do not swing it by 45 degrees from one tile to the next.
local directionWindowTiles = 1.5

local function hasBit(value, bitIndex)
    return math.floor(value / 2 ^ bitIndex) % 2 == 1
end

-- The engine's pathing grid, as the computer player's placement reads it (GetPlacementTile):
-- terrain flag 8 is water; pathing bits 0 and 14, and bit 1 on land, are blocked. It ignores
-- fog. MapTile:IsNavigatable is no use here: live, it reads false on plain visible land.
local waterFlagBit = 3
local function terrainBlocks(x, y)
    local flags, path = GetPlacementTile(x, y)
    if flags == nil then
        return nil
    end
    return hasBit(flags, waterFlagBit) or hasBit(path, 0) or hasBit(path, 14) or hasBit(path, 1)
end

local function isObstacle(object)
    local unitClass = object:GetClass()
    if unitClass == UnitClass.FARM then
        return false
    end
    if unitClass == UnitClass.GATE then
        return obstacleClasses[UnitClass.GATE]
    end
    return obstacleClasses[unitClass] == true or object:GetObjectType() == buildingObjectType
end

local function tileIndex(grid, x, y)
    return (y - grid.top) * grid.width + (x - grid.left)
end

local function inGrid(grid, x, y)
    return x >= grid.left and y >= grid.top and x < grid.left + grid.width and y < grid.top + grid.height
end

function Route.isBlocked(grid, x, y)
    return not inGrid(grid, x, y) or grid.blocked[tileIndex(grid, x, y)] == true
end

local function block(grid, x, y)
    if inGrid(grid, x, y) then
        grid.blocked[tileIndex(grid, x, y)] = true
    end
end

-- Marks the tiles an obstacle covers. Returns false when its size is unreadable; its own
-- tile is still marked, the least it can cover.
local function blockFootprint(grid, object)
    local position = object:GetPosition()
    if position == nil then
        return true
    end
    local halfX, halfY = object:GetAttribute(sizeXAttribute), object:GetAttribute(sizeYAttribute)
    if halfX == nil or halfY == nil then
        block(grid, math.floor(position.x), math.floor(position.y))
        return false
    end
    if halfX < decorationHalfWidth and halfY < decorationHalfWidth then
        return true
    end
    local epsilon = 0.001
    for y = math.floor(position.y - halfY + epsilon), math.floor(position.y + halfY - epsilon) do
        for x = math.floor(position.x - halfX + epsilon), math.floor(position.x + halfX - epsilon) do
            block(grid, x, y)
        end
    end
    return true
end

-- The grid over `bounds` ({ left, top, right, bottom } in tiles, inclusive); returns the
-- grid and how many obstacles had an unreadable size.
function Route.buildGrid(bounds)
    local grid = {
        left = bounds.left,
        top = bounds.top,
        width = bounds.right - bounds.left + 1,
        height = bounds.bottom - bounds.top + 1,
        blocked = {},
        -- What blocked the grid, for the log when an animal has no route.
        stats = { missingTiles = 0, terrainTiles = 0, obstaclesByClass = {}, terrainNames = {} },
    }
    for y = bounds.top, bounds.bottom do
        for x = bounds.left, bounds.right do
            local blocks = terrainBlocks(x, y)
            if blocks == nil then
                block(grid, x, y)
                grid.stats.missingTiles = grid.stats.missingTiles + 1
            elseif blocks then
                block(grid, x, y)
                grid.stats.terrainTiles = grid.stats.terrainTiles + 1
            end
        end
    end
    local unsized = 0
    local corner, farCorner = { x = bounds.left, y = bounds.top }, { x = bounds.right + 1, y = bounds.bottom + 1 }
    for _, object in ipairs(GetObjectsInArea(corner, farCorner)) do
        if isObstacle(object) then
            local unitClass = object:GetClass()
            grid.stats.obstaclesByClass[unitClass] = (grid.stats.obstaclesByClass[unitClass] or 0) + 1
            if unitClass == UnitClass.TERRAIN then
                local name = string.format("%s/%s", object:GetMasterName(), tostring(object:GetAttribute(sizeXAttribute)))
                grid.stats.terrainNames[name] = (grid.stats.terrainNames[name] or 0) + 1
            end
            if not blockFootprint(grid, object) then
                unsized = unsized + 1
            end
        end
    end
    return grid, unsized
end

-- The grid's make-up and the open tiles round the goal, for a no-route log line.
function Route.describe(grid, start, goal)
    local blocked = 0
    for _ in pairs(grid.blocked) do
        blocked = blocked + 1
    end
    local classes = {}
    for unitClass, count in pairs(grid.stats.obstaclesByClass) do
        classes[#classes + 1] = string.format("%d:%d", unitClass, count)
    end
    table.sort(classes)
    local openGoal = 0
    for y = grid.top, grid.top + grid.height - 1 do
        for x = grid.left, grid.left + grid.width - 1 do
            local centre = { x = x + 0.5, y = y + 0.5 }
            local dx, dy = centre.x - goal.x, centre.y - goal.y
            if math.sqrt(dx * dx + dy * dy) <= goal.radius and not Route.isBlocked(grid, x, y) then
                openGoal = openGoal + 1
            end
        end
    end
    local names = {}
    for name, count in pairs(grid.stats.terrainNames) do
        names[#names + 1] = string.format("%s:%d", name, count)
    end
    table.sort(names)
    local function tileReads(x, y)
        local flags, path = GetPlacementTile(x, y)
        return string.format("%d,%d flags=%s path=%s", x, y, tostring(flags), tostring(path))
    end
    local goalX, goalY = math.floor(goal.x) + 3, math.floor(goal.y)
    return string.format(
        "grid %dx%d at %d,%d, blocked %d (missing %d, terrain %d), obstacles by class {%s}, open goal tiles %d, animal tile %d,%d %s; class 914 {%s}; tiles [%s] [%s]",
        grid.width, grid.height, grid.left, grid.top, blocked, grid.stats.missingTiles, grid.stats.terrainTiles,
        table.concat(classes, " "), openGoal, math.floor(start.x), math.floor(start.y),
        Route.isBlocked(grid, math.floor(start.x), math.floor(start.y)) and "blocked" or "open",
        table.concat(names, " "), tileReads(math.floor(start.x), math.floor(start.y)), tileReads(goalX, goalY))
end

local function tileCentre(x, y)
    return { x = x + 0.5, y = y + 0.5 }
end

local function distance(left, right)
    local dx, dy = left.x - right.x, left.y - right.y
    return math.sqrt(dx * dx + dy * dy)
end

-- Binary min-heap of { key, value }.
local function heapPush(heap, key, value)
    heap[#heap + 1] = { key = key, value = value }
    local index = #heap
    while index > 1 do
        local parent = math.floor(index / 2)
        if heap[parent].key <= heap[index].key then
            break
        end
        heap[parent], heap[index] = heap[index], heap[parent]
        index = parent
    end
end

local function heapPop(heap)
    local top = heap[1]
    local last = heap[#heap]
    heap[#heap] = nil
    if #heap > 0 then
        heap[1] = last
        local index = 1
        while true do
            local left, right, smallest = index * 2, index * 2 + 1, index
            if heap[left] and heap[left].key < heap[smallest].key then smallest = left end
            if heap[right] and heap[right].key < heap[smallest].key then smallest = right end
            if smallest == index then break end
            heap[smallest], heap[index] = heap[index], heap[smallest]
            index = smallest
        end
    end
    return top.value
end

local neighbours = {
    { 1, 0, 1 }, { -1, 0, 1 }, { 0, 1, 1 }, { 0, -1, 1 },
    { 1, 1, math.sqrt(2) }, { 1, -1, math.sqrt(2) }, { -1, 1, math.sqrt(2) }, { -1, -1, math.sqrt(2) },
}

-- Tile centres from the animal's tile to the first tile within `goal.radius` of `goal`,
-- moving 8 ways without cutting blocked corners; nil when no route exists. The animal's
-- own tile counts as open, since it is standing there.
function Route.findPath(grid, start, goal)
    local startX, startY = math.floor(start.x), math.floor(start.y)
    if not inGrid(grid, startX, startY) then
        return nil
    end
    local function remaining(x, y)
        return math.max(0, distance(tileCentre(x, y), goal) - goal.radius)
    end
    local startIndex = tileIndex(grid, startX, startY)
    local cost, cameFrom, closed = { [startIndex] = 0 }, {}, {}
    local open = {}
    heapPush(open, remaining(startX, startY), { startX, startY })
    while #open > 0 do
        local node = heapPop(open)
        local x, y = node[1], node[2]
        local index = tileIndex(grid, x, y)
        if not closed[index] then
            closed[index] = true
            if distance(tileCentre(x, y), goal) <= goal.radius then
                local path = {}
                while index do
                    local px = index % grid.width + grid.left
                    local py = math.floor(index / grid.width) + grid.top
                    table.insert(path, 1, tileCentre(px, py))
                    index = cameFrom[index]
                end
                return path
            end
            for _, step in ipairs(neighbours) do
                local nx, ny = x + step[1], y + step[2]
                local diagonalClear = step[1] == 0 or step[2] == 0
                    or (not Route.isBlocked(grid, nx, y) and not Route.isBlocked(grid, x, ny))
                if diagonalClear and not Route.isBlocked(grid, nx, ny) then
                    local nextIndex = tileIndex(grid, nx, ny)
                    local nextCost = cost[index] + step[3]
                    if not closed[nextIndex] and (cost[nextIndex] == nil or nextCost < cost[nextIndex]) then
                        cost[nextIndex] = nextCost
                        cameFrom[nextIndex] = index
                        heapPush(open, nextCost + remaining(nx, ny), { nx, ny })
                    end
                end
            end
        end
    end
    return nil
end

-- True when the straight line between the points crosses no blocked tile.
function Route.hasLineOfSight(grid, from, to)
    local length = distance(from, to)
    local steps = math.max(1, math.ceil(length * 4))
    for step = 1, steps do
        local t = step / steps
        local x = math.floor(from.x + (to.x - from.x) * t)
        local y = math.floor(from.y + (to.y - from.y) * t)
        if Route.isBlocked(grid, x, y) and not (x == math.floor(from.x) and y == math.floor(from.y)) then
            return false
        end
    end
    return true
end

-- The index of the path point nearest `position`, and how far it is from it.
function Route.nearestOnPath(path, position)
    local bestIndex, bestDistance = 1, math.huge
    for index, point in ipairs(path) do
        local pointDistance = distance(point, position)
        if pointDistance < bestDistance then
            bestIndex, bestDistance = index, pointDistance
        end
    end
    return bestIndex, bestDistance
end

-- The farthest path point within `maxDistance` the animal can reach in a straight line,
-- and never nearer than the next point, so the push always has a direction.
function Route.steeringPoint(grid, path, position, maxDistance)
    local nearest = Route.nearestOnPath(path, position)
    local first = math.min(nearest + 1, #path)
    local chosen = path[first]
    for index = first + 1, #path do
        local point = path[index]
        if distance(point, position) > maxDistance or not Route.hasLineOfSight(grid, position, point) then
            break
        end
        chosen = point
    end
    return chosen
end

local function gridBounds(from, to)
    local width, widthAvailable = GetMapWidth()
    local height, heightAvailable = GetMapHeight()
    if not widthAvailable or not heightAvailable then
        return nil
    end
    return {
        left = math.max(0, math.floor(math.min(from.x, to.x)) - gridMarginTiles),
        top = math.max(0, math.floor(math.min(from.y, to.y)) - gridMarginTiles),
        right = math.min(width - 1, math.floor(math.max(from.x, to.x)) + gridMarginTiles),
        bottom = math.min(height - 1, math.floor(math.max(from.y, to.y)) + gridMarginTiles),
    }
end

-- A route kept current across updates by refreshGrid and refreshPath.
function Route.newTracker()
    return { grid = nil, builtAt = 0, path = nil }
end

-- Rebuilds the tracker's grid over `from` and `to` when it is missing or stale, which also
-- drops its path. Returns false when the map size is unreadable, else true and how many
-- obstacles the rebuild found with an unreadable size (0 when nothing was rebuilt).
function Route.refreshGrid(tracker, now, from, to)
    if tracker.grid ~= nil and now - tracker.builtAt < gridRefreshMs then
        return true, 0
    end
    local bounds = gridBounds(from, to)
    if bounds == nil then
        return false, 0
    end
    local unsized
    tracker.grid, unsized = Route.buildGrid(bounds)
    tracker.builtAt = now
    tracker.path = nil
    return true, unsized
end

-- Replans the tracker's path from `start` to `goal` when it has none or `start` has
-- strayed off it. Returns the path, or nil when no route exists. Needs a grid.
function Route.refreshPath(tracker, start, goal)
    local offRoute = tracker.path == nil or select(2, Route.nearestOnPath(tracker.path, start)) > offRouteTiles
    if offRoute then
        tracker.path = Route.findPath(tracker.grid, start, goal)
    end
    return tracker.path
end

function Route.length(path)
    local total = 0
    for index = 2, #path do
        total = total + distance(path[index - 1], path[index])
    end
    return total
end

-- How far along the path, in tiles from its start, the point on it nearest `position` is.
function Route.distanceAlong(path, position)
    local best, bestDistance, travelled = 0, distance(path[1], position), 0
    for index = 2, #path do
        local from, to = path[index - 1], path[index]
        local segment = distance(from, to)
        local share = ((position.x - from.x) * (to.x - from.x) + (position.y - from.y) * (to.y - from.y))
            / (segment * segment)
        share = math.max(0, math.min(1, share))
        local nearest = { x = from.x + (to.x - from.x) * share, y = from.y + (to.y - from.y) * share }
        local nearestDistance = distance(nearest, position)
        if nearestDistance < bestDistance then
            best, bestDistance = travelled + share * segment, nearestDistance
        end
        travelled = travelled + segment
    end
    return best
end

-- The point `along` tiles from the path's start, held to its ends.
function Route.pointAlong(path, along)
    local travelled = 0
    for index = 2, #path do
        local from, to = path[index - 1], path[index]
        local segment = distance(from, to)
        if along <= travelled + segment then
            local share = math.max(0, (along - travelled) / segment)
            return { x = from.x + (to.x - from.x) * share, y = from.y + (to.y - from.y) * share }
        end
        travelled = travelled + segment
    end
    local endPoint = path[#path]
    return { x = endPoint.x, y = endPoint.y }
end

-- The unit direction the path runs at `along` tiles from its start, or nil on a one-point
-- path.
function Route.directionAt(path, along)
    local behind = Route.pointAlong(path, along - directionWindowTiles)
    local ahead = Route.pointAlong(path, along + directionWindowTiles)
    local length = distance(behind, ahead)
    if length < 0.001 then
        return nil
    end
    return { x = (ahead.x - behind.x) / length, y = (ahead.y - behind.y) / length }
end

return Route

manifest.json

{
  "id": "auto-deer-push",
  "name": "Auto Deer Push",
  "description": "Uses your scout to follow your own deer and other huntable prey (not hares, chickens or monkeys) to your town center, steering round trees, walls, gates and buildings. Deer nearer an ally or enemy town center are left alone. With Lock on in its settings, it pushes only the deer whose Push button you click, with the nearest scout, until it arrives or you click Cancel.",
  "group": "Automation",
  "mainMenu": true,
  "order": 50,
  "entry": "main.lua",
  "files": [
    "options.lua",
    "main.lua"
  ],
  "feature": "AutoDeerPush",
  "options": "options.lua",
  "shared": [
    "route.lua"
  ]
}