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

Migrated from github.com/amirmushichge/pixel-plays

Add Coconut Shy: the playable page and its place in the catalogue, on the rules already in `coconut-shy/shy.js` #126

Merged opened this

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

Merged

vesper/pixel-plays:vesper/106-add-coconut-shy-the-playable-page-and-it → main 5 commits fork 3 threads · 3 unresolved

  • Merged. vesper/106-add-coconut-shy-the-playable-page-and-it was merged into main as 07b3d0a.

Review

Sign in to review this change.
9 files changed +482 −2
README.md +3 −2
@@ -45,6 +45,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4545 | [Sheepdog](sheepdog/) | A 90-second dusk over three hillside fields, five sheep each, scattered at the top: drag the dog (or use the arrow keys) so they flee it inside a set radius, flock together and wander when calm, and push one too hard and it bolts the wrong way; each sheep that goes through the dry-stone wall's gate and then into the hurdle pen scores, one that goes round the gate scores nothing once penned; the gate moves every field, the sun lowers with the clock, and 10 or more of 15 wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the dog; arrow keys |
4646 | [Firefly Jar](firefly-jar/) | A 90-second summer night in a back garden: tap a firefly while it glows to catch it into the jar (+1, golden +3), a dim one is scared off and breaks the streak, shoo the moths before they reach the lantern; the third moth ends the night (forged by the crew on the engine and shell above, not by the original creators) | Tap; Tab or arrows + space |
4747 | [Egg Basket](egg-basket/) | A red henhouse with a sloping tin roof and three hens on the ridge: they lay brown eggs (1 point) and rare golden ones (3) that roll down one of four roof lanes and drop off the eave; slide the basket under each before it reaches the ground, where it cracks; rolling speeds up every ten eggs laid (never so fast that the basket cannot cross three lanes in time), three cracks end the round and 25 or more wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the basket; Left and Right arrows move one lane |
48 | [Coconut Shy](coconut-shy/) | A village-fete stall with bunting and a stallholder, five coconuts on wooden posts: drag back and release to throw (or Left and Right to aim, hold Space for power, release to throw); a ball inside the square window knocks a coconut off its post, two glancing hits knock it too, and clearing all five wins a bonus ball; five balls a round, three rounds with the posts moved further back each time, and nine down or more of the game wins (forged by the crew on the engine and shell above, not by the original creators; rules in `coconut-shy/shy.js`) | Drag back and release; Left and Right to aim, hold Space |
4849 | [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 |
4950 | [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 |
5051 | [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 |
@@ -68,7 +69,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
6869 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.
6970
7071 ## Add a game
71 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, Empire Age, Egg Basket and Dinghy Race 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`.
72 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, Empire Age, Egg Basket, Dinghy Race and Coconut Shy 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`.
7273
7374 - `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.
7475 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -84,7 +85,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
8485 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
8586 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
8687 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
87 - 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, 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); all of it stops under `prefers-reduced-motion`.
88 - 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, 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); all of it stops under `prefers-reduced-motion`.
8889
8990 ## Empire Age
9091
coconut-shy/index.html added +382
@@ -0,0 +1,382 @@
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>Coconut Shy</title>
7 <!-- og:begin -->
8 <meta name="description" content="Drag and release to knock the coconuts off their posts, five balls a round">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/coconut-shy/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Coconut Shy">
13 <meta property="og:description" content="Drag and release to knock the coconuts off their posts, five balls a round">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/coconut-shy/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/coconut-shy.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="Coconut Shy: 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: #6b675f; --paper: #fff; --accent: #7a4a2a; }
outdated

--muted: #8b877f on #fff is about 3.4:1, below the 4.5:1 AA needed for the 13px labels ("down, 9 wins", "balls left", the status line). Use a darker tone such as #6b675f.

24 * { box-sizing: border-box; }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
27 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
28 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; }
outdated

outline: none on the focusable canvas removes the only focus indicator for the game's keyboard controls (Left/Right, Space). Replace with canvas:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } and drop outline: none.

29 canvas:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
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 #power { width: 72px; height: 4px; margin-top: 4px; background: rgba(122, 74, 42, .16); }
37 #power i { display: block; height: 100%; background: var(--accent); transform-origin: left; transform: scaleX(0); }
38 #line { color: var(--muted); min-height: 1.35em; }
39 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
outdated

The mute button's focus-visible state is only a colour change, which is hard to see. Give it a visible outline, e.g. button:focus-visible { outline: 2px solid var(--accent); }. Also add a <noscript> message in the body so JS-off visitors see why the page is empty.

40 button:hover, button:focus-visible { color: var(--ink); }
41 button:focus-visible { outline: 2px solid var(--accent); }
42 noscript p { position: fixed; z-index: 3; inset: 40px 0 auto; margin: 0; padding: 12px 16px; background: var(--paper); }
43 </style>
44 </head>
45 <body>
46 <noscript>
47 <p>Coconut Shy needs JavaScript. It is a village-fete coconut shy: throw balls to knock five coconuts off their posts, five balls a round over three rounds, with the posts moved further back each round; nine down or more wins.</p>
48 </noscript>
49 <div id="stage"><canvas id="c" tabindex="0" aria-label="A coconut shy at a village fete: five coconuts on wooden posts in a row, a striped stall with bunting behind them and a stallholder watching. Drag back on the canvas and release to throw, or press Left and Right to aim, hold Space to build power and release it to throw. Knock the coconuts off their posts, five balls a round, three rounds; nine down or more wins."></canvas></div>
50 <div id="scores">
51 <div class="row"><b id="down">0</b><span>down, 9 wins</span></div>
52 <div class="row"><b id="balls">5</b><span>balls left</span></div>
53 <div class="row"><b id="round">1</b><span>of 3 rounds</span><span id="aimed"></span></div>
54 <div class="row"><b id="best">0</b><span>best</span></div>
55 <div id="power"><i></i></div>
56 </div>
57 <div class="hud" id="bottom">
58 <div id="line"><span id="status" role="status" aria-live="polite"></span></div>
59 <button id="mute" type="button" aria-pressed="false">sound on</button>
60 </div>
61 <script src="../shell.js"></script>
62 <script>
63 PixelPlays.mount({
64 id: 'coconut-shy',
65 rules: [
66 'Drag back and release to throw, or Left and Right to aim and hold Space for power.',
67 'Five balls a round, posts further back each round. A square hit knocks a coconut off; two glances do too.',
68 'Clear all five for a bonus ball. Nine down or more wins.',
69 ],
70 });
71 </script>
72 <script>window.PP_SCENE = { originY: 10, shadowX: 1.3, shadowY: -.12 };</script>
73 <script src="../engine.js"></script>
74 <script src="shy.js"></script>
75 <script>
76 'use strict';
77
78 const BEST_KEY = 'pixel-plays-coconut-shy-best';
79 const OFF = 8, POWER_TIME = 1.2, PULL = 100, ANGLE_MIN = 10, ANGLE_MAX = 80; // raw metres to world; seconds to full power; canvas pixels to full power
80 const LINE_X = -OFF + .8, STALL_Y = -4.8, BUNT_Y = STALL_Y + 1.3, X0 = -5.6, X1 = 9.6, POST_H = 1.5;
81 const WOOD = [198, 160, 112], WOOD_DARK = [104, 70, 46], COCONUT = [120, 74, 44], EYE = [34, 22, 16];
82 const CREAM = [240, 228, 200], AWN_RED = [196, 62, 52], PLANK = [206, 168, 112], COUNTER = [172, 120, 72];
83 const BALL = [200, 54, 44], CHALK = [250, 246, 236];
84 const FLAGS = [[214, 70, 58], [240, 196, 60], [66, 120, 176], [240, 232, 212]];
85 const THROWER = { shirt: [74, 112, 172], stripe: [60, 96, 154], legs: [30, 38, 56], hair: [40, 28, 24], skin: [200, 142, 108] };
86 const KEEPER = { shirt: [240, 232, 212], stripe: [196, 62, 52], legs: [86, 70, 56], hair: [176, 176, 170], skin: [214, 160, 126] };
87 const earth = rampOf([186, 156, 112]);
88 const wx = d => d - OFF; // the rules' distance from the line, in world metres
89 const KEY_AIM = { ArrowLeft: -1, ArrowDown: -1, a: -1, A: -1, s: -1, ArrowRight: 1, ArrowUp: 1, d: 1, D: 1, w: 1 };
90
91 /* ---------- state: what the page itself keeps; every rule is in Shy ---------- */
92 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
93 let R = Shy.newGame(best0, (Math.random() * 1e9) | 0);
94 const G = { time: 0, status: '', angle: 45, held: 0, charging: false, pull: null, drag: null, flight: null, pending: null, settle: 9, flyers: [], wobble: null, rested: null };
95 const nodes = {};
96 for (const id of ['down', 'balls', 'round', 'best', 'status', 'aimed']) nodes[id] = document.getElementById(id);
97 nodes.power = document.querySelector('#power i');
98 const powerNow = () => G.pull ? G.pull.power : G.charging ? clamp(G.held / POWER_TIME, 0, 1) : 0;
99 function renderHud() {
100 nodes.down.textContent = R.down;
101 nodes.balls.textContent = R.ballsLeft;
102 nodes.round.textContent = R.round;
103 nodes.best.textContent = R.best;
104 nodes.aimed.textContent = 'angle ' + Math.round(G.angle) + '°';
105 }
106 function setStatus(text) {
107 if (text === G.status) return;
108 G.status = text;
109 nodes.status.textContent = text;
110 }
111 const tail = () => R.over ? ' · tap or press space to play again' : R.phase === 'between' ? ' · tap or press space for round ' + (R.round + 1) : '';
112 const HINT = 'drag back and release, or Left and Right, hold space, release';
113
114 /* ---------- baked scene: the green, the stall, the posts ---------- */
115 function groundColor(x, y, ix, iy) {
116 const edge = Math.pow(Math.pow(Math.abs(x - .5) / 12.4, 6) + Math.pow(Math.abs(y + .6) / 6.2, 6), 1 / 6);
117 const rough = edge + (noise(x * 1.1, y * 1.1) - .5) * .12;
118 if (rough > 1.04) return 0;
119 if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0;
120 if (Math.abs(x - LINE_X) < .07 && Math.abs(y) < 1.9) return rgb(...CHALK);
121 if (Math.abs(y) < 1.3 && x > LINE_X - 1.5) return earth[clamp(Math.floor(2.4 + (noise(x * 2, y * 2) - .5) * 1.3 + (bayerAt(ix, iy) - .5) * .5), 1, 3)];
122 const g = GRASS[clamp(Math.floor(noise(x * .6, y * .6) * 2.4 + hash(ix, iy) * .8 + .5), 0, 3)];
123 return rgb(g[0] * (.92 + hash(ix, iy) * .12), g[1] * (.92 + hash(ix, iy) * .12), g[2] * (.92 + hash(ix, iy) * .12));
124 }
125 function stall() {
126 const ys = STALL_Y;
127 box(X0, ys - .25, 0, X1, ys + .05, 2.5, PLANK, 3); // the back boards
128 box(X0, ys + .05, 0, X1, ys + .85, 1, COUNTER, 5); // the counter
129 for (const x of [X0, (X0 + X1) / 2, X1]) box(x - .12, ys + .8, 0, x + .12, ys + 1.04, 3.0, WOOD, 7); // front posts
130 for (let x = X0, k = 0; x < X1 - .01; x += 1, k++) { // the striped awning and its valance
131 const c = k & 1 ? CREAM : AWN_RED;
132 box(x, ys - .45, 2.5, Math.min(X1, x + 1), ys + 1.05, 2.75, c, k);
133 box(x, ys + 1.05, 2.2, Math.min(X1, x + 1), ys + 1.18, 2.75, c, k + 11);
134 }
135 for (let x = X0 + 1; x < X1; x += 2.6) { sphere(x, ys + .55, 1.3, .3, COCONUT, 'rough'); sphere(x + .5, ys + .55, 1.25, .3, COCONUT, 'rough'); sphere(x + .25, ys + .5, 1.8, .3, COCONUT, 'rough'); } // spare coconuts on the counter
136 for (let x = X0; x <= X1; x += .5) { castShadow(x, ys + 1, 2.6, .55, 1, 0); castShadow(x, ys, 1.5, .45, 1, 0); }
137 for (const x of [X0, X1]) { box(x - .1, BUNT_Y - .1, 0, x + .1, BUNT_Y + .1, 3.2, WOOD_DARK, 9); for (let z = 0; z < 3.2; z += .5) castShadow(x, BUNT_Y, z, .2, 1, 0); } // the bunting poles
138 }
139 function posts() {
140 for (const c of R.coconuts) {
141 const x = wx(c.x);
142 box(x - .18, -.18, 0, x + .18, .18, POST_H, WOOD, Math.floor(c.x * 3));
143 box(x - .28, -.28, POST_H, x + .28, .28, POST_H + .12, WOOD_DARK, 4);
144 for (let z = 0; z < POST_H; z += .5) castShadow(x, 0, z, .22, 1, 0);
145 }
146 }
147 function bake() {
148 ground.fill(0); shadowMask.fill(0); staticShadow.fill(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 stall();
159 posts();
160 bakeOcclusion();
161 staticShadow.set(shadowMask);
162 applyShadows(groundZ);
163 bakedPix.set(pix);
164 bakedZ.set(zb);
165 }
166
167 /* ---------- figures ---------- */
168 function coconut(x, y, z) {
169 sphere(x, y, z, .3, COCONUT, 'rough');
170 for (const [dy, dz] of [[-.11, .08], [.11, .08], [0, -.1]]) sphere(x - .27, y + dy, z + dz, .05, EYE, 'solid');
171 castShadow(x, y, z, .3, 1, 0);
172 }
173 function bunting() {
174 const t = STILL ? 0 : Math.floor(G.time * 8) / 8, n = 18;
175 for (let k = 1; k < n; k++) {
176 const f = k / n, x = X0 + (X1 - X0) * f, sag = Math.sin(f * Math.PI) * .55;
177 const sway = Math.round(Math.sin(t * 2.2 + k * .9) * 2) * .06;
178 sphere(x, BUNT_Y + sway, 3.1 - sag, .06, WOOD_DARK, 'solid');
179 sphere(x, BUNT_Y + sway, 2.9 - sag, .2, FLAGS[k % 4], 'solid');
180 sphere(x, BUNT_Y + sway * 1.5, 2.72 - sag, .11, FLAGS[k % 4], 'solid');
181 }
182 }
183 function keeper() {
184 const t = STILL ? 0 : Math.floor(G.time * 8) / 8, wave = Math.round(Math.sin(t * 1.6) * 2) * .12;
185 figure(wx(3.4), -2.6, 2.7, { stance: .12, armR: .5 + wave, armL: .3 - wave * .5 }, KEEPER, dynamicAdd);
186 }
187 function throwerPose() {
188 if (G.flight) { const f = clamp(G.flight.t / G.flight.T, 0, 1); return { stance: .24, lean: .2, armR: lerp(2.7, 1.5, f), armL: .5 }; }
189 if (G.settle < 1) return { stance: .2, lean: .1, armR: 1.4, armL: .5 };
190 const p = powerNow();
191 return { stance: .22, lean: .05 + p * .25, crouch: p * .2, armR: G.charging || G.pull ? -.5 - p * 1.1 : .4, armL: .5 };
192 }
193 function drawBall(x, y, z) {
194 sphere(x, y, z, .2, BALL, 'gloss');
195 castShadow(x, y, z, .2, 1, 0);
196 }
197 function aimDots(hand) {
198 const a = G.angle * Math.PI / 180, p = powerNow(), pts = [], len = .8 + p * 3;
199 for (let k = 1; k <= 7; k++) {
200 const s = len * k / 7 + .5, q = project(hand[0] + Math.cos(a) * s, hand[1], hand[2] + Math.sin(a) * s);
201 pts.push([q.sx, q.sy]);
202 }
203 drawDots(pts, SIGNAL);
204 }
205 function ballAt() {
206 const f = G.flight;
207 if (!f) return null;
208 const u = clamp(f.t / f.T, 0, 1), x = lerp(LINE_X + .5, wx(f.land), u);
209 return [x, 0, lerp(1.6, .2, u) + f.apex * 4 * u * (1 - u)];
210 }
211 function draw() {
212 pix.set(bakedPix);
213 zb.set(bakedZ);
214 pendingShadows.length = 0;
215 bunting();
216 keeper();
217 const hand = figure(LINE_X - .5, 0, 0, throwerPose(), THROWER, dynamicAdd);
218 const flying = ballAt();
219 R.coconuts.forEach((c, i) => {
220 const x = wx(c.x), shake = G.wobble && G.wobble.i === i && !STILL ? Math.sin(G.time * 40) * .08 * Math.max(0, 1 - (G.time - G.wobble.at) / .6) : 0;
221 if (!c.down) coconut(x, shake, POST_H + .42);
222 else if (!G.flyers.some(f => f.i === i)) coconut(x + .75, (i & 1 ? .55 : -.55), .3); // a fallen coconut rolls to the grass beside its post
223 });
224 for (const f of G.flyers) {
225 const u = clamp((G.time - f.at) / .45, 0, 1);
226 coconut(lerp(f.x, f.x + .75, u), lerp(0, f.i & 1 ? .55 : -.55, u), lerp(POST_H + .42, .3, u) + Math.sin(u * Math.PI) * .9);
227 }
228 if (flying) drawBall(...flying);
229 else if (G.rested && (G.settle < 1.2 || R.phase !== 'aim')) drawBall(...G.rested);
230 else if (R.phase === 'aim' && R.ballsLeft > 0) drawBall(hand[0] + .1, hand[1], hand[2] + .08);
231 flushShadows();
232 applyShadows(bakedZ);
233 shadeEdges();
234 if (R.phase === 'aim' && !G.flight && !R.over) aimDots(hand);
235 ctx.putImageData(image, 0, 0);
236 }
237
238 /* ---------- game: the page turns input into Shy.throwBall and shows what the rules answer ---------- */
239 const WORDS = { knocked: 'knocked off!', fell: 'down it goes', wobbled: 'a wobble', miss: 'missed' };
240 function release(power, angle) {
241 const res = Shy.throwBall(R, { power, angle });
242 if (!res.event) return;
243 const v = power * Shy.MAX_SPEED, a = angle * Math.PI / 180;
244 G.pending = res;
245 G.flight = { t: 0, T: clamp(2 * v * Math.sin(a) / Shy.GRAVITY * .6, .35, 1.2), land: res.event.land, apex: v * v * Math.sin(a) ** 2 / (2 * Shy.GRAVITY) };
246 G.rested = null; G.charging = false; G.held = 0; G.pull = null; G.drag = null;
247 setStatus('');
248 sound('throw', power);
249 }
250 function land() {
251 const { state, event } = G.pending, was = R;
252 G.pending = null; G.flight = null; G.settle = 0;
253 R = state;
254 G.rested = [wx(event.land), 0, .2];
255 if (event.target >= 0) {
256 if (event.type === 'wobbled') G.wobble = { i: event.target, at: G.time };
257 else G.flyers.push({ i: event.target, x: wx(was.coconuts[event.target].x), at: G.time });
258 }
259 sound(event.type === 'miss' ? 'miss' : event.type === 'wobbled' ? 'wobble' : 'knock');
260 if (R.over) {
261 if (R.best > was.best) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: the best lives for this visit */ }
262 sound(R.outcome === 'won' ? 'win' : 'miss');
263 }
264 setStatus((R.over || R.phase === 'between' ? '' : WORDS[event.type] + ' · ') + R.line + tail());
265 renderHud();
266 }
267 function advance() { // a tap between rounds or after the game: the rules say what comes next
268 const next = R.over ? Shy.again(R) : R.phase === 'between' ? Shy.nextRound(R) : null;
269 if (!next) return false;
270 if (G.settle < .5) return true;
271 R = next; G.flyers.length = 0; G.wobble = null; G.rested = null; G.angle = 45;
272 bake();
273 setStatus(R.line);
274 renderHud();
275 return true;
276 }
277 function update(dt) {
278 G.time += dt;
279 G.settle += dt;
280 if (G.charging) G.held += dt;
281 if (G.flight) { G.flight.t += dt; if (G.flight.t >= G.flight.T) land(); }
282 G.flyers = G.flyers.filter(f => G.time - f.at < .45);
283 nodes.power.style.transform = 'scaleX(' + powerNow() + ')';
284 nodes.aimed.textContent = 'angle ' + Math.round(G.angle) + '°';
285 }
286
287 /* ---------- input ---------- */
288 const busy = () => !!G.flight || G.settle < .35;
289 function pullTo(e) {
290 const r = canvas.getBoundingClientRect(), x = (e.clientX - r.left) / (r.width || W) * W, y = (e.clientY - r.top) / (r.height || H) * H;
291 const dx = x - G.drag.x, dy = y - G.drag.y;
292 G.angle = clamp(45 + dy * .4, ANGLE_MIN, ANGLE_MAX);
293 G.pull = { power: clamp(Math.hypot(dx, dy) / PULL, 0, 1) };
294 renderHud();
295 }
296 canvas.addEventListener('pointerdown', e => {
297 ensureAudio();
298 canvas.focus({ preventScroll: true });
299 if (advance() || busy() || R.phase !== 'aim') return;
300 const r = canvas.getBoundingClientRect();
301 G.drag = { id: e.pointerId, x: (e.clientX - r.left) / (r.width || W) * W, y: (e.clientY - r.top) / (r.height || H) * H };
302 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
303 G.pull = { power: 0 };
304 });
305 canvas.addEventListener('pointermove', e => { if (G.drag && G.drag.id === e.pointerId) pullTo(e); });
306 canvas.addEventListener('pointerup', e => {
307 if (!G.drag || G.drag.id !== e.pointerId) return;
308 pullTo(e);
309 const power = G.pull.power;
310 G.drag = null; G.pull = null;
311 if (power >= .05) release(power, G.angle);
312 });
313 canvas.addEventListener('pointercancel', () => { G.drag = null; G.pull = null; });
314 canvas.addEventListener('keydown', e => {
315 const k = KEY_AIM[e.key];
316 if (!k && e.key !== ' ' && e.key !== 'Enter') return;
317 e.preventDefault();
318 ensureAudio();
319 if (k) { if (!busy() && R.phase === 'aim') G.angle = clamp(G.angle + k, ANGLE_MIN, ANGLE_MAX); renderHud(); return; }
320 if (e.repeat) return;
321 if (advance() || busy() || R.phase !== 'aim') return;
322 G.charging = true; G.held = 0; G.drag = null; G.pull = null;
323 });
324 canvas.addEventListener('keyup', e => {
325 if (e.key !== ' ' && e.key !== 'Enter') return;
326 if (!G.charging) return;
327 const power = clamp(G.held / POWER_TIME, 0, 1);
328 G.charging = false; G.held = 0;
329 if (power >= .05) release(power, G.angle);
330 });
331 canvas.addEventListener('blur', () => { G.charging = false; G.held = 0; G.drag = null; G.pull = null; });
332
333 /* ---------- sound ---------- */
334 let audio = null, muted = false;
335 function ensureAudio() {
336 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
337 const AC = window.AudioContext || window.webkitAudioContext;
338 if (AC) audio = new AC();
339 }
340 function sound(kind, n = 0) {
341 if (!audio || muted) return;
342 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
343 const spec = {
344 throw: [200 + n * 300, 480 + n * 400, .16, .05, 'triangle'],
345 knock: [300, 110, .16, .12, 'square'],
346 wobble: [260, 200, .12, .07, 'triangle'],
347 miss: [180, 70, .2, .08, 'sine'],
348 win: [520, 1040, .3, .07, 'triangle'],
349 }[kind];
350 osc.type = spec[4];
351 osc.frequency.setValueAtTime(spec[0], now);
352 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
353 gain.gain.setValueAtTime(spec[3], now);
354 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
355 osc.connect(gain).connect(audio.destination);
356 osc.start(now); osc.stop(now + spec[2] + .01);
357 }
358 const muteButton = document.getElementById('mute');
359 muteButton.addEventListener('click', () => {
360 muted = !muted;
361 muteButton.textContent = muted ? 'sound off' : 'sound on';
362 muteButton.setAttribute('aria-pressed', String(muted));
363 });
364
365 /* ---------- fit and boot ---------- */
366 addEventListener('resize', fit);
367 fit();
368 bake();
369 setStatus(R.line + ' · ' + HINT);
370 renderHud();
371 canvas.focus({ preventScroll: true });
372 let last = performance.now();
373 function frame(now) {
374 update(Math.min(.04, (now - last) / 1000));
375 last = now;
376 draw();
377 requestAnimationFrame(frame);
378 }
379 requestAnimationFrame(frame);
380 </script>
381 </body>
382 </html>
coconut-shy/page.test.mjs added +74
@@ -0,0 +1,74 @@
1 import { readFileSync } from 'node:fs';
2 import { test, expect } from 'bun:test';
3 import { boot } from '../playtest.mjs';
4 import { powerFor } from './shy.js';
5
6 const state = g => g.read('R');
7
8 test('the page shows what the rules state reports: down, balls left, round and best', () => {
9 const g = boot('coconut-shy');
10 g.run(.5);
11 expect(String(g.el('down').textContent)).toBe('0');
12 expect(String(g.el('balls').textContent)).toBe('5');
13 expect(String(g.el('round').textContent)).toBe('1');
14 expect(g.el('status').textContent).toContain(state(g).line);
15 });
16
17 test('holding Space and releasing throws one ball, and the HUD follows the rules once it lands', () => {
18 const g = boot('coconut-shy');
19 g.press(' ', 1.1);
20 expect(state(g).ballsLeft).toBe(5); // the ball is in the air: nothing is decided yet
21 g.run(2.5);
22 expect(state(g).ballsLeft).toBe(4);
23 expect(String(g.el('balls').textContent)).toBe('4');
24 expect(g.errors).toEqual([]);
25 });
26
27 test('Left and Right change the angle the throw is made at', () => {
28 const g = boot('coconut-shy');
29 const from = g.read('G.angle');
30 g.press('ArrowRight', .1); g.press('ArrowRight', .1);
31 expect(g.read('G.angle')).toBe(from + 2);
32 g.press('ArrowLeft', .1);
33 expect(g.read('G.angle')).toBe(from + 1);
34 });
35
36 test('dragging back and releasing throws; a short tap does not', () => {
37 const g = boot('coconut-shy');
38 g.tap(180, 140);
39 g.run(2);
40 expect(state(g).ballsLeft).toBe(5);
41 g.drag([200, 120], [120, 140], .4);
42 g.run(2.5);
43 expect(state(g).ballsLeft).toBe(4);
44 });
45
46 test('a ball thrown at the first coconut knocks it off, and the page draws what the rules say', () => {
47 const g = boot('coconut-shy');
48 const x = state(g).coconuts[0].x, want = powerFor(x, 45);
49 g.keyDown(' ');
50 g.read('G.held = ' + want * 1.2); // exactly the held time that is `want` power, not a frame either side of it
51 g.keyUp(' ');
52 g.run(2.5);
53 const s = state(g);
54 expect(s.coconuts[0].down).toBe(true);
55 expect(s.down).toBeGreaterThanOrEqual(1);
56 expect(String(g.el('down').textContent)).toBe(String(s.down));
57 });
58
59 test('the page has a mute button, says how to play on the canvas and ships no track', () => {
60 const html = readFileSync(new URL('./index.html', import.meta.url), 'utf8');
61 expect(html).toContain('id="mute"');
62 expect(html).toMatch(/aria-label="[^"]*[Dd]rag[^"]*Space[^"]*"/);
63 expect(html).not.toMatch(/\.mp3/);
64 });
65
66 test('the canvas shows where keyboard focus is, the labels are dark enough to read and JS-off visitors get a line', () => {
67 const html = readFileSync(new URL('./index.html', import.meta.url), 'utf8');
68 expect(html).not.toMatch(/outline:\s*none/);
69 expect(html).toMatch(/canvas:focus-visible\s*\{[^}]*outline:\s*2px solid/);
70 expect(html).toMatch(/button:focus-visible\s*\{[^}]*outline:\s*2px solid/);
71 const [r, g, b] = html.match(/--muted:\s*#(\w\w)(\w\w)(\w\w)/).slice(1).map(h => parseInt(h, 16) / 255).map(c => c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4);
72 expect(1.05 / (.2126 * r + .7152 * g + .0722 * b + .05)).toBeGreaterThanOrEqual(4.5); // contrast against white
73 expect(html).toMatch(/<noscript>[\s\S]*Coconut Shy needs JavaScript/);
74 });
index.html +1
@@ -95,6 +95,7 @@ footer a::after { content: none; }
9595 <li data-kind="Catching" data-input="Drag" style="--accent:#5b8a3a"><a href="sheepdog/">Sheepdog</a><span>Drag the dog to steer five sheep through the gate and into the pen before dusk</span><span>Game forged by the crew</span><span class="tags">Catching · Drag</span></li>
9696 <li data-kind="Catching" data-input="Tap" style="--accent:#c9b43a"><a href="firefly-jar/">Firefly Jar</a><span>Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern</span><span>Game forged by the crew</span><span class="tags">Catching · Tap</span></li>
9797 <li data-kind="Catching" data-input="Drag" style="--accent:#d08a2e"><a href="egg-basket/">Egg Basket</a><span>Slide the basket under the eave and catch the eggs before three crack</span><span>Game forged by the crew</span><span class="tags">Catching · Drag</span></li>
98 <li data-kind="Throwing" data-input="Drag" style="--accent:#7a4a2a"><a href="coconut-shy/">Coconut Shy</a><span>Drag and release to knock the coconuts off their posts, five balls a round</span><span>Game forged by the crew</span><span class="tags">Throwing · Drag</span></li>
9899 <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>
99100 <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>
100101 <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>
og/coconut-shy.png added
Binary file not shown.
og/home.png
Binary file not shown.
rounds.mjs +14
@@ -1,6 +1,7 @@
11 // One scripted round per game: a beat of play (where to tap, drag or hold, and for how long) that is
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';
4 import { powerFor, MAX_SPEED, GRAVITY } from './coconut-shy/shy.js';
45
56 const MID = [180, 140];
67 const tapping = (wait = .3) => g => { g.tap(...MID); g.run(wait); };
@@ -18,6 +19,19 @@ export const ROUNDS = {
1819 // tend the fire: a twig whenever the flames sink toward the lower mark
1920 'campfire': { over: /play again/, outcome: /dawn, the fire held · \d+ s/, beat: g => { if (g.read('G.heat') < 55 && g.read('G.fuel.length') < 3) g.press(' '); g.step(5); } },
2021 'domino-run': { over: /play again/, outcome: /\d+ points/, beat: g => { g.press(' '); g.press('ArrowRight'); g.press('Enter'); g.run(1); } },
22 // pick a whole number of frames of Space (a frame is 0.04 s of the 1.2 s charge) at least as strong as a 45 degree throw to the first
23 // standing coconut needs, trim the angle to cancel the overshoot, then hold Space for exactly those frames and let go
24 'coconut-shy': { over: /play again/, outcome: /You win with \d+ down!/, beat: g => {
25 if (g.read('R.over || R.phase === "between"')) { g.press(' ', .6); return; }
26 const x = g.read('(R.coconuts.find(c => !c.down) || R.coconuts[0]).x');
27 const frames = Math.min(30, Math.ceil(powerFor(x, 45) * 30)), v = frames / 30 * MAX_SPEED;
28 const angle = Math.asin(Math.min(1, x * GRAVITY / (v * v))) * 90 / Math.PI;
29 for (let n = Math.round(angle - g.read('G.angle')); n !== 0; n -= Math.sign(n)) g.press(n < 0 ? 'ArrowLeft' : 'ArrowRight', .04);
30 g.keyDown(' ');
31 g.step(frames);
32 g.keyUp(' ');
33 g.run(2);
34 } },
2135 // hold the sail at half the angle to the wind, which is what drives the boat best
2236 'dinghy-race': { over: /play again|race again/, outcome: /(First|Second) place in \d+\.\d s: a win/, beat: g => {
2337 const x = 30 + g.read('Dinghy.bestSail(Dinghy.windAngle(R.heading, R.wind))') / 90 * 300;
serve.test.mjs +7
@@ -430,6 +430,13 @@ test('Egg Basket and its rules script are served without a track', async () => {
430430 expect((await fetch(base + '/egg-basket/basket.js')).status).toBe(200);
431431 });
432432
433 test('Coconut Shy and its rules script are served without a track', async () => {
434 const page = await fetch(base + '/coconut-shy/');
435 expect(page.status).toBe(200);
436 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
437 expect((await fetch(base + '/coconut-shy/shy.js')).status).toBe(200);
438 });
439
433440 test('Dinghy Race and its rules script are served without a track', async () => {
434441 const page = await fetch(base + '/dinghy-race/');
435442 expect(page.status).toBe(200);
shell.js +1
@@ -39,6 +39,7 @@ window.PixelPlays = (() => {
3939 { id: 'sheepdog', title: 'Sheepdog', blurb: 'Drag the dog to steer five sheep through the gate and into the pen before dusk', kind: 'Catching', input: 'Drag', accent: '#5b8a3a', music: false, forged: true },
4040 { id: 'firefly-jar', title: 'Firefly Jar', blurb: 'Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern', kind: 'Catching', input: 'Tap', accent: '#c9b43a', music: false, forged: true },
4141 { id: 'egg-basket', title: 'Egg Basket', blurb: 'Slide the basket under the eave and catch the eggs before three crack', kind: 'Catching', input: 'Drag', accent: '#d08a2e', music: false, forged: true },
42 { id: 'coconut-shy', title: 'Coconut Shy', blurb: 'Drag and release to knock the coconuts off their posts, five balls a round', kind: 'Throwing', input: 'Drag', accent: '#7a4a2a', music: false, forged: true },
4243 { 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 },
4344 { 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 },
4445 { 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 },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs