Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Add Signal Box: repeat the lever sequence to route each train through a country junction #79
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/73-add-signal-box-repeat-the-lever-sequence → main 4 commits fork
10 files
changed +798
−1
README.md +2 −1
| @@ -34,6 +34,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am | ||
| 34 | 34 | | [](tightrope/) | Three crossings of a wire between two rooftops: the walker steps on alone while a lean angle falls away from centre and wind gusts (shown in the grass and the chimney flag a beat early) tip it; hold left or right to lean back, but a long hold overcorrects, and past 30 degrees you drop to the net and restart from the last of three marks; a crossing scores 10 plus 1 per second under 60, and 5 more if the lean never passed half the limit (forged by the crew on the engine and shell above, not by the original creators) | Hold left or right half of the canvas; arrows or A/D | |
| 35 | 35 | | [](wood-split/) | A 60-second round at a chopping block in a farmyard: hold to raise the axe (the longer the hold the stronger the swing, up to a peak, then your arms tire) while the blade sways across the log top, release to swing; on the grain crack at full strength splits it clean for 3, near it for 1, off it or too weak sticks the axe and costs two seconds, and knotty logs need full strength; split halves stack on the woodpile (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space | |
| 36 | 36 | | [](bell-tower/) | The tower rings a peal on four bells of different sizes and you ring it back by pulling the ropes in the same order; a bell must swing back before it rings again, a right peal scores its length and the next is the same peal plus one bell (it starts at three), and a wrong bell ends that peal without scoring, three wrong peals end the game; each bell flashes as it swings, so it plays muted too (forged by the crew on the engine and shell above, not by the original creators) | Tap a rope; 1-4 or the arrows, one per bell | |
| 37 | | [](signal-box/) | A train waits at a country junction and the signalman's lamp lights a sequence of levers, one by one, on a row of five; you pull the same levers in the same order. Right and the train runs through on the route the points set; a wrong lever jams the points and that train is lost. Each routed train adds one lever to the next sequence (it starts at three), three lost trains end the game and eight routed is a win; pulls are ignored while the lamp is lit, and each lever is lit for over half a second so it is memory, not a guess; lit levers show without animation under reduced motion, so it plays muted too (forged by the crew on the engine and shell above, not by the original creators) | Tap a lever; 1-5, or the arrows and enter | | |
| 37 | 38 | | [](ice-fishing/) | A 60-second round on a frozen lake: hold to let line out through the hole and watch the hook sink in the cut-away, a perch (1), trout (2) or pike (3) crossing the hook at its depth bites, then hold to reel and ease off to let the tension fall; full tension snaps the line and three snaps end the round (forged by the crew on the engine and shell above, not by the original creators) | Hold the canvas; hold space | |
| 38 | 39 | | [](archery/) | Ten arrows at a straw target across a meadow: drag back from the archer to draw (the drag length is power, its angle is aim), release to shoot; the wind changes every arrow and shows on the pennant and the grass, holding past three seconds makes the aim sway wider, and rings score 10 (gold), 8, 6, 4 and 2 (forged by the crew on the engine and shell above, not by the original creators) | Drag back, release; arrows + hold space | |
| 39 | 40 | | [](tram-line/) | A 120-second timetable over eight stops: hold to power, release to coast, brake so the front door lands on the yellow mark; within 0.5 m scores 3, within 2 m scores 1, overshooting the shelter scores 0 and strands the passengers, stopping between stops costs 1, and each second left at the last stop adds 1 (forged by the crew on the engine and shell above, not by the original creators) | Hold up or W (right half) to power, down or S (left half) to brake | |
| @@ -58,7 +59,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is | ||
| 58 | 59 | Every page carries Open Graph and Twitter tags (between `og:begin` and `og:end`), and `og/<id>.png` is a 1200x630 card: the game's own opening frame, scaled 2x on white; `og/home.png` is a grid of all of them. Because the games are static, `bun scripts/og.mjs` makes them without a browser: it runs each page's scripts in a `vm` against a stub DOM, captures the canvas pixels and writes the PNG (zlib only, no dependency) and the tags. Run it after adding a game or changing a scene; `serve.test.mjs` fails when a card or its tags are missing or stale. Scenes are rendered with a seeded `Math.random`, so the cards are byte-for-byte reproducible. Absolute URLs use `ORIGIN` at the top of the script (the forge production site), so change it there if the site moves. |
| 59 | 60 | |
| 60 | 61 | ## Add a game |
| 61 | Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper and Wood Split play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`. | |
| 62 | Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split and Signal Box play on their own sound effects). Rules that need testing go in a plain script with a `.test.mjs` beside it, as in `kite-hill/model.js`. | |
| 62 | 63 | |
| 63 | 64 | - `shell.js` provides the game menu, the Rules popup, the credits and the background music. |
| 64 | 65 | - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals. |
index.html +1
| @@ -84,6 +84,7 @@ footer a::after { content: none; } | ||
| 84 | 84 | <li data-kind="Precision" data-input="Hold" style="--accent:#cf4b3a"><a href="tightrope/">Tightrope</a><span>Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
| 85 | 85 | <li data-kind="Timing" data-input="Hold" style="--accent:#9a6b3c"><a href="wood-split/">Wood Split</a><span>Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li> |
| 86 | 86 | <li data-kind="Memory" data-input="Tap" style="--accent:#a8863a"><a href="bell-tower/">Bell Tower</a><span>Ring the peal back: the tower plays a sequence on four bells, pull the ropes in the same order, each round one bell longer</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li> |
| 87 | <li data-kind="Memory" data-input="Tap" style="--accent:#7a3b2e"><a href="signal-box/">Signal Box</a><span>Watch the levers, pull them back in order, and route every train through the junction</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li> | |
| 87 | 88 | <li data-kind="Timing" data-input="Hold" style="--accent:#6fb3d2"><a href="ice-fishing/">Ice Fishing</a><span>Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li> |
| 88 | 89 | <li data-kind="Sport" data-input="Drag" style="--accent:#b33a3a"><a href="archery/">Archery</a><span>Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10</span><span>Game forged by the crew</span><span class="tags">Sport · Drag</span></li> |
| 89 | 90 | <li data-kind="Precision" data-input="Hold" style="--accent:#c9a227"><a href="tram-line/">Tram Line</a><span>Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
og/home.png
Binary file not shown.
og/signal-box.png added
Binary file not shown.
serve.test.mjs +7
| @@ -191,6 +191,13 @@ test('Bell Tower and its rules script are served without a track', async () => { | ||
| 191 | 191 | expect((await fetch(base + '/bell-tower/peal.js')).status).toBe(200); |
| 192 | 192 | }); |
| 193 | 193 | |
| 194 | test('Signal Box and its rules script are served without a track', async () => { | |
| 195 | const page = await fetch(base + '/signal-box/'); | |
| 196 | expect(page.status).toBe(200); | |
| 197 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); | |
| 198 | expect((await fetch(base + '/signal-box/junction.js')).status).toBe(200); | |
| 199 | }); | |
| 200 | ||
| 194 | 201 | test('Ice Fishing and its rules script are served without a track', async () => { |
| 195 | 202 | const page = await fetch(base + '/ice-fishing/'); |
| 196 | 203 | expect(page.status).toBe(200); |
shell.js +1
| @@ -28,6 +28,7 @@ window.PixelPlays = (() => { | ||
| 28 | 28 | { id: 'tightrope', title: 'Tightrope', blurb: 'Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing', kind: 'Precision', input: 'Hold', accent: '#cf4b3a', music: false, forged: true }, |
| 29 | 29 | { id: 'wood-split', title: 'Wood Split', blurb: 'Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds', kind: 'Timing', input: 'Hold', accent: '#9a6b3c', music: false, forged: true }, |
| 30 | 30 | { id: 'bell-tower', title: 'Bell Tower', blurb: 'Ring the peal back: the tower plays a sequence on four bells, pull the ropes in the same order, each round one bell longer', kind: 'Memory', input: 'Tap', accent: '#a8863a', music: false, forged: true }, |
| 31 | { id: 'signal-box', title: 'Signal Box', blurb: 'Watch the levers, pull them back in order, and route every train through the junction', kind: 'Memory', input: 'Tap', accent: '#7a3b2e', music: false, forged: true }, | |
| 31 | 32 | { id: 'ice-fishing', title: 'Ice Fishing', blurb: 'Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises', kind: 'Timing', input: 'Hold', accent: '#6fb3d2', music: false, forged: true }, |
| 32 | 33 | { id: 'archery', title: 'Archery', blurb: 'Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10', kind: 'Sport', input: 'Drag', accent: '#b33a3a', music: false, forged: true }, |
| 33 | 34 | { id: 'tram-line', title: 'Tram Line', blurb: 'Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing', kind: 'Precision', input: 'Hold', accent: '#c9a227', music: false, forged: true }, |
signal-box/index.html added +472
| @@ -0,0 +1,472 @@ | ||
| 1 | ||
| 2 | <html lang="en"> | |
| 3 | <head> | |
| 4 | <meta charset="utf-8"> | |
| 5 | <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"> | |
| 6 | <title>Signal Box</title> | |
| 7 | <!-- og:begin --> | |
| 8 | <meta name="description" content="Watch the levers, pull them back in order, and route every train through the junction"> | |
| 9 | <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/signal-box/"> | |
| 10 | <meta property="og:type" content="website"> | |
| 11 | <meta property="og:site_name" content="Pixel Plays"> | |
| 12 | <meta property="og:title" content="Signal Box"> | |
| 13 | <meta property="og:description" content="Watch the levers, pull them back in order, and route every train through the junction"> | |
| 14 | <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/signal-box/"> | |
| 15 | <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/signal-box.png"> | |
| 16 | <meta property="og:image:type" content="image/png"> | |
| 17 | <meta property="og:image:width" content="1200"> | |
| 18 | <meta property="og:image:height" content="630"> | |
| 19 | <meta property="og:image:alt" content="Signal Box: the opening scene of the game"> | |
| 20 | <meta name="twitter:card" content="summary_large_image"> | |
| 21 | <!-- og:end --> | |
| 22 | <style> | |
| 23 | :root { : #1c1b19; : #8b877f; : #fff; : #7a3b2e; } | |
| 24 | * { box-sizing: border-box; } | |
| 25 | html, body { height: 100%; margin: 0; background: var(); color: var(); } | |
| 26 | body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; } | |
| 27 | #stage { position: fixed; inset: 0; display: grid; place-items: center; } | |
| 28 | canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; } | |
| 29 | .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; gap: 16px; pointer-events: none; } | |
| 30 | #scores { position: fixed; top: max(14px, env(safe-area-inset-top)); left: max(16px, env(safe-area-inset-left)); display: grid; gap: 2px; pointer-events: none; } | |
| 31 | #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; } | |
| 32 | .row { display: flex; align-items: center; gap: 8px; color: var(); } | |
| 33 | .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; } | |
| 34 | .row span { color: var(); } | |
| 35 | #status { color: var(); min-height: 1.35em; } | |
| 36 | button { pointer-events: auto; font: inherit; color: var(); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; } | |
| 37 | button:hover, button:focus-visible { color: var(); } | |
| 38 | </style> | |
| 39 | </head> | |
| 40 | <body> | |
| 41 | <div id="stage"><canvas id="c" tabindex="0" aria-label="A brick signal box beside a country junction, with a row of five coloured levers numbered 1 to 5 and five tracks fanning out below. A train waits at the signal. The signalman's lamp lights a sequence of levers, then you pull the same levers in the same order: tap a lever or press 1 to 5, or move with the arrow keys and press enter. Pulls are ignored while the sequence is shown. A right sequence routes the train and the next is one lever longer; a wrong lever jams the points and loses the train. Three lost trains end the game; eight routed is a win."></canvas></div> | |
| 42 | <div id="scores"> | |
| 43 | <div class="row"><b id="routed">0</b><span>trains routed</span></div> | |
| 44 | <div class="row"><b id="length">3</b><span>sequence</span></div> | |
| 45 | <div class="row"><b id="lost">0/3</b><span>trains lost</span></div> | |
| 46 | <div class="row"><b id="best">0</b><span>best</span></div> | |
| 47 | </div> | |
| 48 | <div class="hud" id="bottom"> | |
| 49 | <div id="status" role="status" aria-live="polite"></div> | |
| 50 | <button id="mute" type="button" aria-pressed="false">sound on</button> | |
| 51 | </div> | |
| 52 | <script src="../shell.js"></script> | |
| 53 | <script> | |
| 54 | PixelPlays.mount({ | |
| 55 | id: 'signal-box', | |
| 56 | rules: [ | |
| 57 | 'The lamp lights levers one by one; pull the same levers in the same order.', | |
| 58 | 'Tap a lever, or press 1 to 5. Pulls are ignored while the lamp is lit.', | |
| 59 | 'Right routes the train and adds a lever; wrong jams the points and loses it.', | |
| 60 | 'Three lost trains end the game. Eight routed is a win.', | |
| 61 | ], | |
| 62 | }); | |
| 63 | </script> | |
| 64 | <script>window.PP_SCENE = { originY: 24, shadowX: 1.3, shadowY: -.12 };</script> | |
| 65 | <script src="../engine.js"></script> | |
| 66 | <script src="junction.js"></script> | |
| 67 | <script> | |
| 68 | 'use strict'; | |
| 69 | ||
| 70 | const BRICK = [[150, 74, 56], [138, 66, 50], [160, 82, 60]], MORTAR = [186, 170, 150], SLATE = [74, 80, 96], SLATE_DARK = [56, 60, 74]; | |
| 71 | const GLASS = [58, 74, 96], LANTERN = [[255, 214, 120], [255, 236, 170]], TRIM = [226, 218, 200]; | |
| 72 | const GRASS_C = [122, 156, 88], GRAVEL = [176, 168, 152], BALLAST = [150, 142, 130]; | |
| 73 | const STEEL = [150, 154, 166], STEEL_BRIGHT = [232, 232, 238], TIE = [104, 78, 56], IRON = [58, 60, 70]; | |
| 74 | const LOCO = [52, 96, 76], CAB = [146, 54, 46], SOOT = [40, 40, 46], WAGON = [150, 100, 62], WAGON_ROOF = [214, 204, 186]; | |
| 75 | const RED = [214, 52, 44], GREEN = [70, 190, 100], RED_DIM = [150, 40, 36], GREEN_DIM = [50, 140, 76]; | |
| 76 | const STEAM = [[244, 244, 248], [226, 228, 236], [210, 214, 226]]; | |
| 77 | const GLOW = [255, 244, 190]; | |
| 78 | const LEVER_COLORS = [[208, 60, 52], [228, 176, 52], [74, 152, 94], [68, 112, 188], [146, 88, 168]]; | |
| 79 | const NOTES = [262, 294, 330, 392, 440]; | |
| 80 | const DIGITS = { | |
| 81 | 1: ['010', '110', '010', '010', '111'], | |
| 82 | 2: ['111', '001', '111', '100', '111'], | |
| 83 | 3: ['111', '001', '111', '001', '111'], | |
| 84 | 4: ['101', '101', '111', '001', '001'], | |
| 85 | 5: ['111', '100', '111', '001', '111'], | |
| 86 | }; | |
| 87 | const INK_PIX = rgb(28, 27, 25), ACCENT_PIX = rgb(122, 59, 46); | |
| 88 | const BEST_KEY = 'pixel-plays-signal-box-best'; | |
| 89 | ||
| 90 | const LEVER_V = -6.4, WALL_V = -7.8, BACK_V = -10, WALL_H = 8, LEVER_LEN = 3.2, DIGIT_V = -4.9; | |
| 91 | const GROUND = { u0: -17.5, u1: 16.5, v0: -11, v1: 10.5 }; | |
| 92 | const TRUNK_V = -2.5, TRUNK_U0 = -18, THROAT_U = -8, END_V = 10.4; | |
| 93 | const leverU = i => -6 + 4.5 * i; | |
| 94 | const D_WAIT = 8.5, D_JAM = 9.4, BLADE_REACH = 2.4; | |
| 95 | const LEVERS = Junction.LEVERS; | |
| 96 | ||
| 97 | const world = (u, v, z) => [(u + v) / R2, (v - u) / R2, z]; | |
| 98 | const mix = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]; | |
| 99 | // stable colour arrays: the engine caches its shading ramps per array, so none is made per frame | |
| 100 | const LIT = LEVER_COLORS.map(c => mix(c, GLOW, .75)); | |
| 101 | const LAMPS = { red: [RED_DIM, RED], green: [GREEN_DIM, GREEN] }; | |
| 102 | ||
| 103 | /* ---------- the track: a trunk from the left, a throat, five branches ---------- */ | |
| 104 | const bezier = (p0, p1, p2, p3, t) => { | |
| 105 | const a = 1 - t, w0 = a * a * a, w1 = 3 * a * a * t, w2 = 3 * a * t * t, w3 = t * t * t; | |
| 106 | return [w0 * p0[0] + w1 * p1[0] + w2 * p2[0] + w3 * p3[0], w0 * p0[1] + w1 * p1[1] + w2 * p2[1] + w3 * p3[1]]; | |
| 107 | }; | |
| 108 | // each route is a list of [u, v] points a quarter unit or so apart, with the distance run so far | |
| 109 | const ROUTES = Array.from({ length: LEVERS }, (_, i) => { | |
| 110 | const uE = leverU(i), dU = uE - THROAT_U; | |
| 111 | const p0 = [THROAT_U, TRUNK_V], p1 = [THROAT_U + dU * .55, TRUNK_V], p2 = [uE, TRUNK_V + 4.5], p3 = [uE, END_V]; | |
| 112 | const pts = [[TRUNK_U0, TRUNK_V], [THROAT_U, TRUNK_V]]; | |
| 113 | for (let k = 1; k <= 40; k++) pts.push(bezier(p0, p1, p2, p3, k / 40)); | |
| 114 | const run = [0]; | |
| 115 | for (let k = 1; k < pts.length; k++) run.push(run[k - 1] + Math.hypot(pts[k][0] - pts[k - 1][0], pts[k][1] - pts[k - 1][1])); | |
| 116 | return { pts, run, length: run[run.length - 1] }; | |
| 117 | }); | |
| 118 | const D_THROAT = THROAT_U - TRUNK_U0; | |
| 119 | // position and heading at distance d along a route; before the start and past the end the track runs straight on | |
| 120 | function at(route, d) { | |
| 121 | const { pts, run, length } = ROUTES[route]; | |
| 122 | let k = 1; | |
| 123 | if (d >= length) k = pts.length - 1; else if (d > 0) while (run[k] < d) k++; | |
| 124 | const a = pts[k - 1], b = pts[k], seg = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1; | |
| 125 | const tu = (b[0] - a[0]) / seg, tv = (b[1] - a[1]) / seg, t = d - run[k - 1]; | |
| 126 | return { u: a[0] + tu * t, v: a[1] + tv * t, tu, tv }; | |
| 127 | } | |
| 128 | ||
| 129 | /* ---------- state ---------- */ | |
| 130 | const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })(); | |
| 131 | let P = Junction.newGame(best0, Date.now() & 0xffff); | |
| 132 | const G = { time: 0, status: '', noteUntil: 0, lean: new Array(LEVERS).fill(0), blade: 2, aim: 2, cursor: 2, kbd: false, arrive: false }; | |
| 133 | const nodes = { routed: document.getElementById('routed'), length: document.getElementById('length'), lost: document.getElementById('lost'), best: document.getElementById('best'), status: document.getElementById('status') }; | |
| 134 | function renderHud() { | |
| 135 | nodes.routed.textContent = P.routed; | |
| 136 | nodes.length.textContent = P.seq.length; | |
| 137 | nodes.lost.textContent = `${P.lost}/${Junction.MAX_LOST}`; | |
| 138 | nodes.best.textContent = Math.max(P.best, P.routed); | |
| 139 | } | |
| 140 | function setStatus(text) { | |
| 141 | if (text === G.status) return; | |
| 142 | G.status = text; | |
| 143 | nodes.status.textContent = text; | |
| 144 | } | |
| 145 | function note(text) { setStatus(text); G.noteUntil = G.time + 1.8; } | |
| 146 | ||
| 147 | /* ---------- baked scene ---------- */ | |
| 148 | function groundColor(x, y, ix, iy) { | |
| 149 | const u = (x - y) / R2, v = (x + y) / R2; | |
| 150 | if (u < GROUND.u0 || u > GROUND.u1 || v < GROUND.v0 || v > GROUND.v1) return 0; | |
| 151 | if (u < GROUND.u0 + .5 || u > GROUND.u1 - .5 || v < GROUND.v0 + .5 || v > GROUND.v1 - .5) return rgb(94, 120, 74); | |
| 152 | const t = .93 + (hash(ix, iy) - .5) * .12; | |
| 153 | const gravel = u > -6.5 && u < 12.5 && v > -9 && v < -3.8; | |
| 154 | const c = gravel ? GRAVEL : GRASS_C; | |
| 155 | return rgb(c[0] * t, c[1] * t, c[2] * t); | |
| 156 | } | |
| 157 | function brickColor(u, z, row) { | |
| 158 | const off = row % 2 ? .5 : 0, col = Math.floor(u + off); | |
| 159 | if (row % 4 === 3) return MORTAR; | |
| 160 | return BRICK[Math.abs(Math.floor(hash(col, row) * 3)) % 3]; | |
| 161 | } | |
| 162 | // the box's front face is courses of brick, with a window each side of the door and a lit lantern in one | |
| 163 | function bakeBox() { | |
| 164 | const U0 = -5.2, U1 = 11.2; | |
| 165 | const door = u => u > 2.2 && u < 3.8, windows = u => (u > -3.6 && u < -.8) || (u > 7.8 && u < 10.6); | |
| 166 | for (let row = 0, z = .15; z < WALL_H; z += .3, row++) { | |
| 167 | for (let u = U0; u < U1; u += .55) { | |
| 168 | const mid = u + .27, glass = z > 4.7 && z < 6.7 && windows(mid), gate = z < 3.6 && door(mid); | |
| 169 | const frame = (z > 4.5 && z < 6.9 && (windows(mid - .3) || windows(mid + .3))) || (z < 3.8 && (door(mid - .3) || door(mid + .3))); | |
| 170 | let c = brickColor(mid, z, row); | |
| 171 | if (frame) c = TRIM; | |
| 172 | if (glass) c = mid > 7 ? LANTERN[0] : GLASS; | |
| 173 | if (gate) c = WOOD_DOOR; | |
| 174 | capsule(world(u, WALL_V, z), world(u + .6, WALL_V, z), .27, .27, () => c, 'rough'); | |
| 175 | } | |
| 176 | } | |
| 177 | // the roof: slate courses sloping up to the ridge, with an overhang | |
| 178 | for (let k = 0; k <= 9; k++) { | |
| 179 | const v = lerp(BACK_V - .3, WALL_V + .5, k / 9), z = WALL_H + .1 + Math.sin(k / 9 * Math.PI) * .9 - (k / 9) * .4; | |
| 180 | capsule(world(U0 - .7, v, z), world(U1 + .7, v, z), .34, .34, () => (k % 2 ? SLATE : SLATE_DARK), 'rough'); | |
| 181 | } | |
| 182 | // chimney stack on the roof | |
| 183 | capsule(world(8.6, BACK_V + 1, WALL_H), world(8.6, BACK_V + 1, WALL_H + 2.2), .6, .6, () => BRICK[1], 'rough'); | |
| 184 | for (let z = 1; z <= WALL_H; z += 1.1) for (let u = U0; u <= U1; u += .9) castShadow(...world(u, WALL_V, z).slice(0, 2), z, .8, 1, 0); | |
| 185 | } | |
| 186 | const WOOD_DOOR = [104, 70, 50]; | |
| 187 | // the lever frame: a low iron beam the five levers pivot on | |
| 188 | function bakeFrame() { | |
| 189 | capsule(world(leverU(0) - 1.6, LEVER_V, .55), world(leverU(4) + 1.6, LEVER_V, .55), .4, .4, () => IRON, 'solid'); | |
| 190 | capsule(world(leverU(0) - 1.6, LEVER_V, .15), world(leverU(4) + 1.6, LEVER_V, .15), .5, .5, () => BALLAST, 'rough'); | |
| 191 | for (let i = 0; i < LEVERS; i++) { | |
| 192 | const u = leverU(i); | |
| 193 | capsule(world(u, LEVER_V, .55), world(u, LEVER_V, .9), .55, .45, () => IRON, 'solid'); | |
| 194 | // a point rod running from each lever down to its track | |
| 195 | capsule(world(u, LEVER_V + .5, .08), world(u, TRUNK_V - 1.6, .08), .07, .07, () => BALLAST, 'solid'); | |
| 196 | } | |
| 197 | } | |
| 198 | function bakeTrack() { | |
| 199 | ROUTES.forEach((r, i) => { | |
| 200 | const from = i === 0 ? 0 : 1; // the trunk is laid once, with the first route | |
| 201 | const start = from ? D_THROAT : 0; | |
| 202 | for (let d = start; d <= r.length; d += 1.05) { | |
| 203 | const p = at(i, d), nu = -p.tv, nv = p.tu; | |
| 204 | capsule(world(p.u + nu * .95, p.v + nv * .95, .08), world(p.u - nu * .95, p.v - nv * .95, .08), .13, .13, () => TIE, 'solid'); | |
| 205 | } | |
| 206 | for (let d = start; d <= r.length; d += .3) { | |
| 207 | const p = at(i, d), q = at(i, d + .3), nu = -p.tv, nv = p.tu; | |
| 208 | for (const s of [-.5, .5]) capsule(world(p.u + nu * s, p.v + nv * s, .22), world(q.u + nu * s, q.v + nv * s, .22), .1, .1, () => STEEL, 'solid'); | |
| 209 | } | |
| 210 | // a buffer post at the end of each branch, in the colour of its lever | |
| 211 | const e = at(i, r.length); | |
| 212 | capsule(world(e.u, e.v - .2, .1), world(e.u, e.v - .2, 1.3), .22, .22, () => IRON, 'solid'); | |
| 213 | }); | |
| 214 | } | |
| 215 | function bakeScene() { | |
| 216 | bakeBox(); | |
| 217 | bakeFrame(); | |
| 218 | bakeTrack(); | |
| 219 | // fence posts along the front of the field | |
| 220 | for (let u = -16.5; u <= 15.5; u += 2) capsule(world(u, GROUND.v1 - .9, 0), world(u, GROUND.v1 - .9, .8), .12, .12, () => WOOD_DOOR, 'rough'); | |
| 221 | } | |
| 222 | function bake() { | |
| 223 | ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0); | |
| 224 | tufts.length = 0; leaves.length = 0; | |
| 225 | zb.fill(-1e9); | |
| 226 | pix.fill(rgb(255, 255, 255)); | |
| 227 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 228 | const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy); | |
| 229 | if (!c) continue; | |
| 230 | pix[i] = c; ground[i] = 1; | |
| 231 | zb[i] = (g.x + g.y) / R2 * COS; | |
| 232 | } | |
| 233 | groundZ.set(zb); | |
| 234 | bakeScene(); | |
| 235 | bakeOcclusion(); | |
| 236 | staticShadow.set(shadowMask); | |
| 237 | applyShadows(groundZ); | |
| 238 | bakedPix.set(pix); | |
| 239 | bakedZ.set(zb); | |
| 240 | } | |
| 241 | ||
| 242 | /* ---------- levers, points, signal, train ---------- */ | |
| 243 | function drawLever(i) { | |
| 244 | const u = leverU(i), lit = P.lit[i] > 0, a = -.4 + G.lean[i] * .95, len = LEVER_LEN; | |
| 245 | const pivot = world(u, LEVER_V, .85); | |
| 246 | const tip = world(u, LEVER_V + Math.sin(a) * len, .85 + Math.cos(a) * len); | |
| 247 | const grip = world(u, LEVER_V + Math.sin(a) * (len - .9), .85 + Math.cos(a) * (len - .9)); | |
| 248 | const color = lit ? LIT[i] : LEVER_COLORS[i]; | |
| 249 | dynamicAdd(pivot, grip, .17, .15, () => IRON); | |
| 250 | dynamicAdd(grip, tip, .3, .3, () => color); | |
| 251 | if (lit) dynamicAdd(tip, tip, .62, .62, () => GLOW); | |
| 252 | } | |
| 253 | function drawPoints() { | |
| 254 | const lo = Math.max(0, Math.min(LEVERS - 1, Math.floor(G.blade))), hi = Math.min(LEVERS - 1, lo + 1), k = G.blade - lo; | |
| 255 | const a = at(lo, D_THROAT + BLADE_REACH), b = at(hi, D_THROAT + BLADE_REACH); | |
| 256 | const tip = world(lerp(a.u, b.u, k), lerp(a.v, b.v, k), .3), root = world(THROAT_U, TRUNK_V, .3); | |
| 257 | const color = P.jam ? LAMPS.red[1] : STEEL_BRIGHT; | |
| 258 | dynamicAdd(root, tip, .17, .14, () => color); | |
| 259 | // the lamp on each branch's end post: lit for the branch the points are set to | |
| 260 | for (let i = 0; i < LEVERS; i++) { | |
| 261 | const e = at(i, ROUTES[i].length), on = P.route === i && !P.jam; | |
| 262 | dynamicAdd(world(e.u, e.v - .2, 1.5), world(e.u, e.v - .2, 1.5), .42, .42, () => (on ? LIT[i] : LEVER_COLORS[i])); | |
| 263 | } | |
| 264 | } | |
| 265 | function drawSignal(step) { | |
| 266 | const green = P.phase === 'between' && P.ok, flick = STILL ? 1 : (step * 7 + Math.floor(step / 3)) % 5 === 0 ? 0 : 1; | |
| 267 | const u = THROAT_U + .2, v = TRUNK_V + 1.5; | |
| 268 | dynamicAdd(world(u, v, 0), world(u, v, 3.2), .14, .14, () => IRON); | |
| 269 | dynamicAdd(world(u, v, 3.2), world(u, v, 3.2), .5, .5, () => IRON); | |
| 270 | const lamp = green ? LAMPS.green[flick] : LAMPS.red[flick]; | |
| 271 | dynamicAdd(world(u, v + .25, 3.2), world(u, v + .25, 3.2), .36, .36, () => lamp); | |
| 272 | } | |
| 273 | function drawTrainPart(route, d, length, h, body, roof) { | |
| 274 | const f = at(route, d), r = at(route, d - length), z = .85; | |
| 275 | if (f.u < GROUND.u0 + .6 || f.v > GROUND.v1 - 1.2 || r.u < GROUND.u0 + .3) return null; | |
| 276 | dynamicAdd(world(r.u, r.v, z), world(f.u, f.v, z), h, h, () => body); | |
| 277 | if (roof) dynamicAdd(world(r.u, r.v, z + h * .7), world(f.u, f.v, z + h * .7), h * .75, h * .75, () => roof); | |
| 278 | for (const k of [.2, .5, .8]) for (const s of [-.8, .8]) { | |
| 279 | const p = at(route, d - length * k), c = world(p.u - p.tv * s, p.v + p.tu * s, .45); | |
| 280 | dynamicAdd(c, c, .42, .42, () => SOOT); | |
| 281 | } | |
| 282 | return { f, r }; | |
| 283 | } | |
| 284 | function drawTrain(step) { | |
| 285 | const route = Math.max(0, P.route), d = trainAt(); | |
| 286 | // loco, then a wagon | |
| 287 | const loco = drawTrainPart(route, d, 3.6, .95, LOCO, null); | |
| 288 | if (loco) { | |
| 289 | const { f, r } = loco; | |
| 290 | dynamicAdd(world(r.u, r.v, 1.4), world(r.u, r.v, 3.1), .85, .85, () => CAB); | |
| 291 | dynamicAdd(world(f.u, f.v, 1.5), world(f.u, f.v, 2.7), .24, .3, () => SOOT); | |
| 292 | const top = world(f.u - f.tu * .3, f.v - f.tv * .3, 2.8); | |
| 293 | // steam from the waiting engine, a few puffs rising and thinning on a stepped clock | |
| 294 | if (P.phase !== 'between' || !P.jam) for (let n = 0; n < 4; n++) { | |
| 295 | const age = STILL ? n * 3 + 2 : (step + n * 3) % 12, t = age / 12; | |
| 296 | const c = world(top[0] * 0 + (f.u - f.tu * .3) + t * 1.3, (f.v - f.tv * .3) - t * .3, 2.8 + t * 3.4); | |
| 297 | dynamicAdd(c, c, .35 + t * .55, .35 + t * .55, () => STEAM[Math.min(2, Math.floor(t * 3))]); | |
| 298 | } | |
| 299 | } | |
| 300 | drawTrainPart(route, d - 4.2, 3.4, .9, WAGON, WAGON_ROOF); | |
| 301 | } | |
| 302 | // where the engine's front is: it rolls in, waits at the signal, then runs on through the points or creeps up and halts | |
| 303 | function trainAt() { | |
| 304 | const ease = t => 1 - (1 - t) * (1 - t); | |
| 305 | if (P.phase === 'lead' && G.arrive) return lerp(-1, D_WAIT, ease(Math.min(1, P.timer / Junction.LEAD))); | |
| 306 | if (P.phase === 'between' || P.phase === 'over') { | |
| 307 | const k = P.phase === 'over' ? 1 : Math.min(1, P.timer / Junction.PAUSE); | |
| 308 | if (P.jam) return lerp(D_WAIT, D_JAM, ease(Math.min(1, k * 2))); | |
| 309 | return D_WAIT + (ROUTES[Math.max(0, P.route)].length + 8 - D_WAIT) * k * k; | |
| 310 | } | |
| 311 | return D_WAIT; | |
| 312 | } | |
| 313 | // 1-5 on the gravel below each lever, lit while it is, and an underline for the keyboard's lever | |
| 314 | function drawNumbers() { | |
| 315 | for (let i = 0; i < LEVERS; i++) { | |
| 316 | const p = project(...world(leverU(i), DIGIT_V, 0)), color = P.lit[i] > 0 ? ACCENT_PIX : INK_PIX; | |
| 317 | const x0 = Math.round(p.sx) - 3, y0 = Math.round(p.sy) - 5; | |
| 318 | DIGITS[i + 1].forEach((row, ry) => { | |
| 319 | for (let cx = 0; cx < 3; cx++) { | |
| 320 | if (row[cx] !== '1') continue; | |
| 321 | for (let dy = 0; dy < 2; dy++) for (let dx = 0; dx < 2; dx++) { | |
| 322 | const x = x0 + cx * 2 + dx, y = y0 + ry * 2 + dy; | |
| 323 | if (x >= 0 && x < W && y >= 0 && y < H) pix[y * W + x] = color; | |
| 324 | } | |
| 325 | } | |
| 326 | }); | |
| 327 | if (G.kbd && G.cursor === i) for (let x = x0 - 1; x < x0 + 7; x++) { pix[(y0 + 11) * W + x] = ACCENT_PIX; pix[(y0 + 12) * W + x] = ACCENT_PIX; } | |
| 328 | } | |
| 329 | } | |
| 330 | // the lantern in the right-hand window flickers | |
| 331 | function drawLantern(step) { | |
| 332 | const flick = STILL ? 0 : (step * 5 + (step >> 2)) % 7 < 2 ? 1 : 0; | |
| 333 | const c = world(9.2, WALL_V + .15, 5.7); | |
| 334 | dynamicAdd(c, c, .5 + flick * .12, .5 + flick * .12, () => LANTERN[flick]); | |
| 335 | } | |
| 336 | ||
| 337 | function draw() { | |
| 338 | pix.set(bakedPix); | |
| 339 | zb.set(bakedZ); | |
| 340 | pendingShadows.length = 0; | |
| 341 | const step = STILL ? 0 : Math.floor(G.time * WIND_FPS); | |
| 342 | drawPoints(); | |
| 343 | for (let i = 0; i < LEVERS; i++) drawLever(i); | |
| 344 | drawSignal(step); | |
| 345 | drawTrain(step); | |
| 346 | drawLantern(step); | |
| 347 | flushShadows(); | |
| 348 | applyShadows(bakedZ); | |
| 349 | shadeEdges(); | |
| 350 | drawNumbers(); | |
| 351 | ctx.putImageData(image, 0, 0); | |
| 352 | } | |
| 353 | ||
| 354 | /* ---------- game ---------- */ | |
| 355 | function act(events) { | |
| 356 | for (const e of events) { | |
| 357 | if (e.type === 'show') note(`watch the lamp · ${e.length} levers`); | |
| 358 | if (e.type === 'light') sound('lever', e.lever); | |
| 359 | if (e.type === 'turn') note(`your turn · 0 of ${P.seq.length} pulled`); | |
| 360 | if (e.type === 'next') { G.arrive = true; renderHud(); } | |
| 361 | if (e.type === 'pull') { sound('lever', e.lever); if (!e.right) sound('jam'); } | |
| 362 | if (e.type === 'routed') { note(`train routed · +1 · ${P.seq.length + 1} levers next`); sound('routed'); renderHud(); } | |
| 363 | if (e.type === 'lost') { note(`lever ${e.lever + 1}, not ${e.wanted + 1} · points jammed · train lost ${e.lost} of ${Junction.MAX_LOST}`); renderHud(); } | |
| 364 | if (e.type === 'over') { | |
| 365 | if (P.record) try { localStorage.setItem(BEST_KEY, String(P.best)); } catch (err) { /* private window: keep it for this visit */ } | |
| 366 | const line = e.verdict === 'win' | |
| 367 | ? `${P.routed} trains routed · the junction ran on time` | |
| 368 | : `${P.routed} trains routed · the junction needs ${Junction.WIN_AT} to run on time`; | |
| 369 | setStatus(`${line}${P.record ? ' · new best' : ` · best ${P.best}`} · tap or press a key to run again`); | |
| 370 | renderHud(); | |
| 371 | } | |
| 372 | } | |
| 373 | } | |
| 374 | function pullLever(lever) { | |
| 375 | ensureAudio(); | |
| 376 | G.cursor = lever; | |
| 377 | if (P.phase === 'over') { | |
| 378 | const next = Junction.again(P); | |
| 379 | if (next) { P = next; G.arrive = false; note(HINT); renderHud(); } | |
| 380 | return; | |
| 381 | } | |
| 382 | const before = P.got; | |
| 383 | act(Junction.pull(P, lever)); | |
| 384 | if (P.phase === 'input' && P.got > before) setStatus(`your turn · ${P.got} of ${P.seq.length} pulled`); | |
| 385 | } | |
| 386 | const HINT = 'watch the lamp, then pull the same levers'; | |
| 387 | function update(dt) { | |
| 388 | G.time += dt; | |
| 389 | act(Junction.advance(P, dt)); | |
| 390 | // levers swing to where they are lit; with reduced motion they jump there | |
| 391 | for (let i = 0; i < LEVERS; i++) { | |
| 392 | const want = P.lit[i] > 0 ? 1 : 0; | |
| 393 | G.lean[i] = STILL ? want : G.lean[i] + Math.max(-dt * 6, Math.min(dt * 6, want - G.lean[i])); | |
| 394 | } | |
| 395 | // the points slide to the track the last lever set | |
| 396 | if (P.route >= 0) G.aim = P.route; | |
| 397 | G.blade = STILL ? G.aim : G.blade + Math.max(-dt * 9, Math.min(dt * 9, G.aim - G.blade)); | |
| 398 | if (G.time < G.noteUntil) return; | |
| 399 | if (P.phase === 'lead' || P.phase === 'show') setStatus(`watch the lamp · ${P.seq.length} levers`); | |
| 400 | else if (P.phase === 'input') setStatus(`your turn · ${P.got} of ${P.seq.length} pulled`); | |
| 401 | } | |
| 402 | ||
| 403 | /* ---------- input ---------- */ | |
| 404 | canvas.addEventListener('pointerdown', e => { | |
| 405 | canvas.focus({ preventScroll: true }); | |
| 406 | const rect = canvas.getBoundingClientRect(), x = (e.clientX - rect.left) / rect.width * W; | |
| 407 | let nearest = 0; | |
| 408 | for (let i = 1; i < LEVERS; i++) if (Math.abs(x - project(...world(leverU(i), LEVER_V, 0)).sx) < Math.abs(x - project(...world(leverU(nearest), LEVER_V, 0)).sx)) nearest = i; | |
| 409 | G.kbd = false; | |
| 410 | pullLever(nearest); | |
| 411 | }); | |
| 412 | // 1 to 5 pull a lever; the arrows pick one and enter or space pulls it | |
| 413 | canvas.addEventListener('keydown', e => { | |
| 414 | const digit = /^[1-5]$/.test(e.key) ? Number(e.key) - 1 : -1; | |
| 415 | const arrow = e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : 0; | |
| 416 | if (digit < 0 && !arrow && e.key !== ' ' && e.key !== 'Enter') return; | |
| 417 | e.preventDefault(); | |
| 418 | if (e.repeat) return; | |
| 419 | G.kbd = true; | |
| 420 | if (digit >= 0) pullLever(digit); | |
| 421 | else if (arrow) G.cursor = (G.cursor + arrow + LEVERS) % LEVERS; | |
| 422 | else pullLever(G.cursor); | |
| 423 | }); | |
| 424 | ||
| 425 | /* ---------- sound ---------- */ | |
| 426 | let audio = null, muted = false; | |
| 427 | function ensureAudio() { | |
| 428 | if (audio) { if (audio.state === 'suspended') audio.resume(); return; } | |
| 429 | const AC = window.AudioContext || window.webkitAudioContext; | |
| 430 | if (AC) audio = new AC(); | |
| 431 | } | |
| 432 | function tone(type, freq, to, life, level, delay = 0) { | |
| 433 | const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator(); | |
| 434 | osc.type = type; | |
| 435 | osc.frequency.setValueAtTime(freq, now); | |
| 436 | if (to !== freq) osc.frequency.exponentialRampToValueAtTime(to, now + life); | |
| 437 | gain.gain.setValueAtTime(level, now); | |
| 438 | gain.gain.exponentialRampToValueAtTime(.0005, now + life); | |
| 439 | osc.connect(gain).connect(audio.destination); | |
| 440 | osc.start(now); osc.stop(now + life + .02); | |
| 441 | } | |
| 442 | function sound(kind, lever = 0) { | |
| 443 | if (!audio || muted) return; | |
| 444 | if (kind === 'lever') { tone('triangle', NOTES[lever], NOTES[lever], .5, .12); tone('square', 110, 60, .08, .05); } | |
| 445 | if (kind === 'jam') { tone('sawtooth', 150, 55, .35, .07); tone('square', 80, 50, .25, .05); } | |
| 446 | if (kind === 'routed') [523, 659, 784].forEach((f, k) => tone('sine', f, f, .5, .08, k * .1)); | |
| 447 | } | |
| 448 | const muteButton = document.getElementById('mute'); | |
| 449 | muteButton.addEventListener('click', () => { | |
| 450 | muted = !muted; | |
| 451 | muteButton.textContent = muted ? 'sound off' : 'sound on'; | |
| 452 | muteButton.setAttribute('aria-pressed', String(muted)); | |
| 453 | }); | |
| 454 | ||
| 455 | /* ---------- fit and boot ---------- */ | |
| 456 | addEventListener('resize', fit); | |
| 457 | fit(); | |
| 458 | bake(); | |
| 459 | note(HINT); | |
| 460 | renderHud(); | |
| 461 | canvas.focus({ preventScroll: true }); | |
| 462 | let last = performance.now(); | |
| 463 | function frame(now) { | |
| 464 | update(Math.min(.04, (now - last) / 1000)); | |
| 465 | last = now; | |
| 466 | draw(); | |
| 467 | requestAnimationFrame(frame); | |
| 468 | } | |
| 469 | requestAnimationFrame(frame); | |
| 470 | </script> | |
| 471 | </body> | |
| 472 | </html> |
signal-box/junction.js added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The signal box rules: a train waits at the junction, the signalman's lamp shows a sequence of levers, the player | |
| 3 | // pulls the same levers in the same order. Right: the train runs through on the route the points set. Wrong lever: | |
| 4 | // the points jam and that train is lost. Each routed train adds one lever to the next sequence, starting at three; | |
| 5 | // a lost train comes back with the same sequence; three lost trains end the game, and eight routed is a win. | |
| 6 | // Plain numbers in, plain numbers out, no DOM. The page draws and sounds what this decides. | |
| 7 | (function (root) { | |
| 8 | const LEVERS = 5; | |
| 9 | const FIRST = 3; // levers in the first sequence | |
| 10 | const MAX_LOST = 3; | |
| 11 | const WIN_AT = 8; // trains routed for the win line | |
| 12 | const SHOW = .6; // seconds each lever stays lit: never below .5 so it is a memory, not a guess | |
| 13 | const GAP = .3; // dark seconds between two levers of the sequence | |
| 14 | const LEAD = .9; // seconds before the lamp starts a sequence | |
| 15 | const TAIL = .5; // seconds after the last lever before the player's turn | |
| 16 | const PULL = .35; // seconds a pulled lever stays lit | |
| 17 | const PAUSE = 2; // seconds the train takes to run through or halt | |
| 18 | const RESTART_AFTER = .6; | |
| 19 | ||
| 20 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 21 | // the lever at place i for a seed: the sequence for n+1 levers is the sequence for n with one more | |
| 22 | function leverAt(seed, i) { | |
| 23 | let h = (finite(seed) >>> 0) ^ Math.imul(i + 1, 0x9e3779b1); | |
| 24 | h = Math.imul(h ^ h >>> 15, 0x85ebca6b); | |
| 25 | h = Math.imul(h ^ h >>> 13, 0xc2b2ae35); | |
| 26 | return ((h ^ h >>> 16) >>> 0) % LEVERS; | |
| 27 | } | |
| 28 | function sequence(seed, length) { | |
| 29 | const out = []; | |
| 30 | for (let i = 0; i < Math.max(0, Math.floor(finite(length))); i++) out.push(leverAt(seed, i)); | |
| 31 | return out; | |
| 32 | } | |
| 33 | function extend(seq, seed) { return [...seq, leverAt(seed, seq.length)]; } | |
| 34 | // the end line: a win at WIN_AT trains routed or more, a loss below it | |
| 35 | function verdict(routed) { return finite(routed) >= WIN_AT ? 'win' : 'loss'; } | |
| 36 | ||
| 37 | function newGame(best = 0, seed = 0) { | |
| 38 | const sd = finite(seed) >>> 0; | |
| 39 | return { | |
| 40 | phase: 'lead', timer: 0, seed: sd, seq: sequence(sd, FIRST), shown: 0, got: 0, | |
| 41 | lit: new Array(LEVERS).fill(0), route: -1, jam: false, ok: false, | |
| 42 | routed: 0, lost: 0, wanted: -1, best: Math.max(0, finite(best)), record: false, won: false, | |
| 43 | }; | |
| 44 | } | |
| 45 | function finish(s, events) { | |
| 46 | s.phase = 'over'; s.timer = 0; s.won = verdict(s.routed) === 'win'; | |
| 47 | if (s.routed > s.best) { s.best = s.routed; s.record = true; } | |
| 48 | events.push({ type: 'over', routed: s.routed, lost: s.lost, verdict: verdict(s.routed), record: s.record }); | |
| 49 | } | |
| 50 | // the player pulls `lever`; only in their turn, never while the sequence is being shown | |
| 51 | function pull(s, lever) { | |
| 52 | const events = []; | |
| 53 | if (s.phase !== 'input' || !Number.isInteger(lever) || lever < 0 || lever >= LEVERS) return events; | |
| 54 | s.lit[lever] = PULL; | |
| 55 | if (lever === s.seq[s.got]) { | |
| 56 | s.got++; s.route = lever; | |
| 57 | events.push({ type: 'pull', lever, right: true }); | |
| 58 | if (s.got >= s.seq.length) { | |
| 59 | s.routed++; s.ok = true; s.phase = 'between'; s.timer = 0; | |
| 60 | events.push({ type: 'routed', length: s.seq.length, routed: s.routed, route: lever }); | |
| 61 | } | |
| 62 | } else { | |
| 63 | s.lost++; s.jam = true; s.ok = false; s.wanted = s.seq[s.got]; s.phase = 'between'; s.timer = 0; | |
| 64 | events.push({ type: 'pull', lever, right: false }); | |
| 65 | events.push({ type: 'lost', lever, wanted: s.wanted, lost: s.lost }); | |
| 66 | if (s.lost >= MAX_LOST) finish(s, events); | |
| 67 | } | |
| 68 | return events; | |
| 69 | } | |
| 70 | function advance(s, dt) { | |
| 71 | const events = []; | |
| 72 | dt = Math.min(1, Math.max(0, finite(dt))); | |
| 73 | for (let i = 0; i < LEVERS; i++) s.lit[i] = Math.max(0, s.lit[i] - dt); | |
| 74 | s.timer += dt; | |
| 75 | if (s.phase === 'lead' || s.phase === 'show') { | |
| 76 | if (s.phase === 'lead' && s.timer >= LEAD) { s.phase = 'show'; events.push({ type: 'show', length: s.seq.length }); } | |
| 77 | // the lamp lights each lever of the sequence in turn | |
| 78 | while (s.phase === 'show' && s.shown < s.seq.length && s.timer >= LEAD + s.shown * (SHOW + GAP)) { | |
| 79 | const lever = s.seq[s.shown++]; | |
| 80 | s.lit[lever] = SHOW; s.route = lever; | |
| 81 | events.push({ type: 'light', lever, index: s.shown - 1 }); | |
| 82 | } | |
| 83 | if (s.phase === 'show' && s.shown >= s.seq.length && s.timer >= LEAD + (s.seq.length - 1) * (SHOW + GAP) + SHOW + TAIL) { | |
| 84 | s.phase = 'input'; s.timer = 0; s.got = 0; s.route = -1; | |
| 85 | events.push({ type: 'turn' }); | |
| 86 | } | |
| 87 | } else if (s.phase === 'between' && s.timer >= PAUSE) { | |
| 88 | // right: one lever longer; wrong: the same sequence for the next train | |
| 89 | if (s.ok) s.seq = extend(s.seq, s.seed); | |
| 90 | s.phase = 'lead'; s.timer = 0; s.shown = 0; s.got = 0; s.ok = false; s.jam = false; s.wanted = -1; s.route = -1; | |
| 91 | events.push({ type: 'next', length: s.seq.length }); | |
| 92 | } | |
| 93 | return events; | |
| 94 | } | |
| 95 | // a tap after the game has been over for a moment starts the next one; otherwise null | |
| 96 | function again(s) { return s.phase === 'over' && s.timer > RESTART_AFTER ? newGame(s.best, s.seed + 1) : null; } | |
| 97 | ||
| 98 | const api = { LEVERS, FIRST, MAX_LOST, WIN_AT, SHOW, GAP, LEAD, TAIL, PULL, PAUSE, RESTART_AFTER, leverAt, sequence, extend, verdict, newGame, pull, advance, again }; | |
| 99 | if (typeof module !== 'undefined') module.exports = api; else root.Junction = api; | |
| 100 | })(typeof window !== 'undefined' ? window : globalThis); |
signal-box/junction.test.mjs added +181
| @@ -0,0 +1,181 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { LEVERS, FIRST, MAX_LOST, WIN_AT, SHOW, GAP, PAUSE, sequence, extend, verdict, newGame, pull, advance, again } from './junction.js'; | |
| 3 | ||
| 4 | const run = (s, seconds, dt = .02) => { const ev = []; for (let t = 0; t < seconds - 1e-9; t += dt) ev.push(...advance(s, dt)); return ev; }; | |
| 5 | const toInput = s => { let n = 0; while (s.phase !== 'input' && n++ < 2000) advance(s, .05); expect(s.phase).toBe('input'); }; | |
| 6 | const wrongFor = s => (s.seq[s.got] + 1) % LEVERS; | |
| 7 | // pull the whole sequence back and let the train go by | |
| 8 | function route(s) { toInput(s); const ev = []; for (const l of [...s.seq]) ev.push(...pull(s, l)); run(s, PAUSE + .1); return ev; } | |
| 9 | function lose(s) { toInput(s); const ev = pull(s, wrongFor(s)); run(s, PAUSE + .1); return ev; } | |
| 10 | ||
| 11 | test('the same seed gives the same sequence, and other seeds differ', () => { | |
| 12 | expect(sequence(5, 8)).toEqual(sequence(5, 8)); | |
| 13 | const seen = new Set(Array.from({ length: 40 }, (_, k) => sequence(k, 6).join())); | |
| 14 | expect(seen.size).toBeGreaterThan(20); | |
| 15 | }); | |
| 16 | ||
| 17 | test('five levers, and the first sequence is three long', () => { | |
| 18 | for (const l of sequence(9, 200)) expect([0, 1, 2, 3, 4]).toContain(l); | |
| 19 | expect(new Set(sequence(9, 200)).size).toBe(5); | |
| 20 | expect(LEVERS).toBe(5); | |
| 21 | expect(newGame(0, 3).seq.length).toBe(3); | |
| 22 | expect(FIRST).toBe(3); | |
| 23 | }); | |
| 24 | ||
| 25 | test('the next sequence is the last plus one lever', () => { | |
| 26 | const a = sequence(11, 3); | |
| 27 | expect(extend(a, 11)).toEqual(sequence(11, 4)); | |
| 28 | expect(extend(a, 11).slice(0, 3)).toEqual(a); | |
| 29 | }); | |
| 30 | ||
| 31 | test('the lamp lights each lever in order, each for at least 500 ms with a gap, then it is the player\'s turn', () => { | |
| 32 | const s = newGame(0, 4); | |
| 33 | const lights = []; | |
| 34 | for (let t = 0; s.phase !== 'input' && t < 3000; t++) for (const e of advance(s, .01)) if (e.type === 'light') lights.push({ ...e, at: t }); | |
| 35 | expect(lights.map(e => e.lever)).toEqual(s.seq); | |
| 36 | expect(s.phase).toBe('input'); | |
| 37 | expect(SHOW).toBeGreaterThanOrEqual(.5); | |
| 38 | expect(GAP).toBeGreaterThan(0); | |
| 39 | for (let i = 1; i < lights.length; i++) expect((lights[i].at - lights[i - 1].at) / 100).toBeGreaterThanOrEqual(SHOW + GAP - .02); | |
| 40 | }); | |
| 41 | ||
| 42 | test('a lit lever stays lit for its whole time and its points are set to its track', () => { | |
| 43 | const s = newGame(0, 4); | |
| 44 | run(s, 0.95); | |
| 45 | const l = s.seq[0]; | |
| 46 | expect(s.lit[l]).toBeGreaterThan(0); | |
| 47 | expect(s.route).toBe(l); | |
| 48 | run(s, SHOW - .1); | |
| 49 | expect(s.lit[l]).toBeGreaterThan(0); | |
| 50 | }); | |
| 51 | ||
| 52 | test('pulling while the sequence is being shown is ignored', () => { | |
| 53 | const s = newGame(0, 4); | |
| 54 | expect(pull(s, s.seq[0])).toEqual([]); | |
| 55 | run(s, 1.2); | |
| 56 | expect(s.phase).toBe('show'); | |
| 57 | expect(pull(s, s.seq[0])).toEqual([]); | |
| 58 | expect(pull(s, wrongFor({ seq: s.seq, got: 0 }))).toEqual([]); | |
| 59 | expect(s.got).toBe(0); | |
| 60 | expect(s.lost).toBe(0); | |
| 61 | }); | |
| 62 | ||
| 63 | test('the same levers in the same order route the train through on the last lever\'s track', () => { | |
| 64 | const s = newGame(0, 6); | |
| 65 | const ev = route(s); | |
| 66 | expect(ev.filter(e => e.type === 'pull').every(e => e.right)).toBe(true); | |
| 67 | const done = ev.find(e => e.type === 'routed'); | |
| 68 | expect(done.route).toBe(sequence(6, 3)[2]); | |
| 69 | expect(s.routed).toBe(1); | |
| 70 | expect(s.lost).toBe(0); | |
| 71 | }); | |
| 72 | ||
| 73 | test('a wrong lever jams the points and that train is lost', () => { | |
| 74 | const s = newGame(0, 6); | |
| 75 | toInput(s); | |
| 76 | const bad = wrongFor(s); | |
| 77 | const ev = pull(s, bad); | |
| 78 | expect(ev.map(e => e.type)).toEqual(['pull', 'lost']); | |
| 79 | expect(ev[1]).toMatchObject({ lever: bad, wanted: s.seq[0], lost: 1 }); | |
| 80 | expect(s.jam).toBe(true); | |
| 81 | expect(s.routed).toBe(0); | |
| 82 | expect(s.lost).toBe(1); | |
| 83 | expect(pull(s, s.seq[0])).toEqual([]); | |
| 84 | }); | |
| 85 | ||
| 86 | test('a wrong lever later in the sequence also loses the train', () => { | |
| 87 | const s = newGame(0, 6); | |
| 88 | toInput(s); | |
| 89 | pull(s, s.seq[0]); | |
| 90 | pull(s, s.seq[1]); | |
| 91 | const ev = pull(s, wrongFor(s)); | |
| 92 | expect(ev.some(e => e.type === 'lost')).toBe(true); | |
| 93 | expect(s.lost).toBe(1); | |
| 94 | }); | |
| 95 | ||
| 96 | test('each routed train adds one lever, starting at three', () => { | |
| 97 | const s = newGame(0, 8); | |
| 98 | const first = [...s.seq]; | |
| 99 | for (let n = 0; n < 4; n++) { expect(s.seq.length).toBe(3 + n); route(s); } | |
| 100 | expect(s.seq.length).toBe(7); | |
| 101 | expect(s.seq.slice(0, 3)).toEqual(first); | |
| 102 | }); | |
| 103 | ||
| 104 | test('a lost train comes back with the same sequence, not a longer one', () => { | |
| 105 | const s = newGame(0, 8); | |
| 106 | const before = [...s.seq]; | |
| 107 | lose(s); | |
| 108 | expect(s.phase).toBe('lead'); | |
| 109 | expect(s.seq).toEqual(before); | |
| 110 | }); | |
| 111 | ||
| 112 | test('three lost trains end the game, and not before', () => { | |
| 113 | const s = newGame(0, 2); | |
| 114 | lose(s); lose(s); | |
| 115 | expect(s.phase).not.toBe('over'); | |
| 116 | toInput(s); | |
| 117 | const ev = pull(s, wrongFor(s)); | |
| 118 | expect(MAX_LOST).toBe(3); | |
| 119 | expect(s.phase).toBe('over'); | |
| 120 | expect(ev.find(e => e.type === 'over')).toMatchObject({ lost: 3, routed: 0, verdict: 'loss' }); | |
| 121 | expect(pull(s, 0)).toEqual([]); | |
| 122 | }); | |
| 123 | ||
| 124 | test('the win line is eight trains routed: eight wins, seven does not', () => { | |
| 125 | expect(WIN_AT).toBe(8); | |
| 126 | expect(verdict(7)).toBe('loss'); | |
| 127 | expect(verdict(8)).toBe('win'); | |
| 128 | expect(verdict(12)).toBe('win'); | |
| 129 | expect(verdict(0)).toBe('loss'); | |
| 130 | const seven = newGame(0, 1); | |
| 131 | for (let n = 0; n < 7; n++) route(seven); | |
| 132 | lose(seven); lose(seven); toInput(seven); | |
| 133 | expect(pull(seven, wrongFor(seven)).find(e => e.type === 'over')).toMatchObject({ routed: 7, verdict: 'loss' }); | |
| 134 | expect(seven.won).toBe(false); | |
| 135 | const eight = newGame(0, 1); | |
| 136 | for (let n = 0; n < 8; n++) route(eight); | |
| 137 | lose(eight); lose(eight); toInput(eight); | |
| 138 | expect(pull(eight, wrongFor(eight)).find(e => e.type === 'over')).toMatchObject({ routed: 8, verdict: 'win' }); | |
| 139 | expect(eight.won).toBe(true); | |
| 140 | }); | |
| 141 | ||
| 142 | test('the best is the most trains routed and a record is flagged', () => { | |
| 143 | const s = newGame(2, 1); | |
| 144 | route(s); route(s); route(s); | |
| 145 | lose(s); lose(s); toInput(s); | |
| 146 | const ev = pull(s, wrongFor(s)); | |
| 147 | expect(s.best).toBe(3); | |
| 148 | expect(ev.find(e => e.type === 'over').record).toBe(true); | |
| 149 | const t = newGame(5, 1); | |
| 150 | route(t); lose(t); lose(t); toInput(t); | |
| 151 | pull(t, wrongFor(t)); | |
| 152 | expect(t.best).toBe(5); | |
| 153 | expect(t.record).toBe(false); | |
| 154 | }); | |
| 155 | ||
| 156 | test('out of range or odd levers are ignored', () => { | |
| 157 | const s = newGame(0, 4); | |
| 158 | toInput(s); | |
| 159 | for (const bad of [-1, 5, 1.5, NaN, '2', null, undefined]) expect(pull(s, bad)).toEqual([]); | |
| 160 | expect(s.lost).toBe(0); | |
| 161 | expect(s.got).toBe(0); | |
| 162 | }); | |
| 163 | ||
| 164 | test('a new game starts after the game has been over for a moment', () => { | |
| 165 | const s = newGame(0, 2); | |
| 166 | lose(s); lose(s); toInput(s); pull(s, wrongFor(s)); | |
| 167 | expect(again(s)).toBe(null); | |
| 168 | run(s, .7); | |
| 169 | const next = again(s); | |
| 170 | expect(next.phase).toBe('lead'); | |
| 171 | expect(next.routed).toBe(0); | |
| 172 | expect(next.lost).toBe(0); | |
| 173 | expect(next.seq.length).toBe(3); | |
| 174 | expect(again(next)).toBe(null); | |
| 175 | }); | |
| 176 | ||
| 177 | test('bad time steps do not break the clock', () => { | |
| 178 | const s = newGame(0, 4); | |
| 179 | advance(s, NaN); advance(s, -5); advance(s, Infinity); | |
| 180 | expect(Number.isFinite(s.timer)).toBe(true); | |
| 181 | }); |
signal-box/page.test.mjs added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | import vm from 'node:vm'; | |
| 2 | import { test, expect } from 'bun:test'; | |
| 3 | import { boot } from '../playtest.mjs'; | |
| 4 | ||
| 5 | // the five levers stand at x = 120, 165, 210, 255 and 300 on the 360-wide canvas | |
| 6 | const state = g => vm.runInContext('P', g.window); | |
| 7 | const X = lever => 120 + lever * 45; | |
| 8 | function untilTurn(g) { for (let n = 0; state(g).phase !== 'input' && n < 400; n++) g.run(.05); expect(state(g).phase).toBe('input'); } | |
| 9 | ||
| 10 | test('tapping the levers back routes the train and the HUD follows; a wrong lever loses it', () => { | |
| 11 | const g = boot('signal-box'); | |
| 12 | g.run(.2); | |
| 13 | untilTurn(g); | |
| 14 | expect(String(g.el('length').textContent)).toBe('3'); | |
| 15 | for (const lever of [...state(g).seq]) { g.tap(X(lever), 150); g.run(.1); } | |
| 16 | expect(String(g.el('routed').textContent)).toBe('1'); | |
| 17 | untilTurn(g); | |
| 18 | expect(String(g.el('length').textContent)).toBe('4'); | |
| 19 | g.tap(X((state(g).seq[0] + 1) % 5), 150); | |
| 20 | expect(String(g.el('lost').textContent)).toBe('1/3'); | |
| 21 | expect(g.errors).toEqual([]); | |
| 22 | }); | |
| 23 | ||
| 24 | test('keys 1 to 5 pull the levers, and taps while the lamp is showing do nothing', () => { | |
| 25 | const g = boot('signal-box'); | |
| 26 | g.run(1.5); | |
| 27 | expect(state(g).phase).toBe('show'); | |
| 28 | g.tap(X(0), 150); g.press('1', .05); | |
| 29 | expect(state(g).lost).toBe(0); | |
| 30 | untilTurn(g); | |
| 31 | g.press(String(state(g).seq[0] + 1), .05); | |
| 32 | expect(state(g).got).toBe(1); | |
| 33 | expect(g.errors).toEqual([]); | |
| 34 | }); |
new above
offline