Open in a new tab

A one-minute rail shooter drawn entirely in SVG. A dusk flight over a teal grid: the player's ship flies into the screen, drones come in waves and fire slow orbs, amber pylons stand in the lane, and after about 50 seconds the Warden, a large core inside a turning ring, holds the lane until it is destroyed. The lasers fire on their own. Steer with the arrow keys or WASD, or drag on the scene; an autopilot flies the attract mode until you take over.

Uses @awacloud/graphic-anim (Apache-2.0). This example's code is Apache-2.0.

When to use it

A model for a real-time SVG scene that must stay cheap: a game, a simulation, a live visualisation. The scene is built once and a frame only writes attributes, so it also shows the pattern for any animation too busy for one tween per element.

Copy-paste steps

  1. npm install @awacloud/fw @awacloud/graphic-anim
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ and node_modules/@awacloud/graphic-anim/src/ at /vendor/graphic-anim/ (node serve.js from the examples root does both; any static server works).
  3. Copy the whole folder: index.html, style.css and main.js next to each other, with the other .js files listed in example.json in src/, and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • The scene is one graphic.svgBuild template, built once. Every sprite (bolts, drones, orbs, pylons, sparks) comes from a pool created at build time; a frame only writes attributes, through a small cache that skips values that did not change. No node is created while the game runs.
  • The loop is one tickable on the package's shared scheduler (graphic.scheduler). The game steps in fixed 1/60 s increments, so a run plays the same on every machine, and advance(ms) steps it without a clock. Every random draw is seeded.
  • graphic.timeline and its tweens animate the HUD only: the wave banners, the damage flash and the Warden's bar.
  • The perspective and the rotations come from the svg3d kernels that graphic.svg3d registers (svg3d.vec3, svg3d.project), resolved by name after fw.runtime.registerAllDeep(graphicModules).
  • Steering uses fw: events for the keys (arrows, WASD, AZERTY) and gesture (pan) for the drag. Touching either takes the wheel from the attract-mode autopilot; "Watch the autopilot" forces it on for a full run.
  • The code is split by responsibility, under src/: constants.js, script.js (the run's waves), scenery.js / sprites.js / hud.js (the template), state.js, step.js with enemies.js, boss.js and autopilot.js (the simulation), render.js with render-sprites.js (the frame), input.js, handle.js and game.js (the wiring). main.js only mounts it and wires the buttons.
  • Limits: the run, the waves and the numbers are fixed; there is no difficulty setting, no high score and no sound. The page has no readout beyond the in-scene HUD, and with reduced motion on the game waits for Fly or the autopilot.

Code

main.js

javascriptApache-2.062 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { events } from '@awacloud/fw/dom/query/events.js';
import { gesture } from '@awacloud/fw/dom/query/gesture.js';
import { graphicModules } from '@awacloud/graphic-anim';
import { createGame } from './src/game.js';

// graphic.svg3d registers its kernels (svg3d.vec3, svg3d.project), which the game uses for the perspective.
fw.runtime.registerAllDeep([events, gesture, ...graphicModules]);
const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));
let instance = 0;

/**
 * Build the game into the `<svg>` `mount` and wire the page controls. The attract mode (the autopilot) flies at
 * once unless the reader prefers reduced motion; Fly hands the ship to the keys and the drag.
 * @param {SVGElement} mount
 */
export function mountRail(mount) {
    const game = createGame({
        mount,
        graphic: fw.runtime.resolve('graphic.anim'),
        kernels: { vec3: fw.runtime.resolve('svg3d.vec3'), project: fw.runtime.resolve('svg3d.project') },
        input: { events: fw.runtime.resolve('events'), gesture: fw.runtime.resolve('gesture') },
        id: instance++,
    });
    const reduced = Boolean(globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches);
    let paused = reduced;
    const sync = () => { el('pause').textContent = paused ? 'Resume' : 'Pause'; };
    const begin = (/** @type {boolean} */ autopilot) => {
        game.start({ autopilot, force: autopilot });
        game.play();
        paused = false;
        sync();
    };
    const onFly = () => begin(false);
    const onAuto = () => begin(true);
    const onPause = () => {
        paused = !paused;
        (paused ? game.pause : game.play)();
        sync();
    };
    const onEnter = (/** @type {KeyboardEvent} */ e) => { if (e.key === 'Enter' && game.state !== 'flying') onFly(); };
    el('fly').addEventListener('click', onFly);
    el('auto').addEventListener('click', onAuto);
    el('pause').addEventListener('click', onPause);
    document.addEventListener('keydown', onEnter);
    if (reduced) el('motion-note').hidden = false;
    else { game.start({ autopilot: true }); game.play(); }
    sync();
    return {
        game,
        dispose() {
            for (const [id, fn] of [['fly', onFly], ['auto', onAuto], ['pause', onPause]]) {
                el(id).removeEventListener('click', fn);
            }
            document.removeEventListener('keydown', onEnter);
            game.dispose();
        },
    };
}

export const rail = mountRail(/** @type {SVGElement} */ (document.getElementById('mount')));

index.html

htmlApache-2.034 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>graphic-anim · A rail shooter in SVG</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <link rel="stylesheet" href="./style.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
    "@awacloud/graphic-anim": "/vendor/graphic-anim/main.js", "@awacloud/graphic-anim/": "/vendor/graphic-anim/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>A rail shooter in SVG</h1>
    <p>Fly the Kite down a dusk lane: drones come in waves, pylons stand in the way, and the Warden waits at the
    end of a one-minute run. The lasers fire on their own. The scene is built once; each frame only moves pooled
    sprites.</p>
    <svg id="mount" viewBox="0 0 1600 900" role="img"
         aria-label="Lumen Rail: a ship flies over a grid toward drones and pylons"></svg>
    <p class="controls">
      <button id="fly" type="button">Fly (Enter)</button>
      <button id="auto" type="button">Watch the autopilot</button>
      <button id="pause" type="button">Pause</button>
      <span class="keys">Steer: arrow keys / WASD, or drag on the scene.</span>
    </p>
    <p id="motion-note" hidden>Reduced motion is on: the game waits for Fly or the autopilot.</p>
  </main>
</body>
</html>

src/constants.js

javascriptApache-2.066 lines

// SPDX-License-Identifier: Apache-2.0
// The game's fixed numbers, its palette, its two meshes and the seeded generator.

/** Screen (SVG user units), 16:9, and the horizon line. */
export const W = 1600;
export const H = 900;
export const HORIZON = 380;
/** The palette: a dusk sky, a teal grid, amber accents. */
export const C = {
    night: '#0B1026', dusk: '#2A1846', rose: '#6B2F4F', amber: '#F2A541',
    ground: '#0A0F1C', teal: '#2BD1C4', ship: '#F5F1E8', shipDark: '#9AA3B5',
    orb: '#FF5A7A', bolt: '#FFE6A8', warden: '#8C6CFF', ridge: '#140D26',
};

