Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Add Shunting Yard: the playable page and its place in the catalogue, on the rules in `shunting-yard/yard.js` #185
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/163-add-shunting-yard-the-playable-page-and → main 6 commits fork
8 files
changed +368
−2
README.md +3 −2
| @@ -55,6 +55,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am | ||
| 55 | 55 | | [](sandcastle/) | A square beach with a sandcastle on the far edge, rocks scattered over the sand and the sea along the near edge: tap a sand square to pat down a wall (or move a cursor with the arrow keys and press Space), four walls before each tide, then tap tide (or press Enter) and the water floods every square it can reach from the sea, a little further each time, never through a wall or a rock, and washes away half the walls it touches; keep the castle dry through five tides, the HUD showing the tide, the walls left and the dry squares; input is ignored while the water spreads, the surf line ripples (stopped under reduced motion), and sand, water, walls and rocks differ by texture as well as colour (forged by the crew on the engine and shell above, not by the original creators; rules in `sandcastle/tide.js`) | Tap a sand square, then tide; arrows and Space to build, Enter for the tide | |
| 56 | 56 | | [](lock-keeper/) | A flight of three canal locks climbing left to right, red narrowboats waiting at the bottom to go up and blue ones at the top to come down, in a seeded order (three rounds shipped, each with a par): tap a paddle or gate to work it and a boat to move it into or out of its lock, or Left and Right to pick a lock and 1 to 5 for its top paddle, bottom paddle, top gate, bottom gate and a boat; a gate opens only on level water, a paddle fills or empties the lock but not while the far gate is open, two open paddles flood the lock and lose the round, a refusal says why, and the end shows operations against par (forged by the crew on the engine and shell above, not by the original creators; rules in `lock-keeper/lock.js`) | Tap; Left and Right, 1 to 5 | |
| 57 | 57 | | [](allotment/) | A five by five garden of raised beds with a bench holding the next seed packet: tap a bed to plant the packet there (or arrow keys to move and Space to plant); twelve packets in a season and every crop scores 1 plus its own rule for each touching bed (up, down, left, right): beans +3 per sweetcorn, sweetcorn -1 per sweetcorn, carrots -2 per onion, onion +2 per lettuce, lettuce +2 per carrots; 28 points by the last packet wins, against the best layout the rules could find (a seeded hand of eight seasons; forged by the crew on the engine and shell above, not by the original creators; rules in `allotment/plot.js`) | Tap a bed; arrows + Space | |
| 58 | | [](shunting-yard/) | A railway yard seen from above: a mixed-up train of numbered wagons waits on the arrival track, two sidings hold 3 wagons each, and the departure track takes the wagons only in order 1, 2, 3...; lift the end wagon of a track and set it down on another (nothing goes back to the arrival track), five levels of 3 to 7 wagons, each with a move target (5, 7, 9, 11, 13) that every yard solves within, and the game is won when all five are cleared within the targets' total; every wagon wears its number on a plate, so order never rests on colour (forged by the crew on the engine and shell above, not by the original creators; rules in `shunting-yard/yard.js`) | Tap a track to lift its end wagon, tap another to set it down; 1-4 pick the tracks, arrows move a ring, Space lifts or sets down | | |
| 58 | 59 | | [](empire/) | A real-time strategy game on a 44 by 44 map against a red bot (easy, normal or hard): four villagers and a town center each, gather food, wood, gold and stone, build houses, camps, farms and military buildings, climb the Dark, Feudal, Castle and Imperial Ages, research upgrades, train militia, spearmen, archers, knights and rams, and destroy every town center and castle of the enemy; fog of war, a minimap, attack alerts, pause, 1x/2x/4x speed, an autopilot, a save that survives a reload and a best time per level (forged by the crew on the engine and shell above, not by the original creators) | Tap or drag a box to select, tap to command, panel buttons to build and train; arrows move the view, Enter taps its centre cross, 1-9 press buttons | |
| 59 | 60 | | [](hot-air-balloon/) | Five flights over patchwork farm fields with hedgerows, a windsock and one field marked with a white cross: hold the burner and the balloon climbs slowly after a short lag, let go and it sinks; the air has three height bands that each blow their own way and a little differently each flight, shown by drifting cloud wisps, three arrows at the left and a pennant on the basket, so you steer only by choosing a height (the ready screen before each flight already shows that flight's winds, so read them first); touching the ground ends the flight and the landing scores by distance from the cross (on it 5, inside its field 3, a neighbouring field 1, trees or the pond 0), each flight from a new launch point; 15 or more of 25 wins; the balloon's shadow on the fields shows where it is over (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space or the up arrow | |
| 60 | 61 | | [](go-kart/) | Three races of three laps round a village track against three rivals: hold to drive, let go to brake, and a yellow board before each bend shows the fastest speed to enter it at; go in faster and you sit a second in the hay bales; first scores 3, second 2, third 1, and 6 points wins (forged by the crew on the engine and shell above, not by the original creators) | Hold; space | |
| @@ -80,7 +81,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is | ||
| 80 | 81 | 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. |
| 81 | 82 | |
| 82 | 83 | ## Add a game |
| 83 | 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, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall, Lock Keeper, Ferryman, Tower Duel, Sandcastle Tide, Hedge Maze, Allotment and Market Barrow 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`. | |
| 84 | 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, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall, Lock Keeper, Ferryman, Tower Duel, Sandcastle Tide, Hedge Maze, Allotment, Market Barrow and Shunting Yard 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`. | |
| 84 | 85 | |
| 85 | 86 | - `town.js` is the town's layout, pure data with no drawing: `window.PixelTown.layout(GAMES)` gives one isometric building per game (plot, screen position under the fixed 30-degree camera, accent, id) with trees in the spare plots, and `pick(town, x, y, filter)` gives the id of the front-most building under a screen point, or null. Nothing loads it yet; the drawing and the page are the second half of #99. |
| 86 | 87 | - `shell.js` provides the game menu, the Rules popup, the credits and the background music. The menu lists the games grouped under their kind (the not-yet-made ones last, under Soon) and scrolls within the screen; type in its find box to narrow it by a word of the title, kind, input or blurb (keys typed there never reach the game), and press Escape to close it. |
| @@ -97,7 +98,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules | ||
| 97 | 98 | - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges. |
| 98 | 99 | - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard. |
| 99 | 100 | - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide. |
| 100 | - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move), and Bowls Green's hedge leaves stir and a cloud shadow drifts across its green (the rolling woods are play, and still move), and Seed Packets' wall clock ticks its second hand and its watering can drips, and Hoopla Stall's bunting flutters (the tossed ring is play, and still moves), and Lock Keeper's water surface ripples (the boats, gates and rising water are play, and still move), and Ferryman's river ripples (the ferry and its passengers are play, and still move), and Tower Duel's river ripples shift and the king towers' pennants stir (the troops and the fireball are play, and still move), and Hedge Maze's fountain splashes (the walker is play, and still moves), and Allotment's planted crops sway (the planting is play) and Market Barrow's stall awnings flutter (the barrow is play, and still moves); all of it stops under `prefers-reduced-motion`. | |
| 101 | - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, Sheepdog's crow on the wall shifts and dips its head, Hot Air Balloon's windsock and cloud wisps drift, Cloakroom's coats sway and the light under its door moves, Go-Kart Fete's chequered flags flutter and its spectators wave, Egg Basket's hens peck and the straw in its basket stirs (its rolling eggs are play, not ambience, and still move), and Dinghy Race's water ripples come and go and its start-line flags flutter (the boats are play, and still sail), and Coconut Shy's bunting flutters and its stallholder shifts and waves (the thrown ball and wobbling coconuts are play, and still move), and Bowls Green's hedge leaves stir and a cloud shadow drifts across its green (the rolling woods are play, and still move), and Seed Packets' wall clock ticks its second hand and its watering can drips, and Hoopla Stall's bunting flutters (the tossed ring is play, and still moves), and Lock Keeper's water surface ripples (the boats, gates and rising water are play, and still move), and Ferryman's river ripples (the ferry and its passengers are play, and still move), and Tower Duel's river ripples shift and the king towers' pennants stir (the troops and the fireball are play, and still move), and Hedge Maze's fountain splashes (the walker is play, and still moves), and Allotment's planted crops sway (the planting is play), Market Barrow's stall awnings flutter (the barrow is play, and still moves) and Shunting Yard's engine puffs steam (the wagons are play, and still move); all of it stops under `prefers-reduced-motion`. | |
| 101 | 102 | |
| 102 | 103 | ## Empire Age |
| 103 | 104 |
index.html +1
| @@ -114,6 +114,7 @@ footer a::after { content: none; } | ||
| 114 | 114 | <li data-kind="Racing" data-input="Hold" style="--accent:#e0a526"><a href="go-kart/">Go-Kart Fete</a><span>Hold to race, let go for the bends: three laps round the hay bales against three rivals</span><span>Game forged by the crew</span><span class="tags">Racing · Hold</span></li> |
| 115 | 115 | <li data-kind="Memory" data-input="Tap" style="--accent:#9c3d6b"><a href="cloakroom/">Cloakroom</a><span>Turn two tags at a time and hand back every matching coat before the dance lets out</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li> |
| 116 | 116 | <li data-kind="Strategy" data-input="Tap" style="--accent:#8a3b3b"><a href="tower-duel/">Tower Duel</a><span>Tap a card, tap your half: send troops over the bridges and topple the rival king tower</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li> |
| 117 | <li data-kind="Puzzle" data-input="Tap" style="--accent:#8a4b2f"><a href="shunting-yard/">Shunting Yard</a><span>Shunt the wagons through the sidings until the train leaves in order</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li> | |
| 117 | 118 | <li data-kind="Puzzle" data-input="Keys" style="--accent:#3d6e4f"><a href="hedge-maze/">Hedge Maze</a><span>Find the way through the hedges to the fountain before the gardener rings the bell</span><span>Game forged by the crew</span><span class="tags">Puzzle · Keys</span></li> |
| 118 | 119 | </ul> |
| 119 | 120 | <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer> |
og/home.png
Binary file not shown.
og/shunting-yard.png added
Binary file not shown.
rounds.mjs +5
| @@ -128,6 +128,11 @@ export const ROUNDS = { | ||
| 128 | 128 | if (index >= 0) { g.press(String(index + 1)); g.tap(...g.read(`scr(${x}, 9)`)); } |
| 129 | 129 | g.run(.2); |
| 130 | 130 | } }, |
| 131 | // lift and set down along the rules' own shortest solution of the yard, with the number keys | |
| 132 | 'shunting-yard': { over: /play again/, outcome: /Won: 5 levels cleared in \d+ moves/, beat: g => { | |
| 133 | const [from, to] = g.read('Yard.solve(P)[0]'); | |
| 134 | g.press(String(from + 1)); g.press(String(to + 1)); | |
| 135 | } }, | |
| 131 | 136 | // walk the one path to the fountain by the arrow keys, maze after maze; once five are solved, wait out the bell |
| 132 | 137 | 'hedge-maze': { over: /play again/, outcome: /\d+ mazes solved, best \d+\. You win!/, beat: g => { |
| 133 | 138 | const s = g.read('P'); |
serve.test.mjs +7
| @@ -528,6 +528,13 @@ test('Tower Duel and its rules script are served without a track', async () => { | ||
| 528 | 528 | expect((await fetch(base + '/tower-duel/duel.js')).status).toBe(200); |
| 529 | 529 | }); |
| 530 | 530 | |
| 531 | test('Shunting Yard and its rules script are served without a track', async () => { | |
| 532 | const page = await fetch(base + '/shunting-yard/'); | |
| 533 | expect(page.status).toBe(200); | |
| 534 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); | |
| 535 | expect((await fetch(base + '/shunting-yard/yard.js')).status).toBe(200); | |
| 536 | }); | |
| 537 | ||
| 531 | 538 | test('Hedge Maze and its rules script are served without a track', async () => { |
| 532 | 539 | const page = await fetch(base + '/hedge-maze/'); |
| 533 | 540 | expect(page.status).toBe(200); |
shell.js +1
| @@ -54,6 +54,7 @@ window.PixelPlays = (() => { | ||
| 54 | 54 | { id: 'go-kart', title: 'Go-Kart Fete', blurb: 'Hold to race, let go for the bends: three laps round the hay bales against three rivals', kind: 'Racing', input: 'Hold', accent: '#e0a526', music: false, forged: true }, |
| 55 | 55 | { id: 'cloakroom', title: 'Cloakroom', blurb: 'Turn two tags at a time and hand back every matching coat before the dance lets out', kind: 'Memory', input: 'Tap', accent: '#9c3d6b', music: false, forged: true }, |
| 56 | 56 | { id: 'tower-duel', title: 'Tower Duel', blurb: 'Tap a card, tap your half: send troops over the bridges and topple the rival king tower', kind: 'Strategy', input: 'Tap', accent: '#8a3b3b', music: false, forged: true }, |
| 57 | { id: 'shunting-yard', title: 'Shunting Yard', blurb: 'Shunt the wagons through the sidings until the train leaves in order', kind: 'Puzzle', input: 'Tap', accent: '#8a4b2f', music: false, forged: true }, | |
| 57 | 58 | { id: 'hedge-maze', title: 'Hedge Maze', blurb: 'Find the way through the hedges to the fountain before the gardener rings the bell', kind: 'Puzzle', input: 'Keys', accent: '#3d6e4f', music: false, forged: true }, |
| 58 | 59 | ]; |
| 59 | 60 | const MUSIC_VOLUME = .4; |
shunting-yard/index.html added +351
| @@ -0,0 +1,351 @@ | ||
| 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>Shunting Yard</title> | |
| 7 | <!-- og:begin --> | |
| 8 | <meta name="description" content="Shunt the wagons through the sidings until the train leaves in order"> | |
| 9 | <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/shunting-yard/"> | |
| 10 | <meta property="og:type" content="website"> | |
| 11 | <meta property="og:site_name" content="Pixel Plays"> | |
| 12 | <meta property="og:title" content="Shunting Yard"> | |
| 13 | <meta property="og:description" content="Shunt the wagons through the sidings until the train leaves in order"> | |
| 14 | <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/shunting-yard/"> | |
| 15 | <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/shunting-yard.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="Shunting Yard: 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; : #8a4b2f; } | |
| 24 | * { box-sizing: border-box; } | |
| 25 | html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; } | |
| 26 | html, body { height: 100%; margin: 0; background: var(); color: var(); } | |
| 27 | body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; } | |
| 28 | #stage { position: fixed; inset: 0; display: grid; place-items: center; } | |
| 29 | canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; } | |
| 30 | .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; align-items: flex-end; gap: 16px; pointer-events: none; } | |
| 31 | #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; } | |
| 32 | #bottom { bottom: max(14px, env(safe-area-inset-bottom)); } | |
| 33 | .row { display: flex; align-items: center; gap: 8px; color: var(); } | |
| 34 | .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; } | |
| 35 | .row span { color: var(); } | |
| 36 | #status { color: var(); min-height: 1.35em; } | |
| 37 | button { pointer-events: auto; font: inherit; color: var(); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; } | |
| 38 | button:hover, button:focus-visible { color: var(); } | |
| 39 | button:focus-visible { outline: 2px solid var(); outline-offset: 2px; } | |
| 40 | noscript p { position: fixed; inset: 40% 16px auto; margin: 0; text-align: center; color: var(); } | |
| 41 | </style> | |
| 42 | </head> | |
| 43 | <body> | |
| 44 | <div id="stage"><canvas id="c" tabindex="0" aria-label="A railway yard seen from above: the arrival track at the top holds a mixed-up train of numbered wagons, two short sidings sit below it, and the departure track with the engine is at the bottom. Tap a track to lift its end wagon and tap another track to set it down, or press 1 to 4 for the tracks (or the arrow keys to move and Space to lift or set down). Wagons may leave only in order 1, 2, 3 and so on; each siding holds 3. Clear five levels within the move targets."></canvas></div> | |
| 45 | <noscript><p>Shunting Yard needs JavaScript to play.</p></noscript> | |
| 46 | <div id="scores"> | |
| 47 | <div class="row"><b id="level">1 of 5</b><span>level</span></div> | |
| 48 | <div class="row"><b id="moves">0 of 5</b><span>moves this level</span></div> | |
| 49 | </div> | |
| 50 | <div class="hud" id="bottom"> | |
| 51 | <div id="status" role="status" aria-live="polite"></div> | |
| 52 | <button id="mute" type="button" aria-pressed="false">sound on</button> | |
| 53 | </div> | |
| 54 | <script src="../shell.js"></script> | |
| 55 | <script> | |
| 56 | PixelPlays.mount({ | |
| 57 | id: 'shunting-yard', | |
| 58 | rules: [ | |
| 59 | 'Tap a track to lift its end wagon, tap another to set it down; keys 1-4 pick the tracks.', | |
| 60 | 'Wagons leave on the last track in order 1, 2, 3...; each siding holds 3.', | |
| 61 | 'Nothing is shunted back onto the first track.', | |
| 62 | 'Clear five levels within the move targets to win.', | |
| 63 | ], | |
| 64 | }); | |
| 65 | </script> | |
| 66 | <script>window.PP_SCENE = { originY: -4, shadowX: 1.3, shadowY: -.12 };</script> | |
| 67 | <script src="../engine.js"></script> | |
| 68 | <script src="yard.js"></script> | |
| 69 | <script> | |
| 70 | 'use strict'; | |
| 71 | ||
| 72 | const Yard = window.ShuntingYard; | |
| 73 | const TRACKS = Yard.DEPARTURE + 1; | |
| 74 | const PITCH = 6.2, SLOT = 3.6, U0 = -14.4; // metres between tracks, along a wagon slot, and the buffer stops' end of the yard | |
| 75 | const ARRIVAL_SLOTS = 7, SIDING_SLOTS = Yard.CAPACITY; | |
| 76 | const slotsOf = t => (t === 0 || t === Yard.DEPARTURE ? ARRIVAL_SLOTS : SIDING_SLOTS); | |
| 77 | const trackV = t => (t - (TRACKS - 1) / 2) * PITCH; | |
| 78 | const slotU = i => U0 + (i + .5) * SLOT; | |
| 79 | const endU = t => U0 + slotsOf(t) * SLOT + .3; | |
| 80 | const ENGINE_U = U0 + ARRIVAL_SLOTS * SLOT + 1.6; | |
| 81 | ||
| 82 | const BALLAST = [168, 158, 142], BALLAST_ALT = [158, 148, 134], SLEEPER = [112, 84, 60], RAIL_STEEL = [196, 196, 202], FRAME = [96, 110, 74]; | |
| 83 | const POST = [92, 70, 52], ROOF = [74, 66, 62], WHEEL = [44, 42, 46]; | |
| 84 | const ENGINE_BODY = [138, 75, 47], ENGINE_DARK = [86, 52, 38], BRASS = [214, 168, 66]; | |
| 85 | const WAGONS = [[176, 84, 72], [88, 130, 176], [206, 164, 72], [98, 150, 104], [150, 106, 168], [220, 130, 80], [96, 148, 156]]; | |
| 86 | const INK_PIX = rgb(28, 27, 25), ACCENT_PIX = rgb(138, 75, 47), PLATE_PIX = rgb(255, 255, 255), RING_PIX = rgb(138, 75, 47); | |
| 87 | const LIFT = 1.9, RIDE = 1.45, HALF = 1.2, GIRTH = 1.15; | |
| 88 | const GLYPHS = { 0: '111101101101111', 1: '010110010010111', 2: '111001111100111', 3: '111001111001111', 4: '101101111001001', 5: '111100111001111', 6: '111100111101111', 7: '111001001001001', 8: '111101111101111', 9: '111101111001111' }; | |
| 89 | ||
| 90 | const eng = (u, v, z) => [(u + v) / R2, (v - u) / R2, z]; | |
| 91 | const scr = (u, v, z = 0) => { const p = project(...eng(u, v, z)); return [p.sx, p.sy]; }; | |
| 92 | const trackAt = (px, py) => { // the track nearest a canvas pixel, aiming at mid-wagon height | |
| 93 | const g = unproject(px, py + 10); | |
| 94 | return Math.max(0, Math.min(TRACKS - 1, Math.round((g.x + g.y) / R2 / PITCH + (TRACKS - 1) / 2))); | |
| 95 | }; | |
| 96 | ||
| 97 | /* ---------- state ---------- */ | |
| 98 | const nodes = {}; | |
| 99 | for (const k of ['level', 'moves', 'status']) nodes[k] = document.getElementById(k); | |
| 100 | const shown = {}; | |
| 101 | function setText(key, text) { | |
| 102 | if (shown[key] === text) return; | |
| 103 | shown[key] = text; | |
| 104 | nodes[key].textContent = text; | |
| 105 | } | |
| 106 | const fresh = () => Yard.start(Math.floor(Math.random() * 4294967296)); | |
| 107 | let P = fresh(); | |
| 108 | // sel: the track whose end wagon is lifted, -1 for none; cur: the keyboard's track, shown once a key has moved it | |
| 109 | const G = { time: 0, noteUntil: 0, sel: -1, cur: 0, ring: false, end: '' }; | |
| 110 | ||
| 111 | function renderHud() { | |
| 112 | setText('level', `${P.level} of ${Yard.LAST_LEVEL}`); | |
| 113 | setText('moves', `${P.levelMoves} of ${Yard.target(P.level)}`); | |
| 114 | } | |
| 115 | function note(text) { setText('status', text); G.noteUntil = G.time + 1.8; } | |
| 116 | const REFUSED = { | |
| 117 | 'empty-track': 'that track has no wagon to lift', departed: 'those wagons have left', 'arrival-closed': 'nothing goes back onto the first track', | |
| 118 | 'siding-full': 'that siding is full', 'out-of-order': 'the train leaves in order: that wagon is not next', 'game-over': 'the game is over', | |
| 119 | }; | |
| 120 | ||
| 121 | /* ---------- baked scene ---------- */ | |
| 122 | function onRails(t, u) { return u >= U0 - .3 && u <= (t === Yard.DEPARTURE ? ENGINE_U + 3.2 : endU(t)); } | |
| 123 | function groundColor(x, y, ix, iy) { | |
| 124 | const u = (x - y) / R2, v = (x + y) / R2; | |
| 125 | if (u < U0 - 2.4 || u > ENGINE_U + 3.8 || Math.abs(v) > trackV(TRACKS - 1) + 3.4) return 0; | |
| 126 | const t = .96 + (hash(ix, iy) - .5) * .06; | |
| 127 | const shade = c => rgb(c[0] * t, c[1] * t, c[2] * t); | |
| 128 | if (u < U0 - 1.8 || u > ENGINE_U + 3.2 || Math.abs(v) > trackV(TRACKS - 1) + 2.8) return shade(FRAME); | |
| 129 | for (let k = 0; k < TRACKS; k++) { | |
| 130 | const d = v - trackV(k); | |
| 131 | if (!onRails(k, u) || Math.abs(d) > 1.4) continue; | |
| 132 | if (Math.abs(Math.abs(d) - .75) < .2) return shade(RAIL_STEEL); | |
| 133 | if (((u - U0) / 1.2) % 1 < .3) return shade(SLEEPER); | |
| 134 | } | |
| 135 | return shade((ix + iy) & 4 ? BALLAST : BALLAST_ALT); | |
| 136 | } | |
| 137 | function bakeStops() { | |
| 138 | for (let k = 0; k < TRACKS; k++) { | |
| 139 | const ends = k === 0 || k === Yard.DEPARTURE ? [U0 - .2] : [U0 - .2, endU(k) - .1]; | |
| 140 | for (const u of ends) { | |
| 141 | for (const s of [-1, 1]) capsule(eng(u, trackV(k) + s * .9, 0), eng(u, trackV(k) + s * .9, 1.1), .2, .2, () => POST, 'solid'); | |
| 142 | capsule(eng(u, trackV(k) - .9, .9), eng(u, trackV(k) + .9, .9), .24, .24, () => POST, 'solid'); | |
| 143 | } | |
| 144 | } | |
| 145 | } | |
| 146 | // the engine waits at the end of the departure track | |
| 147 | function bakeEngine() { | |
| 148 | const v = trackV(Yard.DEPARTURE), at = (u, z, dv = 0) => eng(u, v + dv, z); | |
| 149 | capsule(at(ENGINE_U - 1.2, 1.6), at(ENGINE_U + 2.4, 1.6), 1.25, 1.25, () => ENGINE_BODY, 'solid'); | |
| 150 | capsule(at(ENGINE_U - 1.5, 1.45), at(ENGINE_U + 2.7, 1.45), .3, .3, () => ENGINE_DARK, 'solid'); | |
| 151 | capsule(at(ENGINE_U - 1.4, 2.7), at(ENGINE_U - 1.4, 3.8), 1.05, 1.05, () => ENGINE_DARK, 'solid'); | |
| 152 | capsule(at(ENGINE_U - 1.7, 3.8), at(ENGINE_U - 1.1, 3.8), 1.15, 1.15, () => ROOF, 'solid'); | |
| 153 | capsule(at(ENGINE_U + 2.2, 2.6), at(ENGINE_U + 2.2, 3.8), .32, .46, () => ENGINE_DARK, 'solid'); | |
| 154 | capsule(at(ENGINE_U + .6, 2.7), at(ENGINE_U + .6, 3.2), .4, .3, () => BRASS, 'solid'); | |
| 155 | for (const du of [-.8, .6, 1.9]) for (const s of [-1, 1]) capsule(at(ENGINE_U + du, .7, s * 1.25), at(ENGINE_U + du, .7, s * 1.3), .7, .7, () => WHEEL, 'solid'); | |
| 156 | } | |
| 157 | function bake() { | |
| 158 | ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0); | |
| 159 | tufts.length = 0; leaves.length = 0; | |
| 160 | zb.fill(-1e9); | |
| 161 | pix.fill(rgb(255, 255, 255)); | |
| 162 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 163 | const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy); | |
| 164 | if (!c) continue; | |
| 165 | pix[i] = c; ground[i] = 1; | |
| 166 | zb[i] = (g.x + g.y) / R2 * COS; | |
| 167 | } | |
| 168 | groundZ.set(zb); | |
| 169 | bakeStops(); | |
| 170 | bakeEngine(); | |
| 171 | bakeOcclusion(); | |
| 172 | staticShadow.set(shadowMask); | |
| 173 | applyShadows(groundZ); | |
| 174 | bakedPix.set(pix); | |
| 175 | bakedZ.set(zb); | |
| 176 | } | |
| 177 | ||
| 178 | /* ---------- drawing the yard ---------- */ | |
| 179 | const plates = []; // number plates to stamp once the 3D is down: [wagon, u, v, z] | |
| 180 | function drawWagon(n, u, v, lift) { | |
| 181 | const z = RIDE + lift, col = WAGONS[(n - 1) % WAGONS.length], low = [col[0] * .8, col[1] * .8, col[2] * .8]; | |
| 182 | dynamicAdd(eng(u - HALF, v, z), eng(u + HALF, v, z), GIRTH, GIRTH, () => col); | |
| 183 | dynamicAdd(eng(u - HALF, v, z + GIRTH), eng(u + HALF, v, z + GIRTH), .45, .45, () => ROOF); | |
| 184 | dynamicAdd(eng(u - HALF, v, .55 + lift), eng(u + HALF, v, .55 + lift), .3, .3, () => low); | |
| 185 | for (const du of [-1.3, 1.3]) dynamicAdd(eng(u + du, v, .5 + lift), eng(u + du, v, .55 + lift), .5, .5, () => WHEEL); | |
| 186 | plates.push([n, u, v + GIRTH, z]); | |
| 187 | } | |
| 188 | function stamp(ch, left, top, scale, color) { | |
| 189 | const g = GLYPHS[ch]; | |
| 190 | for (let k = 0; k < 15; k++) if (g[k] === '1') for (let dy = 0; dy < scale; dy++) for (let dx = 0; dx < scale; dx++) { | |
| 191 | const x = left + (k % 3) * scale + dx, y = top + Math.floor(k / 3) * scale + dy; | |
| 192 | if (x >= 0 && x < W && y >= 0 && y < H) pix[y * W + x] = color; | |
| 193 | } | |
| 194 | } | |
| 195 | // every wagon wears its number on a white plate, so the order never rests on colour; a plate hides behind whatever stands in front | |
| 196 | function drawPlates() { | |
| 197 | for (const [n, u, v, z] of plates) { | |
| 198 | const p = project(...eng(u, v, z)), left = Math.round(p.sx) - 5, top = Math.round(p.sy) - 7; | |
| 199 | for (let y = 0; y < 14; y++) for (let x = 0; x < 10; x++) { | |
| 200 | const px = left + x, py = top + y; | |
| 201 | if (px < 0 || px >= W || py < 0 || py >= H || zb[py * W + px] > p.d + .5) continue; | |
| 202 | pix[py * W + px] = x === 0 || y === 0 || x === 9 || y === 13 ? INK_PIX : PLATE_PIX; | |
| 203 | } | |
| 204 | stamp(n, left + 2, top + 2, 2, INK_PIX); | |
| 205 | } | |
| 206 | plates.length = 0; | |
| 207 | } | |
| 208 | // 1-4 on the ground at the buffer end of each track, lit for the lifted track | |
| 209 | function drawNumbers() { | |
| 210 | for (let k = 0; k < TRACKS; k++) { | |
| 211 | const [sx, sy] = scr(U0 - 1.5, trackV(k)), on = k === G.sel || (G.ring && k === G.cur); | |
| 212 | stamp(k + 1, Math.round(sx) - 3, Math.round(sy) - 5, 2, on ? ACCENT_PIX : INK_PIX); | |
| 213 | } | |
| 214 | } | |
| 215 | // the keyboard's ring, round the slot a wagon would leave from or arrive at | |
| 216 | function drawRing() { | |
| 217 | if (!G.ring || P.status !== 'playing') return; | |
| 218 | const t = G.cur, slot = Math.min(slotsOf(t) - 1, Math.max(0, P.tracks[t].length - (G.sel === t ? 1 : 0))), pts = []; | |
| 219 | for (let i = 0; i < 40; i++) { const a = i / 40 * Math.PI * 2, [sx, sy] = scr(slotU(slot) + Math.cos(a) * 2, trackV(t) + Math.sin(a) * 2); pts.push([Math.round(sx), Math.round(sy)]); } | |
| 220 | haloDots(pts); | |
| 221 | drawDots(pts, RING_PIX); | |
| 222 | } | |
| 223 | // the engine's steam: three puffs rise and thin out at 8 fps; under reduced motion the stack is clear | |
| 224 | function drawSteam() { | |
| 225 | if (STILL) return; | |
| 226 | const step = Math.floor(G.time * WIND_FPS), v = trackV(Yard.DEPARTURE); | |
| 227 | for (let i = 0; i < 3; i++) { | |
| 228 | const age = (step + i * 8) % 24, r = .35 + age * .03, z = 4 + age * .16, u = ENGINE_U + 2.2 - age * .07; | |
| 229 | const shade = 244 - age * 2; | |
| 230 | capsule(eng(u, v, z), eng(u, v, z + .1), r, r, () => [shade, shade, shade + 6], 'solid'); | |
| 231 | } | |
| 232 | } | |
| 233 | ||
| 234 | function draw() { | |
| 235 | pix.set(bakedPix); | |
| 236 | zb.set(bakedZ); | |
| 237 | pendingShadows.length = 0; | |
| 238 | P.tracks.forEach((wagons, t) => wagons.forEach((n, i) => drawWagon(n, slotU(i), trackV(t), t === G.sel && i === wagons.length - 1 ? LIFT : 0))); | |
| 239 | flushShadows(); | |
| 240 | drawSteam(); | |
| 241 | applyShadows(bakedZ); | |
| 242 | shadeEdges(); | |
| 243 | drawPlates(); | |
| 244 | drawNumbers(); | |
| 245 | drawRing(); | |
| 246 | ctx.putImageData(image, 0, 0); | |
| 247 | } | |
| 248 | ||
| 249 | /* ---------- game ---------- */ | |
| 250 | function act(events) { | |
| 251 | for (const e of events) { | |
| 252 | if (e.type === 'move') sound(e.to === Yard.DEPARTURE ? 392 : 262, .09, 'triangle'); | |
| 253 | if (e.type === 'cleared') { sound(523, .25, 'sine'); sound(784, .4, 'sine', .12); note(`level ${e.level} cleared in ${e.moves} moves`); } | |
| 254 | if (e.type === 'won' || e.type === 'lost') { | |
| 255 | G.end = `${P.line} · tap or press a key to play again`; G.noteUntil = 0; G.sel = -1; | |
| 256 | setText('status', G.end); | |
| 257 | } | |
| 258 | } | |
| 259 | } | |
| 260 | function choose(t) { | |
| 261 | ensureAudio(); | |
| 262 | if (G.sel < 0) { | |
| 263 | const probe = Yard.move(P, t, t === 1 ? 2 : 1); // only the lifting track matters: a refusal about the track itself ends it here | |
| 264 | if (!probe.ok && (probe.why === 'empty-track' || probe.why === 'departed')) { note(REFUSED[probe.why]); return; } | |
| 265 | G.sel = t; sound(330, .05, 'square'); | |
| 266 | note(`wagon ${P.tracks[t][P.tracks[t].length - 1]} lifted: tap a track to set it down`); | |
| 267 | return; | |
| 268 | } | |
| 269 | const from = G.sel; | |
| 270 | G.sel = -1; | |
| 271 | if (from === t) { note('set back down'); return; } | |
| 272 | const r = Yard.move(P, from, t); | |
| 273 | if (!r.ok) { note(REFUSED[r.why] || 'cannot do that'); sound(110, .15, 'sawtooth'); return; } | |
| 274 | P = r.state; | |
| 275 | act(r.events); | |
| 276 | renderHud(); | |
| 277 | } | |
| 278 | function restart() { | |
| 279 | P = fresh(); G.sel = -1; G.ring = false; G.end = ''; | |
| 280 | note('tap a track to lift its end wagon'); | |
| 281 | renderHud(); | |
| 282 | } | |
| 283 | function update(dt) { | |
| 284 | G.time += dt; | |
| 285 | if (P.status !== 'playing' || G.time < G.noteUntil) return; | |
| 286 | setText('status', G.sel >= 0 ? 'tap a track to set the wagon down' : P.line); | |
| 287 | } | |
| 288 | ||
| 289 | /* ---------- input ---------- */ | |
| 290 | canvas.addEventListener('pointerdown', e => { | |
| 291 | canvas.focus({ preventScroll: true }); | |
| 292 | G.ring = false; | |
| 293 | if (P.status !== 'playing') { restart(); return; } | |
| 294 | const r = canvas.getBoundingClientRect(); | |
| 295 | choose(trackAt((e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H)); | |
| 296 | }); | |
| 297 | canvas.addEventListener('keydown', e => { | |
| 298 | const step = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1 }[e.key], digit = '1234'.indexOf(e.key), play = e.key === ' ' || e.key === 'Enter'; | |
| 299 | if (!step && digit < 0 && !play) return; | |
| 300 | e.preventDefault(); | |
| 301 | if (P.status !== 'playing') { if (!e.repeat) restart(); return; } | |
| 302 | if (step) { G.ring = true; G.cur = Math.max(0, Math.min(TRACKS - 1, G.cur + step)); return; } | |
| 303 | if (e.repeat) return; | |
| 304 | if (digit >= 0) { G.cur = digit; G.ring = true; choose(digit); return; } | |
| 305 | G.ring = true; | |
| 306 | choose(G.cur); | |
| 307 | }); | |
| 308 | ||
| 309 | /* ---------- sound ---------- */ | |
| 310 | let audio = null, muted = false; | |
| 311 | function ensureAudio() { | |
| 312 | if (audio) { if (audio.state === 'suspended') audio.resume(); return; } | |
| 313 | const AC = window.AudioContext || window.webkitAudioContext; | |
| 314 | if (AC) audio = new AC(); | |
| 315 | } | |
| 316 | function sound(freq, life, type, delay = 0) { | |
| 317 | if (!audio || muted) return; | |
| 318 | const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator(); | |
| 319 | osc.type = type; | |
| 320 | osc.frequency.setValueAtTime(freq, now); | |
| 321 | gain.gain.setValueAtTime(.0001, now); | |
| 322 | gain.gain.exponentialRampToValueAtTime(.07, now + .01); | |
| 323 | gain.gain.exponentialRampToValueAtTime(.0005, now + life); | |
| 324 | osc.connect(gain).connect(audio.destination); | |
| 325 | osc.start(now); osc.stop(now + life + .02); | |
| 326 | } | |
| 327 | const muteButton = document.getElementById('mute'); | |
| 328 | muteButton.addEventListener('click', () => { | |
| 329 | muted = !muted; | |
| 330 | muteButton.textContent = muted ? 'sound off' : 'sound on'; | |
| 331 | muteButton.setAttribute('aria-pressed', String(muted)); | |
| 332 | }); | |
| 333 | ||
| 334 | /* ---------- fit and boot ---------- */ | |
| 335 | addEventListener('resize', fit); | |
| 336 | fit(); | |
| 337 | bake(); | |
| 338 | note('tap a track to lift its end wagon'); | |
| 339 | renderHud(); | |
| 340 | canvas.focus({ preventScroll: true }); | |
| 341 | let last = performance.now(); | |
| 342 | function frame(now) { | |
| 343 | update(Math.min(.04, (now - last) / 1000)); | |
| 344 | last = now; | |
| 345 | draw(); | |
| 346 | requestAnimationFrame(frame); | |
| 347 | } | |
| 348 | requestAnimationFrame(frame); | |
| 349 | </script> | |
| 350 | </body> | |
| 351 | </html> |
new above
offline