This commit is contained in:
Forrest 2026-10-01 17:22:18 -04:00
commit 0cba7f5ee0
385 changed files with 17912 additions and 0 deletions

69
tests/bot_speed.gd Normal file
View file

@ -0,0 +1,69 @@
extends SceneTree
## Times the greedy bot: plays greedy-vs-greedy games with every Set 1 card and reports how long
## each choose() call takes. Util.errors must stay empty.
##
## godot --headless --script res://tests/bot_speed.gd -- [--games N] [--seed N] [--bot greedy|nocards]
func _init() -> void:
var games := 20
var first := 1
var bot := "greedy"
var args := OS.get_cmdline_user_args()
var i := 0
while i < args.size():
match args[i]:
"--games":
i += 1
games = int(args[i])
"--seed":
i += 1
first = int(args[i])
"--bot":
i += 1
bot = args[i]
i += 1
var pool := Cards.load_cards()
var rules := Rules.defaults()
var maker: Callable = Play.bots()[bot]
var times := PackedFloat64Array()
var slowest := {"ms": 0.0, "at": ""}
var game_ms := 0.0
var failed := 0
for seed in range(first, first + games):
Util.errors.clear()
var s = RulesEngine.create_game({"pool": pool, "decks": Play.deal(pool, seed, rules), "seed": seed, "rules": rules})
var players := [maker.call(seed * 2 + 1), maker.call(seed * 2 + 2)]
var started := Time.get_ticks_usec()
var n := 0
while s != null and not s.over and n < Play.MAX_ACTIONS:
n += 1
var p: int = RulesEngine.decider(s)
var legal := RulesEngine.legal_actions(s)
var view := RulesEngine.view_for(s, p)
var t0 := Time.get_ticks_usec()
var a: Dictionary = players[p].choose(view, legal, p)
var ms := (Time.get_ticks_usec() - t0) / 1000.0
times.append(ms)
if ms > slowest.ms:
var w = RulesEngine.open_window(s)
var where: String = ("window %s" % w.kind) if w != null else ("choice %s" % s.choice.kind if s.choice != null else "step %s" % s.step)
slowest = {"ms": ms, "at": "seed %d turn %d, %s, picked %s" % [seed, s.turn, where, RulesEngine.action_key(a)]}
if not RulesEngine.apply_action(s, a, legal):
break
game_ms += (Time.get_ticks_usec() - started) / 1000.0
if s == null or not s.over or not Util.errors.is_empty():
failed += 1
print("seed %d: %s" % [seed, "; ".join(Util.errors) if not Util.errors.is_empty() else "didn't finish"])
times.sort()
var total := 0.0
for t in times:
total += t
var count := times.size()
print("%s: %d games, %d choose() calls" % [bot, games, count])
print(" per choose: mean %.3f ms, median %.3f, p99 %.2f, max %.1f" % [
total / count, times[count / 2], times[mini(count - 1, int(count * 0.99))], times[count - 1]])
print(" slowest: %s" % slowest.at)
print(" per game: %.0f ms with the engine, %.0f ms in the bot" % [game_ms / games, total / games])
print(" %d game(s) failed" % failed)
quit(0 if failed == 0 else 1)

1
tests/bot_speed.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dmcgqlewqdvx6

284
tests/conformance.gd Normal file
View file

