Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

22.1 KB
Raw Blame
using System;
using System.Collections.Generic;
using System.Linq;

namespace Statecraft.Sim
{
    /// <summary>The public entry point the Unity layer calls: start a game, then step it one turn at a time.</summary>
    public static class Simulation
    {
        public static GameState NewGame(Content c, ulong seed, Mode mode) => NewGame(c, seed, mode, darkStart: false);

        /// <summary>#1689, #1725 PR 5: with <paramref name="darkStart"/>, the dark start of an exact gdd-0.3 Historical game,
        /// internal and fixture-only (the public NewGame passes false): the Historical ledger (R-POP-004) is initialized in
        /// place before Pools.Init, so the Food stock starts at cover_months of the ledger's need (R-FOOD-001, #2470), and
        /// the starting forces are placed against its soldiers. EventSystem.Trigger still refuses a ledger (R-POP-002) until
        /// its producer is integrated, so a dark start fires no opening event. Legacy and gdd-0.1 content refuse it.</summary>
        internal static GameState NewGame(Content c, ulong seed, Mode mode, bool darkStart)
        {
            if (c == null) throw new ArgumentNullException(nameof(c));
            if (mode == Mode.Open) throw new NotSupportedException("Open mode arrives with milestone M4.");
            if (darkStart && !c.UsesPopulationLedger) throw new InvalidOperationException("A dark start needs exact gdd-0.3 (R-POP-001).");
            var s = new GameState(c) { Date = c.Rules.Start, RngState = seed, Mode = mode };
            var why = new List<Cause>();
            EffectsSystem.Init(c, s);
            EconomySystem.Init(c, s);
            PopulationSystem.Init(c, s);
            Cities.Init(c, s);
            if (darkStart) HistoricalPopulation.Initialize(c, s);   // before Pools.Init, which reads the ledger's need
            if (darkStart) HistoricalPopulation.AddFarmerHousing(c, s);   // #1725 PR 4: one housing place per farmer in a census host
            Pools.Init(c, s);
            StartingForces.Init(c, s);   // R-UNIT-006: before any event can grant a unit, so the forces take ids 0 to n-1
            SecuritySystem.Init(c, s, why);
            if (c.UsesAttention) AttentionSystem.Refill(c, s);
            if (!darkStart) EventSystem.Trigger(c, s, why);   // R-POP-002: refuses an initialized ledger
            return s;
        }

        /// <summary>Applies commands in order (each pays attention first; a command that fails validation is refunded
        /// and carries a reason; a vote that is held and lost is charged and reported as a politics cause), delegates
        /// unanswered events, then advances one turn. Never mutates <paramref name="state"/>.</summary>
        public static StepResult Step(Content c, GameState state, IReadOnlyList<Command> commands)
        {
            if (c == null) throw new ArgumentNullException(nameof(c));
            if (state == null) throw new ArgumentNullException(nameof(state));
            if (commands == null) throw new ArgumentNullException(nameof(commands));
            if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));
            // R-POP-002 (#1725 PR 6, owner 8 November 2026, "Historical mode alone (Rec.)"): a dark start's Historical ledger
            // comes in, and an order whose system is not ledger-ready refuses on the clone; a synthetic or Open ledger does not.
            PopulationLedger.RefuseUnlessHistorical(state);
            CommandText.Validate(commands);

            var s = state.Clone();
            var why = new List<Cause>();
            var rejected = new List<Rejection>();
            if (s.GameOver != null)
            {
                foreach (var cmd in commands) rejected.Add(new Rejection(cmd, $"The game is over: {PlayerText.GameOver(s.GameOver)}"));
                return new StepResult(s, why, rejected);
            }

            var spent = new Dictionary<int, int>();
            var attacked = new Dictionary<int, AttackRecord>();
            var actions = new List<OperationAction>();
            RunOrders(c, s, commands, spent, attacked, why, rejected, actions);
            // A delegated card's unit orders share the turn's movement and attacks (R-ENEMY-005, R-ENEMY-008). On a ledger game
            // only a waiting card is handed over, and Delegate still refuses it (R-POP-002, "Only if none pending (Rec.)").
            if (!s.PopulationLedger.IsInitialized || s.PendingEvents.Count > 0)
                EventSystem.Delegate(c, s, why, spent, rejected, actions, attacked);

