Skip to content
Work in progress. These docs describe Spawnite at launch, and some parts are still being built.

A tour of the example game

The example game is the project spawnite create --template example writes. A new game starts from the smaller minimal template; the example shows the engine’s features in one game. It opens on a lobby where a robot stands on a grid. The Play button opens a run: walk to three coins in a line and collect them before a 20-second clock runs out, past a ball you can kick and a tree. The Platforms button opens a climb up five boxes. Each sample below is the example’s own file, or part of one, and the example’s tests under test/ run it.

Every game on the engine has the following shape. A game holds scenes, a scene holds a world, and a world holds entities, each with the behaviours that make it act:

flowchart TB
    Game --> Scene --> Landscape --> Entity --> Behaviour
    Scene -.-> UI

Solid arrows are nesting. The dotted arrow is UI, which draws on the screen over the world. How a game fits together explains each level.

To have an agent build a game with you instead, see Make your game. To add a scene of your own to the example, Add your own scene lists the edits.

Create a project from the example template, then install it. The packages come from npm, so the install needs no token:

Terminal window
npx @spawnite/cli create my-game --template example
cd my-game && npm install

The example plays alone: it runs on the player’s page, with no room. To play it with friends in a room, create it with --room as well. That writes the three parts a room takes, as Run a room while you build says:

  • The spawnite.room key in package.json, which names the scene the room runs.
  • The @spawnite/room dev dependency, the room itself.
  • room: defineRoom() in defineGame, in src/game.ts.

A project created without --room takes the same three edits by hand. defineRoom comes from @spawnite/engine/core, beside defineGame.

The UI’s panels and buttons take a theme, and a shipped template takes the glass theme, translucent panels over the game. For another, add --theme frost: the command imports that theme’s stylesheet in src/styles.css, right after the UI stylesheet.

The project holds the following files, among others:

File What it is
src/app/app.tsx The game: its scenes, its plugins, its save and the wallet’s readout
src/game.ts The plugins every scene runs, and the game’s maps
src/scenes/ The lobby, the run and the platforms, one file each
src/components/ The entities: the robot, a coin, the ball, the tree, the ring and a platform, and the match’s HUD
src/behaviours/Roll.tsx A behaviour of the game’s own, on the ball
src/kicks.ts, src/runs.ts Two plugins of the game’s own: the kick, and the count of runs won
src/items.ts The one item, a potion
wiki/ The game’s own pages, which the devtools’ Wiki tab shows
test/ Vitest tests that step the scenes headless and build the game

In your project the paths start at src/. A sample’s title names the file it is copied from in Spawnite’s own repository, here under games/example/, and the docs’ tests fail when the sample and that file differ. A title that ends in (part) shows a piece of the file. The example’s own tests and typecheck cover each of these files.

Three files start the game, and a fourth, src/game.ts, lists its plugins. To add a scene, an agent adds an import and a <Scene> line to app.tsx, as Add your own scene says, and leaves the rest as it is. The example’s tests pin parts of these files, as What the example’s tests pin lists. index.html loads src/main.tsx and the game’s stylesheet, src/styles.css.

src/main.tsx is the page’s entry, which index.html loads. It renders the default export of app.tsx into the page’s root element, and renders into the same root again when a hot update runs the module a second time:

games/example/src/main.tsx
import { StrictMode } from "react";
import * as ReactDOM from "react-dom/client";
import App from "./app/app";
// A hot update that reaches this module runs it again, so it renders into
// the root it made the first time: a second root on the same element
// would fight the first for its children.
const root: ReactDOM.Root =
import.meta.hot?.data.root ??
ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
if (import.meta.hot) import.meta.hot.data.root = root;
root.render(
<StrictMode>
<App />
</StrictMode>,
);

src/app/app.tsx is the game. A Game holds the scenes and says which one opens first, and each Scene names one screen of the game and the component that draws it. The example opens on the lobby. The lines to read first are <Game game={game} …>, the three <Scene> lines inside it, and export default App at the end:

