A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
feat(tools,sim): settlement hexes by the hexgrid rule; the sim loads the hex map
eyalgolan3d365681db01
diff --git a/content/map/settlement_hexes.yaml b/content/map/settlement_hexes.yamlnew file mode 100644index 000000000..a4d04be27--- /dev/null+++ b/content/map/settlement_hexes.yaml@@ -0,0 +1,28 @@+# Generated by tools/settlement_hexes.py from settlements_1948.yaml and hexes.json (hexgrid.settlement_hex).+# Do not edit by hand: rerun the tool after changing either input.+settlements:+ - { id: jerusalem, q: 0, r: 23 }+ - { id: tel_aviv, q: -3, r: 19 }+ - { id: jaffa, q: -3, r: 19 }+ - { id: haifa, q: 5, r: 8 }+ - { id: acre, q: 7, r: 6 }+ - { id: tiberias, q: 10, r: 8 }+ - { id: safed, q: 11, r: 6 }+ - { id: nazareth, q: 7, r: 10 }+ - { id: lod, q: -3, r: 21 }+ - { id: ramla, q: -3, r: 21 }+ - { id: gaza, q: -11, r: 27 }+ - { id: beersheba, q: -9, r: 31 }+ - { id: petah_tikva, q: -2, r: 19 }+ - { id: rishon_lezion, q: -4, r: 21 }+ - { id: zikhron_yaakov, q: 3, r: 11 }+ - { id: rosh_pinna, q: 12, r: 6 }+ - { id: rehovot, q: -4, r: 21 }+ - { id: hadera, q: 1, r: 13 }+ - { id: netanya, q: 0, r: 15 }+ - { id: degania_alef, q: 10, r: 10 }+ - { id: ein_harod, q: 7, r: 12 }+ - { id: nahalal, q: 6, r: 10 }+ - { id: hanita, q: 9, r: 4 }+ - { id: revivim, q: -11, r: 34 }+ - { id: yad_mordechai, q: -9, r: 26 }diff --git a/docs/determinism.md b/docs/determinism.mdindex 106d8a14a..a3a8fb4b0 100644--- a/docs/determinism.md+++ b/docs/determinism.md@@ -9,6 +9,8 @@ The simulation must produce the same state, bit for bit, on .NET, Unity Mono and- **Reference vectors:** `DeterminismTests.SplitMix64MatchesTheReferenceVectors` checks the first three outputs forseeds 0 and 1234567. The expected values come from Sebastiano Vigna's reference `splitmix64.c`(https://prng.di.unimi.it/splitmix64.c), compiled and run separately. They were not copied from this implementation.+- **No trigonometry in the sim:** the sim calls only `Math.Abs`, `Math.Min` and `Math.Max`. Geometry that needs+ cos/sin (which hex owns a settlement) is precomputed by `tools/settlement_hexes.py` and read as content.- **Canonical hash:** `GameState.Hash()` is SHA-256 over a canonical text. Keys are sorted ordinally. Doubles arewritten as IEEE bit patterns, with -0.0 written as 0.0. Culture is invariant.diff --git a/sim/Statecraft.Sim.Tests/Fixture.cs b/sim/Statecraft.Sim.Tests/Fixture.csindex 5f950b081..de5073f6f 100644--- a/sim/Statecraft.Sim.Tests/Fixture.cs+++ b/sim/Statecraft.Sim.Tests/Fixture.cs@@ -133,6 +133,22 @@ budget_start: { finance_minister: 1.0 }",["population.yaml"] = @"anchors: []+",+ // A 5 x 2 map: one sea hex, the rest land; one settlement at (1, 0).+ ["map/hexes.json"] = @"{""attribution"":[""test""],""bounds"":{""lon0"":34.2,""lon1"":35.9,""lat0"":29.45,""lat1"":33.35},""hex_size_km"":5.0,""layout"":""pointy"",""hexes"":[+{""q"":0,""r"":0,""lon"":34.2,""lat"":33.35,""elev_m"":0.0,""land"":false,""biome"":""sea""},+{""q"":1,""r"":0,""lon"":34.29,""lat"":33.35,""elev_m"":20.0,""land"":true,""biome"":""coastal_plain""},+{""q"":2,""r"":0,""lon"":34.38,""lat"":33.35,""elev_m"":250.0,""land"":true,""biome"":""hills""},+{""q"":3,""r"":0,""lon"":34.47,""lat"":33.35,""elev_m"":300.0,""land"":true,""biome"":""hills""},+{""q"":4,""r"":0,""lon"":34.56,""lat"":33.35,""elev_m"":100.0,""land"":true,""biome"":""desert""},+{""q"":0,""r"":1,""lon"":34.24,""lat"":33.28,""elev_m"":10.0,""land"":true,""biome"":""coastal_plain""},+{""q"":1,""r"":1,""lon"":34.33,""lat"":33.28,""elev_m"":40.0,""land"":true,""biome"":""coastal_plain""},+{""q"":2,""r"":1,""lon"":34.42,""lat"":33.28,""elev_m"":260.0,""land"":true,""biome"":""hills""},+{""q"":3,""r"":1,""lon"":34.51,""lat"":33.28,""elev_m"":120.0,""land"":true,""biome"":""desert""}]}+",+ ["map/settlement_hexes.yaml"] = @"+settlements:+ - { id: town_a, q: 1, r: 0 }",["aliyah.yaml"] = @"series:@@ -146,6 +162,7 @@ series:{var dir = Path.Combine(Path.GetTempPath(), "statecraft-fixture-" + Guid.NewGuid().ToString("N"));Directory.CreateDirectory(Path.Combine(dir, "events"));+ Directory.CreateDirectory(Path.Combine(dir, "map"));foreach (var kv in Files)File.WriteAllText(Path.Combine(dir, kv.Key), overrides != null && overrides.TryGetValue(kv.Key, out var o) ? o : kv.Value);if (events != null)diff --git a/sim/Statecraft.Sim.Tests/MapContentTests.cs b/sim/Statecraft.Sim.Tests/MapContentTests.csnew file mode 100644index 000000000..90f2f1363--- /dev/null+++ b/sim/Statecraft.Sim.Tests/MapContentTests.cs@@ -0,0 +1,63 @@+using System.Collections.Generic;+using System.Linq;+using Statecraft.Sim;++/// <summary>content/map/hexes.json and settlement_hexes.yaml as the sim loads them.</summary>+public class MapContentTests+{+ [Fact]+ public void TheFixtureMapLoads()+ {+ var c = ContentLoader.Load(Fixture.Write());+ Assert.Equal(9, c.Hexes.Count);+ Assert.False(c.HexAt(0, 0)!.Land);+ Assert.Equal("hills", c.HexAt(2, 1)!.Biome);+ Assert.Null(c.HexAt(9, 9));+ Assert.Equal(("town_a", 1, 0), (c.SettlementHexes[0].Id, c.SettlementHexes[0].Q, c.SettlementHexes[0].R));+ }++ [Fact]+ public void ASettlementOnASeaHexIsALoadError()+ {+ var bad = Fixture.Files["map/settlement_hexes.yaml"].Replace("q: 1, r: 0", "q: 0, r: 0");+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/settlement_hexes.yaml"] = bad })));+ Assert.Equal("map/settlement_hexes.yaml", ex.File);+ Assert.Equal("settlements[town_a]", ex.Field);+ Assert.Contains("hex q=0 r=0 is not a land hex", ex.Message);+ }++ [Fact]+ public void ASettlementOffTheMapIsALoadError()+ {+ var bad = Fixture.Files["map/settlement_hexes.yaml"].Replace("q: 1, r: 0", "q: 40, r: 0");+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/settlement_hexes.yaml"] = bad })));+ Assert.Contains("hex q=40 r=0 is not a land hex", ex.Message);+ }++ [Fact]+ public void ADuplicateHexIsALoadError()+ {+ var bad = Fixture.Files["map/hexes.json"].Replace(@"{""q"":4,""r"":0,", @"{""q"":3,""r"":0,");+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/hexes.json"] = bad })));+ Assert.Equal("map/hexes.json", ex.File);+ Assert.Equal("hexes[q=3,r=0]", ex.Field);+ }++ [Fact]+ public void AnUnknownKeyInHexesJsonIsALoadError()+ {+ var bad = Fixture.Files["map/hexes.json"].Replace(@"""layout""", @"""layuot""");+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/hexes.json"] = bad })));+ Assert.Equal("map/hexes.json", ex.File);+ }++ [Fact]+ public void TheRealMapHas1102HexesAndEvery1948Settlement()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ Assert.Equal(1102, c.Hexes.Count);+ Assert.Equal(870, c.Hexes.Count(h => h.Land));+ Assert.Equal(25, c.SettlementHexes.Count);+ Assert.Contains(c.SettlementHexes, s => s.Id == "tiberias");+ }+}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex 8f640e0a1..06ccb8259 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -189,6 +189,27 @@ namespace Statecraft.Sim[YamlIgnore] public string File { get; set; } = "";}+ /// <summary>One hex of content/map/hexes.json (written by tools/hexgrid.py; axial q, r, pointy-top).</summary>+ public sealed class MapHex+ {+ public int Q { get; set; }+ public int R { get; set; }+ public double Lon { get; set; }+ public double Lat { get; set; }+ public double ElevM { get; set; }+ public bool Land { get; set; }+ public string Biome { get; set; } = "";+ }++ /// <summary>The hex that owns a settlement (content/map/settlement_hexes.yaml, written by tools/settlement_hexes.py+ /// with the hexgrid.settlement_hex rule).</summary>+ public sealed class SettlementHex+ {+ public string Id { get; set; } = "";+ public int Q { get; set; }+ public int R { get; set; }+ }+public sealed class Content{public List<Office> Offices = new List<Office>();@@ -206,6 +227,21 @@ namespace Statecraft.Simpublic List<AliyahPeriod> Aliyah = new List<AliyahPeriod>();public List<PopulationAnchor> PopulationAnchors = new List<PopulationAnchor>();public List<GameEvent> Events = new List<GameEvent>();+ public List<MapHex> Hexes = new List<MapHex>();+ public List<SettlementHex> SettlementHexes = new List<SettlementHex>();+ Dictionary<(int, int), MapHex>? _hexIndex;++ /// <summary>The hex at axial (q, r), or null when the map has none there.</summary>+ public MapHex? HexAt(int q, int r)+ {+ if (_hexIndex == null)+ {+ var index = new Dictionary<(int, int), MapHex>();+ foreach (var h in Hexes) index[(h.Q, h.R)] = h;+ _hexIndex = index;+ }+ return _hexIndex.TryGetValue((q, r), out var hex) ? hex : null;+ }}public sealed class ContentException : Exceptiondiff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex ad4453b22..6fddc21fc 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -28,6 +28,20 @@ namespace Statecraft.Sim}sealed class AliyahFile { public List<AliyahPeriod> Series { get; set; } = new List<AliyahPeriod>(); }sealed class PopulationFile { public List<PopulationAnchor> Anchors { get; set; } = new List<PopulationAnchor>(); }+ sealed class HexBounds { public double Lon0 { get; set; } public double Lon1 { get; set; } public double Lat0 { get; set; } public double Lat1 { get; set; } }+ /// <summary>hexes.json is JSON, which YAML 1.2 reads as a flow mapping; every key the tool writes is declared.</summary>+ sealed class MapFile+ {+ public List<string> Attribution { get; set; } = new List<string>();+ public HexBounds Bounds { get; set; } = new HexBounds();+ public double HexSizeKm { get; set; }+ public string Layout { get; set; } = "";+ public List<MapHex> Hexes { get; set; } = new List<MapHex>();+ }+ sealed class SettlementHexesFile { public List<SettlementHex> Settlements { get; set; } = new List<SettlementHex>(); }++ public const string HexesFile = "map/hexes.json";+ public const string SettlementHexesFileName = "map/settlement_hexes.yaml";static readonly IDeserializer Yaml = new DeserializerBuilder().WithNamingConvention(UnderscoredNamingConvention.Instance)@@ -103,6 +117,8 @@ namespace Statecraft.Simc.Rules = Read<Rules>(readFile, "rules.yaml");c.Aliyah = Read<AliyahFile>(readFile, "aliyah.yaml").Series;c.PopulationAnchors = Read<PopulationFile>(readFile, "population.yaml").Anchors;+ c.Hexes = Read<MapFile>(readFile, HexesFile).Hexes;+ c.SettlementHexes = Read<SettlementHexesFile>(readFile, SettlementHexesFileName).Settlements;foreach (var rel in eventFiles.OrderBy(p => p, StringComparer.Ordinal)){var e = Read<GameEvent>(readFile, rel);@@ -364,7 +380,27 @@ namespace Statecraft.Simif (a.Date == default) throw new ContentException("population.yaml", path + ".date", "required");Count("population.yaml", path + ".jews", a.Jews);}+ ValidateMap(c);EventRules.Validate(c, offices, indicators);}++ static void ValidateMap(Content c)+ {+ if (c.Hexes.Count == 0) throw new ContentException(HexesFile, "hexes", "no hexes");+ var seen = new HashSet<(int, int)>();+ foreach (var h in c.Hexes)+ {+ var at = FormattableString.Invariant($"hexes[q={h.Q},r={h.R}]");+ if (!seen.Add((h.Q, h.R))) throw new ContentException(HexesFile, at, "duplicate hex");+ if (h.Biome == "") throw new ContentException(HexesFile, at + ".biome", "required");+ }+ Unique(SettlementHexesFileName, "settlements", c.SettlementHexes.Select(s => s.Id));+ foreach (var s in c.SettlementHexes)+ {+ var hex = c.HexAt(s.Q, s.R);+ if (hex == null || !hex.Land)+ throw new ContentException(SettlementHexesFileName, $"settlements[{s.Id}]", FormattableString.Invariant($"hex q={s.Q} r={s.R} is not a land hex in {HexesFile}"));+ }+ }}}diff --git a/tools/README.md b/tools/README.mdindex 29f8b7278..f808f7788 100644--- a/tools/README.md+++ b/tools/README.md@@ -9,6 +9,8 @@ Offline data tools (uv inline-script Python). Run from the repo root.- `ims_normals.py` downloads Israel Meteorological Service rain-gauge records from data.gov.il into `tools/.cache/ims/`(not committed) and writes the 1981-2010 station normals `content/map/precip_stations.json` (committed).- `hexgrid.py` writes `content/map/hexes.json` from the heightmap and those committed precipitation inputs (no network).+- `settlement_hexes.py` writes `content/map/settlement_hexes.yaml` (committed): the hex that owns each settlement, by the+ `hexgrid.settlement_hex` rule. The sim reads it, so it needs no projection maths.- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.## Running the tests@@ -19,7 +21,7 @@ Run from the repo root; this installs every pinned dependency (rasterio includeduv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q```-Expected: `93 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.+Expected: `96 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.## Required attribution (Copernicus DEM licence, modified data)diff --git a/tools/settlement_hexes.py b/tools/settlement_hexes.pynew file mode 100644index 000000000..94144c8af--- /dev/null+++ b/tools/settlement_hexes.py@@ -0,0 +1,45 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["numpy==2.5.3", "pyyaml==6.0.3"]+# ///+"""Settlement -> hex ownership for the simulation.++Usage: uv run tools/settlement_hexes.py (reads content/map/hexes.json and content/map/settlements_1948.yaml,+writes content/map/settlement_hexes.yaml)+The rule is hexgrid.settlement_hex: the hex containing the settlement if it is land, else the land neighbour with the+nearest centre (Tiberias). The sim reads the result instead of re-implementing the projection, so it needs no+trigonometry (docs/determinism.md: no libm calls in the sim)."""+import json+import sys+from pathlib import Path++import yaml++sys.path.insert(0, str(Path(__file__).resolve().parent))+import hexgrid as hg # noqa: E402++ROOT = Path(__file__).resolve().parents[1]+MAP = ROOT / "content" / "map"+OUT = MAP / "settlement_hexes.yaml"+HEADER = ("# Generated by tools/settlement_hexes.py from settlements_1948.yaml and hexes.json (hexgrid.settlement_hex).\n"+ "# Do not edit by hand: rerun the tool after changing either input.\n")+++def render(hexes: dict, settlements: list[dict]) -> str:+ """The file text: one flow mapping per settlement, in settlements_1948.yaml order."""+ lines = [HEADER, "settlements:\n"]+ for s in settlements:+ q, r = hg.settlement_hex(s["lon"], s["lat"], hexes)+ lines.append(f" - {{ id: {s['id']}, q: {q}, r: {r} }}\n")+ return "".join(lines)+++def main() -> None:+ hexes = json.loads((MAP / "hexes.json").read_text())+ settlements = yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]+ OUT.write_text(render(hexes, settlements))+ print(f"wrote {OUT.relative_to(ROOT)} ({len(settlements)} settlements)")+++if __name__ == "__main__":+ main()diff --git a/tools/tests/test_settlement_hexes.py b/tools/tests/test_settlement_hexes.pynew file mode 100644index 000000000..ca9d98706--- /dev/null+++ b/tools/tests/test_settlement_hexes.py@@ -0,0 +1,31 @@+"""content/map/settlement_hexes.yaml is the committed output of tools/settlement_hexes.py and must stay in sync."""+import json+from pathlib import Path++import yaml++import hexgrid as hg+import settlement_hexes as sh++ROOT = Path(__file__).resolve().parents[2]+MAP = ROOT / "content" / "map"+HEXES = json.loads((MAP / "hexes.json").read_text())+TOWNS = yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]+BY_QR = {(h["q"], h["r"]): h for h in HEXES["hexes"]}+++def test_committed_file_is_up_to_date():+ assert (MAP / "settlement_hexes.yaml").read_text() == sh.render(HEXES, TOWNS), "rerun: uv run tools/settlement_hexes.py"+++def test_every_settlement_is_on_its_rule_hex_and_that_hex_is_land():+ rows = yaml.safe_load((MAP / "settlement_hexes.yaml").read_text())["settlements"]+ assert [r["id"] for r in rows] == [t["id"] for t in TOWNS]+ for row, town in zip(rows, TOWNS):+ assert (row["q"], row["r"]) == hg.settlement_hex(town["lon"], town["lat"], HEXES), row["id"]+ assert BY_QR[(row["q"], row["r"])]["land"], row["id"]+++def test_tiberias_is_moved_off_the_lake():+ rows = {r["id"]: r for r in yaml.safe_load((MAP / "settlement_hexes.yaml").read_text())["settlements"]}+ assert BY_QR[(rows["tiberias"]["q"], rows["tiberias"]["r"])]["biome"] != "lake"