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.

sim: systems read RulesAt(the turn's starting date), second piece of #58 (#281)

agamrafaeli-instinct97013672123d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3fef57b1c..957d4ed2d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
## [Unreleased]
### Added
+- Rules per era (#58, second piece): the attention, economy, population, security, map-action and cabinet systems read
+ `RulesAt(date)` of the turn's starting date instead of `rules.yaml` directly, and the Defence and Info screens and the
+ HUD follow. With no `content/rules/<era>.yaml` files yet, nothing changes: the goldens do not move. A test fails if a
+ system reads the base rules directly for anything but a start value.
- JSON Schemas for `people.yaml`, `offices.yaml`, `parties.yaml` and the event files (#265), in `content/schema/`. Each file
names its schema on the first line, so an editor with a YAML language server flags a wrong field name or a missing
`sources:` as you type. `SchemaTests` checks all real content against them, keeps their field names equal to the loader
diff --git a/docs/determinism.md b/docs/determinism.md
index ce2bda319..c1b6d1953 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -45,6 +45,17 @@ different fields) and shows every number as a plain value next to its IEEE bits.
reviewers what moved. Then update the hash constants in the three places below by hand, and say why in the commit
message. The snapshot test also fails if a snapshot is stale while the hash is unchanged.
+**Rules per era.** A system reads `Content.RulesAt(date)`, where `date` is the date of the state the turn starts from (`s.Date`
+before the step); `AttentionSystem.Refill` runs after the date moves, so it fills the next turn from that turn's era. Rules
+change only at era boundaries (chapters spec section 3.3). Spec section 4.1 will end the turn that reaches a boundary exactly
+on it, so every turn then lies in one era; until that lands, only the last era's end is a boundary turn, and a turn that
+starts in one era and ends in the next uses the starting era's rules for its whole length
+(`EraRulesSwitchTests.ARunPicksUpTheOverrideFromTheFirstTurnThatStartsInTheNewEra`). Start
+values (`start`, `treasury_start`, `fx_start`, `start_rung`, `initial_population`, `budget_start`) are read once by `NewGame`
+from the base `rules.yaml`: an era override cannot set them. A map action's display name is also read from the base rules,
+because an override cannot remove an action. `EraRulesSwitchTests.OnlyStartValuesAndMapActionNamesReadTheBaseRulesDirectly`
+fails if a file in `sim/Statecraft.Sim` reads `Rules` directly for anything else, including a bare `var r = c.Rules;`.
+
**Cause text is derived, not hashed.** The "Why did this happen?" lines (`Cause.Message`, `Cause.Delta`) are output
computed from the hashed state; replaying a save's commands regenerates them. Wording changes therefore do not move the
goldens (playtest 2 changed every line's casing with no hash change). They are still deterministic:
diff --git a/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs b/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs
new file mode 100644
index 000000000..e03c986b4
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/EraRulesSwitchTests.cs
@@ -0,0 +1,201 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using Statecraft.Sim;
+
+/// <summary>#58, second piece: the systems read RulesAt(the turn's starting date) instead of Rules. Each test gives the
+/// "later" era (1952-01-01 to 1957-01-01) an override and checks the value changes with the state's date, in the founding era
+/// and in the later one.</summary>
+public class EraRulesSwitchTests
+{
+ const string Eras = @"
+eras:
+ - id: founding
+ name: The Founding
+ from: 1948-05-15
+ to: 1952-01-01
+ - id: later
+ name: A Later Chapter
+ from: 1952-01-01
+ to: 1957-01-01
+";
+ static readonly DateTime Early = new DateTime(1950, 6, 1), Late = new DateTime(1953, 6, 1);
+
+ static Content Load(string laterRules)
+ {
+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = Eras });
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), laterRules);
+ return ContentLoader.Load(dir);
+ }
+
+ static GameState At(Content c, DateTime date) { var s = Simulation.NewGame(c, 1, Mode.Historical); s.Date = date; return s; }
+
+ [Fact]
+ public void AttentionRefillsFromTheTurnsEra()
+ {
+ var c = Load("attention_per_turn: 7.5\n");
+ var s = At(c, Early); AttentionSystem.Refill(c, s); Assert.Equal(c.Rules.AttentionPerTurn, s.Attention);
+ s = At(c, Late); AttentionSystem.Refill(c, s); Assert.Equal(7.5, s.Attention);
+ }
+
+ [Fact]
+ public void AttentionCostComesFromTheTurnsEra()
+ {
+ var c = Load("attention_cost:\n set_policy: 9\n");
+ Assert.NotEqual(9, c.Rules.AttentionCost["set_policy"]);
+ Assert.Equal(c.Rules.AttentionCost["set_policy"] * (1 + c.Rules.RungAttentionStep * (At(c, Early).Rung - 1)),
+ AttentionSystem.Cost(c, At(c, Early), "set_policy"));
+ var late = At(c, Late);
+ Assert.Equal(9 * (1 + c.Rules.RungAttentionStep * (late.Rung - 1)), AttentionSystem.Cost(c, late, "set_policy"));
+ }
+
+ [Fact]
+ public void TreasuryFlowsAndMobilizationCostComeFromTheTurnsEra()
+ {
+ var c = Load("tax_per_capita_per_year: 2\nspending_per_capita_per_year: 3\nmobilization_cost_per_year: 5\n");
+ var early = At(c, Early); var late = At(c, Late); early.Mobilization = late.Mobilization = 0.5;
+ var fe = EconomySystem.Flows(c, early, 1.0); var fl = EconomySystem.Flows(c, late, 1.0);
+ Assert.Equal(c.Rules.TaxPerCapitaPerYear * early.TotalPopulation, fe.Tax, 9);
+ Assert.Equal(2 * late.TotalPopulation, fl.Tax, 9);
+ Assert.Equal(3 * late.TotalPopulation, fl.Spending, 9);
+ Assert.Equal(c.Rules.MobilizationCostPerYear * 0.5, fe.Mobilization, 9);
+ Assert.Equal(5 * 0.5, fl.Mobilization, 9);
+ Assert.Equal(fl.Mobilization, EconomySystem.MobilizationCost(c, Late, 0.5), 12);
+ }
+
+ [Fact]
+ public void SecurityFloorAndCeasefireComeFromTheTurnsEra()
+ {
+ var c = Load("rung_min_mobilization: [0.1, 0.2, 0.3, 0.4, 0.5]\nceasefire_weeks: 9\n");
+ Assert.Equal(c.Rules.RungMinMobilization[4], SecuritySystem.MinMobilization(c, Early, 5));
+ Assert.Equal(0.5, SecuritySystem.MinMobilization(c, Late, 5));
+ Assert.Equal(0.5, SecuritySystem.EffectiveMobilization(c, Late, 5, 0.1));
+ Assert.Equal(c.Rules.CeasefireWeeks, SecuritySystem.CeasefireWeeksAfter(c, Early, 3, 0, 5));
+ Assert.Equal(9, SecuritySystem.CeasefireWeeksAfter(c, Late, 3, 0, 5));
+ var s = At(c, Late); s.Mobilization = 0; s.Rung = 3; s.CeasefireWeeksLeft = 0;
+ SecuritySystem.SetRung(c, s, 5, new List<Cause>());
+ Assert.Equal(9, s.CeasefireWeeksLeft);
+ Assert.True(s.Mobilization >= 0.5); // raised to the later era's floor
+ }
+
+ [Fact]
+ public void MapActionAvailabilityComesFromTheTurnsEra()
+ {
+ var c = Load("map_actions_from: 1960-01-01\n");
+ var early = MapActions.Check(c, At(c, Early), MapActions.Housing, 0, 0);
+ var late = MapActions.Check(c, At(c, Late), MapActions.Housing, 0, 0);
+ Assert.DoesNotContain("1960", early ?? "");
+ Assert.Contains("1960", late);
+ }
+
+ [Fact]
+ public void ThePopulationGrowsByTheTurnsEraRate()
+ {
+ var c = Load("natural_increase_per_year: 0.5\n");
+ double Grow(DateTime d)
+ {
+ var s = At(c, d); var before = s.TotalPopulation;
+ PopulationSystem.Apply(c, s, d.AddDays(7), 0.1, new List<Cause>());
+ return s.TotalPopulation / before;
+ }
+ Assert.True(Grow(Late) > Grow(Early));
+ }
+
+ [Fact]
+ public void AppointmentStabilityCostComesFromTheTurnsEra()
+ {
+ var dir = Fixture.Write(new Dictionary<string, string>
+ {
+ ["eras.yaml"] = Eras,
+ ["people.yaml"] = Fixture.Files["people.yaml"] + @"
+ - id: loyalist
+ name: Loy Alist
+ living: false
+ party: alpha
+ competence: 2
+ loyalty: 9
+ offices: []
+",
+ });
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "appoint_stability_cost_other_party: 0.4\n");
+ var c = ContentLoader.Load(dir);
+ double Cost(DateTime d)
+ {
+ var s = At(c, d); var before = s.CoalitionStability;
+ Assert.Null(Cabinet.Appoint(c, s, "finance_minister", "loyalist", new List<Cause>()));
+ return before - s.CoalitionStability;
+ }
+ Assert.Equal(c.Rules.AppointStabilityCostOtherParty, Cost(Early), 9);
+ Assert.Equal(0.4, Cost(Late), 9);
+ }
+
+ /// <summary>Through <c>Simulation.Step</c>, across a boundary that falls inside a turn (1948-06-01; weekly war turns run
+ /// 05-29 to 06-05): the turn that starts before the boundary taxes at the founding rate for its whole length, the first
+ /// turn that starts after it at the later era's rate, and attention is refilled at the later era's value from the end
+ /// of the crossing turn on (the refill is for the turn that starts on the new date).</summary>
+ [Fact]
+ public void ARunPicksUpTheOverrideFromTheFirstTurnThatStartsInTheNewEra()
+ {
+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = @"
+eras:
+ - id: founding
+ name: The Founding
+ from: 1948-05-15
+ to: 1948-06-01
+ - id: later
+ name: A Later Chapter
+ from: 1948-06-01
+ to: 1957-01-01
+" });
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "attention_per_turn: 7.5\ntax_per_capita_per_year: 1.0\n");
+ var c = ContentLoader.Load(dir);
+ var boundary = new DateTime(1948, 6, 1);
+ var s = Simulation.NewGame(c, 1, Mode.Historical);
+ Assert.Equal(c.Rules.AttentionPerTurn, s.Attention);
+ var crossed = false;
+ while (s.Date < boundary.AddDays(7)) // through the first whole turn of the new era (the fixture's ceasefire ends the weekly turns after it)
+ {
+ var start = s.Date;
+ var step = Simulation.Step(c, s, new List<Command>());
+ var end = step.State.Date;
+ Assert.Equal(7, (end - start).Days); // weekly turns; no turn here is adjusted to the boundary yet (spec 4.1)
+ var tax = start < boundary ? c.Rules.TaxPerCapitaPerYear : 1.0;
+ var expected = (tax - c.Rules.SpendingPerCapitaPerYear) * step.State.TotalPopulation * (7 / 365.0)
+ - c.Rules.MobilizationCostPerYear * s.Mobilization * (7 / 365.0);
+ var treasury = step.Why.Single(w => w.System == "economy" && w.Target == "treasury").Delta;
+ Assert.True(Math.Abs(expected - treasury) < 1e-9, $"{start:yyyy-MM-dd}: treasury {treasury}, expected {expected}");
+ Assert.Equal(end < boundary ? c.Rules.AttentionPerTurn : 7.5, step.State.Attention);
+ crossed |= start < boundary && end > boundary;
+ s = step.State;
+ }
+ Assert.True(crossed);
+ }
+
+ /// <summary>The only places the sim reads the base rules directly are the values <c>NewGame</c> reads once (an era
+ /// override cannot set them) and a map action's display name (an override cannot remove an action). Everything else
+ /// reads <c>RulesAt(date)</c>, so a new <c>c.Rules.X</c> read in a system fails here until it is deliberate.</summary>
+ [Fact]
+ public void OnlyStartValuesAndMapActionNamesReadTheBaseRulesDirectly()
+ {
+ var simDir = Path.Combine(Directory.GetParent(RealContentTests.ContentRoot())!.FullName, "sim", "Statecraft.Sim");
+ var allowed = new HashSet<string> { "Start", "TreasuryStart", "FxStart", "BudgetStart", "InitialPopulation", "StartRung", "MapActions" };
+ var bad = new List<string>();
+ foreach (var f in Directory.GetFiles(simDir, "*.cs", SearchOption.AllDirectories))
+ {
+ var name = Path.GetFileName(f);
+ if (name == "ContentLoader.cs" || name == "Content.cs") continue;
+ var lines = File.ReadAllLines(f);
+ for (int i = 0; i < lines.Length; i++)
+ // Any receiver (c, content, ...), and a bare `x.Rules` with no member after it (`var r = c.Rules;`), which
+ // would hand every later read the base rules.
+ foreach (Match m in Regex.Matches(lines[i], @"\b\w+\.Rules\b(?!\s*\()(?:\.(\w+))?"))
+ if (!m.Groups[1].Success || !allowed.Contains(m.Groups[1].Value)) bad.Add($"{name}:{i + 1} {m.Value}");
+ }
+ Assert.True(bad.Count == 0, "read RulesAt(date) instead: " + string.Join(", ", bad));
+ }
+}
diff --git a/sim/Statecraft.Sim.Tests/FinalWaveTests.cs b/sim/Statecraft.Sim.Tests/FinalWaveTests.cs
index c0996efe4..0af6c4dba 100644
--- a/sim/Statecraft.Sim.Tests/FinalWaveTests.cs
+++ b/sim/Statecraft.Sim.Tests/FinalWaveTests.cs
@@ -126,8 +126,8 @@ public class FinalWaveTests
public void TheCallUpCostComesFromOneRule()
{
var s = Simulation.NewGame(Real, 1, Mode.Historical);
- Assert.Equal(Real.Rules.MobilizationCostPerYear * 0.35, EconomySystem.MobilizationCost(Real, 0.35), 12);
+ Assert.Equal(Real.Rules.MobilizationCostPerYear * 0.35, EconomySystem.MobilizationCost(Real, Real.Rules.Start, 0.35), 12);
s.Mobilization = 0.35;
- Assert.Equal(EconomySystem.MobilizationCost(Real, 0.35, 0.25), EconomySystem.Flows(Real, s, 0.25).Mobilization, 12);
+ Assert.Equal(EconomySystem.MobilizationCost(Real, s.Date, 0.35, 0.25), EconomySystem.Flows(Real, s, 0.25).Mobilization, 12);
}
}
diff --git a/sim/Statecraft.Sim.Tests/SecurityTests.cs b/sim/Statecraft.Sim.Tests/SecurityTests.cs
index 4f3f2022e..97e052b15 100644
--- a/sim/Statecraft.Sim.Tests/SecurityTests.cs
+++ b/sim/Statecraft.Sim.Tests/SecurityTests.cs
@@ -104,14 +104,14 @@ public class SecurityTests
[Theory]
[InlineData(1, 0.02)] [InlineData(4, 0.4)] [InlineData(5, 0.8)] [InlineData(9, 0.8)] [InlineData(0, 0.02)]
- public void MinMobilizationIsTheRungsFloor(int rung, double expected) => Assert.Equal(expected, SecuritySystem.MinMobilization(C, rung));
+ public void MinMobilizationIsTheRungsFloor(int rung, double expected) => Assert.Equal(expected, SecuritySystem.MinMobilization(C, C.Rules.Start, rung));
[Fact]
public void EffectiveMobilizationIsNeverBelowTheFloor()
{
- Assert.Equal(0.8, SecuritySystem.EffectiveMobilization(C, 5, 0.1));
- Assert.Equal(0.9, SecuritySystem.EffectiveMobilization(C, 5, 0.9));
- Assert.Equal(0.4, SecuritySystem.EffectiveMobilization(C, 4, 0.0));
+ Assert.Equal(0.8, SecuritySystem.EffectiveMobilization(C, C.Rules.Start, 5, 0.1));
+ Assert.Equal(0.9, SecuritySystem.EffectiveMobilization(C, C.Rules.Start, 5, 0.9));
+ Assert.Equal(0.4, SecuritySystem.EffectiveMobilization(C, C.Rules.Start, 4, 0.0));
}
[Fact]
@@ -122,7 +122,7 @@ public class SecurityTests
{
var s = new GameState { Rung = rung, Mobilization = 0 };
Assert.Null(SecuritySystem.SetMobilization(C, s, level, new List<Cause>()));
- Assert.Equal(SecuritySystem.EffectiveMobilization(C, rung, level), s.Mobilization);
+ Assert.Equal(SecuritySystem.EffectiveMobilization(C, s.Date, rung, level), s.Mobilization);
}
}
@@ -133,7 +133,7 @@ public class SecurityTests
[InlineData(2, 0, 3, 0)]
public void CeasefireWeeksAfterAnOrderFollowsSetRung(int from, int left, int to, int expected)
{
- Assert.Equal(expected, SecuritySystem.CeasefireWeeksAfter(C, from, left, to));
+ Assert.Equal(expected, SecuritySystem.CeasefireWeeksAfter(C, C.Rules.Start, from, left, to));
var s = new GameState { Rung = from, CeasefireWeeksLeft = left };
SecuritySystem.SetRung(C, s, to, new List<Cause>());
Assert.Equal(expected, s.CeasefireWeeksLeft);
diff --git a/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs b/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs
index 3f028b7fa..a943d6fb8 100644
--- a/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs
+++ b/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs
@@ -58,7 +58,7 @@ public class SliceSmokeTests
cmds.Add(new AllocateBudget(new Dictionary<string, double>(s.Budget) { [from] = s.Budget[from] - 0.05, [to] = s.Budget[to] + 0.05 }));
}
if (turn % 10 == 3) cmds.Add(new SetMobilization(Math.Min(1, Math.Round(s.Mobilization + 0.1, 2))));
- if (turn % 10 == 8) cmds.Add(new SetMobilization(SecuritySystem.MinMobilization(c, s.Rung)));
+ if (turn % 10 == 8) cmds.Add(new SetMobilization(SecuritySystem.MinMobilization(c, s.Date, s.Rung)));
if (turn % 2 == 0)
foreach (var action in new[] { MapActions.TransitCamp, MapActions.Housing })
{
diff --git a/sim/Statecraft.Sim/AttentionSystem.cs b/sim/Statecraft.Sim/AttentionSystem.cs
index 522e670b6..c88058a01 100644
--- a/sim/Statecraft.Sim/AttentionSystem.cs
+++ b/sim/Statecraft.Sim/AttentionSystem.cs
@@ -13,11 +13,14 @@ namespace Statecraft.Sim
public static bool IsCommandKind(string kind) => Kinds.Contains(kind);
- public static void Refill(Content c, GameState s) => s.Attention = c.Rules.AttentionPerTurn;
+ public static void Refill(Content c, GameState s) => s.Attention = c.RulesAt(s.Date).AttentionPerTurn;
/// <summary>Cost at <paramref name="rung"/> if given, else at the state's current rung.</summary>
- public static double Cost(Content c, GameState s, string kind, int? rung = null) =>
- c.Rules.AttentionCost[kind] * (1 + c.Rules.RungAttentionStep * ((rung ?? s.Rung) - 1));
+ public static double Cost(Content c, GameState s, string kind, int? rung = null)
+ {
+ var r = c.RulesAt(s.Date); // the era the turn starts in (docs/determinism.md, "Rules per era")
+ return r.AttentionCost[kind] * (1 + r.RungAttentionStep * ((rung ?? s.Rung) - 1));
+ }
/// <summary>Returns null and deducts on success, or the reason it could not be afforded.
/// <paramref name="rung"/> prices the command at that security level (the turn's starting rung).</summary>
diff --git a/sim/Statecraft.Sim/Cabinet.cs b/sim/Statecraft.Sim/Cabinet.cs
index 75bfeeb6c..54bdf5366 100644
--- a/sim/Statecraft.Sim/Cabinet.cs
+++ b/sim/Statecraft.Sim/Cabinet.cs
@@ -120,7 +120,8 @@ namespace Statecraft.Sim
var oldParty = Offices.PartyOf(c, displaced, s.Date);
var newParty = Offices.PartyOf(c, person, s.Date);
bool sameParty = oldParty != "" && oldParty == newParty;
- var cost = sameParty ? c.Rules.AppointStabilityCostSameParty : c.Rules.AppointStabilityCostOtherParty;
+ var rules = c.RulesAt(s.Date);
+ var cost = sameParty ? rules.AppointStabilityCostSameParty : rules.AppointStabilityCostOtherParty;
if (cost <= 0) return null;
var before = s.CoalitionStability;
s.CoalitionStability = Math.Max(0, before - cost);
diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.cs
index 29edf837f..f2b957b82 100644
--- a/sim/Statecraft.Sim/EconomySystem.cs
+++ b/sim/Statecraft.Sim/EconomySystem.cs
@@ -25,18 +25,18 @@ namespace Statecraft.Sim
public static TreasuryFlows Flows(Content c, GameState s, double yearFraction)
{
- var r = c.Rules; var pop = s.TotalPopulation;
+ var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;
return new TreasuryFlows(r.TaxPerCapitaPerYear * pop * yearFraction, r.SpendingPerCapitaPerYear * pop * yearFraction,
- MobilizationCost(c, s.Mobilization, yearFraction));
+ MobilizationCost(c, s.Date, s.Mobilization, yearFraction));
}
/// <summary>The reserve call-up's cost (pay and lost work) for <paramref name="level"/> (0..1) over a share of a year:
/// the one rule Flows and the Defence screen both use (M3 final review M5).</summary>
- public static double MobilizationCost(Content c, double level, double yearFraction = 1.0) => c.Rules.MobilizationCostPerYear * level * yearFraction;
+ public static double MobilizationCost(Content c, DateTime date, double level, double yearFraction = 1.0) => c.RulesAt(date).MobilizationCostPerYear * level * yearFraction;
public static void Apply(Content c, GameState s, double yearFraction, List<Cause> why)
{
- var r = c.Rules; var pop = s.TotalPopulation;
+ var r = c.RulesAt(s.Date); var pop = s.TotalPopulation;
var flows = Flows(c, s, yearFraction);
var revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;
s.Treasury += revenue - spending - mobilization;
diff --git a/sim/Statecraft.Sim/HistoricalAI.cs b/sim/Statecraft.Sim/HistoricalAI.cs
index 13e18f521..8800bd8b4 100644
--- a/sim/Statecraft.Sim/HistoricalAI.cs
+++ b/sim/Statecraft.Sim/HistoricalAI.cs
@@ -17,7 +17,7 @@ namespace Statecraft.Sim
.Select(id => c.Events.First(e => e.Id == id))
.Select(e => (Command)new ChooseEventOption(e.Id, (e.Options.FirstOrDefault(o => o.Historical) ?? e.Options[0]).Id))
.ToList();
- var floor = SecuritySystem.MinMobilization(c, s.Rung);
+ var floor = SecuritySystem.MinMobilization(c, s.Date, s.Rung);
if (s.Mobilization > floor) wanted.Add(new SetMobilization(floor));
var list = new List<Command>();
var left = s.Attention;
diff --git a/sim/Statecraft.Sim/MapActions.cs b/sim/Statecraft.Sim/MapActions.cs
index 91712acc8..faf025e1c 100644
--- a/sim/Statecraft.Sim/MapActions.cs
+++ b/sim/Statecraft.Sim/MapActions.cs
@@ -42,15 +42,16 @@ namespace Statecraft.Sim
// No id in either reason: a command from an old save or a stale UI may name an action this content lacks; the
// replay refuses it here, before anything is formatted, so a placement always has its rule (fix round 3, m-6).
if (!Actions.Contains(action)) return "There is no such map action";
- var rule = c.Rules.MapActions.TryGetValue(action, out var x) ? x : null;
+ var rules = c.RulesAt(s.Date); // the era the turn starts in
+ var rule = rules.MapActions.TryGetValue(action, out var x) ? x : null;
if (rule == null) return "That map action is not available in this game";
- if (s.Date < c.Rules.MapActionsFrom)
- return $"Transit camps and housing projects can be placed from {PlayerText.Date(c.Rules.MapActionsFrom)}";
+ if (s.Date < rules.MapActionsFrom)
+ return $"Transit camps and housing projects can be placed from {PlayerText.Date(rules.MapActionsFrom)}";
if (action == TransitCamp && !(s.Policies.TryGetValue(MaabarotPolicy, out var m) && m >= 0.5))
return "Transit camps need the ma'abarot policy";
var hex = c.HexAt(q, r);
if (hex == null || !hex.Land) return "This hex is not land";
- var max = c.Rules.MapActionMaxDistance;
+ var max = rules.MapActionMaxDistance;
if (!c.SettlementHexes.Any(sh => Distance(q, r, sh.Q, sh.R) <= max))
return FormattableString.Invariant($"This hex is more than {max} {(max == 1 ? "hex" : "hexes")} from a settlement");
var here = At(s, q, r);
@@ -58,8 +59,8 @@ namespace Statecraft.Sim
return $"This hex already has {PlayerText.MapAction(c, here.Action)}";
// The cap comes last so a player who is over it still sees the specific reason an order is illegal. It counts
// accepted actions (not surviving placements): housing on a camp removes the camp but still used an action.
- if (ActionsThisTurn(s) >= c.Rules.MapActionsPerTurn)
- return FormattableString.Invariant($"No more than {c.Rules.MapActionsPerTurn} map actions in one turn");
+ if (ActionsThisTurn(s) >= rules.MapActionsPerTurn)
+ return FormattableString.Invariant($"No more than {rules.MapActionsPerTurn} map actions in one turn");
return null;
}
@@ -68,7 +69,7 @@ namespace Statecraft.Sim
{
var reason = Check(c, s, action, q, r);
if (reason != null) return reason;
- var rule = c.Rules.MapActions[action];
+ var rule = c.RulesAt(s.Date).MapActions[action];
if (s.MapActionsTurnDate != s.Date) { s.MapActionsTurnDate = s.Date; s.MapActionsThisTurn = 0; }
s.MapActionsThisTurn++;
s.Placements.RemoveAll(p => p.Q == q && p.R == r);
diff --git a/sim/Statecraft.Sim/PlayerText.cs b/sim/Statecraft.Sim/PlayerText.cs
index a0e01c88c..6b84d0904 100644
--- a/sim/Statecraft.Sim/PlayerText.cs
+++ b/sim/Statecraft.Sim/PlayerText.cs
@@ -41,7 +41,8 @@ namespace Statecraft.Sim
c.Indicators.FirstOrDefault(i => i.Id == id)?.Name ?? c.Policies.FirstOrDefault(p => p.Id == id)?.Name
?? c.Money.FirstOrDefault(m => m.Id == id)?.Name ?? throw Unknown("indicator, policy or money", id);
- /// <summary>The phrase a map action reads as in a sentence ("a transit camp"; rules.yaml map_actions name).</summary>
+ /// <summary>The phrase a map action reads as in a sentence ("a transit camp"; rules.yaml map_actions name). Read from the base
+ /// rules on purpose: an era override cannot remove a map action, so the base names cover every action an era can have.</summary>
public static string MapAction(Content c, string id) =>
c.Rules.MapActions.TryGetValue(id, out var rule) ? rule.Name : throw Unknown("map action", id);
diff --git a/sim/Statecraft.Sim/PopulationSystem.cs b/sim/Statecraft.Sim/PopulationSystem.cs
index c52d32174..b644d77ff 100644
--- a/sim/Statecraft.Sim/PopulationSystem.cs
+++ b/sim/Statecraft.Sim/PopulationSystem.cs
@@ -29,7 +29,7 @@ namespace Statecraft.Sim
public static void Apply(Content c, GameState s, DateTime to, double yearFraction, List<Cause> why)
{
- var rate = c.Rules.NaturalIncreasePerYear * yearFraction;
+ var rate = c.RulesAt(s.Date).NaturalIncreasePerYear * yearFraction;
foreach (var k in s.Population.Keys.ToList()) s.Population[k] *= 1 + rate;
foreach (var kv in Arrivals(c, s.Date, to).OrderBy(k => k.Key, StringComparer.Ordinal))
{
diff --git a/sim/Statecraft.Sim/SecuritySystem.cs b/sim/Statecraft.Sim/SecuritySystem.cs
index f5f7274c3..64a955762 100644
--- a/sim/Statecraft.Sim/SecuritySystem.cs
+++ b/sim/Statecraft.Sim/SecuritySystem.cs
@@ -15,18 +15,18 @@ namespace Statecraft.Sim
public static int ClampRung(int rung) => Math.Max(1, Math.Min(5, rung));
/// <summary>The least reserve call-up the rung allows (rules.yaml rung_min_mobilization).</summary>
- public static double MinMobilization(Content c, int rung) => c.Rules.RungMinMobilization[ClampRung(rung) - 1];
+ public static double MinMobilization(Content c, DateTime date, int rung) => c.RulesAt(date).RungMinMobilization[ClampRung(rung) - 1];
/// <summary>The call-up a level ends up at on this rung: the sim raises a lower order to the rung's minimum.</summary>
- public static double EffectiveMobilization(Content c, int rung, double level) => Math.Max(level, MinMobilization(c, rung));
+ public static double EffectiveMobilization(Content c, DateTime date, int rung, double level) => Math.Max(level, MinMobilization(c, date, rung));
/// <summary>Weeks left on the UN ceasefire clock after moving from <paramref name="fromRung"/> (with
/// <paramref name="weeksLeft"/> on the clock) to <paramref name="toRung"/>: entering full war starts it, leaving ends it.</summary>
- public static int CeasefireWeeksAfter(Content c, int fromRung, int weeksLeft, int toRung)
+ public static int CeasefireWeeksAfter(Content c, DateTime date, int fromRung, int weeksLeft, int toRung)
{
toRung = ClampRung(toRung);
if (toRung != 5) return 0;
- return fromRung != 5 ? c.Rules.CeasefireWeeks : weeksLeft;
+ return fromRung != 5 ? c.RulesAt(date).CeasefireWeeks : weeksLeft;
}
public static void Init(Content c, GameState s, List<Cause> why) => SetRung(c, s, c.Rules.StartRung, why);
@@ -34,7 +34,7 @@ namespace Statecraft.Sim
public static void SetRung(Content c, GameState s, int rung, List<Cause> why)
{
rung = ClampRung(rung);
- s.CeasefireWeeksLeft = CeasefireWeeksAfter(c, s.Rung, s.CeasefireWeeksLeft, rung);
+ s.CeasefireWeeksLeft = CeasefireWeeksAfter(c, s.Date, s.Rung, s.CeasefireWeeksLeft, rung);
if (rung != s.Rung) why.Add(new Cause("security", "rung", rung - s.Rung, FormattableString.Invariant($"Security level {s.Rung} to {rung}")));
s.Rung = rung;
RaiseToFloor(c, s, why);
@@ -53,7 +53,7 @@ namespace Statecraft.Sim
static void RaiseToFloor(Content c, GameState s, List<Cause> why)
{
var rung = ClampRung(s.Rung); // a bad save cannot index past the table
- var floor = MinMobilization(c, rung);
+ var floor = MinMobilization(c, s.Date, rung);
if (s.Mobilization < floor)
{
why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserve call-up raised to {PlayerText.Percent(floor)}, the minimum for security level {rung}")));
diff --git a/unity/Assets/Scripts/Map/Units/UnitRoster.cs b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
index f5cdd7be7..63cff4101 100644
--- a/unity/Assets/Scripts/Map/Units/UnitRoster.cs
+++ b/unity/Assets/Scripts/Map/Units/UnitRoster.cs
@@ -50,7 +50,7 @@ namespace Statecraft.Game.Map.Units
if (units == null) throw new ArgumentNullException(nameof(units));
if (content == null) throw new ArgumentNullException(nameof(content));
if (state == null) throw new ArgumentNullException(nameof(state));
- return Build(units, content.Rules, state.Date, state.Rung, state.Mobilization);
+ return Build(units, content.RulesAt(state.Date), state.Date, state.Rung, state.Mobilization);
}
public static List<UnitToken> Build(IReadOnlyList<UnitEntry> units, Rules rules, DateTime date, int rung, double mobilization)
diff --git a/unity/Assets/Scripts/UI/DefencePresenter.cs b/unity/Assets/Scripts/UI/DefencePresenter.cs
index beaf6f628..daf7f8d09 100644
--- a/unity/Assets/Scripts/UI/DefencePresenter.cs
+++ b/unity/Assets/Scripts/UI/DefencePresenter.cs
@@ -97,7 +97,7 @@ namespace Statecraft.Game.UI
}
/// <summary>The call-up the turn will end with if <paramref name="level"/> is ordered (the sim raises a lower one to the minimum).</summary>
- double EffectiveAt(double level) => SecuritySystem.EffectiveMobilization(bridge.Content, TargetRung, level);
+ double EffectiveAt(double level) => SecuritySystem.EffectiveMobilization(bridge.Content, bridge.State.Date, TargetRung, level);
bool SameAsToday(double level) => Math.Abs(EffectiveAt(level) - EffectiveAt(bridge.State.Mobilization)) < 1e-9;
@@ -110,7 +110,7 @@ namespace Statecraft.Game.UI
void Mobilize(double step)
{
- var floor = SecuritySystem.MinMobilization(bridge.Content, TargetRung);
+ var floor = SecuritySystem.MinMobilization(bridge.Content, bridge.State.Date, TargetRung);
var level = Math.Max(floor, Math.Min(1, Math.Round((EffectiveAt(ProposedMobilization) + step) / MobilizationStep) * MobilizationStep));
if (SameAsToday(level)) Withdraw(new SetMobilization(0)); else bridge.Queue(new SetMobilization(level));
}
@@ -161,11 +161,11 @@ namespace Statecraft.Game.UI
var ceasefire = screen.Q<Label>("ceasefire");
if (s.Rung == 5 && target == 5) ceasefire.text = text.Format("defence.ceasefire", s.CeasefireWeeksLeft);
else if (s.Rung == 5) ceasefire.text = text["defence.ceasefire_stops"]; // a lowering is queued
- else if (target == 5) ceasefire.text = text.Format("defence.ceasefire_starts", SecuritySystem.CeasefireWeeksAfter(c, s.Rung, s.CeasefireWeeksLeft, target));
+ else if (target == 5) ceasefire.text = text.Format("defence.ceasefire_starts", SecuritySystem.CeasefireWeeksAfter(c, s.Date, s.Rung, s.CeasefireWeeksLeft, target));
else ceasefire.text = "";
ceasefire.style.display = ceasefire.text == "" ? DisplayStyle.None : DisplayStyle.Flex;
screen.Q<Label>("order-pending").text = delta == 0 ? "" : text.Format("defence.order", s.Rung, target);
- var floor = SecuritySystem.MinMobilization(c, target);
+ var floor = SecuritySystem.MinMobilization(c, s.Date, target);
var proposed = EffectiveAt(ProposedMobilization); // what the call-up will be: the sim raises a lower order to the minimum
screen.Q<Label>("mob-level").text = text.Format("defence.mob", PlayerText.Percent(proposed), target, PlayerText.Percent(floor));
screen.Q<Label>("mob-percent").text = PlayerText.Percent(proposed);
@@ -174,7 +174,7 @@ namespace Statecraft.Game.UI
var share = ProposedBudgetShare;
screen.Q<UiBar>("defence-budget-bar").Value = share.HasValue ? (float)share.Value : 0f;
screen.Q<Label>("defence-budget-share").text = share.HasValue ? text.Format("defence.budget_share", PlayerText.Percent(share.Value)) : text["defence.budget_none"];
- screen.Q<Label>("mob-cost").text = text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, proposed)));
+ screen.Q<Label>("mob-cost").text = text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, s.Date, proposed)));
screen.Q<Button>("escalate").SetEnabled(target < 5);
screen.Q<Button>("de-escalate").SetEnabled(target > 1);
}
diff --git a/unity/Assets/Scripts/UI/HudModel.cs b/unity/Assets/Scripts/UI/HudModel.cs
index 88ab6cc20..ef704651d 100644
--- a/unity/Assets/Scripts/UI/HudModel.cs
+++ b/unity/Assets/Scripts/UI/HudModel.cs
@@ -56,7 +56,7 @@ namespace Statecraft.Game.UI
Year = s.Date.Year.ToString(System.Globalization.CultureInfo.InvariantCulture),
Turn = t.Format("hud.turn", s.Turn),
Date = t.Format("hud.date", PlayerText.Date(s.Date)),
- Attention = t.Format("hud.attention", b.AttentionLeft, c.Rules.AttentionPerTurn),
+ Attention = t.Format("hud.attention", b.AttentionLeft, c.RulesAt(s.Date).AttentionPerTurn),
SecurityLevel = t.Format("hud.level", s.Rung),
Treasury = Money("treasury", s.Treasury - s.Debt, prev == null ? (double?)null : prev.Treasury - prev.Debt),
Immigration = People(Arrivals(b.Session.Last), b.BeforeLast == null ? (double?)null : Arrivals(b.BeforeLast)),
diff --git a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
index 2c8af1247..7e27beeaa 100644
--- a/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
+++ b/unity/Assets/Scripts/UI/InfoPanelPresenter.cs
@@ -161,8 +161,8 @@ namespace Statecraft.Game.UI
camp.style.display = DisplayStyle.Flex; housing.style.display = DisplayStyle.Flex;
camp.SetEnabled(campWhy == null); housing.SetEnabled(housingWhy == null);
// with no rule for an action there is no cost to show (it is disabled with the sim's reason anyway)
- camp.text = c.Rules.MapActions.TryGetValue(MapActions.TransitCamp, out var cr) ? text.Format("info.build_camp", PlayerText.Money(c, "treasury", cr.Cost)) : text["info.build_camp_plain"];
- housing.text = c.Rules.MapActions.TryGetValue(MapActions.Housing, out var hr) ? text.Format("info.build_housing", PlayerText.Money(c, "treasury", hr.Cost)) : text["info.build_housing_plain"];
+ camp.text = c.RulesAt(s.Date).MapActions.TryGetValue(MapActions.TransitCamp, out var cr) ? text.Format("info.build_camp", PlayerText.Money(c, "treasury", cr.Cost)) : text["info.build_camp_plain"];
+ housing.text = c.RulesAt(s.Date).MapActions.TryGetValue(MapActions.Housing, out var hr) ? text.Format("info.build_housing", PlayerText.Money(c, "treasury", hr.Cost)) : text["info.build_housing_plain"];
reason.text = string.Join("\n", new[] { campWhy, housingWhy }.Where(x => x != null).Distinct()); // the sim's reasons, each once
}
}
diff --git a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs b/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
index 031fe687d..ebc85f928 100644
--- a/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
+++ b/unity/Assets/Tests/EditMode/DefenceScreenTests.cs
@@ -214,7 +214,7 @@ public class DefenceScreenTests
var bridge = new SimBridge(GameSession.New(c, GoldenRun.Seed, Mode.Historical), Text);
new DefencePresenter(ui.Root, bridge, Text);
StringAssert.StartsWith("Minister of Defense (vacant) · Chief of Staff ", ui.Q<Label>("defence-command").text);
- Assert.AreEqual(Text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, bridge.State.Mobilization))),
+ Assert.AreEqual(Text.Format("defence.mob_cost", PlayerText.Money(c, "treasury", EconomySystem.MobilizationCost(c, bridge.State.Date, bridge.State.Mobilization))),
ui.Q<Label>("mob-cost").text);
}
}
diff --git a/unity/Assets/Tests/EditMode/PromoScreensTests.cs b/unity/Assets/Tests/EditMode/PromoScreensTests.cs
index 092b51f4c..07c5b1a2d 100644
--- a/unity/Assets/Tests/EditMode/PromoScreensTests.cs
+++ b/unity/Assets/Tests/EditMode/PromoScreensTests.cs
@@ -255,7 +255,7 @@ public class PromoScreensTests
Assert.AreEqual("Prime Minister\nMinister of Defense", ui.Q<Label>("lead-prime_minister-office").text);
var bar = ui.Q<UiBar>("mob-bar");
Assert.AreEqual((float)g.State.Mobilization, bar.Value, 1e-6f);
- Assert.AreEqual((float)SecuritySystem.MinMobilization(C, g.State.Rung), bar.Mark!.Value, 1e-6f, "the level's minimum is marked");
+ Assert.AreEqual((float)SecuritySystem.MinMobilization(C, g.State.Date, g.State.Rung), bar.Mark!.Value, 1e-6f, "the level's minimum is marked");
Assert.AreEqual(PlayerText.Percent(g.State.Mobilization), ui.Q<Label>("mob-percent").text);
Assert.AreEqual((float)g.State.Budget[DefencePresenter.BudgetLine], ui.Q<UiBar>("defence-budget-bar").Value, 1e-6f);
Assert.AreEqual($"{PlayerText.Percent(g.State.Budget[DefencePresenter.BudgetLine])} of budget spending", ui.Q<Label>("defence-budget-share").text);
@@ -265,7 +265,7 @@ public class PromoScreensTests
Assert.IsTrue(ui.Q<VisualElement>("rung-4").ClassListContains("rung-target"));
Assert.IsTrue(ui.Q<VisualElement>("rung-5").ClassListContains("rung-current"));
Assert.IsFalse(ui.Q<VisualElement>("rung-5").ClassListContains("rung-target"));
- Assert.AreEqual((float)SecuritySystem.MinMobilization(C, 4), bar.Mark!.Value, 1e-6f);
+ Assert.AreEqual((float)SecuritySystem.MinMobilization(C, g.State.Date, 4), bar.Mark!.Value, 1e-6f);
ui.Press("mob-down");
Assert.AreEqual((float)defence.ProposedMobilization, bar.Value, 1e-6f, "the bar shows the ordered call-up");
ui.Press("escalate");
@@ -321,11 +321,11 @@ public class PromoScreensTests
foreach (var seat in Cabinet.Lineup(C, s)) Person("seat-" + seat.Office.Id, seat.Holder);
foreach (var office in DefencePresenter.Leaders) Person("lead-" + office, Cabinet.Holder(C, s, office));
for (int rung = 1; rung <= 5; rung++) texts[$"rung-{rung}-name"] = Text[$"defence.rung{rung}"];
- var floor = SecuritySystem.MinMobilization(C, s.Rung);
- var callUp = SecuritySystem.EffectiveMobilization(C, s.Rung, s.Mobilization);
+ var floor = SecuritySystem.MinMobilization(C, s.Date, s.Rung);
+ var callUp = SecuritySystem.EffectiveMobilization(C, s.Date, s.Rung, s.Mobilization);
texts["mob-percent"] = PlayerText.Percent(callUp);
texts["mob-level"] = $"{PlayerText.Percent(callUp)} of reserves called up (level {s.Rung} needs at least {PlayerText.Percent(floor)})";
- texts["mob-cost"] = $"Costs {PlayerText.Money(C, "treasury", EconomySystem.MobilizationCost(C, callUp))} a year in pay and lost work";
+ texts["mob-cost"] = $"Costs {PlayerText.Money(C, "treasury", EconomySystem.MobilizationCost(C, s.Date, callUp))} a year in pay and lost work";
texts["mob-down"] = "-5%"; texts["mob-up"] = "+5%"; // the step, DefencePresenter.MobilizationStep
Assert.AreEqual(0.05, DefencePresenter.MobilizationStep, 1e-12);
texts["ceasefire"] = s.Rung == 5 ? Text.Format("defence.ceasefire", s.CeasefireWeeksLeft) : "";