package playtest
import "github.com/nsgo-dev/game/pkg/playtest"Overview
Package playtest defines playtest.yaml (bots, seeded headless runs, metrics and goals), a metrics collection API for games, a deterministic headless playtest runner with replay recordings and YAML reports, and built-in bot profiles (platformer-runner, topdown-explorer, shooter, puzzle-solver, and card-ai).
A game reports positioned events (such as deaths, tile visits and pickups), counters, timers, series bars, matchup matrices and perf readouts through a *Collector during each seeded run. Run drives the game headless for every configured seed through a replay.Recorder so any run can be watched or replayed as a deterministic regression test, evaluates every configured metric against its goal (from brief.yaml, game.yaml or playtest.yaml), and produces a deterministic YAML Report with heat-map position data, bar series and win-rate matrices.
Index
- Constants
- func ApplyBriefTargets(cfg *Config, b *project.Brief) int
- func BotProfiles() []string
- func EncodeConfig(c *Config) ([]byte, error)
- func EncodeReport(r *Report) ([]byte, error)
- func Float64(v float64) *float64
- func LoadBriefTargets(projectDir, scene string) (map[string]*Goal, error)
- func RecordShooterHit(metrics *Collector, waveLabel string, x, y float64)
- func RecordShooterPowerUp(metrics *Collector, collected bool, x, y float64, kind string)
- func RecordShooterWave(metrics *Collector, waveLabel string, targetMaxHits *float64)
- func RegisterBot(name string, factory BotFactory)
- func SaveConfigFile(path string, c *Config) error
- func SaveReportFile(path string, r *Report) error
- func TargetsFromBrief(b *project.Brief, scene string) map[string]*Goal
- func ValidateMetric(m Metric) error
- func ValidateReport(r *Report) error
- type Bot
- type BotActionSource
- func NewBotActionSource(bot Bot, observe func() any, rng *random.Stream, dt time.Duration) *BotActionSource
- func (b *BotActionSource) Axis(name string) float64
- func (b *BotActionSource) JustPressed(name string) bool
- func (b *BotActionSource) JustReleased(name string) bool
- func (b *BotActionSource) Pressed(name string) bool
- func (b *BotActionSource) Step()
- func (b *BotActionSource) StepIndex() int
- type BotChannels
- type BotConfig
- type BotFactory
- type CardAI
- type CardAction
- type CardDecision
- type CardGameState
- type CardMatchFactory
- type CardMatchResult
- type CardObservation
- type CardTournamentReport
- type Collector
- func NewCollector(rate int) *Collector
- func (c *Collector) AddSeries(name, bucket string, delta float64)
- func (c *Collector) ConfigureMatrix(name, label, unit string, flagAbove *float64, labels []string)
- func (c *Collector) ConfigureSeries(name, label, unit, aggregate string, targetMax *float64)
- func (c *Collector) Count(name string, delta float64)
- func (c *Collector) Counter(name string) float64
- func (c *Collector) Done() bool
- func (c *Collector) Elapsed() time.Duration
- func (c *Collector) Event(kind string, x, y float64, tag ...string)
- func (c *Collector) Events() []Event
- func (c *Collector) Fail(reason string)
- func (c *Collector) Finish()
- func (c *Collector) FlagSeries(name, bucket, flag, note string)
- func (c *Collector) Inc(name string)
- func (c *Collector) Outcome() string
- func (c *Collector) Perf() *PerfSummary
- func (c *Collector) Rate() int
- func (c *Collector) Reason() string
- func (c *Collector) RecordMatchup(name, row, col string, wins, total float64)
- func (c *Collector) RecordPerf(stats *debug.FrameStats, gc *debug.GCMonitor)
- func (c *Collector) RecordTimer(name string, d time.Duration)
- func (c *Collector) SetCounter(name string, value float64)
- func (c *Collector) SetPerf(summary PerfSummary)
- func (c *Collector) SetSeries(name, bucket string, value float64)
- func (c *Collector) SetStep(step int)
- func (c *Collector) StartTimer(name string)
- func (c *Collector) Step() int
- func (c *Collector) StopTimer(name string) time.Duration
- func (c *Collector) Timer(name string) (float64, bool)
- type Config
- type Event
- type ExplorerChest
- type ExplorerNPC
- type ExplorerObservation
- type Goal
- type GridCell
- type HeatMap
- type HeatPoint
- type InputState
- type MatrixChart
- type Measure
- type Metric
- type MetricReport
- type PerfSummary
- type PlatformerObservation
- type PlatformerRunner
- type PuzzleHumanResult
- type PuzzleLevel
- type PuzzleLevelReport
- type PuzzleMove
- type PuzzleObservation
- type PuzzlePackReport
- type PuzzleScorer
- type PuzzleSolveResult
- type PuzzleSolver
- type PuzzleState
- type Report
- type RunOptions
- type RunReport
- type RunResult
- type Runs
- type Scope
- type SeriesChart
- type SeriesEntry
- type ShooterBot
- type ShooterBullet
- type ShooterObservation
- type ShooterPowerUp
- type ShooterTarget
- type Sim
- type SimFactory
- type TopDownExplorer
Constants
const (
MeasureEvent = "event"
MeasureCounter = "counter"
MeasureTimer = "timer"
MeasureOutcome = "outcome"
MeasureRatio = "ratio"
MeasurePerf = "perf"
)Measure kinds supported by Measure.Kind.
const (
AggCount = "count"
AggSum = "sum"
AggMean = "mean"
AggMedian = "median"
AggMin = "min"
AggMax = "max"
AggP95 = "p95"
AggP99 = "p99"
AggRate = "rate"
)Aggregation modes supported by Measure.Aggregate.
const (
StatusMet = "met"
StatusMissed = "missed"
StatusInfo = "info"
)Goal evaluation statuses reported in MetricReport.Status.
const (
// EnvConfig overrides the path to playtest.yaml loaded by RunTest.
EnvConfig = "NSGO_PLAYTEST_CONFIG"
// EnvOut tells RunTest where to write the YAML playtest report.
EnvOut = "NSGO_PLAYTEST_OUT"
// EnvRecordings tells RunTest which directory to write per-run .replay.yaml recordings into.
EnvRecordings = "NSGO_PLAYTEST_RECORDINGS"
// EnvCount, when set to a positive integer, overrides runs.count in playtest.yaml.
EnvCount = "NSGO_PLAYTEST_COUNT"
// EnvSeeds, when set to a comma-separated list of uint64 seeds, overrides runs.seeds in playtest.yaml.
EnvSeeds = "NSGO_PLAYTEST_SEEDS"
// EnvNoFail, when set to "1", lets RunTest write its report without failing testing.TB on missed goals, so the caller (such as go tool game playtest) can inspect and report missed goals directly.
EnvNoFail = "NSGO_PLAYTEST_NO_FAIL"
)Environment variables passed by `go tool game playtest` and `game_playtest` to a game's playtest tests.
const (
OutcomeRunning = "running"
OutcomeFinished = "finished"
OutcomeFailed = "failed"
OutcomeTimeout = "timeout"
)Run outcome values reported by Collector and RunReport.Outcome.
const (
FlagProblem = "problem"
FlagWarning = "warning"
)Series entry flag values reported in SeriesEntry.Flag.
const CurrentVersion = 1CurrentVersion is the playtest.yaml schema version this package reads and writes.
const FileName = "playtest.yaml"FileName is the default playtest configuration file name at a project's root.
const ProfileCardAI = "card-ai"ProfileCardAI is the built-in greedy 1-turn-lookahead card AI bot profile for cards2d templates.
const ProfilePlatformerRunner = "platformer-runner"ProfilePlatformerRunner is the built-in greedy side-scrolling platformer bot profile.
const ProfilePuzzleSolver = "puzzle-solver"ProfilePuzzleSolver is the built-in puzzle solver and human-like player bot profile for puzzle2d templates.
const ProfileShooter = "shooter"ProfileShooter is the built-in shoot-'em-up bot profile for shmup2d templates.
const ProfileTopDownExplorer = "topdown-explorer"ProfileTopDownExplorer is the built-in top-down exploration bot profile for RPG and adventure templates (rpg2d).
const ReportFileName = "playtest.report.yaml"ReportFileName is the default playtest report file name written by go tool game playtest.
const ReportVersion = 1ReportVersion is the schema version EncodeReport writes and ParseReport accepts.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURLSchemaComment is the yaml-language-server header line EncodeConfig writes at the top of playtest.yaml.
const SchemaURL = "https://game.nsgo.dev/schemas/playtest.v1.json"SchemaURL is where the JSON Schema of version 1 playtest files (playtest.yaml) is published.
Functions
func ApplyBriefTargets(cfg *Config, b *project.Brief) intApplyBriefTargets fills or refreshes Goals on cfg.Metrics from b's feel and difficulty targets matching cfg.Scope.Scene. Only metrics with a nil Goal or a Goal whose Source is "brief.yaml" are updated, leaving explicit playtest.yaml or game.yaml goals untouched. It returns the number of metrics updated.
func BotProfiles() []stringBotProfiles returns the sorted names of all registered bot profiles.
func EncodeConfig(c *Config) ([]byte, error)EncodeConfig validates c and writes it as canonical, deterministic 2-space YAML prefixed with SchemaComment.
func EncodeReport(r *Report) ([]byte, error)EncodeReport validates r and writes it as canonical, deterministic 2-space YAML.
func Float64(v float64) *float64Float64 returns a pointer to v, useful for building Goal bounds in Go code.
func LoadBriefTargets(projectDir, scene string) (map[string]*Goal, error)LoadBriefTargets reads brief.yaml at the root of projectDir and returns its playtest Goals for scene. When brief.yaml does not exist, it returns (nil, nil).
func RecordShooterHit(metrics *Collector, waveLabel string, x, y float64)RecordShooterHit records a ship hit at (x, y) during waveLabel on both the "hit" event stream and the "hits_per_wave" series.
func RecordShooterPowerUp(metrics *Collector, collected bool, x, y float64, kind string)RecordShooterPowerUp records a spawned or collected power-up so power-ups taken % is tracked accurately.
func RecordShooterWave(metrics *Collector, waveLabel string, targetMaxHits *float64)RecordShooterWave registers waveLabel (such as "wave 1") on the "hits_per_wave" series with 0 initial hits so waves with zero hits still appear in the report.
func RegisterBot(name string, factory BotFactory)RegisterBot registers a named bot profile factory so playtest.yaml files can select it by bot.profile. It panics if name is empty or factory is nil.
func SaveConfigFile(path string, c *Config) errorSaveConfigFile validates, encodes and writes c to path.
func SaveReportFile(path string, r *Report) errorSaveReportFile validates, encodes and writes r to path.
func TargetsFromBrief(b *project.Brief, scene string) map[string]*GoalTargetsFromBrief returns a map of metric name to *Goal read from b's feel and difficulty targets for scene (empty scene includes every target in b, with later scene-specific entries taking precedence).
func ValidateMetric(m Metric) errorValidateMetric checks that m is a valid Metric definition, as used by Config.Validate and playtest_define.
func ValidateReport(r *Report) errorValidateReport checks that r uses ReportVersion and has consistent, finite fields.
Types
type Bot interface {
// Decide returns the inputs to hold for the given zero-based simulation step.
Decide(step int, dt time.Duration, obs any, rng *random.Stream) InputState
}Bot decides one fixed step of player inputs from the game's observation and a deterministic random stream.
func NewBot(cfg BotConfig) (Bot, error)NewBot instantiates the Bot named by cfg.Profile from the registered bot profiles.
func NewCardAI(cfg BotConfig) (Bot, error)NewCardAI constructs a CardAI from a playtest BotConfig.
Supported optional Bot.Params:
- "matchesPerPair" (number, default 20): matches played per unordered deck pair, alternating first player.
- "maxTurns" (number, default 60): maximum turns per match before declaring a draw.
- "maxActionsPerTurn" (number, default 4): greedy lookahead action horizon within a single player's turn.
- "msPerNode" (number, default 0.02): deterministic millisecond cost per evaluated state node for think-time reporting.
- "flagWinRateAbove" (number, default 60): win-rate percentage threshold flagged in the deck-pair matrix.
func NewPlatformerRunner(cfg BotConfig) (Bot, error)NewPlatformerRunner constructs a PlatformerRunner from a playtest Bot configuration.
Supported optional Bot.Params:
- "leftAction" (string, default "left")
- "rightAction" (string, default "right")
- "jumpAction" (string, default "jump")
- "moveAxis" (string, default "move_x")
- "jumpHoldMs" (number, default 220): base jump hold duration in milliseconds.
- "jumpHoldJitterMs" (number, default 40): +/- jitter applied to jump hold duration.
func NewPuzzleSolver(cfg BotConfig) (Bot, error)NewPuzzleSolver constructs a PuzzleSolver from a playtest BotConfig.
Supported optional Bot.Params:
- "stateLimit" (number, default 2000000): maximum distinct states BFS may explore per level.
- "undoAfterBadMoves" (number, default 3): consecutive bad moves before the human-like player undoes.
- "mode" (string, default "human"): "human" (human-like player with undo) or "solver" (BFS shortest solution).
- "mistakeRate" (number in [0, 1], default 0.35): seeded exploration rate for non-optimal moves in human mode.
- "maxHumanMoves" (number, default 200): step cap per level in pack evaluations.
- "upAction" (string, default "up")
- "downAction" (string, default "down")
- "leftAction" (string, default "left")
- "rightAction" (string, default "right")
- "undoAction" (string, default "undo")
func NewShooterBot(cfg BotConfig) (Bot, error)NewShooterBot constructs a ShooterBot from a playtest BotConfig.
If both ReactionMin and ReactionMax are 0, ShooterBot defaults to a fixed 180ms reaction time.
Supported optional Bot.Params:
- "powerUpRange" (number, default 80): distance in points within which the bot steers toward a power-up.
- "dangerRange" (number, default 36): clearance distance in points for dodging incoming bullets.
- "lookaheadMs" (number, default 400): straight-line bullet prediction horizon in milliseconds.
- "useBomb" (bool, default false): whether to trigger a bomb on an unavoidable hit.
- "fireAction" (string, default "fire")
- "focusAction" (string, default "focus")
- "bombAction" (string, default "bomb")
- "moveXAxis" (string, default "moveX")
- "moveYAxis" (string, default "moveY")
func NewTopDownExplorer(cfg BotConfig) (Bot, error)NewTopDownExplorer constructs a TopDownExplorer from a playtest BotConfig.
Supported optional Bot.Params:
- "visionRadius" (number, default 3): tile radius marked seen around the player.
- "talkToNPCs" (bool, default true): whether to seek and talk to each NPC once.
- "openChests" (bool, default true): whether to seek and open each chest once.
- "upAction" (string, default "up")
- "downAction" (string, default "down")
- "leftAction" (string, default "left")
- "rightAction" (string, default "right")
- "confirmAction" (string, default "confirm")
- "moveXAxis" (string, default "moveX")
- "moveYAxis" (string, default "moveY")
type BotActionSource struct {
// contains filtered or unexported fields
}BotActionSource adapts a Bot and an observation callback into a replay.ActionSource. Wrapping a BotActionSource in replay.NewRecorder lets the game step through replay.ActionSource unchanged while every bot decision is recorded into a deterministic replay.Recording.
func NewBotActionSource(bot Bot, observe func() any, rng *random.Stream, dt time.Duration) *BotActionSourceNewBotActionSource returns an ActionSource driven by bot with deterministic stream rng and fixed step duration dt.
func (b *BotActionSource) Axis(name string) float64Axis returns the value of axis name on the current step, falling back to 1 when action name is pressed, matching input.Actions and replay.Player.
func (b *BotActionSource) JustPressed(name string) boolJustPressed reports whether action name transitioned from released to pressed on the current step.
func (b *BotActionSource) JustReleased(name string) boolJustReleased reports whether action name transitioned from pressed to released on the current step.
func (b *BotActionSource) Pressed(name string) boolPressed reports whether action name is pressed on the current step.
func (b *BotActionSource) Step()Step queries the bot for the current step's InputState and updates the action and axis snapshots.
func (b *BotActionSource) StepIndex() intStepIndex returns how many steps have been evaluated.
type BotChannels interface {
Channels() (actions, axes []string)
}BotChannels is optionally implemented by a Bot to declare the default action and axis names recorded into each run's replay.Recording.
type BotConfig struct {
// Profile names the bot profile, such as "platformer-runner", "topdown-explorer", "shooter", "puzzle-solver" or "card-ai".
Profile string `yaml:"profile" schema:"required,minLength=1"`
// Strategy is an optional one-line summary of the bot's behavior for reports.
Strategy string `yaml:"strategy,omitempty"`
// ReactionMin is the minimum human reaction jitter duration, such as "120ms".
ReactionMin time.Duration `yaml:"reactionMin,omitempty"`
// ReactionMax is the maximum human reaction jitter duration, such as "220ms".
ReactionMax time.Duration `yaml:"reactionMax,omitempty"`
// Params holds optional profile-specific scalar parameters (booleans, finite numbers or strings).
Params map[string]any `yaml:"params,omitempty"`
}BotConfig configures the bot profile and parameters driving input during playtest runs.
type BotFactory func(cfg BotConfig) (Bot, error)BotFactory creates a fresh Bot instance for one seeded run from the playtest BotConfig.
type CardAI struct {
// contains filtered or unexported fields
}CardAI is the built-in "card-ai" bot: a greedy player that looks one turn ahead (our turn plus the opponent's best greedy reply) with deterministic tie-breaking and deterministic think-time accounting.
func (b *CardAI) Channels() (actions, axes []string)Channels declares the default action and axis names that card-ai drives.
func (b *CardAI) ChooseAction(state CardGameState, rng *random.Stream) CardDecisionChooseAction picks the highest-scoring legal action for state.ActivePlayer() using greedy 1-turn lookahead (completing our turn greedily, then simulating the opponent's best greedy reply turn).
func (b *CardAI) Decide(_ int, _ time.Duration, rawObs any, rng *random.Stream) InputStateDecide evaluates a CardObservation and encodes the chosen action index into InputState for replay recording.
func (b *CardAI) LastDecision() CardDecisionLastDecision returns the most recent CardDecision produced by ChooseAction or Decide.
type CardAction struct {
// ID uniquely names this action within the current state (such as "play:kindle" or "end_turn").
ID string
// Action is the optional replay input action name (such as "play", "discard", "draw" or "end_turn").
Action string
// Index is an optional hand or target slot index.
Index int
}CardAction identifies one legal action a CardGameState can perform.
type CardDecision struct {
// Action is the chosen CardAction.
Action CardAction
// ActionIndex is the 0-based index of Action in State.LegalActions().
ActionIndex int
// Score is the 1-turn-lookahead evaluation score for the active player.
Score float64
// NodesEvaluated is the deterministic count of state transitions evaluated during this decision.
NodesEvaluated int
// ThinkMs is the deterministic think-time estimate in milliseconds (NodesEvaluated * msPerNode).
ThinkMs float64
}CardDecision is the result of one greedy 1-turn-lookahead evaluation by CardAI.
type CardGameState interface {
// ActivePlayer returns the seat index (0 or 1) whose decision is next.
ActivePlayer() int
// Winner returns the winning seat index (0 or 1) and true when the match is over, (-1, true) for a draw, or (-1, false) while still playing.
Winner() (player int, done bool)
// Turn returns the current 1-based turn count.
Turn() int
// LegalActions returns the legal actions available to ActivePlayer in deterministic order.
LegalActions() []CardAction
// Apply returns the next immutable or cloned state resulting from taking action.
Apply(action CardAction) CardGameState
// Evaluate scores the state from player's perspective (higher is better for player).
Evaluate(player int) float64
}CardGameState is a deterministic card game state evaluated by the greedy 1-turn-lookahead CardAI.
type CardMatchFactory func(deckA, deckB string, firstPlayer int, seed uint64) (CardGameState, error)CardMatchFactory constructs a fresh deterministic match between deckA (seat 0) and deckB (seat 1), where firstPlayer (0 or 1) takes the first turn, seeded by seed.
type CardMatchResult struct {
DeckA string
DeckB string
FirstPlayer int
Winner int
Turns int
Decisions int
MedianThinkMs float64
P99ThinkMs float64
}CardMatchResult holds the outcome of one AI-vs-AI card match.
type CardObservation struct {
// State is the current card game state awaiting ActivePlayer's decision.
State CardGameState
}CardObservation is the per-step observation supplied to CardAI during playtest.Run.
type CardTournamentReport struct {
Decks []string
MatchesPlayed int
FirstPlayerWins int
FirstPlayerWinRate float64
MedianMatchTurns float64
MinMatchTurns int
MaxMatchTurns int
MostLopsidedRate float64
MostLopsidedWinner string
MostLopsidedLoser string
MedianThinkMs float64
P99ThinkMs float64
WinRateMatrix MatrixChart
Matches []CardMatchResult
}CardTournamentReport summarizes a complete round-robin deck-pair tournament between two greedy 1-turn-lookahead CardAIs.
func RunCardTournament(decks []string, factory CardMatchFactory, cfg BotConfig, seed uint64) (*CardTournamentReport, error)RunCardTournament runs every unordered pair of decks matchesPerPair times (from cfg.Params["matchesPerPair"]), alternating who goes first, using two greedy 1-turn-lookahead CardAI players seeded deterministically from seed.
type Collector struct {
// contains filtered or unexported fields
}Collector is the small Go API a game calls during a playtest run to report positioned events, counters, timers, series, matchup matrices, outcome and perf readouts.
Every method on Collector is safe to call on a nil receiver, so game code can call it unconditionally in both playtest runs and live play without guarding every call site.
func NewCollector(rate int) *CollectorNewCollector returns a fresh Collector for a run stepping at rate steps per second (60 when rate <= 0).
func (c *Collector) AddSeries(name, bucket string, delta float64)AddSeries adds delta to bucket in the named series for this run, creating the bucket in deterministic insertion order if needed.
func (c *Collector) ConfigureMatrix(name, label, unit string, flagAbove *float64, labels []string)ConfigureMatrix sets display metadata, flagging threshold and ordered row/column labels for a named win-rate matrix.
func (c *Collector) ConfigureSeries(name, label, unit, aggregate string, targetMax *float64)ConfigureSeries sets display metadata and aggregation rules for a named bar/level series (such as "hits_per_wave" or "shortest_solution").
func (c *Collector) Count(name string, delta float64)Count adds delta to the named counter. Non-finite deltas are ignored.
func (c *Collector) Counter(name string) float64Counter returns the current value of the named counter, or 0 if unset.
func (c *Collector) Done() boolDone reports whether the run has ended via Finish, Fail or timeout.
func (c *Collector) Elapsed() time.DurationElapsed returns the deterministic simulated time corresponding to the current step.
func (c *Collector) Event(kind string, x, y float64, tag ...string)Event records a positioned event (such as "death" or "pickup") at world coordinates (x, y) on the current simulation step, with an optional tag.
func (c *Collector) Events() []EventEvents returns a copy of all positioned events recorded so far.
func (c *Collector) Fail(reason string)Fail marks the run as failed with an optional human-readable reason (such as "out of lives").
func (c *Collector) Finish()Finish marks the run as finished (cleared / won). Calling Finish or Fail stops further stepping in Run.
func (c *Collector) FlagSeries(name, bucket, flag, note string)FlagSeries annotates a series bucket with an optional flag (FlagProblem or FlagWarning) and note.
func (c *Collector) Inc(name string)Inc increments the named counter by 1.
func (c *Collector) Outcome() stringOutcome returns the run's current outcome ("running", "finished", "failed" or "timeout").
func (c *Collector) Perf() *PerfSummaryPerf returns a copy of the recorded PerfSummary, or nil when none was recorded.
func (c *Collector) Rate() intRate returns the fixed step rate in steps per second.
func (c *Collector) Reason() stringReason returns the optional failure reason passed to Fail.
func (c *Collector) RecordMatchup(name, row, col string, wins, total float64)RecordMatchup adds wins out of total matches for row vs col in the named matrix.
func (c *Collector) RecordPerf(stats *debug.FrameStats, gc *debug.GCMonitor)RecordPerf captures frame timing and allocation telemetry from debug.FrameStats and debug.GCMonitor, matching the calculations of game_perf_readout.
func (c *Collector) RecordTimer(name string, d time.Duration)RecordTimer directly records a simulated duration sample for timer name. Negative durations are clamped to 0.
func (c *Collector) SetCounter(name string, value float64)SetCounter sets the named counter to value. Non-finite values are ignored.
func (c *Collector) SetPerf(summary PerfSummary)SetPerf stores an explicit PerfSummary on the collector.
func (c *Collector) SetSeries(name, bucket string, value float64)SetSeries sets bucket in the named series to value for this run, creating the bucket in deterministic insertion order if needed.
func (c *Collector) SetStep(step int)SetStep updates the collector's current zero-based simulation step. Run calls this before each step.
func (c *Collector) StartTimer(name string)StartTimer starts a deterministic simulated-time timer under name at the current step.
func (c *Collector) Step() intStep returns the collector's current zero-based simulation step.
func (c *Collector) StopTimer(name string) time.DurationStopTimer stops the named timer, records its elapsed simulated seconds, and returns the elapsed duration. Calling StopTimer on a timer that was not started returns 0 without recording a sample.
func (c *Collector) Timer(name string) (float64, bool)Timer returns the recorded duration in seconds for timer name and whether it was recorded.
type Config struct {
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version" schema:"required"`
// Scope identifies the project and scene this playtest exercises.
Scope Scope `yaml:"scope" schema:"required"`
// Runs configures the batch of headless seeded runs.
Runs Runs `yaml:"runs" schema:"required"`
// Bot selects the bot profile and configures its behavior parameters.
Bot BotConfig `yaml:"bot" schema:"required"`
// Metrics declares each measured metric, how it is aggregated, and its optional goal.
Metrics []Metric `yaml:"metrics,omitempty"`
}Config is the root of a versioned playtest.yaml document describing the scope, seeded runs, bot profile and measured metrics with goals.
func LoadConfigFile(path string) (*Config, error)LoadConfigFile reads, decodes and validates a playtest.yaml file from disk.
func ParseConfig(data []byte) (*Config, error)ParseConfig decodes and validates a playtest.yaml document, refusing unknown fields, missing or unsupported versions, duplicate keys and trailing YAML documents.
func (c *Config) Clone() *ConfigClone returns an independent deep copy of c, or nil when c is nil.
func (c *Config) Validate() errorValidate checks that c uses CurrentVersion and that its scope, runs, bot and metrics are valid.
type Event struct {
// Kind names the event, such as "death" or "pickup".
Kind string `yaml:"kind"`
// Step is the zero-based fixed simulation step on which the event happened.
Step int `yaml:"step"`
// TimeSeconds is the simulated elapsed time in seconds (Step / Rate).
TimeSeconds float64 `yaml:"timeSeconds"`
// X and Y are the world coordinates where the event occurred.
X float64 `yaml:"x"`
Y float64 `yaml:"y"`
// Tag is an optional label identifying the cause or entity, such as "slime_pit" or "coin_03".
Tag string `yaml:"tag,omitempty"`
}Event is one positioned, step-stamped occurrence reported by the game during a playtest run (such as a death or pickup).
type ExplorerChest struct {
// ID uniquely identifies the chest or item across the world.
ID string
// Cell is the tile where the chest sits.
Cell GridCell
// Opened reports whether the chest has already been opened or picked up.
Opened bool
// Solid reports whether the chest blocks movement and must be opened by facing it and pressing confirm.
// When false, the explorer walks directly onto Cell (and presses confirm if needed).
Solid bool
}ExplorerChest describes one chest or collectible interaction on a top-down map.
type ExplorerNPC struct {
// ID uniquely identifies the NPC across the world.
ID string
// Cell is the tile where the NPC stands.
Cell GridCell
// Talked reports whether the player has already spoken to this NPC.
Talked bool
}ExplorerNPC describes one NPC on a top-down map that the explorer can talk to once.
type ExplorerObservation struct {
// MapID identifies the current map so seen tiles are tracked per map.
MapID string
// Width and Height are the current map's dimensions in tiles.
Width, Height int
// Walkable reports whether tile (x, y) can be walked onto. When nil, every in-bounds tile is treated as walkable.
Walkable func(x, y int) bool
// Player is the player's current tile coordinate.
Player GridCell
// Facing is the player's current facing direction ("up", "down", "left", "right", or "").
Facing string
// Moving reports whether the player is currently mid-step between tiles.
Moving bool
// InDialogue reports whether a dialogue or prompt box is open and expects confirm to advance.
InDialogue bool
// InBattle reports whether a turn-based battle is active and expects confirm to advance.
InBattle bool
// VisionRadius is the radius in tiles around Player marked as seen on each step (defaults to bot visionRadius when <= 0).
VisionRadius int
// NPCs lists NPCs on the current map.
NPCs []ExplorerNPC
// Chests lists chests or pickups on the current map.
Chests []ExplorerChest
// Exits lists walkable exit tiles leading to other maps, used once all reachable targets on the current map have been visited.
Exits []GridCell
}ExplorerObservation is the per-step world view a top-down simulation supplies to the "topdown-explorer" bot.
type Goal struct {
// Summary is an optional human-readable description of the goal, such as "most first-timers clear floor 1".
Summary string `yaml:"summary,omitempty"`
// Source names the file this goal comes from, such as "brief.yaml", "game.yaml" or "playtest.yaml".
Source string `yaml:"source" schema:"required,minLength=1"`
// Min is the inclusive lower bound (value >= Min).
Min *float64 `yaml:"min,omitempty"`
// Max is the inclusive upper bound (value <= Max).
Max *float64 `yaml:"max,omitempty"`
// Equal requires value == Equal.
Equal *float64 `yaml:"equal,omitempty"`
}Goal defines the target range or threshold for a Metric and the file the goal comes from.
func GoalFromBriefTarget(t project.BriefPlaytestTarget) *GoalGoalFromBriefTarget converts a structured playtest target from brief.yaml into a playtest Goal whose Source is project.BriefFileName ("brief.yaml").
func (g *Goal) Describe(unit string) stringDescribe returns a concise human-readable description of g's threshold or range.
func (g *Goal) Evaluate(value float64) stringEvaluate checks whether value satisfies g and returns StatusMet, StatusMissed, or StatusInfo (when g is nil).
type GridCell struct {
X, Y int
}GridCell is a tile coordinate (column, row) in a top-down tile map.
type HeatMap struct {
// Metric is the metric name this heat map corresponds to.
Metric string `yaml:"metric"`
// Event is the event kind recorded in Points (such as "death").
Event string `yaml:"event"`
// Points lists every recorded position in deterministic run-then-step order.
Points []HeatPoint `yaml:"points,omitempty"`
}HeatMap holds world-space positioned samples for one event metric across all runs.
type HeatPoint struct {
// Seed is the run seed that produced this event.
Seed uint64 `yaml:"seed"`
// Step is the zero-based simulation step when the event happened.
Step int `yaml:"step"`
// X and Y are the world coordinates of the event.
X float64 `yaml:"x"`
Y float64 `yaml:"y"`
// Tag is the optional event tag.
Tag string `yaml:"tag,omitempty"`
}HeatPoint is one world-space event sample in a HeatMap.
type InputState struct {
// Actions maps named actions (such as "left", "right", "jump") to whether they are held on this step.
Actions map[string]bool
// Axes maps named axes (such as "move_x") to their value on this step.
Axes map[string]float64
}InputState holds the action presses and axis values a Bot chooses for one fixed simulation step.
type MatrixChart struct {
// Name uniquely identifies the matrix (such as "deck_win_rates").
Name string `yaml:"name"`
// Label is an optional display title (such as "Win rate by deck pair").
Label string `yaml:"label,omitempty"`
// Unit is an optional display unit for cells (such as "%").
Unit string `yaml:"unit,omitempty"`
// FlagAbove, when non-nil, flags cells whose value exceeds this threshold (such as 60 for >60% win rate).
FlagAbove *float64 `yaml:"flagAbove,omitempty"`
// Labels lists the row and column names in order (such as deck names).
Labels []string `yaml:"labels"`
// Cells holds the len(Labels) x len(Labels) grid; nil entries represent diagonal or unplayed pairs.
Cells [][]*float64 `yaml:"cells"`
}MatrixChart holds a labeled row-vs-column numeric matrix (such as deck-pair win rates in percent).
type Measure struct {
// Kind selects the telemetry source: "event", "counter", "timer", "outcome", "ratio" or "perf".
Kind string `yaml:"kind" schema:"required,enum=event|counter|timer|outcome|ratio|perf"`
// Key names the event kind, counter name, timer name, outcome name or perf field to read.
Key string `yaml:"key" schema:"required,minLength=1"`
// DenomKey names the denominator counter for "ratio" metrics (required when Kind is "ratio").
DenomKey string `yaml:"denomKey,omitempty"`
// Aggregate chooses how per-run values combine: "count", "sum", "mean", "median", "min", "max", "p95", "p99" or "rate".
Aggregate string `yaml:"aggregate,omitempty" schema:"enum=count|sum|mean|median|min|max|p95|p99|rate"`
// HeatMap records positioned event coordinates for this metric in the report's heatMaps section.
HeatMap bool `yaml:"heatMap,omitempty"`
}Measure specifies which telemetry signal a Metric reads and how per-run values combine.
func (m Measure) EffectiveAggregate() stringEffectiveAggregate returns m.Aggregate when set, or the default aggregate for m.Kind.
type Metric struct {
// Name uniquely identifies the metric, such as "finished", "median_time" or "frame_time".
Name string `yaml:"name" schema:"required,minLength=1"`
// Label is an optional human-readable display name, such as "Finished".
Label string `yaml:"label,omitempty"`
// Unit is an optional display unit, such as "s", "ms", "%" or "runs".
Unit string `yaml:"unit,omitempty"`
// Measure specifies how per-run telemetry is read and aggregated across runs.
Measure Measure `yaml:"measure" schema:"required"`
// Goal is the optional target threshold or range this metric is checked against.
Goal *Goal `yaml:"goal,omitempty"`
}Metric defines one measured playtest metric, how it is computed across runs, and its optional goal.
type MetricReport struct {
// Name uniquely identifies the metric.
Name string `yaml:"name"`
// Label is the human-readable display label, if set.
Label string `yaml:"label,omitempty"`
// Unit is the display unit, if set.
Unit string `yaml:"unit,omitempty"`
// Aggregate is the aggregation applied across runs (such as "count", "sum", "median", "mean").
Aggregate string `yaml:"aggregate"`
// Value is the evaluated aggregate value.
Value float64 `yaml:"value"`
// Min and Max are the minimum and maximum per-run values contributing to Value.
Min float64 `yaml:"min,omitempty"`
Max float64 `yaml:"max,omitempty"`
// Goal is the target range or threshold checked against Value, if any.
Goal *Goal `yaml:"goal,omitempty"`
// Status is "met", "missed", or "info" (when Goal is nil).
Status string `yaml:"status"`
}MetricReport holds the evaluated aggregate value and goal status for one Metric.
type PerfSummary struct {
// SampleCount is the number of frames sampled.
SampleCount int `yaml:"sampleCount,omitempty"`
// FrameMs is the mean total frame duration in milliseconds.
FrameMs float64 `yaml:"frameMs,omitempty"`
// UpdateMs is the mean fixed-update duration in milliseconds.
UpdateMs float64 `yaml:"updateMs,omitempty"`
// DrawMs is the mean draw duration in milliseconds.
DrawMs float64 `yaml:"drawMs,omitempty"`
// P50FrameMs is the 50th percentile frame duration in milliseconds.
P50FrameMs float64 `yaml:"p50FrameMs,omitempty"`
// P95FrameMs is the 95th percentile frame duration in milliseconds.
P95FrameMs float64 `yaml:"p95FrameMs,omitempty"`
// P99FrameMs is the 99th percentile frame duration in milliseconds.
P99FrameMs float64 `yaml:"p99FrameMs,omitempty"`
// MaxFrameMs is the peak frame duration in milliseconds.
MaxFrameMs float64 `yaml:"maxFrameMs,omitempty"`
// AllocsPerFrame is the mean heap allocations per frame.
AllocsPerFrame float64 `yaml:"allocsPerFrame,omitempty"`
}PerfSummary holds frame timing and allocation telemetry captured from the perf readout (debug.FrameStats and debug.GCMonitor).
func PerfFromStats(stats *debug.FrameStats, gc *debug.GCMonitor) (PerfSummary, bool)PerfFromStats builds a PerfSummary from debug.FrameStats and debug.GCMonitor using the same averaging and percentile definitions as game/mcp's game_perf_readout. It returns false when neither stats nor gc holds any samples.
type PlatformerObservation struct {
// PlayerX and PlayerY are the player's current world position (box center).
PlayerX, PlayerY float64
// PlayerVX and PlayerVY are the player's current velocity in points per second.
PlayerVX, PlayerVY float64
// Grounded reports whether the player is currently standing on ground.
Grounded bool
// OnWall is -1 when touching a wall on the left, 1 on the right, and 0 otherwise.
OnWall int
// ExitX and ExitY are the target exit or goal world coordinates.
ExitX, ExitY float64
// GapAhead reports a drop-off or missing floor tile immediately ahead in the travel direction.
GapAhead bool
// WallAhead reports a solid wall or step immediately ahead in the travel direction.
WallAhead bool
// HazardAhead reports a hazard (such as spikes or a patrolling enemy) immediately ahead.
HazardAhead bool
// HazardDistance is the horizontal distance to the nearest hazard ahead, when known.
HazardDistance float64
// LedgeAbove reports a reachable higher platform or ledge ahead and above the player.
LedgeAbove bool
}PlatformerObservation is the per-step world view a platformer simulation supplies to the "platformer-runner" bot.
func ObservePlatformerGrid(grid physics.TileGrid, playerBox physics.Box, vx, vy float32, grounded bool, onWall int, exitX, exitY float32, hazards []physics.Box, lookahead float32) PlatformerObservationObservePlatformerGrid builds a PlatformerObservation by probing a physics.TileGrid and optional hazard boxes ahead of playerBox toward (exitX, exitY). Lookahead distances default to sensible values relative to the grid's tile width when lookahead <= 0.
type PlatformerRunner struct {
// contains filtered or unexported fields
}PlatformerRunner is the built-in "platformer-runner" bot: a greedy runner toward ExitX that jumps at ledges, gaps and hazards with deterministic human reaction jitter.
func (b *PlatformerRunner) Channels() (actions, axes []string)Channels declares the default action and axis names that platformer-runner drives.
func (b *PlatformerRunner) Decide(_ int, dt time.Duration, rawObs any, rng *random.Stream) InputStateDecide picks the next horizontal movement and jump inputs for a platformer step.
type PuzzleHumanResult struct {
// Solved reports whether the human-like player solved the level.
Solved bool
// Moves is the net number of moves in the winning state (or final move count if unsolved).
Moves int
// MovesOverPar is Moves - Par when Solved is true.
MovesOverPar int
// Undos is how many undo actions the human-like player performed after bad-move streaks or dead states.
Undos int
// Actions is the sequence of move and undo action names emitted.
Actions []string
}PuzzleHumanResult summarizes one deterministic human-like playthrough of a puzzle level.
type PuzzleLevel struct {
// ID uniquely names the level (such as "level_01" or "first-light").
ID string
// Name is an optional display title.
Name string
// Par is the target move count (such as the 3-star threshold).
Par int
// IntendedMoves is the designer's intended solution length; defaults to Par when <= 0.
IntendedMoves int
// Start is the initial PuzzleState of the level.
Start PuzzleState
}PuzzleLevel describes one level in a puzzle pack evaluated by EvaluatePuzzlePack or NewPuzzlePackSim.
func (l PuzzleLevel) EffectiveIntendedMoves() intEffectiveIntendedMoves returns l.IntendedMoves when positive, falling back to l.Par.
type PuzzleLevelReport struct {
ID string
Name string
Par int
IntendedMoves int
Solve PuzzleSolveResult
Human PuzzleHumanResult
ShorterThanIntended bool
DifficultyDip bool
}PuzzleLevelReport holds the BFS solver and human-like playtest findings for one level in a pack.
type PuzzleMove stringPuzzleMove names one discrete puzzle move (such as "up", "down", "left" or "right").
type PuzzleObservation struct {
// LevelID identifies the current level so per-level plans reset cleanly when advancing levels.
LevelID string
// State is the current puzzle state.
State PuzzleState
// CanUndo reports whether the puzzle simulation supports undoing the last move.
CanUndo bool
// ParMoves is the level's par move count.
ParMoves int
// IntendedMoves is the designer's intended solution move count.
IntendedMoves int
}PuzzleObservation is the per-step world view a puzzle simulation supplies to the "puzzle-solver" bot.
type PuzzlePackReport struct {
Levels []PuzzleLevelReport
SolvableCount int
TotalLevels int
DifficultyDips int
ShorterSolutions int
MedianMovesOverPar float64
}PuzzlePackReport summarizes BFS solvability, difficulty ordering, unintended shorter solutions and human-like moves over par across a puzzle pack.
func EvaluatePuzzlePack(levels []PuzzleLevel, cfg BotConfig, seed uint64) (*PuzzlePackReport, error)EvaluatePuzzlePack runs the BFS shortest-solution solver (bounded by stateLimit) and the human-like undo player across levels using deterministic seed.
type PuzzleScorer interface {
ProgressScore() float64
}PuzzleScorer is optionally implemented by a PuzzleState to provide a progress heuristic (higher is closer to solved) for the human-like puzzle player.
type PuzzleSolveResult struct {
// Solved reports whether a solution was found within the state limit.
Solved bool
// Solution is the shortest sequence of moves from the start state to a solved state.
Solution []PuzzleMove
// Moves is len(Solution) when Solved is true, or 0 otherwise.
Moves int
// StatesExplored is the number of distinct states visited by BFS.
StatesExplored int
// HitStateLimit reports whether BFS terminated because it reached maxStates.
HitStateLimit bool
}PuzzleSolveResult is the outcome of a breadth-first shortest-solution search on one PuzzleState.
func SolvePuzzleBFS(start PuzzleState, maxStates int) PuzzleSolveResultSolvePuzzleBFS runs a deterministic breadth-first search from start to find the shortest sequence of moves reaching a Solved state, stopping if maxStates distinct states are visited. When maxStates <= 0, it defaults to 2,000,000 states.
type PuzzleSolver struct {
// contains filtered or unexported fields
}PuzzleSolver is the built-in "puzzle-solver" bot: in "solver" mode it plays the BFS shortest solution, and in "human" mode it plays like a human who explores, makes occasional mistakes, and undoes after three bad moves.
func (b *PuzzleSolver) Channels() (actions, axes []string)Channels declares the default action names that puzzle-solver drives.
func (b *PuzzleSolver) Decide(_ int, _ time.Duration, rawObs any, rng *random.Stream) InputStateDecide chooses the next move or undo action for one puzzle simulation step.
type PuzzleState interface {
// Key returns a unique canonical string identifying this state for visited-state deduplication.
Key() string
// Solved reports whether the puzzle's win condition is satisfied.
Solved() bool
// Dead reports whether this state is an unrecoverable loss (such as falling into a void).
Dead() bool
// Moves returns the legal moves from this state in deterministic order.
Moves() []PuzzleMove
// Apply returns the next state after taking move, and whether the move changed the state.
Apply(move PuzzleMove) (PuzzleState, bool)
}PuzzleState is a discrete puzzle state explored by SolvePuzzleBFS and PuzzleSolver.
type Report struct {
// Version is the report schema version; it must equal ReportVersion (1).
Version int `yaml:"version"`
// Scope identifies the project and scene that were playtested.
Scope Scope `yaml:"scope"`
// Bot records the bot profile and parameters used for the runs.
Bot BotConfig `yaml:"bot"`
// Rate is the fixed simulation step rate in steps per second.
Rate int `yaml:"rate"`
// Speed is the configured speed multiplier.
Speed float64 `yaml:"speed,omitempty"`
// SeedCount is the number of seeded runs included in Runs.
SeedCount int `yaml:"seedCount"`
// Passed reports whether every metric with a Goal met its goal.
Passed bool `yaml:"passed"`
// Metrics holds the aggregated value and goal check for every metric in the playtest config.
Metrics []MetricReport `yaml:"metrics,omitempty"`
// HeatMaps holds world-space position data collected from positioned events for heat maps.
HeatMaps []HeatMap `yaml:"heatMaps,omitempty"`
// Series holds labeled bar or per-level numeric series (such as hits per wave or shortest solution per level).
Series []SeriesChart `yaml:"series,omitempty"`
// Matrices holds labeled row-vs-column numeric matrices (such as deck-pair win rates in percent).
Matrices []MatrixChart `yaml:"matrices,omitempty"`
// Runs holds per-seed outcomes, durations, counters, timers, positioned events, perf readouts and recording paths.
Runs []RunReport `yaml:"runs"`
}Report is the deterministic YAML report written after running a playtest batch.
func LoadReportFile(path string) (*Report, error)LoadReportFile reads, decodes and validates a YAML playtest report from disk.
func ParseReport(data []byte) (*Report, error)ParseReport decodes and validates a YAML playtest report, refusing unknown fields, missing or unsupported versions and trailing YAML documents.
func (r *Report) MissedMetrics() []MetricReportMissedMetrics returns every MetricReport whose Status is StatusMissed.
func (r *Report) Summary() stringSummary formats a concise, deterministic human-readable report summary listing every metric's value, goal, source file and MET/MISSED status.
type RunOptions struct {
// Bot overrides the bot factory resolved from cfg.Bot.Profile when non-nil.
Bot BotFactory
// Actions overrides the watched action names recorded into each run's replay.Recording.
// When empty, Run uses BotChannels.Channels if the bot implements it.
Actions []string
// Axes overrides the watched axis names recorded into each run's replay.Recording.
// When empty, Run uses BotChannels.Channels if the bot implements it.
Axes []string
// RecordingsDir, when non-empty, writes each run's replay.Recording as <RecordingsDir>/run_<NNN>_seed_<seed>.replay.yaml and records the relative/slash path in RunReport.Recording.
RecordingsDir string
// MeasurePerf, when true and the simulation provides no perf readout of its own, measures each Step call with debug.FrameStats.
// Off by default so repeated headless runs produce byte-identical reports.
MeasurePerf bool
}RunOptions configures Run.
type RunReport struct {
// Index is the 1-based run number within the batch.
Index int `yaml:"index"`
// Seed is the deterministic random seed for this run.
Seed uint64 `yaml:"seed"`
// Outcome is "finished", "failed", or "timeout".
Outcome string `yaml:"outcome"`
// Reason is the optional failure reason when Outcome is "failed".
Reason string `yaml:"reason,omitempty"`
// Steps is the number of fixed simulation steps executed.
Steps int `yaml:"steps"`
// DurationSeconds is the simulated run duration in seconds (Steps / Rate).
DurationSeconds float64 `yaml:"durationSeconds"`
// Recording is the slash-separated path to this run's saved .replay.yaml recording, when saved.
Recording string `yaml:"recording,omitempty"`
// Counters holds the final values of all counters reported during this run.
Counters map[string]float64 `yaml:"counters,omitempty"`
// Timers holds the recorded simulated durations in seconds of all timers reported during this run.
Timers map[string]float64 `yaml:"timers,omitempty"`
// Events holds all positioned events reported during this run.
Events []Event `yaml:"events,omitempty"`
// Perf holds the perf readout captured for this run, when available.
Perf *PerfSummary `yaml:"perf,omitempty"`
}RunReport holds the deterministic results of one seeded playtest run.
type RunResult struct {
// Report is the deterministic YAML-serializable playtest report.
Report *Report
// Recordings holds one replay.Recording per entry in Report.Runs, in the same order.
Recordings []*replay.Recording
}RunResult holds the evaluated Report and the in-memory replay.Recording of every seeded run.
func Run(cfg *Config, makeSim SimFactory, opts RunOptions) (*RunResult, error)Run executes every seeded run configured by cfg against makeSim, records each run as a replay.Recording, evaluates every metric and goal, and returns the Report and recordings.
func RunTest(t testing.TB, defaultConfigPath string, makeSim SimFactory, opts ...RunOptions) *RunResultRunTest loads playtest.yaml, runs the playtest against makeSim, writes the report and recordings when requested via environment variables (as `go tool game playtest` sets them), and fails t when any metric goal is missed (unless NSGO_PLAYTEST_NO_FAIL=1).
type Runs struct {
// Count is the number of seeded runs to execute; when 0 and Seeds is non-empty, it defaults to len(Seeds).
Count int `yaml:"count,omitempty" schema:"minimum=0"`
// Seeds lists explicit per-run random seeds; when fewer than Count, additional seeds are derived sequentially from SeedStart.
Seeds []uint64 `yaml:"seeds,omitempty"`
// SeedStart is the starting seed used when generating sequential seeds (defaults to 1 when 0).
SeedStart uint64 `yaml:"seedStart,omitempty"`
// Rate is the fixed simulation step rate in steps per second (defaults to 60 when 0).
Rate int `yaml:"rate,omitempty" schema:"minimum=0"`
// Speed is the simulation speed multiplier metadata, such as 1 or 8 for 8x speed (defaults to 1 when 0).
Speed float64 `yaml:"speed,omitempty" schema:"minimum=0"`
// MaxDuration is the simulated time limit per run before timing out, such as "60s" (defaults to 60s when 0).
MaxDuration time.Duration `yaml:"maxDuration,omitempty"`
}Runs configures how many seeded runs execute, their seeds, fixed step rate, speed and simulated time limit.
func (r Runs) EffectiveMaxDuration() time.DurationEffectiveMaxDuration returns the per-run simulated time limit, defaulting to 60s when unset.
func (r Runs) EffectiveRate() intEffectiveRate returns the fixed step rate in steps per second, defaulting to 60 when unset.
func (r Runs) EffectiveSpeed() float64EffectiveSpeed returns the speed multiplier, defaulting to 1 when unset.
func (r Runs) MaxSteps() intMaxSteps returns the number of fixed steps corresponding to EffectiveMaxDuration at EffectiveRate.
func (r Runs) ResolveSeeds() []uint64ResolveSeeds returns the deterministic list of per-run seeds configured by r.
type Scope struct {
// Project is the project name or relative path to the project root.
Project string `yaml:"project,omitempty"`
// Scene names the scene or level the playtest exercises, such as "level_01".
Scene string `yaml:"scene" schema:"required,minLength=1"`
// Template names the template the playtest originated from, such as "platformer2d".
Template string `yaml:"template,omitempty"`
}Scope identifies the project, scene and optional template a playtest targets.
type SeriesChart struct {
// Name uniquely identifies the series (such as "hits_per_wave" or "shortest_solution").
Name string `yaml:"name"`
// Label is an optional display title (such as "Hits taken per wave").
Label string `yaml:"label,omitempty"`
// Unit is an optional value unit (such as "hits" or "moves").
Unit string `yaml:"unit,omitempty"`
// Aggregate is how per-run bucket values were combined (such as "median", "mean", "sum", "min" or "max").
Aggregate string `yaml:"aggregate,omitempty"`
// TargetMax, when non-nil, is an upper target line for bars; entries above it are flagged.
TargetMax *float64 `yaml:"targetMax,omitempty"`
// Entries lists each labeled bar in deterministic display order.
Entries []SeriesEntry `yaml:"entries,omitempty"`
}SeriesChart holds labeled numeric bars or per-bucket aggregates across runs (such as hits per wave or shortest solution moves per level).
type SeriesEntry struct {
// Label identifies the bucket (such as "wave 1" or "level_07").
Label string `yaml:"label"`
// Value is the aggregated value for this bucket.
Value float64 `yaml:"value"`
// Flag optionally marks a standout bar: "problem" or "warning".
Flag string `yaml:"flag,omitempty"`
// Note is an optional short annotation for this entry.
Note string `yaml:"note,omitempty"`
}SeriesEntry is one labeled value in a SeriesChart.
type ShooterBot struct {
// contains filtered or unexported fields
}ShooterBot is the built-in "shooter" bot: it fires constantly, dodges incoming bullets with a fixed (or bounded) reaction time delay, and collects power-ups within a configurable radius.
func (b *ShooterBot) Channels() (actions, axes []string)Channels declares the default action and axis names that shooter drives.
func (b *ShooterBot) Decide(_ int, dt time.Duration, rawObs any, rng *random.Stream) InputStateDecide picks ship movement, firing, focus and optional bomb inputs for one step using a reaction-delayed perception buffer.
type ShooterBullet struct {
X, Y float64
VX, VY float64
Radius float64
}ShooterBullet describes one active enemy projectile on the playfield.
type ShooterObservation struct {
// PlayfieldWidth and PlayfieldHeight are the stage dimensions in game points.
PlayfieldWidth, PlayfieldHeight float64
// ShipX, ShipY and ShipRadius are the player ship's coordinates and hit radius.
ShipX, ShipY, ShipRadius float64
// ShipAlive reports whether the player ship is alive.
ShipAlive bool
// Invulnerable reports whether the ship is currently invulnerable.
Invulnerable bool
// Bombs is the number of bombs currently available.
Bombs int
// Wave is the 1-based current wave index (0 if not in a wave).
Wave int
// Bullets lists active enemy projectiles.
Bullets []ShooterBullet
// Enemies lists active on-screen enemies and bosses.
Enemies []ShooterTarget
// PowerUps lists active power-ups drifting on the playfield.
PowerUps []ShooterPowerUp
}ShooterObservation is the per-step world view a shoot-'em-up simulation supplies to the "shooter" bot.
type ShooterPowerUp struct {
ID string
Kind string
X, Y float64
}ShooterPowerUp describes one collectible power-up drifting on the playfield.
type ShooterTarget struct {
X, Y float64
Radius float64
IsBoss bool
}ShooterTarget describes one active enemy or boss on the playfield.
type Sim struct {
// Step advances the simulation by one fixed step of dt.
// Like game.Loop.Update and statedump.Sim.Step, Step must call the provided replay.ActionSource's Step method once per step, or Run returns an error.
Step func(dt time.Duration)
// Observe returns the current state observation for the Bot before each step (such as a PlatformerObservation).
Observe func() any
// FrameStats is an optional debug.FrameStats whose perf readout is captured at the end of the run.
FrameStats *debug.FrameStats
// GC is an optional debug.GCMonitor whose allocation readout is captured at the end of the run.
GC *debug.GCMonitor
// Perf is an optional callback returning a PerfSummary at the end of the run; when non-nil it overrides FrameStats and GC.
Perf func() *PerfSummary
}Sim is one seeded headless simulation driven by Run.
type SimFactory func(seed uint64, src replay.ActionSource, metrics *Collector) (Sim, error)SimFactory creates a fresh deterministic simulation for one seeded run. src is a *replay.Recorder wrapping the run's bot; calling src.Step() once per fixed step records every input transition into that run's replay.Recording. metrics is the per-run *Collector where the game reports positioned events, counters, timers and outcome.
func NewCardTournamentSim(decks []string, factory CardMatchFactory, botCfg BotConfig) SimFactoryNewCardTournamentSim returns a SimFactory that executes a round-robin deck-pair tournament inside playtest.Run, recording every AI decision through replay.Recorder and reporting first-player win rate, match length, most lopsided pair, think time, and the win-rate matrix on metrics.
func NewPuzzlePackSim(levels []PuzzleLevel, botCfg BotConfig) SimFactoryNewPuzzlePackSim returns a SimFactory that runs the "puzzle-solver" bot through playtest.Run across every level in levels, recording replay inputs, BFS shortest solutions, difficulty dips, shorter-than-intended solutions, and human-like moves over par on metrics.
type TopDownExplorer struct {
// contains filtered or unexported fields
}TopDownExplorer is the built-in "topdown-explorer" bot: it walks to the nearest unseen tile, talks to every NPC once, opens every chest once, and stops when the run finishes or reaches runs.maxDuration (configured at 8x speed).
func (b *TopDownExplorer) Channels() (actions, axes []string)Channels declares the default action and axis names that topdown-explorer drives.
func (b *TopDownExplorer) Decide(_ int, dt time.Duration, rawObs any, rng *random.Stream) InputStateDecide picks the next directional movement or confirm interaction for one top-down exploration step.
func (b *TopDownExplorer) SeenCount(mapID string) intSeenCount returns how many unique walkable tiles the explorer has seen on mapID.
func (b *TopDownExplorer) TileDuration(mapID string, cell GridCell) time.DurationTileDuration returns the total simulated time spent on cell in mapID.