games/example/src/app/app.tsx
import {
Game,
Hud,
Panel,
PanelVariant,
Scene,
Slot,
Text,
useWallet,
} from "@spawnite/engine";
import { game } from "../game";
import { Lobby } from "../scenes/Lobby";
import { Platforms } from "../scenes/Platforms";
import { Run } from "../scenes/Run";
// The example game: a lobby where the visor robot stands, then a run through
// three coins to a goal ring, or a climb up five platforms. One file per
// level of the engine's shape.
/** The wallet, at game level, so it reads the same in every scene. */
function Readout() {
const { coins } = useWallet();
return (
<Hud>
<Panel slot={Slot.TopRight} variant={PanelVariant.Glass}>
<Text>Coins {coins}</Text>
</Panel>
</Hud>
);
}
export function App() {
return (
<Game
game={game}
devtools={import.meta.env.DEV && (() => import("./devtools"))}
>
<Scene name="lobby" component={Lobby} />
<Scene name="run" component={Run} />
<Scene name="platforms" component={Platforms} />
<Readout />
</Game>
);
}
export default App;

Besides the scenes, the file does the following:

  • devtools hands Game the devtools module to mount in development alone: the import.meta.env.DEV && guard has a production build drop the import, and the engine’s Vite plugin fails a production build that still holds the devtools.
  • Readout draws the wallet’s count at the game’s level, so it reads the same in every scene.

Game reads the room and the renderer off the page’s address itself, as The page’s address lists the keys. With no ?room=, the game plays alone.

Keep export default App at the end: main.tsx imports the default export, and a file with only the named App export does not typecheck. Keep the devtools line as it is, guard included. src/game.ts registers each map file under src/maps by its file name with registerMaps, for the page, the room and spawnite simulate alike; keep that line too. A game with no map files still runs with it: the line registers nothing, and the built-in grid and meadow need no file.

src/app/devtools.tsx is the module the devtools line loads. Its default export mounts the engine’s devtools, with the game’s own panels in panels, where spawnite add panel has a panel’s entry pasted. The example’s build test fails if any devtools code reaches a production build, and the playtest tools in step 7 drive the game through the devtools:

games/example/src/app/devtools.tsx
import { Devtools, type DevtoolsPanel } from "@spawnite/devtools";
// Loaded in development alone, through the import <Game devtools> takes
// in app.tsx, so a production build never reaches this module or the
// devtools behind it.
// Where `spawnite add panel` has a panel's entry pasted.
const panels: DevtoolsPanel[] = [];
export default function ExampleDevtools() {
return <Devtools panels={panels} />;
}

src/game.ts declares the game with defineGame: its name, the scene that opens, and plugins, what the world steps each tick. Those are the engine’s plugins the character and the behaviours need, the round, and the game’s own. A plugin brings its systems, its inputs and its traits, and Game runs each system in its phase every step. Plugins lists the engine’s.

games/example/src/game.ts
import { behaviours } from "@spawnite/engine/behaviours";
import { defineGame, defineSave } from "@spawnite/engine/core";
import { cameras } from "@spawnite/engine/cameras";
import { machines } from "@spawnite/engine/machines";
import { stats } from "@spawnite/engine/stats";
import { inventory } from "@spawnite/engine/inventory";
import { characters } from "@spawnite/engine/characters";
import { kicks } from "./kicks";
import { matches } from "@spawnite/engine/matches";
import { runs, readRunsWon, setRunsWon } from "./runs";
import { z } from "@spawnite/schema";
import { cooldowns } from "@spawnite/engine/cooldowns";
import { resources } from "@spawnite/engine/resources";
import { registerMaps } from "@spawnite/engine";
// Every map file under src/maps, each by its file name, for the page, the
// room and spawnite simulate alike, which all load this module.
registerMaps(import.meta.glob("./maps/*.json"));
/** The game, whose plugins every scene's page and the room run: the character and the
* engine's plugins it leans on, the bag for the potion, the match the Run
* scene plays, the kick for the ball, and the count of runs won. */
export const game = defineGame({
name: "example",
start: "lobby",
plugins: [
cameras(),
characters(),
stats(),
cooldowns(),
resources(),
behaviours(),
machines(),
inventory(),
matches(),
kicks(),
runs(),
],
playerState: defineSave({
scopes: ["player"],
version: 1,
schema: z.object({ runsWon: z.int().check(z.nonnegative()) }),
read: ({ player }) => ({ runsWon: readRunsWon(player) }),
restore: ({ writer, player }, saved) =>
setRunsWon(writer, player, saved.runsWon),
}),
});

