A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(sim): events engine, delegation and sensitive-content rule
eyalgolan539b053baaba
diff --git a/sim/Statecraft.Sim.Tests/EventTests.cs b/sim/Statecraft.Sim.Tests/EventTests.csnew file mode 100644index 000000000..5cf33999c--- /dev/null+++ b/sim/Statecraft.Sim.Tests/EventTests.cs@@ -0,0 +1,141 @@+using System;+using System.Collections.Generic;+using Statecraft.Sim;++public class EventTests+{+ const string Shortage = @"+id: shortage+title: Bread lines+text: '{finance_minister} reports shortages.'+office: finance_minister+from: 1948-06-01+conditions:+ - indicator: food_supply+ max: 0.45+options:+ - id: ration+ text: Ration food+ historical: true+ recommended: true+ effects:+ - target: food_supply+ delta: 0.2+ - id: import+ text: Buy abroad+ effects:+ - target: fx_reserves+ delta: -10+ - id: escalate+ text: Blame the border+ set_rung: 3+";++ static Content Load(Dictionary<string, string> events) => ContentLoader.Load(Fixture.Write(events: events));++ static GameState State(Content c, DateTime d)+ {+ var s = new GameState { Date = d, RngState = 3 };+ EffectsSystem.Init(c, s); EconomySystem.Init(c, s);+ return s;+ }++ [Fact]+ public void TriggersWhenDateAndConditionsHoldOnlyOnce()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ var why = new List<Cause>();+ var s = State(c, new DateTime(1948, 5, 20));+ EventSystem.Trigger(c, s, why); Assert.Empty(s.PendingEvents); // too early+ s.Date = new DateTime(1948, 6, 1);+ EventSystem.Trigger(c, s, why); Assert.Equal(new[] { "shortage" }, s.PendingEvents);+ s.PendingEvents.Clear();+ EventSystem.Trigger(c, s, why); Assert.Empty(s.PendingEvents); // fires once+ }++ [Fact]+ public void ConditionBlocksTrigger()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ var s = State(c, new DateTime(1948, 6, 1)); s.Indicators["food_supply"] = 0.9;+ EventSystem.Trigger(c, s, new List<Cause>());+ Assert.Empty(s.PendingEvents);+ }++ [Fact]+ public void ChooseAppliesEffectsAndClearsPending()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ 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.Equal(40, s.FxReserves);+ Assert.Empty(s.PendingEvents);+ Assert.Equal("Event 'shortage' is not waiting for a decision", EventSystem.Choose(c, s, "shortage", "ration", why));+ }++ [Fact]+ public void UnknownOptionIsRejected()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ var s = State(c, new DateTime(1948, 6, 1)); var why = new List<Cause>();+ EventSystem.Trigger(c, s, why);+ Assert.Equal("Event 'shortage' has no option 'nap'", EventSystem.Choose(c, s, "shortage", "nap", why));+ }++ [Fact]+ public void DelegationIsDeterministicAndClearsPending()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ GameState Run()+ {+ var s = State(c, new DateTime(1948, 6, 1)); var why = new List<Cause>();+ EventSystem.Trigger(c, s, why); EventSystem.Delegate(c, s, why);+ return s;+ }+ var a = Run(); var b = Run();+ Assert.Empty(a.PendingEvents);+ Assert.Equal(a.Hash(), b.Hash());+ }++ [Fact]+ public void RenderFillsOfficeHolder()+ {+ var c = Load(new Dictionary<string, string> { ["shortage.yaml"] = Shortage });+ Assert.Equal("Def Two reports shortages.", EventSystem.Render(c, c.Events[0], new DateTime(1948, 6, 1)));+ }++ [Fact]+ public void SensitiveEventCannotRewardTreasury()+ {+ var bad = Shortage.Replace("title: Bread lines", "title: Bread lines\ntags: [massacre]")+ .Replace("target: fx_reserves\n delta: -10", "target: treasury\n delta: 50");+ var ex = Assert.Throws<ContentException>(() => Load(new Dictionary<string, string> { ["shortage.yaml"] = bad }));+ Assert.Equal("events/shortage.yaml", ex.File);+ Assert.Equal("events[shortage].options[import].effects.treasury", ex.Field);+ }++ [Fact]+ public void PlaceholderMustBeAnOffice()+ {+ var bad = Shortage.Replace("{finance_minister}", "{king}");+ var ex = Assert.Throws<ContentException>(() => Load(new Dictionary<string, string> { ["shortage.yaml"] = bad }));+ Assert.Equal("events[shortage].text", ex.Field);+ }++ [Fact]+ public void EffectTargetMustExist()+ {+ var bad = Shortage.Replace("target: food_supply", "target: bread");+ var ex = Assert.Throws<ContentException>(() => Load(new Dictionary<string, string> { ["shortage.yaml"] = bad }));+ Assert.Equal("events[shortage].options[ration].effects.bread", ex.Field);+ }++ [Fact]+ public void DuplicateEventIdIsAnError()+ {+ var ex = Assert.Throws<ContentException>(() => Load(new Dictionary<string, string> { ["a.yaml"] = Shortage, ["b.yaml"] = Shortage }));+ Assert.Equal("events/b.yaml", ex.File);+ Assert.Equal("events[shortage].id", ex.Field);+ }+}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex 22a5ea691..5e57c0249 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -1,5 +1,6 @@using System;using System.Collections.Generic;+using YamlDotNet.Serialization;namespace Statecraft.Sim{@@ -161,6 +162,8 @@ namespace Statecraft.Simpublic List<EventOption> Options { get; set; } = new List<EventOption>();public List<Source> Sources { get; set; } = new List<Source>();public string Status { get; set; } = "draft";+ /// <summary>Path relative to the content root, set by the loader (not read from YAML).</summary>+ [YamlIgnore] public string File { get; set; } = "";}public sealed class Contentdiff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 9b21c388f..5cdba3d0e 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -56,7 +56,12 @@ namespace Statecraft.Simvar eventsDir = Path.Combine(contentRoot, "events");if (Directory.Exists(eventsDir))foreach (var f in Directory.GetFiles(eventsDir, "*.yaml").OrderBy(p => p, StringComparer.Ordinal))- c.Events.Add(Read<GameEvent>(contentRoot, Path.Combine("events", Path.GetFileName(f))));+ {+ var rel = "events/" + Path.GetFileName(f);+ var e = Read<GameEvent>(contentRoot, rel);+ e.File = rel;+ c.Events.Add(e);+ }Validate(c);return c;}diff --git a/sim/Statecraft.Sim/EventRules.cs b/sim/Statecraft.Sim/EventRules.csindex afe1de002..86fc68f8f 100644--- a/sim/Statecraft.Sim/EventRules.cs+++ b/sim/Statecraft.Sim/EventRules.cs@@ -1,10 +1,49 @@using System.Collections.Generic;+using System.Linq;+using System.Text.RegularExpressions;namespace Statecraft.Sim{- /// <summary>Load-time checks for events. Extended in the events task.</summary>+ /// <summary>Load-time checks for events, including the sensitive-content rule.</summary>static class EventRules{- public static void Validate(Content c, HashSet<string> offices, HashSet<string> indicators) { }+ public static readonly HashSet<string> SensitiveTags = new HashSet<string> { "holocaust", "terror", "massacre", "war-casualties" };+ public static readonly HashSet<string> SpecialTargets = new HashSet<string> { "treasury", "fx_reserves" };++ public static void Validate(Content c, HashSet<string> offices, HashSet<string> indicators)+ {+ var ids = new HashSet<string>();+ foreach (var e in c.Events)+ {+ string F(string field) => $"events[{e.Id}].{field}";+ if (!ids.Add(e.Id)) throw new ContentException(e.File, F("id"), "duplicate event id");+ if (e.Office != "" && !offices.Contains(e.Office)) throw new ContentException(e.File, F("office"), $"unknown office '{e.Office}'");+ CheckPlaceholders(e.File, F("title"), e.Title, offices);+ CheckPlaceholders(e.File, F("text"), e.Text, offices);+ foreach (var cond in e.Conditions)+ if (!indicators.Contains(cond.Indicator)) throw new ContentException(e.File, F($"conditions.{cond.Indicator}"), "unknown indicator");+ if (e.Options.Count == 0) throw new ContentException(e.File, F("options"), "at least one option required");+ if (e.Options.Count(o => o.Historical) > 1) throw new ContentException(e.File, F("options"), "at most one option can be historical");+ bool sensitive = e.Tags.Any(SensitiveTags.Contains);+ foreach (var o in e.Options)+ {+ CheckPlaceholders(e.File, F($"options[{o.Id}].text"), o.Text, offices);+ if (o.SetRung.HasValue && (o.SetRung < 1 || o.SetRung > 5)) throw new ContentException(e.File, F($"options[{o.Id}].set_rung"), "must be 1-5");+ foreach (var fx in o.Effects)+ {+ if (!indicators.Contains(fx.Target) && !SpecialTargets.Contains(fx.Target))+ throw new ContentException(e.File, F($"options[{o.Id}].effects.{fx.Target}"), "unknown target");+ if (sensitive && fx.Target == "treasury" && fx.Delta > 0)+ throw new ContentException(e.File, F($"options[{o.Id}].effects.treasury"), "sensitive events cannot reward the treasury");+ }+ }+ }+ }++ static void CheckPlaceholders(string file, string field, string text, HashSet<string> offices)+ {+ foreach (Match m in Offices.Placeholder.Matches(text))+ if (!offices.Contains(m.Groups[1].Value)) throw new ContentException(file, field, $"unknown office placeholder '{m.Value}'");+ }}}diff --git a/sim/Statecraft.Sim/EventSystem.cs b/sim/Statecraft.Sim/EventSystem.csnew file mode 100644index 000000000..59b1f0c12--- /dev/null+++ b/sim/Statecraft.Sim/EventSystem.cs@@ -0,0 +1,73 @@+using System;+using System.Collections.Generic;+using System.Linq;++namespace Statecraft.Sim+{+ public static class EventSystem+ {+ public const int MaxNewPerTurn = 3;++ static GameEvent Get(Content c, string id) => c.Events.First(e => e.Id == id);++ public static void Trigger(Content c, GameState s, List<Cause> why)+ {+ var eligible = c.Events+ .Where(e => !s.FiredEvents.Contains(e.Id) && e.From <= s.Date && (e.To == null || s.Date < e.To.Value))+ .Where(e => e.Conditions.All(k => (!k.Min.HasValue || s.Indicators[k.Indicator] >= k.Min.Value)+ && (!k.Max.HasValue || s.Indicators[k.Indicator] <= k.Max.Value)))+ .OrderBy(e => e.From).ThenBy(e => e.Id, StringComparer.Ordinal)+ .Take(MaxNewPerTurn);+ foreach (var e in eligible)+ {+ s.FiredEvents.Add(e.Id);+ s.PendingEvents.Add(e.Id);+ why.Add(new Cause("events", e.Id, 0, $"New: {Offices.Fill(c, e.Title, s.Date)}"));+ }+ }++ /// <summary>Returns null on success, or the reason the choice was rejected.</summary>+ public static string? Choose(Content c, GameState s, string eventId, string optionId, List<Cause> why)+ {+ if (!s.PendingEvents.Contains(eventId)) return $"Event '{eventId}' is not waiting for a decision";+ var option = Get(c, eventId).Options.FirstOrDefault(o => o.Id == optionId);+ if (option == null) return $"Event '{eventId}' has no option '{optionId}'";+ Resolve(c, s, eventId, option, "chosen", why);+ return null;+ }++ static void Resolve(Content c, GameState s, string eventId, EventOption o, string how, List<Cause> why)+ {+ s.PendingEvents.Remove(eventId);+ why.Add(new Cause("events", eventId, 0, $"{how}: {Offices.Fill(c, o.Text, s.Date)}"));+ foreach (var fx in o.Effects)+ {+ if (fx.Target == "treasury") s.Treasury += fx.Delta;+ else if (fx.Target == "fx_reserves") s.FxReserves += fx.Delta;+ else s.Indicators[fx.Target] = Math.Max(0, Math.Min(1, s.Indicators[fx.Target] + fx.Delta));+ why.Add(new Cause("events", fx.Target, fx.Delta, $"{fx.Target} {fx.Delta:+0.00;-0.00} ({eventId}/{o.Id})"));+ }+ if (o.SetRung.HasValue) SecuritySystem.SetRung(c, s, o.SetRung.Value, why);+ }++ /// <summary>Unanswered events go to the responsible minister: with probability competence/10 they pick the+ /// recommended option (else the first), otherwise a random option.</summary>+ public static void Delegate(Content c, GameState s, List<Cause> why)+ {+ var rng = new Rng(s.RngState);+ foreach (var id in s.PendingEvents.ToList())+ {+ var e = Get(c, id);+ var minister = e.Office == "" ? null : Offices.Holder(c, e.Office, s.Date);+ var competence = (minister?.Competence ?? 5) / 10.0;+ var option = rng.NextDouble() < competence+ ? e.Options.FirstOrDefault(o => o.Recommended) ?? e.Options[0]+ : e.Options[(int)(rng.NextDouble() * e.Options.Count)];+ Resolve(c, s, id, option, $"delegated to {minister?.Name ?? "the cabinet"}", why);+ }+ s.RngState = rng.State;+ }++ public static string Render(Content c, GameEvent e, DateTime date) => Offices.Fill(c, e.Text, date);+ }+}diff --git a/sim/Statecraft.Sim/Offices.cs b/sim/Statecraft.Sim/Offices.csindex ccd20892f..405a876b6 100644--- a/sim/Statecraft.Sim/Offices.cs+++ b/sim/Statecraft.Sim/Offices.cs@@ -18,7 +18,7 @@ namespace Statecraft.Simpublic static Government? Government(Content c, DateTime date) =>c.Governments.FirstOrDefault(g => In(date, g.From, g.To));- static readonly Regex Placeholder = new Regex(@"\{([a-z_]+)\}");+ internal static readonly Regex Placeholder = new Regex(@"\{([a-z_]+)\}");/// <summary>Replaces {office_id} with the name of the person holding it on date.</summary>public static string Fill(Content c, string text, DateTime date) =>