Log inGet started
World

Next Move: Computer Opponents for Turn-Based Tactics

Branchmain
Branchesmain
Commit263f499d32

README.md

Next Move (turnAiKit): computer opponents for turn-based tactics games

Next Move is an AI opponent (enemy AI, CPU player, bot) for turn-based grid and tactics games: XCOM-likes, squad skirmishes, board wargames, hex or square grids. Its package name is turnAiKit. You give it an adapter (a handful of functions that answer questions about your game) and it decides, one step at a time, what each of a side's units should do: where to move, whom to shoot, when to heal, when to throw the grenade, when to stay in cover, when to end the turn.

It plans a unit's move together with the follow-up action (the best cell is the one with the best shot from it), weighs cover, the damage enemies could deal next turn, kill chances, flanks, firing positions, objectives and the ally it guards, and explains every choice in action.reasons. It ships seven personalities (balanced, aggressive, defensive, objective, skirmisher, flanker, bodyguard) and three difficulties (easy, normal, hard). Every personality plays measurably differently at every difficulty, and the test suite measures it. You can define your own personalities as plain weight tables.

The planner is pure Luau with no engine calls: it runs on any peer, in tests, on a server, and is deterministic for a seed (same state + same seed gives the same action).

What installing gives you:

PartWhat it is
turnAiKit.brainThe planner: nextAction, planUnit, personalities, difficulties.
turnAiKit.simA tiny self-contained square-grid skirmish (hp, range, damage, walls as cover, Bresenham line of sight) with a ready adapter over it, plus Sim.profile to measure how a configuration plays. The reference adapter, and a sandbox for tuning.
tests/turnAiKit.testSuiteDeterminism, termination, kill-taking, cover-seeking, objective play, skirmisher spacing, bodyguarding, per-personality behaviour metrics at every difficulty, pairwise distinctness, difficulty win rates.
how-to-make-a-computer-opponent-for-a-turn-based-tactics-game.guideWalkthrough: write an adapter, pick personalities and difficulty, add and measure a personality.

Install

Search ZeroMind for "Next Move turnAiKit" (or "computer opponent for a turn-based tactics game") and install the turnAiKit package by guid:

tools.use("zeromind", "installAsset", "<turnAiKit package guid>")

Then require("turnAiKit.brain") (and optionally require("turnAiKit.sim")).

30-second example (the sim adapter)

local Brain = require("turnAiKit.brain")
local Sim = require("turnAiKit.sim")

local state = Sim.new(Sim.skirmish(1))           -- 12x9 board, red vs blue
local side = "red"
Sim.beginTurn(state, side)                         -- red's units get 2 AP
while true do
    local action = Brain.nextAction(Sim.adapter(state), side, {
        personality = "flanker", difficulty = "hard", seed = 42,
    })
    print(action.kind, action.unit, table.concat(action.reasons, " | "))
    if action.kind == "end" then break end
    Sim.apply(state, side, action)                 -- your game applies it
end

-- or a whole game:
local result = Sim.playGame(Sim.skirmish(7), {
    red  = { personality = "defensive",  difficulty = "hard", seed = 1 },
    blue = { personality = "aggressive", difficulty = "easy", seed = 2 },
}, 30)
print(result.winner, result.rounds)

The loop your game runs

start of the AI side's turn: refresh its units' AP
repeat
    action = Brain.nextAction(adapter, side, opts)
    if action.kind == "end" then break end
    apply action  (spend AP / set canMove / canAct so the state changes)
until done

nextAction returns one step. If a unit's best plan is "move to X then shoot Y", the first call returns the move and the next call (state changed) returns the shot. It returns { kind = "end" } when no unit has a useful option left, so the loop always ends as long as applying an action spends that unit's AP (or clears canMove / canAct).

API

Brain.VERSION                 -- "1.0.1"
Brain.PERSONALITIES           -- { "balanced", "aggressive", "defensive", "objective", "skirmisher", "flanker", "bodyguard", ...yours }
Brain.DIFFICULTIES            -- { "easy", "normal", "hard" }
Brain.WEIGHT_KEYS             -- every weight key, sorted
Brain.personality(name)       -> weights            -- a copy, defaults filled in
Brain.definePersonality(name, weights)              -- partial table; missing keys take the balanced defaults
Brain.difficulty(name)        -> difficulty params  -- a copy
Brain.nextAction(adapter, side, opts) -> action
Brain.planUnit(adapter, unit, opts)   -> { move = cell?, option = option?, score, gain, reasons }

Sim.profile(brainOpts, profileOpts?) -> { dist, cover, attacks, objective, ward, rangeDev, flank, unitTurns, shots }

opts:

