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

Migrated from github.com/amirmushichge/pixel-plays

Add Market Scale: weigh fruit onto a pan scale to hit each customer's order #37

Merged opened this

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

Merged

quill/pixel-plays:quill/26-add-market-scale-weigh-fruit-onto-a-pan → main 2 commits fork 1 thread · 1 unresolved

  • Merged. quill/26-add-market-scale-weigh-fruit-onto-a-pan was merged into main as b54bea6.

Review

Sign in to review this change.
7 files changed +734 −1
README.md +2 −1
@@ -25,6 +25,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
2525 | [Row Home](row-home/) | Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab, hold left or right to steer against the current (forged by the crew on the engine and shell above, not by the original creators) | Tap or space to stroke; hold left/right |
2626 | [Orchard](orchard/) | Catch falling apples in a basket: ripe 1, golden 3, a wasp-bitten brown one costs a life, three lives end the round (forged by the crew on the engine and shell above, not by the original creators) | Drag; left/right arrows |
2727 | [Lighthouse](lighthouse/) | A 90-second night: sweep the lighthouse beam so boats drifting in towards the rocks are held in the light for a second and turn away, +1 each; three boats lost on the rocks end the night early (forged by the crew on the engine and shell above, not by the original creators) | Drag; hold left/right |
28 | [Market Scale](market-scale/) | Five customers, 15 seconds each: weigh fruit onto a hanging pan scale to match the weight on the chalk slate, exact scores 3 and within 50 g scores 1 (forged by the crew on the engine and shell above, not by the original creators) | Drag or tap fruit, tap the bell; arrows + enter, space |
2829
2930 ## Run
3031 Requires [Node.js](https://nodejs.org/); nothing to install.
@@ -38,7 +39,7 @@ Then open http://127.0.0.1:5300/. `PORT` and `HOST` override the port and addres
3839 On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. The app keeps no state, so it does not need `FORGE_APP_DATA`. `bun test` checks that the server answers every game page and track.
3940
4041 ## Add a game
41 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 (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). 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 and Lighthouse 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`.
42 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 (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too). 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 and Market Scale 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`.
4243
4344 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
4445 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
index.html +1
@@ -40,6 +40,7 @@ footer a { display: inline; padding: 0; font-weight: inherit; text-decoration: u
4040 <li><a href="row-home/">Row Home</a><span>Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab</span><span>Game forged by the crew</span></li>
4141 <li><a href="orchard/">Orchard</a><span>Catch falling apples in a basket: ripe 1, golden 3, a wasp-bitten brown one costs a life</span><span>Game forged by the crew</span></li>
4242 <li><a href="lighthouse/">Lighthouse</a><span>Sweep the lighthouse beam to turn boats away from the rocks: hold one in the light for a second, three wrecks end the night</span><span>Game forged by the crew</span></li>
43 <li><a href="market-scale/">Market Scale</a><span>Weigh fruit onto a hanging pan scale to match each order: exact scores 3, within 50 g scores 1</span><span>Game forged by the crew</span></li>
4344 </ul>
4445 <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.</footer>
4546 </main>
market-scale/index.html added +465
@@ -0,0 +1,465 @@
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>Market Scale</title>
7 <style>
8 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; }
9 * { box-sizing: border-box; }
10 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
11 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
12 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
13 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
14 .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; }
15 #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; }
16 #scores b { font-size: 16px; font-weight: 600; font-variant-numeric: tabular-nums; min-width: 5ch; }
17 #scores span { color: var(--muted); font-variant-numeric: tabular-nums; min-height: 1.35em; }
18 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
19 #notes { display: grid; gap: 2px; }
20 #notes span { color: var(--muted); min-height: 1.35em; }
21 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
22 button:hover, button:focus-visible { color: var(--ink); }
23 </style>
24 </head>
25 <body>
26 <div id="stage"><canvas id="c" tabindex="0" aria-label="Market Scale. Drag fruit from the crate into the pan, or tap it to put it in, and tap a fruit in the pan to take it out. With the keyboard, arrows pick a fruit and enter moves it. Match the weight on the chalk slate, then tap the bell or press space to sell. Five customers, fifteen seconds each."></canvas></div>
27 <div id="scores"><b id="score">0</b><span id="meta"></span></div>
28 <div class="hud" id="bottom">
29 <div id="notes"><span id="status" role="status" aria-live="polite"></span><span>apple 150 · pear 200 · lemon 100 · melon 500 g</span></div>
30 <button id="mute" type="button" aria-pressed="false">sound on</button>
31 </div>
32 <script src="../shell.js"></script>
33 <script>
34 PixelPlays.mount({
35 id: 'market-scale',
36 rules: [
37 'Drag fruit into the pan, or tap it, to match the weight on the chalk slate; tap one in the pan to take it out.',
38 'Arrows pick a fruit, enter moves it. Tap the bell or press space to sell.',
39 'Exact scores 3, within 50 g scores 1, and a miss or the 15-second clock running out scores 0.',
40 'Five customers make a round.',
41 ],
42 });
43 </script>
44 <script>window.PP_SCENE = { originY: 18, shadowX: 1.1, shadowY: -.3 };</script>
45 <script src="../engine.js"></script>
46 <script src="scale.js"></script>
47 <script>
48 'use strict';
49
50 const BEST_KEY = 'pixel-plays-market-scale-best';
51 const HALF = 11, SQ = Math.SQRT1_2, STALL = { lo: -8, hi: -1 }, PAN = { x: 1.5, y: -4.5, radius: 3, rest: 3 };
52 const SAND = [[196, 170, 128], [206, 182, 138], [216, 194, 150], [226, 206, 164]];
53 const WOOD = [168, 120, 78], WOOD_DARK = [112, 78, 54], STRAW = [226, 196, 108], BRASS = [232, 178, 62], CHAIN = [150, 128, 96];
54 const AWN_RED = [214, 72, 52], AWN_CREAM = [246, 236, 214];
55 const KIND_COLOR = { apple: [206, 48, 46], pear: [148, 178, 62], lemon: [248, 212, 54], melon: [66, 138, 72] };
56 const STEM = [92, 66, 44];
57 const SLATE = rgb(40, 56, 50), SLATE_LIGHT = rgb(52, 70, 62), CHALK = rgb(244, 240, 226), FRAME = rgb(...WOOD), FRAME_DARK = rgb(...WOOD_DARK);
58 const FACE = rgb(250, 244, 226), BRASS_PX = rgb(...BRASS), BRASS_DARK = rgb(176, 124, 40), NEEDLE = rgb(176, 32, 32), TICK = rgb(60, 52, 44);
59 const CRATE_AT = { x0: -5.3, x1: -1.1, y0: 2.8, y1: 9.9 };
60 const BELL = { x: 3, y: 1.5 };
61 const roofZ = (x, y) => 7.2 + .05 * (-(x + y) - 2);
62 // screen-axis offsets (right, down) to world axes
63 const uv = (du, dv) => [(du + dv) * SQ, (dv - du) * SQ];
64
65 /* ---------- ground ---------- */
66 function groundColor(x, y, ix, iy) {
67 const edge = Math.pow(Math.pow(Math.abs(x) / HALF, 4) + Math.pow(Math.abs(y) / HALF, 4), .25);
68 const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .1;
69 if (rough > 1.04) return 0;
70 if (rough > .94 && hash(ix, iy) < (rough - .94) / .1) return 0;
71 const t = noise(x * .8, y * .8) * 1.1 + (hash(ix, iy) - .5) * .5 + (1 - edge) * .14 - .1;
72 return rgb(...SAND[clamp(Math.floor(t * 4.2), 0, 3)]);
73 }
74 /* ---------- baked stall ---------- */
75 function post(x, y, top) {
76 capsule([x, y, 0], [x, y, top], .22, .22, () => WOOD_DARK, 'rough');
77 castShadow(x, y, top, .35, 1, .2);
78 }
79 function awning() {
80 const { lo, hi } = STALL;
81 // stripes run front to back, which stand straight up the screen
82 for (let k = -20; k <= 20; k++) {
83 const w = k * .5;
84 const y0 = Math.max(lo, lo - w), y1 = Math.min(hi, hi - w);
85 if (y1 <= y0) continue;
86 const a = [y0 + w, y0, 0], b = [y1 + w, y1, 0];
87 a[2] = roofZ(a[0], a[1]); b[2] = roofZ(b[0], b[1]);
88 const color = Math.floor((k + 40) / 2) % 2 ? AWN_CREAM : AWN_RED;
89 capsule(a, b, .34, .34, () => color, 'solid');
90 }
91 // the front valance band along both front edges
92 for (const edge of [[hi, null], [null, hi]]) for (let t = lo; t <= hi; t += .7) {
93 const x = edge[0] == null ? t : edge[0], y = edge[1] == null ? t : edge[1];
94 sphere(x, y, roofZ(x, y) - .3, .42, Math.floor((t - lo) / .7) % 2 ? AWN_CREAM : AWN_RED, 'solid');
95 }
96 }
97 function crate() {
98 const c = CRATE_AT;
99 box(c.x0, c.y0, 0, c.x1, c.y1, 1, WOOD, 3);
100 box(c.x0 + .3, c.y0 + .3, 0, c.x1 - .3, c.y1 - .3, 1.12, STRAW, 5);
101 castShadow((c.x0 + c.x1) / 2, (c.y0 + c.y1) / 2, 1, 3.4, 1, .3);
102 }
103 function bake() {
104 zb.fill(-1e9);
105 pix.fill(rgb(255, 255, 255));
106 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
107 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy);
108 if (!c) continue;
109 pix[i] = c; ground[i] = 1;
110 zb[i] = (g.x + g.y) / R2 * COS;
111 }
112 groundZ.set(zb);
113 const { lo, hi } = STALL;
114 // counter along the back of the stall, then the four posts and the roof
115 box(lo + .3, lo + .3, 0, hi - .3, lo + 1.5, 2, WOOD, 9);
116 castShadow((lo + hi) / 2, lo + 1, 2, 3.4, 1, .3);
117 post(lo, lo, roofZ(lo, lo) - .2); post(hi, lo, roofZ(hi, lo) - .2);
118 post(lo, hi, roofZ(lo, hi) - .2); post(hi, hi, roofZ(hi, hi) - .2);
119 awning();
120 // the arm the scale hangs from
121 capsule([hi, PAN.y, roofZ(hi, PAN.y) - .5], [PAN.x, PAN.y, roofZ(hi, PAN.y) - .5], .16, .16, () => WOOD_DARK, 'rough');
122 crate();
123 // a stool for the bell
124 box(BELL.x - .8, BELL.y - .8, 0, BELL.x + .8, BELL.y + .8, 1.4, WOOD, 11);
125 castShadow(BELL.x, BELL.y, 1.4, 1.2, 1, .2);
126 bakeOcclusion();
127 staticShadow.set(shadowMask);
128 applyShadows(groundZ);
129 bakedPix.set(pix);
130 bakedZ.set(zb);
131 }
132
133 /* ---------- state ---------- */
134 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
135 let G = MarketScale.newState(best0), time = 0, status = '', overT = 0, lastPhase = 'ready', ringT = 9, drag = null, lastTick = 0;
136 const nodes = { score: document.getElementById('score'), meta: document.getElementById('meta'), status: document.getElementById('status') };
137 let shown = '';
138 function renderHud() {
139 const text = [G.score, G.best, G.customer, Math.ceil(G.clock), G.total, G.phase].join('|');
140 if (text === shown) return;
141 shown = text;
142 nodes.score.textContent = String(G.score);
143 const parts = [];
144 if (G.best) parts.push('best ' + G.best);
145 if (G.phase === 'serve' || G.phase === 'sold') parts.push('customer ' + (G.customer + 1) + '/' + MarketScale.CUSTOMERS);
146 if (G.phase === 'serve') parts.push(Math.ceil(G.clock) + 's', 'pan ' + G.total + ' g');
147 nodes.meta.textContent = parts.join(' · ');
148 }
149 function setStatus(text) {
150 if (text === status) return;
151 status = text;
152 nodes.status.textContent = text;
153 }
154 function statusFor() {
155 if (G.phase === 'ready') return 'tap the bell or press space to open the stall';
156 if (G.phase === 'over') return G.score + ' of ' + MarketScale.CUSTOMERS * 3 + (G.record ? ' · new best' : '') + ' · tap to play again';
157 if (G.phase === 'sold') {
158 const p = G.sale.points, how = G.sale.late ? 'too slow' : p === 3 ? 'exact' : p === 1 ? 'close, ' + Math.abs(G.sale.total - G.sale.target) + ' g off' : 'missed by ' + Math.abs(G.sale.total - G.sale.target) + ' g';
159 return how + ' · +' + p;
160 }
161 return 'want ' + G.target + ' g · pan ' + G.total + ' g · tap the bell to sell';
162 }
163 function press() { // the bell, or space
164 ensureAudio();
165 if (G.phase === 'ready') { MarketScale.start(G); ringT = 0; sound('bell'); return; }
166 if (G.phase === 'over') { if (overT > .8) { G = MarketScale.restart(G); lastPhase = 'ready'; } return; }
167 if (MarketScale.sell(G)) { ringT = 0; sound('bell'); }
168 }
169 function move(i) {
170 ensureAudio();
171 if (MarketScale.toggle(G, i)) sound('thud');
172 }
173 function update(dt) {
174 time += dt;
175 ringT += dt;
176 MarketScale.step(G, dt);
177 if (G.phase !== lastPhase) {
178 if (G.phase === 'sold') { ringT = 0; sound(G.sale.points ? 'coin' : 'miss'); }
179 if (G.phase === 'over') {
180 overT = 0; drag = null;
181 if (G.record) try { localStorage.setItem(BEST_KEY, String(G.best)); } catch (e) { /* private window: keep it for this visit */ }
182 }
183 lastPhase = G.phase;
184 }
185 if (G.phase === 'over') overT += dt;
186 const tick = Math.ceil(G.clock);
187 if (G.phase === 'serve' && tick <= 3 && tick !== lastTick) sound('tick');
188 lastTick = tick;
189 setStatus(statusFor());
190 renderHud();
191 }
192
193 /* ---------- geometry of the pieces ---------- */
194 const slotAt = i => ({ x: CRATE_AT.x0 + 1.2 + 1.9 * Math.floor(i / 4), y: CRATE_AT.y0 + 1.1 + 1.7 * (i % 4) });
195 const RADIUS = { apple: .85, pear: .8, lemon: .7, melon: 1.3 };
196 const panSink = () => Math.round(MarketScale.sink(G.needle) * 12); // whole pixels
197 const panZ = () => PAN.rest - panSink() / (S * COS);
198 // where the k-th fruit in the pan sits: the middle, then a ring, then one on top
199 function panSpot(k, kind) {
200 const z = panZ() + .25;
201 if (k === 0) return { x: PAN.x, y: PAN.y, z: z + RADIUS[kind] };
202 if (k < 7) {
203 const a = (k - 1) * Math.PI / 3 + .4, [dx, dy] = uv(Math.cos(a) * 2.1, Math.sin(a) * 2.1);
204 return { x: PAN.x + dx, y: PAN.y + dy, z: z + RADIUS[kind] };
205 }
206 return { x: PAN.x, y: PAN.y, z: z + RADIUS[kind] + 1.3 };
207 }
208 // where each fruit is on screen: the crate slot, or its place in the pan
209 function spotOf(i) {
210 const kind = MarketScale.CRATE[i], k = G.pan.indexOf(i);
211 if (k >= 0) return panSpot(k, kind);
212 const slot = slotAt(i);
213 return { x: slot.x, y: slot.y, z: 1.12 + RADIUS[kind] };
214 }
215 const screenOf = i => { const p = spotOf(i); return project(p.x, p.y, p.z); };
216 const panScreen = () => project(PAN.x, PAN.y, panZ() + 1);
217 const bellScreen = () => project(BELL.x, BELL.y, 2);
218
219 /* ---------- drawing ---------- */
220 function drawFruit(kind, x, y, z, shadow = true) {
221 const r = RADIUS[kind], color = KIND_COLOR[kind];
222 if (kind === 'apple') {
223 sphere(x, y, z, r, color, 'solid');
224 capsule([x, y, z + r * .8], [x, y, z + r * 1.25], .08, .08, () => STEM, 'solid');
225 } else if (kind === 'pear') {
226 sphere(x, y, z - .1, r, color, 'solid');
227 sphere(x, y, z + r * .85, r * .6, color, 'solid');
228 capsule([x, y, z + r * 1.3], [x, y, z + r * 1.65], .07, .07, () => STEM, 'solid');
229 } else if (kind === 'lemon') {
230 capsule([x - .22, y + .22, z], [x + .22, y - .22, z], r, r, () => color, 'solid');
231 sphere(x + .6, y - .6, z, .22, color, 'solid');
232 } else {
233 sphere(x, y, z, r, color, 'rough');
234 sphere(x, y, z + r * .55, r * .5, [110, 180, 100], 'rough');
235 }
236 if (shadow) castShadow(x, y, z, r * .8, 1, .2);
237 }
238 function drawPan() {
239 const z = panZ(), top = PAN.rest + 4.2;
240 // chains from the arm to the rim
241 for (const a of [.6, 2.7, 4.8]) {
242 const [dx, dy] = uv(Math.cos(a) * PAN.radius, Math.sin(a) * PAN.radius * .9);
243 capsule([PAN.x, PAN.y, top], [PAN.x + dx, PAN.y + dy, z + .1], .045, .045, () => CHAIN, 'solid');
244 }
245 // the dish: rows of brass, with a brighter rim
246 for (let t = -PAN.radius; t <= PAN.radius; t += .4) {
247 const half = Math.sqrt(Math.max(0, PAN.radius * PAN.radius - t * t)), [ax, ay] = uv(-half, t), [bx, by] = uv(half, t);
248 capsule([PAN.x + ax, PAN.y + ay, z - .15], [PAN.x + bx, PAN.y + by, z - .15], .24, .24, () => BRASS, 'solid');
249 }
250 for (let k = 0; k < 28; k++) {
251 const a = k / 28 * Math.PI * 2, [dx, dy] = uv(Math.cos(a) * PAN.radius, Math.sin(a) * PAN.radius);
252 sphere(PAN.x + dx, PAN.y + dy, z + .05, .2, [244, 204, 100], 'solid');
253 }
254 castShadow(PAN.x, PAN.y, z, PAN.radius * .9, 1, .3);
255 }
256 // the fringe sways one pixel either way at the wind's frame rate
257 function drawFringe(t) {
258 const { lo, hi } = STALL;
259 let n = 0;
260 for (const edge of [[hi, null], [null, hi]]) for (let s = lo; s <= hi; s += .7, n++) {
261 const sway = STILL ? 0 : Math.round(Math.sin(t * 2.2 + n * .55) * 1.1);
262 const [dx, dy] = uv(sway * .1, 0);
263 const x = (edge[0] == null ? s : edge[0]) + dx, y = (edge[1] == null ? s : edge[1]) + dy;
264 sphere(x, y, roofZ(x, y) - .9, .3, n % 2 ? AWN_CREAM : AWN_RED, 'solid');
265 sphere(x + dx * .5, y + dy * .5, roofZ(x, y) - 1.3, .22, n % 2 ? AWN_CREAM : AWN_RED, 'solid');
266 }
267 }
268 function drawBell() {
269 const press = ringT < .25 ? .2 : 0;
270 sphere(BELL.x, BELL.y, 1.4 + .2 - press, .8, BRASS, 'solid');
271 capsule([BELL.x - .8, BELL.y + .8, 1.4], [BELL.x + .8, BELL.y - .8, 1.4], .13, .13, () => [244, 204, 100], 'solid');
272 sphere(BELL.x, BELL.y, 1.4 + 1.05 - press, .2, [244, 204, 100], 'solid');
273 castShadow(BELL.x, BELL.y, 1.8, .8, 1, .2);
274 }
275 /* ---------- 2D overlays: a 3x5 chalk font, the slate and the dial ---------- */
276 const GLYPHS = {
277 0: '111101101101111', 1: '010110010010111', 2: '111001111100111', 3: '111001111001111', 4: '101101111001001',
278 5: '111100111001111', 6: '111100111101111', 7: '111001001001001', 8: '111101111101111', 9: '111101111001111',
279 '+': '000010111010000', '?': '111001010000010',
280 };
281 function px(x, y, color) {
282 if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = color;
283 }
284 function rect(x0, y0, x1, y1, color) {
285 for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) px(x, y, color);
286 }
287 function text(str, left, top, scale, color) {
288 let x = left;
289 for (const ch of str) {
290 const g = GLYPHS[ch] || '';
291 for (let k = 0; k < g.length; k++) if (g[k] === '1') rect(x + (k % 3) * scale, top + Math.floor(k / 3) * scale, x + (k % 3 + 1) * scale, top + (Math.floor(k / 3) + 1) * scale, color);
292 x += 4 * scale;
293 }
294 }
295 const textWidth = (str, scale) => str.length * 4 * scale - scale;
296 function line(x0, y0, x1, y1, color, thick) {
297 const n = Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0), 1);
298 for (let k = 0; k <= n; k++) {
299 const x = Math.round(x0 + (x1 - x0) * k / n), y = Math.round(y0 + (y1 - y0) * k / n);
300 for (let a = 0; a < thick; a++) for (let b = 0; b < thick; b++) px(x + a, y + b, color);
301 }
302 }
303 const SLATE_BOX = { x: 84, y: 88, w: 78, h: 44 };
304 function drawSlate() {
305 const { x, y, w, h } = SLATE_BOX;
306 for (const lx of [x + 6, x + w - 8]) rect(lx, y + h + 3, lx + 3, y + h + 17, FRAME_DARK); // the board's legs
307 rect(x - 3, y - 3, x + w + 3, y + h + 3, FRAME_DARK);
308 rect(x - 2, y - 2, x + w + 2, y + h + 1, FRAME);
309 for (let yy = y; yy < y + h; yy++) for (let xx = x; xx < x + w; xx++) px(xx, yy, hash(xx, yy) > .93 ? SLATE_LIGHT : SLATE);
310 const body = G.phase === 'ready' || G.phase === 'over' ? '?' : String(G.target), size = body.length > 3 ? 3 : 4;
311 text(body, x + Math.round((w - textWidth(body, size)) / 2), y + 5, size, CHALK);
312 if (G.phase === 'sold') {
313 const mark = '+' + G.sale.points;
314 text(mark, x + Math.round((w - textWidth(mark, 2)) / 2), y + 29, 2, G.sale.points === 3 ? rgb(255, 214, 10) : CHALK);
315 } else if (G.phase === 'serve') {
316 // the customer's patience: a chalk line that shortens as the clock runs down
317 const len = Math.round((w - 12) * G.clock / MarketScale.CLOCK);
318 rect(x + 6, y + 33, x + 6 + len, y + 35, G.clock < 4 ? rgb(236, 120, 96) : CHALK);
319 }
320 }
321 function drawDial() {
322 const hub = project(PAN.x, PAN.y, PAN.rest + 4.2), cx = Math.round(hub.sx), cy = Math.round(hub.sy) - 12, R = 15;
323 for (let yy = -R - 2; yy <= R + 2; yy++) for (let xx = -R - 2; xx <= R + 2; xx++) {
324 const d = Math.hypot(xx + .5, yy + .5);
325 if (d <= R) px(cx + xx, cy + yy, FACE);
326 else if (d <= R + 1.5) px(cx + xx, cy + yy, BRASS_PX);
327 else if (d <= R + 2.5) px(cx + xx, cy + yy, BRASS_DARK);
328 }
329 const pivotY = cy + 5;
330 for (let k = 0; k <= 8; k++) {
331 const a = (k / 8 * 2 - 1) * Math.PI / 3, s = Math.sin(a), c = Math.cos(a);
332 line(Math.round(cx + s * 10), Math.round(pivotY - c * 10), Math.round(cx + s * 13), Math.round(pivotY - c * 13), TICK, 1);
333 }
334 const a = MarketScale.needleAngle(G.needle);
335 line(cx, pivotY, Math.round(cx + Math.sin(a) * 11), Math.round(pivotY - Math.cos(a) * 11), NEEDLE, 2);
336 rect(cx - 1, pivotY - 1, cx + 2, pivotY + 2, TICK);
337 }
338 function drawMarker(i) {
339 const p = spotOf(i), top = project(p.x, p.y, p.z + RADIUS[MarketScale.CRATE[i]] + 1);
340 drawArrow(top.sx, top.sy, time);
341 }
342 function draw() {
343 pix.set(bakedPix);
344 zb.set(bakedZ);
345 const windT = STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS;
346 drawPan();
347 drawBell();
348 drawFringe(windT);
349 MarketScale.CRATE.forEach((kind, i) => {
350 if (drag && drag.i === i) return;
351 const p = spotOf(i);
352 drawFruit(kind, p.x, p.y, p.z);
353 });
354 applyShadows(bakedZ);
355 shadeEdges();
356 drawSlate();
outdated

z = lift = 2.5 is below the dish (PAN.rest = 3), so the fruit is hidden while it's held over the pan, which is exactly where the player drops it. Also, unprojecting at sy + lift·COS·S and then drawing at z = lift lands the fruit back at sy, centred under the finger rather than lifted above it. Draw it above the pan's top and offset it up a fixed number of screen pixels.

357 drawDial();
358 if (drag) {
359 // drawn last, after the slate and dial: the fruit is held high, above the pan and its load, and shown a fixed 26 px above the pointer so a finger never covers it
360 const kind = MarketScale.CRATE[drag.i], lift = 9, g = unproject(drag.sx, drag.sy - 26 + lift * COS * S);
361 drawFruit(kind, g.x, g.y, lift, false);
362 }
363 if (G.kb && G.phase === 'serve') drawMarker(G.sel);
364 if (G.phase === 'ready' || G.phase === 'over') { const b = bellScreen(); drawArrow(b.sx, b.sy - 10, time); }
365 ctx.putImageData(image, 0, 0);
366 }
367
368 /* ---------- input ---------- */
369 const at = e => {
370 const box = canvas.getBoundingClientRect();
371 return { sx: (e.clientX - box.left) * W / box.width, sy: (e.clientY - box.top) * H / box.height };
372 };
373 const near = (p, q, r) => Math.hypot(p.sx - q.sx, p.sy - q.sy) <= r;
374 function fruitAt(p) {
375 let best = -1, bestD = 1e9;
376 MarketScale.CRATE.forEach((kind, i) => {
377 const s = screenOf(i), d = Math.hypot(p.sx - s.sx, p.sy - s.sy);
378 if (d <= RADIUS[kind] * S + 5 && d < bestD) { best = i; bestD = d; }
379 });
380 return best;
381 }
382 canvas.addEventListener('pointerdown', e => {
383 canvas.focus({ preventScroll: true });
384 const p = at(e);
385 if (G.phase !== 'serve' || near(p, bellScreen(), 16)) { press(); return; }
386 const i = fruitAt(p);
387 if (i < 0) return;
388 ensureAudio();
389 canvas.setPointerCapture(e.pointerId);
390 G.sel = i;
391 if (G.pan.includes(i)) { move(i); return; } // a tap on fruit in the pan takes it back out
392 drag = { i, sx: p.sx, sy: p.sy, from: p, moved: false };
393 });
394 canvas.addEventListener('pointermove', e => {
395 if (!drag) return;
396 const p = at(e);
397 drag.sx = p.sx; drag.sy = p.sy;
398 if (!near(p, drag.from, 5)) drag.moved = true;
399 });
400 function drop() {
401 if (!drag) return;
402 const d = drag, p = { sx: d.sx, sy: d.sy };
403 drag = null;
404 // a tap, or a release over the pan, puts the fruit in; anywhere else it goes back to the crate
405 if (!d.moved || near(p, panScreen(), 42)) move(d.i);
406 }
407 canvas.addEventListener('pointerup', drop);
408 canvas.addEventListener('pointercancel', () => { drag = null; });
409 addEventListener('blur', () => { drag = null; });
410 canvas.addEventListener('keydown', e => {
411 const by = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 4, ArrowUp: -4 }[e.key];
412 if (by) { e.preventDefault(); if (G.phase === 'serve') MarketScale.select(G, by); return; }
413 if (e.key === ' ') { e.preventDefault(); if (!e.repeat) press(); return; }
414 if (e.key === 'Enter') { e.preventDefault(); if (!e.repeat && G.phase === 'serve') { G.kb = true; move(G.sel); } else if (!e.repeat) press(); }
415 });
416
417 /* ---------- sound ---------- */
418 let audio = null, muted = false;
419 function ensureAudio() {
420 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
421 const AC = window.AudioContext || window.webkitAudioContext;
422 if (AC) audio = new AC();
423 }
424 function tone(type, from, to, len, vol) {
425 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
426 osc.type = type;
427 osc.frequency.setValueAtTime(from, now);
428 osc.frequency.exponentialRampToValueAtTime(to, now + len);
429 gain.gain.setValueAtTime(vol, now);
430 gain.gain.exponentialRampToValueAtTime(.0005, now + len);
431 osc.connect(gain).connect(audio.destination);
432 osc.start(now); osc.stop(now + len + .01);
433 }
434 function sound(kind) {
435 if (!audio || muted) return;
436 if (kind === 'bell') { tone('sine', 1320, 1300, .5, .18); tone('sine', 1980, 1960, .35, .06); }
437 else if (kind === 'thud') tone('triangle', 220, 120, .1, .16);
438 else if (kind === 'coin') { tone('square', 880, 880, .08, .05); setTimeout(() => { if (audio) tone('square', 1320, 1320, .16, .05); }, 80); }
439 else if (kind === 'miss') tone('triangle', 260, 130, .3, .14);
440 else if (kind === 'tick') tone('square', 600, 600, .05, .04);
441 }
442 const muteButton = document.getElementById('mute');
443 muteButton.addEventListener('click', () => {
444 muted = !muted;
445 muteButton.textContent = muted ? 'sound off' : 'sound on';
446 muteButton.setAttribute('aria-pressed', String(muted));
447 });
448
449 /* ---------- boot ---------- */
450 addEventListener('resize', fit);
451 fit();
452 bake();
453 setStatus(statusFor());
454 renderHud();
455 let last = performance.now();
456 function frame(now) {
457 update(Math.min(.04, (now - last) / 1000));
458 last = now;
459 draw();
460 requestAnimationFrame(frame);
461 }
462 requestAnimationFrame(frame);
463 </script>
464 </body>
465 </html>
market-scale/scale.js added +120
@@ -0,0 +1,120 @@
1 'use strict';
2 // Market Scale rules as plain data in, plain data out: fruit weights, the pan's total, the needle settling,
3 // scoring a sale against the target and the customer's clock. The page draws from this state and the tests drive it.
4 (function (root) {
5 const FRUIT = { apple: 150, pear: 200, lemon: 100, melon: 500 }; // grams
6 // the crate, one fruit per slot; a fruit is named by its slot index
7 const CRATE = ['apple', 'pear', 'lemon', 'melon', 'apple', 'pear', 'lemon', 'apple'];
8 const TARGETS = [250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1100];
9 const CUSTOMERS = 5, CLOCK = 15, SOLD_PAUSE = 1.2;
10 const POINTS = { exact: 3, near: 1, miss: 0 }, NEAR = 50;
11 const MAX_WEIGHT = 1600, SWING = Math.PI / 3; // the dial reads 0 to MAX_WEIGHT across +-60 degrees
12 const SPRING = 120, DAMPING = 14; // underdamped: the needle overshoots a little, then settles
13 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
14
15 const weightOf = i => FRUIT[CRATE[i]];
16 const weigh = pan => pan.reduce((sum, i) => sum + weightOf(i), 0);
17 // can this many grams be made from some fruit in the crate?
18 function reachable(target, crate = CRATE) {
19 let sums = new Set([0]);
20 for (const kind of crate) sums = new Set([...sums, ...[...sums].map(v => v + FRUIT[kind])]);
21 return sums.has(target);
22 }
23 // a sale scores 3 on the nose, 1 within 50 g, and 0 otherwise or when the customer's clock has run out
24 function saleScore(total, target, clockLeft = CLOCK) {
25 if (clockLeft <= 0) return POINTS.miss;
26 const off = Math.abs(total - target);
27 return off === 0 ? POINTS.exact : off <= NEAR ? POINTS.near : POINTS.miss;
28 }
29 // five distinct targets for a round; rng returns [0, 1)
30 function pickTargets(rng = Math.random) {
31 const pool = TARGETS.filter(t => reachable(t)), out = [];
32 while (out.length < CUSTOMERS) out.push(...pool.splice(Math.floor(rng() * pool.length) % pool.length, 1));
33 return out;
34 }
35 const needleAngle = grams => (clamp(grams / MAX_WEIGHT, 0, 1) * 2 - 1) * SWING;
36 const sink = grams => clamp(grams / MAX_WEIGHT, 0, 1);
37
38 function newState(best = 0, rng = Math.random) {
39 const targets = pickTargets(rng);
40 return {
41 phase: 'ready', targets, customer: 0, target: targets[0], clock: CLOCK, pan: [], total: 0,
42 needle: 0, needleV: 0, sel: 0, kb: false, score: 0, best, record: false, pause: 0, sale: null,
43 };
44 }
45 // 'ready' and 'over' wait for a tap; 'serve' is a customer at the stall; 'sold' shows the result
46 function start(s) {
47 if (s.phase !== 'ready') return false;
48 s.phase = 'serve';
49 return true;
50 }
51 function restart(s, rng = Math.random) {
52 return s.phase === 'over' ? newState(s.best, rng) : s;
53 }
54 const valid = (s, i) => Number.isInteger(i) && i >= 0 && i < CRATE.length && s.phase === 'serve';
55 function add(s, i) {
56 if (!valid(s, i) || s.pan.includes(i)) return false;
57 s.pan.push(i);
58 s.total = weigh(s.pan);
59 return true;
60 }
61 function remove(s, i) {
62 if (!valid(s, i) || !s.pan.includes(i)) return false;
63 s.pan.splice(s.pan.indexOf(i), 1);
64 s.total = weigh(s.pan);
65 return true;
66 }
67 const toggle = (s, i) => (s.pan.includes(i) ? remove(s, i) : add(s, i));
68 function select(s, by) {
69 s.sel = (s.sel + by + CRATE.length * 4) % CRATE.length;
70 s.kb = true;
71 return s.sel;
72 }
73 function sell(s) {
74 if (s.phase !== 'serve') return null;
75 const points = saleScore(s.total, s.target, s.clock);
76 s.sale = { points, total: s.total, target: s.target, late: s.clock <= 0 };
77 s.score += points;
78 s.phase = 'sold';
79 s.pause = SOLD_PAUSE;
80 return s.sale;
81 }
82 function next(s) {
83 s.customer++;
84 if (s.customer >= CUSTOMERS) {
85 s.phase = 'over';
86 s.record = s.score > s.best;
87 if (s.record) s.best = s.score;
88 return;
89 }
90 s.target = s.targets[s.customer];
91 s.clock = CLOCK;
92 s.pan = [];
93 s.total = 0;
94 s.sale = null;
95 s.phase = 'serve';
96 }
97 function step(s, dt) {
98 const diff = s.total - s.needle;
99 if (Math.abs(diff) < 1 && Math.abs(s.needleV) < 5) { s.needle = s.total; s.needleV = 0; }
100 else {
101 s.needleV += (diff * SPRING - s.needleV * DAMPING) * dt;
102 s.needle += s.needleV * dt;
103 }
104 if (s.phase === 'serve') {
105 s.clock = Math.max(0, s.clock - dt);
106 if (s.clock <= 0) sell(s);
107 } else if (s.phase === 'sold') {
108 s.pause -= dt;
109 if (s.pause <= 0) next(s);
110 }
111 return s;
112 }
113 const api = {
114 FRUIT, CRATE, TARGETS, CUSTOMERS, CLOCK, SOLD_PAUSE, POINTS, NEAR, MAX_WEIGHT,
115 weightOf, weigh, reachable, saleScore, pickTargets, needleAngle, sink,
116 newState, start, restart, add, remove, toggle, select, sell, step,
117 };
118 if (typeof module !== 'undefined' && module.exports) module.exports = api;
119 else root.MarketScale = api;
120 })(typeof window !== 'undefined' ? window : globalThis);
market-scale/scale.test.mjs added +138
@@ -0,0 +1,138 @@
1 import { test, expect } from 'bun:test';
2 import { createRequire } from 'node:module';
3
4 const M = createRequire(import.meta.url)('./scale.js');
5 const run = (s, seconds) => { for (let i = 0; i < Math.round(seconds * 60); i++) M.step(s, 1 / 60); return s; };
6 const seeded = () => { let a = 7; return () => (a = (a * 1103515245 + 12345) % 2147483648) / 2147483648; };
7 const serving = () => { const s = M.newState(0, seeded()); M.start(s); return s; };
8 // put fruit in the pan by slot until it weighs exactly `grams`, or nothing if it cannot
9 function fill(s, grams) {
10 const slots = M.CRATE.map((_, i) => i);
11 for (let mask = 0; mask < 1 << slots.length; mask++) {
12 const pick = slots.filter(i => mask >> i & 1);
13 if (M.weigh(pick) === grams) { pick.forEach(i => M.add(s, i)); return true; }
14 }
15 return false;
16 }
17
18 test('fruit weighs what it should and the pan adds it up', () => {
19 expect(M.FRUIT).toEqual({ apple: 150, pear: 200, lemon: 100, melon: 500 });
20 expect(M.weigh([])).toBe(0);
21 expect(M.weigh([0, 1, 3])).toBe(150 + 200 + 500);
22 });
23
24 test('an exact sale scores 3, 40 g off scores 1, and a sale over the clock scores 0', () => {
25 expect(M.saleScore(450, 450, 10)).toBe(3);
26 expect(M.saleScore(490, 450, 10)).toBe(1);
27 expect(M.saleScore(410, 450, 10)).toBe(1);
28 expect(M.saleScore(500, 450, 10)).toBe(1);
29 expect(M.saleScore(550, 450, 10)).toBe(0);
30 expect(M.saleScore(450, 450, 0)).toBe(0);
31 });
32
33 test('selling through the state scores the pan against the customer', () => {
34 const s = serving();
35 expect(fill(s, s.target)).toBe(true);
36 expect(M.sell(s).points).toBe(3);
37 expect(s.score).toBe(3);
38 expect(s.phase).toBe('sold');
39 expect(M.sell(s)).toBe(null); // one sale per customer
40 });
41
42 test('the clock running out sells whatever is in the pan for 0', () => {
43 const s = serving();
44 fill(s, s.target);
45 run(s, M.CLOCK + .1);
46 expect(s.sale.late).toBe(true);
47 expect(s.sale.points).toBe(0);
48 expect(s.score).toBe(0);
49 });
50
51 test('every target can be reached exactly from the crate, and every round asks only for those', () => {
52 for (const t of M.TARGETS) {
53 expect(M.reachable(t)).toBe(true);
54 expect(fill(serving(), t)).toBe(true);
55 }
56 expect(M.reachable(25)).toBe(false);
57 expect(M.reachable(1600)).toBe(false);
58 for (let seed = 1; seed < 20; seed++) {
59 let a = seed;
60 const targets = M.pickTargets(() => (a = (a * 48271) % 2147483647) / 2147483647);
61 expect(targets.length).toBe(M.CUSTOMERS);
62 expect(new Set(targets).size).toBe(M.CUSTOMERS);
63 for (const t of targets) expect(M.reachable(t)).toBe(true);
64 }
65 });
66
67 test('fruit goes into the pan once and comes back out, only while serving', () => {
68 const s = M.newState(0, seeded());
69 expect(M.add(s, 0)).toBe(false); // the stall is not open yet
70 M.start(s);
71 expect(M.add(s, 0)).toBe(true);
72 expect(M.add(s, 0)).toBe(false);
73 expect(M.add(s, 99)).toBe(false);
74 expect(M.add(s, 1.5)).toBe(false);
75 expect(s.total).toBe(150);
76 expect(M.toggle(s, 3)).toBe(true);
77 expect(s.total).toBe(650);
78 expect(M.remove(s, 3)).toBe(true);
79 expect(M.remove(s, 3)).toBe(false);
80 expect(s.total).toBe(150);
81 });
82
83 test('the needle swings past, then settles on the total', () => {
84 const s = serving();
85 M.add(s, 3);
86 let peak = 0;
87 for (let i = 0; i < 120; i++) { M.step(s, 1 / 60); peak = Math.max(peak, s.needle); }
88 expect(peak).toBeGreaterThan(500);
89 run(s, 2);
90 expect(s.needle).toBe(500);
91 expect(s.needleV).toBe(0);
92 M.remove(s, 3);
93 run(s, 2);
94 expect(s.needle).toBe(0);
95 expect(M.needleAngle(0)).toBeCloseTo(-Math.PI / 3);
96 expect(M.needleAngle(M.MAX_WEIGHT)).toBeCloseTo(Math.PI / 3);
97 expect(M.sink(800)).toBe(.5);
98 });
99
100 test('five customers make a round: the pan empties, the clock resets, the best is kept', () => {
101 const s = serving();
102 const seen = [];
103 for (let c = 0; c < M.CUSTOMERS; c++) {
104 seen.push(s.target);
105 expect(s.pan).toEqual([]);
106 expect(s.clock).toBeGreaterThan(M.CLOCK - .5);
107 expect(s.customer).toBe(c);
108 fill(s, s.target);
109 M.sell(s);
110 run(s, M.SOLD_PAUSE + .1);
111 }
112 expect(seen).toEqual(s.targets);
113 expect(s.phase).toBe('over');
114 expect(s.score).toBe(15);
115 expect(s.best).toBe(15);
116 expect(s.record).toBe(true);
117 const again = M.restart(s, seeded());
118 expect(again.phase).toBe('ready');
119 expect(again.best).toBe(15);
120 expect(again.score).toBe(0);
121 });
122
123 test('the clock only runs while a customer is at the stall', () => {
124 const s = M.newState(0, seeded());
125 run(s, 5);
126 expect(s.clock).toBe(M.CLOCK);
127 M.start(s);
128 run(s, 3);
129 expect(s.clock).toBeCloseTo(M.CLOCK - 3, 1);
130 });
131
132 test('arrows wrap around the crate', () => {
133 const s = M.newState();
134 expect(M.select(s, -1)).toBe(M.CRATE.length - 1);
135 expect(M.select(s, 1)).toBe(0);
136 expect(M.select(s, 4)).toBe(4);
137 expect(s.kb).toBe(true);
138 });
serve.test.mjs +7
@@ -134,3 +134,10 @@ test('lighthouse is served without a track', async () => {
134134 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
135135 expect((await fetch(base + '/lighthouse/beam.js')).status).toBe(200);
136136 });
137
138 test('Market Scale and its rules script are served without a track', async () => {
139 const page = await fetch(base + '/market-scale/');
140 expect(page.status).toBe(200);
141 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
142 expect((await fetch(base + '/market-scale/scale.js')).status).toBe(200);
143 });
shell.js +1
@@ -19,6 +19,7 @@ window.PixelPlays = (() => {
1919 { id: 'row-home', title: 'Row Home', blurb: 'Race a rowing boat across the river against a bot: stroke in rhythm with the glide, too early catches a crab', music: false, forged: true },
2020 { id: 'orchard', title: 'Orchard', blurb: 'Catch falling apples in a basket: ripe 1, golden 3, a wasp-bitten brown one costs a life', music: false, forged: true },
2121 { id: 'lighthouse', title: 'Lighthouse', blurb: 'Sweep the lighthouse beam to turn boats away from the rocks: hold one in the light for a second, three wrecks end the night', music: false, forged: true },
22 { id: 'market-scale', title: 'Market Scale', blurb: 'Weigh fruit onto a hanging pan scale to match each order: exact scores 3, within 50 g scores 1', music: false, forged: true },
2223 ];
2324 const MUSIC_VOLUME = .4;
2425 const CREDITS = [

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs