# 4. The Reasoner Momentum Commitment and Cooldowns Part of [[Utility AI]]. Previous: [[3. Considerations Actions and Compensation]]. Next: [[5. Brain Blackboard Sensors and Behaviours]]. ## 4.1 The problem with always picking the best If Attack scores 0.51 and Reload 0.50, and the values wobble a little each frame as the player moves, a naive agent switches back and forth every few frames, never finishing either. The reasoner adds three stabilizers and one source of variety. ## 4.2 UtilityReasoner.cs **`UtilityReasoner.cs`** ```csharp using System; using System.Collections.Generic; public enum UtilitySelection { Best, WeightedRandomAmongTop } /// <summary> /// Picks the action to run. Adds momentum (a bonus for the current action so the agent doesn't /// flicker between two close scores), commitment (minimum run time), cooldowns, and optional /// weighted-random choice among the best few for less predictable agents. Pure C#; time is passed in. /// </summary> public sealed class UtilityReasoner { readonly IReadOnlyList<UtilityAction> _actions; readonly double[] _endedAt; readonly Random _rng; public UtilityReasoner(IReadOnlyList<UtilityAction> actions, Random rng = null) { _actions = actions; _endedAt = new double[actions.Count]; for (var i = 0; i < _endedAt.Length; i++) _endedAt[i] = double.NegativeInfinity; Scores = new float[actions.Count]; _rng = rng ?? new Random(); } public UtilitySelection Selection { get; set; } = UtilitySelection.Best; public float Momentum { get; set; } = 0.25f; // current action's score x 1.25 public int TopCount { get; set; } = 3; // for WeightedRandomAmongTop public float TopFraction { get; set; } = 0.8f; // ...only actions within 80 % of the best public int Current { get; private set; } = -1; public double CurrentSince { get; private set; } public float[] Scores { get; } // last decision's final scores, for debugging public UtilityAction CurrentAction => Current >= 0 ? _actions[Current] : null; public bool OnCooldown(int i, double now) => now - _endedAt[i] < _actions[i].cooldownSeconds; /// <summary>Scores every action and returns the index to run (-1 if nothing scores above 0).</summary> public int Decide(IAIContext ctx, double now) { for (var i = 0; i < _actions.Count; i++) { var s = OnCooldown(i, now) ? 0f : UtilityScoring.Score(_actions[i], ctx); if (i == Current && s > 0f) s *= 1f + Momentum; Scores[i] = s; } if (Current >= 0 && Scores[Current] > 0f && now - CurrentSince < _actions[Current].commitSeconds) return Current; var next = Selection == UtilitySelection.Best ? Best() : WeightedTop(); if (next != Current) Switch(next, now); return Current; } /// <summary>The running action finished or failed: start its cooldown and choose fresh next time.</summary> public void EndCurrent(double now) { if (Current < 0) return; _endedAt[Current] = now; Current = -1; } void Switch(int next, double now) { if (Current >= 0) _endedAt[Current] = now; Current = next; CurrentSince = now; } int Best() { var best = -1; var bestScore = 0f; for (var i = 0; i < Scores.Length; i++) if (Scores[i] > bestScore) { bestScore = Scores[i]; best = i; } return best; } int WeightedTop() { var best = Best(); if (best < 0) return -1; var cutoff = Scores[best] * TopFraction; var candidates = new List<int>(); for (var i = 0; i < Scores.Length; i++) if (Scores[i] > 0f && Scores[i] >= cutoff) candidates.Add(i); candidates.Sort((a, b) => Scores[b].CompareTo(Scores[a])); if (candidates.Count > TopCount) candidates.RemoveRange(TopCount, candidates.Count - TopCount); var total = 0f; foreach (var i in candidates) total += Scores[i]; var roll = (float)_rng.NextDouble() * total; foreach (var i in candidates) { roll -= Scores[i]; if (roll <= 0f) return i; } return candidates[candidates.Count - 1]; } } ``` ## 4.3 Momentum The current action's score is multiplied by `1 + Momentum` (default 1.25). A challenger must beat it by 25 %, not by 0.01. In `MomentumPreventsFlicker`, action B goes from 0.45 to 0.52 against A's 0.48. Without momentum the agent would switch; with it A counts as 0.60 and stays. When B reaches 0.70 against A's 0.375, the switch happens. Raise momentum for steadier agents, lower it for twitchier, more reactive ones. Don't go above about 0.5 or agents get stuck doing stale things. ## 4.4 Commitment `commitSeconds` keeps an action chosen for at least that long once it starts, whatever the other scores do, **as long as it still scores above 0**. A veto always breaks commitment: a guard committed to Attack for one second still stops when the player vanishes behind a wall, because the "Can see threat" gate drops to 0. Use commitment for actions that look silly when interrupted, like a dodge roll or a flee sprint. ## 4.5 Cooldowns `cooldownSeconds` makes an action score 0 for a while **after it ends**, either because another action won or because the behaviour reported it was done (`EndCurrent`). Cooldowns stop loops such as Investigate → (nothing found) → Investigate again forever. They start at the end, not the start, so a long action isn't on cooldown while it runs. ## 4.6 Weighted random among the best With `Selection = WeightedRandomAmongTop`, the reasoner takes the actions within `TopFraction` (80 %) of the best score, keeps at most `TopCount` (3), and picks one at random in proportion to score. Two guards in the same situation might make different reasonable choices. Clearly worse options never get picked: an action at 0.2 when the best is 1.0 is out. `WeightedRandomPicksOnlyCloseContendersInProportion` checks both properties with a fixed seed. Use the fixed-seed constructor argument in tests and in replays (see [[Game Programming Patterns (Review)]] on deterministic simulation); use the default `new Random()` in play. ## 4.7 When to decide The reasoner is called by the brain (part 5) on a timer, not every frame. Four times a second is plenty for most agents and costs almost nothing: scoring six actions with three considerations each is about 20 dictionary lookups and some multiplications. With hundreds of agents, stagger them (the brain does) and lower the rate for agents far from the camera. Next: [[5. Brain Blackboard Sensors and Behaviours]].