@ -0,0 +1,284 @@
extends SceneTree
## Conformance runner (godot-plan.md §2). Replays traces written by the TS sim through the GDScript
## engine, and stops each game at the first step that differs.
##
## godot --headless --script res://tests/conformance.gd -- [options]
##
## --traces DIR a trace set (a folder with an index.json) or a folder of them
## (default res://tests/traces)
## --limit N check at most N games per set
## --check also check rule invariants after every step
## --verbose print every game
##
## Make traces with tools/make_traces.sh, which runs the sim's src/trace.ts.
##
## A step's fingerprint is the action taken, an md5 of the legal action keys in order, of the state
## (sorted-key JSON, without the card defs and log), of the log lines it added, and of the next
## decider's view. A trace made with --full also holds every state, so a difference names the field;
## one made with --labels also checks the move-list labels (Describe).
const DEFAULT_TRACES := "res://tests/traces"
## Detailed reports printed per set before the rest are only counted.
const MAX_REPORTS := 3
var _opts := {"traces": DEFAULT_TRACES, "limit": 0, "check": false, "verbose": false}
var _pool: Dictionary
var _cards_md5 := ""
func _init() -> void:
var args := OS.get_cmdline_user_args()
var i := 0
while i < args.size():
match args[i]:
"--traces":
i += 1
_opts.traces = args[i]
"--limit":
i += 1
_opts.limit = int(args[i])
"--check":
_opts.check = true
"--verbose":
_opts.verbose = true
_:
printerr("conformance: unknown option %s" % args[i])
quit(2)
return
i += 1
quit(_run())
func _run() -> int:
var root: String = ProjectSettings.globalize_path(_opts.traces) if _opts.traces.begins_with("res://") else _opts.traces
var sets := _find_sets(root)
if sets.is_empty():
print("conformance: no trace sets in %s (folders with an index.json)" % root)
return 1
_pool = Cards.load_cards()
_cards_md5 = _md5(FileAccess.get_file_as_string(Cards.DEFAULT_CSV))
var failed := 0
for dir in sets:
failed += _run_set(dir)
print("conformance: %s" % ("all sets match" if failed == 0 else "%d game(s) differ" % failed))
return 0 if failed == 0 else 1
func _find_sets(root: String) -> Array:
if FileAccess.file_exists(root.path_join("index.json")):
return [root]
var out := []
var d := DirAccess.open(root)
if d == null:
return out
var names := d.get_directories()
names.sort()
for n in names:
if FileAccess.file_exists(root.path_join(n).path_join("index.json")):
out.append(root.path_join(n))
return out
func _run_set(dir: String) -> int:
var index: Dictionary = Util.ints(JSON.parse_string(FileAccess.get_file_as_string(dir.path_join("index.json"))))
var set_name := dir.get_file()
if index.get("cards", _cards_md5) != _cards_md5:
print("%s: res://data/cards.csv differs from the CSV the traces were made from. Sync it, or remake the traces." % set_name)
return 1
if index.has("rngCheck"):
var got := _rng_check(index.rngSeeds)
if got != index.rngCheck:
print("%s: Mulberry32 differs from TS (rng check %s, TS %s)" % [set_name, got, index.rngCheck])
return 1
var files := []
for f in DirAccess.get_files_at(dir):
if f.begins_with("game-") and f.ends_with(".json"):
files.append(f)
files.sort_custom(func(a, b): return _game_no(a) < _game_no(b))
if _opts.limit > 0:
files = files.slice(0, _opts.limit)
var started := Time.get_ticks_msec()
var failed := 0
var steps := 0
for f in files:
var trace: Dictionary = JSON.parse_string(FileAccess.get_file_as_string(dir.path_join(f)))
var result := _check_game(trace, index)
steps += result.steps
if result.error != "":
failed += 1
if failed <= MAX_REPORTS:
print("%s/%s: %s" % [set_name, f, result.error])
elif _opts.verbose:
print("%s/%s: ok (%d steps)" % [set_name, f, result.steps])
var secs := (Time.get_ticks_msec() - started) / 1000.0
var summary := "%d/%d games match" % [files.size() - failed, files.size()]
print("%s: %s (%d steps, %.1fs)" % [set_name, summary, steps, secs])
return failed
func _rng_check(seeds: Array) -> String:
var lines := []
for seed in seeds:
var r := Rng.make(seed)
var vals := PackedStringArray()
vals.resize(10000)
for i in 10000:
vals[i] = str(roundi(Rng.next_float(r) * 4294967296.0))
lines.append(",".join(vals))
return _md5("\n".join(lines))
## Replays one trace. Returns {steps, error}, with error "" when every step matches.
func _check_game(t: Dictionary, index: Dictionary) -> Dictionary:
var seed: int = int(t.seed)
var rules := Rules.from_json(t.rules)
var decks: Array = t.decks
var hint := _full_hint(seed, index)
var fail := func(step: int, msg: String) -> Dictionary:
return {"steps": step, "error": "seed %d, %s%s" % [seed, msg, hint]}
# Dealing: the same decks from the same seed.
var include := Callable()
if t.pool is Array:
var names := {}
for n in t.pool:
names[n] = true
include = func(c): return names.has(c.name)
Util.errors.clear()
var dealt := Play.deal(_pool, seed, rules, include)
if dealt != decks:
return fail.call(0, "dealt different decks: %s vs TS %s" % [JSON.stringify(dealt), JSON.stringify(decks)])
var s = RulesEngine.create_game({"pool": _pool, "decks": decks, "seed": seed, "rules": rules, "log": true})
if s == null or not Util.errors.is_empty():
return fail.call(0, "create_game failed: %s" % "; ".join(Util.errors))
var initial: Dictionary = t.initial
var diff := _compare(s, t, 0, initial.state, initial.log, s.log, initial.get("view", ""))
if diff != "":
return fail.call(0, "after setup: %s" % diff)
var makers := Play.bots()
var bots := []
for i in 2:
var b: String = t.bots[i]
bots.append(makers[b].call(seed * 2 + 1 + i) if makers.has(b) else null)
var steps: Array = t.steps
for i in steps.size():
var step: Dictionary = steps[i]
var at := "step %d (%s)" % [i + 1, step.a]
if s.over:
return fail.call(i, "%s: the game is already over" % at)
var p: int = RulesEngine.decider(s)
var legal := RulesEngine.legal_actions(s)
var keys := PackedStringArray()
for a in legal:
keys.append(RulesEngine.action_key(a))
if _md5("\n".join(keys)) != step.l:
return fail.call(i, "%s: legal actions differ. GDScript has %d:\n %s" % [at, keys.size(), "\n ".join(keys)])
var k := keys.find(step.a)
if k < 0:
return fail.call(i, "%s: TS's action isn't legal in GDScript" % at)
if step.has("d"):
var labels := PackedStringArray()
for a in legal:
labels.append(Describe.describe_action(s, a))
if _md5("\n".join(labels)) != step.d:
return fail.call(i, "%s: move labels differ. GDScript has:\n %s" % [at, "\n ".join(labels)])
if bots[p] != null:
var pick: Dictionary = bots[p].choose(RulesEngine.view_for(s, p), legal, p)
if RulesEngine.action_key(pick) != step.a:
return fail.call(i, "%s: the %s bot picked %s" % [at, t.bots[p], RulesEngine.action_key(pick)])
var logged: int = s.log.size()
RulesEngine.apply_action(s, legal[k], legal)
if not Util.errors.is_empty():
return fail.call(i, "%s: engine error: %s" % [at, "; ".join(Util.errors)])
diff = _compare(s, t, i + 1, step.s, step.g, s.log.slice(logged), step.get("v", ""))
if diff != "":
return fail.call(i, "after %s: %s" % [at, diff])
if _opts.check:
var errors := Invariants.check(s)
if not errors.is_empty():
return fail.call(i, "after %s: invariants: %s" % [at, "; ".join(errors)])
var end: Dictionary = Util.ints(t.end)
var got := {"winner": s.winner, "turn": s.turn, "endReason": s.endReason}
if not s.over or got != end:
return fail.call(steps.size(), "the game ends %s, TS %s" % [JSON.stringify(got), JSON.stringify(end)])
return {"steps": steps.size(), "error": ""}
## Compares the state after step `n` with the trace's fingerprints. Returns "" when they match.
func _compare(s: Dictionary, t: Dictionary, n: int, state_md5: String, log_md5: String, new_lines: Array, view_md5: String) -> String:
var body := _body(s)
if _md5(JSON.stringify(body)) != state_md5:
if t.has("states"):
var want = Util.ints(t.states[n])
var have = Util.ints(JSON.parse_string(JSON.stringify(body)))
var where := _diff(want, have, "")
return "state differs: %s" % (where if where != "" else "(no field differs; JSON formatting?)")
return "state differs"
if _md5(JSON.stringify(new_lines)) != log_md5:
return "log differs. GDScript wrote:\n %s" % "\n ".join(new_lines.map(func(l): return JSON.stringify(l)))
if view_md5 != "" and not s.over:
var view := _body(RulesEngine.view_for(s, RulesEngine.decider(s)))
if _md5(JSON.stringify(view)) != view_md5:
return "the decider's view differs"
return ""
## The state as fingerprinted: without its card defs (fixed for the game) and log (checked by line).
func _body(s: Dictionary) -> Dictionary:
var b := s.duplicate()
b.erase("defs")
b.erase("log")
return b
## The first path where two JSON values differ, like "players[1].anomalies[0].damage ts=4 gd=3".
func _diff(want: Variant, have: Variant, path: String) -> String:
if typeof(want) != typeof(have):
return "%s ts=%s gd=%s" % [path, JSON.stringify(want), JSON.stringify(have)]
if want is Dictionary:
var keys: Array = want.keys()
for k in have.keys():
if not keys.has(k):
keys.append(k)
keys.sort()
for k in keys:
var sub := "%s.%s" % [path, k] if path != "" else str(k)
if not want.has(k):
return "%s ts=(missing) gd=%s" % [sub, JSON.stringify(have[k])]
if not have.has(k):
return "%s ts=%s gd=(missing)" % [sub, JSON.stringify(want[k])]
var d := _diff(want[k], have[k], sub)
if d != "":
return d
return ""
if want is Array:
for i in mini(want.size(), have.size()):
var d := _diff(want[i], have[i], "%s[%d]" % [path, i])
if d != "":
return d
if want.size() != have.size():
return "%s length ts=%d gd=%d" % [path, want.size(), have.size()]
return ""
return "" if want == have else "%s ts=%s gd=%s" % [path, JSON.stringify(want), JSON.stringify(have)]
func _full_hint(seed: int, index: Dictionary) -> String:
if index.get("full", false):
return ""
var cmd := "node src/trace.ts --out /tmp/trace-full --seed %d -n 1 --full --south %s --north %s" % [seed, index.bots[0], index.bots[1]]
if index.get("pool", "all") != "all":
cmd += " --pool %s" % index.pool
for r in index.get("rules", []):
cmd += " --rule %s" % r
return "\n For the differing field, in files-tcg/sim: %s\n then: --traces /tmp/trace-full" % cmd
static func _md5(text: String) -> String:
return text.md5_text().substr(0, 12)
static func _game_no(file: String) -> int:
return file.trim_prefix("game-").trim_suffix(".json").to_int()

