# Moments: playable moment links for web games

Moments lets a player share a link to the exact moment they just played. A friend opens the link and plays that same moment in their browser (same position, same enemies, same luck) and tries to beat the score. Then they can send it back.

Moments provides the recording, the share sheet (WhatsApp, X, system share, copy), the hosted link with a rich preview, the "X challenged you" screen, the countdown, the challenge HUD, the result screen and "send it back". The game provides three small functions. Your job is to write them well.

## Workflow

1. **Read the game before changing anything.** Find and write down:
   - the state: every variable that changes during a run (player, enemies, bullets, pipes, coins, score, lives, level, speed, combo, timers, cooldowns, spawn counters);
   - the main loop (requestAnimationFrame, setInterval, setTimeout chain, or an engine loop);
   - the start, game-over and restart flow, including any HTML menus or overlays;
   - the canvas, if there is one.
2. **Add the SDK as the first script on the page**, in `<head>`, before the game's scripts and before any engine library:
   ```html
   <script src="https://playmoments.vercel.app/sdk/v1/moments.js"></script>
   ```
   It must load first. It wraps requestAnimationFrame, timers, Math.random and the clock so it can pause, record and replay the game.
   The game must still work if the script cannot load (offline, blocked by an ad blocker): guard every call, for example `const M = window.Moments;` then `if (M) M.init({...})`, or a do-nothing stand-in object.
3. **Call `Moments.init()` once the game is ready to play**: after assets load and after the game's own initial setup or reset.
4. **Report events**: call `Moments.gameOver()` the moment the player dies or loses. Call `Moments.highlight('Triple combo!')` on genuinely exciting moments (big combos, near misses, boss kills, records), which invites the player to share. In turn-based games, call `Moments.move()` after every completed move.
5. **Run the self-test.** Open the game with `?moments-selftest` in the URL (for example `http://localhost:5173/?moments-selftest`), start a run and play for about 3 seconds (turn-based: make 2 moves). A report appears on screen, is printed to the console as `[moments:selftest] {json}` and is stored in `window.__momentsSelfTest`. Fix every ❌ and re-run until there are none. If you can drive a browser, play and read `window.__momentsSelfTest` yourself; otherwise ask the user to run it and paste the report.
6. **Try the real loop**: tap "Share moment", open the link in another tab, press Play, finish the challenge, check the result and "Send it back". Then check that normal play, game over and restart still work exactly as before.

## Moments.init

```js
Moments.init({
  game: 'Sky Hop',                       // name shown to friends
  getState: () => (mode === 'playing' ? { /* plain JSON */ } : null),
  setState: s => { /* rebuild the game from s and switch to playing */ },
  getScore: () => score,                 // omit if the game has no score
  // canvas: document.querySelector('#game'),  // optional, auto-detected (largest canvas); may also be a function returning a canvas
  // turnBased: true,                    // puzzles and board games; then call Moments.move() after each move
  // clipSeconds: 10,                    // how far back a shared moment starts (3 to 20, default 10)
  // clipMoves: 3,                       // turn-based: how many moves back (default 3)
  // ui: { shareButton: 'top-right',     // 'top-left' | 'bottom-right' | 'bottom-left' | false
  //       hud: 'top' },                 // 'bottom' if the challenge HUD would cover your score
});
```

## Writing getState and setState (the part that matters)

**getState()** returns everything needed to continue the run from this instant.
- Return plain JSON only: objects, arrays, numbers, strings, booleans, null. No class instances, page elements, images, Sets or Maps, functions, or engine objects (Three.js meshes, Phaser sprites, physics bodies). Copy the data out: `{ x: p.x, y: p.y, vy: p.vy }`.
- Return `null` whenever the player is not in active play: title screen, menus, pause, game over. Moments only records during play.
- Include everything that changes what happens next: positions, velocities, entity lists, score, lives, level, speed or difficulty, combo counters, cooldowns, spawn timers, frame or tick counters used for spawning, and the state of any random generator the game keeps itself.
- Store time as time remaining or time elapsed, never as absolute timestamps. Bad: `nextSpawnAt: performance.now() + 900`. Good: `spawnIn: 0.9`. The friend's clock is different from yours, so absolute timestamps break the moment on their device.
- Leave out pure decoration that cannot change the outcome (particles, screen shake, background parallax), unless it is cheap to include.
- Keep it under about 100 KB.