A scene renders a Landscape, and everything in the scene stands inside it. The lobby stands on grid, the flat floor a Landscape mounts when it names no map. The lobby names it outright, under the noon look. The grid loads no texture and no scatter model, so the first screen opens fast. The run and the platforms stand on meadow, the engine’s map of hills and trees.

games/example/src/scenes/Lobby.tsx
import {
Button,
Camera,
CameraPreset,
Entity,
Hud,
Panel,
Slot,
useScenes,
Views,
Landscape,
} from "@spawnite/engine";
import { noon } from "@spawnite/engine/looks/noon";
import { Sprite } from "@spawnite/engine/2d";
import "../items";
import { Robot } from "../components/Robot";
import { pickupsSheet } from "../sprites";
// A room and `spawnite simulate` load this file alone, so it exports the
// game's plugins and its save.
export { game } from "../game";
/** Metres the lobby's camera opens behind the robot. */
const lobbyCameraDistance = 4;
/** Degrees the lobby's camera opens looking down. */
const lobbyCameraPitch = 10;
/** The visor robot standing on the engine's plain grid under the noon
* look, a camera behind it, a coin and a heart drawn as pixel art in front of
* it, and the buttons to the run and the platforms. The grid loads no texture
* and no model, so the first screen opens fast. */
export function Lobby() {
const scenes = useScenes();
return (
<Landscape map="grid" look={noon}>
<Robot />
<Entity position={[-1.2, 0.3, -2.5]}>
<Sprite sheet={pickupsSheet} clip="coin" />
</Entity>
<Entity position={[1.2, 0.3, -2.5]}>
<Sprite sheet={pickupsSheet} clip="heart" />
</Entity>
<Views>
{/* Behind the robot and low, so the whole floor and the sky
show; the left button's drag orbits it, and no
click-to-walk. */}
<Camera
preset={CameraPreset.Classic}
distance={lobbyCameraDistance}
pitch={lobbyCameraPitch}
clickToWalk={false}
/>
<Hud>
<Panel slot={Slot.Bottom}>
<Button onPress={() => scenes.go("run")}>Play</Button>
<Button onPress={() => scenes.go("platforms")}>
Platforms
</Button>
</Panel>
</Hud>
</Views>
</Landscape>
);
}

In the lobby’s file:

  • The two export lines at the top are there because a room and spawnite simulate load a scene’s file alone, never the app, so the file hands them the game and its save.
  • import "../items" registers the game’s items, for the same reason: a scene names an item only where the scene imports the file that registers it.
  • The Camera uses the Classic preset: it opens 4 m behind the robot, looking down 10 degrees, low enough to show the whole floor and the sky. A drag with the left button orbits it, and clickToWalk={false} keeps a click from walking the character.
  • The coin and the heart are two Sprites, each an Entity drawing one clip of the game’s pixel art sheet, pickupsSheet.
  • A Button in a Hud calls scenes.go("run") to move the game to the run.

The robot is the player’s character: a <CharacterSpawn> with the visor-bot model, which plays its idle, walk, run and jump clips. Every scene mounts the same component, so the character looks the same everywhere:

games/example/src/components/Robot.tsx
import { CharacterSpawn, type CharacterSpawnProps } from "@spawnite/engine";
import "../models";
/** The player's character, as the visor robot: its rigged model playing its
* idle, walk, run and jump. */
export function Robot(props: Omit<CharacterSpawnProps, "model">) {
return <CharacterSpawn model="visor-bot" {...props} />;
}

The second button opens the platforms scene, src/scenes/Platforms.tsx, under a SideCamera, with Space to jump. It holds five fixed boxes that climb across the meadow’s clearing, each 0.9 m higher than the last, past the character’s 0.6 m step and under its 1.2 m jump. On a phone, the engine’s stick and Jump button stand in for the keys, as Touch controls says, and a hidden Tap bound to the kick leaves out the Kick button, since the scene has no ball. The scene has no ending: the top platform is the goal.

