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

Migrated from github.com/amirmushichge/pixel-plays

Add Lock Keeper: the playable page and its place in the catalogue, on the rules in `lock-keeper/lock.js` #159

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

quill/pixel-plays:quill/141-add-lock-keeper-the-playable-page-and-it → main 1 commit fork

  • Merged. quill/141-add-lock-keeper-the-playable-page-and-it was merged into main as e7a1429.

Review

Sign in to review this change.
8 files changed +435 −2
README.md +3 −2
@@ -50,6 +50,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
5050 | [Bowls Green](bowls-green/) | A flat lawn bowls green floating on white, a white jack at the far end, a mat at the near end, two rival woods already resting near the jack and a low hedge behind: drag back from the mat and release to roll (or Left and Right to set the line, hold Space to build weight, release to roll); weight sets how far the wood runs (quadratic in weight, against a pace that is one seeded constant per game) and each wood bends towards its bias side as it slows, so aiming straight at the jack misses; a wood off the back of the green (or into the ditch at the side) is dead; one end of four woods, and one or more resting nearer the jack than the nearest rival wood wins (forged by the crew on the engine and shell above, not by the original creators; rules in `bowls-green/bowls.js`) | Drag back and release; Left and Right to aim, hold Space |
5151 | [Dinghy Race](dinghy-race/) | A bay with a square course of three buoys and back over a start line, the wind from the south-east and shifting a little at each buoy: the boat steers itself buoy to buoy and you trim the sail; it drives best at half the angle between boat and wind, and loses speed quadratically as the trim drifts from that, so every leg and every wind shift asks for a new setting; two seeded rivals sail at a steady pace, first or second place is a win (forged by the crew on the engine and shell above, not by the original creators; rules in `dinghy-race/dinghy.js`) | Drag left and right along the sheet; Up and Down arrows trim in and out |
5252 | [Seed Packets](seed-packets/) | A potting-shed bench with sixteen face-down seed packets in a 4x4 grid, a watering can and a clock on the wall: tap a packet to turn it face up to show its flower, then a second; a matching pair stays face up and a mismatch turns both back after 0.8 s (taps in that beat are ignored); the layout is a seeded shuffle of eight pairs and the gardener returns after 16 turns (a turn is two packets), so you can afford eight mismatches; the end shows pairs found and turns used, and the best is the fewest turns in a win (forged by the crew on the engine and shell above, not by the original creators) | Tap; arrows + space |
53 | [Lock Keeper](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 |
5354 | [Empire Age](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 |
5455 | [Hot Air Balloon](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 |
5556 | [Go-Kart Fete](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 |
@@ -73,7 +74,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
7374 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.
7475
7576 ## Add a game
76 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 and Hoopla Stall 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`.
77 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 and Lock Keeper 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`.
7778
7879 - `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.
7980 - `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.
@@ -90,7 +91,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
9091 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
9192 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
9293 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
93 - 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); all of it stops under `prefers-reduced-motion`.
94 - 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); all of it stops under `prefers-reduced-motion`.
9495
9596 ## Empire Age
9697
index.html +1
@@ -104,6 +104,7 @@ footer a::after { content: none; }
104104 <li data-kind="Sport" data-input="Drag" style="--accent:#4f7f3f"><a href="bowls-green/">Bowls Green</a><span>Drag back to set line and weight and curve your woods in close to the jack</span><span>Game forged by the crew</span><span class="tags">Sport · Drag</span></li>
105105 <li data-kind="Racing" data-input="Drag" style="--accent:#2e8a7a"><a href="dinghy-race/">Dinghy Race</a><span>Drag to trim the sail to the wind and round three buoys ahead of the fleet</span><span>Game forged by the crew</span><span class="tags">Racing · Drag</span></li>
106106 <li data-kind="Memory" data-input="Tap" style="--accent:#7d9a4a"><a href="seed-packets/">Seed Packets</a><span>Tap to turn over seed packets and match every pair before the gardener comes back</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li>
107 <li data-kind="Strategy" data-input="Tap" style="--accent:#5a6e8a"><a href="lock-keeper/">Lock Keeper</a><span>Work the paddles and gates to bring every narrowboat through the flight of locks</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
107108 <li data-kind="Strategy" data-input="Tap" style="--accent:#3a5fa8"><a href="empire/">Empire Age</a><span>A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center</span><span>Game forged by the crew</span><span class="tags">Strategy · Tap</span></li>
108109 <li data-kind="Precision" data-input="Hold" style="--accent:#d0453c"><a href="hot-air-balloon/">Hot Air Balloon</a><span>Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
109110 <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>
lock-keeper/index.html added +389
@@ -0,0 +1,389 @@
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>Lock Keeper</title>
7 <!-- og:begin -->
8 <meta name="description" content="Work the paddles and gates to bring every narrowboat through the flight of locks">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/lock-keeper/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Lock Keeper">
13 <meta property="og:description" content="Work the paddles and gates to bring every narrowboat through the flight of locks">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/lock-keeper/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/lock-keeper.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="Lock Keeper: 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: #5a6e8a; }
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: 2.7em; max-width: calc(100% - 100px); }
37 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
38 button:hover, button:focus-visible { color: var(--ink); }
39 </style>
40 </head>
41 <body>
42 <div id="stage"><canvas id="c" tabindex="0" aria-label="A flight of three canal locks climbing from left to right, each with a bottom gate and a top gate, a bottom paddle and a top paddle, and narrowboats waiting at both ends. Tap a paddle or a gate to work it and tap a boat to move it into or out of its lock, or press Left and Right to pick a lock and 1 top paddle, 2 bottom paddle, 3 top gate, 4 bottom gate, 5 move a boat. A gate opens only on level water and two open paddles flood the lock. Bring every boat through in as few operations as the par."></canvas></div>
43 <div id="scores">
44 <div class="row"><b id="ops">0</b><span>operations</span></div>
45 <div class="row"><b id="par">-</b><span>par</span></div>
46 </div>
47 <div class="hud" id="bottom">
48 <div id="status" role="status" aria-live="polite"></div>
49 <button id="mute" type="button" aria-pressed="false">sound on</button>
50 </div>
51 <script src="../shell.js"></script>
52 <script>
53 PixelPlays.mount({
54 id: 'lock-keeper',
55 rules: [
56 'Tap a paddle or gate to work it, a boat to move it; or Left and Right pick a lock and 1-5 work it.',
57 'A gate opens only on level water; two open paddles flood the lock.',
58 'Red boats climb, blue boats descend: bring them all through in as few operations as par.',
59 ],
60 });
61 </script>
62 <script>window.PP_SCENE = { originY: 17, shadowX: 1.3, shadowY: -.12 };</script>
63 <script src="../engine.js"></script>
64 <script src="lock.js"></script>
65 <script>
66 'use strict';
67
68 const Lock = window.LockKeeper;
69 const GRASS_C = [104, 148, 74], BANK = [150, 144, 132], BED = [58, 74, 96], STONE = [156, 150, 140], WOOD = [128, 88, 54], WOOD_LIGHT = [176, 132, 80];
70 const WATER = [78, 156, 204], WATER_FRONT = [44, 104, 156], HULL_UP = [200, 66, 52], HULL_DOWN = [54, 100, 182], CABIN = [238, 224, 192], SLUICE = [120, 212, 240], IRON = [74, 70, 78];
71 const ACCENT_PIX = rgb(90, 110, 138), RING_PIX = rgb(255, 255, 255);
72
73 const WIDTHS = [6.4, 3.8, 4.6, 3.8, 4.6, 3.8, 6.4]; // the seven places of the canal, left to right: pound, lock, pound, lock, pound, lock, pound
74 const START = WIDTHS.map((_, i) => -16.7 + WIDTHS.slice(0, i).reduce((a, b) => a + b, 0));
75 const END = WIDTHS.map((w, i) => START[i] + w);
76 const CENTRE = WIDTHS.map((w, i) => START[i] + w / 2);
77 const VB = -2, VF = 2, BOAT_L = 1, BOAT_W = .55, FLOOR = .3, HALF_U = 17.6, HALF_V = 6.4;
78 const poundZ = j => 1 + 1.3 * j;
79 const waterZ = (place, level) => place % 2 ? poundZ((place - 1) / 2 + (level === 'high' ? 1 : 0)) : poundZ(place / 2);
80 const gateTop = k => poundZ(k + 1) + .5;
81 const lockStart = k => START[2 * k + 1], lockEnd = k => END[2 * k + 1];
82 const world = (u, v, z) => [(u + v) / R2, (v - u) / R2, z];
83
84 /* ---------- state ---------- */
85 let R = Lock.newRound(Lock.SEEDS[0]);
86 const G = { time: 0, round: 0, lock: 0, ring: false, noteUntil: 0 };
87 const V = { water: [], boats: {} }; // what is drawn: the water heights and boat positions, eased towards what the rules say
88 const nodes = {};
89 for (const k of ['ops', 'par', 'status']) nodes[k] = document.getElementById(k);
90 const shown = {};
91 function setText(key, text) {
92 if (shown[key] === text) return;
93 shown[key] = text;
94 nodes[key].textContent = text;
95 }
96 function note(text) { setText('status', text); G.noteUntil = G.time + 3; }
97
98 // where a boat belongs among the others in its place: centred, or spread along the pound
99 function boatSlot(b) {
100 const mates = R.boats.filter(o => o.at === b.at).sort((x, y) => x.id - y.id), n = mates.length, i = mates.findIndex(o => o.id === b.id);
101 const gap = Math.min(2.3, (WIDTHS[b.at] - 2 * BOAT_L - .4) / Math.max(1, n - 1));
102 return CENTRE[b.at] + (i - (n - 1) / 2) * gap;
103 }
104 function targets() {
105 const water = [];
106 for (let p = 0; p < 7; p++) water[p] = p % 2 ? waterZ(p, R.locks[(p - 1) / 2].level) : waterZ(p);
107 return water;
108 }
109 function settle(dt) {
110 const k = Math.min(1, dt * 7), water = targets();
111 for (let p = 0; p < 7; p++) V.water[p] = V.water[p] === undefined ? water[p] : V.water[p] + (water[p] - V.water[p]) * k;
112 for (const b of R.boats) {
113 const u = boatSlot(b), z = water[b.at], v = V.boats[b.id];
114 if (!v) V.boats[b.id] = { u, z };
115 else { v.u += (u - v.u) * k; v.z += (z - v.z) * k; }
116 }
117 }
118
119 /* ---------- painting ---------- */
120 // one point of a surface at (u, v, z), in the depth buffer
121 function put(ramp, u, v, z, tone) {
122 const p = project((u + v) / R2, (v - u) / R2, z), ix = p.sx | 0, iy = p.sy | 0;
123 if (ix < 0 || iy < 0 || ix >= W || iy >= H) return;
124 const i = iy * W + ix;
125 if (p.d <= zb[i]) return;
126 zb[i] = p.d;
127 pix[i] = ramp[clamp(Math.floor(tone + (bayerAt(ix, iy) - .5) * .5), 0, 4)];
128 }
129 // a flat rectangle facing up, and a strip facing the camera
130 function top(ramp, u0, u1, v0, v1, z, tone) {
131 for (let u = u0; u <= u1; u += .08) for (let v = v0; v <= v1; v += .12) put(ramp, u, v, z, typeof tone === 'function' ? tone(u, v) : tone);
132 }
133 function front(ramp, u0, u1, v, z0, z1, tone) {
134 for (let u = u0; u <= u1; u += .08) for (let z = z0; z <= z1; z += .08) put(ramp, u, v, z, typeof tone === 'function' ? tone(u, z) : tone);
135 }
136
137 /* ---------- baked scene: the bank, the stone walls and the bed ---------- */
138 function groundColor(x, y, ix, iy) {
139 const u = (x - y) / R2, v = (x + y) / R2;
140 if (Math.abs(u) > HALF_U || Math.abs(v) > HALF_V) return 0;
141 if (Math.abs(u) > HALF_U - .5 || Math.abs(v) > HALF_V - .5) return rgb(...BANK);
142 const t = .95 + (hash(ix, iy) - .5) * .08 + (noise(u * .6, v * 1.8) - .5) * .12;
143 const c = v >= VB && v <= VF ? BED : GRASS_C;
144 return rgb(c[0] * t, c[1] * t, c[2] * t);
145 }
146 function bake() {
147 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
148 tufts.length = 0; leaves.length = 0;
149 zb.fill(-1e9);
150 pix.fill(rgb(255, 255, 255));
151 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
152 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
153 if (!c) continue;
154 pix[i] = c; ground[i] = 1;
155 zb[i] = (g.x + g.y) / R2 * COS;
156 }
157 groundZ.set(zb);
158 const stone = rampOf(STONE);
159 for (let p = 0; p < 7; p++) {
160 const k = p % 2 ? (p - 1) / 2 : -1, wall = (p % 2 ? gateTop(k) : poundZ(p / 2)) - .1;
161 const course = (u, z) => 2.4 + (Math.floor(z / .45) & 1) * .3 + ((Math.floor(u / 1.1) + Math.floor(z / .45)) & 1) * .25 + (hash(Math.floor(u * 6), Math.floor(z * 6)) - .5) * .2;
162 front(stone, START[p], END[p], VB, 0, wall, course); // the far wall, seen across the water
163 top(stone, START[p], END[p], VB - .6, VB, wall, 3.3);
164 front(stone, START[p], END[p], VF, 0, FLOOR, 2); // the cut-away near wall, below the water
165 top(stone, START[p], END[p], VF, VF + .5, .25, 3.2);
166 front(stone, START[p], END[p], VF + .5, 0, .25, 2);
167 }
168 for (let k = 0; k < Lock.LOCKS; k++) for (const u of [lockStart(k), lockEnd(k)]) { // a stone sill under each gate
169 top(stone, u - .25, u + .25, VB, VF, FLOOR, 2.8);
170 front(stone, u - .25, u + .25, VF, 0, FLOOR, 2);
171 }
172 bakeOcclusion();
173 staticShadow.set(shadowMask);
174 applyShadows(groundZ);
175 bakedPix.set(pix);
176 bakedZ.set(zb);
177 }
178
179 /* ---------- drawn each frame ---------- */
180 function drawWater() {
181 const water = rampOf(WATER), face = rampOf(WATER_FRONT), phase = STILL ? 0 : Math.floor(G.time * WIND_FPS);
182 for (let p = 0; p < 7; p++) {
183 const z = V.water[p];
184 top(water, START[p], END[p], VB, VF, z, (u, v) => 2.6 + ((Math.floor(u * 1.7 + phase * .5) + Math.floor(v * 1.4)) % 5 === 0 ? .9 : 0));
185 front(face, START[p], END[p], VF, FLOOR, z, (u, h) => 1.7 + (h - FLOOR) / 6);
186 }
187 }
188 function drawGate(k, top_) {
189 const lock = R.locks[k], open = top_ ? lock.gateTop : lock.gateBottom, wood = rampOf(WOOD), u = top_ ? lockEnd(k) : lockStart(k), z = gateTop(k);
190 if (!open) {
191 top(wood, u - .15, u + .15, VB, VF, z, 3.1);
192 front(wood, u - .15, u + .15, VF, FLOOR, z, (x, h) => 1.8 + (Math.floor(h / .5) & 1) * .5);
193 return;
194 }
195 const a = top_ ? u - .9 : u - .15, b = top_ ? u + .15 : u + .9; // the leaves swing back against the walls of the lock
196 top(wood, a, b, VB, VB + .3, z, 3.1);
197 top(wood, a, b, VF - .3, VF, z, 3.3);
198 front(wood, a, b, VF, FLOOR, z, (x, h) => 1.8 + (Math.floor(h / .5) & 1) * .5);
199 front(wood, a, b, VB + .3, z - .5, z, 1.6);
200 }
201 // a paddle: a post on the near bank with a sluice wheel that climbs and glows when the paddle is drawn
202 function paddlePost(k, top_) {
203 return world(top_ ? lockEnd(k) - .9 : lockStart(k) + .9, VF + 1.4, 0);
204 }
205 function drawPaddle(k, top_) {
206 const open = top_ ? R.locks[k].paddleTop : R.locks[k].paddleBottom, [x, y] = paddlePost(k, top_);
207 dynamicAdd([x, y, 0], [x, y, open ? 1.5 : 1], .22, .22, () => WOOD);
208 sphere(x, y, open ? 1.75 : 1.2, open ? .45 : .35, open ? SLUICE : WOOD_LIGHT, 'solid');
209 if (open) capsule([x, y, 0], [x, y, .3], .38, .38, () => SLUICE, 'solid');
210 }
211 function hullEdge(du, dir) { const t = du * dir; return t > .55 ? BOAT_W * (1 - (t - .55) / .45 * .7) : BOAT_W; }
212 function drawBoat(b) {
213 const v = V.boats[b.id], dir = b.dir === 'up' ? 1 : -1, hull = rampOf(b.dir === 'up' ? HULL_UP : HULL_DOWN), cabin = rampOf(CABIN), z = v.z + .45;
214 for (let du = -BOAT_L; du <= BOAT_L; du += .08) {
215 const hw = hullEdge(du, dir);
216 for (let dv = -hw; dv <= hw; dv += .12) put(hull, v.u + du, dv, z, 3.1);
217 front(hull, v.u + du, v.u + du, hw, v.z - .1, z, 2);
218 }
219 const c0 = v.u - dir * .75 - .55, c1 = v.u - dir * .75 + .55;
220 top(cabin, c0, c1, -.4, .4, z + .6, 3.4);
221 front(cabin, c0, c1, .4, z, z + .6, (x, h) => Math.abs(((x - c0) % .55) - .27) < .1 && h > z + .2 ? 1 : 2.6);
222 dynamicAdd(world(c1 - .15, -.2, z + .6), world(c1 - .15, -.2, z + 1.1), .12, .12, () => IRON);
223 }
224 function drawRing() {
225 if (!G.ring || R.status !== 'playing') return;
226 const a = project(...world(lockStart(G.lock) - .4, VB - .6, gateTop(G.lock))), b = project(...world(lockEnd(G.lock) + .4, VF + 2.4, 0));
227 const x0 = Math.round(a.sx), x1 = Math.round(b.sx), y0 = Math.round(a.sy) - 2, y1 = Math.round(b.sy);
228 const dot = (x, y, c) => { if (x >= 0 && x < W && y >= 0 && y < H) pix[y * W + x] = c; };
229 for (let x = x0 - 1; x <= x1 + 1; x++) for (const y of [y0 - 1, y1 + 1]) dot(x, y, RING_PIX);
230 for (let y = y0 - 1; y <= y1 + 1; y++) for (const x of [x0 - 1, x1 + 1]) dot(x, y, RING_PIX);
231 for (let x = x0; x <= x1; x++) { dot(x, y0, ACCENT_PIX); dot(x, y1, ACCENT_PIX); }
232 for (let y = y0; y <= y1; y++) { dot(x0, y, ACCENT_PIX); dot(x1, y, ACCENT_PIX); }
233 }
234 function draw() {
235 pix.set(bakedPix);
236 zb.set(bakedZ);
237 pendingShadows.length = 0;
238 drawWater();
239 for (let k = 0; k < Lock.LOCKS; k++) { drawGate(k, false); drawGate(k, true); drawPaddle(k, false); drawPaddle(k, true); }
240 for (const b of R.boats) drawBoat(b);
241 flushShadows();
242 applyShadows(groundZ);
243 shadeEdges();
244 drawRing();
245 ctx.putImageData(image, 0, 0);
246 }
247
248 /* ---------- game ---------- */
249 const WHY = {
250 'gate-closed': 'the gate in the way is shut',
251 'no-room': 'no room for the boat there',
252 'lock-full': 'the lock already holds a boat',
253 'no-boat': 'no boat can cross here',
254 'uneven-water': 'the water is not level, so the gate will not open',
255 'gate-open': 'the gate on the far side is open, so the pound would run through',
256 'round-over': 'the round is over',
257 };
258 const ACT_KEYS = { 1: 'paddle-top', 2: 'paddle-bottom', 3: 'gate-top', 4: 'gate-bottom', 5: 'move' };
259 const NAME = { 'paddle-top': 'top paddle', 'paddle-bottom': 'bottom paddle', 'gate-top': 'top gate', 'gate-bottom': 'bottom gate', move: 'boat' };
260 const END_HINT = ' · tap or press a key to play again';
261 function renderHud() {
262 setText('ops', String(R.ops));
263 setText('par', R.par === null ? '-' : String(R.par));
264 }
265 function finish() { setText('status', R.line + END_HINT); G.noteUntil = 0; }
266 function work(lock, act) {
267 ensureAudio();
268 if (R.status !== 'playing') { again(); return; }
269 G.lock = lock;
270 const r = Lock.apply(R, { lock, act });
271 if (!r.ok) {
272 sound(130, .25, 'sawtooth');
273 note(`Lock ${lock + 1} ${NAME[act]}: ${r.why}, ${WHY[r.why] || 'refused'}`);
274 return;
275 }
276 R = r.state;
277 for (const e of r.events) {
278 if (e.type === 'open' || e.type === 'close') sound(e.type === 'open' ? 360 : 260, .12, 'triangle');
279 if (e.type === 'move') sound(200, .18, 'sine');
280 if (e.type === 'won') { sound(520, .3, 'sine'); sound(780, .5, 'sine', .15); }
281 if (e.type === 'flood') sound(110, .6, 'sawtooth');
282 }
283 renderHud();
284 if (R.status !== 'playing') finish(); else note(R.line);
285 }
286 function again() {
287 G.round++;
288 R = Lock.newRound(Lock.SEEDS[G.round % Lock.SEEDS.length]);
289 V.boats = {};
290 G.noteUntil = 0;
291 renderHud();
292 note(HINT);
293 }
294 const HINT = 'tap a paddle or gate to work it, a boat to move it';
295 function update(dt) {
296 G.time += dt;
297 settle(dt);
298 if (R.status === 'playing' && G.time >= G.noteUntil) setText('status', R.line);
299 }
300
301 /* ---------- input ---------- */
302 // the lock a boat would cross
303 const lockOf = b => b.at % 2 ? (b.at - 1) / 2 : b.dir === 'up' ? b.at / 2 : b.at / 2 - 1;
304 const rectOf = (pts, pad = 3) => {
305 const xs = pts.map(p => p.sx), ys = pts.map(p => p.sy);
306 return [Math.min(...xs) - pad, Math.min(...ys) - pad, Math.max(...xs) + pad, Math.max(...ys) + pad];
307 };
308 // the things to tap, front-most first: [rect, lock, act]
309 function targetsOnScreen() {
310 const list = [];
311 for (const b of R.boats) {
312 const v = V.boats[b.id];
313 if (!v) continue;
314 list.push([rectOf([project(...world(v.u - BOAT_L, -BOAT_W, v.z)), project(...world(v.u + BOAT_L, BOAT_W, v.z + 1.7))]), lockOf(b), 'move']);
315 }
316 for (let k = 0; k < Lock.LOCKS; k++) for (const top_ of [false, true]) {
317 const [x, y] = paddlePost(k, top_);
318 list.push([rectOf([project(x, y, 0), project(x, y, 2.2)], 4), k, top_ ? 'paddle-top' : 'paddle-bottom']);
319 const u = top_ ? lockEnd(k) : lockStart(k);
320 list.push([rectOf([project(...world(u, VB, gateTop(k))), project(...world(u, VF, 0))], 3), k, top_ ? 'gate-top' : 'gate-bottom']);
321 }
322 return list;
323 }
324 function hit(px, py) {
325 return targetsOnScreen().find(([r]) => px >= r[0] && px <= r[2] && py >= r[1] && py <= r[3]) || null;
326 }
327 canvas.addEventListener('pointerdown', e => {
328 canvas.focus({ preventScroll: true });
329 G.ring = false;
330 const r = canvas.getBoundingClientRect(), t = hit((e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H);
331 if (t) work(t[1], t[2]); else if (R.status !== 'playing') again();
332 });
333 canvas.addEventListener('focus', () => { if (canvas.matches(':focus-visible')) G.ring = true; });
334 canvas.addEventListener('keydown', e => {
335 const act = ACT_KEYS[e.key];
336 if (!act && e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
337 e.preventDefault();
338 if (e.repeat) return;
339 if (R.status !== 'playing') { again(); return; }
340 G.ring = true;
341 if (act) { work(G.lock, act); return; }
342 G.lock = clamp(G.lock + (e.key === 'ArrowLeft' ? -1 : 1), 0, Lock.LOCKS - 1);
343 note(`Lock ${G.lock + 1}: 1 top paddle, 2 bottom paddle, 3 top gate, 4 bottom gate, 5 move a boat`);
344 });
345
346 /* ---------- sound ---------- */
347 let audio = null, muted = false;
348 function ensureAudio() {
349 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
350 const AC = window.AudioContext || window.webkitAudioContext;
351 if (AC) audio = new AC();
352 }
353 function sound(freq, life, type, delay = 0) {
354 if (!audio || muted) return;
355 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
356 osc.type = type;
357 osc.frequency.setValueAtTime(freq, now);
358 gain.gain.setValueAtTime(.0001, now);
359 gain.gain.exponentialRampToValueAtTime(.07, now + .01);
360 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
361 osc.connect(gain).connect(audio.destination);
362 osc.start(now); osc.stop(now + life + .02);
363 }
364 const muteButton = document.getElementById('mute');
365 muteButton.addEventListener('click', () => {
366 muted = !muted;
367 muteButton.textContent = muted ? 'sound off' : 'sound on';
368 muteButton.setAttribute('aria-pressed', String(muted));
369 });
370
371 /* ---------- fit and boot ---------- */
372 addEventListener('resize', fit);
373 fit();
374 settle(1);
375 bake();
376 note(HINT);
377 renderHud();
378 canvas.focus({ preventScroll: true });
379 let last = performance.now();
380 function frame(now) {
381 update(Math.min(.04, (now - last) / 1000));
382 last = now;
383 draw();
384 requestAnimationFrame(frame);
385 }
386 requestAnimationFrame(frame);
387 </script>
388 </body>
389 </html>
og/home.png
Binary file not shown.
og/lock-keeper.png added
Binary file not shown.
rounds.mjs +34
@@ -2,6 +2,7 @@
22 // repeated until the game says the round is over. `over` matches the line the player reads at the end.
33 import { boot } from './playtest.mjs';
44 import { powerFor, MAX_SPEED, GRAVITY } from './coconut-shy/shy.js';
5 import Lock from './lock-keeper/lock.js';
56 import { bestThrow, LINE_MAX } from './bowls-green/bowls.js';
67 import { toss, MAX_AIM } from './hoopla/hoop.js';
78
@@ -9,6 +10,31 @@ const MID = [180, 140];
910 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
1011 const idling = seconds => g => g.run(seconds);
1112
13 // the operations of a shortest win from a round state: a breadth-first search over the rules' own `apply`
14 function solve(start) {
15 const ops = [];
16 for (let lock = 0; lock < Lock.LOCKS; lock++) for (const act of Lock.ACTS) ops.push({ lock, act });
17 const key = s => JSON.stringify([s.locks, s.boats.map(b => b.at)]);
18 const seen = new Map([[key(start), null]]);
19 let frontier = [start];
20 while (frontier.length) {
21 const next = [];
22 for (const s of frontier) for (const op of ops) {
23 const r = Lock.apply(s, op);
24 if (!r.ok || r.state.status === 'lost' || seen.has(key(r.state))) continue;
25 seen.set(key(r.state), { from: s, op });
26 if (r.state.status === 'won') {
27 const path = [];
28 for (let at = seen.get(key(r.state)); at; at = seen.get(key(at.from))) path.unshift(at.op);
29 return path;
30 }
31 next.push(r.state);
32 }
33 frontier = next;
34 }
35 return [];
36 }
37
1238 export const ROUNDS = {
1339 'balote': { over: /you win|rival wins/, outcome: /(you win|rival wins) \d+–\d+/, beat: g => { g.drag([180, 140], [150, 120], .4); g.run(2); g.tap(...MID); } },
1440 'beekeeper': { over: /play again/, outcome: /swarmed · \d+ honey/, beat: tapping() },
@@ -118,6 +144,14 @@ export const ROUNDS = {
118144 if (pair) { g.tap(...pair[0]); g.tap(...pair[1]); }
119145 g.run(.9);
120146 } },
147 // work the fewest operations that win (found by a search from the state on the page), each by the keys: Left and Right to the lock, then 1 to 5
148 'lock-keeper': { over: /play again/, outcome: /All \d+ boats through in \d+ operations/, beat: g => {
149 for (const op of solve(g.read('R'))) {
150 const want = op.lock, have = g.read('G.lock');
151 for (let n = have; n !== want; n += Math.sign(want - n)) g.press(want < n ? 'ArrowLeft' : 'ArrowRight', .02);
152 g.press(String(['paddle-top', 'paddle-bottom', 'gate-top', 'gate-bottom', 'move'].indexOf(op.act) + 1), .02);
153 }
154 } },
121155 // herd by pointer: hold the dog 3 units beyond the sheep furthest from its goal (the gate, then the pen)
122156 'sheepdog': { over: /play again/, outcome: /the flock is home · \d+ of 15/, beat: (() => {
123157 let down = false;
serve.test.mjs +7
@@ -465,6 +465,13 @@ test('Seed Packets and its rules script are served without a track', async () =>
465465 expect((await fetch(base + '/seed-packets/packets.js')).status).toBe(200);
466466 });
467467
468 test('Lock Keeper and its rules script are served without a track', async () => {
469 const page = await fetch(base + '/lock-keeper/');
470 expect(page.status).toBe(200);
471 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
472 expect((await fetch(base + '/lock-keeper/lock.js')).status).toBe(200);
473 });
474
468475 test('Empire Age and each of its scripts are served without a track', async () => {
469476 const page = await fetch(base + '/empire/');
470477 expect(page.status).toBe(200);
shell.js +1
@@ -44,6 +44,7 @@ window.PixelPlays = (() => {
4444 { id: 'bowls-green', title: 'Bowls Green', blurb: 'Drag back to set line and weight and curve your woods in close to the jack', kind: 'Sport', input: 'Drag', accent: '#4f7f3f', music: false, forged: true },
4545 { id: 'dinghy-race', title: 'Dinghy Race', blurb: 'Drag to trim the sail to the wind and round three buoys ahead of the fleet', kind: 'Racing', input: 'Drag', accent: '#2e8a7a', music: false, forged: true },
4646 { id: 'seed-packets', title: 'Seed Packets', blurb: 'Tap to turn over seed packets and match every pair before the gardener comes back', kind: 'Memory', input: 'Tap', accent: '#7d9a4a', music: false, forged: true },
47 { id: 'lock-keeper', title: 'Lock Keeper', blurb: 'Work the paddles and gates to bring every narrowboat through the flight of locks', kind: 'Strategy', input: 'Tap', accent: '#5a6e8a', music: false, forged: true },
4748 { id: 'empire', title: 'Empire Age', blurb: 'A real-time strategy game against a bot: gather, build, climb four ages, train an army and destroy the enemy town center', kind: 'Strategy', input: 'Tap', accent: '#3a5fa8', music: false, forged: true },
4849 { id: 'hot-air-balloon', title: 'Hot Air Balloon', blurb: 'Five flights over the farms: hold the burner to climb into a different wind, land on the cross for 5', kind: 'Precision', input: 'Hold', accent: '#d0453c', music: false, forged: true },
4950 { 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 },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs