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.Linq;
namespace Statecraft.Sim
{
/// <summary>The GDD v0.1 pioneer work (docs/GDD.md "Pioneer work"; Phase 1 PR 5): a halutz unit builds a yishuv at a
/// designated site (sites.yaml) over several turns (D-A3), one project per unit (D-D6). Runs only when eras.yaml
/// systems.loop is gdd. The answers to #378's open questions are the plan's recommendations, which the owner took on
/// 14 October 2026: the unit works from where it stands (9), stays a halutz unit when the yishuv is founded (10), the
/// founding changes no city (11), the cost is paid in full at the start (12), a short Treasury borrows (13, the owner's decision of 15 October 2026), stopping loses
/// the progress (14), and one unit builds a site (15). Its causes go to the "map" group of the Why screen ("Building").</summary>
public static class Projects
{
public const string PioneerKind = "pioneer_work";
public const string StopKind = "stop_work";
/// <summary>The command kinds of the city projects (R-PROJ-001, R-PROJ-002).</summary>
public const string StartProjectKind = "start_project";
public const string CancelProjectKind = "cancel_project";
/// <summary>The one pioneer action Phase 1 has (GDD "Pioneer work": "Build yishuv").</summary>
public const string BuildYishuv = "build_yishuv";
/// <summary>The pioneer action that builds a military camp or a Hakhshara, as the site's kind says (GDD "Pioneer work":
/// "Build training camp"; Q-CAMP-3; Phase 4 PR 3).</summary>
public const string BuildCamp = "build_camp";
/// <summary>The kind of site a yishuv may be built at (sites.yaml kinds).</summary>
public const string YishuvKind = "yishuv";
/// <summary>The unit type a halutz unit becomes after veteran_halutz_service turns of work (R-VET-001; impact plan §1.3's id, D-E3).</summary>
public const string VeteranType = "veteran_halutz";
/// <summary>Whether a unit of <paramref name="type"/> does pioneer work: a halutz, or a veteran one (R-SITE-001, R-VET-001).</summary>
public static bool IsPioneer(string type) => type == "halutz" || type == VeteranType;
/// <summary>The pioneer action that plows a field (GDD "Pioneer work": "Prepare agricultural land"; Phase 4 PR 4).</summary>
public const string PlowFields = "plow_fields";
/// <summary>The kind of site a field may be plowed at (sites.yaml kinds). Built, a field site is plowed (R-FIELD-001).</summary>
public const string FieldKind = "field";
/// <summary>The pioneer action that drains a swamp (GDD "Pioneer work": "Dry swamp"; Phase 4 PR 5).</summary>
public const string DrySwamp = "dry_swamp";
/// <summary>The kind of site a swamp may be drained at (sites.yaml kinds). Drained, its hex's field site is ready (R-SWAMP-001).</summary>
public const string SwampKind = "swamp";
/// <summary>Whether a yishuv may be built at <paramref name="site"/>: its kinds name one (R-SITE-001, R-SITE-004). A hex may
/// hold more than one site, as a yishuv hex holds a field one; the panel finds the yishuv by this, not by file order.</summary>
public static bool IsYishuvSite(Site site) => site.Kinds.Contains(YishuvKind);
/// <summary>The turns of progress <paramref name="unit"/>'s project gains in one turn: veteran_progress for a veteran,
/// else 1 (R-SITE-003, R-VET-002).</summary>
public static int Progress(MvpRules r, Unit unit) => unit.Type == VeteranType ? r.VeteranProgress!.Value : 1;
/// <summary>The GDD minister system a site's pioneer work belongs to (R-MIN-001; Q-MIN-1): plowing a field and
/// building a new yishuv are Agriculture's; camps and swamp draining are no mapped system's ("" = neutral;
/// military training joins with #742).</summary>
public static string SystemOf(Site place) =>
place.Kinds.Contains(FieldKind) ? EffectsSystem.FieldWorkSystem
: place.Kinds.Contains(YishuvKind) ? EffectsSystem.YishuvWorkSystem
: "";
/// <summary>The GDD minister system a city project's kind belongs to (R-MIN-001; Q-MIN-1): housing, a transit
/// camp included (Q-HOUSE-3's low-condition housing type) and a gdd-0.3 housing repair (R-HOUSE-006; maintainer call
/// (not an owner ruling): a repair counts as a Housing build, so housing construction's multiplier applies and with a
/// weak minister it can take more than one turn), and industry construction are Labour's; a kind the map does not
/// name is "" (neutral).</summary>
public static string SystemOfKind(string kind) =>
kind == "industry" ? EffectsSystem.IndustryConstructionSystem
// HousingRepair here is a maintainer call, not an owner ruling (R-HOUSE-006): see the summary above.
: kind == "housing" || kind == "transit_camp" || kind == HousingRepair ? EffectsSystem.HousingConstructionSystem
: "";
/// <summary>The turns, this one included, in which the unit completes the site's remaining whole work and
/// fractional carry at its current minister multiplier. Reads the current date's rules, accounts for a halutz
/// promoted during the work, and changes no state. Initial work passes its base duration and zero carry.</summary>
public static int TurnsToBuild(Content c, GameState s, int unit, Site site, int left, double carry)
{
if (site == null) throw new ArgumentNullException(nameof(site));
return TurnsToBuild(c, s, unit, SystemOf(site), left, carry);
}
/// <summary><see cref="TurnsToBuild(Content, GameState, int, Site, int, double)"/> for work scaled by
/// <paramref name="system"/>'s minister multiplier: a site's (SystemOf), or a corridor segment's
/// (Corridors.TurnsToBuild, #792).</summary>
public static int TurnsToBuild(Content c, GameState s, int unit, string system, int left, double carry)
{
if (left < 1) throw new ArgumentOutOfRangeException(nameof(left));
if (!(carry >= 0 && carry < 1)) throw new ArgumentOutOfRangeException(nameof(carry));
var r = c.RulesAt(s.Date).Mvp!;
var m = EffectsSystem.GddSystemMultiplier(c, s, r, system);
if (!(m > 0) || double.IsInfinity(m)) throw new InvalidOperationException("Site progress multiplier must be finite and positive");
var u = s.Units[unit];
for (int turns = 1; ; turns = checked(turns + 1))
{
carry += Progress(r, u) * m;
if (carry >= left) return turns; // before the int cast: completion can exceed the remaining work
var whole = (int)Math.Floor(carry);
left -= whole; carry -= whole;
if (u.Type == "halutz")
{
var service = u.Service + 1;
u = new Unit(u.Id, service >= r.VeteranHalutzService!.Value ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
}
}
}
/// <summary><see cref="TurnsToBuild"/> for a city project (#1150): the turns, this one included, in which a project of
/// <paramref name="kind"/> completes its remaining whole turns and fractional carry at the kind's current minister
/// multiplier, as <see cref="AdvanceCity"/> counts them. Reads the current date's rules and changes no state. A new
/// order passes the kind's turns and zero carry.</summary>
public static int CityTurnsToBuild(Content c, GameState s, string kind, int left, double carry)
{
if (left < 1) throw new ArgumentOutOfRangeException(nameof(left));
if (!(carry >= 0 && carry < 1)) throw new ArgumentOutOfRangeException(nameof(carry));
var r = c.RulesAt(s.Date).Mvp!;
var m = EffectsSystem.GddSystemMultiplier(c, s, r, SystemOfKind(kind));
if (!(m > 0) || double.IsInfinity(m)) throw new InvalidOperationException("City project progress multiplier must be finite and positive");
for (int turns = 1; ; turns = checked(turns + 1))
{
carry += m;
if (carry >= left) return turns;
var whole = (int)Math.Floor(carry);
left -= whole; carry -= whole;
}
}
/// <summary>Whether a site or a corridor segment being built names <paramref name="unit"/>: the unit has a project
/// (D-D6).</summary>
public static bool IsBusy(GameState s, int unit) => s.Sites.Values.Any(w => w.BuiltOn == null && w.Unit == unit) || Corridors.WorkOf(s, unit) != null;
/// <summary><see cref="Start"/>'s and <see cref="Stop"/>'s refusals that name nothing (#2707), and CancelCity's; the unit one is
/// Orders.RefusedNoUnit. The UI maps each to its own string (SimBridge.ReasonText); the English is what a Rejected list and a
/// save carry, so it does not change.</summary>
public const string RefusedNotHalutz = "Only halutzim do pioneer work", RefusedNoWork = "There is no such pioneer work",
RefusedNoSite = "There is no such site", RefusedNotBuilding = "That group of halutzim is not building anything",
RefusedNoCityProject = "There is no such city project";
/// <summary>R-SITE-001: an idle halutz unit starts <paramref name="action"/> (build_yishuv) at a yishuv site that has no
/// record. The Treasury pays build_yishuv_cost now and borrows what it lacks; the site gets build_yishuv_turns to go; the unit
/// does not move. Refused, state untouched, for an unknown unit, a unit that is not a halutz or is busy, an unknown
/// action or site, a site that is not for a yishuv, or is being built or is built. Step
/// has already refused it in the legacy loop. R-CAMP-001: build_camp at a military_camp or hakhshara site follows the same
/// rules, with build_camp_turns and build_camp_cost. R-FIELD-001: plow_fields at a field site follows the same rules, with
/// plow_fields_turns and plow_fields_cost, and is refused while a yishuv site in the field's hex is not built. R-SWAMP-001:
/// dry_swamp at a swamp site follows the same rules, with dry_swamp_turns and dry_swamp_cost; a field site in the swamp's
/// hex is refused until the swamp is drained.</summary>
public static string? Start(Content c, GameState s, int unit, string action, string site, List<Cause> why)
{
if (!s.Units.TryGetValue(unit, out var u)) return "There is no such unit";
if (!IsPioneer(u.Type)) return RefusedNotHalutz;
var busy = s.Sites.Values.FirstOrDefault(w => w.BuiltOn == null && w.Unit == unit);
if (busy != null) return $"That group of halutzim is already building {PlayerText.Site(c, busy.Site)}";
if (Corridors.WorkOf(s, unit) is var (cw, ci))
return $"That group of halutzim is already building {Corridors.SegmentName(c.Corridors.First(x => x.Id == cw.Id), ci)}";
// Phase 4 PR 2 (#786): build_road and build_rail take a corridor segment, "corridor:N" (R-COR-001).
if (Corridors.IsAction(action)) return Corridors.Start(c, s, unit, action, site, why);
if (action != BuildYishuv && action != BuildCamp && action != PlowFields && action != DrySwamp) return RefusedNoWork;
var place = c.Sites.FirstOrDefault(x => x.Id == site);
if (place == null) return RefusedNoSite;
var camp = action == BuildCamp;
var plow = action == PlowFields;
var drain = action == DrySwamp;
if (camp ? !IsCamp(place) : plow ? !place.Kinds.Contains(FieldKind) : drain ? !place.Kinds.Contains(SwampKind) : !IsYishuvSite(place))
return camp ? $"{place.Name} is not a site for a training camp"
: plow ? $"{place.Name} is not a site for fields" : drain ? $"{place.Name} is not a swamp" : $"{place.Name} is not a site for a new yishuv";
if (s.Sites.TryGetValue(site, out var work))
return work.BuiltOn == null ? $"{place.Name} is already being built" : $"{place.Name} is already built";
if (plow && YishuvToBuildFirst(c, s, place) is Site first)
return $"{place.Name} can be plowed once {first.Name} is {(first.Kinds.Contains(SwampKind) ? "drained" : "built")}";
var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loop
// Owner decision "Allow borrowing" (2026-10-15, #378 question 13): a short Treasury borrows, as map actions do.
var (cost, turns) = Terms(r, action);
EconomySystem.PayOrBorrow(c, s, cost, camp ? "to build a training camp" : plow ? "to plow fields" : drain ? "to drain a swamp" : "to build a yishuv", why,
camp ? CauseKeys.Purpose.TrainingCamp : plow ? CauseKeys.Purpose.Plow : drain ? CauseKeys.Purpose.Drain : CauseKeys.Purpose.Yishuv);
// The same reading of D-A6 as training's: the turn of the order is the first build turn, so with
// build_yishuv_turns 6 an order on turn T is built at the end of T+5
// (ProjectsTests.AnOrderOnTurnTWithSixTurnsIsBuiltAtTheEndOfTurnTPlusFive).
s.Sites[site] = new SiteWork(site, unit, turns, null);
why.Add(plow || drain
? new Cause("map", site, 1, $"{place.Name}: a group of halutzim began {(plow ? "plowing" : "draining the swamp")}, cost {PlayerText.Money(c, "treasury", cost)}", key: CauseKeys.LandWorkStarted, args: new[] { plow ? "plow" : "drain", CauseKeys.Number(cost) })
: new Cause("map", site, 1, $"{place.Name}: a group of halutzim began building {(camp ? "a training camp" : "a yishuv")}, cost {PlayerText.Money(c, "treasury", cost)}", key: CauseKeys.SiteStarted, args: new[] { camp ? "camp" : "yishuv", CauseKeys.Number(cost) }));
return null;
}
/// <summary>What pioneer <paramref name="action"/> costs the Treasury and how many turns of progress it takes, under
/// rules <paramref name="r"/>: what <see cref="Start"/> charges and gives the site, and what the info panel shows (#1124).
/// The loader requires every value in the GDD loop.</summary>
public static (double Cost, int Turns) Terms(MvpRules r, string action) => action switch
{
BuildCamp => (r.BuildCampCost!.Value, r.BuildCampTurns!.Value),
PlowFields => (r.PlowFieldsCost!.Value, r.PlowFieldsTurns),
DrySwamp => (r.DrySwampCost!.Value, r.DrySwampTurns!.Value),
// A corridor segment's kind (R-COR-001, R-COR-002): what Corridors.Start charges and Corridors.Advance takes (#792).
Corridors.BuildRoad => (r.RoadSegmentCost, r.RoadSegmentTurns),
Corridors.BuildRail => (r.RailSegmentCost, r.RailSegmentTurns),
_ => (r.BuildYishuvCost, r.BuildYishuvTurns),
};
/// <summary>Whether a training camp may be built at <paramref name="site"/>: its kinds include military_camp or hakhshara
/// (R-CAMP-001). Built, its city gains those facilities (Training.HasFacility).</summary>
public static bool IsCamp(Site site) => site.Kinds.Contains("military_camp") || site.Kinds.Contains("hakhshara");
/// <summary>R-FIELD-001 (Q-FIELD-1): the yishuv site in <paramref name="field"/>'s hex while it is not built yet, so the
/// field cannot be plowed; null when the field is ready (its yishuv is built, or it has none in its hex). R-SWAMP-001
/// (Q-SWAMP-1): a swamp site in the hex counts the same way, so its field is ready only once it is drained.</summary>
public static Site? YishuvToBuildFirst(Content c, GameState s, Site field) =>
c.Sites.FirstOrDefault(y => (y.Kinds.Contains(YishuvKind) || y.Kinds.Contains(SwampKind)) && y.Q == field.Q && y.R == field.R
&& !(s.Sites.TryGetValue(y.Id, out var w) && w.BuiltOn != null));
/// <summary>R-SITE-002 (D-A3): the unit's site loses its record, so it is available again and the unit is idle. The
/// progress and the Money spent are lost. Refused, state untouched, for an unknown unit or one with no work. Step has
/// already refused it in the legacy loop.</summary>
public static string? Stop(Content c, GameState s, int unit, List<Cause> why)
{
if (!s.Units.ContainsKey(unit)) return "There is no such unit";
var work = s.Sites.Values.FirstOrDefault(w => w.BuiltOn == null && w.Unit == unit);
if (work == null) return Corridors.Stop(c, s, unit, why) ? null : RefusedNotBuilding;
s.Sites.Remove(work.Site);
why.Add(new Cause("map", work.Site, -1, $"{PlayerText.Site(c, work.Site)}: the halutzim stopped building; the Money spent is not returned", key: CauseKeys.SiteCancelled));
return null;
}
/// <summary>R-SITE-003, step 5 of the turn (spec 2026-10-12 section 2.3, D-A6): in ordinal site id order, each site being
/// built has one turn less to go, or veteran_progress less with a veteran (R-VET-002). One that reaches 0 is built on
/// <paramref name="next"/>, the turn's end date, and its unit is idle again. No city is founded (Phase 1). Then the
/// unit, a halutz, gains a turn of service, and at veteran_halutz_service becomes a veteran_halutz (R-VET-001). A built
/// camp site gives its city the facility from the next turn (R-CAMP-001, Training.HasFacility). A built field site is
/// plowed (R-FIELD-001), and yields from this turn's step 6 on (R-FIELD-002). A built swamp site is drained, and its
/// hex's field site is ready (R-SWAMP-001).</summary>
public static void Advance(Content c, GameState s, DateTime next, List<Cause> why)
{
var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loop, the only loop TurnResolver runs this in
foreach (var w in s.Sites.Values.Where(x => x.BuiltOn == null).ToList())
{
var u = s.Units[w.Unit!.Value]; // a site being built always names its unit (SiteWork)
var place = c.Sites.First(x => x.Id == w.Site); // a site being built is always in sites.yaml (Start)
// R-MIN-001, R-MIN-002 (D-H3; Q-MIN-1, Q-MIN-2): the office of the site's system scales the turns of
// progress the work gains this turn. The gain accumulates in Progress and only whole turns leave it
// (floor with carry): no fraction of a turn is ever a turn to go.
var acc = w.Progress + Progress(r, u) * EffectsSystem.GddSystemMultiplier(c, s, r, SystemOf(place));
var whole = (int)Math.Floor(acc);
acc -= whole;
if (w.TurnsLeft > whole) s.Sites[w.Site] = w.WithProgress(w.TurnsLeft - whole, acc);
else
{
s.Sites[w.Site] = SiteWork.Built(w.Site, next);
why.Add(new Cause("map", w.Site, 1, $"{place.Name} {(IsCamp(place) ? "built" : place.Kinds.Contains(FieldKind) ? "plowed" : place.Kinds.Contains(SwampKind) ? "drained" : "founded")}", key: CauseKeys.SiteCompleted, args: new[] { IsCamp(place) ? "built" : place.Kinds.Contains(FieldKind) ? "plowed" : place.Kinds.Contains(SwampKind) ? "drained" : "founded" }));
}
// R-VET-001: the project progressed this turn, so a halutz serves a turn; a veteran counts no further.
if (u.Type != "halutz") continue;
var service = u.Service + 1;
var promoted = service >= r.VeteranHalutzService!.Value;
s.Units[u.Id] = new Unit(u.Id, promoted ? VeteranType : u.Type, u.Q, u.R, service, u.Side, u.Strength, u.Order, u.OrderTarget, u.HomeCity, u.Full, u.CombatXp, u.Records);
if (promoted) why.Add(new Cause("map", w.Site, 1, "A group of halutzim became veteran pioneers", key: CauseKeys.PioneersVeteran));
}
Corridors.Advance(c, s, next, why); // R-COR-002: after the sites (Phase 4 PR 2)
}
/// <summary>R-CITY-011 (#1700): the AssignWorkers role that puts builders on a city's projects being built (gdd-0.3 only).</summary>
public const string BuildRole = "build";
/// <summary>R-PROJ-003 with R-CITY-011: why a city project gained no progress this turn (CauseKeys.ProjectWaiting's
/// second argument): it has no builder, or no person of its city without a job was left for its builder.</summary>
public const string NoBuilder = "no_builder", NoWorker = "no_worker";
/// <summary>R-CITY-011: the build order's refusal past the city's projects being built, formats with the settlement's
/// name ({0}) and a count ({1}, invariant).</summary>
public const string RefusedBeingBuiltOne = "{0} has 1 city project being built", RefusedBeingBuilt = "{0} has {1} city projects being built";
/// <summary>R-CITY-011: the city's builders, each one of its people who hold no job. 0 outside gdd-0.3, where no project
/// has one.</summary>
public static int Builders(GameState s, string city) => s.CityProjects.Values.Count(p => p.Builder && p.City == city);
/// <summary>R-CITY-011: the builders this turn's queued gdd-0.3 StartProject orders for <paramref name="city"/> may take,
/// one each at most (#1700 review: the panel limits count them, so a count up to a limit is accepted whichever order
/// runs first). 0 under every other ruleset.</summary>
internal static int Starting(GameState s, string city, IEnumerable<Command> pending) =>
s.Ruleset == SaveGame.Gdd03Ruleset ? pending.OfType<StartProject>().Count(p => p.City == city) : 0;
/// <summary>R-CITY-011: the city's free people: its civilians and craftsmen who hold no job and are not a staffed arms
/// workshop's worker (R-ARMS-005) or a builder.</summary>
static int Free(GameState s, City x) => x.Civilians + x.Craftsmen - x.Employed - Workshops.Staffed(s, x.Id) - Builders(s, x.Id);
static string Refused(string format, params object[] values) => string.Format(System.Globalization.CultureInfo.InvariantCulture, format, values);
/// <summary>R-PROJ-001 under gdd-0.3 only (#1700 slice B; owner, 3 November 2026: "One per city, plus 2 nationally"):
/// the city projects one city may start in a turn. A design value from that ruling, not construction.starts_per_turn
/// (content/gdd03-balance.yaml), whose 1 is Amir's nationwide catalogue reading; map_actions_per_turn stays the
/// national limit.</summary>
public const int Gdd03CityStartsPerTurn = 1;
/// <summary>R-PROJ-001 under gdd-0.3: the city_cap refusal, formatted with the settlement's name ({0}). The English is
/// what a turn's Rejected list and a save carry; the UI words it in its language (SimBridge.ReasonText).</summary>
public const string RefusedCityCap = "{0} has started a city project this turn";
/// <summary>R-HOUSE-006 (#1700, #1703), gdd-0.3 only (the loader keeps the row out of every other ruleset): the
/// projects.yaml id of the housing repair, a city project done on its city's own hex with no hex of its own (owner,
/// 3 November 2026: "No hex needed (Recommended)").</summary>
public const string HousingRepair = "housing_repair";
/// <summary>R-HOUSE-006: a housing repair's refusal on a hex other than its city's own, formatted with the settlement's
/// name ({0}).</summary>
public const string RefusedRepairCityHex = "A housing repair is done on {0}'s own hex";
/// <summary>The city project at hex (q, r), being built or built, or null (Q-PROJ-2: one project or placement a hex). A
/// housing repair has no hex of its own (R-HOUSE-006), so it is never the project at a hex.</summary>
public static CityProject? CityProjectAt(GameState s, int q, int r) => s.CityProjects.Values.FirstOrDefault(p => p.Q == q && p.R == r && p.Kind != HousingRepair);
/// <summary>R-PROJ-001: null when city project <paramref name="kind"/> may be started for <paramref name="city"/> on hex
/// (q, r) now, else the reason. Refused for an unknown kind or city; a kind whose resource the city lacks (R-PROJ-005); a
/// transit camp without the ma'abarot policy (Q-HOUSE-3, D-D3: the policy carries its sourced date); a hex that is not
/// land, is further than map_action_max_distance from the city's settlement hex, or holds a placement or another city
/// project (Q-PROJ-2), except that a gdd-0.3 housing repair must be on the city's own hex and may be ordered whatever it
/// holds (R-HOUSE-006); under gdd-0.3, once the city started <see cref="Gdd03CityStartsPerTurn"/> this turn; and once
/// map_actions_per_turn city projects were started this turn (Q-PROJ-4). A short Treasury is not a reason: it borrows
/// (Q-MONEY-3). The reference player asks this before it orders.</summary>
public static string? CheckCity(Content c, GameState s, string kind, string city, int q, int r) => CheckCityReason(c, s, kind, city, q, r)?.Text;
/// <summary><see cref="CheckCity"/>'s one validator (#1122, owner ruling 2): null when the project may be started, else a
/// stable kind and invariant values for a UI to word in its language (the map actions' pattern), plus the English text.
/// The kinds, in check order: unknown_kind, unknown_city, locked (kind), maabarot_policy, no_resource (city, resource, kind), not_land,
/// depopulated, too_far (distance, city), repair_city_hex (city; a housing repair off its city's own hex), occupied (the placement's
/// action), occupied_project (the project's kind), city_cap (city;
/// gdd-0.3 only), turn_cap (cap).</summary>
public static MapActionReason? CheckCityReason(Content c, GameState s, string kind, string city, int q, int r)
{
var k = c.ProjectKinds.FirstOrDefault(x => x.Id == kind);
if (k == null) return new MapActionReason("unknown_kind", "There is no such city project");
if (!s.Cities.ContainsKey(city)) return new MapActionReason("unknown_city", "There is no such city");
if (k.Locked && !s.UnlockedProjects.Contains(kind)) // R-EFX-008
return new MapActionReason("locked", $"{PlayerText.Capitalised(k.Name)} is not available yet", kind);
if (kind == MapActions.TransitCamp && !(s.Policies.TryGetValue(MapActions.MaabarotPolicy, out var m) && m >= 0.5))
return new MapActionReason("maabarot_policy", "Transit camps need the ma'abarot policy");
// R-PROJ-005. A city founded in play is not in cities.yaml, so it has no resources.
if (!string.IsNullOrEmpty(k.Requires) && c.Cities.FirstOrDefault(x => x.Id == city)?.Resources.Any(x => x.Id == k.Requires) != true)
return new MapActionReason("no_resource", $"{PlayerText.Settlement(c, city)} has no {k.Requires} for {k.Name}", city, k.Requires, kind);
var hex = c.HexAt(q, r);
if (hex == null || !hex.Land) return new MapActionReason("not_land", "This hex is not land");
if (SettlementControl.DepopulatedAt(c, s, q, r)) return new MapActionReason("depopulated", "Nothing can be built on a depopulated place"); // R-CTRL-020
var rules = c.RulesAt(s.Date); // the era the turn starts in
var max = rules.MapActionMaxDistance;
var name = PlayerText.Settlement(c, city);
if (!InReach(c, s, city, q, r))
return new MapActionReason("too_far", FormattableString.Invariant($"This hex is more than {max} {(max == 1 ? "hex" : "hexes")} from {name}"),
max.ToString(System.Globalization.CultureInfo.InvariantCulture), city);
// R-HOUSE-006 (owner, 3 November 2026: "No hex needed (Recommended)"): a repair is done on the city itself, so it
// goes on the city's own hex whatever that hex holds, and takes none (Q-PROJ-2 is for the other kinds).
if (kind == HousingRepair)
{
if (Distance(c, city, q, r) != 0)
return new MapActionReason("repair_city_hex", string.Format(System.Globalization.CultureInfo.InvariantCulture, RefusedRepairCityHex, name), city);
}
else if (MapActions.At(s, q, r) is Placement placed)
return new MapActionReason("occupied", $"This hex already has {PlayerText.MapAction(c, placed.Action)}", placed.Action);
else if (CityProjectAt(s, q, r) is CityProject other)
return new MapActionReason("occupied_project", $"This hex already has {c.ProjectKinds.First(x => x.Id == other.Kind).Name}", other.Kind);
// R-PROJ-001 under gdd-0.3 (owner, 3 November 2026: "One per city, plus 2 nationally"): the city's own limit,
// before the national one, so a player over both sees the city's reason.
if (c.Ruleset == SaveGame.Gdd03Ruleset && s.MapActionsTurnDate == s.Date
&& s.CityStartsThisTurn.TryGetValue(city, out var started) && started >= Gdd03CityStartsPerTurn)
return new MapActionReason("city_cap", string.Format(System.Globalization.CultureInfo.InvariantCulture, RefusedCityCap, name), city);
// Last, as for map actions, so a player over the cap still sees the specific reason an order is illegal. The count
// is the map actions' own (one national limit, Q-PROJ-4).
if ((s.MapActionsTurnDate == s.Date ? s.MapActionsThisTurn : 0) >= rules.MapActionsPerTurn)
return new MapActionReason("turn_cap", FormattableString.Invariant($"No more than {rules.MapActionsPerTurn} city projects in one turn"),
rules.MapActionsPerTurn.ToString(System.Globalization.CultureInfo.InvariantCulture));
return null;
}
/// <summary>Whether hex (q, r) is within map_action_max_distance of <paramref name="city"/>'s settlement hex (Q-PROJ-2): the
/// one range check, of <see cref="CheckCityReason"/> and <see cref="CitiesFor"/>.</summary>
static bool InReach(Content c, GameState s, string city, int q, int r) =>
Distance(c, city, q, r) <= c.RulesAt(s.Date).MapActionMaxDistance; // the era the turn starts in
static int Distance(Content c, string city, int q, int r)
{
var home = c.SettlementHexes.First(h => h.Id == city); // every city has one (ValidateGdd)
return MapActions.Distance(q, r, home.Q, home.R);
}
/// <summary>The cities that may own a city project on hex (q, r) (#1122, owner ruling 1): those whose settlement hex is in
/// reach (<see cref="InReach"/>), nearest first, then in ordinal id order. Being listed promises no kind: each still goes
/// through <see cref="CheckCityReason"/>.</summary>
public static IReadOnlyList<string> CitiesFor(Content c, GameState s, int q, int r) =>
s.Cities.Keys.Where(id => InReach(c, s, id, q, r))
.OrderBy(id => Distance(c, id, q, r)).ThenBy(id => id, StringComparer.Ordinal).ToList();
/// <summary>R-PROJ-001: starts city project <paramref name="kind"/> for <paramref name="city"/> on hex (q, r), or returns
/// the reason (<see cref="CheckCity"/>; state untouched). The Treasury pays the kind's cost now and borrows what it lacks
/// (Q-PROJ-1, Q-MONEY-3); the project takes the next id and the kind's turns, the turn of the order the first (D-A3). It
/// needs no workers (Q-PROJ-3); under gdd-0.3 it takes one of the city's free people as its builder when it has one, as
/// the order runs (R-CITY-011, owner, 3 November 2026: "Yes, if someone is free"), and never anyone in a job. Step has
/// already refused it in the legacy loop.</summary>
public static string? StartCity(Content c, GameState s, string kind, string city, int q, int r, List<Cause> why)
{
var reason = CheckCity(c, s, kind, city, q, r);
if (reason != null) return reason;
var k = c.ProjectKinds.First(x => x.Id == kind);
if (s.MapActionsTurnDate != s.Date) { s.MapActionsTurnDate = s.Date; s.MapActionsThisTurn = 0; s.CityStartsThisTurn.Clear(); }
s.MapActionsThisTurn++;
if (c.Ruleset == SaveGame.Gdd03Ruleset) // R-PROJ-001: the city's start, gdd-0.3 only, so no other ruleset's hash moves
s.CityStartsThisTurn[city] = s.CityStartsThisTurn.TryGetValue(city, out var n) ? n + 1 : 1;
var name = PlayerText.Settlement(c, city);
EconomySystem.PayOrBorrow(c, s, k.Cost, "to build " + k.Name, why, CauseKeys.Purpose.Project, k.Id);
var id = s.NextId++;
var builder = c.Ruleset == SaveGame.Gdd03Ruleset && Free(s, s.Cities[city]) >= 1;
s.CityProjects.Add(id, new CityProject(id, kind, city, q, r, k.Turns, builder: builder));
why.Add(new Cause("city", city, 1, $"{name}: {k.Name} began, cost {PlayerText.Money(c, "treasury", k.Cost)}", key: CauseKeys.ProjectStarted, args: new[] { kind, CauseKeys.Number(k.Cost) }));
if (builder) why.Add(new Cause("city", city, 1, $"{name}: a builder started on {k.Name}", key: CauseKeys.ProjectBuilder, args: new[] { kind }));
return null;
}
/// <summary>R-PROJ-002 (D-A3): city project <paramref name="project"/> leaves the state; the Money spent is not returned,
/// and with no workers (Q-PROJ-3) there are no people to return; under gdd-0.3 its builder, if any, is free again at once
/// (R-CITY-011). Refused, state untouched, for a project that does not
/// exist or is built. Step has already refused it in the legacy loop.</summary>
public static string? CancelCity(Content c, GameState s, int project, List<Cause> why)
{
if (!s.CityProjects.TryGetValue(project, out var p)) return RefusedNoCityProject;
var k = c.ProjectKinds.First(x => x.Id == p.Kind);
if (p.BuiltOn != null) return $"{PlayerText.Capitalised(k.Name)} is already built";
s.CityProjects.Remove(project);
why.Add(new Cause("city", p.City, -1, $"{PlayerText.Settlement(c, p.City)}: {k.Name} was cancelled; the Money spent is not returned", key: CauseKeys.ProjectCancelled, args: new[] { k.Id }));
if (p.Builder) BuilderFreed(c, p, k, why);
return null;
}
// #2530: a count of 1 names the singular, as the UI's helper does.
static string Groups(int n) => n == 1 ? "1 group" : FormattableString.Invariant($"{n} groups");
/// <summary>R-CITY-011 (#1700; owner, 3 November 2026: "Builders in the MVP (Recommended)", "One builder, today's times
/// (Recommended)"): AssignWorkers(city, "build", count), gdd-0.3 only, sets how many of the city's projects being built
/// have a builder. A rise puts builders on the projects that have none, in ascending id; a fall takes them off the
/// projects that have one, in descending id. A new builder is one of the city's free people; while its job default is
/// on (R-CITY-009) the order may take one from the default's jobs, as R-ARMS-005's workshop order does. Refused, state
/// untouched, for a negative count, more than the city's projects being built, or more new builders than its free
/// people. Cities.Assign has already refused an unknown city.</summary>
internal static string? AssignBuilders(Content c, GameState s, string city, int count, List<Cause> why)
{
if (count < 0) return Cities.RefusedNegativeWorkers;
var x = s.Cities[city];
var name = PlayerText.Settlement(c, city);
var building = s.CityProjects.Values.Where(p => p.City == city && p.BuiltOn == null).OrderBy(p => p.Id).ToList();
if (count > building.Count) return building.Count == 1 ? Refused(RefusedBeingBuiltOne, name) : Refused(RefusedBeingBuilt, name, building.Count);
var builders = Builders(s, city);
var staffed = Workshops.Staffed(s, city);
// R-CITY-009 with R-ARMS-005: while the job default is on, a new builder may come from the default's jobs (the
// default then fills one job fewer, R-CITY-001); a number the player set is not lowered.
var free = x.Civilians + x.Craftsmen - (x.JobsDefault ? 0 : x.Employed) - staffed - builders;
if (count - builders > free)
return Refused(x.JobsDefault ? Workshops.RefusedPeople : Workshops.RefusedPeopleNoJob, name, Math.Max(0, free));
var employed = Math.Min(x.Employed, x.Civilians + x.Craftsmen - staffed - count);
if (employed != x.Employed)
{
s.Cities[city] = x.WithCounts(x.Civilians, employed, x.Refugees);
why.Add(new Cause("city", city, employed - x.Employed, FormattableString.Invariant($"{name}: {Groups(employed)} in work"), key: CauseKeys.WorkersAssigned, args: new[] { CauseKeys.Number(employed) }));
}
if (count > builders)
foreach (var p in building.Where(p => !p.Builder).Take(count - builders))
{
s.CityProjects[p.Id] = p.WithBuilder(true);
var k = c.ProjectKinds.First(y => y.Id == p.Kind);
why.Add(new Cause("city", city, 1, $"{name}: a builder started on {k.Name}", key: CauseKeys.ProjectBuilder, args: new[] { k.Id }));
}
else
foreach (var p in building.Where(p => p.Builder).Reverse().Take(builders - count))
{
s.CityProjects[p.Id] = p.WithBuilder(false);
BuilderFreed(c, p, c.ProjectKinds.First(y => y.Id == p.Kind), why);
}
return null;
}
/// <summary>R-CITY-011 (#1700 slice B, slice A's NIT-1): the Why line for a builder freed from project
/// <paramref name="p"/> of kind <paramref name="k"/>, as it is built or cancelled or the build count falls.</summary>
static void BuilderFreed(Content c, CityProject p, ProjectKind k, List<Cause> why) =>
why.Add(new Cause("city", p.City, -1, $"{PlayerText.Settlement(c, p.City)}: a builder left {k.Name} and is free again", key: CauseKeys.ProjectBuilderFreed, args: new[] { k.Id }));
/// <summary>R-PROJ-003, step 5 of the turn (D-A6), after the pioneer work: in ascending id, each city project being built
/// has one turn less to go. One that reaches 0 is built on <paramref name="next"/>, the turn's end date, and adds its
/// kind's housing capacity, condition (kept from 0 to 1) and job slots to its city, once: a built project is never
/// advanced again, except a gdd-0.3 housing repair, whose record then leaves the state (R-HOUSE-006: it has no hex to
/// keep). R-CITY-010: a project in a city the enemy holds keeps its record as it is. R-CITY-011 (gdd-0.3 only):
/// a project gains the turn's progress only when it has a builder and its city still has that person without a job
/// (each project with a builder takes one, in ascending id); otherwise it waits with its record as it is, and the turn
/// report says why. Money is never an input to progress.</summary>
public static void AdvanceCity(Content c, GameState s, DateTime next, List<Cause> why)
{
var r = c.RulesAt(s.Date).Mvp!; // the loader requires it in the GDD loop, the only loop TurnResolver runs this in
var held = Cities.Held(c, s);
var builders = c.Ruleset == SaveGame.Gdd03Ruleset;
var working = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var p in s.CityProjects.Values.Where(x => x.BuiltOn == null && !held.Contains(x.City)).OrderBy(x => x.Id).ToList())
{
if (builders)
{
var x = s.Cities[p.City];
working.TryGetValue(p.City, out var taken);
var waits = !p.Builder ? NoBuilder : taken >= x.Civilians + x.Craftsmen - x.Employed ? NoWorker : null;
if (waits != null)
{
var kind = c.ProjectKinds.First(y => y.Id == p.Kind);
var because = waits == NoBuilder ? "no builder" : "no person without a job is left for its builder";
why.Add(new Cause("city", p.City, 0, $"{PlayerText.Settlement(c, p.City)}: {kind.Name} waits: {because}", key: CauseKeys.ProjectWaiting, args: new[] { kind.Id, waits }));
continue;
}
working[p.City] = taken + 1;
}
// R-MIN-001, R-MIN-002 (D-H3; Q-MIN-1, Q-MIN-2): the office of the kind's system scales the turn of
// progress the project gains this turn, with R-MIN-002's floor and carry as at the sites (Advance).
var acc = p.Progress + EffectsSystem.GddSystemMultiplier(c, s, r, SystemOfKind(p.Kind));
var whole = (int)Math.Floor(acc);
acc -= whole;
if (p.TurnsLeft > whole) { s.CityProjects[p.Id] = p.WithProgress(p.TurnsLeft - whole, acc); continue; }
if (p.Kind == HousingRepair) s.CityProjects.Remove(p.Id); // R-HOUSE-006: no hex, so nothing is left
else s.CityProjects[p.Id] = p.Built(next);
var k = c.ProjectKinds.First(x => x.Id == p.Kind);
var city = s.Cities[p.City];
var condition = city.Condition is double now ? Math.Min(1.0, Math.Max(0.0, now + k.Condition)) : (double?)null;
s.Cities[p.City] = new City(city.Id, city.HousingCapacity + k.Capacity, city.JobSlots + k.JobSlots, city.Civilians, city.Employed, city.Refugees, city.Recruits, condition, city.Craftsmen, city.JobsDefault, city.Qualified);
why.Add(new Cause("city", p.City, 1, $"{PlayerText.Settlement(c, p.City)}: {k.Name} was finished", key: CauseKeys.ProjectCompleted, args: new[] { k.Id }));
if (p.Builder) BuilderFreed(c, p, k, why);
}
}
}
}