            var len = SecuritySystem.TurnLengthFor(c, s.Date, s.Rung);
            // The next era's start, or the game's end (the last era's end, or mvp.end in the GDD loop, R-LOOP-004), is a
            // boundary: the turn that reaches it ends on it, with that turn's real days (spec 4.1, 4.5).
            var end = c.End;
            var next = TurnEnd(c, s);
            if (c.IsGdd) SettlementControl.Stamp(s, next);   // R-CTRL-004: dates for captures made during the orders
            var adjusted = next != SimTime.Advance(s.Date, len);
            var days = (next - s.Date).Days;
            var yf = adjusted ? days / 365.0 : SimTime.YearFraction(len);
            TurnResolver.Resolve(c, s, next, yf, why);   // the GDD v0.1 loop only; the legacy loop goes straight on
            EffectsSystem.Apply(c, s, why);
            PopulationSystem.Apply(c, s, next, yf, why);
            EconomySystem.Apply(c, s, yf, why);
            PoliticsSystem.UpdateStability(c, s, yf, why);
            if (adjusted) SecuritySystem.Apply(c, s, days / 7, why);   // whole weeks of the adjusted turn
            else SecuritySystem.Apply(c, s, len, why);
            PoliticsSystem.ReportChanges(c, s.Date, next, why);
            var turnStart = s.Date;
            s.Date = next;
            s.Turn++;
            if (s.GameOver == null && s.Date >= end)
            {
                // #19's legacy report is EndReport.For, which the end screen reads once GameOver is set (D-H4)
                s.GameOver = end == c.Eras[c.Eras.Count - 1].To ? GameOverCodes.EraEnded : GameOverCodes.MvpEnded;
                why.Add(new Cause("era", s.GameOver, 0, PlayerText.GameOver(s.GameOver), key: CauseKeys.EraEnded));
            }
            ContentWindows.Update(c, s, turnStart);
            EventSystem.LapseExpiredOperations(c, s, why);
            Cabinet.ExpireOnGovernmentChange(c, s, why);
            if (c.UsesAttention) AttentionSystem.Refill(c, s);
            // A game that just ended raises no new events, but the unfired cards of recorded objectives (R-LOOP-004, R-OBJ-003;
            // the owner's choice "Show the card (Recommended)", 4 November 2026, #2536).
            EventSystem.Trigger(c, s, why, turnStart, endingTurn: s.GameOver != null);
            return new StepResult(s, why, rejected, actions);
        }

        /// <summary>The date the turn starting on <paramref name="s"/>'s date ends on: its turn length from the war state,
        /// cut at the next era's start or the game's end when it comes first (spec 4.1, 4.5). Step's own rule; the advisors'
        /// city warning (Threats) reads it too.</summary>
        public static DateTime TurnEnd(Content c, GameState s)
        {
            var len = SecuritySystem.TurnLengthFor(c, s.Date, s.Rung);
            var boundary = c.Eras.Select(e => e.From).Where(f => f > s.Date).Concat(new[] { c.End }).Min();
            return SimTime.AdvanceTo(s.Date, len, boundary);
        }

        /// <summary>Who End Turn would hand the event to (EventSystem.Delegate) if the turn ended with these orders: runs
        /// them on a clone, as <see cref="Step"/> does, then asks EventSystem.DelegatedTo. Never mutates <paramref name="state"/>.</summary>
        public static Person? DelegatedTo(Content c, GameState state, IReadOnlyList<Command> commands, string eventId)
        {
            if (c == null) throw new ArgumentNullException(nameof(c));
            if (state == null) throw new ArgumentNullException(nameof(state));
            if (commands == null) throw new ArgumentNullException(nameof(commands));
            if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));
            // R-POP-002: fixture ledger producers/consumers are not integrated with the aggregate loop.
            PopulationLedger.RefuseAggregate(state);
            CommandText.Validate(commands);
            var s = state.Clone();
            if (s.GameOver == null) RunOrders(c, s, commands, new Dictionary<int, int>(), new Dictionary<int, AttackRecord>(), new List<Cause>(), new List<Rejection>());
            return EventSystem.DelegatedTo(c, s, c.Events.First(e => e.Id == eventId));
        }

        /// <summary>The state after <paramref name="commands"/> run as End turn would run them first (spec 2026-10-23 section 3;
        /// RunOrders, shared with Step), on a clone. Never mutates <paramref name="state"/>.</summary>
        public static PreviewResult Preview(Content c, GameState state, IReadOnlyList<Command> commands)
        {
            if (c == null) throw new ArgumentNullException(nameof(c));
            if (state == null) throw new ArgumentNullException(nameof(state));
            if (commands == null) throw new ArgumentNullException(nameof(commands));
            if (commands.Any(x => x == null)) throw new ArgumentException("Commands cannot contain null.", nameof(commands));
            // R-POP-002: fixture ledger producers/consumers are not integrated with the aggregate loop.
            PopulationLedger.RefuseAggregate(state);
            CommandText.Validate(commands);
            var s = state.Clone();
            var why = new List<Cause>(); var rejected = new List<Rejection>(); var spent = new Dictionary<int, int>();
            var attacked = new Dictionary<int, AttackRecord>();
            var actions = new List<OperationAction>();
            if (s.GameOver != null)
                foreach (var cmd in commands) rejected.Add(new Rejection(cmd, $"The game is over: {PlayerText.GameOver(s.GameOver)}"));
            else RunOrders(c, s, commands, spent, attacked, why, rejected, actions);
            return new PreviewResult(s, spent, attacked, why, rejected, actions);
        }

        /// <summary>A move, a go-to, an attack, fortify or hold takes effect at once; Send home and every other order waits
        /// for End turn (spec 2026-10-23 section 3.2).</summary>
        public static bool IsInstant(Command cmd) => cmd is Move || (cmd is UnitOrder o && o.Order != Demobilization.SendHome);

        /// <summary>The turn's orders in queue order, conversions before Arms purchases (ConversionsBeforeArms): each pays
        /// Attention first; one that fails validation is refunded and rejected with its reason. Step, DelegatedTo and Preview
        /// share it, so every dry run sees what End Turn will.</summary>
        static void RunOrders(Content c, GameState s, IReadOnlyList<Command> commands, Dictionary<int, int> spent,
                              Dictionary<int, AttackRecord> attacked, List<Cause> why, List<Rejection> rejected,
                              List<OperationAction>? actions = null)
        {
            if (c.IsGdd) Movement.ContinueRoutes(c, s, spent, why, rejected);   // R-MOVE-009: the route step, before the turn's orders
            if (c.IsGdd) SettlementControl.CaptureHeld(c, s, why);
            var priceRung = s.Rung;   // every command this turn is priced at the rung the turn started at (R-MONEY-004's war is that rung too)
            var dollarsAtStart = s.DollarsConverted;   // R-MONEY-004: the turn's limit counts every conversion order in it
            foreach (var cmd in ConversionsBeforeArms(commands))
            {
                if (!AttentionSystem.IsCommandKind(cmd.Kind)) { rejected.Add(new Rejection(cmd, "That order is not known")); continue; }
                // A GDD order has no price in the legacy rules: refuse it before charging (R-CITY-001).
                if (AttentionSystem.IsGddKind(cmd.Kind) && !c.IsGdd) { rejected.Add(new Rejection(cmd, "That order is not available in this game")); continue; }
                // The call-up and the security order are retired in the GDD loop (R-WAR-002): refused the same way,
                // before charging, so the state and the Attention are unchanged.
                if (c.IsGdd && (cmd is SetMobilization || cmd is SecurityOrder)) { rejected.Add(new Rejection(cmd, "That order is not available in this game")); continue; }
                string? error;
                if (c.UsesAttention)
                {
                    var before = s.Attention;
                    error = AttentionSystem.TrySpend(c, s, cmd.Kind, priceRung) ?? Execute(c, s, cmd, spent, attacked, why, priceRung, dollarsAtStart, rejected, actions);
                    if (error != null) s.Attention = before;
                }
                else error = Execute(c, s, cmd, spent, attacked, why, priceRung, dollarsAtStart, rejected, actions);
                if (error != null) rejected.Add(new Rejection(cmd, error));
                if (c.IsGdd) SettlementControl.CaptureHeld(c, s, why);   // R-CTRL-004: only where an order ends
            }
        }

        /// <summary>The turn's orders in the order they run (#2206; R-ARMS-002, R-MONEY-004; owner, 2 November 2026:
        /// "Conversion counts first (Recommended)"): queue order, except that the dollar conversions queued after the turn's
        /// first Arms purchase run just before it, in their queue order, so a conversion's Money counts for the purchase
        /// whatever the order of the clicks. Every other order keeps its place.</summary>
        static IEnumerable<Command> ConversionsBeforeArms(IReadOnlyList<Command> commands)
        {
            var buy = -1;
            for (int i = 0; i < commands.Count && buy < 0; i++) if (commands[i] is BuyArms) buy = i;
            if (buy < 0) return commands;
            var rest = commands.Skip(buy);
            return commands.Take(buy).Concat(rest.Where(x => x is ConvertDollars)).Concat(rest.Where(x => !(x is ConvertDollars)));
        }

        /// <summary>Returns null when the command was carried out (a lost vote counts: it consumes the RNG draw and is
        /// reported as a politics cause), or the reason it failed validation. A command that fails validation leaves
        /// the state as it found it (attention is refunded by the caller).</summary>
        static string? Execute(Content c, GameState s, Command cmd, Dictionary<int, int> spent,
                               Dictionary<int, AttackRecord> attacked, List<Cause> why, int startRung, int dollarsAtStart,
                               List<Rejection> rejected, List<OperationAction>? actions)
        {
            switch (cmd)
            {
                case SetPolicy p:
                    if (c.Policies.All(x => x.Id != p.Policy)) return "That policy does not exist in this game";
                    if (c.At(s.Date).Policies.All(x => x.Id != p.Policy)) return "That policy is not available at this time";
                    if (!(p.Level >= 0 && p.Level <= 1)) return "Policy level must be between 0 and 1";
                    var legislature = Offices.Legislature(c, s.Date);
                    if (legislature == null) return "No legislature is sitting";
                    if (!PassVote(c, s))
                    {
                        if (Advisory(c, s))
                            why.Add(new Cause("politics", p.Policy, 0, $"{legislature.Body} voted against {PlayerText.Target(c, p.Policy)} at {PlayerText.Percent(p.Level)}, but its vote does not bind", key: CauseKeys.AdvisoryPolicyRejected, args: new[] { legislature.Id, CauseKeys.Number(p.Level) }));
                        else
                        {
                            why.Add(new Cause("politics", p.Policy, 0, $"{legislature.Body} voted down {PlayerText.Target(c, p.Policy)} at {PlayerText.Percent(p.Level)}", key: CauseKeys.PolicyRejected, args: new[] { legislature.Id, CauseKeys.Number(p.Level) }));
                            return null;
                        }
                    }
                    s.Policies[p.Policy] = p.Level;
                    why.Add(new Cause("policy", p.Policy, p.Level, $"{PlayerText.Target(c, p.Policy)} set to {PlayerText.Percent(p.Level)}", key: CauseKeys.PolicySet));
                    return null;
                case AllocateBudget b:
                {
                    // Validate before voting, so a malformed allocation neither draws from the RNG nor blames the legislature.
                    var old = s.Budget;
                    var invalid = EconomySystem.Allocate(c, s, b.Shares);
                    if (invalid != null) return invalid;
                    if (PoliticsSystem.BudgetNeedsVote(c, s.Date) && !PassVote(c, s))
                    {
                        if (Advisory(c, s))
                            why.Add(new Cause("politics", "budget", 0, $"{Offices.Legislature(c, s.Date)!.Body} voted against the budget, but its vote does not bind", key: CauseKeys.AdvisoryBudgetRejected, args: new[] { Offices.Legislature(c, s.Date)!.Id }));
                        else
                        {
                            s.Budget = old;
                            why.Add(new Cause("politics", "budget", 0, $"{Offices.Legislature(c, s.Date)!.Body} voted the budget down", key: CauseKeys.BudgetRejected, args: new[] { Offices.Legislature(c, s.Date)!.Id }));
                        }
                    }
                    return null;
                }
                case ChooseEventOption e:
                    return EventSystem.Choose(c, s, e.EventId, e.OptionId, why, spent, rejected, actions, attacked);   // a refused unit order is rejected on its own (R-ENEMY-005)
                case SetMobilization m:
                    return SecuritySystem.SetMobilization(c, s, m.Level, why);
                case Appoint a:
                    return Cabinet.Appoint(c, s, a.Office, a.Person, why);
                case MapAction m:
                    return MapActions.Apply(c, s, m.Action, m.Q, m.R, why);
                case AssignWorkers w:
                    return Cities.Assign(c, s, w.City, w.Role, w.Count, why);
                case Train t:
                    return Training.Start(c, s, t.City, t.Track, t.Count, why);
                case CancelTraining t:
                    return Training.Cancel(c, s, t.Cohort, why);
                case ReturnCraftsmen r:
                    return Qualification.ReturnCraftsmen(c, s, r.City, r.Count, why);
                case ReassignCraftsmen r:
                    return Qualification.ReassignCraftsmen(c, s, r.City, r.Count, why);
                case ReassignPioneers r:
                    return Qualification.ReassignPioneers(c, s, r.City, r.Track, r.Count, why);
                case Reinforce r:
                    return Training.Reinforce(c, s, r.Unit, r.City, r.Count, why);
                case PioneerWork p:
                    return Projects.Start(c, s, p.Unit, p.Action, p.Site, why);
                case StopWork w:
                    return Projects.Stop(c, s, w.Unit, why);
                case UnitOrder o:
                {
                    // R-ENEMY-009 (owner, 4 November 2026; on #2544, "Only remaining orders (Recommended)"): an order that takes a
                    // unit off its operation's go-to cancels the operation's remaining orders. A refused order cancels nothing.
                    var operation = EventSystem.OperationOf(c, s, o.Unit);
                    var bound = operation == null ? null : EventSystem.OperationUnits(c, s, operation);
                    var error = GiveUnitOrder(c, s, o, spent, attacked, why);
                    if (error == null && operation != null && EventSystem.OperationOf(c, s, o.Unit) != operation)
                        EventSystem.CancelOperation(c, s, operation, bound!, why, actions);
                    return error;
                }
                case StartProject p:
                    return Projects.StartCity(c, s, p.ProjectKind, p.City, p.Q, p.R, why);
                case CancelProject p:
                    return Projects.CancelCity(c, s, p.Project, why);
                case Move m:
                    return Movement.Move(c, s, m.Unit, m.Q, m.R, spent, why);
                case BuyArms a:
                    return Pools.BuyArms(c, s, a.Count, why);
                case ConvertDollars d:
                    return EconomySystem.ConvertDollars(c, s, d.Amount, s.DollarsConverted - dollarsAtStart, startRung, why);
                case ResolveCapture x:
                    return SettlementControl.Resolve(c, s, x.Settlement, x.Outcome, why);
                case EndOccupation x:
                    return SettlementControl.End(c, s, x.Settlement, x.Outcome, why);
                case SecurityOrder o:
                    // long arithmetic: an extreme delta clamps to the ladder's end instead of wrapping around.
                    SecuritySystem.SetRung(c, s, (int)Math.Max(1L, Math.Min(5L, (long)s.Rung + o.Delta)), why);
                    return null;
                default:
                    return "That order is not known";
            }
        }

        static string? GiveUnitOrder(Content c, GameState s, UnitOrder o, Dictionary<int, int> spent, Dictionary<int, AttackRecord> attacked, List<Cause> why)
        {
            if (o.Order == Movement.GoTo) return Movement.GiveGoTo(c, s, o.Unit, o.Q, o.R, spent, why);
            if (o.Order == Combat.Attack) return Combat.Strike(c, s, o.Unit, o.Q, o.R, spent, attacked, why);
            if (o.Q != null || o.R != null) return Orders.RefusedNamesNoHex;
            if (o.Order == Qualification.ReturnOrder) return Qualification.Return(c, s, o.Unit, why);
            return o.Order == Demobilization.SendHome
                ? Demobilization.Give(c, s, o.Unit, attacked, why)
                : Orders.Give(c, s, o.Unit, o.Order, why);
        }

        /// <summary>True in an era whose legislature is an assembly (eras.yaml systems.legislature): its vote is held but does not bind.</summary>
        static bool Advisory(Content c, GameState s) => c.SystemsAt(s.Date).Legislature == EraSystems.Assembly;

        static bool PassVote(Content c, GameState s)
        {
            var rng = new Rng(s.RngState);
            var passed = PoliticsSystem.Vote(c, s, ref rng);
            s.RngState = rng.State;
            return passed;
        }
    }
}