KeyMeaning
personalityA name from Brain.PERSONALITIES or a (partial) weights table. Default balanced.
difficulty"easy", "normal" (default), "hard", or a table overriding difficulty params.
seedNumber. Same state + same seed gives the same action. Noise is hashed from the seed and the unit/cell, not drawn from a stream, so it stays stable across calls.
perUnit{ [unitId] = personalityName or weights }: mix roles inside one side (a bodyguard next to flankers).

action:

  • { kind = "move", unit = id, cell = {q, r} }
  • { kind = "act", unit = id, option = <the adapter's option table, as given>, cell = option.cell }
  • { kind = "end" }

All carry score and reasons (short strings such as "move then shoot", "cover 2.0 (+5.0)", "shoot b3 75% kill 50% (+10.7)", "threat 6.0 (-9.0)", "firing position (+2.1)").

Which unit goes first: a unit that can act from where it stands goes before units that need to move, then the biggest improvement first.

Adapter reference

All cells are { q = number, r = number } (square, hex or any grid: the brain only compares cells through your distance). Functions are called with a dot (adapter.units(side)), not a colon.

FunctionRequiredReturns
units(side)yesThat side's living units that can still act this turn.
enemies(side)yesLiving enemy units (AP irrelevant).
allies(side)yesAll living units of the side.
moves(unit)yes{ { cell, cost } } reachable this action, not including staying.
options(unit, fromCell)yesWhat the unit could do if it stood at fromCell (see options).
cover(cell, fromCell)yes0, 1 or 2: cover a unit at cell has against an attacker at fromCell.
distance(a, b)yesGrid distance.
threat(cell, side)noExpected damage enemies of side could deal to a unit at cell next turn. If absent the brain estimates it from enemy cells, range, move, damage, cover and canSee.
canSee(a, b)noLine of sight between two cells (used by the threat estimate).
objective(side)no{ cells = { cell }, weight = number? } or nil: a zone to take / hold.

Unit fields: id, side, cell, hp, maxHp, ap (actions left; moving with ap >= 2 lets the brain plan an action after the move, with ap == 1 it is move OR act), canMove, canAct, role ("healer" | "leader" | "melee" | "ranged" | nil), range. Optional extras the brain reads when present: move (cells per move, default 3, used for threat reach) and damage ({min,max} or a number, default 3, used for threat and kill value).

Option fields: kind ("attack" | "heal" | "ability" | "overwatch" | "wait" | ...), id, target (unit id), cell, hitChance (0 to 100), damage = {min, max}, killChance (0 to 100; estimated from damage and target hp when absent), heal, area = { unitIds } (everyone an area attack hits) with friendlyHits = n (how many of those are friendly), value (extra game-supplied worth, multiplied by the ability weight). An option the brain scores at or below zero (e.g. wait) is never chosen.

Personalities

Each personality is a weight table (only what differs from balanced is listed). The signature column is what the test suite measures with Sim.profile and requires to stand out from balanced at easy, normal and hard.

PersonalityWhat it doesWeights (vs balanced)Signature metric
balancedAdvances into firing positions behind cover, trades shots, heals. The reference.(defaults)
aggressiveCloses in fast and shoots at every chance, but still takes cover and keeps out of melee reach when it can.damage 2, kill 7, approach 2.2, threat 0.45, avoidMelee 0.5, flank 0.5, moveCost 0ends closer to enemies and attacks more often
defensiveHolds strong cover, avoids exposure, shoots from safety.damage 0.9, cover 3, threat 1.8, approach 0.2, pressure 0.5, moveCost 0.1ends its turns in cover more often
objectiveMoves onto and holds the objective zone.objective 3, approach 0.3, cover 1, threat 0.5ends closer to the objective
skirmisherStays at its weapon's range and backs away from melee.keepRange 2, avoidMelee 2, approach 0, threat 0.6, cover 1holds its weapon range most tightly
flankerWorks around cover for shots on exposed targets.flank 3.5, pressure 1.2, cover 0.8larger share of shots on targets without cover
bodyguardStays by the side's healer (else leader), between it and threats, and shoots what can reach it.protect 2.5, guard 1.5, approach 0.3, cover 1ends closer to its ward

Measured behaviour (1.0.1, Sim.profile defaults: 6 seeded skirmishes x 6 rounds as red against balanced/normal; dist = cells to the nearest enemy, cover = share of units ending in cover from it, attacks = attacks per unit-turn, objective = cells to the zone, ward = cells from the medic, rangeDev = cells off weapon range, flank = share of shots on uncovered targets):

diffpersonalitydistcoverattacksobjectivewardrangeDevflank
easybalanced2.600.720.632.943.742.840.54
easyaggressive1.640.410.682.682.582.560.69
easydefensive3.590.970.553.882.733.310.34
easyobjective2.150.180.510.622.122.440.61
easyskirmisher3.930.500.293.725.000.990.71
easyflanker2.290.430.563.033.832.840.95
easybodyguard3.210.740.583.941.433.000.53
normalbalanced2.160.800.622.903.412.430.51
normalaggressive2.010.550.682.821.962.560.73
normaldefensive4.050.950.543.783.413.370.41
normalobjective2.320.210.520.671.942.110.56
normalskirmisher4.350.580.353.343.171.240.72
normalflanker2.220.550.612.433.522.480.72
normalbodyguard3.360.770.563.541.952.970.52
hardbalanced3.010.840.613.392.572.810.56
hardaggressive2.090.470.702.641.502.740.69
harddefensive3.130.970.633.782.303.070.35
hardobjective2.400.190.540.692.162.080.66
hardskirmisher4.500.650.433.513.511.210.40
hardflanker2.860.580.522.633.202.990.77
hardbodyguard3.060.750.613.451.922.760.45

Measure your own personality the same way:

local p = Sim.profile({ personality = "berserker", difficulty = "hard" })
print(p.dist, p.cover, p.attacks, p.flank)

Difficulties

noisepicks amongthreat consideredfocus firekill valuesmart abilities
easy+-0.2its top 3 plans of the same kind within 1.5 points60%nox0.5no (half-counts friendly fire, flat overwatch)
normal+-0.075best80%nox1yes
hardnonebest100%yesx1.3yes

Easy plays worse by choosing among the personality's own best plans (never trading a shot for a reposition or the other way round), underrating kills, half-ignoring next-turn threat and not focusing fire. It no longer adds large random noise, so an easy aggressive unit still plays aggressively and an easy defensive unit still hugs cover.

In the package's sim (seeded, deterministic): hard balanced beats easy balanced in 18 of 20 games; hard aggressive wins 17 of 30 against easy balanced; and against the same balanced/normal opponent every personality's hard version wins at least as often as its easy version (92 vs 58 wins over 7 x 20 games).

Weights reference

Every personality is a table of these keys (the balanced value in brackets). Units: damage and threat are in hit points; distances in cells.

KeyMeaning
damage [1.0]Per point of expected damage dealt (hit% x average damage, capped at target hp).
kill [5.0]Per 1.0 kill probability, x (1 + target's average damage / 4): a kill removes its next turn.
priority [1.0]Scales the role bonus of a target (leader +50%, healer +35%, ranged +15%, melee +5%).
focus [0.6]Bonus for shooting wounded targets, applied only on difficulties that focus fire (hard).
flank [0.3]Per cover level the target lacks against the shooter's cell (also counted in pressure).
cover [1.2]Per average cover level of the end cell against enemies close enough to matter.
threat [0.6]Penalty per point of expected incoming damage next enemy turn (doubled for a badly hurt unit).
approach [0.9]Penalty per cell to the nearest enemy (pulls the unit in).
pressure [1.0]For a cell the unit moves to without acting: per point of expected damage it threatens from there next turn (pulls units into firing positions instead of stalemates).
keepRange [0]Penalty per cell away from the unit's range to the nearest enemy.
avoidMelee [0]Penalty per cell inside a melee enemy's reach (move + 1).
objective [0]Pull toward the objective zone (-0.5 per cell away, +2 on it), x the zone's weight.
protect [0]Pull toward the protected ally (a healer, else a leader) and a bonus for standing between it and the nearest enemy.
guard [0]Bonus for attacking an enemy that can reach the protected ally.
heal [1.0]Per hp healed, more when the target is badly hurt.
overwatch [1.0]Value of an overwatch / reaction option (more when enemies are near, on smart difficulties).
ability [1.0]Multiplier on an option's game-supplied value.
friendlyFire [3.0]Penalty per friendly unit caught in an area attack.
moveCost [0.05]Penalty per movement cost (prefer staying when equal).

The demo

The world this package is published from opens on a demo board where two sides play the sim skirmish against each other, with buttons to change each side's personality and difficulty and a live log of the brain's reasons.

Versions

  • 1.0.1: renamed from turnBrain to Next Move (turnAiKit): require turnAiKit.brain / turnAiKit.sim instead of turnBrain.brain / turnBrain.sim; the API is otherwise unchanged. Personality tuning: new pressure weight (value of firing positions) and balanced approach 0.3 to 0.9, so cautious sides no longer stall out of range; aggressive keeps cover (cover 1.2, threat 0.45, avoids melee reach) and no longer loses most games to easy balanced; defensive, skirmisher, flanker and bodyguard weights sharpened; easy now picks among the personality's own top plans of the same kind instead of adding heavy noise. Added Sim.profile and tests that measure every personality x difficulty.
  • 1.0.0: first release as turnBrain.