Playtest
Define automated playtests in playtest.yaml, run bots headless across seeded runs with deterministic input recordings, and check measured metrics against the game's goals.
import "github.com/nsgo-dev/game/pkg/tooling/playtest"
playtest.yaml
playtest.yaml is a versioned plain-text YAML file with a published JSON Schema (https://nsgo.games/schemas/playtest.v1.json). Unknown fields, missing or unsupported versions, duplicate metric names and invalid goals are refused; EncodeConfig writes canonical deterministic YAML that round-trips without changes.
# yaml-language-server: $schema=https://nsgo.games/schemas/playtest.v1.json
version: 1
scope:
project: dungeon-run
scene: level_01
template: platformer2d
runs:
count: 20
seedStart: 1
rate: 60
speed: 1
maxDuration: 1m30s
bot:
profile: platformer-runner
strategy: Greedy route to the door, jumps at ledges and gaps, 120-220 ms reaction jitter
reactionMin: 120ms
reactionMax: 220ms
params:
jumpHoldMs: 220
metrics:
- name: finished
label: Finished
measure:
kind: outcome
key: finished
aggregate: count
goal:
summary: most first-timers clear floor 1
source: brief.yaml
min: 16
- name: median_time
label: Median time
unit: s
measure:
kind: timer
key: clear_time
aggregate: median
goal:
summary: under a minute
source: brief.yaml
min: 40
max: 60
- name: frame_time
label: Frame time
unit: ms
measure:
kind: perf
key: frame_ms
aggregate: median
goal:
summary: 16.7 ms at 60 Hz
source: game.yaml
max: 16.7
- name: coins_taken
label: Coins taken
unit: '%'
measure:
kind: ratio
key: coins_taken
denomKey: coins_total
aggregate: mean
goal:
summary: every coin on a route
source: playtest.yaml
min: 100
- name: deaths
label: Deaths
measure:
kind: event
key: death
aggregate: sum
heatMap: true
Sections
-
scope: theproject, requiredscene, and optionaltemplate. -
runs:count, optional explicitseeds,seedStart(defaults to1), fixedratein steps per second (defaults to60),speedmultiplier metadata (defaults to1), andmaxDurationsimulated time limit per run (defaults to60s). -
bot:profile(such asplatformer-runner,topdown-explorer,shooter,puzzle-solver,card-ai, oridle), optionalstrategytext,reactionMin/reactionMaxhuman reaction jitter durations, and optional scalarparams. -
metrics: each metric has a uniquename, optionallabelandunit, ameasure, and an optionalgoal:measure.kindisevent,counter,timer,outcome,ratio(requiringdenomKey), orperf(frame_ms,update_ms,draw_ms,p50_frame_ms,p95_frame_ms,p99_frame_ms,max_frame_ms,allocs_per_frame).measure.aggregateiscount,sum,mean,median,min,max,p95,p99, orrate.measure.heatMap: trueon aneventmetric emits all recorded(x, y)coordinates into the report'sheatMapssection.goalspecifiessource(such asbrief.yaml,game.yaml, orplaytest.yaml), an optionalsummary, andmin,max(or both for a range), orequal.
-
baselines(optional): the outcome policies the game must show besides the configured bot's metrics.idle.outcomeisloseorstall, the result a run with no input must reach, withinidle.within, a duration no longer thanruns.maxDuration.reference.winRateis the minimum share of seeded runs, from0to1, the configured bot must win.degradedweakens the same bot withreactionScale(a multiplier onreactionMin/reactionMax),dropRate(the share of its actions discarded, from0to1), or both, and limits its win rate withmaxWinRate,margin(the minimum gap below the reference win rate), or both.
playtest.report.yamlhas a matching optionalbaselineslist, one entry per policy with itsname(idle,referenceordegraded),passed, and the measuredoutcomeorwinRate.playtest.Runexecutes the declared idle and degraded policies with the same seeds, fills the report, and fails the report when a policy fails; the report summary lists each policy as[MET]or[MISSED]with its note, such as how many idle runs reached the outcome in time.Collector.WinandCollector.Losemark explicit outcomes for baseline checks.
Reporting metrics from Go
During a run, the game receives a *playtest.Collector and calls it to report events, counters, timers and outcome. Every method is nil-safe, so game code can call it unconditionally in both live play and playtest runs:
metrics.StartTimer("clear_time")
metrics.SetCounter("coins_total", float64(len(coins)))
// When collecting a coin:
metrics.Event("pickup", float64(cx), float64(cy), coin.ID)
metrics.Inc("coins_taken")
// When dying:
metrics.Event("death", float64(px), float64(py), "slime_pit")
// On win or loss:
metrics.StopTimer("clear_time")
metrics.Finish() // or metrics.Fail("out of lives")
Frame time comes from the perf readout: pass FrameStats: stats and GC: gcMon on playtest.Sim (or call metrics.RecordPerf(stats, gcMon)), which uses the same averaging and percentile calculations as game/mcp's game_perf_readout.
For bar charts and matchup matrices in playtest.report.yaml, call metrics.ConfigureSeries / metrics.AddSeries / metrics.SetSeries / metrics.FlagSeries (emitting report.Series, such as hits per wave or shortest solution per level) and metrics.ConfigureMatrix / metrics.RecordMatchup (emitting report.Matrices, such as win rate by deck pair).
Built-in bot profiles
Every built-in profile is deterministic for a given seed and registers itself via playtest.RegisterBot:
platformer-runner(playtest.ProfilePlatformerRunner, templateplatformer2d): runs greedily towardPlatformerObservation.ExitXand jumps at ledges, gaps and hazards with deterministic human reaction jitter sampled from the per-runrandom.Streamin[reactionMin, reactionMax]. Useplaytest.ObservePlatformerGridto build aPlatformerObservationfrom aphysics.TileGridand hazard boxes.topdown-explorer(playtest.ProfileTopDownExplorer, templaterpg2d): walks to the nearest unseen walkable tile via BFS, talks to every NPC once, opens every chest, and stops when finished or whenruns.maxDurationis reached (configured at8xspeed inrpg2d'splaytest.yaml). SupplyExplorerObservationand recordgoal_time,tiles_seen/tiles_total, andtile_visitevents (heatMap: true) for the time-per-tile heat map.shooter(playtest.ProfileShooter, templateshmup2d): fires constantly, collects power-ups withinpowerUpRange(default80px), and dodges predicted incoming bullets through a reaction-delayed perception buffer (fixed180mswhenreactionMin == reactionMax == 180ms). UseRecordShooterWave,RecordShooterHitandRecordShooterPowerUpto report hits per wave (hits_per_waveseries) and power-ups taken.puzzle-solver(playtest.ProfilePuzzleSolver, templatepuzzle2d): pairsSolvePuzzleBFS(exact breadth-first search for the shortest solution up tostateLimit, default 2,000,000 states) with a human-like player that undoes afterundoAfterBadMoves(default3) consecutive bad moves. UseEvaluatePuzzlePackorNewPuzzlePackSimto report solvable levels, moves over par, difficulty order dips, and solutions shorter than intended.card-ai(playtest.ProfileCardAI, templatecards2d): two greedy 1-turn-lookahead players (CardAI.ChooseAction) play every unordered deck pairmatchesPerPairtimes, alternating who goes first. UseRunCardTournamentorNewCardTournamentSimto report first-player win rate, median match length, most lopsided pair, deterministic think time, and thedeck_win_ratesmatrix.idle(playtest.ProfileIdle): sends no actions or axes on any frame and never reads the game observation. Pair it with a boundedruns.maxDurationand anoutcomegoal for an idle-loss baseline, so a game that a player wins by doing nothing fails its playtest.
Register custom bot profiles with playtest.RegisterBot(name, factory). The platformer2d, rpg2d, shmup2d, puzzle2d, and cards2d project templates each ship a canonical playtest.yaml configured for their matching profile alongside a playtest_test.go wired through playtest.RunTest, so running go tool game playtest inside a freshly created template writes a deterministic report right away:
go run github.com/nsgo-dev/game/cmd/game@latest new -template platformer2d mygame
cd mygame
go tool game playtest
Running headless and replaying runs
Call playtest.Run(cfg, makeSim, opts) directly or wire a test with playtest.RunTest so go tool game playtest can execute it:
func TestLevel1Playtest(t *testing.T) {
playtest.RunTest(t, "playtest.yaml", makeSim)
}
Then run from the project directory:
go tool game playtest
go tool game playtest -config playtest.yaml -out playtest.report.yaml -recordings playtest-recordings
go tool game playtest -check
Each seeded run wraps the bot in a replay.Recorder and writes <recordings>/run_NNN_seed_<seed>.replay.yaml, so any run can be replayed deterministically with replay.NewPlayer or turned into a game replay regression test. The YAML report (playtest.report.yaml, version: 1) records every run's outcome, metrics, goal statuses (met, missed, info), heat-map points and recording paths.
When a brief.yaml sits beside playtest.yaml, playtest.RunTest also lists in the report's briefTargets every feel target of the brief that applies to the playtest's scene (ApplyBriefTargetStatuses), with its basis and a status: pending when the playtest has no metric of that name, so a target nobody measured is never reported as verified, and otherwise met or missed by the target's own bounds in the brief, even when playtest.yaml gives the metric a different goal.
Editor MCP tools
The editor's MCP server (game/editor/editormcp, reached via go tool game mcp) exposes two playtest tools:
game_playtest(run): validatesplaytest.yaml, runs the playtest headless with replays, writes the YAML report, and returns the structured report and summary.playtest_define(edit): validates a proposed metric and returns a canonicalplaytest.yamldiff queued as a pending review (Server.PlaytestReviews,Server.ApplyPlaytestReview,Server.DismissPlaytestReview) without modifyingplaytest.yamlon disk until reviewed.