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): one sign style, unsigned zero, no NaN; a whole-word guard over Causes and refusals (fix round 2, N2 N3 N5 N7)
eyalgoland2787874f1e8
diff --git a/sim/Statecraft.Sim.Tests/EventTests.cs b/sim/Statecraft.Sim.Tests/EventTests.csindex 24c60a6df..27876bc5a 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 +$0.0m (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/PlayerTextTests.cs b/sim/Statecraft.Sim.Tests/PlayerTextTests.csindex 31906811b..70f660645 100644--- a/sim/Statecraft.Sim.Tests/PlayerTextTests.cs+++ b/sim/Statecraft.Sim.Tests/PlayerTextTests.cs@@ -96,11 +96,22 @@ public class PlayerTextTestsstatic 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|$)");+ return EnglishWords.ContainsKey(id)+ ? new Regex($@"(^|\(|, |/|from ){e}(\)|,|/|:| [+-]?\d| set to| =| began| ended| at \d|$)")+ : new Regex($@"\b{e}\b");}+ /// <summary>Fix round 2 (N3): ids are matched anywhere as whole words, except these, which are also ordinary English in+ /// player text (each with where it legitimately appears; <see cref="EveryAllowedWordIsRealEnglishInPlayerText"/>).+ /// They are still caught wherever an id would sit.</summary>+ static readonly Dictionary<string, string> EnglishWords = new Dictionary<string, string>+ {+ ["morale"] = "Homes lift morale", // effect names (model.yaml)+ ["housing"] = "a housing project", // the map action's phrase (rules.yaml) and "New housing"+ ["rationing"] = "Impose rationing", // event option text (events/austerity_1949.yaml)+ ["security"] = "the minimum for security level", // the security ladder (SecuritySystem), not the indicator+ };+static List<string> Leaks(Content c, IEnumerable<string> messages){var patterns = ContentIds(c).Select(id => (id, re: IdPattern(id))).ToList();@@ -110,6 +121,9 @@ public class PlayerTextTests/// <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>+ /// <summary>Refusal reasons the scripted run met (player-facing too).</summary>+ static readonly List<string> Rejections = new List<string>();+internal static List<Cause> ScriptedCauses(Content c){var causes = new List<Cause>();@@ -123,16 +137,19 @@ public class PlayerTextTestscauses.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++)+ bool budget = false, camp = false, housing = false;+ var appointedOffices = new HashSet<string>(); var appointable = new HashSet<string>();+ var policiesSet = new HashSet<string>();+ for (int turn = 0; turn < 120 && 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));- }+ var policy = c.Policies[turn % c.Policies.Count]; // every policy, passed and lost votes+ cmds.Add(new SetPolicy(policy.Id, (turn / c.Policies.Count) % 2 == 0 ? 0.9 : 0.2)); // each policy up, then down, in turn+ foreach (var o in c.Offices)+ if (Cabinet.Candidates(c, s, o.Id).Any(x => x.reason == null)) appointable.Add(o.Id);+ var pick = c.Offices.Where(o => !appointedOffices.Contains(o.Id)).OrderBy(o => o.Until ?? DateTime.MaxValue) // soonest abolished first+ .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.Insert(0, new Appoint(pick.Item1, pick.Item2)); // first, so attention never runs out for itif (!budget){var first = s.Budget.Keys.OrderBy(k => k, StringComparer.Ordinal).First();@@ -146,13 +163,18 @@ public class PlayerTextTests}var r = Simulation.Step(c, s, cmds);causes.AddRange(r.Why);- appointed |= r.Why.Any(w => w.System == "cabinet");+ Rejections.AddRange(r.Rejected.Select(x => x.Reason));+ foreach (var w in r.Why.Where(w => w.System == "cabinet" && w.Target != "appointments")) appointedOffices.Add(w.Target);+ foreach (var w in r.Why.Where(w => w.System == "policy")) policiesSet.Add(w.Target);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.True(budget && camp && housing, $"the script ran every command (budget {budget}, camp {camp}, housing {housing})");+ Assert.True(appointable.SetEquals(appointedOffices), $"every appointable office was filled: missing {string.Join(", ", appointable.Except(appointedOffices))}");+ Assert.True(c.Policies.All(p => policiesSet.Contains(p.Id)), $"every policy was set: missing {string.Join(", ", c.Policies.Select(p => p.Id).Except(policiesSet))}");+ Assert.Contains(causes, w => w.Message.StartsWith("borrowed ", StringComparison.Ordinal));Assert.Contains(causes, w => w.System == "policy");Assert.Contains(causes, w => w.System == "politics" && w.Message.Contains(" voted down "));return causes;@@ -175,7 +197,10 @@ public class PlayerTextTests[Fact]public void NoCauseFromAnyCommandShowsAContentId(){- var leaks = Leaks(Real, AllCauses(Real).Select(w => w.Message));+ Rejections.Clear();+ var messages = AllCauses(Real).Select(w => w.Message).ToList();+ Assert.NotEmpty(Rejections); // the script also met refusals+ var leaks = Leaks(Real, messages.Concat(Rejections));Assert.True(leaks.Count == 0, "Cause text shows content ids:\n" + string.Join("\n", leaks.Take(60)));}@@ -190,6 +215,40 @@ public class PlayerTextTestspublic void TheGuardCatchesOneWordIds(string message, string id) =>Assert.Contains(Leaks(Real, new[] { message }), l => l.StartsWith($"'{id}'", StringComparison.Ordinal));+ [Theory]+ [InlineData("morale: low", "morale")]+ [InlineData("the morale fell", "morale")] // plain English: not an id position, so allowed+ public void AllowedWordsAreStillCaughtWhereAnIdWouldSit(string message, string id)+ {+ var caught = Leaks(Real, new[] { message }).Any(l => l.StartsWith($"'{id}'", StringComparison.Ordinal));+ Assert.Equal(message.StartsWith(id, StringComparison.Ordinal), caught);+ }++ [Theory]+ [InlineData("of asia", "asia")]+ [InlineData("the treasury fell", "treasury")]+ [InlineData("Ends with debt", "debt")]+ public void OtherOneWordIdsAreCaughtAnywhere(string message, string id) =>+ Assert.Contains(Leaks(Real, new[] { message }), l => l.StartsWith($"'{id}'", StringComparison.Ordinal));++ /// <summary>Each allowed English word really is display text from content or sim prose, so allowing it hides nothing.</summary>+ [Fact]+ public void EveryAllowedWordIsRealEnglishInPlayerText()+ {+ var display = Real.Effects.Select(e => e.Name).Concat(Real.Rules.MapActions.Values.Select(a => a.Name))+ .Concat(Real.Events.SelectMany(e => e.Options.Select(o => o.Text))).ToList();+ foreach (var kv in EnglishWords)+ {+ Assert.Contains(kv.Key, kv.Value.Split(' '));+ if (kv.Key == "security") continue; // sim prose: SecuritySystem's ladder message+ Assert.Contains(display, d => Regex.IsMatch(d, $@"\b{kv.Key}\b"));+ }+ var s = Simulation.NewGame(Real, 1, Mode.Historical);+ var why = new List<Cause>();+ SecuritySystem.SetMobilization(Real, s, 0, why); // below the floor: the ladder message+ Assert.Contains(why, w => w.Message.Contains(EnglishWords["security"]));+ }+[Theory][InlineData("Impose rationing")][InlineData("A housing project at (3, 4): cost IL 1.5m")]@@ -206,10 +265,16 @@ public class PlayerTextTestsvar bad = new List<string>();foreach (var w in AllCauses(Real)){- if (money.Contains(w.Target) && !Regex.IsMatch(w.Message, @"[+-]?(IL |\$)\d+\.\dm"))+ // Every number in the line must carry the unit (fix round 2, N3): strip the unit tokens; no digit may remain.+ if (money.Contains(w.Target) && Regex.IsMatch(Regex.Replace(w.Message, @"[+-]?(IL |\$)\d+\.\dm", ""), @"\d"))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.System == "map") // "A housing project at (q, r): cost IL 6.0m, Housing +3.0%, ...": coordinates aside, all units+ {+ if (Regex.IsMatch(Regex.Replace(Regex.Replace(w.Message, @"\(-?\d+, -?\d+\)", ""), @"[+-]?(IL |\$)\d+\.\dm|[+-]?\d+(\.\d)?%", ""), @"\d"))+ bad.Add("map line number without a unit: " + w.Message);+ }+ else if (indicators.Contains(w.Target) && Regex.IsMatch(Regex.Replace(w.Message, @"[+-]?\d+(\.\d)?%", ""), @"\d"))+ bad.Add("indicator number not on the 0-100 % scale: " + w.Message);if (w.Message.Contains("stability") && !w.Message.Contains("%"))bad.Add("stability without %: " + w.Message);}@@ -223,7 +288,7 @@ public class PlayerTextTestsAssert.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("$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));@@ -282,4 +347,55 @@ public class PlayerTextTestsAssert.Equal($"({hex.Q}, {hex.R}) already has a ma'abara", MapActions.Check(c, s, MapActions.TransitCamp, hex.Q, hex.R));Assert.Throws<InvalidOperationException>(() => PlayerText.MapAction(c, "factory"));}++ // ---- Fix round 2 (N2): one sign style, unsigned zero, no NaN ----++ [Fact]+ public void ZeroIsUnsignedAndTheSignGoesBeforeTheCurrency()+ {+ Assert.Equal("0%", PlayerText.Percent(-0.004));+ Assert.Equal("55%", PlayerText.Percent(0.55));+ Assert.Equal("-5%", PlayerText.Percent(-0.05));+ Assert.Equal("0.0%", PlayerText.PercentChange(-0.0004));+ Assert.Equal("0.0%", PlayerText.PercentChange(0.0004));+ Assert.Equal("+4.1%", PlayerText.PercentChange(0.041));+ Assert.Equal("-4.0%", PlayerText.PercentChange(-0.04));+ Assert.Equal("+5%", PlayerText.PercentChange(0.05, 0));+ Assert.Equal("0%", PlayerText.PercentChange(-0.004, 0));+ Assert.Equal("-IL 3.0m", PlayerText.Money(Real, "treasury", -3));+ Assert.Equal("IL 0.0m", PlayerText.Money(Real, "treasury", -0.04));+ 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.04));+ Assert.Equal("IL 0.0m", PlayerText.MoneyChange(Real, "treasury", 0.04));+ }++ [Theory]+ [InlineData(double.NaN)]+ [InlineData(double.PositiveInfinity)]+ [InlineData(double.NegativeInfinity)]+ public void ANonFiniteNumberIsAProgrammerError(double v)+ {+ Assert.Throws<ArgumentOutOfRangeException>(() => PlayerText.Percent(v));+ Assert.Throws<ArgumentOutOfRangeException>(() => PlayerText.PercentChange(v));+ Assert.Throws<ArgumentOutOfRangeException>(() => PlayerText.Money(Real, "treasury", v));+ Assert.Throws<ArgumentOutOfRangeException>(() => PlayerText.MoneyChange(Real, "treasury", v));+ Assert.Throws<ArgumentOutOfRangeException>(() => PlayerText.Scale(v));+ }++ // ---- Fix round 2 (N7): money entries that are blank, bare or collide ----++ [Theory]+ [InlineData("model.yaml", " - { id: treasury, name: Treasury, prefix: 'IL ' }\n", " - { id: treasury, name: Treasury, prefix: }\n", "money[treasury].prefix")]+ [InlineData("model.yaml", " - { id: treasury, name: Treasury, prefix: 'IL ' }\n", " - { id: treasury, name: Treasury, prefix: ' ' }\n", "money[treasury].prefix")]+ [InlineData("model.yaml", " - { id: debt, name: Debt, prefix: 'IL ' }\n", " - { id: debt, name: Debt, prefix: 'IL ' }\n -\n", "money[2]")]+ [InlineData("model.yaml", " - id: morale\n", " - id: treasury\n", "indicators[treasury].id")]+ [InlineData("model.yaml", " - id: maabarot\n", " - id: debt\n", "policies[debt].id")]+ public void MoneyEntriesAreCheckedLikeEveryOtherName(string file, string from, string to, string field)+ {+ var ex = ValidationTests.Bad(file, from, to);+ Assert.Equal(file, ex.File);+ Assert.Equal(field, ex.Field);+ }}diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 4b4791b8a..f00df7c98 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -302,12 +302,17 @@ namespace Statecraft.Simif (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 '$')");+ if (string.IsNullOrWhiteSpace(a.Prefix)) 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)");+ // Money, indicators and policies share one namespace in Cause targets and PlayerText.Target (fix round 2, N7).+ foreach (var i in c.Indicators)+ if (Array.IndexOf(PlayerText.MoneyIds, i.Id) >= 0) throw new ContentException("model.yaml", $"indicators[{i.Id}].id", "same id as money (treasury, debt, fx_reserves)");+ foreach (var p in c.Policies)+ if (Array.IndexOf(PlayerText.MoneyIds, p.Id) >= 0) throw new ContentException("model.yaml", $"policies[{p.Id}].id", "same id as money (treasury, debt, fx_reserves)");foreach (var p in c.People) Status("people.yaml", $"people[{p.Id}].status", p.Status);foreach (var l in c.Legislatures) Status("legislatures.yaml", $"legislatures[{l.Id}].status", l.Status);diff --git a/sim/Statecraft.Sim/PlayerText.cs b/sim/Statecraft.Sim/PlayerText.csindex 938c0e67e..b911deade 100644--- a/sim/Statecraft.Sim/PlayerText.cs+++ b/sim/Statecraft.Sim/PlayerText.cs@@ -44,27 +44,48 @@ namespace Statecraft.Simstatic MoneyAccount Account(Content c, string id) => c.Money.FirstOrDefault(m => m.Id == id) ?? throw Unknown("money", id);- /// <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";+ static double Finite(double v, string name) =>+ double.IsNaN(v) || double.IsInfinity(v) ? throw new ArgumentOutOfRangeException(name, v, "not a finite number (a programmer error)") : v;- /// <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>+ static string Fixed(double abs, int decimals) => abs.ToString(decimals == 0 ? "0" : "0.0", CultureInfo.InvariantCulture);++ /// <summary>The one sign style: the sign goes before the currency or number, and a value that rounds to zero prints+ /// unsigned. <paramref name="signed"/> adds "+" to positive values (changes).</summary>+ static string Signed(double rounded, string prefix, string body, bool signed) =>+ rounded == 0 ? prefix + body : (rounded < 0 ? "-" : signed ? "+" : "") + prefix + body;++ /// <summary>An amount in millions with its currency: "IL 18.6m", "-IL 3.0m", "$41.5m"; zero is "IL 0.0m".</summary>+ public static string Money(Content c, string id, double millions)+ {+ var r = Math.Round(Finite(millions, nameof(millions)), 1, MidpointRounding.AwayFromZero);+ return Signed(r, Account(c, id).Prefix, Fixed(Math.Abs(r), 1) + "m", signed: false);+ }++ /// <summary>A change in millions with its currency, sign first: "+IL 1.2m", "-$0.4m"; zero is "IL 0.0m".</summary>public static string MoneyChange(Content c, string id, double millions){- 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";+ var r = Math.Round(Finite(millions, nameof(millions)), 1, MidpointRounding.AwayFromZero);+ return Signed(r, Account(c, id).Prefix, Fixed(Math.Abs(r), 1) + "m", signed: true);}/// <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;+ public static double Scale(double level) => Finite(level, nameof(level)) * 100;- /// <summary>"55%" for a level of 0.55.</summary>- public static string Percent(double level) => Scale(level).ToString("0", CultureInfo.InvariantCulture) + "%";+ /// <summary>"55%" for a level of 0.55; zero is "0%".</summary>+ public static string Percent(double level)+ {+ var r = Math.Round(Scale(level), 0, MidpointRounding.AwayFromZero);+ return Signed(r, "", Fixed(Math.Abs(r), 0) + "%", signed: false);+ }- /// <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>"+4.1%" for a change of 0.041 (points on the 0-100 scale, <paramref name="decimals"/> 0 or 1); zero is+ /// "0.0%" (or "0%").</summary>+ public static string PercentChange(double change, int decimals = 1)+ {+ if (decimals != 0 && decimals != 1) throw new ArgumentOutOfRangeException(nameof(decimals), decimals, "0 or 1");+ var r = Math.Round(Scale(change), decimals, MidpointRounding.AwayFromZero);+ return Signed(r, "", Fixed(Math.Abs(r), decimals) + "%", signed: true);+ }/// <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) =>diff --git a/sim/Statecraft.Sim/SecuritySystem.cs b/sim/Statecraft.Sim/SecuritySystem.csindex 6db8756df..a51d06bf9 100644--- a/sim/Statecraft.Sim/SecuritySystem.cs+++ b/sim/Statecraft.Sim/SecuritySystem.cs@@ -45,7 +45,7 @@ namespace Statecraft.Sim{if (!(level >= 0 && level <= 1)) return "Mobilization must be between 0 and 1";s.Mobilization = level;- why.Add(new Cause("security", "mobilization", level, FormattableString.Invariant($"reserve call-up set to {level * 100:0}%")));+ why.Add(new Cause("security", "mobilization", level, $"reserve call-up set to {PlayerText.Percent(level)}"));RaiseToFloor(c, s, why);return null;}@@ -56,7 +56,7 @@ namespace Statecraft.Simvar floor = MinMobilization(c, rung);if (s.Mobilization < floor){- why.Add(new Cause("security", "mobilization", floor - s.Mobilization, FormattableString.Invariant($"reserve call-up raised to {floor * 100:0}%, the minimum for security level {rung}")));+ 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}")));s.Mobilization = floor;}}