1
tests/conformance.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cofxw7fkedxqj

88
tests/screenshot.gd Normal file
View file

@ -0,0 +1,88 @@
extends SceneTree
## Renders the game scene after some moves and saves a screenshot, for checking the look. Needs a
## display (not --headless).
##
## godot --script res://tests/screenshot.gd -- [--seed N] [--moves N] [--out PATH] [--top] [--north] [--select KEY|auto]
var _game: Node
var _seed := 1
var _moves := 40
var _out := "/tmp/files-tcg-shot.png"
var _top := false
var _select := ""
var _human := 0
var _frames := 0
var _rng := RandomNumberGenerator.new()
func _init() -> void:
var args := OS.get_cmdline_user_args()
var i := 0
while i < args.size():
match args[i]:
"--seed":
i += 1
_seed = int(args[i])
"--moves":
i += 1
_moves = int(args[i])
"--out":
i += 1
_out = args[i]
"--top":
_top = true
"--north":
_human = 1
"--select":
i += 1
_select = args[i]
i += 1
_rng.seed = _seed
# Don't take keyboard focus or clicks from whatever you're doing while it renders.
DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_NO_FOCUS, true)
_game = load("res://scenes/game.tscn").instantiate()
_game.set_process_unhandled_input(false)
root.add_child.call_deferred(_game)
func _process(_delta: float) -> bool:
if not _game.is_node_ready():
return false
_frames += 1
if _frames == 2:
_game._paused = true
_game.hud.close_modal()
_game.start_game({"seed": _seed, "human": _human, "style": "greedy"})
var m: LocalMatch = _game.match_
var n := 0
while n < _moves and not m.is_over():
n += 1
if m.bot_to_act():
m.bot_step()
continue
var moves: Array = _game.moves
var others := moves.filter(func(mv): return mv.action.type not in ["end", "pass", "salvage"])
if not others.is_empty() and _rng.randf() < 0.7:
_game._play(others[_rng.randi() % others.size()])
else:
var stop := moves.filter(func(mv): return mv.action.type in ["end", "pass"])
_game._play(stop[0] if not stop.is_empty() else moves[0])
m.run_bot()
if _top:
_game.table.toggle_view()
if _select == "auto":
# The first hand card with a targeted move.
for mv in _game.moves:
if mv.source.begins_with("hand:") and mv.target != "none":
_select = mv.source
break
if _select != "":
_game._select(_select)
var card := _select.substr(5) if _select.begins_with("hand:") else ""
_game._inspect({"key": _select, "card": card})
if _frames == 70:
var img := root.get_viewport().get_texture().get_image()
img.save_png(_out)
print("saved %s" % _out)
return true
return false

1
tests/screenshot.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://c7keilqyjlpds

40
tests/smoke.gd Normal file
View file

@ -0,0 +1,40 @@
extends SceneTree
## Plays random-vs-random games with every Set 1 card and checks the rule invariants after every
## action. Quicker than conformance for catching script errors; conformance checks the results.
##
## godot --headless --script res://tests/smoke.gd -- [--games N] [--seed N] [--rule K=V]...
func _init() -> void:
var games := 20
var first := 1
var rules := Rules.defaults()
var args := OS.get_cmdline_user_args()
var i := 0
while i < args.size():
match args[i]:
"--games":
i += 1
games = int(args[i])
"--seed":
i += 1
first = int(args[i])
"--rule":
i += 1
rules = Rules.with_rule(rules, args[i])
i += 1
var pool := Cards.load_cards()
for w in CardScripts.stale_scripts(pool):
print("warning: %s" % w)
var started := Time.get_ticks_msec()
var failed := 0
for seed in range(first, first + games):
Util.errors.clear()
var random: Callable = Play.bots().random
var s = Play.play_game({"pool": pool, "bots": [random, random], "seed": seed, "rules": rules, "check": true})
if s == null or not Util.errors.is_empty():
failed += 1
print("seed %d: %s" % [seed, "; ".join(Util.errors)])
var secs := (Time.get_ticks_msec() - started) / 1000.0
print("smoke: %d/%d games ran clean (%.1fs)" % [games - failed, games, secs])
quit(0 if failed == 0 else 1)