**setState(s)** turns the game into exactly that moment.
- Replace, never merge. Rebuild every list from `s` (`enemies = s.enemies.map(e => ({ ...e }))`) and reset anything that is not in `s` to its normal starting value.
- Recreate engine objects for restored entities and remove the old ones (meshes from the scene, sprites from groups, bodies from the physics world).
- Put the game into active play: set the mode or phase to playing, hide start and game-over screens (including HTML overlays), update HUD text such as the score display.
- Don't start a second game loop. The existing loop keeps running and simply sees the new data. Re-arming your own tick timer is fine (clear the old timeout, set a new one with the saved remaining time), and if setState calls a start function that requests the same loop function again, Moments drops the duplicate. A loop started with a new function each time, like `requestAnimationFrame(() => loop())`, would run twice.
- Reset input state (held keys, active touches, pending jump) so the restored moment starts clean.
- If the game measures its frame time itself (`dt = now - lastTime`), set `lastTime = performance.now()` in setState so the first frame after a restore does not jump.
- If positions depend on the screen size (for example measured up from a ground line at the bottom of the window), store them in a size-independent unit, or save the size you used and rescale in setState. The friend's screen is rarely the same as yours.

**getScore()** returns the live score as a number. With a score, challenges read "Beat +40 in 10s". Without one they read "Last longer than 7.5s".

**Frame rate**: for challenges that are fair across 60 Hz and 120 Hz screens, step the game with a fixed timestep (accumulate dt and update in 1/60 s steps). Games with a variable timestep work, but a faster screen plays the same moment out slightly differently.

**Randomness** is handled for you: Math.random is replaced by a seeded generator whose position is saved in every moment, so friends get the same luck. If the game keeps its own seeded generator, put its seed and position in getState. If visual effects draw many random numbers every frame (particles), use `Moments.random()` for gameplay randomness (spawns, drops, enemy choices) so that a faster screen cannot change the luck.

## Engine notes

- **Plain canvas and JavaScript objects**: often the cleanest getState is an explicit object literal built from the game's variables. `JSON.parse(JSON.stringify(x))` is a fine way to copy nested plain data.
- **Three.js**: save data, not meshes: `{ lane, z, speed, obstacles: [{ lane, z, type }] }`. In setState, remove existing obstacle meshes from the scene, create meshes for the restored list, and move the player mesh. No need for preserveDrawingBuffer: the SDK captures right after each frame.
- **Phaser**: save sprite data (x, y, velocity, active, frame) and scene variables. In setState, reposition pooled sprites or destroy and recreate them, set body velocities with `body.setVelocity`, and replace `this.time` events with new ones using the saved remaining delays.
- **Matter.js and other physics engines**: save each body's position, angle, velocity and angular velocity. Restore them with `Body.setPosition`, `setAngle`, `setVelocity` and `setAngularVelocity`. Use a fixed timestep if the self-test reports that replays drift.
- **Games driven by setInterval or setTimeout**: supported. Keep counters such as "ticks until the next food" in the state.
- **Games without a canvas (DOM games)**: supported. Clips and preview images need a picture, so keep a small offscreen canvas, redraw a simple version of the board on it whenever the game renders, and pass `canvas: () => thatCanvas`. Without one, link previews show text only.

## Reading the self-test

