js-game-zero 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +138 -2
  3. package/dist/active-service.d.ts +21 -0
  4. package/dist/actor.d.ts +182 -0
  5. package/dist/animation.d.ts +61 -0
  6. package/dist/assets.d.ts +148 -0
  7. package/dist/audio.d.ts +150 -0
  8. package/dist/browser-asset-backends.d.ts +8 -0
  9. package/dist/browser.d.ts +10 -0
  10. package/dist/chunk-brk0rjcy.js +7846 -0
  11. package/dist/clock.d.ts +29 -0
  12. package/dist/color.d.ts +15 -0
  13. package/dist/events.d.ts +145 -0
  14. package/dist/friendly-names.d.ts +43 -0
  15. package/dist/geometry.d.ts +125 -0
  16. package/dist/helpers.d.ts +28 -0
  17. package/dist/host.d.ts +58 -0
  18. package/dist/host.js +435 -0
  19. package/dist/index.d.ts +340 -0
  20. package/dist/index.js +258 -0
  21. package/dist/input.d.ts +200 -0
  22. package/dist/inspection.d.ts +58 -0
  23. package/dist/jgz.js +8419 -0
  24. package/dist/node.d.ts +14 -0
  25. package/dist/node.js +145 -0
  26. package/dist/pixel-density.d.ts +23 -0
  27. package/dist/random.d.ts +31 -0
  28. package/dist/reference/actor.md +197 -0
  29. package/dist/reference/audio.md +128 -0
  30. package/dist/reference/clock.md +150 -0
  31. package/dist/reference/helpers.md +46 -0
  32. package/dist/reference/hooks.md +379 -0
  33. package/dist/reference/index.d.ts +2 -0
  34. package/dist/reference/index.js +39 -0
  35. package/dist/reference/loaders.md +164 -0
  36. package/dist/reference/rect.md +129 -0
  37. package/dist/reference/runtime.md +478 -0
  38. package/dist/reference/screen.md +313 -0
  39. package/dist/reference/storage.md +90 -0
  40. package/dist/rendering.d.ts +188 -0
  41. package/dist/runtime-contracts.d.ts +117 -0
  42. package/dist/runtime-diagnostics.d.ts +37 -0
  43. package/dist/runtime-persistence.d.ts +32 -0
  44. package/dist/runtime-source.d.ts +82 -0
  45. package/dist/runtime.d.ts +81 -0
  46. package/dist/source-scan.d.ts +49 -0
  47. package/dist/storage-path.d.ts +3 -0
  48. package/dist/storage.d.ts +88 -0
  49. package/dist/tone.d.ts +81 -0
  50. package/dist/touch-controls.d.ts +24 -0
  51. package/dist/touch-pointer.d.ts +11 -0
  52. package/dist/util.d.ts +62 -0
  53. package/package.json +69 -4
