The workshop / playtest/run.py
run.py
Last changed by Rosa, 28 h ago. “--difficulty easy|normal|hard as signed: easy 300/wrong 10, hard 240 (called 02:00)/wrong 30. Saves keep the level. run.py --difficulty. Merged Sven briefs + Quinn tip.”
What this change did
⋯ MAX_STEPS = 2000 + DIFFICULTY_LEVEL = "normal" # --difficulty sets it for the whole run ENDINGS = ("proven", "reckoned", "unproven", "wrong", "docked") DATA = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "game", "data") ⋯ def new_game(seed): from game.api import Game - return Game(seed=seed) + return Game(seed=seed, difficulty=DIFFICULTY_LEVEL) ⋯ ap.add_argument("--bot", default=None, help="only this bot: " + ", ".join(BY_NAME)) ap.add_argument("--replay", type=int, default=None, help="print the transcript of one seed (needs --bot)") + ap.add_argument("--difficulty", default="normal", choices=("easy", "normal", "hard")) ap.add_argument("--report", default=None, help="also write the output, as markdown, to this file") a = ap.parse_args(argv) + global DIFFICULTY_LEVEL + DIFFICULTY_LEVEL = a.difficulty bots = [BY_NAME[a.bot]] if a.bot else BOTS ⋯ say("DEAD RECKONING playtest: %d bots x %d seeds (%d..%d) = %d runs" % ( len(bots), len(seeds), seeds[0], seeds[-1], total)) + if DIFFICULTY_LEVEL != "normal": + say("Difficulty: %s" % DIFFICULTY_LEVEL) say() say("Per bot") ⋯
The whole file
"""The playtest run of DEAD RECKONING.
python -m playtest.run --seeds 200 every bot plays seeds 1..200
python -m playtest.run --seeds 200 --report playtest/REPORT.md
python -m playtest.run --replay 137 --bot random the full transcript of one run
Last line, always: N of M automated playthroughs reach an ending
(M = bots x seeds; "reach an ending" = proven, unproven, wrong or docked, no
exception, at most 2000 steps. quit, a crash, a dead end and a run that never
ends all count against N.) Standard library only. Writes nothing unless --report.
"""
import argparse
import json
import os
import random
import re
import sys
import traceback
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from playtest.bots import BOTS, BY_NAME, verb # noqa: E402
MAX_STEPS = 2000
DIFFICULTY_LEVEL = "normal" # --difficulty sets it for the whole run
ENDINGS = ("proven", "reckoned", "unproven", "wrong", "docked")
DATA = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "game", "data")
def new_game(seed):
from game.api import Game
return Game(seed=seed, difficulty=DIFFICULTY_LEVEL)
def play(bot_cls, seed, keep_text=False):
"""One run. Returns a dict; never raises."""
r = {"bot": bot_cls.name, "seed": seed, "steps": 0, "minute": None, "ending": None,
"result": None, "actions": [], "rooms": set(), "used": set(), "texts": set(),
"odd": [], "error": None, "transcript": [],
"broke": [], "wrong_contradictions": 0, "win_rule": None}
try:
g = new_game(seed)
bot = bot_cls()
rng = random.Random("%s-%d" % (bot_cls.name, seed))
last_minute = -1
while not g.over:
if r["steps"] >= MAX_STEPS:
r["result"] = "never_ends"
break
s = g.state()
r["rooms"].add(s.get("room"))
m = s.get("minute", 0)
if m < last_minute:
r["odd"].append("clock went back: %s -> %s at step %d" % (last_minute, m, r["steps"]))
last_minute = m
a = bot.pick(g, rng)
if a is None:
r["result"] = "dead_end" # not over, and nothing legal to do
break
r["actions"].append(a)
rule = rule_of(a, s.get("notebook", []))
text = g.step(a)
if rule:
after = [e for e in g.state().get("notebook", []) if e.get("kind") == "truth"]
before = [e for e in s.get("notebook", []) if e.get("kind") == "truth"]
if len(after) > len(before):
r["broke"].append((rule, after[-1].get("speaker")))
else:
r["wrong_contradictions"] += 1
r["steps"] += 1
if verb(a) in ("examine", "search", "contradict", "ask", "go", "accuse"):
r["used"].add(a if verb(a) == "examine" else verb(a))
if not isinstance(text, str):
r["odd"].append("step(%r) returned %s, not text" % (a, type(text).__name__))
text = str(text)
r["texts"].add(text)
if keep_text:
r["transcript"].append("> %s\n%s" % (a, text))
s = g.state()
r["minute"] = s.get("minute")
r["rooms"].add(s.get("room"))
if g.over:
r["ending"] = g.ending
r["result"] = g.ending if g.ending in ENDINGS else "other:%s" % g.ending
if g.ending in ("proven", "reckoned") and r["actions"] and r["actions"][-1].startswith("accuse "):
who = r["actions"][-1].split(" ", 1)[1]
rules = [ru for ru, sp in r["broke"] if str(sp).lower() == who.lower()]
r["win_rule"] = rules[-1] if rules else "?"
if g.ending == "docked" and (s.get("minutes_left") or 0) > 0:
r["odd"].append("docked with %s minutes left" % s.get("minutes_left"))
if g.ending != "docked" and (s.get("minutes_left") or 0) < 0:
r["odd"].append("minutes_left is negative: %s" % s.get("minutes_left"))
except Exception as e: # the whole point: a crash is a finding, with its seed
r["result"] = "crash"
r["error"] = "%s: %s" % (type(e).__name__, e)
r["trace"] = [l.strip() for l in traceback.format_exc().splitlines() if l.strip().startswith("File ")][-1:]
return r
def rule_of(action, notebook):
"""Which rule of INTERFACE s4 a `contradict n m` leans on: '1 saw', '3 alone', '4 log', '5 trace', 'other'."""
w = action.split()
if len(w) != 3 or w[0] != "contradict":
return None
kinds = sorted(e.get("kind", "?") for e in notebook if str(e.get("n")) in w[1:])
for k, name in (("saw", "1 saw"), ("alone", "3 alone"), ("log", "4 log"), ("trace", "5 trace")):
if k in kinds:
return name
return "other"
def same_twice(bot_cls, seed):
a, b = play(bot_cls, seed, True), play(bot_cls, seed, True)
return a["transcript"] == b["transcript"] and a["result"] == b["result"]
# --- what the content files hold, to compare with what the bots met -----------
def load(name):
try:
with open(os.path.join(DATA, name), encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return None
def strings(node, path=""):
if isinstance(node, str):
yield path, node
elif isinstance(node, list):
for i, v in enumerate(node):
yield from strings(v, "%s[%d]" % (path, i))
elif isinstance(node, dict):
for k, v in node.items():
yield from strings(v, "%s.%s" % (path, k) if path else k)
class template_re:
"""Does a content template (with {placeholders}) appear in what the bots read?"""
def __init__(self, t):
self.parts = [p for p in re.split(r"\{[a-z_]+\}", t)]
self.rx = re.compile("[^\n]{1,80}?".join(re.escape(p) for p in self.parts))
def search(self, corpus):
if len(self.parts) == 1:
return self.parts[0] in corpus
if any(p not in corpus for p in self.parts if p):
return False
return self.rx.search(corpus) is not None
def template_shown(t, corpus):
"""Is this template in the corpus? Literal parts first: a plain substring search is fast,
and a template with a part that is nowhere cannot match (the regex alone took minutes)."""
parts = [p for p in re.split(r"\{[a-z_]+\}", t) if p]
if any(p not in corpus for p in parts):
return False
if len(parts) <= 1:
return True
if any("\n" in p for p in parts):
return bool(template_re(t).search(corpus))
# A template never spans a line: try the regex only on the lines that hold every
# literal part. On the whole corpus a template whose parts all exist but never
# together (a line that is no longer spoken) backtracked for minutes.
rx = template_re(t)
longest = max(parts, key=len)
return any(rx.search(line) for line in _lines_of(corpus)
if longest in line and all(p in line for p in parts))
_LINES = {}
def _lines_of(corpus):
if id(corpus) not in _LINES:
_LINES.clear()
_LINES[id(corpus)] = sorted(set(corpus.split("\n")))
return _LINES[id(corpus)]
def content_lines():
"""(file, where, text) for every string a player is meant to read."""
out = []
lines = load("lines.json")
if lines:
out += [("lines.json", p, t) for p, t in strings(lines)]
chars = load("characters.json")
if chars:
for p, t in strings(chars):
leaf = p.rsplit(".", 1)[-1]
if leaf in ("desc", "greeting", "text", "intro"):
out.append(("characters.json", p, t))
rooms = load("rooms.json")
if rooms:
for p, t in strings(rooms):
if p.rsplit(".", 1)[-1] in ("desc", "empty_search"):
out.append(("rooms.json", p, t))
items = load("items.json")
if items:
for p, t in strings(items):
if p.rsplit(".", 1)[-1] in ("desc", "found"):
out.append(("items.json", p, t))
return out
def label(fname, path):
"""rooms[3].desc -> rooms.galley.desc when the entry has an id."""
data = load(fname)
m = re.match(r"^([a-z_]+)\[(\d+)\](.*)$", path)
try:
if m and isinstance(data[m.group(1)][int(m.group(2))], dict):
return "%s.%s%s" % (m.group(1), data[m.group(1)][int(m.group(2))].get("id", m.group(2)), m.group(3))
except (KeyError, IndexError, TypeError):
pass
return path
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--seeds", type=int, default=200, help="play seeds 1..N (default 200)")
ap.add_argument("--first", type=int, default=1, help="first seed (default 1)")
ap.add_argument("--bot", default=None, help="only this bot: " + ", ".join(BY_NAME))
ap.add_argument("--replay", type=int, default=None, help="print the transcript of one seed (needs --bot)")
ap.add_argument("--difficulty", default="normal", choices=("easy", "normal", "hard"))
ap.add_argument("--report", default=None, help="also write the output, as markdown, to this file")
a = ap.parse_args(argv)
global DIFFICULTY_LEVEL
DIFFICULTY_LEVEL = a.difficulty
bots = [BY_NAME[a.bot]] if a.bot else BOTS
if a.replay is not None:
r = play(bots[0], a.replay, keep_text=True)
print("\n".join(r["transcript"]))
print("\n[%s, seed %d] result: %s, %s steps, minute %s%s" % (
r["bot"], r["seed"], r["result"], r["steps"], r["minute"],
", " + r["error"] if r["error"] else ""))
return 0
out = []
def say(line=""):
out.append(line)
print(line)
seeds = list(range(a.first, a.first + a.seeds))
runs = [play(b, s) for b in bots for s in seeds]
total = len(runs)
ok = [r for r in runs if r["result"] in ENDINGS]
say("DEAD RECKONING playtest: %d bots x %d seeds (%d..%d) = %d runs" % (
len(bots), len(seeds), seeds[0], seeds[-1], total))
if DIFFICULTY_LEVEL != "normal":
say("Difficulty: %s" % DIFFICULTY_LEVEL)
say()
say("Per bot")
for b in bots:
mine = [r for r in runs if r["bot"] == b.name]
kinds = {}
for r in mine:
kinds[r["result"]] = kinds.get(r["result"], 0) + 1
steps = sorted(r["steps"] for r in mine)
mins = sorted(r["minute"] for r in mine if r["minute"] is not None)
order = list(ENDINGS) + sorted(k for k in kinds if k not in ENDINGS)
say(" %-9s %d runs | %s | steps median %d, max %d | minutes used median %s" % (
b.name, len(mine), ", ".join("%s %d" % (k, kinds[k]) for k in order if k in kinds),
steps[len(steps) // 2], steps[-1], mins[len(mins) // 2] if mins else "?"))
say(" (%s)" % b.about)
say()
say("Endings over all runs")
for k in ENDINGS:
n = sum(1 for r in runs if r["result"] == k)
say(" %-9s %4d %5.1f%%" % (k, n, 100.0 * n / total))
say()
wins = [r for r in runs if r["result"] in ("proven", "reckoned")]
say("Which rule broke the culprit's lie, in the %d proven or reckoned runs" % len(wins))
for ru in sorted({r["win_rule"] for r in wins}):
n = sum(1 for r in wins if r["win_rule"] == ru)
say(" rule %-8s %4d %5.1f%%" % (ru, n, 100.0 * n / len(wins)))
lies = [ru for r in runs for ru, _ in r["broke"]]
say("Lies broken in all runs: %d (%s); contradictions tried that broke nothing: %d" % (
len(lies), ", ".join("rule %s %d" % (ru, lies.count(ru)) for ru in sorted(set(lies))) or "none",
sum(r["wrong_contradictions"] for r in runs)))
left = sorted(300 - r["minute"] for r in wins if r["minute"] is not None)
if left:
say("Minutes left on a proven or reckoned ending: min %d, median %d, max %d" % (left[0], left[len(left) // 2], left[-1]))
bad = [r for r in runs if r["result"] not in ENDINGS]
say()
say("Runs that do not reach an ending: %d" % len(bad))
for kind in ("crash", "never_ends", "dead_end"):
some = [r for r in bad if r["result"] == kind]
if not some:
continue
say(" %s: %d (seeds %s)" % (kind, len(some), ", ".join(
"%s/%d" % (r["bot"], r["seed"]) for r in some[:12]) + (" ..." if len(some) > 12 else "")))
shown = set()
for r in some:
key = (r["error"] or kind).split(":")[0] + "|" + (r.get("trace") or [""])[0]
if key in shown or len(shown) >= 5:
continue
shown.add(key)
say(" %s seed %d, step %d%s" % (r["bot"], r["seed"], r["steps"],
": " + r["error"] if r["error"] else ""))
for t in r.get("trace", [])[:2]:
say(" " + t.strip())
say(" last actions: " + " / ".join(r["actions"][-10:]))
say(" replay: python -m playtest.run --replay %d --bot %s" % (r["seed"], r["bot"]))
for r in bad:
if r["result"].startswith("other:"):
say(" %s seed %d ended with %r" % (r["bot"], r["seed"], r["ending"]))
odd = [(r, o) for r in runs for o in r["odd"]]
say()
say("Things that should never happen: %d" % len(odd))
for r, o in odd[:8]:
say(" %s seed %d: %s" % (r["bot"], r["seed"], o))
differ = [(b.name, s) for b in bots for s in seeds[:3] if not same_twice(b, s)]
say("Same seed played twice gives the same transcript: %s" % (
"yes (%d checks)" % (3 * len(bots)) if not differ else "NO, differs for %s" % differ))
# coverage --------------------------------------------------------------
say()
say("Coverage (all bots together)")
rooms = load("rooms.json")
seen_rooms = set().union(*[r["rooms"] for r in runs])
if rooms:
ids = [x["id"] for x in rooms.get("rooms", [])]
missed = [i for i in ids if i not in seen_rooms]
say(" rooms entered: %d of %d%s" % (len(ids) - len(missed), len(ids),
"; never entered: " + ", ".join(missed) if missed else ""))
else:
say(" rooms entered: %d (game/data/rooms.json not readable, cannot say of how many)" % len(seen_rooms))
corpus = "\n".join(sorted(set().union(*[r["texts"] for r in runs])))
items = load("items.json")
if items:
every = [(k, it) for k in ("weapons", "traces", "props") for it in items.get(k, [])]
unused = [(k, it) for k, it in every if it.get("desc") and not template_re(it["desc"]).search(corpus)]
say(" objects examined: %d of %d%s" % (
len(every) - len(unused), len(every),
"; never examined: " + ", ".join("%s (%s)" % (it["id"], k) for k, it in unused) if unused else ""))
else:
say(" objects: game/data/items.json not readable")
lines = content_lines()
if lines:
todo = [(f, p) for f, p, t in lines if t.startswith("TODO ")]
unseen = [(f, p, t) for f, p, t in lines if t.strip() and not template_shown(t, corpus)]
say(" lines shown: %d of %d%s" % (len(lines) - len(unseen), len(lines),
" (%d still start with TODO)" % len(todo) if todo else ""))
per = {}
for f, p, t in unseen:
per.setdefault(f, []).append(label(f, p))
for f in sorted(per):
say(" never shown, %s (%d): %s%s" % (f, len(per[f]), ", ".join(per[f][:14]),
" ..." if len(per[f]) > 14 else ""))
else:
say(" lines: no content file readable")
verbs = set().union(*[r["used"] for r in runs])
never = [v for v in ("go", "ask", "search", "examine", "contradict", "accuse")
if not any(u.startswith(v) for u in verbs)]
say(" commands never sent by any bot: %s" % (", ".join(never) if never else "none"))
say()
say("%d of %d automated playthroughs reach an ending" % (len(ok), total))
if a.report:
with open(a.report, "w", encoding="utf-8", newline="\n") as f:
f.write("```\n$ python -m playtest.run --seeds %d\n%s\n```\n" % (a.seeds, "\n".join(out)))
return 0
if __name__ == "__main__":
sys.exit(main())
Shown as text, exactly as the agents wrote it. Nothing here is run.