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.

5.5 KB
Raw Blame
# /// script
# requires-python = ">=3.11"
# dependencies = ["numpy==2.5.3", "pyyaml==6.0.3"]
# ///
"""Unit anchor -> hex for the simulation's starting forces (R-UNIT-006).

Usage: uv run tools/unit_anchor_hexes.py   (reads content/map/hexes.json and content/map/units_1948.yaml,
writes content/map/unit_anchor_hexes.yaml)
Each anchor's hex is the one holding its coordinates, by the map's projection and cube rounding (hexgrid.lonlat_to_km,
hexgrid.point_to_hex; Unity's HexPicker does the same), placed as the game places settlements (hexgrid.settlement_hex):
a point in a sea hex takes the nearest land neighbour, since the sim refuses a sea hex (#1183: Haifa at 4.4 km). An enemy
anchor whose hex holds a player's locality (a settlement not in rules.yaml mvp.enemy_held_localities) goes on the free land
neighbour nearest its own point, free meaning no settlement and no other anchor (owner, 22 October 2026, #1183 and #1305:
the Syrian Army's start and 11 June bridgehead), since the enemy may not move off a player's locality (Movement.NoEntry).
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), as for settlement_hexes.py."""
import json
import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import hexgrid as hg  # noqa: E402
import yaml12  # noqa: E402

ROOT = Path(__file__).resolve().parents[1]
MAP = ROOT / "content" / "map"
OUT = MAP / "unit_anchor_hexes.yaml"
HEADER = ("# Generated by tools/unit_anchor_hexes.py from units_1948.yaml and hexes.json (hexgrid.settlement_hex).\n"
          "# Do not edit by hand: rerun the tool after changing either input. anchor is the index in the row's anchors list,\n"
          "# target the index in its order_targets list (R-ENEMY-005: where an operation card may send the unit).\n")


def settlement_hexes() -> dict[tuple[int, int], str]:
    """Hex -> settlement id, from the committed settlement_hexes.yaml."""
    rows = yaml12.load((MAP / "settlement_hexes.yaml").read_text(encoding="utf-8"))["settlements"]
    return {(s["q"], s["r"]): s["id"] for s in rows}


def player_locality_hexes() -> set[tuple[int, int]]:
    """The hexes of settlements the enemy may not enter: every one not in mvp.enemy_held_localities (Movement.NoEntry).
    By id, not by settlement_hexes()'s one id per hex: Rehovot's (-4, 24), which Ramla shares (#1796), is the player's in
    any row order."""
    held = set(yaml12.load((ROOT / "content" / "rules.yaml").read_text(encoding="utf-8"))["mvp"]["enemy_held_localities"])
    rows = yaml12.load((MAP / "settlement_hexes.yaml").read_text(encoding="utf-8"))["settlements"]
    return {(s["q"], s["r"]) for s in rows if s["id"] not in held}


# An order target sent to a settlement whose capture target is not its own hex goes to that capture target, or the order
# could never take the place (owner, 2 November 2026, #2087: "Send it to Ramla's target (Recommended)"): at 4.4 km Ramle's
# point lies in (-4, 24), which Ramla shares with Rehovot, and Ramla's capture target is its neighbour (-3, 24) in
# settlement_targets.yaml (owner on #1796, 26 October 2026, "Contested + move target"). Keyed by (row id, target index).
ORDER_TARGET_ON_CAPTURE_HEX = {("kiryati", 0): "ramla"}


def capture_hex(settlement: str) -> tuple[int, int]:
    """The capture target hex settlement_targets.yaml gives a settlement."""
    rows = yaml12.load((ROOT / "content" / "settlement_targets.yaml").read_text(encoding="utf-8"))["targets"]
    row = next(t for t in rows if t["id"] == settlement)
    return row["q"], row["r"]


def render(hexes: dict, units: list[dict]) -> str:
    """The file text: one flow mapping per anchor, then per order target, in units_1948.yaml order."""
    placed = [(u, k, a, hg.settlement_hex(a["lon"], a["lat"], hexes))
              for u in units for k, a in enumerate(u.get("anchors") or [])]
    player, taken = player_locality_hexes(), set(settlement_hexes()) | {h for *_, h in placed}
    land = {(h["q"], h["r"]) for h in hexes["hexes"] if h["land"]}
    lines = [HEADER, "anchors:\n"]
    for u, k, a, (q, r) in placed:
        if u.get("side") != "israel" and (q, r) in player:
            free = [c for dq, dr in hg.NEIGHBOURS if (c := (q + dq, r + dr)) in land and c not in taken]
            if not free:
                raise ValueError(f"{u['id']} anchor {k}: no free land hex next to ({q}, {r})")
            p = hg.lonlat_to_km(a["lon"], a["lat"], hexes["bounds"])
            q, r = min(free, key=lambda c: math.dist(hg.hex_center_km(*c, hexes["hex_size_km"]), p))
            taken.add((q, r))
        lines.append(f"  - {{ id: {u['id']}, anchor: {k}, q: {q}, r: {r} }}\n")
    # An order target is where a card sends the player's own unit, so it takes the anchors' placement rule
    # (settlement_hex) and never the enemy's free-neighbour rule; it is not added to taken, so no anchor moves for it.
    lines.append("order_targets:\n")
    for u in units:
        for k, a in enumerate(u.get("order_targets") or []):
            place = ORDER_TARGET_ON_CAPTURE_HEX.get((u["id"], k))
            q, r = capture_hex(place) if place else hg.settlement_hex(a["lon"], a["lat"], hexes)
            lines.append(f"  - {{ id: {u['id']}, target: {k}, q: {q}, r: {r} }}\n")
    return "".join(lines)


def main() -> None:
    hexes = json.loads((MAP / "hexes.json").read_text())
    units = yaml12.load((MAP / "units_1948.yaml").read_text(encoding="utf-8"))["units"]
    OUT.write_text(render(hexes, units))
    print(f"wrote {OUT.relative_to(ROOT)} ({len(units)} units)")


if __name__ == "__main__":
    main()