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: era rules overrides and Content.RulesAt, first piece of #58 (#254)

agamrafaeli-instinct316a04290d52
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 049e21985..c5d2ce7a1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,12 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
English under each, and Continue (only with a save) and New Game (with the top bar's two-press confirmation). Automated
runs skip it (golden, smoke, shot, the profiles, units, borderproof), as does `?nostart`. The Hebrew is set in Frank Ruhl
Libre (OFL) and laid out right to left by UI Toolkit's advanced text generator (#193).
+- Rules per era (#58, first piece): an era can override `rules.yaml` keys in `content/rules/<era>.yaml` (only the keys it
+ changes; maps merge key by key, a list or a value replaces). The merged rules are read with the strict `Rules` type, so a
+ misspelt key or wrong type fails naming the era file and line, start values (`treasury_start`, `start_rung` and so on) are
+ refused, a file that names no era is refused, and `rules/` is in the player manifest. They are checked like `rules.yaml`. `Content.RulesAt(date)` returns the rules of
+ the era a date is in (built once at load); the founding era has no file, so its rules are `rules.yaml`. Nothing reads
+ `RulesAt` yet, so the goldens do not move.
- Units in play: the map draws the 1948 brigades, 101 Squadron and the first navy ships as Civ-style tokens at their
dated, sourced positions (`content/map/units_1948.yaml`, map-only, outside the content hash). The figures follow the
reserve call-up, the squadron flies at security level 4 or 5 (an Avia S-199, then the Spitfire from its first sourced
diff --git a/sim/Statecraft.Sim.Tests/EraRulesTests.cs b/sim/Statecraft.Sim.Tests/EraRulesTests.cs
new file mode 100644
index 000000000..ee812a9b9
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/EraRulesTests.cs
@@ -0,0 +1,182 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using Statecraft.Sim;
+
+/// <summary>Rules per era (#58): content/rules/&lt;era&gt;.yaml overrides only the keys it names, is read with the strict
+/// Rules type, and Content.RulesAt(date) returns the rules of the era the date is in.</summary>
+public class EraRulesTests
+{
+ const string TwoEras = @"
+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 string Write(string? laterRules, string eras = TwoEras)
+ {
+ var dir = Fixture.Write(new Dictionary<string, string> { ["eras.yaml"] = eras });
+ if (laterRules != null)
+ {
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), laterRules);
+ }
+ return dir;
+ }
+
+ [Fact]
+ public void RealContentHasNoOverrideAndRulesAtIsRulesYaml()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ Assert.Empty(c.EraRules);
+ Assert.Same(c.Rules, c.RulesAt(c.Rules.Start));
+ Assert.Same(c.Rules, c.RulesAt(new DateTime(1956, 12, 31)));
+ Assert.Same(c.Rules, c.RulesAt(new DateTime(1960, 1, 1))); // outside every era: the base rules
+ }
+
+ [Fact]
+ public void AnOverrideChangesOnlyItsKeys()
+ {
+ var c = ContentLoader.Load(Write("attention_per_turn: 5\nattention_cost: { set_policy: 2 }\n"));
+ var b = c.Rules; var l = c.RulesAt(new DateTime(1952, 1, 1));
+ Assert.NotSame(b, l);
+ Assert.Equal(5, l.AttentionPerTurn);
+ Assert.Equal(3, b.AttentionPerTurn);
+ Assert.Equal(2, l.AttentionCost["set_policy"]); // maps merge key by key
+ Assert.Equal(b.AttentionCost["appoint"], l.AttentionCost["appoint"]);
+ Assert.Equal(b.StartRung, l.StartRung); // every other key is rules.yaml's
+ Assert.Equal(b.Start, l.Start);
+ Assert.Equal(b.AppointStabilityCostOtherParty, l.AppointStabilityCostOtherParty);
+ Assert.Same(b, c.RulesAt(new DateTime(1951, 12, 31))); // the founding era keeps rules.yaml
+ }
+
+ [Fact]
+ public void AListInAnOverrideReplacesTheWholeList()
+ {
+ var c = ContentLoader.Load(Write("rung_min_mobilization: [0, 0.1, 0.2, 0.3, 0.4]\n"));
+ Assert.Equal(new[] { 0, 0.1, 0.2, 0.3, 0.4 }, c.RulesAt(new DateTime(1953, 1, 1)).RungMinMobilization);
+ }
+
+ [Fact]
+ public void AnUnknownKeyInAnOverrideFailsNamingTheFile()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("attention_per_turnn: 5\n")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ }
+
+ [Fact]
+ public void AnOverrideIsValidatedLikeRulesYaml()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("ceasefire_weeks: -1\n")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ Assert.Contains("ceasefire_weeks", e.Message);
+ }
+
+ [Fact]
+ public void AnOverrideCannotMoveTheStartDate()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("start: 1952-01-01\n")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ }
+
+ [Fact]
+ public void AnEmptyOverrideFileFails()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ }
+
+ [Fact]
+ public void AnOverrideFileCountsInTheContentHash()
+ {
+ var without = ContentLoader.Load(Write(null)).Hash;
+ var with = ContentLoader.Load(Write("attention_per_turn: 5\n")).Hash;
+ Assert.NotEqual(without, with);
+ }
+
+ [Fact]
+ public void AnEraWithoutAFileHasNoEntry()
+ {
+ var c = ContentLoader.Load(Write(null));
+ Assert.Empty(c.EraRules);
+ Assert.Same(c.Rules, c.RulesAt(new DateTime(1953, 1, 1)));
+ }
+
+ [Fact]
+ public void ABaseRulesErrorNamesRulesYamlEvenWithAnEraFile()
+ {
+ var dir = Write("attention_per_turn: 5\n");
+ var rulesPath = Path.Combine(dir, "rules.yaml");
+ File.WriteAllText(rulesPath, System.Text.RegularExpressions.Regex.Replace(File.ReadAllText(rulesPath), @"(?m)^ceasefire_weeks:.*$", "ceasefire_weeks: -1"));
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(dir));
+ Assert.Contains("rules.yaml", e.Message);
+ Assert.DoesNotContain("rules/later.yaml", e.Message);
+ }
+
+ [Fact]
+ public void ATypeErrorInAnOverrideNamesTheFileAndLine()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("# note\nattention_per_turn: abc\n")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ Assert.Contains("line 2", e.Message);
+ }
+
+ [Fact]
+ public void ANestedUnknownKeyNamesTheFileAndLine()
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write("map_actions:\n housing:\n costt: 9\n")));
+ Assert.Contains("rules/later.yaml", e.Message);
+ Assert.Contains("line 3", e.Message);
+ }
+
+ [Theory]
+ [InlineData("treasury_start: 999\n")]
+ [InlineData("fx_start: 1\n")]
+ [InlineData("start_rung: 2\n")]
+ [InlineData("initial_population:\n jews: 1\n")]
+ [InlineData("budget_start:\n defence: 1\n")]
+ public void AnOverrideCannotSetAStartValue(string yaml)
+ {
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(Write(yaml)));
+ Assert.Contains("rules/later.yaml", e.Message);
+ Assert.Contains("start/<era>.yaml", e.Message);
+ }
+
+ [Fact]
+ public void AFileThatNamesNoEraIsRefused()
+ {
+ var dir = Write(null);
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "latr.yaml"), "attention_per_turn: 5\n");
+ var e = Assert.Throws<ContentException>(() => ContentLoader.Load(dir));
+ Assert.Contains("rules/latr.yaml", e.Message);
+ }
+
+ [Fact]
+ public void ARealOverrideFileInContentNamesAnEra()
+ {
+ var root = RealContentTests.ContentRoot();
+ var dir = Path.Combine(root, "rules");
+ if (!Directory.Exists(dir)) return;
+ var eras = new HashSet<string>(ContentLoader.Load(root).Eras.ConvertAll(e => e.Id));
+ foreach (var f in Directory.GetFiles(dir, "*.yaml")) Assert.Contains(Path.GetFileNameWithoutExtension(f), eras);
+ }
+
+ [Fact]
+ public void AMergeTwoLevelsDeepKeepsTheSiblingKeys()
+ {
+ var c = ContentLoader.Load(Write("map_actions:\n housing:\n cost: 9\n"));
+ var later = c.RulesAt(new DateTime(1953, 1, 1)).MapActions;
+ var basis = c.Rules.MapActions;
+ Assert.Equal(9, later["housing"].Cost);
+ Assert.Equal(basis["housing"].Housing, later["housing"].Housing);
+ Assert.Equal(basis["housing"].Name, later["housing"].Name);
+ Assert.Equal(basis.Count, later.Count);
+ }
+}
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index 72b670765..576eb7635 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -309,6 +309,16 @@ namespace Statecraft.Sim
public List<VoterGroup> VoterGroups = new List<VoterGroup>();
public List<Actor> Actors = new List<Actor>();
public Rules Rules = new Rules();
+ /// <summary>The complete rules of each era that has an override file (content/rules/&lt;era&gt;.yaml): rules.yaml with that
+ /// file's keys merged in. Built once at load and never changed. An era without a file is not in this map.</summary>
+ public Dictionary<string, Rules> EraRules = new Dictionary<string, Rules>();
+ /// <summary>The rules in force on <paramref name="date"/>: the era's own rules when its override file exists, else
+ /// <see cref="Rules"/> (the founding era has no override, so its rules are rules.yaml itself).</summary>
+ public Rules RulesAt(DateTime date)
+ {
+ var era = EraAt(date);
+ return era != null && EraRules.TryGetValue(era.Id, out var r) ? r : Rules;
+ }
public 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>();
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index 27df0cb0b..7e4d24c33 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -74,6 +74,59 @@ namespace Statecraft.Sim
.WithDuplicateKeyChecking() // two equal keys would otherwise silently keep only the last value
.Build();
+ static readonly IDeserializer NodeYaml = new DeserializerBuilder().WithDuplicateKeyChecking().Build();
+ static readonly ISerializer NodeWriter = new SerializerBuilder().Build();
+
+ /// <summary>Keys an era override may not set: the values <c>NewGame</c> reads once. A later era's start values
+ /// belong in start/&lt;era&gt;.yaml (chapters spec section 6), and the set of budget lines in the carry rules (section 4).</summary>
+ static readonly string[] StartOnlyKeys = { "start", "treasury_start", "fx_start", "start_rung", "initial_population", "budget_start" };
+
+ /// <summary>Era rules (#58): for each era with a content/rules/&lt;era&gt;.yaml file, rules.yaml with that file's keys
+ /// merged in at the YAML-node level (maps merge key by key, a list or a value replaces), then read with the strict
+ /// <see cref="Rules"/> type. The override is first read on its own with the same strict reader, so a misspelt key
+ /// or a wrong type fails naming the era file and the line. An override cannot remove a key: an era cannot drop a
+ /// budget_start line, a map_actions entry or an attention_cost kind. An override file is read through
+ /// <paramref name="readFile"/>, so it counts in the content hash; <paramref name="baseText"/> is the text of
+ /// rules.yaml already read (and hashed) once. An era with no file is left out of the map.</summary>
+ static Dictionary<string, Rules> ReadEraRules(string baseText, Func<string, string?> readFile, List<Era> eras)
+ {
+ var result = new Dictionary<string, Rules>();
+ foreach (var era in eras)
+ {
+ if (!Offices.OfficeId.IsMatch(era.Id ?? "")) continue; // eras.yaml validation names a bad id
+ var rel = "rules/" + era.Id + ".yaml";
+ string? text;
+ try { text = readFile(rel); }
+ catch (IOException e) { throw new ContentException(rel, "(file)", e.Message); }
+ catch (UnauthorizedAccessException e) { throw new ContentException(rel, "(file)", e.Message); }
+ if (text == null) continue;
+ Dictionary<object, object> over;
+ try
+ {
+ var alone = Yaml.Deserialize<Rules>(text) ?? throw new ContentException(rel, "(file)", "empty file: list the keys this era changes");
+ CheckNulls(rel, "", alone);
+ over = NodeYaml.Deserialize<Dictionary<object, object>>(text) ?? throw new ContentException(rel, "(file)", "empty file: list the keys this era changes");
+ }
+ catch (YamlException e) { throw new ContentException(rel, $"line {e.Start.Line}", e.InnerException?.Message ?? e.Message); }
+ foreach (var k in StartOnlyKeys)
+ if (over.ContainsKey(k))
+ throw new ContentException(rel, k, k == "start" ? "an era cannot change the start date"
+ : "start values go in start/<era>.yaml (chapters spec section 6), not in an override");
+ var merged = NodeYaml.Deserialize<Dictionary<object, object>>(baseText) ?? new Dictionary<object, object>();
+ MergeNodes(merged, over);
+ try { result[era.Id!] = Yaml.Deserialize<Rules>(NodeWriter.Serialize(merged)) ?? throw new ContentException(rel, "(file)", "empty file"); }
+ catch (YamlException e) { throw new ContentException(rel, "(merged with rules.yaml)", e.InnerException?.Message ?? e.Message); }
+ }
+ return result;
+ }
+
+ static void MergeNodes(Dictionary<object, object> into, Dictionary<object, object> over)
+ {
+ foreach (var kv in over)
+ if (into.TryGetValue(kv.Key, out var cur) && cur is Dictionary<object, object> a && kv.Value is Dictionary<object, object> b) MergeNodes(a, b);
+ else into[kv.Key] = kv.Value;
+ }
+
static T Read<T>(Func<string, string?> readFile, string relPath)
{
string? text;
@@ -163,7 +216,9 @@ namespace Statecraft.Sim
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.Money = m.Money;
- c.Rules = Read<Rules>(readFile, "rules.yaml");
+ string rulesText = "";
+ c.Rules = Read<Rules>(p => { var t = readFile(p); rulesText = t ?? ""; return t; }, "rules.yaml");
+ c.EraRules = ReadEraRules(rulesText, readFile, c.Eras);
var aliyah = Read<AliyahFile>(readFile, "aliyah.yaml");
c.Aliyah = aliyah.Series; c.Regions = aliyah.Regions;
c.PopulationAnchors = Read<PopulationFile>(readFile, "population.yaml").Anchors;
@@ -214,11 +269,19 @@ namespace Statecraft.Sim
var eventFiles = Directory.Exists(eventsDir)
? Directory.GetFiles(eventsDir, "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList()
: new List<string>();
- return Load(rel =>
+ var content = Load(rel =>
{
var path = Path.Combine(contentRoot, rel);
return File.Exists(path) ? File.ReadAllText(path) : null;
}, eventFiles);
+ // Only this overload can list the directory. The readFile overload (WebGL) cannot, so a misnamed file is caught
+ // here and by RealContentTests before anything ships.
+ var rulesDir = Path.Combine(contentRoot, "rules");
+ if (Directory.Exists(rulesDir))
+ foreach (var f in Directory.GetFiles(rulesDir, "*.yaml").OrderBy(f => f, StringComparer.Ordinal))
+ if (!content.EraRules.ContainsKey(Path.GetFileNameWithoutExtension(f)))
+ throw new ContentException("rules/" + Path.GetFileName(f), "(file)", "the file name must be the id of an era in eras.yaml");
+ return content;
}
internal const string IdRule = "must be lowercase letters, digits and underscores, starting with a letter";
@@ -287,6 +350,66 @@ namespace Statecraft.Sim
}
}
+ /// <summary>Checks one complete rules set: rules.yaml itself, or an era's rules after its override is merged in.</summary>
+ static void ValidateRules(Content c, Rules r, string file, HashSet<string> indicators, HashSet<string> offices, HashSet<string> historicalOffices)
+ {
+ if (r.Start == default) throw new ContentException(file, "start", "required");
+ if (!(r.AttentionPerTurn >= 0 && !double.IsInfinity(r.AttentionPerTurn))) throw new ContentException(file, "attention_per_turn", "must be a finite non-negative number");
+ if (!(r.RungAttentionStep >= 0 && !double.IsInfinity(r.RungAttentionStep))) throw new ContentException(file, "rung_attention_step", "must be a finite non-negative number");
+ foreach (var kv in r.AttentionCost)
+ if (!(kv.Value >= 0 && !double.IsInfinity(kv.Value))) throw new ContentException(file, $"attention_cost.{kv.Key}", "must be a finite non-negative number");
+ foreach (var k in r.AttentionCost.Keys)
+ if (!AttentionSystem.IsCommandKind(k)) throw new ContentException(file, $"attention_cost.{k}", "unknown command kind");
+ foreach (var k in AttentionSystem.CommandKinds)
+ if (!r.AttentionCost.ContainsKey(k)) throw new ContentException(file, $"attention_cost.{k}", "missing cost");
+ if (r.RungMinMobilization.Count != 5) throw new ContentException(file, "rung_min_mobilization", "needs exactly 5 values (rungs 1-5)");
+ for (int i = 0; i < 5; i++)
+ {
+ var field = FormattableString.Invariant($"rung_min_mobilization[{i}]");
+ Unit(file, field, r.RungMinMobilization[i]);
+ if (i > 0 && r.RungMinMobilization[i] < r.RungMinMobilization[i - 1])
+ throw new ContentException(file, field, "must not be below the previous rung's floor");
+ }
+ if (r.StartRung < 1 || r.StartRung > 5) throw new ContentException(file, "start_rung", "must be 1-5");
+ if (r.CeasefireWeeks <= 0) throw new ContentException(file, "ceasefire_weeks", "must be > 0");
+ foreach (var (key, v) in new[] { ("treasury_start", r.TreasuryStart), ("fx_start", r.FxStart), ("tax_per_capita_per_year", r.TaxPerCapitaPerYear),
+ ("spending_per_capita_per_year", r.SpendingPerCapitaPerYear), ("exports_per_year", r.ExportsPerYear), ("imports_per_capita_per_year", r.ImportsPerCapitaPerYear),
+ ("mobilization_cost_per_year", r.MobilizationCostPerYear), ("natural_increase_per_year", r.NaturalIncreasePerYear),
+ ("capital_inflow_per_year", r.CapitalInflowPerYear), ("fx_crisis_food_per_year", r.FxCrisisFoodPerYear) })
+ Finite(file, key, v);
+ Unit(file, "appoint_stability_cost_other_party", r.AppointStabilityCostOtherParty);
+ Unit(file, "appoint_stability_cost_same_party", r.AppointStabilityCostSameParty);
+ if (r.MapActionMaxDistance < 0) throw new ContentException(file, "map_action_max_distance", "must be >= 0");
+ if (r.MapActionsPerTurn < 1) throw new ContentException(file, "map_actions_per_turn", "must be >= 1");
+ foreach (var kv in r.MapActions)
+ {
+ if (!MapActions.Actions.Contains(kv.Key)) throw new ContentException(file, $"map_actions.{kv.Key}", "unknown map action (transit_camp or housing)");
+ if (!(kv.Value.Cost >= 0 && IsFinite(kv.Value.Cost))) throw new ContentException(file, $"map_actions.{kv.Key}.cost", "must be a finite number >= 0");
+ Named(file, $"map_actions.{kv.Key}.name", kv.Value.Name);
+ foreach (var (key, v) in new[] { ("housing", kv.Value.Housing), ("morale", kv.Value.Morale) })
+ if (!(v >= -1 && v <= 1)) throw new ContentException(file, $"map_actions.{kv.Key}.{key}", "must be a number from -1 to 1");
+ }
+ if (r.MapActions.Count > 0 && r.MapActionsFrom == default) throw new ContentException(file, "map_actions_from", "required when map_actions are defined");
+ if (r.MapActions.Count > 0 && (!indicators.Contains("housing") || !indicators.Contains("morale")))
+ throw new ContentException(file, "map_actions", "needs housing and morale indicators in model.yaml");
+ if (r.FxCrisisFoodPerYear > 0) throw new ContentException(file, "fx_crisis_food_per_year", "must be <= 0 (a crisis cuts food imports)");
+ if (r.FxCrisisFoodPerYear < 0 && !indicators.Contains("food_supply")) throw new ContentException(file, "fx_crisis_food_per_year", "needs a food_supply indicator in model.yaml");
+ foreach (var kv in r.InitialPopulation) Count(file, $"initial_population.{kv.Key}", kv.Value);
+ foreach (var kv in r.BudgetStart)
+ {
+ if (!offices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "unknown office");
+ if (historicalOffices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "historical-only titles cannot have a budget line");
+ // A budget line must not silently stop mattering when its office is abolished: move it to the office that
+ // took over (plan amendment C3).
+ var until = c.Offices.First(o => o.Id == kv.Key).Until;
+ if (until.HasValue)
+ throw new ContentException(file, $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over"));
+ Unit(file, $"budget_start.{kv.Key}", kv.Value);
+ }
+ // The same rule EconomySystem.Allocate applies to every later allocation.
+ if (r.BudgetStart.Count > 0 && Math.Abs(r.BudgetStart.Values.Sum() - 1.0) > 1e-6) throw new ContentException(file, "budget_start", "shares must sum to 1");
+ }
+
static void Validate(Content c, List<string> settlementIds)
{
var offices = new HashSet<string>(c.Offices.Select(o => o.Id));
@@ -471,62 +594,9 @@ namespace Statecraft.Sim
Finite("model.yaml", $"voter_groups[{v.Id}].weights.{kv.Key}", kv.Value);
}
foreach (var a in c.Actors) Unit("model.yaml", $"actors[{a.Id}].standing", a.Standing);
- if (c.Rules.Start == default) throw new ContentException("rules.yaml", "start", "required");
- if (!(c.Rules.AttentionPerTurn >= 0 && !double.IsInfinity(c.Rules.AttentionPerTurn))) throw new ContentException("rules.yaml", "attention_per_turn", "must be a finite non-negative number");
- if (!(c.Rules.RungAttentionStep >= 0 && !double.IsInfinity(c.Rules.RungAttentionStep))) throw new ContentException("rules.yaml", "rung_attention_step", "must be a finite non-negative number");
- foreach (var kv in c.Rules.AttentionCost)
- if (!(kv.Value >= 0 && !double.IsInfinity(kv.Value))) throw new ContentException("rules.yaml", $"attention_cost.{kv.Key}", "must be a finite non-negative number");
- foreach (var k in c.Rules.AttentionCost.Keys)
- if (!AttentionSystem.IsCommandKind(k)) throw new ContentException("rules.yaml", $"attention_cost.{k}", "unknown command kind");
- foreach (var k in AttentionSystem.CommandKinds)
- if (!c.Rules.AttentionCost.ContainsKey(k)) throw new ContentException("rules.yaml", $"attention_cost.{k}", "missing cost");
- if (c.Rules.RungMinMobilization.Count != 5) throw new ContentException("rules.yaml", "rung_min_mobilization", "needs exactly 5 values (rungs 1-5)");
- for (int i = 0; i < 5; i++)
- {
- var field = FormattableString.Invariant($"rung_min_mobilization[{i}]");
- Unit("rules.yaml", field, c.Rules.RungMinMobilization[i]);
- if (i > 0 && c.Rules.RungMinMobilization[i] < c.Rules.RungMinMobilization[i - 1])
- throw new ContentException("rules.yaml", field, "must not be below the previous rung's floor");
- }
- if (c.Rules.StartRung < 1 || c.Rules.StartRung > 5) throw new ContentException("rules.yaml", "start_rung", "must be 1-5");
- if (c.Rules.CeasefireWeeks <= 0) throw new ContentException("rules.yaml", "ceasefire_weeks", "must be > 0");
- var r = c.Rules;
- foreach (var (key, v) in new[] { ("treasury_start", r.TreasuryStart), ("fx_start", r.FxStart), ("tax_per_capita_per_year", r.TaxPerCapitaPerYear),
- ("spending_per_capita_per_year", r.SpendingPerCapitaPerYear), ("exports_per_year", r.ExportsPerYear), ("imports_per_capita_per_year", r.ImportsPerCapitaPerYear),
- ("mobilization_cost_per_year", r.MobilizationCostPerYear), ("natural_increase_per_year", r.NaturalIncreasePerYear),
- ("capital_inflow_per_year", r.CapitalInflowPerYear), ("fx_crisis_food_per_year", r.FxCrisisFoodPerYear) })
- Finite("rules.yaml", key, v);
- Unit("rules.yaml", "appoint_stability_cost_other_party", r.AppointStabilityCostOtherParty);
- Unit("rules.yaml", "appoint_stability_cost_same_party", r.AppointStabilityCostSameParty);
- if (r.MapActionMaxDistance < 0) throw new ContentException("rules.yaml", "map_action_max_distance", "must be >= 0");
- if (r.MapActionsPerTurn < 1) throw new ContentException("rules.yaml", "map_actions_per_turn", "must be >= 1");
- foreach (var kv in r.MapActions)
- {
- if (!MapActions.Actions.Contains(kv.Key)) throw new ContentException("rules.yaml", $"map_actions.{kv.Key}", "unknown map action (transit_camp or housing)");
- if (!(kv.Value.Cost >= 0 && IsFinite(kv.Value.Cost))) throw new ContentException("rules.yaml", $"map_actions.{kv.Key}.cost", "must be a finite number >= 0");
- Named("rules.yaml", $"map_actions.{kv.Key}.name", kv.Value.Name);
- foreach (var (key, v) in new[] { ("housing", kv.Value.Housing), ("morale", kv.Value.Morale) })
- if (!(v >= -1 && v <= 1)) throw new ContentException("rules.yaml", $"map_actions.{kv.Key}.{key}", "must be a number from -1 to 1");
- }
- if (r.MapActions.Count > 0 && r.MapActionsFrom == default) throw new ContentException("rules.yaml", "map_actions_from", "required when map_actions are defined");
- if (r.MapActions.Count > 0 && (!indicators.Contains("housing") || !indicators.Contains("morale")))
- throw new ContentException("rules.yaml", "map_actions", "needs housing and morale indicators in model.yaml");
- if (r.FxCrisisFoodPerYear > 0) throw new ContentException("rules.yaml", "fx_crisis_food_per_year", "must be <= 0 (a crisis cuts food imports)");
- if (r.FxCrisisFoodPerYear < 0 && !indicators.Contains("food_supply")) throw new ContentException("rules.yaml", "fx_crisis_food_per_year", "needs a food_supply indicator in model.yaml");
- foreach (var kv in r.InitialPopulation) Count("rules.yaml", $"initial_population.{kv.Key}", kv.Value);
- foreach (var kv in r.BudgetStart)
- {
- if (!offices.Contains(kv.Key)) throw new ContentException("rules.yaml", $"budget_start.{kv.Key}", "unknown office");
- if (historicalOffices.Contains(kv.Key)) throw new ContentException("rules.yaml", $"budget_start.{kv.Key}", "historical-only titles cannot have a budget line");
- // A budget line must not silently stop mattering when its office is abolished: move it to the office that
- // took over (plan amendment C3).
- var until = c.Offices.First(o => o.Id == kv.Key).Until;
- if (until.HasValue)
- throw new ContentException("rules.yaml", $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over"));
- Unit("rules.yaml", $"budget_start.{kv.Key}", kv.Value);
- }
- // The same rule EconomySystem.Allocate applies to every later allocation.
- if (r.BudgetStart.Count > 0 && Math.Abs(r.BudgetStart.Values.Sum() - 1.0) > 1e-6) throw new ContentException("rules.yaml", "budget_start", "shares must sum to 1");
+ ValidateRules(c, c.Rules, "rules.yaml", indicators, offices, historicalOffices);
+ foreach (var kv in c.EraRules)
+ ValidateRules(c, kv.Value, "rules/" + kv.Key + ".yaml", indicators, offices, historicalOffices);
for (int i = 0; i < c.Aliyah.Count; i++)
{
var a = c.Aliyah[i]; var path = FormattableString.Invariant($"series[{i}]");
diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.cs
index e327aec3c..1672ad435 100644
--- a/unity/Assets/Scripts/Boot/ContentManifest.cs
+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs
@@ -23,14 +23,14 @@ namespace Statecraft.Game.Boot
[Serializable] sealed class ManifestJson { public string[] files = new string[0]; }
- /// <summary>Every *.yaml in <paramref name="contentDir"/>, events/ and map/ (but <see cref="ToolInputs"/>), plus
+ /// <summary>Every *.yaml in <paramref name="contentDir"/>, events/, map/ and rules/ (era rule overrides, #58; the folder may be absent) (but <see cref="ToolInputs"/>), plus
/// map/hexes.json; ordinal order.</summary>
public static List<string> Collect(string contentDir)
{
- IEnumerable<string> Yaml(string sub) => Directory.GetFiles(Path.Combine(contentDir, sub), "*.yaml")
+ IEnumerable<string> Yaml(string sub) => sub == "rules" && !Directory.Exists(Path.Combine(contentDir, sub)) ? new string[0] : Directory.GetFiles(Path.Combine(contentDir, sub), "*.yaml")
.Select(f => (sub == "" ? "" : sub + "/") + Path.GetFileName(f));
if (!File.Exists(Path.Combine(contentDir, HexesJson))) throw new FileNotFoundException("content file missing", HexesJson);
- return Yaml("").Concat(Yaml("events")).Concat(Yaml("map")).Append(HexesJson)
+ return Yaml("").Concat(Yaml("events")).Concat(Yaml("map")).Concat(Yaml("rules")).Append(HexesJson)
.Where(f => !ToolInputs.Contains(f)).OrderBy(f => f, StringComparer.Ordinal).ToList();
}
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 19f42da80..2a671c85b 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -30,6 +30,24 @@ public class GameInputsTests
Assert.AreEqual(files, ContentManifest.Parse(ContentManifest.Write(files)));
}
+ [Test]
+ public void TheManifestListsEraRuleOverridesAndToleratesNoRulesFolder()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "manifest-rules-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ Directory.CreateDirectory(Path.Combine(dir, "events"));
+ Directory.CreateDirectory(Path.Combine(dir, "map"));
+ File.WriteAllText(Path.Combine(dir, "people.yaml"), "people: []\n");
+ File.WriteAllText(Path.Combine(dir, "map", "hexes.json"), "{}");
+ CollectionAssert.DoesNotContain(ContentManifest.Collect(dir), "rules/later.yaml"); // no rules/ folder: fine
+ Directory.CreateDirectory(Path.Combine(dir, "rules"));
+ File.WriteAllText(Path.Combine(dir, "rules", "later.yaml"), "ceasefire_weeks: 4\n");
+ CollectionAssert.Contains(ContentManifest.Collect(dir), "rules/later.yaml"); // #58: players must get override files
+ }
+ finally { Directory.Delete(dir, true); }
+ }
+
[Test]
public void ABrokenManifestIsAClearError()
{