# 7. Simple Tactics AI
Part of [[Grid and Turn-Based Tactics]]. Prev: [[6. Selection Input Highlights and Animation]]. Next: [[8. Pathfinding Tests and Performance]].
> [!warning] Code not compiled
> Written against the Unity 6000.5 Scripting API (`Awaitable.WaitForSecondsAsync`) and the rules classes from parts 1-5. Not compiled.
## 7.1 The idea: score every option, pick the best
Grid tactics AI does not need a behaviour tree to be decent. Each enemy unit has a small, enumerable set of options:
```text
for each cell I can stop on (ReachableSet.StopCells):
option "move here and wait"
for each enemy I could attack from here:
option "move here and attack that enemy"
score each option, take the highest
```
With 30 stop cells and a handful of targets that is a few hundred evaluations per unit, microseconds of work. This is **utility scoring**, one ply deep. It already produces the behaviours players read as "smart": finishing off wounded units, standing in forests, not walking into three archers.
| Term | Rewards | Weight (start) |
|---|---|---|
| Damage | expected damage dealt | 1.0 per HP |
| Kill | the attack kills | +10 |
| Terrain | defense bonus of the cell | 0.5 per point |
| Danger | damage enemies could deal to me here next turn | -0.75 per HP |
| Approach | closeness to the nearest foe (when not attacking) | -0.2 per cell of distance |
| Noise | randomness for lower difficulties | 0..`scoreNoise` |
Different weights make different personalities (Level Up! Level 11: combine a behaviour with a movement style): a **berserker** (danger 0, approach high), a **sniper** (danger high, terrain high), a **guard** (approach 0; only attacks what comes in range).
## 7.2 `TacticsAI`
```csharp
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
namespace Tactics
{
/// <summary>One-ply utility AI. Plans on the model, executes through commands like the player. NOT compiled.</summary>
public sealed class TacticsAI : MonoBehaviour
{
[SerializeField] BattlePresenter presenter;
[SerializeField] float thinkDelay = 0.3f;
[Header("Weights")]
[SerializeField] float damageWeight = 1f;
[SerializeField] float killBonus = 10f;
[SerializeField] float terrainWeight = 0.5f;
[SerializeField] float dangerWeight = 0.75f;
[SerializeField] float approachWeight = 0.2f;
[Header("Difficulty")]
[Tooltip("Random 0..scoreNoise added to every option. 0 = always the best move.")]
[SerializeField] float scoreNoise = 0f;
[SerializeField] int seed = 12345;
readonly CommandHistory history = new CommandHistory();
readonly List<Vector2Int> path = new List<Vector2Int>(64);
ReachableSet reach;
System.Random rng;
struct Plan
{
public Vector2Int Destination;
public UnitModel Target;
public float Score;
}
public async Awaitable TakeTurnAsync(BattleModel battle, List<UnitModel> actors, CancellationToken token)
{
reach ??= new ReachableSet(battle.Map);
rng ??= new System.Random(seed);
// Each unit plans on the live model, so later units see earlier results (focus fire).
foreach (UnitModel unit in actors)
{
if (!unit.IsAlive || unit.TurnDone) continue;
await Awaitable.WaitForSecondsAsync(thinkDelay, token); // readable pacing
Plan plan = MakePlan(battle, unit);
if (plan.Destination != unit.Cell && reach.TryGetPath(plan.Destination, path))
await history.ExecuteAsync(new MoveCommand(unit, path), battle, presenter, token);
if (plan.Target != null && plan.Target.IsAlive)
await history.ExecuteAsync(new AttackCommand(unit, plan.Target), battle, presenter, token);
else
await history.ExecuteAsync(new WaitCommand(unit), battle, presenter, token);
}
history.Commit();
}
Plan MakePlan(BattleModel b, UnitModel u)
{
reach.Compute(u.Cell, u.Stats.movePoints, u.Rules);
var best = new Plan { Destination = u.Cell, Target = null, Score = float.NegativeInfinity };
foreach (Vector2Int cell in reach.StopCells)
{
int index = b.Map.ToIndex(cell);
float positional = terrainWeight * b.Map.Defense(index) - dangerWeight * Danger(b, u, cell, index);
bool attackedFromHere = false;
foreach (UnitModel e in b.Units)
{
if (!CombatRules.CanTarget(b, u, cell, e)) continue;
attackedFromHere = true;
int dmg = CombatRules.Damage(b, u, e);
float s = damageWeight * Math.Min(dmg, e.Hp) + (dmg >= e.Hp ? killBonus : 0f) + positional + Noise();
if (s > best.Score) best = new Plan { Destination = cell, Target = e, Score = s };
}
if (!attackedFromHere)
{
float s = positional - approachWeight * NearestFoeDistance(b, u, cell) + Noise();
if (s > best.Score) best = new Plan { Destination = cell, Target = null, Score = s };
}
}
return best;
}
/// <summary>Damage foes could plausibly deal to u at 'cell' next turn. Cheap over-estimate by distance.</summary>
float Danger(BattleModel b, UnitModel u, Vector2Int cell, int index)
{
int terrain = b.Map.Defense(index);
float total = 0f;
foreach (UnitModel e in b.Units)
{
if (!e.IsAlive || e.Team == u.Team) continue;
int threatRadius = e.Stats.movePoints + e.Stats.maxRange;
if (GridMap.Manhattan(e.Cell, cell) > threatRadius) continue;
total += CombatRules.DamageAt(e.Stats, u.Stats, terrain);
}
return total;
}
static int NearestFoeDistance(BattleModel b, UnitModel u, Vector2Int cell)
{
int best = int.MaxValue;
foreach (UnitModel e in b.Units)
if (e.IsAlive && e.Team != u.Team) best = Math.Min(best, GridMap.Manhattan(e.Cell, cell));
return best == int.MaxValue ? 0 : best;
}
float Noise() => scoreNoise <= 0f ? 0f : (float)rng.NextDouble() * scoreNoise;
}
}
```
Notes on correctness:
- **The unit's own cell is in `StopCells`**, so "don't move" is always considered.
- **`CanTarget` from a hypothetical cell** uses line of sight from that cell. The unit has not moved yet, so its current cell still counts as occupied; that does not matter because line of sight ignores units in part 3.
- **Overkill is not rewarded:** `Math.Min(dmg, e.Hp)` stops the AI preferring a big hit on a nearly dead unit over a meaningful hit elsewhere; the kill bonus handles finishing blows.
- **Manhattan distance lies around walls.** Danger and approach use straight-line grid distance, so an enemy behind a river looks close. Part 8's distance field fixes both with true path distance at the cost of one Dijkstra per team per turn.
- **The AI uses the same commands and `CanExecute` checks** as the player, so it cannot cheat by accident, and its moves animate identically.
## 7.3 Making it better (in order of payoff)
1. **True distances.** Use a distance field from all player units (part 8) for the approach term, and from each enemy for danger.
2. **Focus fire.** After each unit's plan executes, the next unit plans on the updated model, so a wounded target is already cheaper to kill. This works now because planning reads live HP.
3. **Ordering.** Plan all units, execute the highest-scoring plan first, re-plan the rest. Prevents a melee unit blocking an archer's only firing position.
4. **Look-ahead.** Apply the plan on the model, let a cheap "player reply" heuristic score the result, undo. Snapshot HP before and restore after because attacks are not undoable in the history.
5. **Behaviours above the scorer.** Objectives (hold the gate, retreat when below 30% HP, protect the healer) change the *weights* per unit. A designer-facing way to author those is a graph in [[Unity Behavior]] or the class-based FSM in [[Enemy AI State Machine]] whose states set weights; the scorer stays the same.
## 7.4 Difficulty and fairness
- **Noise** in the scores is an honest difficulty knob: the AI sometimes picks the second-best option. Combine it with stat scaling from [[Game Balance and Dynamic Difficulty]] rather than giving the AI hidden information.
- **Telegraph intent.** Into the Breach shows exactly what each enemy will do next turn. You can do the same here: plan at the *start* of the player's phase, draw the plans as arrows, then execute them in the enemy phase (re-validating with `CanExecute`). Level Up!'s "no dropping rocks on the player's head" (Level 12) is the design reason.
- **Pacing.** `thinkDelay` and the presentation awaits keep enemy turns readable. Add a fast-forward toggle that halves delays for players who want it (Level 13, "If it feels too long... it probably is").
## Exercise
Give archers `dangerWeight = 1.5, terrainWeight = 1.0, approachWeight = 0.05` and knights `dangerWeight = 0, approachWeight = 0.5`. Put the weights in a `AIPersonality` ScriptableObject referenced from `UnitStats`. Playtest: the archers should hang back in forests while the knights charge.
## Sources
- `Awaitable.WaitForSecondsAsync`: https://docs.unity3d.com/6000.5/Documentation/ScriptReference/Awaitable.WaitForSecondsAsync.html
- Red Blob Games, A* introduction (distance fields as Dijkstra from many sources): https://www.redblobgames.com/pathfinding/a-star/introduction.html
- [[Enemy AI State Machine]], [[Unity Behavior]], [[Game Balance and Dynamic Difficulty]], [[Level Up! (Review)]] (Levels 11-13), [[Game Programming Patterns (Review)]] (Command, Type Object)