A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace Statecraft.Sim
{
/// <summary>Unit movement in the GDD v0.1 loop (Phase 5 PRs 5 and 6; docs/rules/mvp.md R-MOVE-001 to R-MOVE-007). A Move
/// goes at command time along the cheapest path within the unit's movement points (spec 2026-10-12 section 2.3); Reachable
/// and Path are the preview the UI reads (spec section 2.6), from the same search.</summary>
public static class Movement
{
public const string Kind = "move";
/// <summary>The go-to order (R-MOVE-008): <see cref="Unit.Order"/> while a unit is on its way, with the hex "q,r".</summary>
public const string GoTo = "go_to";
/// <summary>The player's side (units_1948.yaml's id). A unit of any other side is the enemy's; a halutz has no side and
/// is the player's.</summary>
public const string PlayerSide = "israel";
/// <summary>The go-to's and the move's refusals (R-MOVE-005/006/008), as constants so the UI can say them in its
/// language (#2707). RefusedFull takes the count the hex already holds.</summary>
public const string RefusedNoHex = "A route names a hex", RefusedCannotMove = "That unit cannot move",
RefusedAlreadyThere = "That unit is already there", RefusedOffLand = "Units cannot enter water or leave the map",
RefusedEnemyHex = "An enemy unit holds that hex",
RefusedClosed = "Units may not enter an enemy-held locality before its capture is possible",
RefusedNoRoute = "No route reaches that hex", RefusedOutOfReach = "That hex is out of reach this turn",
RefusedFull = "That hex already holds {0} units of that side, the most one hex can hold";
static readonly IReadOnlyDictionary<int, int> NothingSpent = new Dictionary<int, int>();
/// <summary>The six axial directions in tools/hexgrid.py's NEIGHBOURS order, the fixed order of hexes.json's layout
/// (R-MOVE-002).</summary>
internal static readonly (int Q, int R)[] Neighbours = { (1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1) };
static bool IsEnemy(Unit u) => u.Side != "" && u.Side != PlayerSide;
/// <summary>R-MOVE-001: effective movement allowance, shared by simulation and presentation. Under 0.3 artillery keeps
/// its authored points (main's 2) and pays the infantry terrain costs (Q12, owner, 1 November 2026).</summary>
public static int Allowance(Content c, Unit u)
{
var type = c.UnitTypes.FirstOrDefault(t => t.Id == u.Type);
if (type == null) return 0;
if (!Gdd03Military.Applies(c) || type.Side == "") return type.MovementPoints;
if (type.Class == "infantry") return Gdd03Military.Scalar(c, "military.move_infantry");
if (type.Class == "armour") return Gdd03Military.Scalar(c, "military.move_armoured");
if (type.Class == Combat.ArtilleryClass) return type.MovementPoints;
return 0; // no fallback to an older identity's number for Deferred/unknown roles
}
/// <summary>Existing action budget, including artillery fire; not a new movement allowance.</summary>
public static int ActionsLeft(Content c, GameState s, int id, IReadOnlyDictionary<int, int> spent) =>
s.Units.TryGetValue(id, out var u) ? Math.Max(0, Points(c, u) - (spent.TryGetValue(id, out var used) ? used : 0)) : 0;
internal static int Points(Content c, Unit u) => Allowance(c, u);
/// <summary>The hexes unit <paramref name="unitId"/> can move to this turn, each with its path's cost, in (q, r) order:
/// what Move accepts on a turn the unit has not moved yet (R-MOVE-001 to R-MOVE-005). Empty for an unknown unit, an
/// enemy unit or one that cannot move.</summary>
public static IReadOnlyDictionary<(int Q, int R), int> Reachable(Content c, GameState s, int unitId) =>
Reachable(c, s, unitId, NothingSpent);
/// <summary>The hexes unit <paramref name="unitId"/> can move to with the points left after <paramref name="spent"/>,
/// each with its path's cost, in (q, r) order. Empty for an unknown unit, an enemy unit or one that cannot move.</summary>
public static IReadOnlyDictionary<(int Q, int R), int> Reachable(Content c, GameState s, int unitId, IReadOnlyDictionary<int, int> spent)
{
var result = new SortedDictionary<(int Q, int R), int>();
if (!s.Units.TryGetValue(unitId, out var u) || IsEnemy(u)) return result;
var points = Points(c, u);
if (points == 0) return result;
spent.TryGetValue(unitId, out var used);
var (dist, _) = Search(c, s, u, points - used, fresh: used == 0);
foreach (var kv in dist)
if (kv.Key != (u.Q, u.R) && Full(c, s, u, kv.Key.Q, kv.Key.R) == null) result[kv.Key] = kv.Value;
return result;
}
/// <summary>The hexes the unit's cheapest path to (<paramref name="q"/>, <paramref name="r"/>) enters, in order, within
/// this turn's movement points (R-MOVE-002); empty when the hex is out of reach.</summary>
public static IReadOnlyList<(int Q, int R)> Path(Content c, GameState s, int unitId, int q, int r) =>
Path(c, s, unitId, q, r, NothingSpent);
/// <summary>The hexes the unit's cheapest path to (<paramref name="q"/>, <paramref name="r"/>) enters, in order, within
/// the points left after <paramref name="spent"/>; empty when the hex is out of reach.</summary>
public static IReadOnlyList<(int Q, int R)> Path(Content c, GameState s, int unitId, int q, int r, IReadOnlyDictionary<int, int> spent)
{
if (!Reachable(c, s, unitId, spent).ContainsKey((q, r))) return Array.Empty<(int, int)>();
var u = s.Units[unitId];
spent.TryGetValue(unitId, out var used);
var (_, prev) = Search(c, s, u, Points(c, u) - used, fresh: used == 0);
var path = new List<(int Q, int R)>();
for (var h = (q, r); h != (u.Q, u.R); h = prev[h]) path.Add(h);
path.Reverse();
return path;
}
/// <summary>R-MOVE-002, R-MOVE-008: the cheapest path to (q, r) with no points limit, each hex with the turn it is
/// reached on (turn 1 spends the points left after <paramref name="spent"/>, later turns all of them; a step that costs
/// more than the full points takes a whole turn, R-MOVE-001). Empty for an unknown or enemy unit, one that cannot
/// move, its own hex, or a hex no path reaches. With <paramref name="card"/> the route is an operation card's (R-ENEMY-005)
/// and goes round every enemy-held locality but (q, r) (<see cref="Search"/>).</summary>
public static IReadOnlyList<(int Q, int R, int Turn)> Route(Content c, GameState s, int unitId, int q, int r, IReadOnlyDictionary<int, int> spent, bool card = false)
{
if (!s.Units.TryGetValue(unitId, out var u) || IsEnemy(u) || (u.Q, u.R) == (q, r) || Points(c, u) == 0)
return new List<(int Q, int R, int Turn)>();
var (dist, prev) = Search(c, s, u, int.MaxValue, card: card ? (q, r) : ((int, int)?)null);
return Split(c, s, u, q, r, spent, dist, prev);
}
/// <summary><see cref="Route"/> without a card, to many hexes of one unit: the search does not depend on the target, so
/// it runs once (at the first call) and each call only reads that unit's path to (q, r). The same routes as Route.</summary>
internal static Func<int, int, IReadOnlyList<(int Q, int R, int Turn)>> Routes(Content c, GameState s, int unitId, IReadOnlyDictionary<int, int> spent)
{
(Dictionary<(int Q, int R), int> Dist, Dictionary<(int Q, int R), (int Q, int R)> Prev)? search = null;
return (q, r) =>
{
if (!s.Units.TryGetValue(unitId, out var u) || IsEnemy(u) || (u.Q, u.R) == (q, r) || Points(c, u) == 0)
return new List<(int Q, int R, int Turn)>();
search ??= Search(c, s, u, int.MaxValue);
return Split(c, s, u, q, r, spent, search.Value.Dist, search.Value.Prev);
};
}
/// <summary>The path to (q, r) in one search, split into turns (R-MOVE-001, R-MOVE-003); empty when no path reaches it.</summary>
static IReadOnlyList<(int Q, int R, int Turn)> Split(Content c, GameState s, Unit u, int q, int r, IReadOnlyDictionary<int, int> spent,
Dictionary<(int Q, int R), int> dist, Dictionary<(int Q, int R), (int Q, int R)> prev)
{
var result = new List<(int Q, int R, int Turn)>();
var full = Points(c, u);
if (!dist.ContainsKey((q, r))) return result;
var hexes = new List<(int Q, int R)>();
for (var h = (q, r); h != (u.Q, u.R); h = prev[h]) hexes.Add(h);
hexes.Reverse();
spent.TryGetValue(u.Id, out var used);
int left = full - used, turn = 1, before = 0, first = 0;
for (int i = 0; i < hexes.Count; i++)
{
var step = dist[hexes[i]] - before;
if (step > left && !(left == full && step > full))
{
// R-MOVE-003, as Advance moves: a turn that would end on a hex full of the unit's side ends on the last
// free hex of that turn instead, and the next turn starts from there (#2548). With none free, as before.
var end = i - 1;
while (end >= first && Full(c, s, u, hexes[end].Q, hexes[end].R) != null) end--;
if (end >= first && end < i - 1)
{
result.RemoveRange(end + 1, result.Count - end - 1);
i = end + 1;
step = dist[hexes[i]] - dist[hexes[end]];
}
turn++; left = full; first = i;
}
before = dist[hexes[i]];
left = step > left ? 0 : left - step;
result.Add((hexes[i].Q, hexes[i].R, turn));
}
return result;
}
static string HexText(int q, int r) => string.Format(CultureInfo.InvariantCulture, "{0},{1}", q, r);
static (int Q, int R) Target(Unit u)
{
var parts = u.OrderTarget.Split(',');
return (int.Parse(parts[0], CultureInfo.InvariantCulture), int.Parse(parts[1], CultureInfo.InvariantCulture));
}
static void Stop(GameState s, Unit u, string key, string line, string hex, List<Cause> why)
{
Clear(s, u);
why.Add(UnitLines.Line(key, line, new[] { u }, hex));
}
/// <summary>R-ENEMY-009: an operation's remaining go-to for unit <paramref name="id"/> is cancelled (EventSystem.CancelOperation):
/// the unit stops where it stands, with the line of a card order that has ended.</summary>
internal static void Withdraw(GameState s, int id, List<Cause> why)
{
var u = s.Units[id];
var hex = u.OrderTarget;
Stop(s, u, WhyKeys.CardOrderEnded, $"Unit {id} stopped: the operation's order to hex {hex} has ended", hex, why);
}
/// <summary>Takes the unit's go-to away where it stands.</summary>
static void Clear(GameState s, Unit u)
{
s.Units[u.Id] = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, "", "", u.HomeCity, u.Full, u.CombatXp, u.Records);
s.CardOrders.Remove(u.Id); // a stopped go-to is no operation card's order any more (R-ENEMY-005)
}
/// <summary>R-MOVE-008: gives the player's unit the go-to order and moves it at once as far as its points left reach.
/// Refused, the state untouched, for no hex, an unknown or enemy unit, one that cannot move or is there, water or off
/// the board, an enemy unit's hex, a closed locality (R-MOVE-005) or a hex no route reaches. With <paramref name="cardUntil"/>
/// the order is an operation card's (R-ENEMY-005): its route goes round every enemy-held locality but the hex, and it
/// ends on that day (<see cref="ContinueRoutes"/>). The player's own go-to replaces a card's.</summary>
internal static string? GiveGoTo(Content c, GameState s, int unitId, int? q, int? r, Dictionary<int, int> spent, List<Cause> why, DateTime? cardUntil = null)
{
if (q == null || r == null) return RefusedNoHex;
if (!s.Units.TryGetValue(unitId, out var u)) return "There is no such unit";
if (IsEnemy(u)) return "That unit is not yours";
if (Points(c, u) == 0) return RefusedCannotMove;
if (u.Q == q && u.R == r) return RefusedAlreadyThere;
if (!(c.HexAt(q.Value, r.Value) is MapHex hex) || !hex.Land) return RefusedOffLand;
if (s.Units.Values.Any(x => x.Q == q && x.R == r && IsEnemy(x))) return RefusedEnemyHex;
if (Closed(c, s, false).Contains((q.Value, r.Value))) return RefusedClosed;
if (Route(c, s, unitId, q.Value, r.Value, spent, cardUntil != null).Count == 0) return RefusedNoRoute;
var target = HexText(q.Value, r.Value);
var given = new Unit(u.Id, u.Type, u.Q, u.R, u.Service, u.Side, u.Strength, GoTo, target, u.HomeCity, u.Full, u.CombatXp, u.Records);
s.Units[unitId] = given;
if (cardUntil is DateTime until) s.CardOrders[unitId] = until; else s.CardOrders.Remove(unitId);
why.Add(UnitLines.Line(WhyKeys.OnItsWay, $"Unit {unitId} is on its way to hex {target}", new[] { given }, target));
if (u.Order == "fortify")
why.Add(UnitLines.Line(WhyKeys.FortifyLost, $"Unit {unitId} left hex {u.OrderTarget} and is no longer fortified", new[] { u }, u.OrderTarget));
Advance(c, s, given, q.Value, r.Value, spent, why, cardUntil != null);
return null;
}
/// <summary>R-MOVE-009, the route step: at the start of the player's turn, in ascending id, each unit with a go-to moves
/// on (<see cref="Advance"/>). An enemy unit next to it does not stop it (Q-MOVE-4: no zone of control). An operation
/// card's go-to (R-ENEMY-005) whose day has come stops instead, where the unit stands: the order ends with the operation.
/// A card's go-to whose unit is now the last Israeli unit on an occupied place (SettlementControl.LastGarrison; owner,
/// 2 November 2026, #2087: "Keep a garrison in Nazareth (Recommended)") is taken away too, the unit stays, and
/// <paramref name="rejected"/> lists it with <see cref="Orders.RefusedLastGarrison"/>, as the card's order would be at
/// the start. The player's own go-to is never held back.</summary>
internal static void ContinueRoutes(Content c, GameState s, Dictionary<int, int> spent, List<Cause> why, List<Rejection>? rejected = null)
{
// A card's order the player replaced (fortify, hold, attack, send home) or whose unit is gone is no card's order.
foreach (var id in s.CardOrders.Keys.ToList())
if (!s.Units.TryGetValue(id, out var x) || x.Order != GoTo) s.CardOrders.Remove(id);
foreach (var id in s.Units.Keys.OrderBy(x => x).ToList())
{
if (!s.Units.TryGetValue(id, out var u) || u.Order != GoTo) continue;
var (q, r) = Target(u);
var card = s.CardOrders.TryGetValue(id, out var until);
if (card && s.Date >= until)
Stop(s, u, WhyKeys.CardOrderEnded, $"Unit {id} stopped: the operation's order to hex {HexText(q, r)} has ended", HexText(q, r), why);
else if (card && SettlementControl.LastGarrison(c, s, u))
{
Clear(s, u);
rejected?.Add(new Rejection(new UnitOrder(id, GoTo, q, r), Orders.RefusedLastGarrison));
}
else Advance(c, s, u, q, r, spent, why, card);
}
}
/// <summary>R-MOVE-008, R-MOVE-009: moves the unit along a fresh route to (q, r) as far as this turn's points reach,
/// stopping short of a full hex; stops it (order cleared) when no route reaches the hex or the hex is full on arrival,
/// and clears the order on arrival. With no hex of this turn free, it waits, keeping the order. A <paramref name="card"/>
/// order's route and moves go round every enemy-held locality but (q, r) (R-ENEMY-005).</summary>
static void Advance(Content c, GameState s, Unit u, int q, int r, Dictionary<int, int> spent, List<Cause> why, bool card = false)
{
var route = Route(c, s, u.Id, q, r, spent, card);
if (route.Count == 0) { Stop(s, u, WhyKeys.StoppedNoRoute, $"Unit {u.Id} stopped: no route reaches hex {HexText(q, r)}", HexText(q, r), why); return; }
var today = route.TakeWhile(h => h.Turn == 1).ToList();
for (int i = today.Count - 1; i >= 0; i--)
{
var h = today[i];
if (Full(c, s, u, h.Q, h.R) != null)
{
if ((h.Q, h.R) == (q, r)) { Stop(s, u, WhyKeys.StoppedFull, $"Unit {u.Id} stopped: hex {HexText(q, r)} is full", HexText(q, r), why); return; }
continue;
}
if (Move(c, s, u.Id, h.Q, h.R, spent, why, card: card ? (q, r) : ((int, int)?)null) is string refused) { Stop(s, u, WhyKeys.StoppedNoRoute, $"Unit {u.Id} stopped: {refused}", HexText(q, r), why); return; }
if ((h.Q, h.R) == (q, r)) Stop(s, s.Units[u.Id], WhyKeys.Arrived, $"Unit {u.Id} arrived at hex {HexText(q, r)}", HexText(q, r), why);
return;
}
}
/// <summary>R-MOVE-001: the movement points unit <paramref name="unitId"/> has left this turn; 0 for an unknown unit.</summary>
public static int PointsLeft(Content c, GameState s, int unitId, IReadOnlyDictionary<int, int> spent)
{
if (!s.Units.TryGetValue(unitId, out var u)) return 0;
spent.TryGetValue(unitId, out var used);
return Math.Max(0, Points(c, u) - used);
}
/// <summary>R-MOVE-010: the player's military units, in ascending id, that have movement points, have neither moved nor
/// attacked this turn (nothing in <paramref name="spent"/>) and have no order (fortify, fortifying, hold and go-to are
/// orders). End turn waits for them (spec 2026-10-23 section 7); Skip is the UI's and not in the sim.</summary>
public static IReadOnlyList<int> NeedsOrders(Content c, GameState s, IReadOnlyDictionary<int, int> spent) =>
s.Units.Values.Where(u => u.Side == PlayerSide && Points(c, u) > 0 && u.Order == ""
&& !(spent.TryGetValue(u.Id, out var used) && used > 0))
.Select(u => u.Id).ToList();
/// <summary>R-MOVE-006: moves the unit, spending the path's cost from what <paramref name="spent"/> says it has used this
/// turn (R-MOVE-001). Refused, state untouched, for an unknown or enemy unit, one that cannot move or is already there,
/// water or a hex off the map, an enemy unit's hex (entering it is an attack, Q-MOVE-3), an enemy-held locality that
/// is not a target (R-MOVE-005), a hex full of the unit's side (R-MOVE-003), or a hex out of reach this turn. With <paramref name="enemy"/>
/// the enemy AI orders its own unit through the same checks, the sides swapped (R-ENEMY-001). With <paramref name="card"/>
/// the move is a step of an operation card's go-to to that hex, and its cost is that of the way round (<see cref="Search"/>).</summary>
internal static string? Move(Content c, GameState s, int unitId, int q, int r, Dictionary<int, int> spent, List<Cause> why, bool enemy = false, (int Q, int R)? card = null)
{
if (!s.Units.TryGetValue(unitId, out var u)) return "There is no such unit";
if (IsEnemy(u) != enemy) return "That unit is not yours";
var points = Points(c, u);
if (points == 0) return RefusedCannotMove;
if (u.Q == q && u.R == r) return RefusedAlreadyThere;
if (!(c.HexAt(q, r) is MapHex hex) || !hex.Land) return RefusedOffLand;
if (s.Units.Values.Any(x => x.Q == q && x.R == r && IsEnemy(x) != enemy)) return RefusedEnemyHex;
if (Closed(c, s, enemy).Contains((q, r))) return RefusedClosed;
if (Full(c, s, u, q, r) is string full) return full;
spent.TryGetValue(unitId, out var used);
var (dist, _) = Search(c, s, u, points - used, fresh: used == 0, card: card, to: (q, r));
if (!dist.TryGetValue((q, r), out var cost)) return RefusedOutOfReach;
// Moving clears fortify at once (Q-HOLD-1, "lost on move"; the standing orders' "fortify", or "fortifying" the turn it
// is given, with the hex it names), so a unit that goes out and comes back the same turn is not fortified; hold moves with
// the unit. The order step at the end of the turn only sees the final hex.
var fortified = u.Order == "fortify" || u.Order == "fortifying";
s.Units[unitId] = new Unit(u.Id, u.Type, q, r, u.Service, u.Side, u.Strength, fortified ? "" : u.Order, fortified ? "" : u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
spent[unitId] = used + cost;
why.Add(new Cause("map", unitId.ToString(CultureInfo.InvariantCulture), cost,
FormattableString.Invariant($"Unit {unitId} moved to hex {q},{r} for {cost} movement points"), enemy ? Kind : "",
key: WhyKeys.UnitMoved, units: new[] { new UnitRef(u) },
args: new[] { FormattableString.Invariant($"{q},{r}"), cost.ToString(CultureInfo.InvariantCulture) }));
if (u.Order == "fortify")
why.Add(UnitLines.Line(WhyKeys.FortifyLost,
$"Unit {unitId} left hex {u.OrderTarget} and is no longer fortified", new[] { u }, u.OrderTarget));
return null;
}
internal static int StackLimit(Content c, GameState s) => Gdd03Military.Applies(c)
? Gdd03Military.Scalar(c, "military.stack_limit") : c.RulesAt(s.Date).Mvp!.StackLimit!.Value;
/// <summary>R-MOVE-003: the refusal when (q, r) already holds stack_limit units of <paramref name="u"/>'s side, else null.</summary>
internal static string? Full(Content c, GameState s, Unit u, int q, int r)
{
var limit = StackLimit(c, s); // the loader requires it in the GDD loop
var held = s.Units.Values.Count(x => x.Id != u.Id && x.Side == u.Side && x.Q == q && x.R == r);
return held >= limit ? string.Format(CultureInfo.InvariantCulture, RefusedFull, held) : null;
}
/// <summary>R-MOVE-005: the hexes of mvp.enemy_held_localities. For the enemy (R-ENEMY-001, the rule's mirror) every
/// other locality's hex, so no enemy retreat ends on a player's locality (#2932). An enemy move may, but only on the
/// one it is sent to (R-CTRL-006, <see cref="Closed"/>, <see cref="Search"/>).</summary>
internal static HashSet<(int Q, int R)> NoEntry(Content c, GameState s, bool enemy = false)
{
var ids = Held(c, s);
// The enemy's set is built from the player's localities, not as all hexes minus the enemy-held ones: at 4.4 km (#1183)
// Rehovot shares Ramla's hex (-4, 24), which must stay closed to the enemy while Ramla is enemy-held (owner review, #1796).
// An annexed target closes its target's hex too (Ramla's (-3, 24), #1796), where R-CTRL-006 checks it (#2955).
if (enemy) return new HashSet<(int Q, int R)>(c.SettlementHexes.Where(h => !ids.Contains(h.Id)).Select(h => (h.Q, h.R))
.Concat(c.SettlementTargets.Where(t => HeldAnnexed(s, t.Id)).Select(t => (t.Q, t.R))));
// A target's hex, not its settlement's, as in Closed: for Ramla (ContentLoader.TargetOnANeighbour, #1796) that is
// (-3, 24), so a retreat or a Raid's withdrawal never ends where it would capture the place, while Rehovot's shared
// settlement hex (-4, 24) stays open (owner review, #1796).
return new HashSet<(int Q, int R)>(c.SettlementHexes.Where(h => ids.Contains(h.Id) && !c.SettlementTargets.Any(t => t.Id == h.Id))
.Select(h => (h.Q, h.R)).Concat(c.SettlementTargets.Where(t => ids.Contains(t.Id)).Select(t => (t.Q, t.R))));
}
/// <summary>mvp.enemy_held_localities less the annexed targets Israel holds: an annexed target is Israeli (R-CTRL-016,
/// OWNER QUESTION 3 (a) on #799), not enemy-held, until enemy units take it (R-CTRL-006; the owner on #2955, "Can be
/// taken"); then it is enemy-held again.</summary>
static List<string> Held(Content c, GameState s) => c.RulesAt(s.Date).Mvp!.EnemyHeldLocalities
.Where(id => !HeldAnnexed(s, id)).ToList();
/// <summary>An annexed target Israel holds: its record is annexed and Israeli, not taken by enemy units (R-CTRL-006).</summary>
static bool HeldAnnexed(GameState s, string id) =>
s.Settlements.TryGetValue(id, out var x) && x.State == SettlementControl.Annexed && x.Owner == PlayerSide;
/// <summary>R-MOVE-005 in Phase 6 (#1304): the hexes a move and its path may not enter. For the player, those of
/// mvp.enemy_held_localities that are not curated targets (settlement_targets.yaml), so a target can be captured in play
/// (the owner's #793 ruling) while the rest, Gaza today, stay closed, and so does a depopulated target's hex (R-CTRL-020);
/// for the enemy, <see cref="NoEntry"/>'s mirror less the player's localities, which an enemy move may now end on
/// when it is sent there (R-CTRL-006; <see cref="Search"/> keeps every other one off its path), and so may it on an
/// annexed target Israel holds (the owner on #2955, "Can be taken"), so only an arab_town that is not enemy-held (Jaffa)
/// stays closed to them. A hex one of those shares stays closed. Raid's withdrawal and combat retreat still read <see cref="NoEntry"/>, so neither
/// ends on an enemy-held place, nor an enemy retreat on a player's locality.</summary>
static HashSet<(int Q, int R)> Closed(Content c, GameState s, bool enemy)
{
if (enemy)
{
var open = new HashSet<string>(SettlementControl.PlayerLocalities(c, s).Select(h => h.Id)
.Concat(c.SettlementTargets.Where(t => HeldAnnexed(s, t.Id)).Select(t => t.Id)), StringComparer.Ordinal);
var held = Held(c, s);
return new HashSet<(int Q, int R)>(c.SettlementHexes.Where(h => !held.Contains(h.Id) && !open.Contains(h.Id)).Select(h => (h.Q, h.R)));
}
// A depopulated target (R-CTRL-020) stays closed: Deport leaves nothing to capture there again.
var ids = c.RulesAt(s.Date).Mvp!.EnemyHeldLocalities.Except(c.SettlementTargets.Select(t => t.Id)
.Where(id => !(s.Settlements.TryGetValue(id, out var x) && x.Depopulated))).ToList();
// A depopulated target closes its target's hex: for Ramla (ContentLoader.TargetOnANeighbour, #1796) that is
// (-3, 24), not its settlement hex, which Rehovot shares.
return new HashSet<(int Q, int R)>(c.SettlementHexes.Where(h => ids.Contains(h.Id) && !c.SettlementTargets.Any(t => t.Id == h.Id))
.Select(h => (h.Q, h.R)).Concat(c.SettlementTargets.Where(t => ids.Contains(t.Id)).Select(t => (t.Q, t.R))));
}
/// <summary>R-ENEMY-002: the furthest hex the unit can reach this turn on its cheapest path to (<paramref name="q"/>,
/// <paramref name="r"/>), by the same search as Move, including R-MOVE-001's full-points first-step exception; null
/// when no path leads there or the unit is already there.</summary>
internal static (int Q, int R)? Toward(Content c, GameState s, Unit u, int q, int r)
{
var points = Points(c, u);
if (points == 0) return null;
var (dist, prev) = Search(c, s, u, int.MaxValue, to: (q, r));
if (!dist.ContainsKey((q, r)) || (u.Q, u.R) == (q, r)) return null;
var h = (q, r);
while (dist[h] > points && prev[h] != (u.Q, u.R)) h = prev[h];
return h == (u.Q, u.R) ? ((int, int)?)null : h;
}
/// <summary>R-MOVE-007: the hexes of each built corridor segment (a segment not started or being built is no road yet),
/// with its kind's mvp.road_move_cost or mvp.rail_move_cost.</summary>
static List<(HashSet<(int Q, int R)> Hexes, int Cost)> BuiltSegments(Content c, GameState s)
{
var m = c.RulesAt(s.Date).Mvp!; // the loader requires both costs in the GDD loop
var built = new List<(HashSet<(int Q, int R)>, int)>();
foreach (var d in c.Corridors)
if (s.Corridors.TryGetValue(d.Id, out var w))
for (int i = 0; i < d.Segments.Count; i++)
if (w.Segments[i]?.BuiltOn != null)
built.Add((new HashSet<(int Q, int R)>(d.Segments[i].Hexes.Select(h => (h[0], h[1]))),
Gdd03Military.Applies(c)
? Gdd03Military.Scalar(c, d.Kind == Corridors.Rail ? "military.move_rail" : "military.move_road")
: d.Kind == Corridors.Rail ? m.RailMoveCost!.Value : m.RoadMoveCost!.Value));
return built;
}
/// <summary>R-MOVE-001, R-MOVE-002, R-MOVE-004, R-MOVE-005, R-MOVE-007: the cheapest cost of every hex within
/// <paramref name="budget"/> points from the unit's hex, and the hex each is entered from. A path enters only land hexes,
/// at their biome's cost or, from a hex of the same built corridor segment, at the kind's cost when that is lower, and
/// never an enemy unit's hex or a closed enemy-held locality's (<see cref="Closed"/>); passing next to either costs nothing extra (no zone of
/// control, Q-MOVE-4). Hexes leave the frontier in (cost, q, r) order and neighbours are tried in the fixed
/// <see cref="Neighbours"/> order, so a hex reached at the same cost twice keeps the first, and the path is the same
/// every run. With <paramref name="fresh"/>, one neighbouring hex whose cost exceeds the budget costs the whole budget
/// (R-MOVE-001, OQ-3). Stacking limits only where a move ends, so it is not checked here. With <paramref name="card"/>, an
/// operation card's go-to to that hex (R-ENEMY-005; the owner's answer 1 on #2087, 31 October 2026), every enemy-held
/// locality (<see cref="NoEntry"/>) but that hex is closed too, open target or not: the march never ends on, and so
/// never captures, a place it was not sent to. An enemy unit's path, the same way, enters no player's locality and no
/// annexed target Israel holds but <paramref name="to"/>, the hex it is sent to (R-CTRL-006; the owner on #2955,
/// "Destination only (Recommended)").</summary>
static (Dictionary<(int Q, int R), int> Dist, Dictionary<(int Q, int R), (int Q, int R)> Prev) Search(
Content c, GameState s, Unit u, int budget, bool fresh = false, (int Q, int R)? card = null, (int Q, int R)? to = null)
{
var costs = c.RulesAt(s.Date).Mvp!.MoveCost; // the loader requires a cost for every land biome in the GDD loop
var blocked = Closed(c, s, IsEnemy(u));
if (card is (int, int) sent) blocked.UnionWith(NoEntry(c, s).Where(h => h != sent));
// R-CTRL-006: an enemy path goes round every player's locality but the one it is sent to, as a card's go-to does
// (the owner's answer 1 on #2087), so an enemy march never ends on, and so never takes, a place it was not sent to.
if (IsEnemy(u)) blocked.UnionWith(NoEntry(c, s, true).Where(h => h != to));
var built = BuiltSegments(c, s);
foreach (var x in s.Units.Values) if (IsEnemy(x) != IsEnemy(u)) blocked.Add((x.Q, x.R));
var dist = new Dictionary<(int Q, int R), int> { [(u.Q, u.R)] = 0 };
var prev = new Dictionary<(int Q, int R), (int Q, int R)>();
var frontier = new SortedSet<(int Cost, int Q, int R)> { (0, u.Q, u.R) };
var role = c.UnitTypes.FirstOrDefault(t => t.Id == u.Type)?.Class ?? "";
while (frontier.Count > 0)
{
var (cost, q, r) = frontier.Min;
frontier.Remove(frontier.Min);
foreach (var (dq, dr) in Neighbours)
{
var next = (q + dq, r + dr);
if (!(c.HexAt(next.Item1, next.Item2) is MapHex hex) || !hex.Land || blocked.Contains(next)) continue;
var step = Gdd03Military.Applies(c) && role != "" ? Gdd03Military.Terrain(c, hex.Biome, role) : costs[hex.Biome];
foreach (var (hexes, kindCost) in built)
if (kindCost < step && hexes.Contains((q, r)) && hexes.Contains(next)) step = kindCost;
var total = Gdd03Military.Applies(c) ? (long)cost + step : cost + step;
if (fresh && cost == 0 && total > budget) total = budget; // R-MOVE-001: with full points a unit can always move one hex (OQ-3)
if (total > budget || (dist.TryGetValue(next, out var known) && known <= total)) continue;
if (dist.ContainsKey(next)) frontier.Remove((known, next.Item1, next.Item2));
dist[next] = (int)total;
prev[next] = (q, r);
frontier.Add(((int)total, next.Item1, next.Item2));
}
}
return (dist, prev);
}
}
}