/** World (y up, z away from the camera). */
export const GROUND_Y = -150;
/** The camera's eye height: the ship flies below it, in the lower part of the frame. */
export const EYE = 90;
/** The ship's depth; sprites retire once they are this far behind it. */
export const SHIP_Z = 230;
export const RETIRE_Z = SHIP_Z - 70;
export const SPAWN_Z = 2600;
/** World units per ms, toward the camera. */
export const SPEED = 0.85;
export const LANE_X = 260;
export const LANE_Y = [-110, 120];
/** The fixed simulation step, ms. */
export const STEP = 1000 / 60;
/** Ship speed in units per ms, x and y. */
export const SHIP_SPEED = [0.5, 0.4];
export const FIRE_EVERY = 120;
export const BOLT_SPEED = 2.6;
export const BOSS_AT = 47000;
export const BOSS_HP = 60;

/** Pool sizes: every sprite is built once, a frame only writes attributes. */
export const N = { bolts: 18, drones: 12, orbs: 16, pylons: 10, sparks: 48 };

/** The Kite: nose, two wings, a tail fin above and below. */
export const KITE = {
    v: [[0, 0, 62], [-52, -6, -18], [52, -6, -18], [0, 15, -24], [0, -11, -24]],
    upper: [[0, 1, 3], [0, 3, 2]],
    lower: [[0, 1, 4], [0, 4, 2]],
};
/** An octahedron of radius 1 (drones and the Warden's core). */
export const OCTA = {
    v: [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]],
    f: [[0, 2, 4], [2, 1, 4], [1, 3, 4], [3, 0, 4], [2, 0, 5], [1, 2, 5], [3, 1, 5], [0, 3, 5]],
};

/**
 * A seeded linear congruential generator (32-bit): drawn at build time and on
 * game events, never from the clock, so a run plays the same everywhere.
 * @param {number} seed
 * @returns {() => number}
 */
export function rng(seed) {
    let s = seed >>> 0;
    return () => {
        s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
        return s / 4294967296;
    };
}

/** @param {number} n @returns {string} */
export const f1 = (n) => (Math.round(n * 10) / 10).toString();

src/script.js

javascriptApache-2.050 lines

// SPDX-License-Identifier: Apache-2.0
import { BOSS_AT } from './constants.js';

/**
 * The run: a script of waves, pylons and banners in game time (ms), about
 * 50 s long, ending with the Warden.
 * @returns {{ t: number, kind: string }[]} The script, sorted by time.
 */
export function script() {
    const out = [];
    const banner = (t, text) => out.push({ t, kind: 'banner', text });
    const pylons = (t, xs) => xs.forEach((x) => out.push({ t, kind: 'pylon', x }));
    const wave = (t, shape, n, opts = {}) => {
        const { y = 10, pattern = 'still', fire = true, span = 420, gap = 0 } = opts;
        for (let i = 0; i < n; i += 1) {
            const u = n === 1 ? 0 : i / (n - 1) - 0.5;
            let x = u * span;
            let yy = y;
            let dt = gap * i;
            if (shape === 'v') { dt = Math.abs(u) * 900; yy = y + Math.abs(u) * 80; }
            if (shape === 'arc') yy = y + 70 * Math.cos(u * Math.PI);
            if (shape === 'columns') { x = (i % 2 ? 1 : -1) * span / 2; dt = Math.floor(i / 2) * 700; }
            out.push({ t: t + dt, kind: 'drone', x, y: yy, pattern, fire });
        }
    };
    banner(800, 'WAVE 1');
    wave(1500, 'line', 5, { fire: false });
    pylons(4500, [-170, 170]);
    wave(6500, 'v', 5, { pattern: 'sine' });
    pylons(8200, [0]);
    pylons(9500, [-220, -60]);
    pylons(10700, [60, 220]);
    banner(12000, 'WAVE 2');
    wave(12500, 'arc', 6, { pattern: 'swoop' });
    wave(15500, 'line', 5, { y: 80 });
    [-100, 100, -100, 100].forEach((x, i) => pylons(18000 + i * 1000, [x]));
    wave(22500, 'columns', 6, { span: 360 });
    banner(26000, 'WAVE 3');
    wave(26500, 'v', 7, { pattern: 'sine', span: 480 });
    pylons(29000, [-200, 0, 200]);
    wave(31000, 'line', 6, { y: -60 });
    wave(34000, 'arc', 6, { pattern: 'swoop' });
    pylons(36500, [-120, 120]);
    wave(38000, 'v', 7, { pattern: 'sine', span: 480 });
    wave(41000, 'line', 6, { pattern: 'sine', y: 40 });
    pylons(44000, [-200, -60, 60, 200]);
    banner(45500, 'WARNING — WARDEN');
    out.push({ t: BOSS_AT, kind: 'boss' });
    return out.sort((a, b) => a.t - b.t);
}

src/dom.js

javascriptApache-2.031 lines

// SPDX-License-Identifier: Apache-2.0

/** @param {Element} root @returns {Map<string, Element>} `data-id` to element, bound once. */
export function indexByDataId(root) {
    return new Map([...root.querySelectorAll('[data-id]')].map((node) => [node.getAttribute('data-id'), node]));
}

/**
 * The frame's writers. Attribute writes go through a cache, so a frame writes
 * only what changed; text goes through the element's own text node, so no
 * node is created per frame.
 * @param {(node: Element, name: string, value: string) => void} attr the graphic engine's attribute writer
 */
export function createWriters(attr) {
    const cache = new Map();
    const set = (/** @type {Element} */ node, /** @type {string} */ name, /** @type {any} */ value) => {
        const s = String(value);
        let m = cache.get(node);
        if (!m) { m = new Map(); cache.set(node, m); }
        if (m.get(name) === s) return;
        m.set(name, s);
        attr(node, name, s);
    };
    const show = (/** @type {Element} */ node, /** @type {boolean} */ on) =>
        set(node, 'display', on ? 'inline' : 'none');
    const text = (/** @type {Element} */ node, /** @type {string} */ value) => {
        const t = /** @type {any} */ (node.firstChild);
        if (t && t.data !== value) t.data = value;
    };
    return { set, show, text };
}

src/scenery.js

javascriptApache-2.068 lines

// SPDX-License-Identifier: Apache-2.0
import { C, H, HORIZON, W, f1 } from './constants.js';

/** @param {number} n @param {(i: number) => object} make */
export const pool = (n, make) => Array.from({ length: n }, (_, i) => make(i));

const stop = (/** @type {string} */ offset, /** @type {string} */ color) => ({
    tag: 'stop', attrs: { offset, 'stop-color': color },
});
const gradient = (/** @type {string} */ id, /** @type {object[]} */ stops) => ({
    tag: 'linearGradient', attrs: { id, x1: 0, y1: 0, x2: 0, y2: 1 }, children: stops,
});

function defs() {
    return {
        tag: 'defs',
        children: [
            gradient('sky', [stop('0%', C.night), stop('68%', C.dusk), stop('92%', C.rose), stop('100%', C.amber)]),
            gradient('ground', [stop('0%', '#1B1530'), stop('30%', C.ground)]),
            {
                tag: 'filter', attrs: { id: 'glow', x: '-50%', y: '-50%', width: '200%', height: '200%' },
                children: [{ tag: 'feGaussianBlur', attrs: { stdDeviation: 3 } }],
            },
        ],
    };
}

/** The ridge line of the far mountains: a seeded path along the horizon. */
function ridge(/** @type {() => number} */ rand) {
    let d = `M0 ${HORIZON}`;
    for (let x = 0; x <= W; x += 40) {
        const y = HORIZON - 18 - 46 * Math.abs(Math.sin(x / 210 + rand() * 0.6)) - rand() * 14;
        d += ` L${x} ${f1(y)}`;
    }
    return `${d} L${W} ${HORIZON} Z`;
}

/**
 * The static scenery, back to front: sky, ridge, ground, the grid (lateral
 * lines and scrolling rows, placed per frame) and the horizon line.
 * @param {() => number} rand
 */
export function scenery(rand) {
    const rect = (/** @type {number} */ y, /** @type {number} */ height, /** @type {string} */ fill) => ({
        tag: 'rect', attrs: { x: 0, y, width: W, height, fill },
    });
    return [
        defs(),
        rect(0, HORIZON, 'url(#sky)'),
        { tag: 'path', attrs: { d: ridge(rand), fill: C.ridge } },
        rect(HORIZON, H - HORIZON, 'url(#ground)'),
        {
            tag: 'g', attrs: { stroke: C.teal, 'stroke-width': 1.2 },
            children: [
                ...pool(15, (i) => ({ tag: 'line', attrs: { 'data-id': `lat${i}`, 'stroke-opacity': 0.32 } })),
                ...pool(12, (i) => ({
                    tag: 'line', attrs: { 'data-id': `row${i}`, x1: 0, x2: W, 'stroke-opacity': 0 },
                })),
            ],
        },
        {
            tag: 'line',
            attrs: {
                x1: 0, y1: HORIZON, x2: W, y2: HORIZON, stroke: C.amber, 'stroke-width': 1.5, 'stroke-opacity': 0.75,
            },
        },
    ];
}

src/sprites.js

javascriptApache-2.062 lines

// SPDX-License-Identifier: Apache-2.0
import { C, N } from './constants.js';
import { pool } from './scenery.js';

const HIDDEN = { display: 'none' };
/** @param {string} id @param {object} attrs */
const path = (id, attrs) => ({ tag: 'path', attrs: { 'data-id': id, ...attrs } });
/** @param {string} id @param {object} attrs */
const circle = (id, attrs) => ({ tag: 'circle', attrs: { 'data-id': id, ...attrs } });
const ROUND = { 'stroke-linejoin': 'round' };

/** The Kite: a glowing engine under two shaded wing halves. */
function ship() {
    const wing = { 'stroke-width': 1.2, 'stroke-linejoin': 'round', stroke: C.ship };
    return {
        tag: 'g', attrs: { 'data-id': 'ship' },
        children: [
            circle('engine', { r: 9, fill: C.amber, filter: 'url(#glow)' }),
            path('shipLower', { fill: C.shipDark, ...wing }),
            path('shipUpper', { fill: C.ship, ...wing }),
        ],
    };
}

/** The Warden: a turning ring around a large core. */
function boss() {
    return {
        tag: 'g', attrs: { 'data-id': 'boss', ...HIDDEN },
        children: [
            path('ring', { fill: C.warden, 'fill-opacity': 0.18, stroke: C.warden, 'stroke-width': 2 }),
            path('core', { fill: C.amber, 'fill-opacity': 0.35, stroke: C.amber, 'stroke-width': 2, ...ROUND }),
        ],
    };
}

/**
 * Every sprite, from a pool built once: pylons, the Warden, drones, orbs (a
 * glowing halo and a core), bolts, sparks, then the ship on top.
 */
export function sprites() {
    const pylon = { fill: C.amber, 'fill-opacity': 0.22, stroke: C.amber, 'stroke-width': 1.5, ...HIDDEN };
    const drone = { fill: C.teal, 'fill-opacity': 0.16, stroke: C.teal, 'stroke-width': 1.6, ...ROUND, ...HIDDEN };
    return [
        { tag: 'g', children: pool(N.pylons, (i) => path(`pylon${i}`, pylon)) },
        boss(),
        { tag: 'g', children: pool(N.drones, (i) => path(`drone${i}`, drone)) },
        {
            tag: 'g', attrs: { filter: 'url(#glow)' },
            children: pool(N.orbs, (i) => circle(`orb${i}`, { fill: C.orb, ...HIDDEN })),
        },
        { tag: 'g', children: pool(N.orbs, (i) => circle(`orbCore${i}`, { fill: '#FFE3EA', ...HIDDEN })) },
        {
            tag: 'g', attrs: { stroke: C.bolt, 'stroke-linecap': 'round' },
            children: pool(N.bolts, (i) => ({ tag: 'line', attrs: { 'data-id': `bolt${i}`, ...HIDDEN } })),
        },
        {
            tag: 'g',
            children: pool(N.sparks, (i) => circle(`spark${i}`, { r: 3, fill: i % 3 ? C.amber : C.teal, ...HIDDEN })),
        },
        ship(),
    ];
}

src/hud.js

javascriptApache-2.055 lines

// SPDX-License-Identifier: Apache-2.0
import { C, H, W } from './constants.js';
import { scenery } from './scenery.js';
import { sprites } from './sprites.js';

const MONO = 'Consolas, Menlo, "DejaVu Sans Mono", monospace';
const label = (/** @type {object} */ attrs, /** @type {string} */ text, /** @type {string} */ id = '') => ({
    tag: 'text', attrs: id ? { 'data-id': id, ...attrs } : attrs, text,
});
const box = (/** @type {object} */ attrs) => ({ tag: 'rect', attrs });

/** The heads-up display: score, shield bar, the Warden's bar, banners, the mode label. */
function hud() {
    const mid = W / 2;
    return {
        tag: 'g', attrs: { 'font-family': MONO, fill: C.ship },
        children: [
            label({ x: 40, y: 56, 'font-size': 18, opacity: 0.7 }, 'SCORE'),
            label({ x: 40, y: 92, 'font-size': 34 }, '000000', 'score'),
            label({ x: 40, y: H - 70, 'font-size': 18, opacity: 0.7 }, 'SHIELD'),
            box({ x: 40, y: H - 58, width: 300, height: 14, fill: 'none', stroke: C.ship, 'stroke-opacity': 0.5 }),
            box({ 'data-id': 'shieldBar', x: 42, y: H - 56, width: 296, height: 10, fill: C.teal }),
            {
                tag: 'g', attrs: { 'data-id': 'bossBar', opacity: 0 },
                children: [
                    label({ x: mid, y: 46, 'font-size': 16, 'text-anchor': 'middle', fill: C.warden }, 'WARDEN'),
                    box({ x: mid - 200, y: 56, width: 400, height: 10, fill: 'none', stroke: C.warden }),
                    box({ 'data-id': 'bossFill', x: mid - 198, y: 58, width: 396, height: 6, fill: C.warden }),
                ],
            },
            label({
                x: mid, y: 250, 'font-size': 54, 'text-anchor': 'middle', 'letter-spacing': 8, opacity: 0,
            }, ' ', 'banner'),
            label({ x: mid, y: 330, 'font-size': 30, 'text-anchor': 'middle', opacity: 0 }, ' ', 'message'),
            label({ x: W - 40, y: 56, 'font-size': 16, 'text-anchor': 'end', opacity: 0.7 }, ' ', 'mode'),
        ],
    };
}

/**
 * The whole game as one `svgBuild` template.
 * @param {() => number} rand
 */
export function design(rand) {
    return {
        tag: 'svg',
        attrs: { x: 0, y: 0, width: '100%', height: '100%', viewBox: `0 0 ${W} ${H}` },
        children: [
            ...scenery(rand),
            ...sprites(),
            box({ 'data-id': 'flash', x: 0, y: 0, width: W, height: H, fill: C.orb, opacity: 0 }),
            hud(),
        ],
    };
}

src/projection.js

javascriptApache-2.031 lines

// SPDX-License-Identifier: Apache-2.0
import { EYE, H, HORIZON, W, f1 } from './constants.js';

/**
 * The perspective: world to screen, and the faces of a mesh drawn as one path.
 * The camera and the rotation come from the svg3d kernels (`svg3d.project`,
 * `svg3d.vec3`); `screen = offset + depth * p / z`.
 * @param {any} vec3 the `svg3d.vec3` kernel
 * @param {any} project the `svg3d.project` kernel
 */
export function createProjection(vec3, project) {
    const camera = project.createCamera({ width: W, height: H, depth: 640, near: 40 });
    const F = camera.depth;
    const sx = (/** @type {number} */ x, /** @type {number} */ z) => camera.offsetX + (F * x) / z;
    const sy = (/** @type {number} */ y, /** @type {number} */ z) => HORIZON - (F * (y - EYE)) / z;
    const m = new Float64Array(9);
    const out = new Float64Array(3);

    /** Faces of a mesh, rotated, scaled, placed, projected; one subpath per face. */
    function faces(/** @type {any} */ mesh, /** @type {number[][]} */ list, /** @type {number} */ scale,
        /** @type {number[]} */ [px, py, pz], /** @type {number[]} */ [rx, ry, rz]) {
        vec3.rotationMatrix3(rx, ry, rz, m);
        const pts = mesh.v.map(([x, y, z]) => {
            vec3.applyMatrix3(m, x * scale, y * scale, z * scale, out);
            const wz = pz + out[2];
            return `${f1(sx(px + out[0], wz))} ${f1(sy(py + out[1], wz))}`;
        });
        return list.map(([a, b, c]) => `M${pts[a]} L${pts[b]} L${pts[c]} Z`).join(' ');
    }
    return { F, sx, sy, faces };
}

src/state.js

javascriptApache-2.034 lines

// SPDX-License-Identifier: Apache-2.0
import { BOSS_HP, N, SPAWN_Z, rng } from './constants.js';

/**
 * The pools (built once, a sprite is "active" or not), the Warden and the
 * run's state. Sprites are plain records bound to their SVG node.
 * @param {Map<string, Element>} el the scene's elements by `data-id`
 */
export function createState(el) {
    /** @param {number} n @param {string} prefix @param {(i: number) => object} extra */
    const mk = (n, prefix, extra) => Array.from({ length: n }, (_, i) => ({
        node: el.get(`${prefix}${i}`), active: false, x: 0, y: 0, z: 0, ...extra(i),
    }));
    return {
        bolts: mk(N.bolts, 'bolt', () => ({})),
        drones: mk(N.drones, 'drone', () => ({
            bx: 0, by: 0, pattern: 'still', fire: false, fired: false, born: 0, spin: 0,
        })),
        orbs: mk(N.orbs, 'orb', (i) => ({ core: el.get(`orbCore${i}`), vx: 0, vy: 0, vz: 0 })),
        pylons: mk(N.pylons, 'pylon', () => ({ hit: false })),
        sparks: mk(N.sparks, 'spark', () => ({ vx: 0, vy: 0, vz: 0, life: 0 })),
        boss: { active: false, x: 0, y: 30, z: SPAWN_Z, hp: BOSS_HP, fireT: 1500, spin: 0, dead: false },
        S: {
            state: 'ready', autopilot: false, forced: false, attract: false, t: 0, score: 0, shield: 100,
            ship: { x: 0, y: -20, vx: 0, vy: 0 }, fireT: 0, wing: 1, reachedBoss: false,
            next: 0, endAt: 0, rand: rng(0x7261696c),
        },
        keys: new Set(),
        pan: { dx: 0, dy: 0 },
    };
}

/** The first free sprite of a pool, or null when every one is in flight. */
export const take = (/** @type {any[]} */ pool) => pool.find((o) => !o.active) || null;

src/fx.js

javascriptApache-2.045 lines

// SPDX-License-Identifier: Apache-2.0
// The HUD's animations (graphic.timeline), released when they settle, and the run's state label.

/** Run one short timeline; it leaves the live set when it settles. `g.live` lets dispose stop them. */
export function animate(/** @type {any} */ g, /** @type {(tl: any) => void} */ build) {
    const tl = new g.timeline.Timeline({ onSettle: () => g.live.delete(tl) });
    build(tl);
    g.live.add(tl);
    tl.play();
}

export function banner(/** @type {any} */ g, /** @type {string} */ label) {
    const node = g.el.get('banner');
    g.text(node, label);
    animate(g, (tl) => {
        tl.add({ target: node, property: 'opacity', from: 0, to: 1, duration: 220, easing: 'ease-out' }, 0);
        tl.add({
            target: node, property: 'letter-spacing', from: 22, to: 8, duration: 500,
            easing: 'cubic-bezier(0.2, 0, 0, 1)',
        }, 0);
        tl.add({ target: node, property: 'opacity', from: 1, to: 0, duration: 450, easing: 'ease-in' }, 1500);
    });
}

/** The damage flash: the whole screen, rose, fading out. */
export function flash(/** @type {any} */ g) {
    animate(g, (tl) => tl.add({
        target: g.el.get('flash'), property: 'opacity', from: 0.28, to: 0, duration: 260, easing: 'ease-out',
    }, 0));
}

/** The Warden's bar fades in, a little after its banner. */
export function bossBarIn(/** @type {any} */ g) {
    animate(g, (tl) => tl.add({
        target: g.el.get('bossBar'), property: 'opacity', from: 0, to: 1, duration: 600, easing: 'ease-out',
    }, 400));
}

