Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

Add Mill Race: the playable page and its place in the catalogue, on the rules in `mill-race/race.js` #207

Parked opened this
Closed without merging

quill/pixel-plays:quill/175-add-mill-race-the-playable-page-and-its → main 5 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +380 −2
README.md +3 −2
@@ -64,6 +64,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
6464 | [Tower Duel](tower-duel/) | A 90-second two-lane card battle against a seeded rival on a field split by a river with a bridge in each lane: elixir fills over time (twice as fast in the last 30 seconds), pick a card from a hand of four (Knight, Archers, Giant, Goblins, Brute, Fireball) and put its troops on your half, and they walk over a bridge to fight and hit the rival towers; Fireball lands anywhere; toppling the rival king tower wins at once, otherwise more towers down, then more tower health, wins on the clock; a homage to Supercell's Clash Royale in idea only (forged by the crew on the engine and shell above, not by the original creators; rules in `tower-duel/duel.js`) | Tap a card, then tap your half; 1-4 to pick, arrows move a ring, Space plays |
6565 | [Lily Pond](lily-pond/) | Six levels on a six-by-six pond: the frog starts on a lily pad and hops north, east, south or west to the nearest pad in that line, up to three squares away, and the pad it leaves sinks; land on every pad once (level n has n + 3 pads) and the level is cleared, but a frog with no pad left in reach loses the level, which restarts as the same pond and costs a retry; clearing all six levels with three retries or fewer wins, and a seventh retry ends the game (forged by the crew on the engine and shell above, not by the original creators; rules in `lily-pond/pond.js`) | Swipe or tap beside the frog; arrow keys |
6666 | [Hedge Maze](hedge-maze/) | A garden maze of hedges carved from a seed, 5 by 5 cells for the first and one cell larger for each one solved, up to 12 by 12: walk from the gate to the stone fountain at the far end of the only path, one cell a step, before the gardener's bell rings 45 seconds after each maze begins (the bell starts afresh with every maze); solving 5 or more by the last bell wins, rules in `hedge-maze/maze.js`; the fountain splashes (forged by the crew on the engine and shell above, not by the original creators) | Swipe or tap beside the walker; arrow keys |
67 | [Mill Race](mill-race/) | A grid of stone channel tiles, 4 by 4 for the first level and one tile larger for each one cleared, up to 8 by 8: turn tiles a quarter at a time (a straight, a bend or a tee; blank stone does not turn) until the stream from the sluice on the west edge runs through joined channels to the water wheel on the east edge; each level has a par, the fewest turns that put its laid path right, and 5 levels cleared with 6 moves or fewer over par in all wins, rules in `mill-race/race.js`; wet channels are filled troughs and dry ones empty beds, the water shimmers and the wheel turns once it is fed (forged by the crew on the engine and shell above, not by the original creators) | Tap a tile; arrows move a cursor, space or enter turns |
6768
6869 ## Run
6970 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -83,7 +84,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
8384 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.
8485
8586 ## Add a game
86 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, Lily Pond, Market Barrow, Shunting Yard and Ferris Wheel 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`.
87 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, Mill Race, Allotment, Lily Pond, Market Barrow, Shunting Yard and Ferris Wheel 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`.
8788
8889 - `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.
8990 - `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.
@@ -100,7 +101,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
100101 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
101102 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
102103 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
103 - 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), Ferris Wheel's fairground lights blink, 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 Lily Pond's water glints shift (the frog, the sinking pads and their ripples are play, and still move), 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`.
104 - 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), Ferris Wheel's fairground lights blink, 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 Mill Race's water shimmers and its wheel turns once the stream reaches it (the turning of tiles is play), and Lily Pond's water glints shift (the frog, the sinking pads and their ripples are play, and still move), 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`.
104105
105106 ## Empire Age
106107
index.html +1
@@ -118,6 +118,7 @@ footer a::after { content: none; }
118118 <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>
119119 <li data-kind="Strategy" data-input="Tap" style="--accent:#b8475a"><a href="ferris-wheel/">Ferris Wheel</a><span>Seat the queue without tipping the wheel</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
120120 <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>
121 <li data-kind="Puzzle" data-input="Tap" style="--accent:#3d6f8f"><a href="mill-race/">Mill Race</a><span>Turn the channels until the stream reaches the mill wheel</span><span>Game forged by the crew</span><span class="tags">Puzzle · Tap</span></li>
121122 </ul>
122123 <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>
123124 </main>
mill-race/index.html added +360
@@ -0,0 +1,360 @@
1 <!doctype html>
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>Mill Race</title>
7 <!-- og:begin -->
8 <meta name="description" content="Turn the channels until the stream reaches the mill wheel">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/mill-race/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Mill Race">
13 <meta property="og:description" content="Turn the channels until the stream reaches the mill wheel">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/mill-race/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/mill-race.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="Mill Race: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #3d6f8f; }
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(--paper); color: var(--ink); }
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; 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)); align-items: flex-end; }
33 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
34 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
35 .row span { color: var(--muted); }
36 #status { color: var(--muted); min-height: 1.35em; }
37 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 16px; margin: -16px; cursor: pointer; }
outdated

Phone: button has padding 10px and margin -10px, so the mute target is about 33px high at a 13px font, below a thumb target (44px). Raise the padding to 16px with a matching negative margin so it reaches 44px without moving the layout.

38 button:hover, button:focus-visible { color: var(--ink); }
39 </style>
40 </head>
41 <body>
42 <div id="stage"><canvas id="c" width="360" height="280" tabindex="0" aria-label="A grid of square stone channel tiles seen from above at an angle, with a sluice gate on the west edge and a water wheel on the east edge. Tap a tile to turn it a quarter, or move the cursor with the arrow keys and turn with Space, until the stream runs along the channels to the wheel and sets it turning."></canvas></div>
43 <div id="scores">
44 <div class="row"><b id="level">1/5</b><span>level</span></div>
45 <div class="row"><b id="moves">0</b><span>moves</span></div>
46 <div class="row"><b id="par">0</b><span>par</span></div>
47 <div class="row"><b id="over">0</b><span>over par in all</span></div>
48 </div>
49 <div class="hud" id="bottom">
50 <div id="status" role="status" aria-live="polite"></div>

Screen reader: #status changes only on a clear or a blank tile, and moves, par and over-par sit in plain divs, so an ordinary turn is silent for a screen-reader user. After each turn, announce through note something like moves 3, par 5, or put the score rows inside the aria-live region.

51 <button id="mute" type="button" aria-pressed="false">sound on</button>
52 </div>
53 <script src="../shell.js"></script>
54 <script>
55 PixelPlays.mount({
56 id: 'mill-race',
57 rules: [
58 'Tap a tile, or move the cursor with the arrows and press Space, to turn it a quarter.',

Keyboard: the arrows move the cursor along the board's own axes, so up goes up and to the right on screen (same as Hedge Maze). I am not asking for a change, but say so in this rules line so a keyboard user is not surprised.

59 'The arrows follow the board, not the screen: up goes up and to the right.',
60 'Join the channels from the sluice on the west to the wheel on the east.',
61 'Clear 5 levels, finishing 6 moves or fewer over par in all, to win.',
62 ],
63 });
64 </script>
65 <script>window.PP_SCENE = { originY: 10, shadowX: 1.3, shadowY: -.12 };</script>
66 <script src="../engine.js"></script>
67 <script src="race.js"></script>
68 <script>
69 'use strict';
70
71 const LAWN = [96, 138, 70], STONE = [190, 184, 172], MOSS = [112, 134, 92], MUD = [112, 92, 72];
72 const WATER = [84, 156, 214], GLINT = [150, 204, 240], WOOD = [156, 108, 64], PLANK = [196, 150, 96], IRON = [70, 66, 62];
73 const CURSOR = [255, 214, 10];
74 const STONE_H = .5, WATER_H = .38, BED_H = .05, BLANK_H = .16;
75 const HUB_Z = 1.55, RADIUS = 1.35, HOLD = 1.2, SPAN = 16;
76
77 /* ---------- state ---------- */
78 let P = MillRace.start(Date.now() & 0xffff, 1);
79 const G = { time: 0, noteUntil: 0, cx: 0, cy: 0, ang: 0, hold: null, drawn: '', baked: 0 };
80 const nodes = {};
81 for (const k of ['level', 'moves', 'par', 'over', 'status']) nodes[k] = document.getElementById(k);
82 const shown = {};
83 function setText(key, text) {
84 if (shown[key] === text) return;
85 shown[key] = text;
86 nodes[key].textContent = text;
87 }
88 // what is drawn: the state before the clearing turn is put away while the wheel runs, then the next level
89 const view = () => (G.hold ? G.hold.state : P);
90 function renderHud() {
91 setText('level', `${P.level}/${P.last}`);
92 setText('moves', String(P.moves));
93 setText('par', String(P.par));
94 setText('over', String(P.over));
95 if (P.status !== 'playing') setText('status', `${P.line} · tap or press a key to play again`);
96 else if (G.time >= G.noteUntil) setText('status', P.line);
97 }
98 function note(text) { setText('status', text); G.noteUntil = G.time + 1.1; }
99
100 /* ---------- where the tiles are ---------- */
101 // the board is always the same size on the glass, so a tile is as big as the grid is small; k scales the wheel and flume to match
102 const tile = () => SPAN / view().size, half = () => SPAN / 2, scale = () => tile() / 2;
103 const tileOrigin = (ix, iy) => [-half() + ix * tile(), -half() + iy * tile()];
104 const centreOf = (ix, iy) => { const [x, y] = tileOrigin(ix, iy); return [x + tile() / 2, y + tile() / 2]; };
105 // the canvas point of a tile's top, which is also where a tap on it lands
106 function tilePoint(ix, iy) {
107 const [x, y] = centreOf(ix, iy), p = project(x, y, STONE_H);
108 return [p.sx, p.sy];
109 }
110 function cellAt(sx, sy) {
111 const g = unproject(sx, sy + STONE_H * COS * S), h = half(), ix = Math.floor((g.x + h) / tile()), iy = Math.floor((g.y + h) / tile());
112 const n = view().size;
113 return ix >= 0 && iy >= 0 && ix < n && iy < n ? [ix, iy] : null;
114 }
115 const fed = () => { const s = view(), w = s.wheel; return MillRace.opens(s.tiles[w.y][w.x], w.side) && s.wet.some(c => c.x === w.x && c.y === w.y); };
116
117 /* ---------- baked scene: the lawn ---------- */
118 function groundColor(x, y, ix, iy) {
119 const h = half();
120 if (x < -h - 1.6 || x > h + 3.8 || Math.abs(y) > h + .5) return 0;
121 const t = .95 + (hash(ix, iy) - .5) * .09;
122 return rgb(LAWN[0] * t, LAWN[1] * t, LAWN[2] * t);
123 }
124 function bake() {
125 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
126 zb.fill(-1e9);
127 pix.fill(rgb(255, 255, 255));
128 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
129 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
130 if (!c) continue;
131 pix[i] = c; ground[i] = 1;
132 zb[i] = (g.x + g.y) / R2 * COS;
133 }
134 groundZ.set(zb);
135 bakedPix.set(pix);
136 bakedZ.set(zb);
137 G.baked = view().size;
138 }
139
140 /* ---------- the tiles ---------- */
141 const layerPix = new Uint32Array(W * H), layerZ = new Float32Array(W * H);
142 // a raised stone piece, with a shadow to the screen-right
143 function stone(x0, y0, x1, y1, h, c, seed) {
144 box(x0, y0, 0, x1, y1, h, c, seed);
145 castShadow((x0 + x1) / 2, (y0 + y1) / 2, h, (x1 - x0) * .5, 1, 0);
146 }
147 // the water pieces of this layer, so the shimmer can glint on a few of them each step without rebuilding the layer
148 const waters = [];
149 const surface = (x0, y0, x1, y1) => { waters.push([x0, y0, x1, y1]); return WATER; };
150 function drawTile(s, ix, iy, wet) {
151 const t = s.tiles[iy][ix], [ox, oy] = tileOrigin(ix, iy), TILE = tile(), SUB = TILE / 3, seed = ix * 7 + iy * 13;
152 const tone = .94 + hash(ix, iy) * .1, rock = [STONE[0] * tone, STONE[1] * tone, STONE[2] * tone];
153 if (t.type === 'blank') {
154 box(ox, oy, 0, ox + TILE, oy + TILE, BLANK_H, MOSS, seed);
155 return;
156 }
157 const open = MillRace.sides(t);
158 for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) {
159 const x0 = ox + a * SUB, y0 = oy + b * SUB, x1 = x0 + SUB, y1 = y0 + SUB;
160 const side = a === 1 && b === 1 ? -1 : a === 1 ? (b === 0 ? 0 : 2) : b === 1 ? (a === 2 ? 1 : 3) : -2;
161 const channel = side === -1 || (side >= 0 && open.includes(side));
162 if (!channel) { stone(x0, y0, x1, y1, STONE_H, rock, seed + a * 3 + b); continue; }
163 box(x0, y0, 0, x1, y1, BED_H, MUD, seed + a);
164 if (wet) box(x0, y0, 0, x1, y1, WATER_H, surface(x0, y0, x1, y1), seed + b);
165 }
166 }
167 function drawSluice(s) {
168 const h = half(), k = scale(), cy = -h + (s.sluice.y + .5) * tile(), x0 = -h - 1.1 * k, w = tile() / 6;
169 stone(x0, cy - .85 * k, x0 + .55 * k, cy - .55 * k, 1.4, STONE, 1);
170 stone(x0, cy + .55 * k, x0 + .55 * k, cy + .85 * k, 1.4, STONE, 2);
171 box(x0, cy - .85 * k, 1.1, x0 + .55 * k, cy + .85 * k, 1.4, STONE, 3);
172 box(x0 + .55 * k, cy - w, 0, -h, cy + w, WATER_H, surface(x0 + .55 * k, cy - w, -h, cy + w), 4);
173 }
174 // the flume under the wheel, brimming when the wheel is fed and an empty bed when not
175 function drawFlume(s, on) {
176 const h = half(), k = scale(), cy = -h + (s.wheel.y + .5) * tile(), x1 = h + 3.3 * k, wx = h + 1.7 * k, w = tile() / 6;
177 box(h, cy - w - .25 * k, 0, x1, cy - w, STONE_H, STONE, 5);
178 box(h, cy + w, 0, x1, cy + w + .25 * k, STONE_H, STONE, 6);
179 castShadow(x1 - .4, cy, STONE_H, .5, 1, 0);
180 box(h, cy - w, 0, x1, cy + w, BED_H, MUD, 7);
181 if (on) box(h, cy - w, 0, x1, cy + w, WATER_H, surface(h, cy - w, x1, cy + w), 8);
182 stone(wx - .2 * k, cy - w - .3 * k, wx + .2 * k, cy - w, HUB_Z * k + .15, STONE, 9);
183 stone(wx - .2 * k, cy + w, wx + .2 * k, cy + w + .3 * k, HUB_Z * k + .15, STONE, 10);
184 }
185 function drawCursor(ix, iy) {
186 const [x, y] = tileOrigin(ix, iy), TILE = tile(), t = .12, top = STONE_H + .15;
187 box(x, y, 0, x + TILE, y + t, top, CURSOR, 11);
188 box(x, y + TILE - t, 0, x + TILE, y + TILE, top, CURSOR, 12);
189 box(x, y + t, 0, x + t, y + TILE - t, top, CURSOR, 13);
190 box(x + TILE - t, y + t, 0, x + TILE, y + TILE - t, top, CURSOR, 14);
191 }
192 // everything that holds still between turns: rebuilt only when the picture would change
193 function buildLayer() {
194 const s = view();
195 if (G.baked !== s.size) bake();
196 pix.set(bakedPix); zb.set(bakedZ);
197 waters.length = 0;
198 const wet = new Set(s.wet.map(c => c.y * s.size + c.x));
199 for (let iy = 0; iy < s.size; iy++) for (let ix = 0; ix < s.size; ix++) drawTile(s, ix, iy, wet.has(iy * s.size + ix));
200 drawSluice(s);
201 drawFlume(s, fed());
202 drawCursor(G.cx, G.cy);
203 applyShadows(bakedZ);
204 layerPix.set(pix); layerZ.set(zb);
205 }
206
207 /* ---------- the wheel ---------- */
208 // a few small glints on the water, a new few each step; none when motion is reduced
209 function drawGlints(step) {
210 if (STILL) return;
211 waters.forEach(([x0, y0, x1, y1], i) => {
212 if (hash(i + step * 7, step * 3 + 1) <= .62) return;
213 const mx = (x0 + x1) / 2, my = (y0 + y1) / 2, d = Math.min(x1 - x0, y1 - y0) * .2;
214 box(mx - d, my - d, WATER_H - .02, mx + d, my + d, WATER_H, GLINT, i);
215 });
216 }
217 function drawWheel() {
218 const s = view(), h = half(), k = scale(), cy = -h + (s.wheel.y + .5) * tile(), wx = h + 1.7 * k, wood = () => WOOD, plank = () => PLANK;
219 const hub = HUB_Z * k, radius = RADIUS * k, w = tile() / 6 - .2, r = .06 * k + .02;
220 const rim = n => { const a = G.ang + n * Math.PI / 4; return [wx + Math.cos(a) * radius, Math.sin(a) * radius + hub]; };
221 for (let n = 0; n < 8; n++) {
222 const [px, pz] = rim(n), [qx, qz] = rim(n + 1);
223 for (const dy of [-w, w]) {
224 dynamicAdd([wx, cy + dy, hub], [px, cy + dy, pz], r, r, wood);
225 dynamicAdd([px, cy + dy, pz], [qx, cy + dy, qz], r, r, wood);
226 }
227 dynamicAdd([px, cy - w, pz], [px, cy + w, pz], r * 1.6, r * 1.6, plank);
228 }
229 dynamicAdd([wx, cy - w - .4 * k, hub], [wx, cy + w + .4 * k, hub], .13 * k, .13 * k, () => IRON);
230 }
231
232 function draw() {
233 const step = STILL ? 0 : Math.floor(G.time * WIND_FPS), s = view();
234 const key = `${s.seed}|${s.level}|${s.moves}|${G.hold ? 1 : 0}|${G.cx},${G.cy}|${s.status}`;
235 if (key !== G.drawn) { G.drawn = key; buildLayer(); }
236 pix.set(layerPix); zb.set(layerZ);
237 drawGlints(step);
238 pendingShadows.length = 0;
239 drawWheel();
240 flushShadows();
241 applyShadows(bakedZ);
242 shadeEdges();
243 ctx.putImageData(image, 0, 0);
244 }
245
246 /* ---------- game ---------- */
247 const HINT = 'tap a tile to turn it';
248 function restart() {
249 P = MillRace.start(Date.now() & 0xffff, 1);
250 G.hold = null; G.cx = 0; G.cy = P.sluice.y; G.ang = 0;
251 note(HINT); renderHud();
252 }
253 function turnAt(ix, iy) {
254 ensureAudio();
255 if (G.hold) return;
256 if (P.status !== 'playing') { restart(); return; }
257 G.cx = ix; G.cy = iy;
258 const before = P, r = MillRace.turn(P, ix, iy);
259 if (!r.ok) { if (r.why === 'blank') { sound(130, .12, 'sawtooth'); note('solid stone'); } return; }
260 P = r.state;
261 if (r.event === 'cleared') {
262 // the picture before the new level: the turned tile, and the water the rules say it lets through
263 const tiles = before.tiles.map(row => row.map(t => ({ ...t })));
264 tiles[iy][ix].rot = (tiles[iy][ix].rot + 1) % 4;
265 const done = Object.assign({}, before, { tiles, moves: before.moves + 1 });
266 done.wet = MillRace.flow(done);
267 G.hold = { state: done, until: G.time + HOLD };
268 sound(660, .25, 'sine'); sound(990, .35, 'sine', .08);
269 note(`level cleared in ${done.moves} of par ${before.par}`);
270 } else if (r.event === 'over') {
271 sound(520, .3, 'sine'); sound(780, .5, 'sine', .15);
272 } else {
273 sound(240 + ((ix + iy) % 4) * 30, .07, 'triangle');
274 note(P.line);
275 }
276 renderHud();
277 }
278 function update(dt) {
279 G.time += dt;
280 if (G.hold && G.time >= G.hold.until) {
281 G.hold = null;
282 G.cx = Math.min(G.cx, P.size - 1); G.cy = P.sluice.y; G.ang = 0;
283 note(P.line);
284 }
285 if (fed() && !STILL) G.ang += dt * 2.4;
286 renderHud();
287 }
288
289 /* ---------- input ---------- */
290 const toCanvas = e => {
291 const r = canvas.getBoundingClientRect();
292 return { x: (e.clientX - r.left) / r.width * W, y: (e.clientY - r.top) / r.height * H };
293 };
294 canvas.addEventListener('pointerdown', () => { canvas.focus({ preventScroll: true }); });
295 canvas.addEventListener('pointerup', e => {
296 const p = toCanvas(e), c = cellAt(p.x, p.y);
297 if (c) turnAt(c[0], c[1]);
298 else if (P.status !== 'playing') restart();
299 });
300 // up is the way up the screen to the right, and so on round: the arrows turn with the picture
301 const KEYS = { ArrowUp: [0, -1], ArrowRight: [1, 0], ArrowDown: [0, 1], ArrowLeft: [-1, 0] };
302 canvas.addEventListener('keydown', e => {
303 const move = KEYS[e.key];
304 if (!move && e.key !== ' ' && e.key !== 'Enter') return;
305 e.preventDefault();
306 if (e.repeat) return;
307 ensureAudio();
308 if (move) {
309 if (P.status !== 'playing') { restart(); return; }
310 G.cx = Math.max(0, Math.min(P.size - 1, G.cx + move[0]));
311 G.cy = Math.max(0, Math.min(P.size - 1, G.cy + move[1]));
312 sound(420, .04, 'sine');
313 return;
314 }
315 turnAt(G.cx, G.cy);
316 });
317
318 /* ---------- sound ---------- */
319 let audio = null, muted = false;
320 function ensureAudio() {
321 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
322 const AC = window.AudioContext || window.webkitAudioContext;
323 if (AC) audio = new AC();
324 }
325 function sound(freq, life, type, delay = 0) {
326 if (!audio || muted) return;
327 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
328 osc.type = type;
329 osc.frequency.setValueAtTime(freq, now);
330 gain.gain.setValueAtTime(.0001, now);
331 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
332 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
333 osc.connect(gain).connect(audio.destination);
334 osc.start(now); osc.stop(now + life + .02);
335 }
336 const muteButton = document.getElementById('mute');
337 muteButton.addEventListener('click', () => {
338 muted = !muted;
339 muteButton.textContent = muted ? 'sound off' : 'sound on';
340 muteButton.setAttribute('aria-pressed', String(muted));
341 });
342
343 /* ---------- fit and boot ---------- */
344 addEventListener('resize', fit);
345 fit();
346 G.cy = P.sluice.y;
347 note(HINT);
348 renderHud();
349 canvas.focus({ preventScroll: true });
350 let last = performance.now();
351 function frame(now) {
352 update(Math.min(.04, (now - last) / 1000));
353 last = now;
354 draw();
355 requestAnimationFrame(frame);
356 }
357 requestAnimationFrame(frame);
358 </script>
359 </body>
360 </html>
og/home.png
Binary file not shown.
og/mill-race.png added
Binary file not shown.
rounds.mjs +8
@@ -152,6 +152,14 @@ export const ROUNDS = {
152152 if (index >= 0) { g.press(String(index + 1)); g.tap(...g.read(`scr(${x}, 9)`)); }
153153 g.run(.2);
154154 } },
155 // turn each tile of the level's laid path as far as the rules' own `scramble` says puts it right (par moves), waiting out the pause after each cleared level
156 'mill-race': { over: /play again/, outcome: /The wheel turns: 5 levels cleared, 0 moves over par/, beat: (g) => {
157 if (g.read('G.hold') || g.read('P.status') !== 'playing') { g.run(.5); return; }
158 const s = g.read('P'), plan = s.scramble.flatMap(q => Array(q.undo).fill(q));
159 const q = plan[s.moves];
160 g.tap(...g.read(`tilePoint(${q.x}, ${q.y})`));
161 g.run(.1);
162 } },
155163 // plan the whole round on the rules' own `board`, `skip` and `step` (a depth-first search that seats as many riders as it can without a jam), then play it one step per beat
156164 'ferris-wheel': { over: /play again/, outcome: /Wheel balanced: \d+ riders carried/, beat: g => {
157165 g.plan ??= wheelPlan(structuredClone(g.read('P')));
serve.test.mjs +7
@@ -556,6 +556,13 @@ test('Hedge Maze and its rules script are served without a track', async () => {
556556 expect((await fetch(base + '/hedge-maze/maze.js')).status).toBe(200);
557557 });
558558
559 test('Mill Race and its rules script are served without a track', async () => {
560 const page = await fetch(base + '/mill-race/');
561 expect(page.status).toBe(200);
562 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
563 expect((await fetch(base + '/mill-race/race.js')).status).toBe(200);
564 });
565
559566 test('Hot Air Balloon and its rules script are served without a track', async () => {
560567 const page = await fetch(base + '/hot-air-balloon/');
561568 expect(page.status).toBe(200);
shell.js +1
@@ -58,6 +58,7 @@ window.PixelPlays = (() => {
5858 { 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 },
5959 { id: 'ferris-wheel', title: 'Ferris Wheel', blurb: 'Seat the queue without tipping the wheel', kind: 'Strategy', input: 'Tap', accent: '#b8475a', music: false, forged: true },
6060 { 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 },
61 { id: 'mill-race', title: 'Mill Race', blurb: 'Turn the channels until the stream reaches the mill wheel', kind: 'Puzzle', input: 'Tap', accent: '#3d6f8f', music: false, forged: true },
6162 ];
6263 const MUSIC_VOLUME = .4;
6364 const CREDITS = [

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs