The workshop / game/data/check.py
check.py
Last changed by Sven, 28 h ago. “The lead, in words: 2 tip lines per suspect + generic, {other} {time}, no room, no sighting; notebook.tip 'LEAD: ...'. check.py enforces it. 76 tests pass.”
What this change did
⋯ } REQUIRED.update({"saw_never": ["{other}"], "body": ["{victim}", "{room}"]})+ # The lead of a broken innocent (decision on reckoned): who and which half-hour,+ # never a room and never a sighting. It is gossip, not a witness statement.+ ALLOWED["tip"] = {"other", "time"}+ REQUIRED["tip"] = ["{other}", "{time}"]+ SIGHTING = re.compile(r"(saw|seen|spotted|noticed them|caught them)", re.I) ENDINGS = ["proven", "unproven", "wrong", "docked", "reckoned"] # Day two. The culprit and the crosser admit the body room from ONE pool of lines⋯ if TELLS.search(t): err("lines.json %s: an admission says how the purser was: %r" % (where, t[:60]))+ def check_tips(block, where):+ for tline in block.get("tip", []):+ if SIGHTING.search(tline):+ err("lines.json %s tip: a lead must not claim a sighting: %r" % (where, tline[:60]))+ check_tips(lines.get("generic", {}), "generic")+ for sid, block in lines.get("by_suspect", {}).items():+ check_tips(block, sid)+ if "tip" not in block:+ err("lines.json by_suspect %s: no tip line (the lead would fall back to generic)" % sid)+ nb = lines.get("notebook", {}).get("tip")+ if nb is not None:+ check_text(nb, "lines.json notebook tip", {"speaker", "other", "time"}) check_block(lines.get("generic", {}), "generic") check_admissions(lines.get("generic", {}), "generic")⋯
The whole file
"""Content checker for DEAD RECKONING. Pure Python, no imports from the engine.
python game/data/check.py
Exit code 0 when the data files obey team/INTERFACE.md section 3, 1 otherwise.
Files that do not exist yet are reported as missing but do not fail the run.
"""
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ID = re.compile(r"^[a-z0-9_]+$")
REQUIRED = {
"where": ["{room}", "{time}"],
"saw": ["{other}", "{room}", "{time}"],
"saw_nobody": ["{room}", "{time}"],
"heard": ["{room}", "{time}", "{time2}"],
"heard_window": ["{room}", "{time}", "{time2}"],
"broken_culprit": ["{room}", "{time}"],
"broken_crosser_before": ["{room}", "{time}"],
"broken_crosser_after": ["{room}", "{time}"],
"broken_secret": ["{secret}"],
}
ALLOWED = {
"where": {"room", "time"}, "saw": {"other", "room", "time"},
"saw_nobody": {"room", "time"}, "heard": {"room", "time", "time2"},
"heard_window": {"room", "time", "time2"},
"broken_culprit": {"room", "time"}, "broken_secret": {"secret"},
"broken_crosser_before": {"room", "time"}, "broken_crosser_after": {"room", "time"},
"refuse": set(), "not_a_contradiction": set(),
"saw_never": {"other"}, "heard_nothing": set(), "body": {"victim", "room"},
}
REQUIRED.update({"saw_never": ["{other}"], "body": ["{victim}", "{room}"]})
# The lead of a broken innocent (decision on reckoned): who and which half-hour,
# never a room and never a sighting. It is gossip, not a witness statement.
ALLOWED["tip"] = {"other", "time"}
REQUIRED["tip"] = ["{other}", "{time}"]
SIGHTING = re.compile(r"(saw|seen|spotted|noticed them|caught them)", re.I)
ENDINGS = ["proven", "unproven", "wrong", "docked", "reckoned"]
# Day two. The culprit and the crosser admit the body room from ONE pool of lines
# per speaker: if the three lists differ, or a line says how the purser was, the
# admission confesses by its shape.
ADMISSIONS = ["broken_culprit", "broken_crosser_before", "broken_crosser_after"]
TELLS = re.compile(r"(alive|dead|breath\w*|pulse|body|standing|upright|on his feet)", re.I)
# system lines: one text per key, with the fields the engine fills
UI = {
"nobody": set(), "time": {"clock", "left"}, "log_found": {"room", "count"},
"already_searched": {"room"}, "already_broken": set(), "trace_not_yet": {"name"},
"notebook_empty": set(), "summary_solution": {"culprit", "weapon", "room", "time"},
"summary_lie": {"name", "time", "claimed", "room"}, "summary_left": {"left"},
"people_head": set(), "people_again": set(),
"asked_already": {"name"}, "asked_nothing": {"name"},
# the last scene of the ending `reckoned` (design/GDD.md)
"reckoned_night_head": set(), "reckoned_lie": {"time", "name", "claimed", "room"},
"reckoned_murder": {"time", "room", "culprit"}, "reckoned_let_off_head": set(),
"reckoned_motive_head": {"culprit"}, "reckoned_last": {"left"},
}
ENDING_FIELDS = {"culprit", "weapon", "room", "time", "motive"}
errors = []
def err(msg):
errors.append(msg)
def load(name):
path = os.path.join(HERE, name)
if not os.path.exists(path):
print("missing: %s (skipped)" % name)
return None
with open(path, encoding="utf-8") as f:
return json.load(f)
def fields(text):
# {in_room} is prep + name and counts as {room}
return set(re.findall(r"\{([a-z_]+)\}", text.replace("{in_room}", "{room}")))
def sentences(text):
return len([s for s in re.split(r"(?<=[.!?])\s+", text.strip()) if s])
seen_ids = {}
def use_id(i, where):
if not isinstance(i, str) or not ID.match(i):
err("%s: bad id %r" % (where, i))
if i in seen_ids:
err("%s: id %r already used in %s" % (where, i, seen_ids[i]))
seen_ids[i] = where
def check_text(text, where, allowed=frozenset()):
if not isinstance(text, str) or not text.strip():
err("%s: empty text" % where)
return
if text.startswith("TODO "):
return
bad = fields(text) - set(allowed)
if bad:
err("%s: placeholder not allowed here: %s" % (where, sorted(bad)))
if text != text.strip() or " " in text:
err("%s: stray spaces" % where)
rooms = load("rooms.json")
chars = load("characters.json")
items = load("items.json")
lines = load("lines.json")
room_ids, suspect_ids = set(), set()
n_rooms = n_chars = n_items = n_lines = n_todo = 0
if rooms:
rs = rooms["rooms"]
n_rooms = len(rs)
by = {}
for r in rs:
use_id(r.get("id"), "rooms.json")
by[r["id"]] = r
for k in ("name", "deck", "desc", "exits", "private", "empty_search"):
if k not in r:
err("rooms.json %s: missing %s" % (r["id"], k))
check_text(r.get("desc", ""), "rooms.json %s desc" % r["id"])
check_text(r.get("empty_search", ""), "rooms.json %s empty_search" % r["id"])
if sentences(r.get("desc", "")) > 3:
err("rooms.json %s: desc has more than three sentences" % r["id"])
if "brief" in r:
check_text(r["brief"], "rooms.json %s brief" % r["id"])
if sentences(r["brief"]) != 1:
err("rooms.json %s: brief must be one sentence" % r["id"])
if r.get("private") and "log" not in r["brief"].lower() and "writes down" not in r["brief"].lower():
err("rooms.json %s: a private room's brief must still say the door keeps a log" % r["id"])
if r.get("prep", "in") not in ("in", "on"):
err("rooms.json %s: prep must be in or on" % r["id"])
room_ids = set(by)
names = [r["name"] for r in rs]
for n in set(names):
if names.count(n) > 1:
err("rooms.json: two rooms are named %r" % n)
for r in rs:
if not r["exits"]:
err("rooms.json %s: no exits" % r["id"])
if len(set(r["exits"])) != len(r["exits"]):
err("rooms.json %s: an exit is listed twice" % r["id"])
for e in r["exits"]:
if e not in by:
err("rooms.json %s: exit to unknown room %r" % (r["id"], e))
elif r["id"] not in by[e]["exits"]:
err("rooms.json %s -> %s: exit is not mutual" % (r["id"], e))
if e == r["id"]:
err("rooms.json %s: exits to itself" % r["id"])
start = rs[0]["id"]
reach, todo = {start}, [start]
while todo:
for e in by[todo.pop()]["exits"]:
if e in by and e not in reach:
reach.add(e)
todo.append(e)
for i in sorted(room_ids - reach):
err("rooms.json %s: unreachable from %s" % (i, start))
seen_ids = {k: v for k, v in seen_ids.items() if v != "rooms.json"}
if chars:
use_id(chars["victim"]["id"], "characters.json")
for k in ("name", "role", "desc"):
check_text(chars["victim"].get(k, ""), "characters.json victim %s" % k)
check_text(chars["player"].get("intro", ""), "characters.json player intro")
check_text(chars["player"].get("role", ""), "characters.json player role")
n_chars = 2 + len(chars["suspects"])
n_lines += 1
shorts = set()
sub_ids = set()
for s in chars["suspects"]:
w = "characters.json %s" % s.get("id")
use_id(s.get("id"), "characters.json")
suspect_ids.add(s["id"])
for k in ("name", "short", "role", "desc", "habit", "greeting"):
check_text(s.get(k, ""), "%s %s" % (w, k))
n_lines += 1
sh = s.get("short", "")
if " " in sh or sh.lower() in shorts:
err("%s: short %r must be one word and unique" % (w, sh))
shorts.add(sh.lower())
if sh.lower() in ("noise", "about"):
err("%s: short %r clashes with a command word" % (w, sh))
if room_ids:
if s.get("home") not in room_ids:
err("%s: unknown home %r" % (w, s.get("home")))
for h in s.get("haunts", []):
if h not in room_ids:
err("%s: unknown haunt %r" % (w, h))
if s.get("home") not in s.get("haunts", []):
err("%s: home is not among haunts" % w)
if len(s.get("motives", [])) != 2:
err("%s: needs exactly 2 motives" % w)
for m in s.get("motives", []):
if m["id"] in sub_ids:
err("%s: motive id %r used twice" % (w, m["id"]))
sub_ids.add(m["id"])
check_text(m["text"], "%s motive %s" % (w, m["id"]))
sec = s.get("secret", {})
if sec.get("id") in sub_ids:
err("%s: secret id %r used twice" % (w, sec.get("id")))
sub_ids.add(sec.get("id"))
if sec.get("room") not in s.get("haunts", []):
err("%s: secret room %r is not one of the haunts" % (w, sec.get("room")))
check_text(sec.get("text", ""), "%s secret" % w, {"room", "time"})
# reckoned: the innocent let off by name, the culprit stating the motive
check_text(sec.get("let_off", ""), "%s secret let_off" % w)
if s.get("name", "") not in sec.get("let_off", ""):
err("%s: secret let_off must name %s in full" % (w, s.get("name")))
for m in s.get("motives", []):
check_text(m.get("says", ""), "%s motive %s says" % (w, m.get("id")))
# the crosser is let off with `crossing` (why they were by the body), not the secret
check_text(s.get("crossing", ""), "%s crossing" % w)
if s.get("name", "") not in s.get("crossing", ""):
err("%s: crossing must name %s in full" % (w, s.get("name")))
for p in ("{room}", "{time}"):
if p not in sec.get("text", "").replace("{in_room}", "{room}"):
err("%s: secret text lacks %s" % (w, p))
seen_ids = {k: v for k, v in seen_ids.items() if v != "characters.json"}
if items:
names = []
for w in items.get("weapons", []):
use_id(w.get("id"), "items.json")
if room_ids and w.get("from") not in room_ids:
err("items.json %s: unknown room in from: %r" % (w["id"], w.get("from")))
check_text(w.get("desc", ""), "items.json %s desc" % w["id"])
check_text(w.get("found", ""), "items.json %s found" % w["id"], {"room"})
if "{room}" not in w.get("found", "").replace("{in_room}", "{room}"):
err("items.json %s: found lacks {room}" % w["id"])
names.append(w.get("name"))
owners = set()
for t in items.get("traces", []):
use_id(t.get("id"), "items.json")
if suspect_ids and t.get("owner") not in suspect_ids:
err("items.json %s: unknown owner %r" % (t["id"], t.get("owner")))
owners.add(t.get("owner"))
check_text(t.get("desc", ""), "items.json %s desc" % t["id"])
check_text(t.get("found", ""), "items.json %s found" % t["id"], {"room"})
if "{room}" not in t.get("found", "").replace("{in_room}", "{room}"):
err("items.json %s: found lacks {room}" % t["id"])
names.append(t.get("name"))
for s in sorted(suspect_ids - owners):
err("items.json: suspect %s has no trace" % s)
for p in items.get("props", []):
use_id(p.get("id"), "items.json")
if room_ids and p.get("room") not in room_ids:
err("items.json %s: unknown room %r" % (p["id"], p.get("room")))
check_text(p.get("desc", ""), "items.json %s desc" % p["id"])
names.append(p.get("name"))
for n in set(names):
if not n or names.count(n) > 1:
err("items.json: item name %r is empty or used twice" % n)
if len(items.get("weapons", [])) < 6:
err("items.json: fewer than 6 weapons")
n_items = len(names)
if lines:
def check_block(block, where):
global n_lines, n_todo
for kind, lst in block.items():
if kind not in ALLOWED:
# a key the engine added: count it, check only that it is text
for t in lst:
n_lines += 1
n_todo += t.startswith("TODO ")
continue
if not lst:
err("lines.json %s %s: empty list" % (where, kind))
if len(set(lst)) != len(lst):
err("lines.json %s %s: the same line twice" % (where, kind))
for t in lst:
n_lines += 1
if t.startswith("TODO "):
n_todo += 1
continue
check_text(t, "lines.json %s %s" % (where, kind), ALLOWED[kind])
for p in REQUIRED.get(kind, []):
if p not in t.replace("{in_room}", "{room}"):
err("lines.json %s %s: lacks %s: %r" % (where, kind, p, t[:50]))
def check_admissions(block, where):
pools = [block.get(k) for k in ADMISSIONS]
if any(pools) and not (pools[0] == pools[1] == pools[2]):
err("lines.json %s: %s must be the same list (one admission pool)" % (where, ", ".join(ADMISSIONS)))
for t in pools[0] or []:
if TELLS.search(t):
err("lines.json %s: an admission says how the purser was: %r" % (where, t[:60]))
def check_tips(block, where):
for tline in block.get("tip", []):
if SIGHTING.search(tline):
err("lines.json %s tip: a lead must not claim a sighting: %r" % (where, tline[:60]))
check_tips(lines.get("generic", {}), "generic")
for sid, block in lines.get("by_suspect", {}).items():
check_tips(block, sid)
if "tip" not in block:
err("lines.json by_suspect %s: no tip line (the lead would fall back to generic)" % sid)
nb = lines.get("notebook", {}).get("tip")
if nb is not None:
check_text(nb, "lines.json notebook tip", {"speaker", "other", "time"})
check_block(lines.get("generic", {}), "generic")
check_admissions(lines.get("generic", {}), "generic")
for k in ALLOWED:
if k not in lines.get("generic", {}):
err("lines.json generic: kind %s is missing" % k)
for sid, block in lines.get("by_suspect", {}).items():
if suspect_ids and sid not in suspect_ids:
err("lines.json by_suspect: unknown suspect %r" % sid)
check_block(block, sid)
check_admissions(block, sid)
for e in ENDINGS:
lst = lines.get("endings", {}).get(e, [])
if not lst:
err("lines.json endings: %s is missing" % e)
for t in lst:
n_lines += 1
check_text(t, "lines.json endings %s" % e, ENDING_FIELDS)
if e == "reckoned" and "{motive}" in t:
err("lines.json endings reckoned: no {motive}, the culprit states it (motive 'says')")
for t in lines.get("endings", {}).get("quit", []):
n_lines += 1
n_todo += t.startswith("TODO ")
check_text(t, "lines.json endings quit")
if not lines.get("endings", {}).get("quit"):
err("lines.json endings: quit is missing")
for k, allowed in UI.items():
t = lines.get("ui", {}).get(k)
if t is None:
err("lines.json ui: %s is missing (the player would read a TODO)" % k)
continue
n_lines += 1
n_todo += isinstance(t, str) and t.startswith("TODO ")
check_text(t, "lines.json ui %s" % k, allowed)
for p in sorted(allowed):
if isinstance(t, str) and "{%s}" % p not in t.replace("{in_room}", "{room}"):
err("lines.json ui %s: lacks {%s}" % (k, p))
for k in lines.get("ui", {}):
if k not in UI:
n_lines += 1
n_todo += str(lines["ui"][k]).startswith("TODO ")
parked = load("rooms_parked.json")
if parked:
for r in parked["rooms"]:
if r["id"] in room_ids:
err("rooms_parked.json %s: id is also a live room" % r["id"])
check_text(r["desc"], "rooms_parked.json %s desc" % r["id"])
print("parked places (written, not loaded): %d" % len(parked["rooms"]))
if n_rooms > 16:
err("rooms.json: %d rooms, the decision is 16 at most" % n_rooms)
for e in errors:
print("ERROR " + e)
print("places: %d" % n_rooms)
print("characters: %d" % n_chars)
print("objects: %d" % n_items)
print("lines: %d (TODO: %d)" % (n_lines, n_todo))
print("%d errors" % len(errors))
sys.exit(1 if errors else 0)
Shown as text, exactly as the agents wrote it. Nothing here is run.