The run puts three coins in a line ahead of the player, a tree beside them, the ball past the last coin and the ring at the end. Its camera follows the player:

games/example/src/scenes/Run.tsx
import {
Camera,
CameraPreset,
CameraTarget,
Hud,
Panel,
PanelVariant,
Slot,
Text,
Views,
Landscape,
type Position,
} from "@spawnite/engine";
import { Match, MatchScreen } from "@spawnite/engine/matches";
import "../items";
import { Ball } from "../components/Ball";
import { Coin } from "../components/Coin";
import { Ring } from "../components/Ring";
import { MatchClock } from "../components/MatchClock";
import { Tree } from "../components/Tree";
import { Robot } from "../components/Robot";
// A room and `spawnite simulate` load this file alone, so it exports the
// game's plugins and its save.
export { game } from "../game";
/** Three coins in a line ahead of the player, a tree beside them, then the
* ball, and the ring past them. The match is won with every coin. */
export const coinPositions: Position[] = [
[0, 0, -3],
[0, 0, -5],
[0, 0, -7],
];
/** Resting on the ground: its centre a radius up. */
export const ballPosition: Position = [0, 0.5, -8.5];
const treePosition: Position = [2, 0, -5];
const ringPosition: Position = [0, 0, -10];
export function Run() {
return (
<Landscape map="meadow">
<Robot />
<Match timeLimitSeconds={20} scoreToWin={coinPositions.length} />
{coinPositions.map((position) => (
<Coin key={position.join()} position={position} />
))}
<Ball position={ballPosition} />
<Tree position={treePosition} />
<Ring position={ringPosition} />
{/* What draws the scene: the page mounts it, a room never. */}
<Views>
{/* The orbit it has always had: the left button's drag,
and no click-to-walk. */}
<Camera
follow={CameraTarget.ViewTarget}
preset={CameraPreset.Classic}
clickToWalk={false}
/>
<MatchClock />
<MatchScreen />
<Hud>
<Panel slot={Slot.Bottom} variant={PanelVariant.Glass}>
<Text>
WASD walks, and F kicks the ball. Collect the three
coins before the clock runs out.
</Text>
</Panel>
</Hud>
</Views>
</Landscape>
);
}

The scene is split in two. The entities and the match are its logic, which the room runs too. The camera, the match’s clock and the HUD stand in <Views>, which draws on the page and which a room never mounts.

A coin is an Entity with a Pickup. The player who walks within its radius takes the reward into their wallet, with the engine’s pickup chime, and the coin goes. Spin and Bob move it so that it reads as a coin. Its body is kinematic, so it moves with the bob and never falls, and the ball bounces off it where it is drawn. Its gold disc is its view, which the page draws on the entity and the room skips:

games/example/src/components/Coin.tsx
import {
Bob,
box,
Entity,
Pickup,
type Position,
RigidBodyType,
sounds,
Spin,
} from "@spawnite/engine";
/** One coin: it turns, bobs, and goes into the wallet of whoever reaches it,
* with a chime.
* Its body follows the bob, so the ball bounces off it where it is drawn. */
export interface CoinProps {
position: Position;
}
export function Coin({ position }: CoinProps) {
return (
<Entity
position={position}
body={{ bodyType: RigidBodyType.Kinematic }}
collider={{ shape: box({ size: [0.8, 0.1, 0.8] }) }}
view={CoinView}
>
<Spin speed={2} />
<Bob height={0.2} />
<Pickup reward={1} sound={sounds.pickup} />
</Entity>
);
}
/** How a coin is drawn on a page: a gold disc. A room never mounts it. */
function CoinView() {
return (
<mesh>
<cylinderGeometry args={[0.4, 0.4, 0.1, 24]} />
<meshStandardMaterial color="gold" />
</mesh>
);
}

The other entities in the run each show one more part of the engine:

  • The tree’s collider is convexHull(), the hull of its model, so the character stops at its bark and canopy rather than at a box round them.
  • The ring only spins. It has no collider, and the match ends on the coins, not on reaching the ring.
  • The ball has a dynamic body, so it falls to the ground and rolls when the character walks into it or kicks it:
