# Autoplay

Buddy plays a work for a few seconds for a visitor who has not touched it yet, from a small policy in the work. Written to
Playspace's publishing agent, which adds one at publish; a work of yours may make the call itself. "The manifest" is `playspace.json`'s `controls`.

## 0.6 Autoplay: Buddy plays first

A visitor who opens a work and does nothing for 3 seconds sees Buddy play it: a few seconds of calm play with the
Playspace set, under a label of the player's ("Buddy is playing · touch to play"), until the visitor's first touch,
key, click or wheel takes over in that same input. It stops by itself after 30 seconds. It is a preview of what the
work is and of what each control does, never a show and never a speedrun. You write it once, in the build, as a small
policy; our runtime plays it beside the work at no cost per view. Nothing Buddy does is kept as a person's: while he
plays the SDK drops the work's scores, saves, stats, outcomes and moments (the work's own storage is yours to put back,
below).

For every work, decide one of two:

- **A policy**: the call below, in the build, and the
  manifest's block `"autoplay": { "mode": "policy", "handover": "fresh" }` (or `"continue"`).
- **No autoplay**: no call, and the manifest's block
  `"autoplay": { "mode": "off" }`. A declined work is a right answer where the list under "When to decline" says so:
  it is never a failure, and the work publishes and plays as always.

### The call

`playspace.autoplay(policy)`, once (a second call is ignored), where the work's state is in scope: beside the code
that makes the game (the Svelte component, the scene's setup, the adapter where it reaches the work's objects). It
returns true when the policy is kept. The policy:

    playspace.autoplay({
      handover: "fresh",                                    // or "continue": below
      map: { move: ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], a: "Enter" },  // only where nothing else names a key
      start: [["tapText", "Play"], ["wait", 800]],          // once, past a title
      every: 150, rule(c, s) { /* each `every` ms: read the work's own variables, press the set */ },
      // or, in place of `rule`: loop: [["stick", 0, -1, 900], ["wait", 600]],   (for ever)
      reset() { /* the work's own way back to its start */ },
    });

- **Steps** (`start`, `loop`): `["stick", x, y, ms]` holds the stick at x, y (-1..1, up negative) for `ms`, then the
  next step (`["stick", 0, 0, ms]` lets it go); `["a", ms]` and `["b", ms]` press A or B for `ms`; `["tap", x, y]` and
  `["drag", x0, y0, x1, y1, ms]` on the work (x and y 0..1 of the frame); `["tapText", "Play"]` clicks the work's own
  control whose text is exactly those words (case aside); `["wait", ms]`. `start` runs once; then `rule`, or `loop`
  for ever. A step's `ms` is by the clock, not by frames or ticks: a 2 s drag lasts about 2 s on a slow phone too.
- **A rule** (`rule(c, s)`): called every `every` ms (50 to 5,000; 250 when absent), after the last call settles (it
  may return a promise). `s` is a scratch object of its own between calls. `c` is the controller.
- **The controller, the set and nothing else**: `c.stick(x, y)` (held until the next `stick`; past 0.4 on an axis is
  that direction's key down), `c.a(on)` and `c.b(on)` (held), `c.press("a" | "b", ms)` (90 ms when absent),
  `c.tap(x, y)`, `c.drag(x0, y0, x1, y1, ms)`, `c.tapText(words)` (true where it found the control), `c.reset()`,
  `c.now()` (ms since Buddy began). No key by name, no Esc, no menu, no pointer lock: what he cannot do with the set
  he does not do.

### The keys he presses

The stick, A and B press the work's own keys, each from the first of these that names one:

1. the build's manifest: `move.keys` in its order up, down, left, right; `a.key`; `b.key`;
2. the work's own `playspace.layout()` keys (`forward`, `back`, `left`, `right`, `action`, `secondary`);
3. the policy's `map`: `move` in the same order up, down, left, right, and `a`, `b`.

A control with no key from any of the three presses nothing. `map` never replaces a key the manifest or the layout
names; it is for a work whose manifest leaves a key out, as Svelte Snake's does (its own swipe is the phone's, so its
arrows are `extra`, and its policy's `map` names them). A manifest's `"click"` or `"click2"` on A or B is the mouse's,
not a key: for that, `tap` or `drag` on the work. A tap or a drag goes to the work's element under the point, never to
our controls; Buddy never presses through our touch layer.

### Read the work's own state

You write inside the build, so a rule reads the work's own variables: the snake's head and the food, the car's
position on the track's checkpoints, the level's state. Never the pixels (a canvas read many times a second costs a
phone its battery, and a WebGL canvas cannot be read at all). Keep a rule cheap: a few variables, one decision, then
the set. Where the state is not reachable (a minified bundle with no globals), write steps, or decline.

### Fresh or continue, and the reset

- **`"fresh"`** for a work with a score, a clock, lives or a run: the visitor's first touch is spent on `reset()` and
  their game starts from the beginning, as an arcade's coin starts a fresh game. Buddy's score is not theirs.
- **`"continue"`** for a toy, a walk, a viewer, a painter: the first touch passes through as the visitor's first input,
  and they carry on from where Buddy is.

`reset()` is the work's own way back to its start: its restart function, its new game, its level reload. Never a page
reload (the visitor sees a flash and loses the load). **Put back what Buddy stored in the work's own storage**: a best
score, a save, an unlocked level. Read that storage once, where you register the policy (before Buddy plays), and
write it back in `reset()`; in the work's memory too, where the work keeps a copy (Snake kept "best: 18", Buddy's, as
the visitor's in the first trial). An error in `reset()` is caught; the visitor plays on.

### Past a title, and the pace

- **A title or a "click to start"**: `start` steps, `["tapText", "<the work's own words>"]` then a wait for the scene.
  Under a version 3 manifest Buddy may play before the work calls `playspace.start()`: his `start` steps are what pass
  the title. Sound stays off until the visitor's own touch (the browser's rule); a work that needs a gesture to make
  sound plays silent for Buddy, and that is fine.
