A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(sim): every Cause names content and carries its unit; a guard that covers player commands
eyalgolan4cf5e1b29c19
diff --git a/content/model.yaml b/content/model.yamlindex 7999bf27d..f22095cb6 100644--- a/content/model.yaml+++ b/content/model.yaml@@ -24,6 +24,11 @@ effects:situations:- { id: food_crisis, indicator: food_supply, on_below: 0.30, off_above: 0.45, name: Food crisis }- { id: housing_crisis, indicator: housing, on_below: 0.25, off_above: 0.40, name: Housing crisis }+# Money the sim tracks (these three ids, in millions): the name and the currency prefix the player sees.+money:+ - { id: treasury, name: Treasury, prefix: 'IL ' }+ - { id: debt, name: Debt, prefix: 'IL ' }+ - { id: fx_reserves, name: Foreign currency, prefix: '$' }voter_groups:- { id: veterans, weights: { morale: 0.6, security: 0.4 } }- { id: new_immigrants, weights: { housing: 0.5, food_supply: 0.5 } }diff --git a/sim/Statecraft.Sim.Tests/CabinetTests.cs b/sim/Statecraft.Sim.Tests/CabinetTests.csindex ea49bc8f9..c13eba8ed 100644--- a/sim/Statecraft.Sim.Tests/CabinetTests.cs+++ b/sim/Statecraft.Sim.Tests/CabinetTests.cs@@ -61,7 +61,7 @@ public class CabinetTestsAssert.Equal("def_two", Offices.Holder(C, "finance_minister", s.Date)!.Id); // history itself is unchangedAssert.Equal(0.9, s.CoalitionStability, 9); // Def Two had no party: a seat lostAssert.Contains(why, w => w.System == "cabinet" && w.Message == "Loy Alist appointed Minister of Finance, replacing Def Two");- Assert.Contains(why, w => w.Target == "coalition_stability" && w.Message == "coalition stability -0.10 (Def Two lost the Minister of Finance)");+ Assert.Contains(why, w => w.Target == "coalition_stability" && w.Message == "coalition stability -10.0% (Def Two lost the Minister of Finance)");}[Fact]@@ -72,7 +72,7 @@ public class CabinetTestsvar why = new List<Cause>();Assert.Null(Cabinet.Appoint(C, s, "finance_minister", "loyal_two", why));Assert.Equal(0.9 - 0.03, s.CoalitionStability, 9);- Assert.Contains(why, w => w.Message == "coalition stability -0.03 (Alpha resents the reshuffle)");+ Assert.Contains(why, w => w.Message == "coalition stability -3.0% (Alpha resents the reshuffle)");}[Theory]diff --git a/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs b/sim/Statecraft.Sim.Tests/EconomyM3Tests.csindex 7f8739b6b..31a4eda6b 100644--- a/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs+++ b/sim/Statecraft.Sim.Tests/EconomyM3Tests.cs@@ -27,7 +27,7 @@ public class EconomyM3Testsvar why = new List<Cause>();EconomySystem.Apply(c, s, 0.25, why);Assert.Equal(50 + 5 + 2 - 0.025, s.FxReserves, 9); // exports 20/4, inflow 8/4, imports 0.0001*1000/4- Assert.Contains(why, w => w.Target == "fx_reserves" && w.Message.Contains("donations and loans 2.00"));+ Assert.Contains(why, w => w.Target == "fx_reserves" && w.Message.Contains("donations and loans $2.0m"));}[Fact]@@ -41,7 +41,7 @@ public class EconomyM3TestsAssert.Contains(EconomySystem.FxCrisis, s.ActiveSituations);Assert.Equal(0.4 - 0.1, s.Indicators["food_supply"], 9);Assert.Equal(-0.1, s.IndicatorShifts["food_supply"], 9);- Assert.Contains(why, w => w.Target == "food_supply" && w.Message == "Food supply -0.100 (foreign currency crisis: food imports cut)");+ Assert.Contains(why, w => w.Target == "food_supply" && w.Message == "Food supply -10.0% (foreign currency crisis: food imports cut)");}[Fact]diff --git a/sim/Statecraft.Sim.Tests/EffectsTests.cs b/sim/Statecraft.Sim.Tests/EffectsTests.csindex 1445d2087..1baaa8ab8 100644--- a/sim/Statecraft.Sim.Tests/EffectsTests.cs+++ b/sim/Statecraft.Sim.Tests/EffectsTests.cs@@ -57,7 +57,7 @@ public class EffectsTestsAssert.Equal(0.64, s.Indicators["food_supply"], 9); // 0.4 + 0.14 + 0.1var cause = Assert.Single(why, w => w.System == "effects" && w.Target == "food_supply");Assert.Equal(s.Indicators["food_supply"] - before, cause.Delta, 12);- Assert.Equal("Food supply +0.240 (Rations feed people, More rations)", cause.Message);+ Assert.Equal("Food supply +24.0% (Rations feed people, More rations)", cause.Message);}[Fact]diff --git a/sim/Statecraft.Sim.Tests/EventTests.cs b/sim/Statecraft.Sim.Tests/EventTests.csindex 48c43cbcb..24c60a6df 100644--- a/sim/Statecraft.Sim.Tests/EventTests.cs+++ b/sim/Statecraft.Sim.Tests/EventTests.cs@@ -524,7 +524,7 @@ options:var s = State(c, new DateTime(1948, 6, 1)); var why = new List<Cause>();EventSystem.Trigger(c, s, why);Assert.Null(EventSystem.Choose(c, s, "shortage", "import", why));- Assert.Contains(why, w => w.Message == "Foreign currency reserves +0.00 (Bread lines)");+ Assert.Contains(why, w => w.Message == "Foreign currency +$0.0m (Bread lines)");Assert.DoesNotContain(why, w => w.Message.Contains("-+"));}diff --git a/sim/Statecraft.Sim.Tests/Fixture.cs b/sim/Statecraft.Sim.Tests/Fixture.csindex 8793beaf8..6a1bfcd8b 100644--- a/sim/Statecraft.Sim.Tests/Fixture.cs+++ b/sim/Statecraft.Sim.Tests/Fixture.cs@@ -115,6 +115,10 @@ situations:on_below: 0.3off_above: 0.45name: Hunger+money:+ - { id: treasury, name: Treasury, prefix: 'IL ' }+ - { id: debt, name: Debt, prefix: 'IL ' }+ - { id: fx_reserves, name: Foreign currency, prefix: '$' }voter_groups:- id: everyoneweights: { morale: 1.0 }diff --git a/sim/Statecraft.Sim.Tests/MapActionTests.cs b/sim/Statecraft.Sim.Tests/MapActionTests.csindex d2de8f533..32006249a 100644--- a/sim/Statecraft.Sim.Tests/MapActionTests.cs+++ b/sim/Statecraft.Sim.Tests/MapActionTests.cs@@ -32,7 +32,7 @@ public class MapActionTestsAssert.Equal(housing + 0.05, s.Indicators["housing"], 9);Assert.Equal(morale - 0.02, s.Indicators["morale"], 9);Assert.Equal("transit_camp", MapActions.At(s, 2, 0)!.Action);- Assert.Contains(why, w => w.System == "map" && w.Message == "a transit camp at (2, 0): cost 2.0, housing +0.050, morale -0.020");+ Assert.Contains(why, w => w.System == "map" && w.Message == "A transit camp at (2, 0): cost IL 2.0m, Housing +5.0%, Morale -2.0%");}[Fact]@@ -44,7 +44,7 @@ public class MapActionTestsAssert.Null(MapActions.Apply(C, s, "housing", 1, 1, why));Assert.Equal(0, s.Treasury);Assert.Equal(5, s.Debt, 9);- Assert.Contains(why, w => w.Message == "borrowed 5.00 to build a housing project");+ Assert.Contains(why, w => w.Message == "borrowed IL 5.0m to build a housing project");}[Fact]diff --git a/sim/Statecraft.Sim.Tests/PlayerTextTests.cs b/sim/Statecraft.Sim.Tests/PlayerTextTests.csindex 50c69b570..570a74d86 100644--- a/sim/Statecraft.Sim.Tests/PlayerTextTests.cs+++ b/sim/Statecraft.Sim.Tests/PlayerTextTests.cs@@ -41,7 +41,7 @@ public class PlayerTextTestsAssert.Contains(messages, m => m.EndsWith("immigrants arrived (the Americas and Oceania)", StringComparison.Ordinal));Assert.Contains(messages, m => m.EndsWith("immigrants arrived (country of origin not recorded)", StringComparison.Ordinal));Assert.Contains(messages, m => m.StartsWith("Morale ", StringComparison.Ordinal) && m.Contains("Homes lift morale"));- Assert.Contains(messages, m => m.StartsWith("International standing +0.05 (Armistice with Egypt)", StringComparison.Ordinal));+ Assert.Contains(messages, m => m.StartsWith("International standing +5.0% (Armistice with Egypt)", StringComparison.Ordinal));Assert.Contains(messages, m => m.Contains("elected 25 January 1949"));}@@ -78,4 +78,178 @@ public class PlayerTextTestsAssert.Equal(file, ex.File);Assert.Equal(field, ex.Field);}++ // ---- Fix round 1 (review I1, I2, M3) ----++ static readonly Content Real = ContentLoader.Load(RealContentTests.ContentRoot());++ /// <summary>Every content id a Cause could leak: indicators, policies, effects, situations, money, regions, offices+ /// and events.</summary>+ static IEnumerable<string> ContentIds(Content c) =>+ c.Indicators.Select(x => x.Id).Concat(c.Policies.Select(x => x.Id)).Concat(c.Effects.Select(x => x.Id))+ .Concat(c.Situations.Select(x => x.Id)).Concat(c.Money.Select(x => x.Id)).Concat(c.Regions.Select(x => x.Id))+ .Concat(c.Offices.Select(x => x.Id)).Concat(c.Events.Select(x => x.Id)).Distinct();++ /// <summary>Where an id would appear in a Cause: a snake_case id anywhere as a whole word; a one-word id ("morale",+ /// "treasury", "asia") at the start, alone in parentheses or a list, before a signed number, "set to", "=",+ /// "began"/"ended", or after "from" (case-sensitive: the display names are capitalised or phrased).</summary>+ static Regex IdPattern(string id)+ {+ var e = Regex.Escape(id);+ return id.Contains("_")+ ? new Regex($@"\b{e}\b")+ : new Regex($@"(^|\(|, |/|from ){e}(\)|,|/| [+-]\d| set to| =| began| ended|$)");+ }++ static List<string> Leaks(Content c, IEnumerable<string> messages)+ {+ var patterns = ContentIds(c).Select(id => (id, re: IdPattern(id))).ToList();+ return messages.Distinct().SelectMany(m => patterns.Where(p => p.re.IsMatch(m)).Select(p => $"'{p.id}' in: {m}")).ToList();+ }++ /// <summary>The player's own commands from mid-1950 on (historical play up to then): policy votes (passed and lost),+ /// an appointment, a budget, both map actions, and every option of every event, each from a state where the event+ /// is pending. Returns every Cause.</summary>+ internal static List<Cause> ScriptedCauses(Content c)+ {+ var causes = new List<Cause>();+ foreach (var e in c.Events)+ foreach (var o in e.Options)+ {+ var g = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);+ g.Date = e.From; g.PendingEvents.Clear(); g.PendingEvents.Add(e.Id);+ var r = Simulation.Step(c, g, new Command[] { new ChooseEventOption(e.Id, o.Id) });+ Assert.Empty(r.Rejected);+ causes.AddRange(r.Why);+ }+ var s = GoldenRun.Play(c, new DateTime(1950, 6, 15));+ bool appointed = false, budget = false, camp = false, housing = false;+ for (int turn = 0; turn < 60 && s.GameOver == null; turn++)+ {+ var cmds = new List<Command>(HistoricalAI.Commands(c, s));+ cmds.Add(new SetPolicy("rationing", turn % 2 == 0 ? 0.9 : 0.2));+ if (!appointed)+ {+ var pick = c.Offices.SelectMany(o => Cabinet.Candidates(c, s, o.Id).Where(x => x.reason == null).Select(x => (o.Id, x.person.Id))).FirstOrDefault();+ if (pick.Item1 != null) cmds.Add(new Appoint(pick.Item1, pick.Item2));+ }+ if (!budget)+ {+ var first = s.Budget.Keys.OrderBy(k => k, StringComparer.Ordinal).First();+ cmds.Add(new AllocateBudget(new Dictionary<string, double>(s.Budget.ToDictionary(k => k.Key, k => k.Value)) { [first] = s.Budget[first] }));+ }+ foreach (var (action, done) in new[] { (MapActions.TransitCamp, camp), (MapActions.Housing, housing) })+ {+ if (done) continue;+ var hex = c.Hexes.FirstOrDefault(h => MapActions.Check(c, s, action, h.Q, h.R) == null);+ if (hex != null) cmds.Add(new MapAction(action, hex.Q, hex.R));+ }+ var r = Simulation.Step(c, s, cmds);+ causes.AddRange(r.Why);+ appointed |= r.Why.Any(w => w.System == "cabinet");+ budget |= cmds.OfType<AllocateBudget>().Any() && !r.Rejected.Any(x => x.Command is AllocateBudget);+ camp |= r.Why.Any(w => w.System == "map" && w.Target == MapActions.TransitCamp);+ housing |= r.Why.Any(w => w.System == "map" && w.Target == MapActions.Housing);+ s = r.State;+ }+ Assert.True(appointed && budget && camp && housing, $"the script ran every command (appointed {appointed}, budget {budget}, camp {camp}, housing {housing})");+ Assert.Contains(causes, w => w.System == "policy");+ Assert.Contains(causes, w => w.System == "politics" && w.Message.Contains(" voted down "));+ return causes;+ }++ static List<Cause> AllCauses(Content c)+ {+ var all = new List<Cause>();+ var s = Simulation.NewGame(c, GoldenRun.Seed, Mode.Historical);+ for (int turn = 0; turn < 1000 && s.Date < GoldenRun.Until1952 && s.GameOver == null; turn++)+ {+ var r = Simulation.Step(c, s, HistoricalAI.Commands(c, s));+ all.AddRange(r.Why);+ s = r.State;+ }+ all.AddRange(ScriptedCauses(c));+ return all;+ }++ [Fact]+ public void NoCauseFromAnyCommandShowsAContentId()+ {+ var leaks = Leaks(Real, AllCauses(Real).Select(w => w.Message));+ Assert.True(leaks.Count == 0, "Cause text shows content ids:\n" + string.Join("\n", leaks.Take(60)));+ }++ /// <summary>The guard itself: a one-word id in an id position is caught (the old snake_case regex missed these).</summary>+ [Theory]+ [InlineData("rationing set to 0.50", "rationing")]+ [InlineData("treasury +1.23 (tax 2.00)", "treasury")]+ [InlineData("14 immigrants arrived from asia", "asia")]+ [InlineData("Morale +4.1% (homes_lift_morale)", "homes_lift_morale")]+ [InlineData("Food supply +5.0% (austerity_1949)", "austerity_1949")]+ public void TheGuardCatchesOneWordIds(string message, string id) =>+ Assert.Contains(Leaks(Real, new[] { message }), l => l.StartsWith($"'{id}'", StringComparison.Ordinal));++ [Theory]+ [InlineData("Impose rationing")]+ [InlineData("A housing project at (3, 4): cost IL 1.5m")]+ [InlineData("reserve call-up raised to 80%, the minimum for security level 5")]+ public void TheGuardLeavesPlainEnglishAlone(string message) => Assert.Empty(Leaks(Real, new[] { message }));++ /// <summary>Review I2: money Causes carry their currency (IL or $, in millions); indicator Causes use the top bar's+ /// 0-100 scale with "%".</summary>+ [Fact]+ public void EveryCauseNumberCarriesItsUnit()+ {+ var money = Real.Money.Select(m => m.Id).ToHashSet();+ var indicators = Real.Indicators.Select(i => i.Id).ToHashSet();+ var bad = new List<string>();+ foreach (var w in AllCauses(Real))+ {+ if (money.Contains(w.Target) && !Regex.IsMatch(w.Message, @"[+-]?(IL |\$)\d+\.\dm"))+ bad.Add("money without a unit: " + w.Message);+ if (indicators.Contains(w.Target) && w.System != "situations" && !Regex.IsMatch(w.Message, @"[+-]\d+\.\d%"))+ bad.Add("indicator change not on the 0-100 % scale: " + w.Message);+ if (w.Message.Contains("stability") && !w.Message.Contains("%"))+ bad.Add("stability without %: " + w.Message);+ }+ Assert.True(bad.Count == 0, string.Join("\n", bad.Distinct().Take(40)));+ }++ [Fact]+ public void PlayerTextFormatsMoneyAndTheIndicatorScale()+ {+ Assert.Equal("IL 18.6m", PlayerText.Money(Real, "treasury", 18.6));+ Assert.Equal("$41.5m", PlayerText.Money(Real, "fx_reserves", 41.5));+ Assert.Equal("+IL 1.2m", PlayerText.MoneyChange(Real, "treasury", 1.23));+ Assert.Equal("-$0.4m", PlayerText.MoneyChange(Real, "fx_reserves", -0.4));+ Assert.Equal("+$0.0m", PlayerText.MoneyChange(Real, "fx_reserves", -0.004));+ Assert.Equal(30.0, PlayerText.Scale(0.3), 9);+ Assert.Equal("55%", PlayerText.Percent(0.55));+ Assert.Equal("+4.1%", PlayerText.PercentChange(0.041));+ Assert.Equal("Treasury -IL 2.0m", PlayerText.Change(Real, "treasury", -2));+ Assert.Equal("Morale +5.0%", PlayerText.Change(Real, "morale", 0.05));+ Assert.Equal("Foreign currency", PlayerText.Target(Real, "fx_reserves"));+ }++ /// <summary>Review M3: no silent fallback to the id.</summary>+ [Fact]+ public void AnUnknownIdIsAnError()+ {+ Assert.Throws<InvalidOperationException>(() => PlayerText.Target(Real, "no_such_thing"));+ Assert.Throws<InvalidOperationException>(() => PlayerText.Region(Real, "atlantis"));+ Assert.Throws<InvalidOperationException>(() => PlayerText.Money(Real, "morale", 1));+ }++ /// <summary>Review M3: the money names and currency prefixes come from content and are validated at load.</summary>+ [Theory]+ [InlineData(" - { id: treasury, name: Treasury, prefix: 'IL ' }\n", " - { id: treasury, prefix: 'IL ' }\n", "money[treasury].name")]+ [InlineData(" - { id: fx_reserves, name: Foreign currency, prefix: '$' }\n", " - { id: fx_reserves, name: Foreign currency }\n", "money[fx_reserves].prefix")]+ [InlineData(" - { id: debt, name: Debt, prefix: 'IL ' }\n", "", "money")]+ [InlineData(" - { id: debt, name: Debt, prefix: 'IL ' }\n", " - { id: debt, name: Debt, prefix: 'IL ' }\n - { id: gold, name: Gold, prefix: 'g' }\n", "money[gold].id")]+ public void MoneyNamesAreRequired(string from, string to, string field)+ {+ var ex = ValidationTests.Bad("model.yaml", from, to);+ Assert.Equal("model.yaml", ex.File);+ Assert.Equal(field, ex.Field);+ }}diff --git a/sim/Statecraft.Sim.Tests/SimTests.cs b/sim/Statecraft.Sim.Tests/SimTests.csindex 1a6149fc1..e62ea3f78 100644--- a/sim/Statecraft.Sim.Tests/SimTests.cs+++ b/sim/Statecraft.Sim.Tests/SimTests.cs@@ -164,7 +164,7 @@ options:var r = Simulation.Step(C, s0, new Command[] { new SetPolicy("rationing", 0.5) });Assert.Empty(r.Rejected);Assert.Equal(0.5, r.State.Policies["rationing"]);- Assert.Contains(r.Why, w => w.System == "policy" && w.Message == "Rationing set to 0.50");+ Assert.Contains(r.Why, w => w.System == "policy" && w.Message == "Rationing set to 50%");}[Fact]@@ -210,7 +210,7 @@ options:var r = Simulation.Step(C, s0, new Command[] { cmd, cmd, cmd });Assert.Equal(new[] { "Not enough attention (need 1.0, have 0.0)" }, r.Rejected.Select(x => x.Reason));Assert.Equal(0.0, r.State.Policies["rationing"]);- Assert.Equal(2, r.Why.Count(w => w.System == "politics" && w.Target == "rationing" && w.Message == "House voted down Rationing 0.90"));+ Assert.Equal(2, r.Why.Count(w => w.System == "politics" && w.Target == "rationing" && w.Message == "House voted down Rationing at 90%"));}[Theory]diff --git a/sim/Statecraft.Sim/Cabinet.cs b/sim/Statecraft.Sim/Cabinet.csindex 373de16ac..ff2a5162f 100644--- a/sim/Statecraft.Sim/Cabinet.cs+++ b/sim/Statecraft.Sim/Cabinet.cs@@ -121,8 +121,8 @@ namespace Statecraft.Simvar before = s.CoalitionStability;s.CoalitionStability = Math.Max(0, before - cost);var who = oldParty == "" ? displaced.Name : c.Parties.First(p => p.Id == oldParty).Name;- why.Add(new Cause("politics", "coalition_stability", s.CoalitionStability - before, FormattableString.Invariant(- $"coalition stability {s.CoalitionStability - before:+0.00;-0.00;+0.00} ({who} {(sameParty ? "resents the reshuffle" : "lost the " + office.Title)})")));+ why.Add(new Cause("politics", "coalition_stability", s.CoalitionStability - before, (+ $"coalition stability {PlayerText.PercentChange(s.CoalitionStability - before)} ({who} {(sameParty ? "resents the reshuffle" : "lost the " + office.Title)})")));return null;}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex e2ffa9ed2..eb5a5775a 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -168,6 +168,15 @@ namespace Statecraft.Simpublic double Morale { get; set; }}+ /// <summary>Money the sim tracks (model.yaml money): treasury, debt and fx_reserves, each with the name and currency+ /// prefix the player sees ("IL " for Israeli pounds, "$" for foreign currency; amounts are in millions).</summary>+ public sealed class MoneyAccount+ {+ public string Id { get; set; } = "";+ public string Name { get; set; } = "";+ public string Prefix { get; set; } = "";+ }+/// <summary>An origin group of immigrants (aliyah.yaml regions): the key of AliyahPeriod.Origins.</summary>public sealed class Region{@@ -265,6 +274,8 @@ namespace Statecraft.Simpublic List<AliyahPeriod> Aliyah = new List<AliyahPeriod>();/// <summary>Origin groups of the aliyah series, with display names (aliyah.yaml regions).</summary>public List<Region> Regions = new List<Region>();+ /// <summary>Display names and currency prefixes of the treasury, debt and foreign currency reserves (model.yaml money).</summary>+ public List<MoneyAccount> Money = new List<MoneyAccount>();public List<PopulationAnchor> PopulationAnchors = new List<PopulationAnchor>();public List<GameEvent> Events = new List<GameEvent>();List<MapHex> _hexes = new List<MapHex>();diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 30e4e5e61..b0fd2714a 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -25,6 +25,7 @@ namespace Statecraft.Simpublic List<Situation> Situations { get; set; } = new List<Situation>();public List<VoterGroup> VoterGroups { get; set; } = new List<VoterGroup>();public List<Actor> Actors { get; set; } = new List<Actor>();+ public List<MoneyAccount> Money { get; set; } = new List<MoneyAccount>();}sealed class AliyahFile{@@ -159,7 +160,7 @@ namespace Statecraft.Simc.Governments = Read<GovernmentsFile>(readFile, "governments.yaml").Governments;var m = Read<ModelFile>(readFile, "model.yaml");c.Indicators = m.Indicators; c.Policies = m.Policies; c.Effects = m.Effects;- c.Situations = m.Situations; c.VoterGroups = m.VoterGroups; c.Actors = m.Actors;+ c.Situations = m.Situations; c.VoterGroups = m.VoterGroups; c.Actors = m.Actors; c.Money = m.Money;c.Rules = Read<Rules>(readFile, "rules.yaml");var aliyah = Read<AliyahFile>(readFile, "aliyah.yaml");c.Aliyah = aliyah.Series; c.Regions = aliyah.Regions;@@ -288,6 +289,7 @@ namespace Statecraft.SimUnique("model.yaml", "situations", c.Situations.Select(s => s.Id));Unique("model.yaml", "voter_groups", c.VoterGroups.Select(v => v.Id));Unique("model.yaml", "actors", c.Actors.Select(a => a.Id));+ Unique("model.yaml", "money", c.Money.Select(a => a.Id));Unique("aliyah.yaml", "regions", c.Regions.Select(g => g.Id));// Display names (spec: player-facing text): Cause messages show these, never the ids.foreach (var i in c.Indicators) Named("model.yaml", $"indicators[{i.Id}].name", i.Name);@@ -295,6 +297,15 @@ namespace Statecraft.Simforeach (var e in c.Effects) Named("model.yaml", $"effects[{e.Id}].name", e.Name);foreach (var s in c.Situations) Named("model.yaml", $"situations[{s.Id}].name", s.Name);foreach (var g in c.Regions) Named("aliyah.yaml", $"regions[{g.Id}].name", g.Name);+ foreach (var a in c.Money)+ {+ if (Array.IndexOf(PlayerText.MoneyIds, a.Id) < 0)+ throw new ContentException("model.yaml", $"money[{a.Id}].id", $"must be one of {string.Join(", ", PlayerText.MoneyIds)}");+ Named("model.yaml", $"money[{a.Id}].name", a.Name);+ if (a.Prefix.Length == 0) throw new ContentException("model.yaml", $"money[{a.Id}].prefix", "required (the currency the player sees, e.g. 'IL ' or '$')");+ }+ var missingMoney = PlayerText.MoneyIds.FirstOrDefault(id => c.Money.All(a => a.Id != id));+ if (missingMoney != null) throw new ContentException("model.yaml", "money", $"missing {missingMoney}");foreach (var p in c.Policies)if (indicators.Contains(p.Id)) throw new ContentException("model.yaml", $"policies[{p.Id}].id", "same id as an indicator (effect sources would be ambiguous)");diff --git a/sim/Statecraft.Sim/EconomySystem.cs b/sim/Statecraft.Sim/EconomySystem.csindex 7baaffaf9..56263535f 100644--- a/sim/Statecraft.Sim/EconomySystem.cs+++ b/sim/Statecraft.Sim/EconomySystem.cs@@ -37,11 +37,11 @@ namespace Statecraft.Simvar revenue = flows.Tax; var spending = flows.Spending; var mobilization = flows.Mobilization;s.Treasury += revenue - spending - mobilization;why.Add(new Cause("economy", "treasury", revenue - spending - mobilization,- FormattableString.Invariant($"treasury {revenue - spending - mobilization:+0.00;-0.00;+0.00} (tax {revenue:0.00}, spending {spending:0.00}, reserve call-up {mobilization:0.00})")));+ $"{PlayerText.Change(c, "treasury", revenue - spending - mobilization)} (tax {PlayerText.Money(c, "treasury", revenue)}, spending {PlayerText.Money(c, "treasury", spending)}, reserve call-up {PlayerText.Money(c, "treasury", mobilization)})"));if (s.Treasury < 0){s.Debt += -s.Treasury;- why.Add(new Cause("economy", "debt", -s.Treasury, FormattableString.Invariant($"borrowed {-s.Treasury:0.00} to cover the deficit")));+ why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} to cover the deficit"));s.Treasury = 0;}@@ -50,7 +50,7 @@ namespace Statecraft.Simvar imports = r.ImportsPerCapitaPerYear * pop * yearFraction;var net = exports + inflow - imports;s.FxReserves += net;- why.Add(new Cause("economy", "fx_reserves", net, FormattableString.Invariant($"foreign currency {net:+0.00;-0.00;+0.00} (exports {exports:0.00}, donations and loans {inflow:0.00}, imports {imports:0.00})")));+ why.Add(new Cause("economy", "fx_reserves", net, $"{PlayerText.Change(c, "fx_reserves", net)} (exports {PlayerText.Money(c, "fx_reserves", exports)}, donations and loans {PlayerText.Money(c, "fx_reserves", inflow)}, imports {PlayerText.Money(c, "fx_reserves", imports)})"));bool on = s.ActiveSituations.Contains(FxCrisis);if (!on && s.FxReserves < 0) { s.ActiveSituations.Add(FxCrisis); why.Add(new Cause("economy", FxCrisis, 1, "Foreign currency reserves are exhausted")); }@@ -61,7 +61,7 @@ namespace Statecraft.Sim{var change = EffectsSystem.Shift(c, s, "food_supply", r.FxCrisisFoodPerYear * yearFraction);if (change != 0)- why.Add(new Cause("economy", "food_supply", change, FormattableString.Invariant($"{PlayerText.Target(c, "food_supply")} {change:+0.000;-0.000;+0.000} (foreign currency crisis: food imports cut)")));+ why.Add(new Cause("economy", "food_supply", change, $"{PlayerText.Change(c, "food_supply", change)} (foreign currency crisis: food imports cut)"));}}diff --git a/sim/Statecraft.Sim/EffectsSystem.cs b/sim/Statecraft.Sim/EffectsSystem.csindex 1e2a7c970..9a75365f2 100644--- a/sim/Statecraft.Sim/EffectsSystem.cs+++ b/sim/Statecraft.Sim/EffectsSystem.cs@@ -57,7 +57,7 @@ namespace Statecraft.Simif (Math.Abs(delta) <= 1e-9) continue;var names = c.Effects.Where(e => e.Target == i.Id && moved.Contains(e.Id)).Select(e => e.Name).ToList();var from = names.Count > 0 ? $" ({string.Join(", ", names)})" : "";- why.Add(new Cause("effects", i.Id, delta, FormattableString.Invariant($"{i.Name} {delta:+0.000;-0.000;+0.000}{from}")));+ why.Add(new Cause("effects", i.Id, delta, $"{PlayerText.Change(c, i.Id, delta)}{from}"));}UpdateSituations(c, s, why);}@@ -91,8 +91,8 @@ namespace Statecraft.Simbool on = s.ActiveSituations.Contains(sit.Id);bool turnOn = sit.OnBelow.HasValue ? v < sit.OnBelow.Value : v > sit.OnAbove!.Value;bool turnOff = sit.OffAbove.HasValue ? v > sit.OffAbove.Value : v < sit.OffBelow!.Value;- if (!on && turnOn) { s.ActiveSituations.Add(sit.Id); why.Add(new Cause("situations", sit.Id, 1, FormattableString.Invariant($"{sit.Name} began ({PlayerText.Target(c, sit.Indicator)} = {v:0.00})"))); }- else if (on && turnOff) { s.ActiveSituations.Remove(sit.Id); why.Add(new Cause("situations", sit.Id, -1, FormattableString.Invariant($"{sit.Name} ended ({PlayerText.Target(c, sit.Indicator)} = {v:0.00})"))); }+ if (!on && turnOn) { s.ActiveSituations.Add(sit.Id); why.Add(new Cause("situations", sit.Id, 1, $"{sit.Name} began ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})")); }+ else if (on && turnOff) { s.ActiveSituations.Remove(sit.Id); why.Add(new Cause("situations", sit.Id, -1, $"{sit.Name} ended ({PlayerText.Target(c, sit.Indicator)} at {PlayerText.Percent(v)})")); }}}diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csindex 3ec009e7e..012653ad8 100644--- a/sim/Statecraft.Sim/EventSystem.cs+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -64,12 +64,12 @@ namespace Statecraft.Simif (fx.Target == "treasury") s.Treasury += fx.Delta;else if (fx.Target == "fx_reserves") s.FxReserves += fx.Delta;else change = EffectsSystem.Shift(c, s, fx.Target, fx.Delta);- why.Add(new Cause("events", fx.Target, change, FormattableString.Invariant($"{PlayerText.Target(c, fx.Target)} {change:+0.00;-0.00;+0.00} ({title})")));+ why.Add(new Cause("events", fx.Target, change, $"{PlayerText.Change(c, fx.Target, change)} ({title})"));}foreach (var kv in o.SetPolicy.OrderBy(k => k.Key, StringComparer.Ordinal)){s.Policies[kv.Key] = kv.Value;- why.Add(new Cause("events", kv.Key, kv.Value, FormattableString.Invariant($"{PlayerText.Target(c, kv.Key)} set to {kv.Value:0.00} ({title})")));+ why.Add(new Cause("events", kv.Key, kv.Value, $"{PlayerText.Target(c, kv.Key)} set to {PlayerText.Percent(kv.Value)} ({title})"));}if (o.SetRung.HasValue) SecuritySystem.SetRung(c, s, o.SetRung.Value, why);}diff --git a/sim/Statecraft.Sim/MapActions.cs b/sim/Statecraft.Sim/MapActions.csindex 5f8d2845c..443843256 100644--- a/sim/Statecraft.Sim/MapActions.cs+++ b/sim/Statecraft.Sim/MapActions.cs@@ -37,6 +37,8 @@ namespace Statecraft.Simstatic string Name(string action) => action == TransitCamp ? "a transit camp" : "a housing project";+ static string Capitalised(string s) => char.ToUpperInvariant(s[0]) + s.Substring(1);+/// <summary>Null when <paramref name="action"/> may be placed on (q, r) now, else the reason shown to the player.</summary>public static string? Check(Content c, GameState s, string action, int q, int r){@@ -76,13 +78,13 @@ namespace Statecraft.Simif (s.Treasury < 0){s.Debt += -s.Treasury;- why.Add(new Cause("economy", "debt", -s.Treasury, FormattableString.Invariant($"borrowed {-s.Treasury:0.00} to build {Name(action)}")));+ why.Add(new Cause("economy", "debt", -s.Treasury, $"borrowed {PlayerText.Money(c, "debt", -s.Treasury)} to build {Name(action)}"));s.Treasury = 0;}var housing = rule.Housing == 0 ? 0 : EffectsSystem.Shift(c, s, "housing", rule.Housing);var morale = rule.Morale == 0 ? 0 : EffectsSystem.Shift(c, s, "morale", rule.Morale);why.Add(new Cause("map", action, 1, FormattableString.Invariant(- $"{Name(action)} at ({q}, {r}): cost {rule.Cost:0.0}, housing {housing:+0.000;-0.000;+0.000}, morale {morale:+0.000;-0.000;+0.000}")));+ $"{Capitalised(Name(action))} at ({q}, {r}): cost {PlayerText.Money(c, "treasury", rule.Cost)}, {PlayerText.Change(c, "housing", housing)}, {PlayerText.Change(c, "morale", morale)}")));return null;}}diff --git a/sim/Statecraft.Sim/PlayerText.cs b/sim/Statecraft.Sim/PlayerText.csindex 7e6582c6f..115bd27ee 100644--- a/sim/Statecraft.Sim/PlayerText.cs+++ b/sim/Statecraft.Sim/PlayerText.cs@@ -5,26 +5,61 @@ using System.Linq;namespace Statecraft.Sim{/// <summary>Player-facing wording shared by the sim (Cause text, refusal reasons) and the UI: the one date format- /// ("15 May 1948") and the display names content gives its ids. No player-facing string shows a content id or an- /// ISO date (spec: player-facing text).</summary>+ /// ("15 May 1948"), the display names content gives its ids, money with its currency ("IL 18.6m", "$41.5m"), and the+ /// one scale for indicators (0-100, as the top bar shows them, written with "%"). No player-facing string shows a+ /// content id, an ISO date or a bare number (spec: player-facing text; playtest 1 items 4, 5 and 7). An id content+ /// does not name is an error, never shown as it is.</summary>public static class PlayerText{+ /// <summary>The money the sim tracks; model.yaml money names each one.</summary>+ public static readonly string[] MoneyIds = { "treasury", "debt", "fx_reserves" };+/// <summary>"15 May 1948".</summary>public static string Date(DateTime d) => d.ToString("d MMMM yyyy", CultureInfo.InvariantCulture);/// <summary>"May 1948".</summary>public static string Month(DateTime d) => d.ToString("MMMM yyyy", CultureInfo.InvariantCulture);+ static InvalidOperationException Unknown(string what, string id) =>+ new InvalidOperationException($"no display name for {what} '{id}' (content validation should have caught this)");+/// <summary>The display name of an aliyah origin group (aliyah.yaml regions).</summary>- public static string Region(Content c, string id) => c.Regions.FirstOrDefault(r => r.Id == id)?.Name ?? id;+ public static string Region(Content c, string id) => c.Regions.FirstOrDefault(r => r.Id == id)?.Name ?? throw Unknown("region", id);++ /// <summary>The display name of what a cause changes: an indicator or policy (model.yaml names), or money+ /// (model.yaml money).</summary>+ public static string Target(Content c, string id) =>+ 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);++ public static bool IsMoney(Content c, string id) => c.Money.Any(m => m.Id == id);++ static MoneyAccount Account(Content c, string id) => c.Money.FirstOrDefault(m => m.Id == id) ?? throw Unknown("money", id);- /// <summary>The display name of what a cause changes: an indicator or policy (model.yaml names), the treasury or- /// the foreign currency reserves.</summary>- public static string Target(Content c, string id) => id switch+ /// <summary>An amount in millions with its currency: "IL 18.6m", "$41.5m".</summary>+ public static string Money(Content c, string id, double millions) =>+ Account(c, id).Prefix + millions.ToString("0.0", CultureInfo.InvariantCulture) + "m";++ /// <summary>A signed change in millions with its currency, sign first: "+IL 1.2m", "-$0.4m" (a change that rounds to+ /// zero reads "+IL 0.0m", never "-IL 0.0m").</summary>+ public static string MoneyChange(Content c, string id, double millions){- "treasury" => "Treasury",- "fx_reserves" => "Foreign currency reserves",- _ => c.Indicators.FirstOrDefault(i => i.Id == id)?.Name ?? c.Policies.FirstOrDefault(p => p.Id == id)?.Name ?? id,- };+ var abs = Math.Abs(millions).ToString("0.0", CultureInfo.InvariantCulture);+ var sign = millions < 0 && abs != "0.0" ? "-" : "+";+ return sign + Account(c, id).Prefix + abs + "m";+ }++ /// <summary>An indicator level (0..1) or a share on the scale the player sees: 0..100.</summary>+ public static double Scale(double level) => level * 100;++ /// <summary>"55%" for a level of 0.55.</summary>+ public static string Percent(double level) => Scale(level).ToString("0", CultureInfo.InvariantCulture) + "%";++ /// <summary>"+4.1%" for a change of 0.041 (points on the 0-100 scale).</summary>+ public static string PercentChange(double change) => Scale(change).ToString("+0.0;-0.0;+0.0", CultureInfo.InvariantCulture) + "%";++ /// <summary>"Morale +4.1%" or "Treasury -IL 2.0m": the name and the change, in the target's unit.</summary>+ public static string Change(Content c, string id, double change) =>+ Target(c, id) + " " + (IsMoney(c, id) ? MoneyChange(c, id, change) : PercentChange(change));}}diff --git a/sim/Statecraft.Sim/PoliticsSystem.cs b/sim/Statecraft.Sim/PoliticsSystem.csindex 7dfc7a6ba..55d1771b3 100644--- a/sim/Statecraft.Sim/PoliticsSystem.cs+++ b/sim/Statecraft.Sim/PoliticsSystem.cs@@ -36,7 +36,7 @@ namespace Statecraft.Simvar old = s.CoalitionStability;s.CoalitionStability = old + (EffectsSystem.Approval(c, s) - old) * Math.Min(1.0, yearFraction * 2);if (Math.Abs(s.CoalitionStability - old) > 1e-9)- why.Add(new Cause("politics", "coalition_stability", s.CoalitionStability - old, FormattableString.Invariant($"coalition stability {s.CoalitionStability - old:+0.00;-0.00;+0.00} (public approval)")));+ why.Add(new Cause("politics", "coalition_stability", s.CoalitionStability - old, $"coalition stability {PlayerText.PercentChange(s.CoalitionStability - old)} (public approval)"));if (s.CoalitionStability < CollapseBelow && s.GameOver == null){s.GameOver = "coalition_collapse";diff --git a/sim/Statecraft.Sim/SecuritySystem.cs b/sim/Statecraft.Sim/SecuritySystem.csindex 8325ae54d..6db8756df 100644--- a/sim/Statecraft.Sim/SecuritySystem.cs+++ b/sim/Statecraft.Sim/SecuritySystem.cs@@ -35,7 +35,7 @@ namespace Statecraft.Sim{rung = ClampRung(rung);s.CeasefireWeeksLeft = CeasefireWeeksAfter(c, s.Rung, s.CeasefireWeeksLeft, rung);- if (rung != s.Rung) why.Add(new Cause("security", "rung", rung - s.Rung, FormattableString.Invariant($"security level {s.Rung} -> {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);}diff --git a/sim/Statecraft.Sim/Simulation.cs b/sim/Statecraft.Sim/Simulation.csindex ffbeb5a2d..07b571158 100644--- a/sim/Statecraft.Sim/Simulation.cs+++ b/sim/Statecraft.Sim/Simulation.cs@@ -84,11 +84,11 @@ namespace Statecraft.Simif (legislature == null) return "No legislature is sitting";if (!PassVote(c, s)){- why.Add(new Cause("politics", p.Policy, 0, FormattableString.Invariant($"{legislature.Body} voted down {PlayerText.Target(c, p.Policy)} {p.Level:0.00}")));+ why.Add(new Cause("politics", p.Policy, 0, $"{legislature.Body} voted down {PlayerText.Target(c, p.Policy)} at {PlayerText.Percent(p.Level)}"));return null;}s.Policies[p.Policy] = p.Level;- why.Add(new Cause("policy", p.Policy, p.Level, FormattableString.Invariant($"{PlayerText.Target(c, p.Policy)} set to {p.Level:0.00}")));+ why.Add(new Cause("policy", p.Policy, p.Level, $"{PlayerText.Target(c, p.Policy)} set to {PlayerText.Percent(p.Level)}"));return null;case AllocateBudget b:{