/** A state change (`flying`, `down`, `clear`), with the message it shows. */
export function setState(/** @type {any} */ g, /** @type {string} */ state, /** @type {string} [message] */ message) {
    g.S.state = state;
    g.text(g.el.get('message'), message || ' ');
    g.set(g.el.get('message'), 'opacity', message ? 1 : 0);
    if (g.onState) g.onState(state);
}

src/events.js

javascriptApache-2.057 lines

// SPDX-License-Identifier: Apache-2.0
import { BOSS_HP, GROUND_Y, SHIP_Z, SPAWN_Z, SPEED } from './constants.js';
import { banner, bossBarIn, flash, setState } from './fx.js';
import { take } from './state.js';

/** A burst of `n` sparks from a point, thrown with `power`. */
export function burst(g, x, y, z, n, power) {
    for (let k = 0; k < n; k += 1) {
        const s = take(g.sparks);
        if (!s) return;
        const rand = g.S.rand;
        const a = rand() * Math.PI * 2;
        const b = (rand() - 0.5) * Math.PI;
        const v = power * (0.3 + rand() * 0.7);
        Object.assign(s, {
            active: true, x, y, z, life: 420 + rand() * 300,
            vx: Math.cos(a) * Math.cos(b) * v, vy: Math.sin(b) * v, vz: Math.sin(a) * Math.cos(b) * v,
        });
    }
}

/** An orb aimed at where the ship is now. */
export function fireOrb(g, x, y, z, aimX, aimY) {
    const o = take(g.orbs);
    if (!o) return;
    const vz = SPEED * 1.5;
    const tt = (z - SHIP_Z) / vz;
    Object.assign(o, { active: true, x, y, z, vx: (aimX - x) / tt, vy: (aimY - y) / tt, vz });
}

export function damage(g, n) {
    const { S } = g;
    S.shield = Math.max(0, S.shield - n);
    flash(g);
    if (S.shield === 0 && S.state === 'flying') setState(g, 'down', `SHIELD DOWN — SCORE ${S.score}`);
}

/** One scripted event: a banner, a pylon, a drone or the Warden. */
export function apply(g, ev) {
    if (ev.kind === 'banner') banner(g, ev.text);
    else if (ev.kind === 'pylon') {
        const p = take(g.pylons);
        if (p) Object.assign(p, { active: true, x: ev.x, y: GROUND_Y, z: SPAWN_Z, hit: false });
    } else if (ev.kind === 'drone') {
        const d = take(g.drones);
        if (d) {
            Object.assign(d, {
                active: true, bx: ev.x, by: ev.y, x: ev.x, y: ev.y, z: SPAWN_Z,
                pattern: ev.pattern, fire: ev.fire, fired: false, born: g.S.t, spin: g.S.rand() * 6,
            });
        }
    } else if (ev.kind === 'boss') {
        Object.assign(g.boss, { active: true, x: 0, y: 30, z: SPAWN_Z, hp: BOSS_HP, fireT: 2500, dead: false });
        g.S.reachedBoss = true;
        bossBarIn(g);
    }
}

src/autopilot.js

javascriptApache-2.071 lines

// SPDX-License-Identifier: Apache-2.0
import { LANE_X, LANE_Y, SHIP_SPEED, SHIP_Z } from './constants.js';

/** @param {number} v @param {number} lo @param {number} hi */
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

/** The nearest threat in the lane: a pylon or an orb about to reach the ship, or null. */
function threat(g) {
    const sh = g.S.ship;
    let danger = null;
    for (const p of g.pylons) {
        const near = p.active && p.z > SHIP_Z && p.z < SHIP_Z + 900;
        if (near && Math.abs(p.x - sh.x) < 70) danger = { x: p.x, z: p.z, w: 70 };
    }
    for (const o of g.orbs) {
        if (!o.active || o.z <= SHIP_Z || o.z >= SHIP_Z + 700) continue;
        const tt = (o.z - SHIP_Z) / o.vz;
        const ox = o.x + o.vx * tt;
        const oy = o.y + o.vy * tt;
        if (Math.abs(ox - sh.x) < 46 && Math.abs(oy - sh.y) < 46) danger = { x: ox, y: oy, z: o.z, w: 46 };
    }
    return danger;
}

/** Where the autopilot wants the ship: away from a threat, else under the nearest target. */
export function autopilotGoal(g) {
    const sh = g.S.ship;
    const danger = threat(g);
    if (danger) {
        // The free x farthest from every near pylon, close to the ship.
        let best = sh.x;
        let bestScore = -Infinity;
        for (let x = -LANE_X; x <= LANE_X; x += 20) {
            let clear = Infinity;
            for (const p of g.pylons) {
                if (p.active && p.z > SHIP_Z && p.z < SHIP_Z + 1100) clear = Math.min(clear, Math.abs(p.x - x));
            }
            if (danger.w === 46) clear = Math.min(clear, Math.abs(danger.x - x) * 1.5);
            const score = Math.min(clear, 200) - Math.abs(x - sh.x) * 0.25;
            if (score > bestScore) { bestScore = score; best = x; }
        }
        return { x: best, y: danger.y !== undefined ? (danger.y > sh.y ? LANE_Y[0] + 20 : sh.y) : sh.y };
    }
    let target = null;
    for (const d of g.drones) if (d.active && d.z > SHIP_Z + 150 && (!target || d.z < target.z)) target = d;
    const { boss } = g;
    if (boss.active && !boss.dead && (!target || boss.z < target.z)) target = boss;
    return target ? { x: target.x, y: target.y } : { x: 0, y: -20 };
}

/** Move the ship for `dt` ms: the autopilot, or the keys, plus any drag. */
export function steer(g, dt) {
    const sh = g.S.ship;
    let ax;
    let ay;
    if (g.S.autopilot) {
        const goal = autopilotGoal(g);
        ax = clamp((goal.x - sh.x) / 40, -1, 1);
        ay = clamp((goal.y - sh.y) / 40, -1, 1);
    } else {
        const { keys } = g;
        ax = (keys.has('right') ? 1 : 0) - (keys.has('left') ? 1 : 0);
        ay = (keys.has('up') ? 1 : 0) - (keys.has('down') ? 1 : 0);
    }
    sh.vx = ax * SHIP_SPEED[0];
    sh.vy = ay * SHIP_SPEED[1];
    sh.x = clamp(sh.x + sh.vx * dt + g.pan.dx * 0.55, -LANE_X, LANE_X);
    sh.y = clamp(sh.y + sh.vy * dt - g.pan.dy * 0.45, LANE_Y[0], LANE_Y[1]);
    g.pan.dx = 0;
    g.pan.dy = 0;
}

src/enemies.js

javascriptApache-2.066 lines

// SPDX-License-Identifier: Apache-2.0
import { RETIRE_Z, SHIP_Z, SPEED } from './constants.js';
import { burst, damage, fireOrb } from './events.js';

/** Drones: their pattern, their one shot, collisions with the ship, hits by bolts. */
export function moveDrones(g, dt) {
    const sh = g.S.ship;
    for (const d of g.drones) {
        if (!d.active) continue;
        const prevZ = d.z;
        d.z -= SPEED * dt;
        const age = g.S.t - d.born;
        if (d.pattern === 'sine') d.x = d.bx + 70 * Math.sin(age / 520);
        if (d.pattern === 'swoop') d.y = d.by - Math.min(120, age * 0.05);
        d.spin += dt * 0.003;
        if (d.fire && !d.fired && d.z < 1500) { d.fired = true; fireOrb(g, d.x, d.y, d.z, sh.x, sh.y); }
        if (prevZ > SHIP_Z && d.z <= SHIP_Z && Math.abs(d.x - sh.x) < 50 && Math.abs(d.y - sh.y) < 40) {
            d.active = false;
            damage(g, 20);
            burst(g, d.x, d.y, SHIP_Z + 40, 8, 0.25);
        }
        if (d.z < RETIRE_Z) d.active = false;
        for (const b of g.bolts) {
            const hit = Math.abs(b.z - d.z) < 70 && Math.abs(b.x - d.x) < 36 && Math.abs(b.y - d.y) < 36;
            if (d.active && b.active && hit) {
                d.active = false;
                b.active = false;
                g.S.score += 100;
                burst(g, d.x, d.y, d.z, 10, 0.3);
            }
        }
    }
}

/** Orbs fly straight at where the ship was when they were fired. */
export function moveOrbs(g, dt) {
    const sh = g.S.ship;
    for (const o of g.orbs) {
        if (!o.active) continue;
        const prevZ = o.z;
        o.x += o.vx * dt;
        o.y += o.vy * dt;
        o.z -= o.vz * dt;
        if (prevZ > SHIP_Z && o.z <= SHIP_Z && Math.abs(o.x - sh.x) < 34 && Math.abs(o.y - sh.y) < 30) {
            o.active = false;
            damage(g, 12);
        }
        if (o.z < RETIRE_Z) o.active = false;
    }
}

/** Pylons stand in the lane and cost shield once, when the ship passes through. */
export function movePylons(g, dt) {
    const sh = g.S.ship;
    for (const p of g.pylons) {
        if (!p.active) continue;
        const prevZ = p.z;
        p.z -= SPEED * dt;
        if (!p.hit && prevZ > SHIP_Z && p.z <= SHIP_Z && Math.abs(p.x - sh.x) < 44) {
            p.hit = true;
            damage(g, 25);
            burst(g, p.x, sh.y, SHIP_Z + 20, 8, 0.25);
        }
        if (p.z < RETIRE_Z) p.active = false;
    }
}

src/boss.js

javascriptApache-2.041 lines

// SPDX-License-Identifier: Apache-2.0
import { SPEED } from './constants.js';
import { burst, fireOrb } from './events.js';
import { flash, setState } from './fx.js';

const HOLD = 1100;

/** The Warden: it holds the lane, fires fans of orbs, takes bolts, and ends the run when destroyed. */
export function moveBoss(g, dt) {
    const { boss, S } = g;
    if (!boss.active) return;
    if (boss.z > HOLD) boss.z = Math.max(HOLD, boss.z - SPEED * dt);
    boss.x = 150 * Math.sin(S.t / 1600);
    boss.y = 30 + 40 * Math.sin(S.t / 1100);
    boss.spin += dt * 0.0012;
    if (!boss.dead && boss.z <= HOLD + 1) {
        boss.fireT -= dt;
        if (boss.fireT <= 0) {
            boss.fireT = 1500;
            for (let k = -2; k <= 2; k += 1) fireOrb(g, boss.x, boss.y, boss.z - 80, S.ship.x + k * 90, S.ship.y);
        }
    }
    for (const b of g.bolts) {
        if (boss.dead || !b.active) continue;
        if (Math.abs(b.z - boss.z) >= 90 || Math.abs(b.x - boss.x) >= 70 || Math.abs(b.y - boss.y) >= 70) continue;
        b.active = false;
        boss.hp -= 1;
        burst(g, b.x, b.y, boss.z - 40, 2, 0.2);
        if (boss.hp <= 0) {
            boss.dead = true;
            S.score += 5000;
            burst(g, boss.x, boss.y, boss.z, 30, 0.6);
            flash(g);
            S.endAt = S.t + 1600;
        }
    }
    if (boss.dead && S.t >= S.endAt) {
        boss.active = false;
        setState(g, 'clear', `RUN CLEAR — SCORE ${S.score}`);
    }
}

src/step.js

javascriptApache-2.051 lines

// SPDX-License-Identifier: Apache-2.0
import { BOLT_SPEED, FIRE_EVERY, RETIRE_Z, SHIP_Z, SPAWN_Z, SPEED } from './constants.js';
import { steer } from './autopilot.js';
import { moveBoss } from './boss.js';
import { moveDrones, moveOrbs, movePylons } from './enemies.js';
import { apply } from './events.js';
import { take } from './state.js';

/** The ship's lasers fire on their own, alternating wings. */
function fireBolts(g, dt) {
    const { S } = g;
    S.fireT -= dt;
    if (S.fireT <= 0) {
        S.fireT += FIRE_EVERY;
        const b = take(g.bolts);
        S.wing = -S.wing;
        if (b) Object.assign(b, { active: true, x: S.ship.x + S.wing * 30, y: S.ship.y - 4, z: SHIP_Z + 30 });
    }
    for (const b of g.bolts) {
        if (!b.active) continue;
        b.z += BOLT_SPEED * dt;
        if (b.z > SPAWN_Z) b.active = false;
    }
}

/** Sparks drift on their own velocity and fade. */
function moveSparks(g, dt) {
    for (const s of g.sparks) {
        if (!s.active) continue;
        s.x += s.vx * dt;
        s.y += s.vy * dt;
        s.z += s.vz * dt - SPEED * dt * 0.5;
        s.life -= dt;
        if (s.life <= 0 || s.z < RETIRE_Z) s.active = false;
    }
}

/** One fixed step of the game (`dt` is the 1/60 s step, in ms). */
export function step(g, dt) {
    const { S } = g;
    if (S.state !== 'flying') return;
    S.t += dt;
    while (S.next < g.script.length && g.script[S.next].t <= S.t) apply(g, g.script[S.next++]);
    steer(g, dt);
    fireBolts(g, dt);
    moveDrones(g, dt);
    moveOrbs(g, dt);
    movePylons(g, dt);
    moveBoss(g, dt);
    moveSparks(g, dt);
}

src/render-sprites.js

javascriptApache-2.079 lines

// SPDX-License-Identifier: Apache-2.0
import { BOSS_HP, GROUND_Y, OCTA, f1 } from './constants.js';