- **The pace: slow and calm.** Hold the stick for most of a second, wait between moves, turn the view slowly. In the
  first ten seconds show each control the work uses once (move, then A, then a look), so the visitor learns what the
  set does on this work by watching. A careful player, not a fast one. A rule that steers an arcade game at its own
  speed is fine; a rule that presses ten keys a second is not.
- **Never stand still.** The check fails a picture that does not change for 5 seconds while he plays. After a game
  over, press the work's own way on (a key the set reaches, `tapText` on its "Play again"). A rule stuck against a
  wall should turn, or call `c.reset()`.

### What the check watches

After the check's own play, where the build registered a policy and the manifest does not say `"mode": "off"`, the
check loads the build afresh on each device (the phone first, then the computer), with no input of its own, waits for
Buddy, and watches his 30 seconds: a picture every 0.4 s (our controls hidden: only the work's picture counts), the
keys he pressed and his own reports. It fails him with one of these, in these words:

- `he never started` (no policy registered in time, or it never began: within 30 s of the work being armed)
- `his plan stopped with an error` (the rule threw; Buddy stops and the work is left as it is)
- `he stopped by himself after N s` (he ended before his 30 s)
- `he left a key held down (KeyW)` (a key still down at the end)
- `the picture never changed while he played`
- `the picture stood still for N s while he played` (5 s or more)

A picture reading that fails is read once more before it counts. The row's verdict is `pass`, `fail` with the device
and the reason (`on a phone, the picture stood still for 7 s while he played, both times he was watched`), or `unread`
(no time left to watch him again). A
policy that does not pass is simply never played for a visitor: the work publishes as always. A reviewing model also looks at pictures of his play: calm, competent, showing
the controls, so that someone watching for ten seconds understands what the work is and that they can take over.

### When to decline

- **Music and rhythm works** (an instrument, a beat game): play without the sound means nothing, and the sound waits
  for a touch.
- **A puzzle past its first move or two**: show the first move, then nothing more; where even that spoils it, decline.
- **A skill the policy does not have**: a driving game on a real track, a platformer's jumps, a shooter's aim, unless
  the rule reads what it needs from the game's own data (the track's checkpoints, the platforms' positions) and the
  check passes it. A blind policy that crashes into the first bend looks broken, and a broken preview is worse than
  none.
- **A work that already moves by itself** (a fluid, a shader, a scene that animates, the work's own attract mode) and
  needs no input to be alive.
- **A work whose play is typing, or a form**: there is nothing for the set to show.

### Two worked policies

- **Svelte Snake** (an arcade rule on the game's own state; `"fresh"`). In `App.svelte`, after `const game = new
  Game(...)`: its manifest leaves the arrows to the work's own swipe (`extra`), so `map` names them; Enter is the
  work's own "new game" after a game over; the best score is put back.

      const storage = getAppContext('storageService'), best = storage.highScore;   // read before Buddy plays
      const DIRS = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
      playspace.autoplay({
        handover: "fresh",
        map: { move: ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"], a: "Enter" },
        every: 150,
        rule(c) {
          if (game.currentGameState.gameOver) return c.press("a", 100);        // the work's own new game
          const N = game.config.gridSize, h = game.snake.head, f = game.food.position, body = game.snake.parts;
          const free = (x, y) => x >= 0 && y >= 0 && x < N && y < N && !body.some((p) => p.x === x && p.y === y);
          let pick = null, far = Infinity;
          for (const [name, [dx, dy]] of Object.entries(DIRS)) {
            if (!free(h.x + dx, h.y + dy)) continue;
            const d = Math.abs(f.x - h.x - dx) + Math.abs(f.y - h.y - dy);
            if (d < far) { far = d; pick = name; }
          }
          if (pick && pick !== game.snake.direction) { c.stick(...DIRS[pick]); c.stick(0, 0); }   // one press of its arrow
        },
        reset() {
          game.restart();
          storage.highScore = best;                                            // the work's own storage, as it was
          gameState.update((s) => ({ ...s, highScore: best }));                // and its copy in memory
        },
      });

  Manifest: `"autoplay": { "mode": "policy", "handover": "fresh" }`.

- **Musewalk** (a walk's steps; `"continue"`). Past its title by its own words, then a slow look and a step, again
  and again; its manifest names W A S D, so no `map`; nothing to put back.

      playspace.autoplay({
        handover: "continue",
        start: [["tapText", "Enter the Museum"], ["wait", 3500]],
        loop: [["drag", 0.7, 0.45, 0.5, 0.45, 2200], ["wait", 1200], ["stick", 0, -1, 900], ["stick", 0, 0, 1000],
               ["drag", 0.4, 0.45, 0.66, 0.46, 2600], ["wait", 1200], ["stick", 0, 1, 800], ["stick", 0, 0, 900]],
      });

  Manifest: `"autoplay": { "mode": "policy", "handover": "continue" }`. A declined one, for contrast: Qwertone
  `"autoplay": { "mode": "off" }`.