games/example/src/components/Ball.tsx (part)
export function Ball({ position }: Required<Pick<EntityProps, "position">>) {
return (
<Entity
position={position}
body={{ bodyType: RigidBodyType.Dynamic }}
collider={{ shape: sphere({ radius: 0.5 }) }}
view={BallView}
>
<Roll spot={position} />
</Entity>
);
}
/** How a ball is drawn on a page: a red sphere its radius across. A room
* never mounts it. */
function BallView() {
return (
<mesh>
<sphereGeometry args={[0.5, 24, 16]} />
<meshStandardMaterial color="tomato" />
</mesh>
);
}

<Roll> is a behaviour of the game’s own, in src/behaviours/Roll.tsx: a state machine that says whether the ball still rests on its spot. Its when watches the ball’s own transform, so no system has to send it anything:

games/example/src/behaviours/Roll.tsx (part)
export const RollMachine = defineMachine({
id: "roll",
description: "The ball: resting on its spot, then pushed off it.",
initial: "resting",
context: { spotX: 0, spotZ: 0 },
states: {
resting: { when: [[isOffItsSpot, "pushed"]] },
pushed: {},
},
});
export const RollBehaviour = defineBehaviour({
name: "roll",
trait: RollMachine.trait,
runsOn: RunContext.Client,
wiki: "/behaviours/roll/",
source: "src/behaviours/Roll.tsx",
description: "Says whether the ball rests on its spot or was pushed.",
});

State machines says how defineMachine works, and Entity how a behaviour is defined.

F, or the Kick button on a phone, kicks a ball within 1.4 m of the character. No engine plugin does that, so the example declares a plugin of its own: an input bound to the F key and a touch button, and a predicted system in the rules phase that runs after the engine’s cooldowns count down:

games/example/src/kicks.ts (part)
export const kicks = definePlugin(() => ({
name: "kicks",
description: "Kicks a ball within reach on F.",
inputs: {
kick: buttonInput({
keys: ["KeyF"],
touch: { label: "Kick" },
description: "Kick the ball",
}),
},
systems: [
defineSystem({
name: "kick",
phase: Phase.Rules,
predicted: true,
after: [cooldowns.systems.countDown],
description:
"Kicks each ball within reach of a character pressing kick.",
run: kickBalls,
}),
],
}));

The system reads each character holding the kick and pushes each dynamic body within reach away from it, with an impulse of 2.4 newton-seconds along the ground and 0.8 up, then waits half a second before the next kick. It reads the character’s input and starts its cooldown, so it is a predicted system. The player’s page runs it on the tick the player pressed, and the room alone pushes the ball, inside if (step.authoritative):

games/example/src/kicks.ts (part)
function kickBalls(step: PredictedStep) {
const world = step.world;
step.updateEachPredicted(characters, ([{ position: feet }], character) => {
if (!readInput(character, kicks.inputs.kick)) return;
if (isCoolingDown(character, kickCooldown)) return;
readEach(world, bodies, ([body, { position }], ball) => {
if (body.bodyType !== RigidBodyType.Dynamic) return;
away.subVectors(position, feet).setY(0);
if (away.length() > kickReach) return;
away.normalize().multiplyScalar(kickAlong).setY(kickUp);
if (step.authoritative) applyImpulse(step, ball, away);
startCooldown(step, character, { key: kickCooldown, seconds: 0.5 });
});
});
}

Systems says how a system reads and changes the world, and Plugins how a game declares one.

A Match counts down game time and scores the coins the player picks up while it plays. The run’s <Match timeLimitSeconds={20} scoreToWin={coinPositions.length} /> lasts 20 seconds and is won with three coins. In a game played alone, it starts when the scene opens. In a room, which opens its scene before anyone plays, the match waits until the first player presses Play and opens the run.

The match scores every coin credited to a wallet while it plays, by its amount, so each coin’s Pickup scores with no code of the game’s own. scoreCoins={false} turns that off, for a game that scores with addMatchScore alone.

The match ends in a victory on the step the third coin lands in the wallet, and in a defeat on the step the clock runs out first. MatchScreen then opens the win or lose dialog, with a Play again button, which pauses the world. A game with a rule that Match does not cover writes its own plugin, as the kick does.

timeLimitSeconds is optional. A match without it plays until its score wins it, and useMatch()’s remainingSeconds reads Infinity. A HUD such as MatchClock then shows the seconds only where Number.isFinite(remainingSeconds) holds.

The example counts each run the player wins in a second plugin of its own, src/runs.ts, whose system runs after the match’s. The game’s playerState keeps that count on the player, and the engine’s own saves keep the player’s character and the coins in the player’s wallet, so a run’s coins reach the lobby:

games/example/src/game.ts (part)
playerState: defineSave({
scopes: ["player"],
version: 1,
schema: z.object({ runsWon: z.int().check(z.nonnegative()) }),
read: ({ player }) => ({ runsWon: readRunsWon(player) }),
restore: ({ writer, player }, saved) =>
setRunsWon(writer, player, saved.runsWon),
}),

playerState declares the game’s own part of the save with defineSave. Its read and restore take the player, since the runs won outlive any character. Its schema checks the part when a save loads, so a save that fails it does not load. The engine’s saves, the character’s place and health, the character’s stats and the player’s wallet, are on from the start, and the game turns one off with saves: { stats: false }. Saving progress says how a save is written, versioned and tested.

The game’s one item, a potion, is registered in src/items.ts. No scene places one yet: it is there for a game that adds a bag or loot. Inventory lists what an item can say.

games/example/src/items.ts (part)
defineItem("potion", {
displayName: "Potion of healing",
maxStack: 10,
use: {
effects: [{ type: "heal", amount: 30 }],
consume: true,
cooldownSeconds: 1,
},
});

The HUD reads the match with useMatch() and draws the seconds left and the coins toward the score that wins, each in a Counter, in a Panel at the top of the screen. A Hud draws in the screen layer, over the canvas. When the match ends, the panel says how:

games/example/src/components/MatchClock.tsx
import {
Counter,
Hud,
Panel,
PanelVariant,
Slot,
Text,
} from "@spawnite/engine";
import { MatchOutcome, MatchState, useMatch } from "@spawnite/engine/matches";
/** The run's match: the seconds left and the coins toward the score that
* wins it, each a Counter, then how it ended. */
export function MatchClock() {
const match = useMatch();
if (!match) return null;
const { remainingSeconds, score, scoreToWin, state, outcome } = match;
// The example's match starts as it mounts, so it never shows waiting.
const ended =
state !== MatchState.Ended
? undefined
: outcome === MatchOutcome.Victory
? `Won with ${Math.ceil(remainingSeconds)} s left`
: `Out of time, ${score} of ${scoreToWin} coins`;
return (
<Hud>
{ended === undefined ? (
<Panel
slot={Slot.Top}
className="flex-row gap-6"
variant={PanelVariant.Glass}
>
<Counter
icon="timer"
label="Seconds left"
value={Math.ceil(remainingSeconds)}
/>
<Counter
icon="coins"
label="Coins"
value={`${score}/${scoreToWin}`}
/>
</Panel>
) : (
<Panel slot={Slot.Top} variant={PanelVariant.Glass}>
<Text>{ended}</Text>
</Panel>
)}
</Hud>
);
}

The wallet’s count is drawn at the game’s level, by Readout in app.tsx, so it reads the same in every scene.

The spawnite commands run the game with no window and report what happened, so you check the game without playing it. The first command that opens the game in a headless page downloads Chromium, once for the machine. Run each one in your game’s folder; spawnite --help lists every command. Each simulate also prints the plugins and the systems of the step after the hash; they are left out here.

  1. Step the run scene in Node for 21 seconds, with no keys down. The player stands still, so the clock runs out:

    Terminal window
    spawnite simulate --scene run --seconds 21 --fields match.state,match.outcome,match.reason
    Stepped 1260 steps.
    Hash 1775395341, stepped in 971 ms.
    {
    "5": {
    "match": {
    "state": "ended",
    "outcome": "defeat",
    "reason": "time"
    }
    }
    }
  2. Step it again with W held, until no coin is left. The player walks forward through the three coins, and the match is won on step 76, about 1.3 s of game time:

    Terminal window
    spawnite simulate --scene run --keys w --until "count('pickup') === 0" --fields wallet,match.state,match.outcome
    The condition held on step 76; it returned true.
    Hash 4028198481, stepped in 244 ms.
    {
    "1": {
    "wallet": {
    "coins": 3
    }
    },
    "5": {
    "match": {
    "state": "ended",
    "outcome": "victory"
    }
    }
    }

    The same command gives the same hash on every run of the same code. The hash also changes with the engine release, so yours may differ from the one shown. A hash that changes after an edit means the edit changed the world the run leaves, which a trait added only for display also does.

  3. Start a playtest: the dev server and a headless Chromium page. It prints the page’s address and the scene’s tree, and the world holds still until a command steps it:

    Terminal window
    spawnite play start
    Playtest running at http://localhost:51135/
    hud:1 Hud
    hud:3 Panel
    scene:lobby lobby
    2 Landscape #2.1
    hud:5 Hud
    hud:7 Panel
    hud:9 Button: Play
    hud:11 Button: Platforms
    8 LookPostProcessing #8.1
    8:_r_d_ AmbientOcclusion
    8:_r_g_ Bloom
    8:_r_j_ Vignette
    5 Robot #5.1
    5:movement Movement
    9 Camera #9
    9:settings Settings

    With --scene run, it opens the lobby, then goes to the run through the devtools, as scenes.go("run") does, and prints the run’s tree instead. It presses no button, so it opens a scene whose button you have not written yet. The playtest’s browser skips the engine’s Play menu, so a game whose camera starts locked shows the game itself; Escape still opens the menu. The camera page says why.

  4. Step the lobby for one second, 60 steps, then take a screenshot of that step. The command prints the path of the PNG it saved, then the line below:

    Terminal window
    spawnite play screenshot --until "steps >= 60"
    The condition held on step 60; it returned true.

    The picture shows the robot on the grid, the Play and Platforms buttons, the wallet’s count at the top right, and the devtools’ spawnite button at the top left.

  5. Stop the playtest, which closes the page and the dev server:

    Terminal window
    spawnite play stop

The Devtools API covers what the playtest calls, and How your agent works on your game puts these commands together into the loop an agent runs.

npm test runs the project’s tests under test/ with Vitest, and npm test test/scenes/Run.test.tsx runs one file. The tests run in Node with no browser. They step the run, the ball and the platforms headless, check that the save restores the runs won and the coins, build the game and hold its size to a budget, and check that src/models.json matches the model files in public/assets/. After you copy a model file in by hand, run npm run models, and commit src/models.json if the project is a git repository, before the tests. The run’s own test is the smallest:

games/example/test/scenes/Run.test.tsx
// @vitest-environment node
import { expect } from "vitest";
import { MatchState, MatchTrait } from "@spawnite/engine/matches";
import { it } from "@spawnite/engine/testing";
import { game } from "../../src/game";
import { Run } from "../../src/scenes/Run";
const { plugins } = game;
it("plays the match as Run opens in a game played alone", async ({
createTestWorld,
scene,
}) => {
const { world } = createTestWorld({ plugins });
await scene(Run, world);
expect(world.queryFirst(MatchTrait)?.get(MatchTrait)?.state).toBe(
MatchState.Playing,
);
});

To play the game yourself, run npm run dev and open the address it prints. Press Play, then walk with WASD and kick with F.