@@ -0,0 +1,39 @@
1
+ /*!
2
+ * js-game-zero 0.3.0
3
+ * https://github.com/Leaf-Learning/js-game-zero
4
+ *
5
+ * MIT License
6
+ *
7
+ * Copyright (c) 2026 Taha Rafiq
8
+ * Copyright (c) 2001 Robert Penner (easing equations)
9
+ *
10
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ * of this software and associated documentation files (the "Software"), to deal
12
+ * in the Software without restriction, including without limitation the rights
13
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ * copies of the Software, and to permit persons to whom the Software is
15
+ * furnished to do so, subject to the following conditions:
16
+ *
17
+ * The above copyright notice and this permission notice shall be included in all
18
+ * copies or substantial portions of the Software.
19
+ *
20
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ * SOFTWARE.
27
+ */
28
+ export const reference = Object.freeze({
29
+ "actor.md": "# Actor\n\n`Actor` bundles an image, a position, and a hitbox rectangle into one object\nyou can move, rotate, fade, and collide-test. It's the class you'll use for\nplayers, enemies, bullets — anything that moves around the screen.\n\n```ts\nnew Actor(image: string, pos?: [number, number] | ActorOptions, options?: ActorOptions): Actor\n```\n\n```js\nlet player = new Actor(\"player.svg\", { center: [160, 90] });\n\nfunction draw() {\n screen.fill(\"#111827\");\n player.draw();\n}\n```\n\n`image` is an asset name resolved under `images/` (see\n[`docs/reference/loaders.md`](loaders.md)). In `jgz`, the sandbox, and a page\nthat decodes its images first with\n[`loadImages`](loaders.md#assets-without-a-server), the image is ready\nbefore your code runs, so `player.width` and an edge position like\n`midBottom` are right from the first line. Anywhere else, loading starts\nwhen the Actor is made: until it finishes, the Actor has no size and `draw()`\nis a no-op, and the runtime holds the first frame until images touched while\nyour script starts up have loaded. `player.ready()` returns a promise for\nthe image; the top level of a zero-boilerplate game can't `await`, so use\n`player.ready().then(() => …)` there.\n\n## Positioning\n\nGive **at most one** position source — either the second constructor\nargument as a `[x, y]` point, or exactly one of these option keys:\n`pos`, `topLeft`, `topRight`, `bottomLeft`, `bottomRight`, `midTop`,\n`midLeft`, `midRight`, `midBottom`, `center`. Passing more than one throws a\n`TypeError`. With no position at all, the actor starts at `topLeft: [0, 0]`.\n\n```js\nnew Actor(\"player.svg\", [100, 50]); // shorthand for { pos: [100, 50] }\nnew Actor(\"player.svg\", { midBottom: [160, 180] }); // stands on the floor at y=180\n```\n\n`anchor` controls which point of the image maps to the position — it\ndefaults to `[\"center\", \"center\"]`, so by default `player.x`/`player.y` (and\n`pos`) refer to the image's center, matching pgzero. Each axis accepts\n`\"left\"`/`\"center\"`/`\"right\"` (horizontal) or `\"top\"`/`\"center\"`/`\"bottom\"`\n(vertical), or a literal pixel offset number.\n\n```js\nnew Actor(\"player.svg\", { topLeft: [0, 0], anchor: [\"left\", \"top\"] });\n```\n\n## Properties\n\n| Property | Type | Notes |\n| ---------------------------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------------------------------------------------- |\n| `image` | `string` | Reassigning starts loading the new image. |\n| `pos`, `x`, `y` | point / number | The anchor point's position. |\n| `angle` | `number` | Degrees, counterclockwise, around the anchor. |\n| `opacity` | `number` | `0`–`1`; out-of-range values are clamped, not rejected. |\n| `anchor` | `[h, v]` | See above. |\n| `scale` | `number` | Drawn size as a multiple of the image's native size; default `1`. |\n| `width`, `height` | `number` | The current (possibly rotated) bounding box size. Setting one resizes the sprite to that size, keeping its proportions. |\n| `topLeft`, `topRight`, `bottomLeft`, `bottomRight`, `midTop`, `midLeft`, `midRight`, `midBottom`, `center` | point | Read or move the actor by any edge/corner of its bounding box. |\n| `left`, `top`, `right`, `bottom` | `number` | Same idea, one axis at a time. |\n\nSetting `angle` rotates the sprite around its anchor and changes the\naxis-aligned bounding box returned by `rect()`/`width`/`height` — useful when\nyou collide-test a rotated actor, since the hitbox grows to cover the\nrotated silhouette. The edge and corner properties read and move that same\nbox, so `ship.left = 0` puts a rotated ship's leftmost point at the left of\nthe screen.\n\n```js\nfunction update(dt) {\n if (keyboard.right) player.x += 120 * dt;\n player.angle += 90 * dt; // spin\n}\n```\n\n## Sizing\n\nSprites draw at their native pixel size by default. To fit a picture to\nyour game, give it a `scale`, or a `width` or `height` (at most one of the\nthree; the other axis follows so the picture keeps its proportions):\n\n```js\nlet cow = new Actor(\"cow.png\", { midBottom: [240, 620], width: 80 }); // 80px wide\nlet car = new Actor(\"car.png\", { scale: 3 }); // three times its native size\ncow.height = 60; // resize later; the midBottom stays on the floor\n```\n\nThe hitbox, `rect()`, and every edge/corner property follow the drawn size,\nand the position you gave (a `midBottom` on the floor, a `center`) stays\nput when the size changes. A size set before the image has loaded is\napplied as soon as it arrives. `inflateIp` still grows only the hitbox,\nnever the picture.\n\n## Methods\n\n- `rect(): Rect` — the actor's current bounding rectangle (see\n [`docs/reference/rect.md`](rect.md)); useful for custom drawing or manual\n collision math.\n- `draw(screen?)` — draws the actor at its current position, angle, and\n opacity. Normally called with no arguments inside `draw()`.\n- `ready(): Promise<SurfaceLike>` — resolves once the current image has\n loaded.\n- `unloadImage()` — releases the cached image (advanced; rarely needed).\n- `angleTo(target)` / `distanceTo(target)` — `target` is another `Actor`\n or a `[x, y]` point. `angleTo` returns degrees, `distanceTo` returns\n pixels.\n- `move(x, y)` / `moveIp(x, y)` — like `Rect.move`/`moveIp`; `move` returns\n a new `Rect`, `moveIp` moves the actor itself.\n- `inflate(x, y)` / `inflateIp(x, y)` — grow/shrink the hitbox around its\n center; the picture keeps its size and place.\n- `touches(target)` — `true` when the actor overlaps `target`, which can be\n another `Actor`, a `Rect`, a `[left, top, width, height]` tuple, or an\n `[x, y]` point such as a click position.\n- `collidePoint(point)`, `collideRect(other)`, `collideList(others)`,\n `collideListAll(others)`, `contains(other)` — Pygame Zero's collision\n tests, delegating to the actor's `rect()`. `other` can be a `Rect`, a\n plain `[left, top, width, height]` tuple, or another `Actor`.\n- `clampIp(area)` — moves the actor (without resizing it) so its bounding\n box fits inside `area`. `player.clampIp(screen.bounds())` keeps the\n player on screen.\n- `clamp(other)`, `clip(other)`, `union(other)`, `unionAll(others)`,\n `fit(other)` — geometry helpers, same semantics as the matching `Rect`\n methods, again accepting `Actor`s directly. They return a new `Rect` and\n leave the actor where it is.\n\n```js\nfunction update(dt) {\n if (keyboard.right) player.x += 120 * dt;\n player.clampIp(screen.bounds()); // stop at the edges of the screen\n}\n\nfunction onMouseDown(pos) {\n if (player.touches(pos)) console.log(\"clicked the player\");\n}\n\nif (player.touches(enemy)) loseLife();\n```\n\n## Animating an Actor\n\n`Actor` is a plain object as far as `animate()` is concerned — any numeric\nproperty (`x`, `y`, `angle`, `opacity`, ...) can be animated:\n\n```js\nanimate(player, { x: 300, duration: 0.6, tween: \"bounceEnd\" });\n```\n\nSee [`docs/reference/clock.md`](clock.md#animation) for the full tween list.\n\n## Flip-book animation: `images` and `fps`\n\nGive an actor a list of pictures and it flips through them by itself, like a\nflip book — for walking legs, spinning coins, or explosions:\n\n```js\nlet coin = new Actor(\"coin_0\", {\n center: [200, 120],\n images: [\"coin_0\", \"coin_1\", \"coin_2\", \"coin_3\"],\n fps: 8, // pictures per second\n});\n\nfunction draw() {\n coin.draw();\n}\n```\n\n| Property | Meaning |\n| ---------- | ------------------------------------------------------------------------------------- |\n| `images` | The pictures to show, in order. Setting it starts again from the first; `null` stops. |\n| `fps` | Pictures per second (default `10`). Changing it keeps the current picture. |\n| `loop` | Start over after the last picture (default `true`). `false` stops on the last. |\n| `frame` | Which picture is showing: `0` for the first. |\n| `finished` | `true` once a `loop: false` animation has shown its last picture. |\n\nThe pictures change on the game's own clock, so they pause when the game\ndoes and keep the same speed at any frame rate. All of them start loading\nas soon as you set `images`. For a one-shot effect, remove the actor once\nit's `finished`:\n\n```js\nexplosions.push(\n new Actor(\"boom_0\", {\n center: pos,\n images: [\"boom_0\", \"boom_1\", \"boom_2\"],\n fps: 16,\n loop: false,\n }),\n);\nexplosions = explosions.filter((explosion) => !explosion.finished);\n```\n",
30
+ "audio.md": "# Sounds, Music, And Tone\n\nBrowsers block audio from playing until the page has seen a user gesture\n(a click or key press). Every audio API below works fine technically before\nthat gesture, but nothing will actually be _audible_ until the player has\ninteracted with the page at least once — trigger your first sound from an\n`onMouseDown` or `onKeyDown` handler, not from top-level code or the\nfirst `draw()` frame.\n\n## Sound effects: `sounds`\n\n`sounds.<name>` resolves an asset under `sounds/` (see\n[`docs/reference/loaders.md`](loaders.md)) the first time you touch it.\n\n```js\nfunction onMouseDown() {\n sounds.tap.play();\n}\n```\n\n### `.play(loops = 0)`\n\nPlays the sound. `loops` follows pygame's convention: it counts the\n_extra_ plays after the first. `0` (the default) plays it once, `2` plays it\nthree times in total, and `-1` loops forever until `.stop()` is called.\n\nCalling `.play()` again while a previous playback is still going **does not\ncut it off** — sounds overlap, just like pygame's channel mixing, so rapid\nrepeated triggers (e.g. a machine-gun sound effect) layer instead of\nstuttering.\n\n### `.loop()`\n\nPlays the sound over and over until `.stop()` — the same as `.play(-1)`.\nHandy for engine hums and background ambience:\n\n```js\nsounds.engine.loop();\n// later\nsounds.engine.stop();\n```\n\n### `.stop()`\n\nStops every currently-overlapping playback of this sound.\n\n### `.getLength()`\n\nDuration in seconds (`0` if not yet known).\n\n### `.setVolume(volume)` / `.getVolume()`\n\nPer-sound volume, `0`–`1`.\n\n## Music: `music`\n\nUnlike `sounds`, `music` plays **one track at a time** — starting a new\ntrack always stops whatever was playing.\n\n```js\nmusic.play(\"theme.ogg\"); // loops forever\n```\n\n| Method | Behavior |\n| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |\n| `music.play(name)` | Stops the current track, plays `name` on a loop. |\n| `music.playOnce(name)` | Stops the current track, plays `name` once. |\n| `music.queue(name)` | Appends `name` to the queue; starts immediately (as a one-shot) if nothing is currently playing. Queued tracks play in order, each once. |\n| `music.stop()` | Stops playback and clears the queue. |\n| `music.pause()` / `music.unpause()` | Pause and resume without losing position. |\n| `music.rewind()` | Restarts the current track from the beginning without stopping it. |\n| `music.fadeOut(seconds)` | Fades the volume to zero over `seconds`, then stops. `0` stops immediately. |\n| `music.setVolume(volume)` / `music.getVolume()` | `0`–`1`. |\n| `music.position` | Seconds into the current track (`0` if nothing is loaded). Set it to jump: `music.position = 30`. |\n| `music.getPos()` | **Milliseconds** the current track has been playing, or `-1` if nothing is loaded (Pygame's unit). |\n| `music.setPos(seconds)` | Seeks the current track to a position, in **seconds**. To save and restore a spot, use `music.position` for both. |\n| `music.isPlaying()` | `true` if a track is currently playing and not paused. |\n\n`onMusicEnd()` (or a callback given to `music.setOnMusicEnd(callback)`)\nfires once the queue is exhausted and nothing is left to play.\n\n## Generated tones: `tone`\n\n`tone` synthesizes a short beep with the Web Audio API — no sound asset file\nneeded, useful for quick feedback sounds (menu blips, jumps, coin pickups).\n\n```js\nfunction onMouseDown() {\n tone.play(\"A4\", 0.2);\n}\n```\n\n### `tone.play(noteOrFrequency, duration = 1, options?)`\n\n- `noteOrFrequency` — either a note name like `\"A4\"`, `\"C#5\"`, or `\"Bb3\"`\n (letter, optional `#`/`b`, octave number, using standard scientific pitch\n notation with A4 = 440Hz), or a positive number of Hz.\n- `duration` — seconds, **must be greater than `0` and at most `4`**; longer\n values throw a `RangeError`. Generated tones are meant for short blips,\n not background music — use `music` for that.\n- `options.waveform` — `\"sine\"` (default), `\"square\"`, `\"sawtooth\"`,\n `\"triangle\"`, or the pgzero-style short aliases `\"sin\"` (→ `\"sine\"`) and\n `\"saw\"` (→ `\"sawtooth\"`).\n- `options.volume` — `0`–`1`, defaults to `0.8` (matching pgzero's `tone`\n module default, which is louder than most other defaults in this API).\n\nReturns a `Promise` that resolves once the tone has been scheduled.\n\n### `tone.create(noteOrFrequency, duration = 1, options?)`\n\nBuilds a reusable tone spec without playing it yet — call `.play(options?)`\non the result whenever you want to trigger it, optionally overriding\n`waveform`/`volume` for that one playback.\n\n```js\nconst jumpTone = tone.create(\"E5\", 0.12, { waveform: \"square\" });\n\nfunction onKeyDown(key) {\n if (key === keys.SPACE) jumpTone.play();\n}\n```\n\n### `tone.isUnlocked()`\n\nReturns whether the browser has granted audio playback yet — it flips to\n`true` the first time a sound or tone actually plays after a user gesture.\nThis unlock state is shared across `sounds` and `tone`, so a single tap\nun-gates both.\n",
31
+ "clock.md": "# Clock And Animation\n\n## `clock`\n\n`clock` schedules callbacks against the game's own timeline, which only\nadvances while your game is running (driven by the frame loop's `dt`, not by\nwall-clock time) — so a scheduled callback never fires while the tab is\nbackgrounded and the game is effectively paused.\n\n### `clock.schedule(callback, delay)`\n\nCalls `callback` once, `delay` seconds from now.\n\n```js\nclock.schedule(spawnEnemy, 2); // spawn one enemy, 2 seconds from now\n```\n\nA callback scheduled by another scheduled callback waits for the next tick,\neven with a delay of `0`, so one that schedules itself again with\n`clock.schedule(loop, 0)` runs once a frame.\n\n### `clock.scheduleInterval(callback, interval)`\n\nCalls `callback` repeatedly, every `interval` seconds, until unscheduled.\n`interval` must be greater than `0`.\n\n```js\nclock.scheduleInterval(spawnEnemy, 3); // a new enemy every 3 seconds\n```\n\nEvery schedule, and `eachTick`, takes the function itself, without brackets.\n`clock.scheduleInterval(spawnEnemy(), 3)` would call it once right away and\nhand over what it returned, so it throws a `TypeError` that says to drop the\nbrackets.\n\n### `clock.scheduleUnique(callback, delay)`\n\nLike `schedule`, but first cancels any existing scheduled call for the same\n`callback` function — useful when an event might restart a timer that's\nalready pending and you only want the latest one to count.\n\n### `clock.unschedule(callback)`\n\nCancels a pending `schedule`, `scheduleInterval`, or `eachTick` callback\nregistered with that exact function reference. Safe to call even if nothing\nmatching is scheduled.\n\n### `clock.eachTick(callback)`\n\nCalls `callback(dt)` on every single frame, forever (until unscheduled) —\nthis is what `animate()` uses internally to advance animations, and it's\nuseful directly for continuous per-frame effects that don't fit naturally\ninto your top-level `update()`.\n\n### `clock.clear()`\n\nCancels every scheduled call and every `eachTick` callback at once — handy\nwhen resetting a level or restarting a game so old timers from the previous\nrun don't fire.\n\n### `clock.now()`\n\nReturns the clock's current time in seconds (the running total of every\n`dt` it has been ticked with).\n\n### Error handling\n\nIn a game, a scheduled or `eachTick` callback that throws (an animation's\n`onFinished` too) stops the game, as an error in `update()` does: the game\nfails in the `clock` phase (`handle.failure.phase` is `\"clock\"`), and a\n`runtime-error` diagnostic reports `clock failed: …`. The other callbacks\ndue on that tick still run, but `update()` and `draw()` don't.\n\nA `Clock` you make yourself with `new Clock()` keeps going instead: it logs\nthe error to the console and unschedules only that callback.\n`new Clock({ onError })` hands the error to `onError` instead of logging it.\n\n## Animation\n\n### `animate(object, options)`\n\n```ts\nfunction animate<T extends object>(\n object: T,\n options: AnimationOptions<T>,\n): Animation<T>;\n```\n\nSmoothly interpolates one or more numeric properties on `object` over time.\nAny key in `options` other than `tween`, `duration`, and `onFinished` is\ntreated as a target value for a same-named property that must already exist\non `object` — animating a property `object` doesn't have throws an error.\n\n```js\nanimate(player, { x: 300, y: 120, duration: 0.5, tween: \"decelerate\" });\n```\n\n- `duration` — seconds, default `1`.\n- `tween` — the easing curve name (see the table below), default\n `\"linear\"`. An unknown name throws with a \"did you mean ...?\" suggestion.\n- `onFinished` — called once, when the animation reaches its target. It\n isn't called when the animation is stopped, even with `stop(true)`.\n- Each target value must be a finite number, or an array of finite numbers\n matching the shape of the property's current value (e.g. animating a\n `[x, y]`-shaped property to another two-number array).\n\nStarting a new `animate()` call for a property that's already mid-animation\nreplaces just that property's animation; other properties being animated by\nan earlier call keep running.\n\n`animate()` returns an `Animation` instance:\n\n- `.running: boolean`\n- `.stop(complete = false)` — stops the animation. `stop(true)` jumps the\n properties to their final values first. Neither calls `onFinished`.\n- `.removeTarget(property)` — stops animating a single property, leaving\n any others on the same call running.\n\n### Tween names\n\n| Name | What the motion looks like |\n| ---------------- | ---------------------------------------------------------------------------- |\n| `linear` | Constant speed. |\n| `easeIn` | Starts slow, speeds up (CSS's name). Same as `accelerate`. |\n| `easeOut` | Starts fast, slows to a stop (CSS's name). Same as `decelerate`. |\n| `easeInOut` | Speeds up, then slows down (CSS's name). Same as `accelDecel`. |\n| `bounce` | Bounces to a stop at the target, like a dropped ball. Same as `bounceEnd`. |\n| `spring` | Shoots past the target, then wobbles back and settles. Same as `outElastic`. |\n| `accelerate` | Starts slow, speeds up. |\n| `decelerate` | Starts fast, eases to a stop. |\n| `accelDecel` | Eases in, then eases out. |\n| `inElastic` | Wobbles around the starting point, then snaps to the target at the end. |\n| `outElastic` | Shoots past the target right away, then wobbles back and settles. |\n| `inOutElastic` | Wobbles at the start, then again around the target. |\n| `bounceEnd` | Bounces to a stop at the target, like a dropped ball. |\n| `bounceStart` | Bounces around the starting point, then heads for the target. |\n| `bounceStartEnd` | Bounces at both ends. |\n| `endElastic` | Same as `inElastic`: the wobble comes near the end. |\n| `startElastic` | Same as `outElastic`: the wobble comes near the start. |\n| `bothElastic` | Same as `inOutElastic`. |\n\nThat's all 18 names `tween` accepts: Pygame Zero's 10 curves, the five\nplain-language names, and `endElastic`, `startElastic` and `bothElastic`,\nnames from Pygame Zero's older docs (`end_elastic` and so on) that its code\ndoesn't accept. To check a name in code, import the same list as\n`tweenNames` (`import { tweenNames } from \"js-game-zero\"`); it isn't a\nglobal in a game file. Like every other name, they're camelCase:\n`tween: \"bounce_end\"` throws, suggesting `bounceEnd`. If you're not\nsure which to pick, try `easeOut` for smooth movement, `bounce` for things\nthat land, and `spring` for things that pop into place.\n",
32
+ "helpers.md": "# Helpers\n\nSmall functions for things almost every game needs. In a game file they're\nready to use, like `screen` and `Actor`; in import mode, import them from\n`js-game-zero`.\n\n## `randomInt(min, max)`\n\nA random whole number from `min` to `max`, **including both ends**.\n\n```js\nlet roll = randomInt(1, 6); // a die: 1, 2, 3, 4, 5 or 6\nlet x = randomInt(20, WIDTH - 20); // somewhere across the screen\n```\n\nFractional ends are rounded inward (`randomInt(0.5, 3.5)` picks 1, 2 or 3).\nPutting the bigger number first throws an error that says so.\n\n## `randomChoice(list)`\n\nA random item from a list.\n\n```js\nlet color = randomChoice([\"red\", \"gold\", \"skyblue\"]);\nball.vx = randomChoice([-200, 200]); // left or right\n```\n\nAn empty list throws, since there's nothing to choose.\n\n## `clamp(value, min, max)`\n\n`value`, moved inside `min`–`max` if it's outside; values already inside\ncome back unchanged.\n\n```js\nplayer.x = clamp(player.x, 0, WIDTH);\nplane.angle = clamp(-plane.vy / 8, -25, 75);\n```\n\nTo keep a whole sprite on screen, `player.clampIp(screen.bounds())` (see\n[`actor.md`](actor.md)) uses the sprite's real edges.\n\n## `rgb(red, green, blue, alpha?)`\n\nA color mixed from red, green and blue, each `0`–`255`, as in\n`rgb(255, 140, 105)`. See [Colors](screen.md#colors).\n",
33
+ "hooks.md": "# Hooks And Input Constants\n\nYour game is a set of top-level functions and settings. The runtime calls the\nfunctions it recognizes, in zero-boilerplate mode as plain `function`\ndeclarations and in import mode as properties on the object you pass to\n`run()`. This page documents the settings, every hook, then the `keys`,\n`keymods`, and `mouse` constant tables used by the input hooks.\n\nHook names are camelCase (`onKeyDown`, `onMouseDown`, ...), and work the\nsame way in both modes. (A game made with `defineGame()` is the exception:\nits input hooks receive one event object — see [`runtime.md`](runtime.md).)\nA hook spelled another way, such as Pygame Zero's `on_key_down`, is never\ncalled; the runtime warns about it with a `hook-typo` diagnostic that names\nthe camelCase hook to rename it to.\n\nA hook's arguments are matched **by parameter name** first. The runtime reads\nyour function's declared parameter names and passes the value with that name,\nin whatever order you wrote them. That means\n`function onKeyDown(mod, key) {}` receives `mod` and `key` correctly even\nthough the \"natural\" order is `key, mod`.\n\nA parameter with any other name receives the next value in the hook's\ndocumented order that isn't already taken by name, just like an ordinary\nJavaScript function: `function onKeyDown(k) {}` gets the key, and\n`function onMouseDown(position) {}` gets `pos`. The runtime adds a\n`hook-parameter` warning saying which value such a parameter receives, since\n`onMouseDown(btn)` gets the position, not the button. Name your parameters\nas shown below to avoid the warning.\n\nOne name is different: a hook whose only parameter is called `event`\nreceives all of its values in one object, as a `defineGame()` hook does, so\n`function onKeyDown(event) {}` reads `event.key` and `event.mod`.\n\n## Settings\n\nSet these at the top of a game, like `WIDTH = 480;`.\n\n| Setting | What it does | Default |\n| ---------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------ |\n| `WIDTH` | The game's width in pixels, rounded down to a whole number. `screen` and the mouse use it. | `800` |\n| `HEIGHT` | The game's height in pixels, rounded down to a whole number. | `600` |\n| `TITLE` | The page's title, shown on its tab. | The page's own title |\n| `ICON` | The name of an image in `images/`, as `Actor` takes it (`ICON = \"ship\";`), shown as the page's icon. | The page's own icon |\n| `PIXEL_DENSITY` | How many canvas pixels each game pixel gets. See [`screen.md`](screen.md#pixel_density-and-screendensity). | The device's pixel ratio |\n| `TOUCH_CONTROLS` | On-screen buttons for touch screens. See [Touch controls](#touch-controls). | None |\n\nA `WIDTH` or `HEIGHT` that isn't a positive number is ignored, with an\n`invalid-config` warning, and so is an `ICON` that isn't an image name. In\nimport mode, put the settings on the game module or in `run()`'s options\n(see [`runtime.md`](runtime.md#runoptions)).\n\n## draw()\n\n```ts\nfunction draw(): void;\n```\n\nCalled once per animation frame after `update` and after any pending assets\nhave loaded. `draw` must not declare any parameters — `run()` throws a\n`TypeError` at startup if it does, since a `draw(dt)` typo (mixing it up with\n`update`) is a common beginner mistake worth catching immediately.\n\n```js\nfunction draw() {\n screen.fill(\"#0f172a\");\n screen.draw.filledCircle([160, 90], 40, \"gold\");\n}\n```\n\n## update() / update(dt)\n\n```ts\nfunction update(): void;\nfunction update(dt: number): void;\n```\n\nCalled once per frame, before `draw`. Declare zero parameters if you don't\nneed frame timing, or one parameter (conventionally named `dt`) to receive the\nseconds elapsed since the previous frame — use it to make movement\nframe-rate-independent. When the game runs on its own, `dt` is clamped to at\nmost `0.25` seconds so a dropped frame (e.g. the tab was backgrounded) can't\ncause a huge jump. A host stepping the game itself, as `handle.step(dt)` and\nthe CLI's `step` do, passes its `dt` through unchanged.\n\n```js\nfunction update(dt) {\n if (keyboard.right) player.x += 200 * dt; // 200 px/sec, any frame rate\n}\n```\n\n## onKeyDown(key, mod, unicode, repeat) / onKeyUp(key, mod, unicode, repeat)\n\n```ts\nfunction onKeyDown(\n key: number,\n mod: number,\n unicode: string,\n repeat: boolean,\n): void;\nfunction onKeyUp(\n key: number,\n mod: number,\n unicode: string,\n repeat: boolean,\n): void;\n```\n\nFired on `keydown`/`keyup`.\n\n- `key` — **a numeric key constant from `keys`**, not a string. This is the\n single most common mistake when porting from other frameworks: compare it\n with `key === keys.LEFT`, never `key === \"left\"` or `key === \"ArrowLeft\"`.\n- `mod` — a bitmask of currently-held modifier keys from `keymods` (see\n below). Test a specific modifier with `mod & keymods.SHIFT`.\n- `unicode` — the typed character as a one-character string (`\"\"` for\n non-printable keys like arrows or function keys).\n- `repeat` — `true` if this event is an OS-generated key-repeat while the key\n is held down, rather than the initial press. It's always `false` for\n `onKeyUp`.\n\n```js\nfunction onKeyDown(key, mod) {\n if (key === keys.SPACE) jump();\n if (key === keys.R && mod & keymods.CTRL) restartLevel();\n}\n```\n\n`keyboard.left`, `keyboard.a`, and similar boolean properties (see below) are\nusually a better fit for continuous movement inside `update`; use\n`onKeyDown`/`onKeyUp` for one-shot actions like jumping or firing.\n\n## Touch controls\n\nSet `TOUCH_CONTROLS` near `WIDTH` and `HEIGHT` to add controls below your\ngame on phones, tablets, and computers with touch input. The runtime fits\nthe canvas into the space above the controls, preserving its aspect ratio\nand logical `WIDTH`/`HEIGHT`. Keyboard code works with these buttons too:\n\n```js\nTOUCH_CONTROLS = {\n left: keys.LEFT,\n right: keys.RIGHT,\n a: keys.SPACE,\n start: keys.RETURN,\n};\n```\n\nIn portrait mode, the dock places the D-pad on the left and the action\nbuttons on the right, with Start/Select beneath them; a game with no A or B\nputs Start/Select on the right instead. A sits above and to the right of B\nin a Game Boy-style diagonal arrangement. Three or four directions join into\none cross; left and right alone (or up and down) stay two separate keys. The\ndock stays below the canvas in both portrait and landscape layouts, near the\nbottom of the game's viewport. In portrait, the canvas is centered\nvertically with at least 48px above the control dock. On shorter screens it\nmoves upward as needed to keep the game and controls visible. Landscape\nkeeps a 16px gap. Bottom padding keeps buttons clear of the device's home\nindicator.\n\nOnly the buttons you list appear. Supported names are `up`, `down`, `left`,\n`right`, `a`, `b`, `start`, and `select`. Each value must be a numeric\nconstant from `keys`; the button's label is independent of its mapped key.\nFor example, `a: keys.SPACE` makes A trigger a game's existing Space action.\nOmitting `TOUCH_CONTROLS`, or setting it to `false`, hides the controls.\n\n`TOUCH_CONTROLS = true` enables this full preset:\n\n| Button | Mapped key |\n| ------------------------ | ---------------------------------------------------- |\n| Up / Down / Left / Right | `keys.UP` / `keys.DOWN` / `keys.LEFT` / `keys.RIGHT` |\n| A | `keys.SPACE` |\n| B | `keys.X` |\n| Start | `keys.RETURN` |\n| Select | `keys.ESCAPE` |\n\nThe default `show: \"auto\"` displays controls when the browser reports touch\nsupport or a coarse pointing device. Add `show: \"always\"` to a mapping to\npreview them on desktop. These are native buttons, so mouse clicks and\nTab followed by Space or Enter work as well.\n\nHolding a button updates `keyboard` and fires `onKeyDown` once; releasing\nit fires `onKeyUp`. Virtual presses have `mod: keymods.NONE`,\n`unicode: \"\"`, and `repeat: false`; use `update(dt)` for repeated actions.\nMultiple fingers can hold directions and action buttons together. Slide a\nfinger across the D-pad to change direction. Each mapped key stays held\nuntil every touch button and physical key holding it has\nbeen released. Cancellation, loss of pointer capture, leaving the window,\nand hiding the page clear held inputs. Stopping or reloading a game removes\nits controls and listeners.\n\nA page that hosts a game can restyle the dock by setting these CSS custom\nproperties on any element around the canvas, such as `:root`:\n\n| Property | What it sets | Default |\n| -------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------- |\n| `--jgz-key-size` | A key's size; the cross is three keys across | `clamp(40px, 10vw, 52px)` |\n| `--jgz-key-fill`, `--jgz-key-ink` | A key's fill, and its label and arrow color | `#263244`, `#fff` |\n| `--jgz-key-line`, `--jgz-key-line-width` | A key's outline | `#718096`, `2px` |\n| `--jgz-key-pressed-fill`, `--jgz-key-pressed-line` | A held key's fill and outline | `#4267a0`, `#b9d5ff` |\n| `--jgz-key-shadow-x`, `-y`, `-color` | A hard shadow under each key and the cross; a held key moves onto it | `0px`, `0px`, `transparent` |\n| `--jgz-key-radius` | Separate keys' corners (any `border-radius`) | `12px` |\n| `--jgz-dpad-radius` | The cross's outer corners | `10px` |\n| `--jgz-dpad-dot` | The dot in the middle of the cross | `rgba(255, 255, 255, 0.16)` |\n| `--jgz-key-font`, `--jgz-action-font` | Start/Select labels, and A/B labels (a `font` shorthand) | `bold 13px` and `bold 18px` `system-ui` |\n| `--jgz-action-line-width` | A and B's outline | `--jgz-key-line-width` |\n| `--jgz-system-height`, `--jgz-system-radius` | Start and Select's height and corners | `40px`, `12px` |\n| `--jgz-focus-ring` | The keyboard focus outline | `#facc15` |\n| `--jgz-dock-gap` | The least space between the canvas and the dock | `48px` portrait, `16px` landscape |\n\nIn import mode, put `TOUCH_CONTROLS` on the module returned by `defineGame`,\non a raw game module, or in the options passed to `run`. TypeScript exports\n`TouchButton`, `TouchControlsConfig`, and `TouchControlsOptions`.\n\n### Tapping and dragging the canvas\n\nCanvas touch and pen input work even without a control dock. A primary\ntouch triggers `onMouseDown`, dragging triggers `onMouseMove` with\n`mouse.LEFT` in `buttons`, and releasing or cancelling triggers\n`onMouseUp`. Positions and movement are converted to logical game\ncoordinates when the canvas is scaled. The pointer remains captured when\nit leaves the canvas; extra canvas touches are ignored until the first is\nreleased. Touch buttons do not trigger canvas mouse hooks.\n\nThe canvas and control buttons disable native touch panning during play;\nthe surrounding page retains its normal gestures. Games can therefore use\ntap-to-flap or drag-to-steer without adding separate touch hooks.\n\nFor embedding, give each canvas a parent with a defined height. While the\ndock is visible, the runtime groups the canvas and controls into a column\nthat fills the available space, anchors controls at the bottom, and centers\nthe portrait canvas when space permits. It accounts for visible siblings,\npadding, and row gaps, and restores the original canvas placement when the\ndock is hidden or the game stops.\nThe sandbox preview handles this automatically.\n\n## onMouseDown(pos, button) / onMouseUp(pos, button)\n\n```ts\nfunction onMouseDown(pos: [number, number], button: number): void;\nfunction onMouseUp(pos: [number, number], button: number): void;\n```\n\nFired on `mousedown`/`mouseup`, and also for **wheel scroll**: a wheel event\nis reported as `onMouseDown` with `button` set to `mouse.WHEEL_UP` or\n`mouse.WHEEL_DOWN` (matching pygame's convention of treating the scroll wheel\nas buttons 4 and 5, rather than a separate event). There is no\n`onMouseWheel` hook — check `button` inside `onMouseDown` instead.\n\n```js\nfunction onMouseDown(pos, button) {\n if (button === mouse.LEFT) fireAt(pos);\n if (button === mouse.WHEEL_UP) zoom += 1;\n if (button === mouse.WHEEL_DOWN) zoom -= 1;\n}\n```\n\n## onMouseMove(pos, rel, buttons)\n\n```ts\nfunction onMouseMove(\n pos: [number, number],\n rel: [number, number],\n buttons: Set<number>,\n): void;\n```\n\nFired on `mousemove`. `rel` is the movement since the previous event (from\nthe browser's `movementX`/`movementY` when available). `buttons` is a `Set`\nof currently held mouse buttons (`mouse.LEFT`, `mouse.MIDDLE`, `mouse.RIGHT`)\n— check membership with `buttons.has(mouse.LEFT)`.\n\n## onMusicEnd()\n\n```ts\nfunction onMusicEnd(): void;\n```\n\nFired once the active `music` track (and any queued tracks) finish playing\nwith nothing left to play.\n\n## `keyboard`\n\n`keyboard` is a live object of boolean properties reflecting which keys are\ncurrently held down, one for each key in `keys` under the same name in any\ncapitalization (`keyboard.left`, `keyboard.space`, `keyboard.a`, and\n`keyboard.K_1` for the digit keys). Read it inside `update()` for continuous\nmovement:\n\n```js\nfunction update(dt) {\n if (keyboard.left) player.x -= 150 * dt;\n if (keyboard.right) player.x += 150 * dt;\n}\n```\n\nAccessing an attribute that isn't a real key name throws an error (`The key\n\"...\" does not exist`) instead of silently returning `false` — this catches\ntypos like `keyboard.lfet` immediately rather than letting your character\nquietly fail to move. A misspelling says which key it's closest to:\n`keyboard.lfet doesn't exist. Did you mean keyboard.left?`. `keyboard.pressed()` returns a sorted array of every\ncurrently-held key constant, for debugging.\n\n## `keys`\n\nNumeric key constants, one property per key. The full set includes:\n\n| Category | Names |\n| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Letters | `keys.A` … `keys.Z` |\n| Digits | `keys.K_0` … `keys.K_9` |\n| Arrows | `keys.UP`, `keys.DOWN`, `keys.LEFT`, `keys.RIGHT` |\n| Editing | `keys.BACKSPACE`, `keys.TAB`, `keys.RETURN` (alias `keys.ENTER`), `keys.DELETE`, `keys.ESCAPE`, `keys.SPACE` |\n| Function keys | `keys.F1` … `keys.F15` |\n| Navigation | `keys.HOME`, `keys.END`, `keys.PAGEUP`, `keys.PAGEDOWN`, `keys.INSERT` |\n| Modifiers (as key presses) | `keys.LSHIFT`, `keys.RSHIFT`, `keys.LCTRL`, `keys.RCTRL`, `keys.LALT`, `keys.RALT`, `keys.LMETA`, `keys.RMETA` |\n| Numpad | `keys.KP0` … `keys.KP9`, `keys.KP_PERIOD`, `keys.KP_DIVIDE`, `keys.KP_MULTIPLY`, `keys.KP_MINUS`, `keys.KP_PLUS`, `keys.KP_ENTER`, `keys.KP_EQUALS` |\n| Punctuation | `keys.MINUS`, `keys.EQUALS`, `keys.LEFTBRACKET`, `keys.RIGHTBRACKET`, `keys.BACKSLASH`, `keys.SEMICOLON`, `keys.QUOTE`, `keys.BACKQUOTE`, `keys.COMMA`, `keys.PERIOD`, `keys.SLASH` |\n| Locks | `keys.CAPSLOCK`, `keys.NUMLOCK`, `keys.SCROLLOCK` |\n\nThe values are arbitrary integers (matching SDL/pygame's numbering) — never\nhardcode them, always compare against the named constant. Constants are\nupper case. In a game file, any other spelling such as `keys.space` or\n`keys.SPCE` throws with a suggestion (`Did you mean keys.SPACE?`) instead of\nquietly comparing against `undefined`. The same goes for `keymods` and\n`mouse`.\n\n## `keymods`\n\nA bitmask of held modifier keys, combined with `|` and tested with `&`:\n\n| Constant | Meaning |\n| ----------------------------------- | ----------------------------------------- |\n| `keymods.NONE` | No modifier held |\n| `keymods.SHIFT` | Either Shift key (`LSHIFT \\| RSHIFT`) |\n| `keymods.CTRL` | Either Control key (`LCTRL \\| RCTRL`) |\n| `keymods.ALT` | Either Alt/Option key (`LALT \\| RALT`) |\n| `keymods.META` | Either Cmd/Windows key (`LMETA \\| RMETA`) |\n| `keymods.LSHIFT` / `keymods.RSHIFT` | Left/right Shift specifically |\n| `keymods.LCTRL` / `keymods.RCTRL` | Left/right Control specifically |\n| `keymods.LALT` / `keymods.RALT` | Left/right Alt specifically |\n| `keymods.LMETA` / `keymods.RMETA` | Left/right Cmd/Windows specifically |\n| `keymods.CAPS` | Caps Lock is toggled on |\n| `keymods.NUM` | Num Lock is toggled on |\n| `keymods.MODE` | AltGr / alternate-graphics modifier |\n\n```js\nfunction onKeyDown(key, mod) {\n if (mod & keymods.SHIFT) console.log(\"shift-modified key\");\n}\n```\n\n## `mouse`\n\nIn a game file, `mouse` also says where the mouse is right now, for code in\n`update()` that follows or aims at it — the way `keyboard` does for keys:\n\n| Property | Meaning |\n| --------------- | ----------------------------------------------------------------------------- |\n| `mouse.pos` | `[x, y]` of the mouse (or a finger) over the game. The center until it moves. |\n| `mouse.x` | The same `x`. |\n| `mouse.y` | The same `y`. |\n| `mouse.buttons` | A `Set` of buttons held now: `mouse.buttons.has(mouse.LEFT)`. |\n| `mouse.down` | `true` while any button, or a finger, is down. |\n\n```js\nfunction update(dt) {\n ship.angle = ship.angleTo(mouse.pos); // aim at the mouse\n}\n```\n\nButton constants:\n\n| Constant | Value | Meaning |\n| ------------------ | ----- | ---------------------------------------------------- |\n| `mouse.LEFT` | 1 | Left mouse button |\n| `mouse.MIDDLE` | 2 | Middle mouse button (wheel click) |\n| `mouse.RIGHT` | 3 | Right mouse button |\n| `mouse.WHEEL_UP` | 4 | Scroll wheel moved up (reported via `onMouseDown`) |\n| `mouse.WHEEL_DOWN` | 5 | Scroll wheel moved down (reported via `onMouseDown`) |\n",
34
+ "loaders.md": "# Loading Assets\n\nGames load four kinds of asset, each from its own conventional directory:\n\n| Kind | Directory | Extensions |\n| ------ | --------- | ------------------------------------------------- |\n| Images | `images/` | `png`, `gif`, `jpg`, `jpeg`, `bmp`, `webp`, `svg` |\n| Sounds | `sounds/` | `wav`, `ogg`, `mp3`, `m4a` |\n| Music | `music/` | `wav`, `ogg`, `mp3`, `m4a` |\n| Fonts | `fonts/` | `ttf`, `otf`, `woff`, `woff2` |\n\nIn the sandbox, these are the Images, Sounds, Music and Fonts panels; for examples and\nhand-written projects, they're plain directories next to your game's code.\n\n## Asset name grammar\n\nAn asset name is a lowercase, forward-slash path, resolved relative to its\nkind's directory — `\"player.svg\"` means `images/player.svg`,\n`\"levels/forest_bg.png\"` means `images/levels/forest_bg.png`. Rules:\n\n- Each path segment must start with a lowercase letter and contain only\n lowercase letters, digits, and underscores (no hyphens, no uppercase, no\n spaces) — `\"player.svg\"` is valid, `\"Player.svg\"` and `\"player-1.svg\"` are\n not.\n- No leading `/`, no `\\`, no empty segments, no `.`/`..` segments.\n- At most one extension per segment, and it must be one of the kind's\n supported list above, in lowercase.\n- The extension is optional when you reference the asset — `images.player`\n and `new Actor(\"player\")` both work by trying every supported extension\n for that kind in turn until one loads.\n\nAn invalid name throws `InvalidAssetNameError`; a name that doesn't match\nany file throws `MissingAssetError` naming the asset kind and the name you\nasked for — both are meant to be immediately readable, so check the browser\nconsole for the exact reason before assuming a typo is something else.\n\n## Using assets\n\n### Images\n\nMost games load images through `Actor` (see\n[`docs/reference/actor.md`](actor.md)) or `screen.blit()`. To use an image\ndirectly — for its dimensions, say — the zero-boilerplate `images` global\n(or `import { images } from \"js-game-zero\"`) exposes property-style\nlazy access:\n\n```js\nlet ship = images.player; // starts loading images/player.svg\n\nfunction draw() {\n let [width, height] = ship.getSize();\n}\n```\n\nThe game's first frame waits for every image its top level named, so their\nsizes are there in `update()` and `draw()`. At the top level an image is\nusually still loading, and reading its size there throws an error that says\nso, unless the host page handed the images over already decoded\n(`loadImages`, which `jgz` and the sandbox use).\n\nAn image has `getWidth()`, `getHeight()`, `getSize()` and `getRect()`. Give\n`getRect()` a point to place it by, like an Actor's\n(`images.player.getRect({ center: [160, 90] })`), for a `Rect` of the image's\nsize there; without one it sits at `[0, 0]`.\n\nIn an import-mode game, or any `async` function, load explicitly and `await`\nthe result:\n\n```js\nconst sprite = await images.load(\"player.svg\");\nsprite.getWidth();\nsprite.getHeight();\n```\n\n### Sounds and music\n\n`sounds.<name>` and `music.play(name)` resolve assets the same way — see\n[`docs/reference/audio.md`](audio.md) for the playback API.\n\n### Fonts\n\nFonts aren't injected as a zero-boilerplate global; use `fontname` in\n`draw.text`/`draw.textbox` (see [`docs/reference/screen.md`](screen.md)) and\nthe loader starts fetching the font in the background the first time it's\nreferenced:\n\n```js\nscreen.draw.text(\"Retro!\", [20, 20], { fontname: \"pixel\", fontsize: 32 });\n```\n\n`fontname` is the file's stem (`fonts/pixel.ttf` → `\"pixel\"`), registered\nwith the browser under that family name once loaded. If you need to `await`\na font being ready (e.g. to measure text before your first draw), import\n`fonts` and call `await fonts.load(\"pixel\")` directly.\n\n## Assets without a server\n\nBy default a run loads each asset from a URL under `assetBaseUrl`\n(`/assets/<projectId>/images/cat.svg`), so something has to serve them. A\nhost page that already has the files can hand them over instead, with\n`assetUrls`: a map from each asset's path, as it sits in the project, to a\nURL the browser can load, such as a data URL or a blob URL.\n\n```js\nrun(source, {\n assetUrls: {\n \"images/cat.svg\": \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0i…\",\n \"sounds/pop.wav\": \"data:audio/wav;base64,UklGRi…\",\n },\n});\n```\n\nGames name assets as usual: `new Actor(\"cat\")`, `images.cat` and\n`sounds.pop` find `images/cat.svg` and `sounds/pop.wav` in the map, trying\neach supported extension as they would on a server. With a map, assets come\nonly from it: one it doesn't list is a `MissingAssetError`, and nothing is\nrequested from `assetBaseUrl`.\n\n`run()` starts a game's code straight away, and an image the run loads\nitself is still decoding while the top level runs, so it has no size yet:\n`player.width` reads 0 there, and an Actor placed by `midBottom` and then\nmoved lands as if it were 0×0. A page can decode the images first with\n`loadImages` from `js-game-zero/host` (`JGZ.loadImages` in the\nscript-tag build), as `jgz` and the sandbox do. The game then finds them\nready from its first line, as a Pygame Zero game would:\n\n```js\nconst images = await loadImages(assetUrls);\nrun(source, { assetUrls, preloadedAssets: { images } });\n```\n\n`loadImages` decodes every `images/` entry of the map, by its name under\n`images/`. One that fails is left out, so the run loads it itself and\nreports the failure only if the game uses it. Sounds, music and fonts given as data URLs\nare decoded in the page rather than fetched, so a page whose content\nsecurity policy allows no connections (no `connect-src`) still plays them;\nimages need `img-src data:` (or `blob:`), and sounds `media-src` to match.\nAn `ICON` the map doesn't list leaves the page's favicon as it is.\n\n## Loader methods (advanced)\n\nEvery asset kind is backed by a loader with the same shape. Games normally use\nthe `images`, `sounds`, and `fonts` services from `js-game-zero`; music\nplayback uses the `music` player. Hosts that need to construct or override\nloaders import `createAssetLoaders()` or the individual factories from\n`js-game-zero/host`:\n\n- `load(name): Promise<Asset>` — fetches and caches the asset.\n- `assetUrls` — the asset map the loader reads instead of `assetBaseUrl`,\n or `undefined` when it has none.\n- `get(name): Asset | undefined` — synchronous; only returns something if\n already cached.\n- `has(name): boolean`\n- `define(name, asset)` — registers an asset object directly without going\n through the network, useful for tests or preloading fixtures.\n- `unload(name): boolean` — evicts one cached asset.\n- `unloadAll()` — clears the whole cache.\n- `cacheKeys(): string[]` — every currently-cached asset name, sorted.\n\nWhy a frame never shows a half-loaded sprite: each runtime tracks its own image\nand font loads started while the script's top level runs (and any started\nafterward) and holds frames until they settle. Audio loads remain recoverable\nand do not gate frames — see the\n\"preload gate\" section of [`docs/reference/runtime.md`](runtime.md).\n",
35
+ "rect.md": "# Rect And ZRect\n\n`Rect` is a mutable rectangle with pygame/pgzero-style geometry helpers:\nposition properties that move the rectangle without resizing it, collision\ntests, and set operations. `ZRect` is a subclass of `Rect` that adds\nnothing, kept for code ported from pgzero that references `ZRect` directly —\nthe two behave the same, and a `ZRect` is also a `Rect`.\n\n## Constructing a Rect\n\n```ts\nnew Rect(left: number, top: number, width: number, height: number)\nnew Rect(topLeft: [number, number], size: [number, number])\nnew Rect(other: Rect)\nnew Rect([left, top, width, height])\nnew Rect({ left, top, width, height })\nnew Rect({ x, y, w, h })\nnew Rect(objectWithADotRectPropertyOrMethod)\n```\n\nThe last form is duck-typed: if you pass any object with a `.rect` property\n(or a `.rect()` method), the `Rect` constructor follows it — recursively, up\nto a sensible depth — until it finds real rectangle data. This is what lets\nyou write `new Rect(myActor)` directly, since `Actor` exposes a `.rect()`\nmethod, and it means most `Rect`/`Actor` collision methods below accept an\n`Actor` anywhere they say \"rect-like\" without you needing to call `.rect()`\nyourself.\n\n```js\nlet hitbox = new Rect(10, 20, 40, 30);\nlet same = new Rect(hitbox); // copy via any accepted shape\nlet fromActor = new Rect(player); // works because Actor has .rect()\n```\n\n## Properties\n\nAll of these read or write the rectangle in place; setting a position\nproperty moves the rectangle without changing its size, and setting `width`,\n`height`, `w`, `h`, or `size` resizes it.\n\n| Property | Meaning |\n| -------------------------------------------------- | --------------------------------- |\n| `left`, `top`, `width`, `height` | The four base fields. |\n| `x`, `y`, `w`, `h` | Aliases for the same. |\n| `right`, `bottom` | `left + width`, `top + height`. |\n| `centerX`, `centerY` | Center point, one axis at a time. |\n| `topLeft`, `topRight`, `bottomLeft`, `bottomRight` | Corners, as `[x, y]`. |\n| `midTop`, `midLeft`, `midRight`, `midBottom` | Edge midpoints, as `[x, y]`. |\n| `center` | `[centerX, centerY]`. |\n| `size` | `[width, height]`. |\n\n`Rect` also supports index access (`rect[0]` through `rect[3]` for\n`left`/`top`/`width`/`height`) and spreading/iteration\n(`[...rect]` → `[left, top, width, height]`, `Array.from(rect)`), so it can\nbe dropped into APIs that expect a plain tuple.\n\n```js\nhitbox.center = [100, 80]; // moves it; width/height unchanged\nhitbox.size = [64, 64]; // resizes it in place\nlet [left, top, width, height] = hitbox;\n```\n\n## Copying and moving\n\n- `copy(): Rect`\n- `move(x, y)` / `move([x, y])` → new `Rect`; `moveIp(...)` moves in place.\n- `inflate(x, y)` / `inflate([x, y])` → new `Rect`, grown by `x`/`y` around\n its center (negative shrinks); `inflateIp(...)` mutates in place.\n- `normalize()` — flips a negative `width`/`height` so the rectangle has a\n well-defined top-left corner (mutates in place).\n\n## Set operations\n\nEach but `fit` has a mutating `…Ip` counterpart that applies the result back\nonto the rectangle itself instead of returning a new one:\n\n- `clamp(other)` / `clampIp(other)` — moves (without resizing) to fit\n entirely inside `other`, centering on whichever axis doesn't fit.\n- `clip(other)` / `clipIp(other)` — the overlapping area of this rect and\n `other` (zero-sized if they don't overlap).\n- `union(other)` / `unionIp(other)` — the smallest rect containing both.\n- `unionAll(others)` / `unionAllIp(others)` — union across an array of\n rect-likes.\n- `fit(other)` — scales (preserving aspect ratio) and centers this rect to\n fit inside `other`.\n\n```js\nlet hitbox = new Rect(300, 60, 40, 40);\nhitbox.clampIp(screen.bounds()); // now fully on screen\n```\n\n`Actor` has its own `clampIp`, which moves the actor itself:\n`player.clampIp(screen.bounds())` keeps the player on screen. (Calling\n`player.rect().clampIp(...)` would only move a copy of the player's\nrectangle, not the player.)\n\n## Collision tests\n\nCollision uses **half-open bounds**: the left and top edges are inclusive,\nthe right and bottom edges are exclusive — a point exactly on the right or\nbottom edge does not count as colliding. This matches pygame's `Rect`.\n\n- `touches(target): boolean` — the one test most games need: `target` is an\n `[x, y]` point (does the rect contain it?) or any rect-like value, such as\n another `Rect` or an `Actor` (do they overlap?).\n- `contains(other): boolean`\n- `collidePoint(point)` / `collidePoint(x, y): boolean`\n- `collideRect(other): boolean`\n- `collideList(others): number` — index of the first colliding rect-like in\n the array, or `-1`.\n- `collideListAll(others): number[]` — indexes of every colliding entry.\n- `collideDict(dict, useValues = true)` — `dict` is a `Map` or plain object;\n returns the first `[key, value]` entry whose value (or key, if\n `useValues` is `false`) collides with this rect, or `undefined`.\n- `collideDictAll(dict, useValues = true)` — same, but returns every\n matching `[key, value]` entry as an array.\n\n```js\nlet enemies = { goblin: goblinRect, bat: batRect };\nlet hit = player.rect().collideDict(enemies);\nif (hit) console.log(`hit the ${hit[0]}`);\n```\n\n## Standalone helpers\n\n`angleTo(from, to)` and `distanceTo(from, to)` are exported functions (used\ninternally by `Actor.angleTo`/`distanceTo`) if you need the same math on\nplain points without an `Actor`. They aren't globals in a game file; import\nthem from `js-game-zero`.\n",
36
+ "runtime.md": "# The `run()` Module API\n\nMost learners never call `run()` directly — the sandbox and zero-boilerplate\nexamples call it for you, and you just write top-level `WIDTH`/`draw`/\n`update`/hook definitions. This page is for import-mode code and for anyone\nembedding the framework in a host page (a custom sandbox, a course platform,\nan automated test).\n\n```ts\nfunction run(\n moduleOrSource: GameModule | DefinedGame | string,\n options?: RunOptions,\n): GameHandle;\n```\n\n## Three entry styles\n\n**Scoped import mode (recommended for applications)** — `defineGame()` gives\nthe game a typed set of services owned by that one run. Actors, assets,\nstorage, animation, input, and audio therefore cannot accidentally bind to a\ndifferent game on the same page:\n\n```ts\nimport { defineGame, run } from \"js-game-zero\";\n\nrun(\n defineGame(({ Actor, screen, keyboard }) => {\n const player = new Actor(\"player.svg\");\n return {\n WIDTH: 320,\n HEIGHT: 180,\n update(dt) {\n if (keyboard.right) player.x += 120 * dt;\n },\n draw() {\n screen.clear();\n player.draw();\n },\n onKeyDown(event) {\n console.log(event.key);\n },\n };\n }),\n);\n```\n\nThe input hooks in a defined game receive one typed event object.\nZero-boilerplate and raw import hooks keep their Pygame Zero-style\nparameter-name dispatch.\n\n| Event | Fields |\n| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `GameKeyEvent` (`onKeyDown`, `onKeyUp`) | `key`, `mod`, `unicode` and `repeat`, as [`hooks.md`](hooks.md#onkeydownkey-mod-unicode-repeat--onkeyupkey-mod-unicode-repeat) describes them. |\n| `GameMouseEvent` (`onMouseDown`, `onMouseUp`, `onMouseMove`) | `pos`, `button` (the button pressed or released, or `null` for one with no `mouse` constant; `onMouseMove` reads `buttons` instead), `buttons` (a `Set` of held buttons) and `rel` (movement since the last event). |\n\nThe function given to `defineGame()` receives the run's own services:\n`screen`, `clock`, `keyboard`, `mouse`, `images`, `sounds`, `music`, `fonts`,\n`storage`, `tone`, `animate` and `exit`, the constants `keys` and `keymods`,\nand the classes `Actor`, `Animation`, `Rect`, `ZRect`, `Screen` and\n`Storage`. An `Actor` or `Animation` made from them belongs to that run.\n\nPackage-level `screen`, `clock`, `keyboard`, `images`, `sounds`, `music`, and\n`storage` remain available for learner compatibility. They are convenience\nproxies for a single active runtime; applications that can run more than one\ngame should prefer the services passed to `defineGame()`.\n\n**Import mode** — pass a plain object of hooks and config:\n\n```js\nimport { run, screen, keyboard } from \"js-game-zero\";\n\nrun({\n WIDTH: 320,\n HEIGHT: 180,\n draw() {\n screen.fill(\"#10243d\");\n },\n update(dt) {\n /* ... */\n },\n onKeyDown(key) {\n /* hooks receive values by parameter name */\n },\n});\n```\n\n**Global mode** — pass a source-code string, which runs with the framework's\nglobals (`Actor`, `screen`, `keyboard`, `WIDTH`, `draw`, ...) already in\nscope, exactly like a zero-boilerplate sandbox project. This is how the\nsandbox's preview pane runs the code from your editor.\n\n```js\nrun(`\n WIDTH = 320;\n HEIGHT = 180;\n function draw() { screen.fill(\"navy\"); }\n`);\n```\n\n`handle.mode` tells you which one was used (`\"import\"` or `\"global\"`).\n\nA global-mode game runs in its own scope rather than the page's. Reading a\nname nothing defines throws a `ReferenceError` with a suggestion\n(`scren is not defined. Did you mean screen?`); `typeof name` stays safe.\nBrowser APIs a game can't reach say what to use instead — for example,\n`setTimeout` points at `clock.schedule(callback, seconds)`, and\n`localStorage` at `storage`. Standard JavaScript built-ins such as `Math`,\n`JSON`, `isNaN`, `Map` and `console` are available as usual.\n\nEvery library name has one spelling, in camelCase: `screen.draw.filledCircle`,\n`actor.angleTo`, `rect.collidePoint`, `clock.scheduleInterval`, `onKeyDown`.\nConstants stay upper case (`WIDTH`, `keys.SPACE`, `mouse.LEFT`). Another\nspelling of a member, such as Pygame Zero's `actor.angle_to` or\n`rect.colliderect`, throws where it's read, naming the real one\n(`actor.angle_to doesn't exist. Did you mean actor.angleTo?`). In a\nglobal-mode game, `screen`, `clock`, `music`, `tone`, `keys`, `keymods` and\n`mouse` also throw with a suggestion for any member they don't have\n(`screen.draw.cirlce doesn't exist. Did you mean screen.draw.circle?`), and\nan undefined global suggests the real one\n(`random_int is not defined. Did you mean randomInt?`).\nThe classes behind them (`Screen`, `Clock`, `Storage`) are globals too, so a\ncapital letter by mistake, as in `Screen.fill(\"navy\")`, points at the service\ninstead (`Screen.fill doesn't exist. Did you mean screen.fill?`).\n\n## `RunOptions`\n\n| Option | Purpose |\n| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `canvas` | Draw into an existing `<canvas>` instead of creating one. |\n| `container` | Where to mount a created canvas (default the page's `<body>`). Called from a script in `<head>`, before there's a `<body>`, the game starts at once and its canvas joins the `<body>` when the page has been read. |\n| `autostart` | Default `true`. Set `false` to skip the automatic frame loop and drive frames yourself via `handle.step(dt)` — useful for deterministic tests. |\n| `projectId` | Scopes storage keys and asset URLs, so multiple games on one page don't collide. |\n| `assetBaseUrl` | Where asset URLs are rooted (default `/assets`). |\n| `assetUrls` | The game's assets by path, each with its URL: `{ \"images/cat.svg\": \"data:image/svg+xml;base64,…\" }`. When set, assets load only from here, never from `assetBaseUrl`. See [assets without a server](loaders.md#assets-without-a-server). |\n| `preload` | An array of asset paths (e.g. `[\"images/player.svg\"]`) to start loading immediately, before any is referenced by code. |\n| `preloadedAssets` | Pre-built `{ images, sounds, music, fonts }` asset maps to seed the cache synchronously — used by hosts that already have the bytes. `loadImages(assetUrls)` makes the `images` map; see [assets without a server](loaders.md#assets-without-a-server). |\n| `storage` | A `Storage` instance or a raw `StorageAdapter` (`{ path, load(), save(text) }`) to use instead of the default `localStorage`-backed one. |\n| `loaders` | Override one or more of the `images`/`sounds`/`music`/`fonts` loader instances. |\n| `keyboardTarget` | The `EventTarget` that receives keyboard events (default `window`). |\n| `mouseReleaseTarget` | The `EventTarget` where mouse releases (`mouseup`) are heard (default `window`, so a drag released outside the canvas still ends). A host driving a game itself passes the canvas, so its releases reach no other game. |\n| `seed` | A string or number that makes the game's randomness repeatable: `Math.random` as a zero-boilerplate game sees it, and `randomInt` and `randomChoice`, follow one sequence for this seed, the sequence `jgz test --seed` uses. See [seeded runs](#seeded-runs). |\n| `TOUCH_CONTROLS` | `true` for the full touch-control preset, `false` to disable it, or a button mapping with optional `show: \"auto\"` / `\"always\"`. See [touch controls](hooks.md#touch-controls). |\n| `PIXEL_DENSITY` | Canvas pixels per logical pixel. Defaults to the device's pixel ratio, from 1 to 3. See [pixel density](#pixel-density). |\n| `scheduler` | Override `requestAnimationFrame`/`cancelAnimationFrame` (for tests). |\n| `diagnostics` | `(diagnostic) => void` — called for every diagnostic (see below). Without it, they go to the browser console. |\n\nAny hook or `WIDTH`/`HEIGHT`/`PIXEL_DENSITY`/`TITLE`/`ICON`/`TOUCH_CONTROLS`\nconfig can also be passed directly on `RunOptions`; if the same one is also present on the module\nobject, the option wins and a diagnostic warns about the duplicate.\n\n## `GameHandle`\n\n`run()` returns a handle for controlling the running game:\n\n| Member | Purpose |\n| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |\n| `canvas`, `screen`, `clock`, `keyboard`, `loaders`, `storage` | The live instances this run is using. |\n| `module` | The final, merged hook/config object. |\n| `diagnostics` | The diagnostics collected so far. |\n| `state`, `failure` | Lifecycle state and the first fatal runtime failure, if one occurred. |\n| `ready: Promise<void>` | Resolves once the preload gate is satisfied (see below). |\n| `done: Promise<void>` | Resolves after final storage flushing and resource cleanup complete. |\n| `pause()` / `resume()` | Stop/restart the frame loop without tearing anything down. |\n| `step(dt)` | Manually advance one frame by `dt` seconds — only meaningful with `autostart: false`. |\n| `stop()` | Detaches input listeners, flushes any pending storage save, and cancels the frame loop. |\n| `dispose()` | Awaited form of cleanup; resolves only after pending persistence work is finished. |\n| `restart(nextSource?)` | Awaits cleanup, then starts a fresh run with the same options. Resolves to the new run's handle; this one stays stopped. |\n| `reload(nextSource?)` | Compatibility alias that starts synchronously and returns the new run's handle; prefer `restart()` when persistence ordering matters. |\n\n```js\nconst handle = run(gameModule, { canvas });\n// later\nhandle.stop();\n```\n\n## `exit()`\n\n```js\nimport { exit } from \"js-game-zero\";\nexit(); // equivalent to calling .stop() on the currently active run() handle\n```\n\nAlso injected as a zero-boilerplate global, so game code can call `exit()`\ndirectly to end itself.\n\n## Preload gate\n\nEach run tracks its own required image and font loads (Actor constructions,\n`images.player` touches, and `preload` entries) and holds frames, with no\n`update` and no `draw`, until those loads and storage initialization settle.\nAn image or font first asked for later, in a hook (a new `actor.image`, a first\n`screen.blit`), holds the frames after it the same way until it has loaded,\nand `handle.step()` does nothing meanwhile. So a host that steps a game in a\nsynchronous loop should hand it its images decoded, with\n[`loadImages`](loaders.md#assets-without-a-server). A required image/font\nfailure rejects `handle.ready`, fails the handle, and performs cleanup. Sound and music loads\nare recoverable: they report a warning but never freeze another run or stop\nrendering. `handle.ready` lets hosts await startup explicitly instead of\npolling.\n\n## Pixel density\n\nThe canvas holds `WIDTH × HEIGHT × density` pixels, so a game is as sharp\nas the screen it's on. Density is the device's `devicePixelRatio`, from 1\nto 3, unless the game file or `RunOptions` sets `PIXEL_DENSITY`. A\n`PIXEL_DENSITY` that isn't a positive number warns and uses the device's\nratio.\n\nGame code works in logical pixels at any density; only reading the\ncanvas itself sees its real pixels:\n\n| Logical pixels | Canvas pixels (logical × density) |\n| -------------------------------------------------------- | --------------------------------- |\n| `screen.width`, `screen.height`, `screen.bounds()` | `canvas.width`, `canvas.height` |\n| Every drawing call, text, images and Actors | `getImageData()`, `toDataURL()` |\n| Mouse and touch positions, Actor positions and hit tests | |\n\n`screen.density` reports the density in use, so a host reading pixels back\nmultiplies logical coordinates by it.\n\n**CSS size.** A denser canvas would show at its pixel size, so the runtime\ngives it a CSS width of `WIDTH` px through a `:where(canvas[data-jgz-density])`\nrule; its height follows the aspect ratio. The rule has no specificity, so\nCSS the page sets on the canvas wins. A page that sizes the canvas should\nset its width, or both width and height: a height alone keeps the rule's\nwidth. The touch-control dock and the sandbox preview fit the canvas by its\nlogical size. At density 1 the canvas gets no rule and shows at its own\nsize.\n\n**Changes.** Before each frame the runtime checks the canvas against the\nscreen:\n\n- With no `PIXEL_DENSITY`, density follows `devicePixelRatio`, which\n changes when the page is zoomed or moved to another display. The canvas\n keeps what it shows, rescaled, for games that don't redraw everything.\n- A host that sets `canvas.width` or `canvas.height` sets the logical size,\n and the runtime multiplies it by the density.\n- Setting a canvas's size resets its context, so the runtime restores the\n density scale.\n\n**Limit.** iOS Safari leaves a canvas over 16,777,216 pixels (4096²)\nblank, so density comes down until the canvas fits, though never below 1\nunless the game asks for less. A `PIXEL_DENSITY` that doesn't fit warns\nand uses the most that does.\n\nRaster images (PNG, JPEG) can't hold more detail than their own pixels. In\nChromium, SVG images draw from their vectors at the canvas's density, so an\nSVG Actor stays sharp at any size.\n\n## Package boundaries\n\nGames import learner-facing values from `js-game-zero`. Embedders should\nimport loader factories, browser adapters, scheduler/diagnostic types, and\nother integration APIs from `js-game-zero/host`; Node filesystem storage\nlives at `js-game-zero/node`. Browser-safe advanced root imports remain\nas deprecated compatibility aliases through 0.2.\n\nHost tooling can also import `getGameInspector(handle)` from\n`js-game-zero/host`. It returns a live, read-only binding inspector for a\nrunning zero-boilerplate source game, or `null` for import-mode and disposed\nhandles (a failed game keeps its inspector, so a host can read the state at the\ncrash). This is the inspection seam the browser-backed `jgz` verification CLI\nuses; it does not add globals or learner-facing runtime methods.\n\n| Member | Purpose |\n| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |\n| `bindings()` | The captured non-function top-level identifiers, in source order. |\n| `functions()` | The top-level functions. |\n| `read(path)` | The live value at a binding or a [state path](#state-paths), as it is. |\n| `inspect(path?)` | The value at a path as JSON, exactly as `jgz`'s `inspect` reports it (`serializeGameValue`); with no path, every binding's value by name. |\n\nThe same module exports `serializeGameValue(value)`, `parseStatePath(source)`,\n`createSeededRandom(seed)` and `loadImages(assetUrls)` (see\n[assets without a server](loaders.md#assets-without-a-server)).\n\nThe rest of `js-game-zero/host` is for building a host:\n\n| Export | What it's for |\n| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| `createImageLoader`, `createSoundLoader`, `createMusicLoader`, `createFontLoader` and `createAssetLoaders` | Loaders for `RunOptions.loaders`, each taking a `projectId` and an `assetBaseUrl` or `assetUrls`. |\n| `createStorage({ adapter?, projectId?, path? })` and `createLocalStorageAdapter({ projectId?, path? })` | A `Storage`, or the `localStorage` adapter behind the default one, for `RunOptions.storage`. |\n| `collectRuntimeDiagnostics(game, options?)` | The static [diagnostics](#diagnostics) `run()` would report for a game's source or module, without running it. |\n| `layoutText(context, text, pos, options?)` and `fitTextboxFontSize(context, text, rect, options?)` | Where `screen.draw.text` and `screen.draw.textbox` would put text, and at what size. |\n\nIts other exports (the input dispatcher, the `map…Event` functions,\n`dispatchHook`, the audio and tone classes, `getScreen`/`setScreen`) are the\nruntime's own parts, exported for tools and tests, and may change.\n`js-game-zero/node` exports `createSandboxFileStorageAdapter({\nprojectRoot, path? })`, a `StorageAdapter` that keeps a project's storage in\na JSON file under `projectRoot` (`storage.json` by default).\n\nThis reference ships with `js-game-zero`, for a host that hands it to a\nlearner, a tool or a model. `js-game-zero/reference` exports `reference`,\nevery page's Markdown by its file name (`reference[\"actor.md\"]`), and each\npage is also a file at `js-game-zero/reference/<page>.md`.\n\n### State paths\n\nA path names a top-level binding, then `.name` for a property and `[n]` for an\nindex: `score`, `player.x`, `fish[0].y`. `parseStatePath(\"fish[0].y\")` returns\n`{ source: \"fish[0].y\", binding: \"fish\", segments: [0, \"y\"] }`, and throws a\n`TypeError` for anything else, including `__proto__`, `prototype` and\n`constructor`. `jgz`'s `inspect` takes the same paths.\n\n### What a frame drew\n\nA path that starts with `$drawn` reads what the game's last `draw()` drew,\nin order, rather than one of its bindings, through `read`, `inspect` and\n`jgz`'s `inspect` alike. Each thing drawn has its `kind` and what it is and\nwhere, as the game gave them:\n\n| `kind` | Fields | From |\n| --------- | ----------------------------------------------------------------------------- | --------------------------------------------------------- |\n| `fill` | `color`, and `to` for a gradient | `screen.fill` |\n| `clear` | | `screen.clear` |\n| `image` | `image` (its name), `x`, `y` (its top-left) | `screen.blit`, `screen.draw.image` |\n| `actor` | `image`, `x`, `y` (its `pos`: its center, unless its `anchor` says otherwise) | an Actor's `draw()` |\n| `circle` | `x`, `y`, `radius`, `color`, `filled` | `screen.circle`, `screen.draw.circle`, `filledCircle` |\n| `rect` | `x`, `y`, `width`, `height`, `color`, `filled` | `screen.rect`, `screen.draw.rect`, `filledRect` |\n| `polygon` | `x`, `y` (its first point), `points` (how many), `color`, `filled` | `screen.triangle`, `screen.draw.polygon`, `filledPolygon` |\n| `line` | `x`, `y`, `x2`, `y2`, `color` | `screen.line`, `screen.draw.line` |\n| `text` | `text`, `x`, `y`, `width`, `height` (its box), and `color` when it has one | `screen.text`, `screen.draw.text`, `screen.draw.textbox` |\n\n`$drawn[0].kind`, `$drawn[2].image` and the like read single things. A frame\nkeeps its first 200 things; before the first frame `$drawn` is empty. So a\ncheck that something is on the screen reads what the game drew rather than\nits pixels: `{ kind: \"actor\", image: \"robot.svg\" }` is in `$drawn`.\n\n### Inspected values\n\n`serializeGameValue` turns a value into JSON: numbers, strings, booleans,\narrays and plain objects as they are (object keys sorted); anything else tagged\nwith `$type`:\n\n```js\nserializeGameValue(new Actor(\"cat\", [40, 60]));\n// { $type: \"Actor\", image: \"cat\", x: 40, y: 60, width, height, angle, …, properties: {} }\nserializeGameValue(new Rect(1, 2, 3, 4));\n// { $type: \"Rect\", left: 1, top: 2, right: 4, bottom: 6, width: 3, height: 4, center: [2.5, 4] }\nserializeGameValue({ missing: undefined, big: Infinity });\n// { big: { $type: \"Number\", value: \"Infinity\" }, missing: { $type: \"Undefined\" } }\n```\n\nAn Actor's `properties` are the fields the game gave it (`cat.speed = 40` is\n`properties.speed`); a `read` gives the Actor itself, so `cat.speed` there.\nSets, maps, dates and errors are tagged too; values deeper than six levels,\nlists past 100 items and circular references come back as `Truncated` or\n`Circular`.\n\n### Seeded runs\n\n`run(source, { seed })` gives the game a sequence of its own. A\nzero-boilerplate game sees a `Math` whose `random` follows the seed (every\nother member is the real `Math`'s), and `randomInt` and `randomChoice` draw\nfrom it while the game runs, in its hooks and its top-level code alike. An\nimport-mode game's `randomInt` and `randomChoice` follow the seed in its hooks;\nits `Math.random` is the page's. Nothing else changes: the page's own\n`Math.random`, and any other game on the page, keep their randomness, and a\n`restart()` starts the sequence again.\n\nUp to nine plain digits are the number they spell (`42` and `\"42\"` are the same\nseed); any other string is hashed (FNV-1a), and the sequence is Mulberry32 over\nthat 32-bit state. `jgz test --seed` passes its seed to the same option, so one\nseed gives the same values in the CLI and in a host page;\n`createSeededRandom(seed)` returns the sequence itself, for a host or a test to\npredict. A seed that isn't a string or a finite number fails at startup.\n\n### Driving a game from a host page\n\nThe script-tag build is `dist/jgz.js` in `js-game-zero` (`js-game-zero/iife`),\nwhich jsDelivr also serves, at\n`https://cdn.jsdelivr.net/npm/js-game-zero@0.3/dist/jgz.js`.\nIts `window.JGZ` carries `loadImages`, `getGameInspector`,\n`serializeGameValue`, `parseStatePath` and `createSeededRandom` beside the\nlearner-facing API, so a page can run a game it drives itself, the way the CLI\ndoes, without a bundler:\n\n```js\nconst canvas = document.createElement(\"canvas\"); // never added to the page\nconst handle = JGZ.run(source, {\n canvas,\n autostart: false,\n seed: \"check-1\",\n keyboardTarget: canvas,\n mouseReleaseTarget: canvas,\n PIXEL_DENSITY: 1,\n});\nawait handle.ready;\nhandle.step(0); // draws the first screen, as the CLI does\ncanvas.dispatchEvent(\n new KeyboardEvent(\"keydown\", { key: \"ArrowRight\", code: \"ArrowRight\" }),\n);\nfor (let frame = 0; frame < 30; frame += 1) handle.step(1 / 60);\ncanvas.dispatchEvent(\n new KeyboardEvent(\"keyup\", { key: \"ArrowRight\", code: \"ArrowRight\" }),\n);\ncanvas.dispatchEvent(\n new MouseEvent(\"mousedown\", {\n clientX: 25,\n clientY: 30,\n button: 0,\n buttons: 1,\n }),\n);\ncanvas.dispatchEvent(\n new MouseEvent(\"mouseup\", { clientX: 25, clientY: 30, button: 0 }),\n);\nJGZ.getGameInspector(handle).inspect(\"player.x\");\n```\n\n- **Frames.** With `autostart: false`, nothing runs until the page calls\n `handle.step(dt)`; each call is one `update(dt)` and one `draw()`. The CLI\n steps once with `dt` 0 after `ready`, then one sixtieth of a second per frame,\n so a page that does the same sees what `jgz test play` sees.\n- **Keys.** Keyboard events are heard on `keyboardTarget` (default `window`):\n `keydown` and `keyup`, read by `code` first (`ArrowRight`, `Space`, `KeyA`)\n and then `key`. Passing the canvas keeps them from reaching other games.\n- **Mouse and taps.** `mousedown`, `mousemove` and `wheel` are heard on the\n canvas, `mouseup` on `mouseReleaseTarget` (default `window`). A position is\n mapped from the canvas's displayed box onto the logical screen:\n `clientX = box.left + x / screen.width * box.width`, and the same for `y`\n (`handle.canvas.getBoundingClientRect()`, `handle.screen`). A canvas that\n isn't on the page has an empty box, so its client coordinates are the\n logical ones, as above. Touch arrives as `pointerdown`, `pointermove` and\n `pointerup` with `pointerType: \"touch\"`; the CLI uses the mouse events.\n\n## Diagnostics\n\n`run()` performs lightweight static checks and reports them through the\n`diagnostics` option (and collects them on `handle.diagnostics`) rather than\nfailing outright. A few mistakes stop the game before it starts instead:\n`run()` reports a `runtime-error` in the `startup` phase and throws. The\nmain one is that **`draw()` must not declare any parameters** (a\n`TypeError`, since mixing it up with `update(dt)` is a very common typo).\nThe others are a `TOUCH_CONTROLS` that isn't a valid mapping, a `seed` that\nisn't a string or a finite number, an invalid `projectId` or `assetUrls`, and\na top-level statement that throws.\n\nEverything else is a warning:\n\n| `code` | Meaning |\n| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |\n| `hook-typo` | A top-level function is named nearly like a hook (e.g. `onKeyDwon`), or is a hook spelled another way (`on_key_down`), which is never called. |\n| `constant-typo` | A top-level assignment is named nearly like a setting, such as `WIDTH` or `TITLE`. |\n| `duplicate-config` | The same setting was given both on the module and in the run options. |\n| `hook-arity` | `update` declares more than one parameter. |\n| `hook-parameter` | An input hook parameter isn't one of its documented names; says what it receives. |\n| `invalid-config` | `WIDTH`/`HEIGHT`/`PIXEL_DENSITY`/`ICON` isn't usable. |\n| `asset-name` | A quoted string that looks like an asset filename doesn't match the naming grammar. |\n| `runtime-error` | An uncaught error, or a failure loading/saving storage. |\n\nThe two typo checks only look at names the script _defines_ at top level\n(`function drow()`, `const udpate = () => {}`, `WIDHT = 800`), never at names\nit merely uses (`row`, `col`, `rows[y]`), and they stay quiet when the real\nname is also defined. Short names get one edit of slack and longer ones two.\n\nA `runtime-error` raised by the game's own code (a hook that threw, or a\ntop-level statement at startup) also carries `line`: the 1-based line in the\ngame source where the error was thrown, when the engine's stack trace names it.\nA `hook-typo` or `constant-typo` warning carries the line that declares the\nmisspelled name, and `draw()` declaring parameters fails on the line that\ndeclares it.\nA syntax error carries one too: where the engine gives no position (V8 gives\nnone for compiled game code), it's the first line whose part of the source\nfails the same way, so a missing `)` is placed on the line it's missing from,\nand a block left open on the line it opens on. A name the game never defined\nis placed the same way where the engine gives no position (JavaScriptCore): on\nthe one line that reads it, when only one does. `handle.failure.line` is the\nsame number. Errors thrown inside the library have no `line`.\n\nThe sandbox shows these under Messages, and marks a problem's line in the editor; import-mode hosts can pass\na `diagnostics` callback to log or display them however they like. Without\none, a run reports them to the browser console: a warning with\n`console.warn` and an error with `console.error`, each starting\n`js-game-zero:` and ending with its line, if it has one. A mistake that\nmakes `run()` itself throw isn't logged as well. A game that fails while\nrunning removes a canvas it made, so on a page with no callback, the\nconsole is where to find out why.\n",
37
+ "screen.md": "# Screen And Drawing\n\n`screen` is the global canvas surface. Everything you draw happens inside\n`draw()`, in screen pixels: `[0, 0]` is the top-left corner, x grows right,\ny grows down, and `[WIDTH, HEIGHT]` is the bottom-right corner.\n\n## Short forms\n\nFive short calls draw the most common shapes and text, with each position\ngiven as separate numbers rather than an `[x, y]` list:\n\n| Call | Draws |\n| ------------------------------------------------ | -------------------------------------------------- |\n| `screen.circle(x, y, radius, color)` | a filled circle centered on `x, y` |\n| `screen.rect(x, y, width, height, color)` | a filled rectangle whose top-left corner is `x, y` |\n| `screen.triangle(x1, y1, x2, y2, x3, y3, color)` | a filled triangle with those three corners |\n| `screen.line(x1, y1, x2, y2, color, width = 1)` | a line from `x1, y1` to `x2, y2`, `width` px thick |\n| `screen.text(text, x, y, color, size = 24)` | text whose top-left corner is `x, y`, `size` tall |\n\n`color` is optional and defaults to `\"white\"`; it takes any of the\n[colors](#colors) below.\n\n```js\nfunction draw() {\n screen.clear();\n screen.rect(0, 220, 400, 80, \"green\");\n screen.circle(200, 150, 25, \"gold\");\n screen.triangle(160, 40, 120, 120, 200, 120);\n screen.line(20, 20, 200, 120, \"white\", 3);\n screen.text(\"Score: \" + score, 20, 30);\n}\n```\n\n`screen.text` takes words in quotes or a number. To place text by its\ncenter, wrap it or give it an outline, use\n[`screen.draw.text`](#screendrawtexttext-pos-options--screendrawtexttext-options).\n\nThe short forms fill their shapes. The outline versions, and the versions\nthat take `[x, y]` lists, stay under `screen.draw` below. Mind the names:\n**`screen.circle` fills, but `screen.draw.circle` draws only an outline**,\nand the same goes for `screen.rect` and `screen.draw.rect`.\n\nA wrong call throws a `TypeError` that says what to change. A list, as in\n`screen.circle([200, 150], 25)`, points to the `screen.draw` method that\ntakes lists (here `screen.draw.filledCircle`). A missing or non-number\nargument is named, and an extra one, such as an outline width, points to\nthe outline method.\n\n## Colors\n\nEvery drawing method accepts a `Color`, which is either a CSS color string\n(`\"white\"`, `\"#0f172a\"`, `\"rgb(20, 30, 40)\"`) or an RGB/RGBA tuple of\nintegers `0`–`255`: `[249, 115, 22]` or `[249, 115, 22, 128]` (the fourth\nvalue is alpha out of 255, not a `0`–`1` fraction). Passing anything else\nthrows a `TypeError` that says what was wrong:\n\n- A misspelled color name suggests the right one: `\"lightblu\"` fails with\n `Did you mean \"lightblue\"?`. (A canvas would otherwise ignore the color\n and keep drawing in the previous one.)\n- A hex code needs 3 or 6 hex digits (or 4 or 8, with alpha).\n- A fractional alpha such as `[255, 0, 0, 0.5]` fails with the 0–255 value\n to use instead (`128`).\n\nDrawing options are checked the same way: an option a method doesn't have,\nsuch as `{ colour: \"red\" }`, throws and names the closest real option.\n\n### `rgb(red, green, blue, alpha?)`\n\nMixes a color from red, green and blue light, each `0`–`255`, with an\noptional alpha out of 255. It returns the matching list, so\n`rgb(255, 140, 105)` is `[255, 140, 105]` and works anywhere a color does.\nIt's ready to use in a game file; in import mode, import it from\n`js-game-zero`.\n\n```js\nlet coral = rgb(255, 140, 105);\nlet glass = rgb(120, 200, 255, 128); // half see-through\nscreen.circle(200, 150, 25, coral);\n```\n\nIts numbers are checked like a list's, with the same hints (a fractional\nalpha such as `0.5` names `128` instead), and a missing one is named:\n`rgb(255, 140)` fails with `rgb is missing blue`.\n\n## `screen.clear()`\n\nResets the whole canvas to opaque black.\n\n```js\nfunction draw() {\n screen.clear();\n}\n```\n\n## `screen.fill(color, bottomColor?)`\n\nFills the canvas with a solid color, or a top-to-bottom gradient when a\nsecond color is given: `color` at the top fading to `bottomColor` at the\nbottom.\n\n```js\nscreen.fill(\"#0f172a\"); // solid\nscreen.fill(\"#0f172a\", \"#164e63\"); // gradient, dark at top to teal at bottom\n```\n\n## `screen.draw.image(image, pos)` / `screen.blit(image, pos)`\n\n`screen.draw.image` and `screen.blit` (Pygame Zero's name) do the same\nthing. Draws an already-loaded image (by asset name, or a `SurfaceLike` you already\nhold) at a position. `pos` is a `[x, y]` point for the image's top-left\ncorner, or a rect-like value (its top-left corner is used; blit does not\nscale the image to the rect's size).\n\n```js\nscreen.draw.image(\"player.svg\", [40, 40]);\n```\n\nIf the named image hasn't finished loading yet, nothing is drawn: it returns\na `Promise` that resolves once the image has loaded, and the runtime holds\nthe frames that follow until then, so the image shows from the next one.\nIf it can't be loaded, the promise rejects and the run reports the missing\nimage by name, so `draw()` needn't handle the promise itself.\nImages touched while the script starts up load before the first frame (see\n[`docs/reference/runtime.md`](runtime.md#preload-gate)).\nPrefer `Actor` for anything that moves or needs collision — drawing an image\ndirectly is for background art and tiles.\n\n## `screen.bounds()`\n\nReturns a `ZRect` covering the whole canvas (`[0, 0, WIDTH, HEIGHT]`), handy\nfor clamping or collision against the screen edge.\n\n```js\nif (!screen.bounds().contains(player.rect()))\n player.center = [WIDTH / 2, HEIGHT / 2];\n```\n\n## `PIXEL_DENSITY` and `screen.density`\n\nOn a phone, one screen pixel covers several of the device's own pixels.\nThe canvas has a pixel for each of them, so text, outlines and SVG pictures\nstay sharp. `screen.density` says how many canvas pixels make up one screen\npixel along each side: between 2 and 3 on most phones and 1 on a computer\nmonitor. Your game's numbers don't change with it: a game 360 pixels wide\nis 360 wide at any density.\n\nSet `PIXEL_DENSITY` next to `WIDTH` and `HEIGHT` to choose the density\nyourself. Without it, the game uses the device's own, up to 3.\n\n```js\nWIDTH = 360;\nHEIGHT = 640;\nPIXEL_DENSITY = 1; // one canvas pixel per screen pixel, even on a phone\n```\n\nSee [pixel density](runtime.md#pixel-density) for how hosts size and read\nthe canvas.\n\n## `screen.draw.line(start, end, color, width = 1)`\n\n```js\nscreen.draw.line([20, 20], [200, 120], \"white\", 3);\n```\n\n## `screen.draw.circle(pos, radius, color, width = 1)` / `filledCircle(pos, radius, color)`\n\n`screen.draw.circle` draws an outline; `filledCircle` and the short form\n[`screen.circle`](#short-forms) fill.\n\n```js\nscreen.draw.circle([160, 90], 40, \"#38bdf8\", 2); // outline\nscreen.draw.filledCircle([160, 90], 40, \"#38bdf8\"); // filled\n```\n\n## `screen.draw.rect(rect, color, width = 1)` / `filledRect(rect, color)`\n\n`rect` accepts anything geometry accepts: a `Rect`, an `Actor` (via its\n`.rect()` duck type — see [`docs/reference/rect.md`](rect.md)), or a plain\n`[left, top, width, height]` tuple.\n\n```js\nscreen.draw.filledRect([40, 40, 120, 60], \"#f97316\");\nscreen.draw.rect(player.rect(), \"yellow\", 2); // highlight a hitbox\n```\n\n## `screen.draw.polygon(points, color, width = 1)` / `filledPolygon(points, color)`\n\nNeeds at least three points.\n\n```js\nscreen.draw.filledPolygon(\n [\n [238, 40],\n [292, 64],\n [270, 126],\n [214, 118],\n ],\n \"#f8fafc\",\n);\n```\n\n## `screen.draw.text(text, pos?, options?)` / `screen.draw.text(text, options)`\n\nDraws text with a large set of beginner-friendly options — this is a\nJavaScript-native reimplementation of pgzero's `ptext` module, including its\nword-wrapping algorithm and gradient/outline/shadow effects.\n\n```js\nscreen.draw.text(\"Score: 12\", [16, 16], {\n size: 24,\n color: \"white\",\n});\n```\n\nWhen the options say where the text goes (`center`, `topRight`, ...), pass\nthem second, in place of the position:\n\n```js\nscreen.draw.text(\"Game Over\", { center: [WIDTH / 2, HEIGHT / 2], size: 40 });\n```\n\nSeveral options have two names: a readable one, and the shorter one Pygame\nZero uses. Either works, but not both at once:\n\n| Readable name | Pygame Zero name |\n| --------------- | ---------------- |\n| `size` | `fontsize` |\n| `outline` | `owidth` |\n| `outlineColor` | `ocolor` |\n| `shadowColor` | `scolor` |\n| `gradientColor` | `gcolor` |\n\n### Position options\n\nGive **exactly one** of the following ways to position the text (mixing\nthem throws a `TypeError`):\n\n- `pos` (or the second positional argument) — a `[x, y]` point. Combined\n with `anchor` (default `\"topLeft\"`) to decide which part of the text box\n sits at that point.\n- A named anchor point directly: `topLeft`, `topRight`, `bottomLeft`,\n `bottomRight`, `midTop`, `midLeft`, `midRight`, `midBottom`, `center` —\n each takes a `[x, y]` point for that corner/edge/center of the text.\n- Scalar axis keywords, combined per-axis: `left`/`centerX`/`right` for the\n horizontal position, `top`/`centerY`/`bottom` for the vertical position.\n You can mix one horizontal and one vertical scalar (`{ right: 300, top: 10\n}`), or use just one axis and fall back to `pos` for the other.\n\n```js\nscreen.draw.text(\"Game Over\", {\n center: [WIDTH / 2, HEIGHT / 2],\n size: 40,\n});\nscreen.draw.text(\"HUD\", { right: WIDTH - 10, top: 10 }); // top-right corner, 10px margin\n```\n\n### Font options\n\n- `size` / `fontsize` (default `24`)\n- `fontname` — the stem of a font asset under `fonts/` (e.g. `\"pixel\"` for\n `fonts/pixel.ttf`); loads asynchronously the first time it's used.\n- `sysfontname` — a literal CSS font family name instead (e.g. `\"Georgia\"`).\n Mutually exclusive with `fontname`.\n- `bold`, `italic`, `underline` — booleans.\n- `color` (default `\"white\"`), `background` (fills a box behind the text).\n- `gradientColor` / `gcolor` — a second color for a top-to-bottom gradient\n across the text.\n\n### Layout options\n\n- `width` — wraps text to fit this many pixels; without it, text is only\n broken at explicit newlines (`\\n`). Wrapping is greedy word-wrap: a single\n word longer than `width` is placed on its own (overflowing) line rather\n than being cut.\n- `widthem` — like `width`, but expressed as a multiple of `size`.\n- `lineheight` — pixels between lines (default `size * 1.2`).\n- `align` — `\"left\"` (default), `\"center\"`, or `\"right\"`, for multi-line text.\n A [`textbox`](#screendrawtextboxtext-rect-options) follows its `anchor`\n instead, so it centers by default.\n- `strip` — trims trailing spaces from each wrapped line (default `true`).\n- `anchor` — overrides which part of the text's bounding box sits at the\n resolved position; either one of the named anchor strings above, or a\n `[horizontal, vertical]` pair where each side is `\"left\"`/`\"center\"`/`\"right\"`,\n `\"top\"`/`\"center\"`/`\"bottom\"`, or a literal pixel-offset number.\n- `angle` — rotates the text counterclockwise around the anchor point, in\n degrees.\n\n### Effects\n\n- `outline` / `owidth` + `outlineColor` / `ocolor` — an outline stroke\n around the glyphs, `outline` pixels thick.\n- `shadow` (a number or `[x, y]` offset) + `shadowColor` / `scolor`\n (default `\"black\"`) — a drop shadow.\n- `alpha` — overall opacity, `0`–`1` (default `1`).\n\n## `screen.draw.textbox(text, rect, options?)`\n\nLike `draw.text`, but instead of a fixed `size` you give a rectangle and\n`textbox` picks the **largest font size that fits inside it** (shrinking\ndown to `minSize`, default `4`, if necessary; `minFontsize` is another name\nfor it, but not both at once). Text is centered in the rect by default.\nPass `anchor` (e.g. `\"topLeft\"`) to place it elsewhere in the rect; its\nlines line up the same way (on the left for `\"topLeft\"`) unless you give\n`align`. The rect places the text, so `textbox` takes none of\n`draw.text`'s position options (`pos`, `center`, `topLeft`, `left`, ...)\nand no `width`; giving one throws a `TypeError` that says so.\n\n```js\nscreen.draw.textbox(\"You win!\", [40, 60, 240, 80], {\n color: \"white\",\n size: 48, // upper bound; shrinks to fit if \"You win!\" would overflow\n});\n```\n",
38
+ "storage.md": "# Storage\n\n`storage` is a persistent, dictionary-like object for saving small amounts\nof data between play sessions — high scores, unlocked levels, settings.\n\n```js\nlet highScore = storage.get(\"highScore\") ?? 0;\n\nfunction update() {\n if (score > highScore) {\n highScore = score;\n storage.set(\"highScore\", highScore);\n }\n}\n```\n\n## Auto-load and auto-save\n\nYou don't need to call `save()` or `load()` yourself in normal use:\n\n- **Auto-load**: the default browser adapter has a synchronous `loadSync()`\n path, so a top-level read like `let score = storage.get(\"score\") ?? 0`\n sees previously-saved data immediately. So does a custom adapter with a\n `loadSync()`, or whose `load()` returns its text rather than a Promise. A\n custom asynchronous adapter is loaded once during startup and delays\n frames/`handle.ready`, but cannot retroactively change values already\n copied into top-level variables, and what it loads replaces anything the\n top level stored before it arrived.\n- **Auto-save**: any mutation (`storage.set(...)`, `storage.score = 5`,\n `storage.delete(...)`, `storage.clear()`) schedules a save a fraction of a\n second later, and within a second even while the game keeps changing it\n every frame; rapid changes coalesce into one write instead of saving on\n every single mutation. Storage is also flushed immediately when the tab is\n hidden or closed, and when the game stops, so nothing is lost. A change\n inside a stored object or list, such as `storage.highScores.push(score)`,\n is saved too, with the next of those saves; set the key again\n (`storage.highScores = storage.highScores`) to save it sooner.\n\n## Reading and writing\n\nTwo equivalent styles work — plain method calls, or attribute-style access\nthrough a proxy (closer to pgzero's `storage` object):\n\n```js\nstorage.set(\"score\", 10);\nstorage.get(\"score\"); // 10\n\nstorage.score = 10; // same as storage.set(\"score\", 10)\nstorage.score; // 10\n```\n\n| Method | Behavior |\n| --------------------------------------- | -------------------------------------------------------------------------------------------------- |\n| `storage.get(key, defaultValue?)` | Returns the stored value, or `defaultValue` (`undefined` if omitted) if `key` isn't set. |\n| `storage.set(key, value)` | Stores `value` under `key`. |\n| `storage.setDefault(key, defaultValue)` | Sets `key` to `defaultValue` only if it isn't already set; returns the resulting value either way. |\n| `storage.has(key)` | `boolean`. |\n| `storage.delete(key)` | Removes `key`; also works as `delete storage.key`. Returns `true` if something was removed. |\n| `storage.clear()` | Removes everything. |\n| `storage.keys()` | Every stored key, alphabetically sorted. |\n| `storage.path` | The backing location: a scoped `localStorage` key in the browser, or a file path in the sandbox. |\n\nValues must be JSON-serializable — plain objects, arrays, strings, numbers,\nbooleans, and `null`. Storing anything else (a class instance, a function,\n`undefined`, `NaN`, `Infinity`, a circular reference), anywhere inside the\nvalue, throws a `JsonStorageError` naming the offending path, e.g.\n`NaN is not a JSON value at storage.highScores[2].score`, and stores nothing.\nA value changed inside a stored object or list after it was stored is only\nchecked when storage saves: until it's a JSON value again, saving fails,\nwith a warning naming its path, and nothing in storage is saved.\n\n## Gotchas\n\n- **Don't shadow method names.** `storage.save`, `storage.load`, `storage.path`\n and the other method names above are real properties on `storage` itself,\n not just proxy-forwarded keys — writing `storage.save = 5` overwrites the\n actual `save` method instead of storing a value, and another spelling of\n a method, such as `storage.setdefault`, throws naming the method. Pick key\n names that don't collide with the method list.\n- Storage is scoped per project: in the browser it's namespaced by project\n id (so two different games on the same site don't share data, as long as\n each has its own `projectId`; games run without one all share the id\n `default`); in the sandbox it's a JSON file inside that project's own\n directory.\n\n## Manual save/load\n\nFor advanced cases — forcing an immediate write instead of waiting for the\ndebounce, or working outside of `run()` — `storage.save()` and\n`storage.load()` are both available directly and return `Promise<void>`.\n"
39
+ });
@@ -0,0 +1,164 @@
1
+ # Loading Assets
2
+
3
+ Games load four kinds of asset, each from its own conventional directory:
4
+
5
+ | Kind | Directory | Extensions |
6
+ | ------ | --------- | ------------------------------------------------- |
7
+ | Images | `images/` | `png`, `gif`, `jpg`, `jpeg`, `bmp`, `webp`, `svg` |
8
+ | Sounds | `sounds/` | `wav`, `ogg`, `mp3`, `m4a` |
9
+ | Music | `music/` | `wav`, `ogg`, `mp3`, `m4a` |
10
+ | Fonts | `fonts/` | `ttf`, `otf`, `woff`, `woff2` |
11
+
12
+ In the sandbox, these are the Images, Sounds, Music and Fonts panels; for examples and
13
+ hand-written projects, they're plain directories next to your game's code.
14
+
15
+ ## Asset name grammar
16
+
17
+ An asset name is a lowercase, forward-slash path, resolved relative to its
18
+ kind's directory — `"player.svg"` means `images/player.svg`,
19
+ `"levels/forest_bg.png"` means `images/levels/forest_bg.png`. Rules:
20
+
21
+ - Each path segment must start with a lowercase letter and contain only
22
+ lowercase letters, digits, and underscores (no hyphens, no uppercase, no
23
+ spaces) — `"player.svg"` is valid, `"Player.svg"` and `"player-1.svg"` are
24
+ not.
25
+ - No leading `/`, no `\`, no empty segments, no `.`/`..` segments.
26
+ - At most one extension per segment, and it must be one of the kind's
27
+ supported list above, in lowercase.
28
+ - The extension is optional when you reference the asset — `images.player`
29
+ and `new Actor("player")` both work by trying every supported extension
30
+ for that kind in turn until one loads.
31
+
32
+ An invalid name throws `InvalidAssetNameError`; a name that doesn't match
33
+ any file throws `MissingAssetError` naming the asset kind and the name you
34
+ asked for — both are meant to be immediately readable, so check the browser
35
+ console for the exact reason before assuming a typo is something else.
36
+
37
+ ## Using assets
38
+
39
+ ### Images
40
+
41
+ Most games load images through `Actor` (see
42
+ [`docs/reference/actor.md`](actor.md)) or `screen.blit()`. To use an image
43
+ directly — for its dimensions, say — the zero-boilerplate `images` global
44
+ (or `import { images } from "js-game-zero"`) exposes property-style
45
+ lazy access:
46
+
47
+ ```js
48
+ let ship = images.player; // starts loading images/player.svg
49
+
50
+ function draw() {
51
+ let [width, height] = ship.getSize();
52
+ }
53
+ ```
54
+
55
+ The game's first frame waits for every image its top level named, so their
56
+ sizes are there in `update()` and `draw()`. At the top level an image is
57
+ usually still loading, and reading its size there throws an error that says
58
+ so, unless the host page handed the images over already decoded
59
+ (`loadImages`, which `jgz` and the sandbox use).
60
+
61
+ An image has `getWidth()`, `getHeight()`, `getSize()` and `getRect()`. Give
62
+ `getRect()` a point to place it by, like an Actor's
63
+ (`images.player.getRect({ center: [160, 90] })`), for a `Rect` of the image's
64
+ size there; without one it sits at `[0, 0]`.
65
+
66
+ In an import-mode game, or any `async` function, load explicitly and `await`
67
+ the result:
68
+
69
+ ```js
70
+ const sprite = await images.load("player.svg");
71
+ sprite.getWidth();
72
+ sprite.getHeight();
73
+ ```
74
+
75
+ ### Sounds and music
76
+
77
+ `sounds.<name>` and `music.play(name)` resolve assets the same way — see
78
+ [`docs/reference/audio.md`](audio.md) for the playback API.
79
+
80
+ ### Fonts
81
+
82
+ Fonts aren't injected as a zero-boilerplate global; use `fontname` in
83
+ `draw.text`/`draw.textbox` (see [`docs/reference/screen.md`](screen.md)) and
84
+ the loader starts fetching the font in the background the first time it's
85
+ referenced:
86
+
87
+ ```js
88
+ screen.draw.text("Retro!", [20, 20], { fontname: "pixel", fontsize: 32 });
89
+ ```
90
+
91
+ `fontname` is the file's stem (`fonts/pixel.ttf` → `"pixel"`), registered
92
+ with the browser under that family name once loaded. If you need to `await`
93
+ a font being ready (e.g. to measure text before your first draw), import
94
+ `fonts` and call `await fonts.load("pixel")` directly.
95
+
96
+ ## Assets without a server
97
+
98
+ By default a run loads each asset from a URL under `assetBaseUrl`
99
+ (`/assets/<projectId>/images/cat.svg`), so something has to serve them. A
100
+ host page that already has the files can hand them over instead, with
101
+ `assetUrls`: a map from each asset's path, as it sits in the project, to a
102
+ URL the browser can load, such as a data URL or a blob URL.
103
+
104
+ ```js
105
+ run(source, {
106
+ assetUrls: {
107
+ "images/cat.svg": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0i…",
108
+ "sounds/pop.wav": "data:audio/wav;base64,UklGRi…",
109
+ },
110
+ });
111
+ ```
112
+
113
+ Games name assets as usual: `new Actor("cat")`, `images.cat` and
114
+ `sounds.pop` find `images/cat.svg` and `sounds/pop.wav` in the map, trying
115
+ each supported extension as they would on a server. With a map, assets come
116
+ only from it: one it doesn't list is a `MissingAssetError`, and nothing is
117
+ requested from `assetBaseUrl`.
118
+
119
+ `run()` starts a game's code straight away, and an image the run loads
120
+ itself is still decoding while the top level runs, so it has no size yet:
121
+ `player.width` reads 0 there, and an Actor placed by `midBottom` and then
122
+ moved lands as if it were 0×0. A page can decode the images first with
123
+ `loadImages` from `js-game-zero/host` (`JGZ.loadImages` in the
124
+ script-tag build), as `jgz` and the sandbox do. The game then finds them
125
+ ready from its first line, as a Pygame Zero game would:
126
+
127
+ ```js
128
+ const images = await loadImages(assetUrls);
129
+ run(source, { assetUrls, preloadedAssets: { images } });
130
+ ```
131
+
132
+ `loadImages` decodes every `images/` entry of the map, by its name under
133
+ `images/`. One that fails is left out, so the run loads it itself and
134
+ reports the failure only if the game uses it. Sounds, music and fonts given as data URLs
135
+ are decoded in the page rather than fetched, so a page whose content
136
+ security policy allows no connections (no `connect-src`) still plays them;
137
+ images need `img-src data:` (or `blob:`), and sounds `media-src` to match.
138
+ An `ICON` the map doesn't list leaves the page's favicon as it is.
139
+
140
+ ## Loader methods (advanced)
141
+
142
+ Every asset kind is backed by a loader with the same shape. Games normally use
143
+ the `images`, `sounds`, and `fonts` services from `js-game-zero`; music
144
+ playback uses the `music` player. Hosts that need to construct or override
145
+ loaders import `createAssetLoaders()` or the individual factories from
146
+ `js-game-zero/host`:
147
+
148
+ - `load(name): Promise<Asset>` — fetches and caches the asset.
149
+ - `assetUrls` — the asset map the loader reads instead of `assetBaseUrl`,
150
+ or `undefined` when it has none.
151
+ - `get(name): Asset | undefined` — synchronous; only returns something if
152
+ already cached.
153
+ - `has(name): boolean`
154
+ - `define(name, asset)` — registers an asset object directly without going
155
+ through the network, useful for tests or preloading fixtures.
156
+ - `unload(name): boolean` — evicts one cached asset.
157
+ - `unloadAll()` — clears the whole cache.
158
+ - `cacheKeys(): string[]` — every currently-cached asset name, sorted.
159
+
160
+ Why a frame never shows a half-loaded sprite: each runtime tracks its own image
161
+ and font loads started while the script's top level runs (and any started
162
+ afterward) and holds frames until they settle. Audio loads remain recoverable
163
+ and do not gate frames — see the
164
+ "preload gate" section of [`docs/reference/runtime.md`](runtime.md).
@@ -0,0 +1,129 @@
1
+ # Rect And ZRect
2
+
3
+ `Rect` is a mutable rectangle with pygame/pgzero-style geometry helpers:
4
+ position properties that move the rectangle without resizing it, collision
5
+ tests, and set operations. `ZRect` is a subclass of `Rect` that adds
6
+ nothing, kept for code ported from pgzero that references `ZRect` directly —
7
+ the two behave the same, and a `ZRect` is also a `Rect`.
8
+
9
+ ## Constructing a Rect
10
+
11
+ ```ts
12
+ new Rect(left: number, top: number, width: number, height: number)
13
+ new Rect(topLeft: [number, number], size: [number, number])
14
+ new Rect(other: Rect)
15
+ new Rect([left, top, width, height])
16
+ new Rect({ left, top, width, height })
17
+ new Rect({ x, y, w, h })
18
+ new Rect(objectWithADotRectPropertyOrMethod)
19
+ ```
20
+
21
+ The last form is duck-typed: if you pass any object with a `.rect` property
22
+ (or a `.rect()` method), the `Rect` constructor follows it — recursively, up
23
+ to a sensible depth — until it finds real rectangle data. This is what lets
24
+ you write `new Rect(myActor)` directly, since `Actor` exposes a `.rect()`
25
+ method, and it means most `Rect`/`Actor` collision methods below accept an
26
+ `Actor` anywhere they say "rect-like" without you needing to call `.rect()`
27
+ yourself.
28
+
29
+ ```js
30
+ let hitbox = new Rect(10, 20, 40, 30);
31
+ let same = new Rect(hitbox); // copy via any accepted shape
32
+ let fromActor = new Rect(player); // works because Actor has .rect()
33
+ ```
34
+
35
+ ## Properties
36
+
37
+ All of these read or write the rectangle in place; setting a position
38
+ property moves the rectangle without changing its size, and setting `width`,
39
+ `height`, `w`, `h`, or `size` resizes it.
40
+
41
+ | Property | Meaning |
42
+ | -------------------------------------------------- | --------------------------------- |
43
+ | `left`, `top`, `width`, `height` | The four base fields. |
44
+ | `x`, `y`, `w`, `h` | Aliases for the same. |
45
+ | `right`, `bottom` | `left + width`, `top + height`. |
46
+ | `centerX`, `centerY` | Center point, one axis at a time. |
47
+ | `topLeft`, `topRight`, `bottomLeft`, `bottomRight` | Corners, as `[x, y]`. |
48
+ | `midTop`, `midLeft`, `midRight`, `midBottom` | Edge midpoints, as `[x, y]`. |
49
+ | `center` | `[centerX, centerY]`. |
50
+ | `size` | `[width, height]`. |
51
+
52
+ `Rect` also supports index access (`rect[0]` through `rect[3]` for
53
+ `left`/`top`/`width`/`height`) and spreading/iteration
54
+ (`[...rect]` → `[left, top, width, height]`, `Array.from(rect)`), so it can
55
+ be dropped into APIs that expect a plain tuple.
56
+
57
+ ```js
58
+ hitbox.center = [100, 80]; // moves it; width/height unchanged
59
+ hitbox.size = [64, 64]; // resizes it in place
60
+ let [left, top, width, height] = hitbox;
61
+ ```
62
+
63
+ ## Copying and moving
64
+
65
+ - `copy(): Rect`
66
+ - `move(x, y)` / `move([x, y])` → new `Rect`; `moveIp(...)` moves in place.
67
+ - `inflate(x, y)` / `inflate([x, y])` → new `Rect`, grown by `x`/`y` around
68
+ its center (negative shrinks); `inflateIp(...)` mutates in place.
69
+ - `normalize()` — flips a negative `width`/`height` so the rectangle has a
70
+ well-defined top-left corner (mutates in place).
71
+
72
+ ## Set operations
73
+
74
+ Each but `fit` has a mutating `…Ip` counterpart that applies the result back
75
+ onto the rectangle itself instead of returning a new one:
76
+
77
+ - `clamp(other)` / `clampIp(other)` — moves (without resizing) to fit
78
+ entirely inside `other`, centering on whichever axis doesn't fit.
79
+ - `clip(other)` / `clipIp(other)` — the overlapping area of this rect and
80
+ `other` (zero-sized if they don't overlap).
81
+ - `union(other)` / `unionIp(other)` — the smallest rect containing both.
82
+ - `unionAll(others)` / `unionAllIp(others)` — union across an array of
83
+ rect-likes.
84
+ - `fit(other)` — scales (preserving aspect ratio) and centers this rect to
85
+ fit inside `other`.
86
+
87
+ ```js
88
+ let hitbox = new Rect(300, 60, 40, 40);
89
+ hitbox.clampIp(screen.bounds()); // now fully on screen
90
+ ```
91
+
92
+ `Actor` has its own `clampIp`, which moves the actor itself:
93
+ `player.clampIp(screen.bounds())` keeps the player on screen. (Calling
94
+ `player.rect().clampIp(...)` would only move a copy of the player's
95
+ rectangle, not the player.)
96
+
97
+ ## Collision tests
98
+
99
+ Collision uses **half-open bounds**: the left and top edges are inclusive,
100
+ the right and bottom edges are exclusive — a point exactly on the right or
101
+ bottom edge does not count as colliding. This matches pygame's `Rect`.
102
+
103
+ - `touches(target): boolean` — the one test most games need: `target` is an
104
+ `[x, y]` point (does the rect contain it?) or any rect-like value, such as
105
+ another `Rect` or an `Actor` (do they overlap?).
106
+ - `contains(other): boolean`
107
+ - `collidePoint(point)` / `collidePoint(x, y): boolean`
108
+ - `collideRect(other): boolean`
109
+ - `collideList(others): number` — index of the first colliding rect-like in
110
+ the array, or `-1`.
111
+ - `collideListAll(others): number[]` — indexes of every colliding entry.
112
+ - `collideDict(dict, useValues = true)` — `dict` is a `Map` or plain object;
113
+ returns the first `[key, value]` entry whose value (or key, if
114
+ `useValues` is `false`) collides with this rect, or `undefined`.
115
+ - `collideDictAll(dict, useValues = true)` — same, but returns every
116
+ matching `[key, value]` entry as an array.
117
+
118
+ ```js
119
+ let enemies = { goblin: goblinRect, bat: batRect };
120
+ let hit = player.rect().collideDict(enemies);
121
+ if (hit) console.log(`hit the ${hit[0]}`);
122
+ ```
123
+
124
+ ## Standalone helpers
125
+
126
+ `angleTo(from, to)` and `distanceTo(from, to)` are exported functions (used
127
+ internally by `Actor.angleTo`/`distanceTo`) if you need the same math on
128
+ plain points without an `Actor`. They aren't globals in a game file; import
129
+ them from `js-game-zero`.