1
tests/smoke.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://caxfhflrwc56n

147
tests/table_smoke.gd Normal file
View file

@ -0,0 +1,147 @@
extends SceneTree
## Plays whole games through the game scene, headless: you are driven by random picks from the
## move list, the bot is the greedy bot. Checks that every legal move can be reached by clicking
## the table: a screen point clear of the panels whose raycast hits the move's source, and one for
## its target (or a button on the source's menu). Also checks that the table builds for every
## view and that nothing raises an engine error.
##
## godot --headless --script res://tests/table_smoke.gd -- [--games N] [--seed N] [--style S] [--threaded]
##
## --threaded lets the game run the bot itself, on its worker thread, as it does in play.
var _game: Node
var _games := 3
var _seed := 1
var _style := "greedy"
var _played := 0
var _steps := 0
var _unreachable := {}
var _rng := RandomNumberGenerator.new()
var _started := 0
var _failed := false
var _threaded := false
## The physics frame to wait for before the next check, so the bodies have moved with the cards.
var _wait := -1
var _checks := 0
func _init() -> void:
var args := OS.get_cmdline_user_args()
var i := 0
while i < args.size():
match args[i]:
"--games":
i += 1
_games = int(args[i])
"--seed":
i += 1
_seed = int(args[i])
"--style":
i += 1
_style = args[i]
"--threaded":
_threaded = true
i += 1
_rng.seed = _seed
Card3D.instant = true
_game = load("res://scenes/game.tscn").instantiate()
root.add_child.call_deferred(_game)
_started = Time.get_ticks_msec()
func _process(_delta: float) -> bool:
if _game == null or not _game.is_node_ready():
return false
if _steps == 0 and _played == 0:
_new_game()
if Engine.get_physics_frames() < _wait:
return false
# Bot moves run until you decide; then wait for physics to catch up before checking.
for n in 200:
var m: LocalMatch = _game.match_
if m.human_to_act() and not m.is_over() and Util.errors.is_empty():
if _wait < 0:
_wait = Engine.get_physics_frames() + 2
return false
_check_reachable(m)
_wait = -1
if not _step():
return true
if _threaded and m.bot_to_act():
return false
if not m.bot_to_act():
_wait = -1
return false
return false
func _new_game() -> void:
_game._paused = not _threaded
_game.settings.botDelay = 0.0
_game.hud.close_modal()
_game.start_game({"seed": _seed + _played, "human": _played % 2, "style": _style})
Util.errors.clear()
## One move. Returns false when the run is over.
func _step() -> bool:
var m: LocalMatch = _game.match_
if not Util.errors.is_empty():
print("seed %d: engine error: %s" % [m.setup.seed, "; ".join(Util.errors)])
_failed = true
return _finish()
if m.is_over():
print("seed %d: %s after %d moves, turn %d" % [m.setup.seed, Hud.status_line(m.view(), m), m.actions.size(), m.s.turn])
_played += 1
if _played >= _games:
return _finish()
_new_game()
return true
if m.bot_to_act():
if _threaded:
return true
_steps += 1
m.bot_step()
return true
_steps += 1
_check_reachable(m)
var moves: Array = _game.moves
var others := moves.filter(func(mv): return mv.action.type != "end" and mv.action.type != "pass" and mv.action.type != "salvage")
var pick: Dictionary
if not others.is_empty() and _rng.randf() < 0.6:
pick = others[_rng.randi() % others.size()]
else:
var stop := moves.filter(func(mv): return mv.action.type == "end" or mv.action.type == "pass")
pick = stop[0] if not stop.is_empty() else moves[_rng.randi() % moves.size()]
_game._play(pick)
return true
func _check_reachable(_m: LocalMatch) -> void:
_checks += 1
var table: GameTable = _game.table
var found := {}
for mv in _game.moves:
if mv.source == "bar":
continue
var bad := ""
for key in [mv.source, mv.target]:
if key == "none" or found.has(key):
continue
if table.screen_point_for(key) != null:
found[key] = true
else:
bad = key
break
if bad != "":
var k := "%s (%s → %s, missing %s)" % [mv.group, mv.source.split(":")[0], mv.target.split(":")[0], bad.split(":")[0]]
if not _unreachable.has(k):
_unreachable[k] = mv.label
print("unreachable by clicking: %s: %s [%s]" % [k, mv.label, bad])
func _finish() -> bool:
var secs := (Time.get_ticks_msec() - _started) / 1000.0
print("table smoke: %d game(s), %d steps, %d click checks, %d unreachable move kinds, %.1fs" % [_played, _steps, _checks, _unreachable.size(), secs])
quit(1 if _failed or not _unreachable.is_empty() else 0)
return false

1
tests/table_smoke.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://dies82ygd3so5

0
tests/traces/.gdignore Normal file
View file