# 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:
| Part | What it is |
|---|---|
| `turnAiKit.brain` | The planner: `nextAction`, `planUnit`, personalities, difficulties. |
| `turnAiKit.sim` | A 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.testSuite` | Determinism, 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.guide` | Walkthrough: 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:
```luau
tools.use("zeromind", "installAsset", "<turnAiKit package guid>")
```
Then `require("turnAiKit.brain")` (and optionally `require("turnAiKit.sim")`).
## 30-second example (the sim adapter)
```luau
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
```luau
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`:
| Key | Meaning |
|---|---|
| `personality` | A name from `Brain.PERSONALITIES` or a (partial) weights table. Default `balanced`. |
| `difficulty` | `"easy"`, `"normal"` (default), `"hard"`, or a table overriding difficulty params. |
| `seed` | Number. 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.
| Function | Required | Returns |
|---|---|---|
| `units(side)` | yes | That side's living units that can still act this turn. |
| `enemies(side)` | yes | Living enemy units (AP irrelevant). |
| `allies(side)` | yes | All living units of the side. |
| `moves(unit)` | yes | `{ { cell, cost } }` reachable this action, not including staying. |
| `options(unit, fromCell)` | yes | What the unit could do if it stood at `fromCell` (see options). |
| `cover(cell, fromCell)` | yes | `0`, `1` or `2`: cover a unit at `cell` has against an attacker at `fromCell`. |
| `distance(a, b)` | yes | Grid distance. |
| `threat(cell, side)` | no | Expected 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)` | no | Line 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.
| Personality | What it does | Weights (vs balanced) | Signature metric |
|---|---|---|---|
| `balanced` | Advances into firing positions behind cover, trades shots, heals. The reference. | (defaults) | |
| `aggressive` | Closes 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 0 | ends closer to enemies and attacks more often |
| `defensive` | Holds strong cover, avoids exposure, shoots from safety. | damage 0.9, cover 3, threat 1.8, approach 0.2, pressure 0.5, moveCost 0.1 | ends its turns in cover more often |
| `objective` | Moves onto and holds the objective zone. | objective 3, approach 0.3, cover 1, threat 0.5 | ends closer to the objective |
| `skirmisher` | Stays at its weapon's range and backs away from melee. | keepRange 2, avoidMelee 2, approach 0, threat 0.6, cover 1 | holds its weapon range most tightly |
| `flanker` | Works around cover for shots on exposed targets. | flank 3.5, pressure 1.2, cover 0.8 | larger share of shots on targets without cover |
| `bodyguard` | Stays 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 1 | ends 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):
| diff | personality | dist | cover | attacks | objective | ward | rangeDev | flank |
|---|---|---|---|---|---|---|---|---|
| easy | balanced | 2.60 | 0.72 | 0.63 | 2.94 | 3.74 | 2.84 | 0.54 |
| easy | aggressive | **1.64** | 0.41 | **0.68** | 2.68 | 2.58 | 2.56 | 0.69 |
| easy | defensive | 3.59 | **0.97** | 0.55 | 3.88 | 2.73 | 3.31 | 0.34 |
| easy | objective | 2.15 | 0.18 | 0.51 | **0.62** | 2.12 | 2.44 | 0.61 |
| easy | skirmisher | 3.93 | 0.50 | 0.29 | 3.72 | 5.00 | **0.99** | 0.71 |
| easy | flanker | 2.29 | 0.43 | 0.56 | 3.03 | 3.83 | 2.84 | **0.95** |
| easy | bodyguard | 3.21 | 0.74 | 0.58 | 3.94 | **1.43** | 3.00 | 0.53 |
| normal | balanced | 2.16 | 0.80 | 0.62 | 2.90 | 3.41 | 2.43 | 0.51 |
| normal | aggressive | **2.01** | 0.55 | **0.68** | 2.82 | 1.96 | 2.56 | 0.73 |
| normal | defensive | 4.05 | **0.95** | 0.54 | 3.78 | 3.41 | 3.37 | 0.41 |
| normal | objective | 2.32 | 0.21 | 0.52 | **0.67** | 1.94 | 2.11 | 0.56 |
| normal | skirmisher | 4.35 | 0.58 | 0.35 | 3.34 | 3.17 | **1.24** | 0.72 |
| normal | flanker | 2.22 | 0.55 | 0.61 | 2.43 | 3.52 | 2.48 | **0.72** |
| normal | bodyguard | 3.36 | 0.77 | 0.56 | 3.54 | **1.95** | 2.97 | 0.52 |
| hard | balanced | 3.01 | 0.84 | 0.61 | 3.39 | 2.57 | 2.81 | 0.56 |
| hard | aggressive | **2.09** | 0.47 | **0.70** | 2.64 | 1.50 | 2.74 | 0.69 |
| hard | defensive | 3.13 | **0.97** | 0.63 | 3.78 | 2.30 | 3.07 | 0.35 |
| hard | objective | 2.40 | 0.19 | 0.54 | **0.69** | 2.16 | 2.08 | 0.66 |
| hard | skirmisher | 4.50 | 0.65 | 0.43 | 3.51 | 3.51 | **1.21** | 0.40 |
| hard | flanker | 2.86 | 0.58 | 0.52 | 2.63 | 3.20 | 2.99 | **0.77** |
| hard | bodyguard | 3.06 | 0.75 | 0.61 | 3.45 | **1.92** | 2.76 | 0.45 |
Measure your own personality the same way:
```luau
local p = Sim.profile({ personality = "berserker", difficulty = "hard" })
print(p.dist, p.cover, p.attacks, p.flank)
```
## Difficulties
| | noise | picks among | threat considered | focus fire | kill value | smart abilities |
|---|---|---|---|---|---|---|
| easy | +-0.2 | its top 3 plans of the same kind within 1.5 points | 60% | no | x0.5 | no (half-counts friendly fire, flat overwatch) |
| normal | +-0.075 | best | 80% | no | x1 | yes |
| hard | none | best | 100% | yes | x1.3 | yes |
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.
| Key | Meaning |
|---|---|
| `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`.