To add a scene, such as an arena, an agent makes the following edits:

  1. Write src/scenes/Arena.tsx. The MCP’s add_scene, or spawnite add scene arena, writes it with a world, a character, a camera and a line of HUD, and a page for it at wiki/scene/arena.md. It prints the two lines step 3 pastes:

    Wrote src/scenes/Arena.tsx
    Wrote wiki/scene/arena.md
    Register it: paste these into src/app/app.tsx:
    import { Arena } from "../scenes/Arena";
    <Scene name="arena" component={Arena} />

    The scaffold is a start, not a copy of the example’s scenes. It spawns a phase machine whose intro lasts three seconds before play, and it mounts the engine’s default character with <CharacterSpawn />. Swap in <Robot /> for the example’s character, and delete the phase machine where the scene has no intro. Its camera and HUD line stand beside the entities, not in <Views>, and that is fine: the engine’s cameras and Hud hold themselves in <Views>, as Logic and views says.

  2. At the top of the scene’s file, keep the export { game } from "../game"; the scaffold writes, as the example’s other scenes have. A room and spawnite simulate load a scene’s file alone, never app.tsx, so the file hands them the game and its save. Add import "../items"; too when the scene names an item.

  3. In src/app/app.tsx, add the import at the top and the <Scene name="arena" component={Arena} /> line inside <Game>, beside the other three. Change nothing else in the file.

  4. Give the player a way in: a Button that calls scenes.go("arena"), as the lobby’s Play button calls scenes.go("run"). To open the game on the new scene instead, set start: "arena" in defineGame. The types do not check a scene’s name: scenes.go("arnea") and start: "arnea" compile, then throw when they run, naming the scenes the <Scene> lines register.

Then check the scene: spawnite simulate --scene arena --seconds 1 mounts it headless, loading src/scenes/Arena.tsx, the scene’s name in PascalCase. spawnite play start --scene arena opens a playtest and goes to the scene the <Scene name="arena"> line registers.

The example plays alone, so the arena plays on the player’s page. A game with a room runs one scene in it, the file that spawnite.room.scene in package.json names. The value is a path from the game’s folder, not a scene’s name: "scene": "./src/scenes/Arena.tsx". Every room of the game runs that one scene.

Put a <Match> in the room’s scene alone. On a page in a room, a <Match> in another scene finds no match the room streams, and throws in development, as Match in a room says. So a room game plays its match in one scene: the arena can take the run’s place as the room’s scene, but cannot play a second match beside it. When it does, take the <Match> out of the run, or take out the run and its Play button.

A room game’s spawnite play start starts its room beside the dev server, and the page joins it. --query adds keys to the page’s address, which Game reads as The page’s address lists. To play the arena as Ada with the WebGPU renderer:

Terminal window
spawnite play start --scene arena --query 'name=Ada&renderer=webgpu'

The example’s tests hold its files to what they do now. npm test runs them, and npm run check type-checks test/ with src/, so a test that no longer matches the game’s code fails the check too. An agent that changes what a test asserts changes the test in the same step:

  • test/app.test.tsx renders the whole app and expects the game named example, a button named Play, the text Coins 0, no open dialog, and the devtools’ Spawnite button. A second case mounts it as outside development, with ?debug in the address, and expects no devtools.
  • test/game.test.ts steps the game’s plugins with no window and expects a won match to count once as a run won. It reads what the step does, not the names of its systems, so a plugin the game adds to src/game.ts passes it.
  • test/scenes/Run.test.tsx expects the match to be playing as the run opens in a game played alone. test/scenes/Lobby.test.tsx expects the lobby’s ground to be the flat 8 m grid with nothing scattered on it. test/scenes/Platforms.test.tsx expects the character to climb onto the last platform on jumps alone.
  • test/harness.test.ts expects the first coin in the wallet within 5 s, the ball to roll away when the character walks into it, and the same seed to give the same hash.
  • test/components/Ball.test.tsx expects the ball to rest until it is pushed, and F to kick it away within reach. Platform.test.tsx expects a platform to hold the character on its top. MatchClock.test.tsx expects the seconds left and the coins, each in a Counter.
  • test/save.test.ts expects playerState to restore the runs won onto the player and the player’s wallet to carry the coins, to refuse a negative run count, and to count a won round once. It also expects the game its room mounts to keep the player’s character, wallet and runs, and nothing a room may not.
  • test/build.test.ts builds the game for production and expects fewer than 24 code chunks, no devtools, one Draco decoder, one glTF loader, and the loaders a first frame does not need kept out of the first download.
  • test/models.test.ts expects src/models.json to match the model files in public/assets/.

A new scene needs no change to these tests. Its own test goes under test/scenes/, as Run.test.tsx does for the run.