/** Pylons: a box with a wider cap, perspective-projected. */
export function drawPylons(g) {
    const { sx, sy } = g.proj;
    for (const p of g.pylons) {
        g.show(p.node, p.active);
        if (!p.active) continue;
        const x0 = sx(p.x - 18, p.z);
        const x1 = sx(p.x + 18, p.z);
        const y0 = sy(GROUND_Y, p.z);
        const y1 = sy(150, p.z);
        const cap = (x1 - x0) * 0.3;
        const box = `M${f1(x0)} ${f1(y0)} L${f1(x0)} ${f1(y1)} L${f1(x1)} ${f1(y1)} L${f1(x1)} ${f1(y0)} Z`;
        g.set(p.node, 'd', `${box} M${f1(x0 - cap)} ${f1(y1)} L${f1(x1 + cap)} ${f1(y1)}`);
    }
}

export function drawDrones(g) {
    for (const d of g.drones) {
        g.show(d.node, d.active);
        if (d.active) g.set(d.node, 'd', g.proj.faces(OCTA, OCTA.f, 34, [d.x, d.y, d.z], [d.spin * 0.7, d.spin, 0]));
    }
}

/** The Warden: the core shrinks as it dies; the ring is ten turning segments. */
export function drawBoss(g) {
    const { boss, S, proj, el } = g;
    g.show(el.get('boss'), boss.active);
    if (!boss.active) return;
    const size = boss.dead ? 70 * Math.max(0, (S.endAt - S.t) / 1600) : 70;
    const angles = [boss.spin, boss.spin * 1.3, 0];
    g.set(el.get('core'), 'd', proj.faces(OCTA, OCTA.f, size, [boss.x, boss.y, boss.z], angles));
    const at = (/** @type {number} */ a, /** @type {number} */ r) =>
        `${f1(proj.sx(boss.x + r * Math.cos(a), boss.z))} ${f1(proj.sy(boss.y + r * Math.sin(a), boss.z))}`;
    let ring = '';
    for (let k = 0; k < 10; k += 1) {
        const a0 = boss.spin * 1.8 + (k / 10) * Math.PI * 2;
        const a1 = a0 + 0.42;
        ring += `M${at(a0, 130)} L${at(a1, 130)} L${at(a1, 165)} L${at(a0, 165)} Z `;
    }
    g.set(el.get('ring'), 'd', boss.dead ? '' : ring.trim());
    g.set(el.get('bossFill'), 'width', f1(396 * Math.max(0, boss.hp) / BOSS_HP));
}

/** Orbs (halo and core), bolts and sparks: circles and lines whose size follows the depth. */
export function drawShots(g) {
    const { sx, sy, F } = g.proj;
    for (const o of g.orbs) {
        g.show(o.node, o.active);
        g.show(o.core, o.active);
        if (!o.active) continue;
        const [x, y] = [f1(sx(o.x, o.z)), f1(sy(o.y, o.z))];
        const r = Math.max(1.5, (F * 14) / o.z);
        for (const [node, k] of [[o.node, 1], [o.core, 0.45]]) {
            g.set(node, 'cx', x);
            g.set(node, 'cy', y);
            g.set(node, 'r', f1(r * k));
        }
    }
    for (const b of g.bolts) {
        g.show(b.node, b.active);
        if (!b.active) continue;
        g.set(b.node, 'x1', f1(sx(b.x, b.z)));
        g.set(b.node, 'y1', f1(sy(b.y, b.z)));
        g.set(b.node, 'x2', f1(sx(b.x, b.z + 70)));
        g.set(b.node, 'y2', f1(sy(b.y, b.z + 70)));
        g.set(b.node, 'stroke-width', f1(Math.max(1, (F * 5) / b.z)));
    }
    for (const s of g.sparks) {
        g.show(s.node, s.active);
        if (!s.active) continue;
        g.set(s.node, 'cx', f1(sx(s.x, s.z)));
        g.set(s.node, 'cy', f1(sy(s.y, s.z)));
        g.set(s.node, 'r', f1(Math.max(1, (F * 4) / s.z)));
        g.set(s.node, 'opacity', f1(Math.min(1, s.life / 300)));
    }
}

src/render.js

javascriptApache-2.055 lines

// SPDX-License-Identifier: Apache-2.0
import { C, GROUND_Y, KITE, SHIP_Z, SPEED, f1 } from './constants.js';
import { drawBoss, drawDrones, drawPylons, drawShots } from './render-sprites.js';

/** The 15 lateral grid lines are static: placed once, from the horizon to just ahead of the ship. */
export function placeGrid(g) {
    const { sx, sy } = g.proj;
    for (let i = 0; i < 15; i += 1) {
        const x = (i - 7) * 130;
        const node = g.el.get(`lat${i}`);
        g.set(node, 'x1', f1(sx(x, 3000)));
        g.set(node, 'y1', f1(sy(GROUND_Y, 3000)));
        g.set(node, 'x2', f1(sx(x, 120)));
        g.set(node, 'y2', f1(sy(GROUND_Y, 120)));
    }
}

/** The grid's rows scroll toward the ship and fade with distance. */
function drawGrid(g) {
    const off = (g.S.t * SPEED) % 230;
    for (let k = 0; k < 12; k += 1) {
        const z = 140 + k * 230 - off;
        const row = g.el.get(`row${k}`);
        const y = g.proj.sy(GROUND_Y, Math.max(z, 60));
        g.set(row, 'y1', f1(y));
        g.set(row, 'y2', f1(y));
        g.set(row, 'stroke-opacity', f1(Math.max(0, Math.min(0.5, (3000 - z) / 3000)) * 0.9));
    }
}

/** The Kite banks with its velocity; the engine glow pulses. */
function drawShip(g) {
    const { S, el, proj } = g;
    const sh = S.ship;
    const angles = [sh.vy * 0.6, 0, -sh.vx * 1.1];
    g.set(el.get('shipUpper'), 'd', proj.faces(KITE, KITE.upper, 0.6, [sh.x, sh.y, SHIP_Z], angles));
    g.set(el.get('shipLower'), 'd', proj.faces(KITE, KITE.lower, 0.6, [sh.x, sh.y, SHIP_Z], angles));
    g.set(el.get('engine'), 'cx', f1(proj.sx(sh.x, SHIP_Z - 16)));
    g.set(el.get('engine'), 'cy', f1(proj.sy(sh.y, SHIP_Z - 16)));
    g.set(el.get('engine'), 'r', f1(5 + 1.5 * Math.sin(S.t / 60)));
}

/** One frame: attribute writes only, no node is created. */
export function render(g) {
    const { S, el } = g;
    drawGrid(g);
    drawPylons(g);
    drawDrones(g);
    drawBoss(g);
    drawShots(g);
    drawShip(g);
    g.text(el.get('score'), String(S.score).padStart(6, '0'));
    g.set(el.get('shieldBar'), 'width', f1(296 * S.shield / 100));
    g.set(el.get('shieldBar'), 'fill', S.shield > 35 ? C.teal : C.orb);
}

src/input.js

javascriptApache-2.053 lines

// SPDX-License-Identifier: Apache-2.0