| Check | Meaning when it fails | Usual fix |
| --- | --- | --- |
| State is plain JSON | Something in getState is not plain data | Copy fields out of class instances and engine objects |
| setState restores the state exactly | getState after setState gives different data | setState is missing fields or merging lists |
| Can jump back to an earlier moment | Restoring an older state leaves leftovers | Replace lists and reset fields that are not saved |
| Same moment plays out identically | Two replays of the same second differ | A spawn timer, counter, cooldown, second random generator or absolute timestamp is missing from the state |
| setState starts an extra game loop | More frame callbacks after a restore | Don't start a new loop in setState, especially with a fresh arrow function |
| setState then getState returns null | The restored game is not in active play | setState must switch the game to playing and hide menus |
| Captured frames look blank | WebGL canvas read at the wrong time | Draw from requestAnimationFrame, or set preserveDrawingBuffer: true |

The replay check runs one second with nobody playing. If the player loses during it (a bird with nobody flapping, a snake heading for a wall) that is fine: the check only needs both replays to go the same way. Don't add special cases for the self-test, and don't use `Moments._debug`; it is internal and will change.

Because the replay runs your real game code, anything the game does on death or on a new record also happens during it. If the game saves a best score, sends analytics or unlocks achievements at the instant something happens, skip that while `Moments.replaying` is true (or do it later, for example when the game-over screen appears).

## API

- `Moments.init(options)`: see above.
- `Moments.gameOver()`: the player died or lost. Ends a challenge; outside a challenge it offers "Share the moment that got you?".
- `Moments.highlight(label)`: something exciting just happened; offers to share (at most every 15 seconds).
- `Moments.move()`: turn-based games, after each completed move.
- `Moments.share()`: open the share sheet from your own button, for example on the game-over screen.
- `Moments.random()`: seeded random number in [0, 1) for gameplay-only randomness.
- `Moments.selfTest()`: runs the self-test and returns a Promise of the report.
- `Moments.on(event, fn)`: events `challengeload`, `challengestart`, `challengeend`, `challengeexit` (the friend chose "Keep playing"), `share`, `gameover`.
- `Moments.challenge`: null, or the active challenge `{ id, from, goal, phase, mine, result }`.
- `Moments.replaying`: true while the self-test is replaying the game; skip saving records or sending analytics then.

**During a challenge, let Moments own the screen.** When the friend dies in a challenge, Moments shows the result card, so skip your own game-over screen while `Moments.challenge` is set, and show it on `challengeexit` if the run had ended:
```js
function onDeath() {
  Moments.gameOver();
  if (!Moments.challenge) showGameOverScreen();
}
Moments.on('challengeexit', () => { if (isGameOver) showGameOverScreen(); });
```
Also skip saving high scores or progress while `Moments.challenge` is set, so a friend's attempt at someone else's moment does not overwrite their own records.
- Script attributes (not recommended): `data-patch-random="false"`, `data-patch-time="false"`, `data-api="https://…"`.

## What players see

- During play, a small "Share moment" button (position configurable), a share prompt on highlights and after game over.
- The share sheet: an animated clip of the last seconds, the friend's goal, name field, WhatsApp, X, system share and copy link.
- The friend gets a link preview with a picture of the moment, then a page with the clip and a Play button. The game opens at that moment: "Vamsi challenged you", a 3-2-1 countdown, a live HUD ("Beat +40 · You +12 · 4.2s"), then the result with "Send it back", "Try again" and "Keep playing".

## Before you finish

- [ ] The SDK script is the first script on the page.
- [ ] The self-test shows no ❌.
- [ ] You shared a moment, opened the link and the restored moment looked and played right.
- [ ] Start, game over, restart and normal play behave exactly as before.
- [ ] Tell the user that links point to wherever the game is hosted: localhost links only work on their own machine, so deploy the game to a public URL before sharing.

---
Use this guide with any coding agent: "Add Moments to my game. Follow https://playmoments.vercel.app/llms.txt".
Claude Code skill: https://playmoments.vercel.app/skill/SKILL.md