const KEYMAP = {
    ArrowLeft: 'left', a: 'left', q: 'left', ArrowRight: 'right', d: 'right',
    ArrowUp: 'up', w: 'up', z: 'up', ArrowDown: 'down', s: 'down',
};
const keyOf = (/** @type {KeyboardEvent} */ e) => /** @type {Record<string, string>} */ (KEYMAP)[e.key]
    || /** @type {Record<string, string>} */ (KEYMAP)[String(e.key).toLowerCase()];

/**
 * Steering: the arrow keys / WASD (fw `events`, on the document) and a drag on
 * the scene (fw `gesture`, `pan`). Touching either takes the wheel from the
 * attract-mode autopilot, unless the player forced it on.
 * @param {any} g the game
 * @param {Element} mount the scene's SVG root
 * @param {any} events fw's `events` module
 * @param {any} gesture fw's `gesture` module
 * @returns {{ dispose(): void }}
 */
export function bindInput(g, mount, events, gesture) {
    const doc = mount.ownerDocument;
    const scope = events.scope(`lumen-rail-${g.id}`);
    const takeOver = () => {
        const { S } = g;
        if (!S.autopilot || S.state !== 'flying' || S.forced) return;
        S.autopilot = false;
        S.attract = false;
        g.text(g.el.get('mode'), 'MANUAL');
    };
    scope.on('down', doc, 'keydown', (/** @type {KeyboardEvent} */ e) => {
        const k = keyOf(e);
        if (!k) return;
        g.keys.add(k);
        takeOver();
        if (g.S.state === 'flying' && e.key.startsWith('Arrow') && e.preventDefault) e.preventDefault();
    });
    scope.on('up', doc, 'keyup', (/** @type {KeyboardEvent} */ e) => {
        const k = keyOf(e);
        if (k) g.keys.delete(k);
    });
    const gestures = gesture.attach(mount);
    gestures.on('pan', ({ dx, dy }) => {
        g.pan.dx += dx;
        g.pan.dy += dy;
        takeOver();
    });
    return {
        dispose() {
            scope.clear();
            gestures.detach();
        },
    };
}

src/handle.js

javascriptApache-2.075 lines

// SPDX-License-Identifier: Apache-2.0
import { STEP, rng } from './constants.js';
import { setState } from './fx.js';
import { render } from './render.js';
import { step } from './step.js';

/**
 * The handle the page drives: run state, `start` / `play` / `pause` / `advance`, `dispose`.
 * The loop is one tickable on the package's shared scheduler; the game steps in fixed 1/60 s
 * increments, so `advance(ms)` plays the same run without a clock.
 * @param {any} g the game
 * @param {Element} root the scene root, removed on dispose
 * @param {{ dispose(): void }} inputs the key and drag bindings
 * @param {any} scheduler the shared scheduler
 */
export function createHandle(g, root, inputs, scheduler) {
    let [acc, last, playing, endedFor] = [0, 0, false, 0];
    const advance = (/** @type {number} */ ms) => {
        acc += ms;
        while (acc >= STEP) { step(g, STEP); acc -= STEP; }
        render(g);
    };
    const ticker = {
        _step(/** @type {number} */ ts) {
            const dt = last ? Math.min(100, ts - last) : 0;
            last = ts;
            advance(dt);
            endedFor = g.S.state === 'flying' ? 0 : endedFor + dt;
            // The attract mode flies again 4 s after its run ends.
            if (g.S.attract && endedFor > 4000) handle.start({ autopilot: true });
        },
    };
    const handle = {
        get state() { return g.S.state; },
        get time() { return g.S.t; },
        get score() { return g.S.score; },
        get shield() { return g.S.shield; },
        get reachedBoss() { return g.S.reachedBoss; },
        get ship() { return { x: g.S.ship.x, y: g.S.ship.y }; },
        get autopilot() { return g.S.autopilot; },
        get nodeCount() { return root.querySelectorAll('*').length; },
        /** A new run: the player's, or the autopilot's (`force` keeps it on whatever is pressed). */
        start({ autopilot = false, force = false } = {}) {
            for (const pool of [g.bolts, g.drones, g.orbs, g.pylons, g.sparks]) for (const o of pool) o.active = false;
            g.boss.active = false;
            Object.assign(g.S, {
                t: 0, score: 0, shield: 100, fireT: 0, next: 0, endAt: 0, reachedBoss: false, autopilot,
                attract: autopilot && !force, forced: force, rand: rng(0x7261696c),
            });
            Object.assign(g.S.ship, { x: 0, y: -20, vx: 0, vy: 0 });
            g.keys.clear();
            g.set(g.el.get('bossBar'), 'opacity', 0);
            g.text(g.el.get('mode'), autopilot ? 'AUTOPILOT' : 'MANUAL');
            setState(g, 'flying');
            render(g);
        },
        play() {
            if (playing) return;
            [playing, last] = [true, 0];
            scheduler.scheduler.add(ticker);
        },
        pause() {
            playing = false;
            scheduler.scheduler.remove(ticker);
        },
        advance,
        dispose() {
            handle.pause();
            for (const tl of [...g.live]) tl.stop();
            inputs.dispose();
            root.remove();
        },
    };
    return handle;
}

src/game.js

javascriptApache-2.035 lines

// SPDX-License-Identifier: Apache-2.0
import { rng } from './constants.js';
import { createWriters, indexByDataId } from './dom.js';
import { createHandle } from './handle.js';
import { design } from './hud.js';
import { bindInput } from './input.js';
import { createProjection } from './projection.js';
import { placeGrid, render } from './render.js';
import { script } from './script.js';
import { createState } from './state.js';

/**
 * Build the game into `mount`: the whole scene once (a seeded template, so every
 * build is the same), then the handle that runs it.
 * @param {object} ctx
 * @param {Element} ctx.mount an `<svg>` the scene is appended to
 * @param {any} ctx.graphic the resolved `graphic.anim` aggregate
 * @param {{ vec3: any, project: any }} ctx.kernels the svg3d kernels
 * @param {{ events: any, gesture: any }} ctx.input fw's `events` and `gesture`
 * @param {number} ctx.id a number that keeps this instance's ids and scope apart
 * @param {(state: string) => void} [ctx.onState] called when the run's state changes
 */
export function createGame({ mount, graphic, kernels, input, id, onState }) {
    const { svgBuild, scopedIds, svgApply, timeline, scheduler } = graphic;
    const root = svgBuild.build(design(rng(0x6c756d65)), { idScope: scopedIds.createScope(`lumen-rail-${id}`) });
    mount.appendChild(root);
    const el = indexByDataId(root);
    const g = {
        el, timeline, onState, id, script: script(), live: new Set(),
        ...createWriters(svgApply.svgAttr), ...createState(el), proj: createProjection(kernels.vec3, kernels.project),
    };
    placeGrid(g);
    render(g);
    return createHandle(g, root, bindInput(g, mount, input.events, input.gesture), scheduler);
}

style.css

cssApache-2.04 lines

/* SPDX-License-Identifier: Apache-2.0 */
#mount { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; background: #0B1026; touch-action: none; }
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
.keys { opacity: 0.75; }