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

Migrated from github.com/amirmushichge/pixel-plays

Add Tea Party: the playable page and its place in the catalogue, on the rules in `tea-party/table.js` #302

Merged opened this

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

Merged

vesper/pixel-plays:vesper/278-add-tea-party-the-playable-page-and-its → main 2 commits fork

  • Merged. vesper/278-add-tea-party-the-playable-page-and-its was merged into main as d481920.

Review

Sign in to review this change.
11 files changed +714 −2
README.md +2 −1
@@ -63,6 +63,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
6363 | [Jam Jars](jam-jars/) | A pantry shelf of 3 to 5 glass jars with their fruit layers (plum, fig, quince) visible through the glass: tap a jar, or press its number key, to pick it up (it lifts and is outlined), then tap another to pour the top run of one fruit into it, as many layers as fit, onto the same fruit or into free space; a rejected pour says why and changes nothing; undo (button or U) reverses the last pour and costs a pour, R starts the shelf again; every jar must end empty or full of one fruit, the HUD showing the shelf, pours against par and points; each fruit carries its own pip pattern (plum dots, fig stripes, quince checks) as well as its colour, so it can be solved without telling colours apart; four shelves, scoring 100 and 50 more at or under par pours (forged by the crew on the engine and shell above, not by the original creators; rules in `jam-jars/shelf.js`) | Tap a jar, or 1-5, arrows, Space, U and R |
6464 | [Library Shelf](library-shelf/) | An oak library shelf with two runners and books of different widths, the returned book (red, with a ribbon bookmark) waiting at one end and a dashed gap marking where it must reach: drag a book along its runner, or press Tab to choose one and use the arrow keys, to slide it; each book slides only the way the arrow on its spine points and cannot pass another, however far a slide goes it counts as one, undo (button or U) takes the last slide back at the cost of a slide, R begins the level again, and all 3 levels cleared wins, with a bonus for each within par slides (forged by the crew on the engine and shell above, not by the original creators; rules in `library-shelf/shelf.js`) | Drag; Tab and arrows |
6565 | [Skipping Rope](skipping-rope/) | A school yard of tarmac with a grass verge, a hopscotch grid, a fence and a tree, where two friends turn a long rope and you skip in the line between them (you wear a yellow cap; the others wear none): tap the canvas or press Space to jump, and be in the air when the rope touches the ground, which a chalk line on the ground flashes; the rope quickens and another skipper joins every 3 clears, each joined skipper adds 5 to every clear, so win by making 12 clears and lose by landing on the rope (forged by the crew on the engine and shell above, not by the original creators; rules in `skipping-rope/rope.js`) | Tap the canvas; space |
66 | [Tea Party](tea-party/) | A garden table with a gingham cloth, a teapot (round), a coffee pot (tall), a milk jug, a sugar bowl and a cake stand, and two to five guests who differ by hat (top hat, boater, sun hat, bobble hat, party hat) as well as colour: each guest's order (tea or coffee, milk or none, 0 to 3 sugars, a cake) shows in a speech bubble in turn, then you serve from memory by tapping a guest, then the pot, milk, sugar (each tap adds one) and cake (each tap changes it), and the guest again to serve; each right part scores 10 and a perfect cup 20 more, the table grows from 2 to 5 guests over 4 rounds, and 3 wrong parts in a round lose (forged by the crew on the engine and shell above, not by the original creators; rules in `tea-party/table.js`) | Tap a guest, then the pots; Tab, arrows and Enter |
6667 | [Conkers](conkers/) | A school playground under a horse-chestnut tree, your conker (double knot and a chalk cross) and the rival's hanging side by side on their strings, and a power meter that sweeps up and down: tap the canvas, or press Space or Enter, to swing when the meter is where you want it; the gold sweet spot (marked by a notch) does 4 damage, anywhere else up to the hatched end does 1, and the hatched end tangles the strings, does nothing and passes the turn; you and the rival swing in turn (their reading comes from the seed, shown as a red pointer), crack all 3 rivals' conkers (6, 8 and 10 hit points) before yours (12) cracks, scoring 100 for each and 10 for each hit point left; cracks show on the conkers (forged by the crew on the engine and shell above, not by the original creators; rules in `conkers/match.js`) | Tap, or Space |
6768 | [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 |
6869 | [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 |
@@ -95,7 +96,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
9596 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.
9697
9798 ## Add a game
98 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall, Lock Keeper, Ferryman, Tower Duel, Sandcastle Tide, Hedge Maze, Allotment, Lily Pond, Market Barrow, Curling Rink, Shunting Yard, Ferris Wheel, Bird Watch, Bunting, Patchwork Quilt, Mill Race, Rain Barrel, Rock Pool, Stained Glass, Conkers, Jam Jars, Library Shelf and Skipping Rope 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`.
99 Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules })`, set `window.PP_SCENE`, load `../engine.js`, then add the game to `GAMES` in `shell.js` with a one-line `blurb`; the home page lists every `GAMES` entry as a card with its `kind`, `input` and `accent`, searchable and filterable by kind (a static fallback list for no-JS is kept in sync by `serve.test.mjs`, so add the matching `<li>` to `index.html` too, with the same `data-kind`, `data-input`, `--accent` and tags line). Then run `bun scripts/og.mjs` to make its share card and tags. The page needs a `#mute` button. Put its background track at `<id>/<id>.mp3`, or set `music: false` on its `GAMES` entry when it has none (Stone Skip, Kite Hill, Paper Route, Harbour Crane, Pizza Toss, Sled Run, Pottery Wheel, Row Home, Orchard, Lighthouse, Market Scale, Window Washer, Domino Run, Campfire, Beekeeper, Bread Oven, Ice Fishing, Tightrope, Tram Line, Archery, Bell Tower, Espresso Bar, Goalkeeper, Wood Split, Signal Box, Soapbox Derby, Sheepdog, Firefly Jar, Hot Air Balloon, Cloakroom, Go-Kart Fete, Empire Age, Egg Basket, Dinghy Race, Coconut Shy, Bowls Green, Seed Packets, Hoopla Stall, Lock Keeper, Ferryman, Tower Duel, Sandcastle Tide, Hedge Maze, Allotment, Lily Pond, Market Barrow, Curling Rink, Shunting Yard, Ferris Wheel, Bird Watch, Bunting, Patchwork Quilt, Mill Race, Rain Barrel, Rock Pool, Stained Glass, Conkers, Jam Jars, Library Shelf, Skipping Rope and Tea Party 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`.
99100
100101 - `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.
101102 - `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.
index.html +1
@@ -130,6 +130,7 @@ footer a::after { content: none; }
130130 <li data-kind="Puzzle" data-input="Drag" style="--accent:#6b4a2e"><a href="library-shelf/">Library Shelf</a><span>Slide the books along their runners to make room for the returned one</span><span>Game forged by the crew</span><span class="tags">Puzzle · Drag</span></li>
131131 <li data-kind="Sport" data-input="Tap" style="--accent:#8a4b22"><a href="conkers/">Conkers</a><span>Time your swing to crack every rival conker in the playground</span><span>Game forged by the crew</span><span class="tags">Sport · Tap</span></li>
132132 <li data-kind="Timing" data-input="Tap" style="--accent:#d0573c"><a href="skipping-rope/">Skipping Rope</a><span>Jump the turning rope as it quickens and friends join the line</span><span>Game forged by the crew</span><span class="tags">Timing · Tap</span></li>
133 <li data-kind="Memory" data-input="Tap" style="--accent:#c98aa0"><a href="tea-party/">Tea Party</a><span>Remember every guest's order and pour it right as the table grows</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li>
133134 </ul>
134135 <footer>Concept by <a href="https://x.com/awwbhi2">abhi</a>. Game by <a href="https://x.com/AmirMushich">AmirMushich</a>. Visual reference for the style: shawn.'s <a href="https://x.com/zzzzshawn/status/2111546123546661289">Small plays</a>; no assets or subjects were copied.<br><a href="stats/">Most played</a></footer>
135136 </main>
og/home.png
Binary file not shown.
og/tea-party.png added
Binary file not shown.
rounds.mjs +14
@@ -447,6 +447,20 @@ export const ROUNDS = {
447447 if (g.read('!M.airborne(P) && P.nextCross - P.t <= .25')) g.press(' ', .04);
448448 else g.run(.04);
449449 } },
450 // serve each guest the order the rules dealt: pick the guest, pour what differs from the order one tap at a time, then serve
451 'tea-party': { over: /play again/, outcome: /You win: score \d+, 14 perfect cups/, beat: g => {
452 if (g.read('P.status') !== 'playing') { g.run(.3); return; }
453 if (g.read('P.phase') === 'order') { g.run(.5); return; }
454 const guest = g.read('Array.from({ length: P.guests }, (_, i) => i).find(i => !P.served.includes(i))');
455 const tap = t => g.tap(...g.read(`pointOf(${JSON.stringify(t)})`));
456 if (g.read('G.sel') !== guest) { tap(guest); return; }
457 const want = g.read(`({ ...P.orders[${guest}] })`), cup = g.read('({ ...G.cup })');
458 if (cup.drink !== want.drink) tap(want.drink);
459 else if (cup.milk !== want.milk) tap('milk');
460 else if (cup.sugars !== want.sugars) tap('sugar');
461 else if (cup.cake !== want.cake) tap('cake');
462 else tap(guest);
463 } },
450464 'window-washer': { over: /play again/, outcome: /[1-9]\d* of 500/, beat: g => g.drag([60, 100], [300, 100], .6) },
451465 };
452466
serve.test.mjs +7
@@ -712,3 +712,10 @@ test('Skipping Rope and its rules script are served without a track', async () =
712712 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
713713 expect((await fetch(base + '/skipping-rope/rope.js')).status).toBe(200);
714714 });
715
716 test('Tea Party and its rules script are served without a track', async () => {
717 const page = await fetch(base + '/tea-party/');
718 expect(page.status).toBe(200);
719 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
720 expect((await fetch(base + '/tea-party/table.js')).status).toBe(200);
721 });
shell.js +1
@@ -70,6 +70,7 @@ window.PixelPlays = (() => {
7070 { id: 'library-shelf', title: 'Library Shelf', blurb: 'Slide the books along their runners to make room for the returned one', kind: 'Puzzle', input: 'Drag', accent: '#6b4a2e', music: false, forged: true },
7171 { id: 'conkers', title: 'Conkers', blurb: 'Time your swing to crack every rival conker in the playground', kind: 'Sport', input: 'Tap', accent: '#8a4b22', music: false, forged: true },
7272 { id: 'skipping-rope', title: 'Skipping Rope', blurb: 'Jump the turning rope as it quickens and friends join the line', kind: 'Timing', input: 'Tap', accent: '#d0573c', music: false, forged: true },
73 { id: 'tea-party', title: 'Tea Party', blurb: 'Remember every guest\'s order and pour it right as the table grows', kind: 'Memory', input: 'Tap', accent: '#c98aa0', music: false, forged: true },
7374 ];
7475 const MUSIC_VOLUME = .4;
7576 const CREDITS = [
tea-party/index.html added +570
@@ -0,0 +1,570 @@
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>Tea Party</title>
7 <!-- og:begin -->
8 <meta name="description" content="Remember every guest's order and pour it right as the table grows">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/tea-party/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Tea Party">
13 <meta property="og:description" content="Remember every guest's order and pour it right as the table grows">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/tea-party/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/tea-party.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="Tea Party: 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: #c98aa0; }
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 canvas:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
31 .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; pointer-events: none; }
32 #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; }
33 #bottom { bottom: max(20px, env(safe-area-inset-bottom)); }
34 .line { display: flex; flex-wrap: wrap; gap: 0 12px; }
35 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
36 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
37 .row span { color: var(--muted); }
38 #status { color: var(--muted); min-height: 2.7em; max-width: 60ch; }
39 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 13px 10px; margin: -13px -10px; min-height: 44px; min-width: 44px; cursor: pointer; }
40 button:hover, button:focus-visible { color: var(--ink); }
41 button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
42 noscript p { position: fixed; inset: 40% 16px auto; margin: 0; text-align: center; color: var(--muted); }
43 </style>
44 </head>
45 <body>
46 <div id="stage"><canvas id="c" tabindex="0" aria-label="Tea Party: a garden table with up to five guests, a teapot, a coffee pot, a milk jug, a sugar bowl and a cake stand. Each guest's order shows in a speech bubble in turn: drink, milk, sugars and cake. Then serve from memory: tap a guest, then the pot, milk, sugar and cake, and tap the guest again to serve. With a keyboard, Tab or the arrow keys move and Enter chooses. Three wrong parts in a round end the party."></canvas></div>
47 <noscript><p>Tea Party needs JavaScript to play.</p></noscript>
48 <div id="scores">
49 <div class="line">
50 <div class="row"><b id="round">1</b><span id="of">of 4 rounds</span></div>
51 <div class="row"><b id="guests">2</b><span>guests</span></div>
52 <div class="row"><b id="score">0</b><span>points</span></div>
53 </div>
54 <div class="line">
55 <div class="row"><b id="wrong">0</b><span id="ofwrong">wrong parts</span></div>
56 <div class="row"><b id="perfect">0</b><span>perfect</span></div>
57 <div class="row"><b id="best">0</b><span>best</span></div>
58 </div>
59 <div class="row"><span id="cup"></span></div>
60 </div>
61 <div class="hud" id="bottom">
62 <div id="status" role="status" aria-live="polite"></div>
63 <button id="mute" type="button" aria-pressed="false">sound on</button>
64 </div>
65 <script src="../shell.js"></script>
66 <script>
67 PixelPlays.mount({
68 id: 'tea-party',
69 rules: [
70 'Listen: each guest shows an order in turn, tea or coffee, milk or none, 0 to 3 sugars and a cake. Remember them all.',
71 'Serve: tap a guest, then the pot, milk, sugar (each tap adds one) and cake (each tap changes it); tap the guest again to serve. Keys: Tab or arrows, Enter.',
72 'Each right part scores 10 and a perfect cup 20 more. Three wrong parts in a round end the party.',
73 'Serve rounds of 2, 3, 4 and 5 guests to win.',
74 ],
75 });
76 </script>
77 <script>window.PP_SCENE = { originY: 10, shadowX: 1.3, shadowY: -.12 };</script>
78 <script src="../engine.js"></script>
79 <script src="table.js"></script>
80 <script>
81 'use strict';
82
83 const M = window.TeaParty;
84 const BEST_KEY = 'pixel-plays-tea-party-best';
85 const LINE = rgb(40, 36, 48), WHITE = rgb(255, 255, 255), PINK = rgb(201, 138, 160), GREEN = rgb(86, 160, 96), RED = rgb(208, 87, 60), GOLD = rgb(250, 206, 36);
86 const PAVING = [[150, 146, 150], [164, 160, 162], [178, 174, 172], [192, 188, 184]];
87 const CLOTH_A = [206, 140, 164], CLOTH_B = [246, 236, 232], VALANCE = [186, 112, 140];
88 const SKIN = [[222, 170, 132], [176, 124, 92], [236, 190, 150], [150, 100, 72], [200, 148, 112]];
89 const HAIR = [[74, 50, 34], [36, 30, 28], [196, 150, 70], [60, 40, 30], [150, 150, 156]];
90 // each guest differs by hat as well as colour: a top hat, a boater, a sun hat with a flower, a bobble hat and a party hat
91 const GUESTS = [
92 { name: 'in the top hat', shirt: [64, 118, 190], stripe: [240, 232, 210], legs: [60, 60, 70], hair: HAIR[1], skin: SKIN[1] },
93 { name: 'in the boater', shirt: [86, 160, 96], stripe: [240, 232, 210], legs: [52, 66, 96], hair: HAIR[2], skin: SKIN[2] },
94 { name: 'in the sun hat', shirt: [236, 196, 60], stripe: [250, 244, 226], legs: [70, 80, 100], hair: HAIR[3], skin: SKIN[3] },
95 { name: 'in the bobble hat', shirt: [150, 80, 168], stripe: [240, 232, 210], legs: [44, 50, 60], hair: HAIR[0], skin: SKIN[0] },
96 { name: 'in the party hat', shirt: [208, 87, 60], stripe: [240, 232, 210], legs: [52, 66, 96], hair: HAIR[4], skin: SKIN[4] },
97 ];
98 const SEATS = { 2: [225, 315], 3: [180, 270, 0], 4: [180, 235, 305, 0], 5: [180, 225, 270, 315, 0] }; // degrees round the table
99 const SEAT_A = 6.8, SEAT_B = 4.6, TABLE_R = 4.2, TOP = 1.5;
100 const STATIONS = ['tea', 'coffee', 'milk', 'sugar', 'cake'];
101 const STATION_A = { tea: -3.1, coffee: -1.55, milk: 0, sugar: 1.55, cake: 3.1 }, STATION_B = .5;
102 const STATION_NAME = { tea: 'the teapot', coffee: 'the coffee pot', milk: 'the milk jug', sugar: 'the sugar bowl', cake: 'the cake stand' };
103 // local table space: a runs across (screen right is +), b toward the camera, z up; the world axes sit 45 degrees off
104 const toWorld = (a, b, z) => [(a + b) / R2, (b - a) / R2, z];
105 const toLocal = (x, y) => ({ a: (x - y) / R2, b: (x + y) / R2 });
106
107 /* ---------- state ---------- */
108 const nodes = {};
109 for (const k of ['round', 'of', 'guests', 'score', 'wrong', 'ofwrong', 'perfect', 'best', 'cup', 'status']) nodes[k] = document.getElementById(k);
110 const shown = {};
111 function setText(key, text) {
112 if (shown[key] === text) return;
113 shown[key] = text;
114 nodes[key].textContent = text;
115 }
116 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
117 let P = M.start(Math.floor(Math.random() * 4294967296));
118 // sel: the guest being served; cup: what is poured so far; results: how each served guest did this round;
119 // focus/keyed: the keyboard's place; dirty: the picture needs repainting; overAt: when the game ended
120 const G = { time: 0, sel: null, cup: blankCup(), results: {}, focus: 0, keyed: false, dirty: true, wind: -1, overAt: 0, best: best0, carry: '' };
121 function blankCup() { return { drink: null, milk: null, sugars: null, cake: null }; }
122 const article = c => (c === 'eclair' ? 'an ' : 'a ') + c;
123 const sugarText = n => n === 0 ? 'no sugar' : n + (n === 1 ? ' sugar' : ' sugars');
124 const orderText = o => `${o.drink}, ${o.milk === 'milk' ? 'with milk' : 'no milk'}, ${sugarText(o.sugars)}, ${article(o.cake)}`;
125 function cupText(c) {
126 const bits = [c.drink || 'drink?', c.milk ? (c.milk === 'milk' ? 'milk' : 'no milk') : 'milk?', c.sugars === null ? 'sugar?' : sugarText(c.sugars), c.cake || 'cake?'];
127 return bits.join(' · ');
128 }
129 const guestName = i => `guest ${i + 1} ${GUESTS[i].name}`;
130 const cupDone = c => M.PARTS.every(p => c[p] !== null);
131
132 function renderHud() {
133 setText('round', String(P.round));
134 setText('of', `of ${M.LAST_ROUND} rounds`);
135 setText('guests', String(P.guests));
136 setText('score', String(P.score));
137 setText('wrong', String(P.wrong));
138 setText('ofwrong', `of ${M.MAX_WRONG} wrong parts`);
139 setText('perfect', String(P.perfect));
140 setText('best', String(G.best));
141 setText('cup', G.sel === null ? '' : `cup for guest ${G.sel + 1}: ${cupText(G.cup)}`);
142 }
143 function say(text) { setText('status', text); }
144
145 /* ---------- places on the screen ---------- */
146 function seatOf(i) {
147 const deg = SEATS[P.guests][i], a = SEAT_A * Math.cos(deg * Math.PI / 180), b = SEAT_B * Math.sin(deg * Math.PI / 180);
148 const w = toWorld(a, b, 0);
149 return { a, b, x: w[0], y: w[1] };
150 }
151 function stationAt(id) { const w = toWorld(STATION_A[id], STATION_B, TOP); return { x: w[0], y: w[1] }; }
152 // where a target sits on the canvas, as a tap would reach it
153 function pointOf(t) {
154 if (typeof t === 'number') { const s = seatOf(t), p = project(s.x, s.y, 1.7); return [Math.round(p.sx), Math.round(p.sy)]; }
155 const s = stationAt(t), p = project(s.x, s.y, TOP + .7);
156 return [Math.round(p.sx), Math.round(p.sy)];
157 }
158 function targetAt(sx, sy) {
159 let best = null, bestD = 1e9;
160 for (const id of STATIONS) {
161 const [x, y] = pointOf(id), dx = Math.abs(sx - x), dy = sy - y;
162 if (dx <= 8 && dy >= -13 && dy <= 12 && dx + Math.abs(dy) < bestD) { best = id; bestD = dx + Math.abs(dy); }
163 }
164 if (best) return best;
165 for (let i = 0; i < P.guests; i++) {
166 const [x, y] = pointOf(i), dx = Math.abs(sx - x), dy = sy - y;
167 if (dx <= 13 && dy >= -26 && dy <= 24 && dx + Math.abs(dy) < bestD) { best = i; bestD = dx + Math.abs(dy); }
168 }
169 return best;
170 }
171 const ring = () => [...Array(P.guests).keys(), ...STATIONS];
172
173 /* ---------- ground: a garden with a paved patio under the table ---------- */
174 function groundColor(x, y, ix, iy, i) {
175 const { a, b } = toLocal(x, y);
176 const edge = Math.pow(Math.pow(Math.abs(a) / 15, 4) + Math.pow(Math.abs(b) / 7.6, 4), .25);
177 const rough = edge + (noise(a * 1.3, b * 1.3) - .5) * .1;
178 if (rough > 1.04) return 0;
179 if (rough > .94 && hash(ix, iy) < (rough - .94) / .1) return 0;
180 if (Math.pow(a / 9.5, 2) + Math.pow(b / 5.8, 2) > 1 || rough > .86) {
181 kinds[i] = KIND_GRASS;
182 const t = noise(a * .9, b * .9) * 1.15 + (hash(ix, iy) - .5) * .55 - .08;
183 return rgb(...GRASS[clamp(Math.floor(t * 4.2), 0, 3)]);
184 }
185 const joint = Math.abs(((a + 30) % 1.6) - .8) > .72 || Math.abs(((b + 30) % 1.6) - .8) > .72;
186 const t = noise(a * .7, b * .7) * .7 + (hash(ix, iy) - .5) * .3 + (bayerAt(ix, iy) - .5) * .2 - (joint ? .45 : 0);
187 return rgb(...PAVING[clamp(Math.floor(t * 3.6), 0, 3)]);
188 }
189 const clothZ = new Float32Array(W * H).fill(-1e9);
190 function paintCloth(x, y, z, color) {
191 const p = project(x, y, z), ix = p.sx | 0, iy = p.sy | 0;
192 if (ix < 0 || iy < 0 || ix >= W || iy >= H) return;
193 const i = iy * W + ix;
194 if (p.d <= zb[i]) return;
195 zb[i] = p.d; pix[i] = color; clothZ[i] = p.d;
196 }
197 function bakeTable() {
198 const tone = (a, b, lit) => {
199 const check = (Math.floor((a + 20) / 1.15) + Math.floor((b + 20) / 1.15)) % 2 ? CLOTH_A : CLOTH_B;
200 const k = lit + (hash(Math.floor(a * 9), Math.floor(b * 9)) - .5) * .08;
201 return rgb(check[0] * k, check[1] * k, check[2] * k);
202 };
203 for (let a = -TABLE_R; a <= TABLE_R; a += .055) for (let b = -TABLE_R; b <= TABLE_R; b += .055) {
204 if (a * a + b * b > TABLE_R * TABLE_R) continue;
205 const w = toWorld(a, b, TOP);
206 paintCloth(w[0], w[1], TOP, tone(a, b, 1));
207 }
208 // the valance hangs from the rim in scallops, darker toward the right edge
209 for (let ang = 0; ang < Math.PI * 2; ang += .006) {
210 const a = TABLE_R * Math.cos(ang), b = TABLE_R * Math.sin(ang), scallop = .45 + .22 * Math.abs(Math.sin(ang * 14));
211 for (let z = TOP - .02; z > TOP - scallop; z -= .05) {
212 const w = toWorld(a, b, z), k = .8 - .2 * Math.max(0, Math.cos(ang)) * (b > -.5 ? 1 : .3);
213 paintCloth(w[0], w[1], z, rgb(VALANCE[0] * k, VALANCE[1] * k, VALANCE[2] * k));
214 }
215 }
216 const post = toWorld(0, 0, 0);
217 capsule([post[0], post[1], 0], [post[0], post[1], 1.0], .32, .26, () => [150, 120, 96], 'solid');
218 const foot = toWorld(0, 0, .08);
219 capsule([foot[0], foot[1], .05], [foot[0], foot[1], .12], 1.1, 1.0, () => [150, 120, 96], 'solid');
220 for (let a = -TABLE_R; a <= TABLE_R; a += .9) for (let b = -TABLE_R; b <= TABLE_R; b += .9) {
221 if (a * a + b * b < TABLE_R * TABLE_R * 1.1) { const w = toWorld(a, b, TOP); castShadow(w[0], w[1], TOP, .9, 1, .2); }
222 }
223 }
224 // a darker patch where a pot's shadow falls on the cloth, screen-right
225 function clothShadow(x, y, h, r) {
226 const p = project(x + SHADOW_X * h, y + SHADOW_Y * h, TOP), rx = r * S, ry = rx * SIN + 1;
227 for (let iy = Math.max(0, Math.floor(p.sy - ry)); iy <= Math.min(H - 1, Math.ceil(p.sy + ry)); iy++) {
228 for (let ix = Math.max(0, Math.floor(p.sx - rx)); ix <= Math.min(W - 1, Math.ceil(p.sx + rx)); ix++) {
229 const dx = (ix + .5 - p.sx) / rx, dy = (iy + .5 - p.sy) / ry, i = iy * W + ix;
230 if (dx * dx + dy * dy < 1 && clothZ[i] > -1e8 && zb[i] === clothZ[i]) tint(i, .6, .56, .74);
231 }
232 }
233 }
234 const TEAL = [96, 160, 170], CREAM = [244, 236, 224], COPPER = [196, 120, 70], DARK = [72, 52, 44], STEEL = [200, 204, 214];
235 function bakeItems() {
236 const solid = (a, b, r0, r1, c) => capsule(a, b, r0, r1, () => c, 'solid');
237 const at = (id, dx, dz) => { const w = toWorld(STATION_A[id] + dx, STATION_B, TOP + dz); return w; };
238 // the teapot is round and squat, with a lid knob, a short spout on the left and a loop handle on the right
239 let c = at('tea', 0, .5);
240 sphere(c[0], c[1], c[2], .52, TEAL, 'gloss');
241 const lid = at('tea', 0, 1.05); sphere(lid[0], lid[1], lid[2], .22, CREAM, 'gloss');
242 const knob = at('tea', 0, 1.25); sphere(knob[0], knob[1], knob[2], .08, [201, 138, 160], 'solid');
243 solid(at('tea', -.4, .4), at('tea', -.85, .95), .13, .07, TEAL);
244 solid(at('tea', .45, .95), at('tea', .8, .6), .08, .08, TEAL); solid(at('tea', .8, .6), at('tea', .45, .25), .08, .08, TEAL);
245 // the coffee pot is tall and tapered, in copper, with a high spout and a straight handle
246 solid(at('coffee', 0, .05), at('coffee', 0, 1.45), .42, .3, COPPER);
247 const top = at('coffee', 0, 1.6); sphere(top[0], top[1], top[2], .2, DARK, 'gloss');
248 solid(at('coffee', -.3, 1.25), at('coffee', -.62, 1.62), .1, .06, COPPER);
249 solid(at('coffee', .4, 1.25), at('coffee', .52, .45), .07, .07, DARK);
250 // the milk jug is small and straight-sided, in white with a blue band
251 solid(at('milk', 0, .05), at('milk', 0, .8), .3, .26, [236, 238, 244]);
252 solid(at('milk', 0, .4), at('milk', 0, .5), .31, .31, [96, 132, 190]);
253 solid(at('milk', -.25, .75), at('milk', -.45, .88), .08, .05, [236, 238, 244]);
254 solid(at('milk', .28, .7), at('milk', .42, .4), .06, .06, [236, 238, 244]);
255 // the sugar bowl is a round pink bowl with a lid and a little cube on top
256 c = at('sugar', 0, .38); sphere(c[0], c[1], c[2], .42, [244, 214, 222], 'gloss');
257 const lid2 = at('sugar', 0, .78); sphere(lid2[0], lid2[1], lid2[2], .22, [250, 232, 238], 'gloss');
258 // the cake stand: a stem, a foot and a silver plate; the cake itself is drawn live
259 solid(at('cake', 0, .03), at('cake', 0, .1), .5, .5, STEEL);
260 solid(at('cake', 0, .1), at('cake', 0, .72), .1, .1, STEEL);
261 solid(at('cake', 0, .72), at('cake', 0, .8), .62, .62, STEEL);
262 for (const id of STATIONS) { const w = at(id, 0, 0); for (const h of [.4, .8, 1.2]) clothShadow(w[0], w[1], h, .45); }
263 }
264 function bake() {
265 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
266 zb.fill(-1e9);
267 pix.fill(PAPER);
268 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
269 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i);
270 if (!c) continue;
271 pix[i] = c; ground[i] = 1;
272 zb[i] = (g.x + g.y) / R2 * COS;
273 }
274 growGrass();
275 groundZ.set(zb);
276 bakeTable();
277 bakeItems();
278 const tree = toWorld(-12, -4.8, 0);
279 growTree(tree[0], tree[1], .9, 260, 5);
280 castShadow(tree[0], tree[1], 1.3, 1.1, 1, .4);
281 bakeOcclusion();
282 staticShadow.set(shadowMask);
283 applyShadows(groundZ);
284 bakedPix.set(pix);
285 bakedZ.set(zb);
286 }
287
288 /* ---------- guests, hats and the cake ---------- */
289 function hat(k, x, y, base, yaw) {
290 const z = base + 2.72, fx = Math.cos(yaw), fy = Math.sin(yaw);
291 if (k === 0) { // top hat: tall black crown, flat brim, red band
292 dynamicAdd([x, y, z + .06], [x, y, z + .06], .4, .4, () => [40, 36, 44]);
293 dynamicAdd([x, y, z + .1], [x, y, z + .72], .26, .26, () => [40, 36, 44]);
294 dynamicAdd([x, y, z + .14], [x, y, z + .24], .28, .28, () => [190, 50, 50]);
295 } else if (k === 1) { // boater: flat straw crown and brim, blue band
296 dynamicAdd([x, y, z + .05], [x, y, z + .05], .46, .46, () => [236, 214, 150]);
297 dynamicAdd([x, y, z + .1], [x, y, z + .38], .28, .28, () => [236, 214, 150]);
298 dynamicAdd([x, y, z + .13], [x, y, z + .2], .29, .29, () => [60, 90, 170]);
299 } else if (k === 2) { // sun hat: very wide brim and a pink flower
300 dynamicAdd([x, y, z + .05], [x, y, z + .05], .62, .62, () => [240, 220, 160]);
301 dynamicAdd([x, y, z + .1], [x, y, z + .26], .26, .26, () => [240, 220, 160]);
302 dynamicAdd([x - fy * .24, y + fx * .24, z + .3], [x - fy * .24, y + fx * .24, z + .3], .13, .13, () => [230, 90, 130]);
303 } else if (k === 3) { // bobble hat: a close cap with a ball on top
304 dynamicAdd([x, y, z + .02], [x, y, z + .02], .29, .29, () => [90, 130, 200]);
305 dynamicAdd([x, y, z + .3], [x, y, z + .3], .12, .12, () => [250, 244, 226]);
306 } else { // party hat: a cone with a gold tip
307 dynamicAdd([x, y, z + .04], [x, y, z + .8], .26, .04, () => [220, 80, 150]);
308 dynamicAdd([x, y, z + .84], [x, y, z + .84], .08, .08, () => [250, 206, 36]);
309 }
310 }
311 function drawGuest(i) {
312 const s = seatOf(i), yaw = Math.atan2(-s.y, -s.x), pal = GUESTS[i];
313 const talking = P.phase === 'order' && P.status === 'playing' && P.shown === i + 1;
314 const picked = G.sel === i;
315 figure(s.x, s.y, yaw, { armR: talking ? .9 : .1, armL: picked ? .5 : .12, stance: .1, crouch: .05 }, pal, dynamicAdd);
316 hat(i, s.x, s.y, 0, yaw);
317 }
318 function drawCake() {
319 const w = toWorld(STATION_A.cake, STATION_B, TOP + .8), x = w[0], y = w[1], c = G.cup.cake, z = w[2];
320 const add = (a, b, r0, r1, col) => dynamicAdd(a, b, r0, r1, () => col);
321 if (c === 'scone') { add([x, y, z + .02], [x, y, z + .06], .46, .46, [214, 160, 84]); add([x, y, z + .24], [x, y, z + .24], .34, .34, [226, 176, 96]); }
322 else if (c === 'sponge') {
323 add([x, y, z + .02], [x, y, z + .2], .42, .42, [244, 214, 120]); add([x, y, z + .22], [x, y, z + .3], .43, .43, [250, 244, 230]);
324 add([x, y, z + .32], [x, y, z + .5], .42, .42, [244, 214, 120]); add([x, y, z + .52], [x, y, z + .56], .43, .43, [226, 130, 160]);
325 } else if (c === 'tart') { add([x, y, z + .02], [x, y, z + .16], .5, .46, [226, 176, 90]); add([x, y, z + .18], [x, y, z + .2], .38, .38, [238, 120, 60]); add([x, y, z + .3], [x, y, z + .3], .12, .12, [200, 40, 50]); }
326 else if (c === 'eclair') { const a = toWorld(STATION_A.cake - .4, STATION_B, z + .22), b = toWorld(STATION_A.cake + .4, STATION_B, z + .22); add(a, b, .22, .22, [250, 240, 214]); add([a[0], a[1], a[2] + .14], [b[0], b[1], b[2] + .14], .2, .2, [100, 62, 44]); }
327 else add([x, y, z + .05], [x, y, z + .05], .45, .45, [184, 204, 220]); // nothing chosen yet: a glass cover
328 }
329
330 /* ---------- icons, drawn flat on top of the scene ---------- */
331 function rect(x, y, w, h, c) {
332 for (let iy = Math.max(0, y); iy < Math.min(H, y + h); iy++) for (let ix = Math.max(0, x); ix < Math.min(W, x + w); ix++) pix[iy * W + ix] = c;
333 }
334 function frameRect(x, y, w, h, c) { rect(x, y, w, 1, c); rect(x, y + h - 1, w, 1, c); rect(x, y, 1, h, c); rect(x + w - 1, y, 1, h, c); }
335 // '#' ink, '.' clear, any other letter looks up its colour in the palette
336 function bitmap(rows, x, y, pal) {
337 rows.forEach((row, r) => { for (let c = 0; c < row.length; c++) { const ch = row[c]; if (ch !== '.') rect(x + c, y + r, 1, 1, ch === '#' ? LINE : pal[ch]); } });
338 }
339 const ICON_W = 9, ICON_H = 8;
340 const TEA_ICON = ['....#....', '..#####..', '##aaaaa##', '#aaaaaaa#', '#aaaaaaa#', '.#aaaaa#.', '..#####..'];
341 const COFFEE_ICON = ['...###...', '..#bbb#..', '..#aaa##.', '..#aaa#.#', '..#aaa#.#', '..#aaa##.', '..#aaa#..', '..#####..'];
342 const MILK_ICON = ['..####...', '.#wwww#..', '.#wwww##.', '.#wwww#.#', '.#wwww#.#', '.#wwww##.', '..####...'];
343 const CROSS_ICON = ['#.......#', '.#.....#.', '..#...#..', '...#.#...', '..#...#..', '.#.....#.', '#.......#'];
344 const CAKE_ICONS = {
345 scone: ['.........', '...###...', '..#ttt#..', '.#ttttt#.', '.#ttttt#.', '.#######.'],
346 sponge: ['..#####..', '.#ppppp#.', '.#ccccc#.', '.#sssss#.', '.#ccccc#.', '.#sssss#.', '..#####..'],
347 tart: ['....r....', '...rrr...', '.#######.', '#fffrfff#', '.#fffff#.', '..#####..'],
348 eclair: ['.........', '.#######.', '#kkkkkkk#', '#kkkkkkk#', '#ccccccc#', '.#######.'],
349 };
350 const ICON_PAL = { a: [214, 150, 70], b: [120, 80, 60], w: [250, 250, 250], t: [226, 176, 96], p: [226, 130, 160], c: [250, 244, 230], s: [244, 214, 120], f: [226, 176, 90], r: [200, 40, 50], k: [100, 62, 44] };
351 const palOf = {}; for (const k in ICON_PAL) palOf[k] = rgb(...ICON_PAL[k]);
352 function drawIcon(part, value, x, y) {
353 if (part === 'drink') {
354 const pal = { ...palOf, a: value === 'tea' ? rgb(214, 150, 70) : rgb(90, 56, 44), b: rgb(120, 80, 60) };
355 bitmap(value === 'tea' ? TEA_ICON : COFFEE_ICON, x, y, pal);
356 } else if (part === 'milk') bitmap(value === 'milk' ? MILK_ICON : CROSS_ICON, x, y, palOf);
357 else if (part === 'sugars') {
358 if (value === 0) { bitmap(CROSS_ICON.map(r => r.slice(1, 8)).slice(1, 6), x + 1, y + 1, palOf); return; }
359 const cube = (cx, cy) => { rect(cx, cy, 4, 4, LINE); rect(cx + 1, cy + 1, 2, 2, WHITE); };
360 if (value === 1) cube(x + 2, y + 3);
361 else if (value === 2) { cube(x, y + 3); cube(x + 5, y + 3); }
362 else { cube(x, y + 4); cube(x + 5, y + 4); cube(x + 2, y); }
363 } else if (part === 'cake') bitmap(CAKE_ICONS[value], x, y + (value === 'sponge' ? 0 : 1), palOf);
364 }
365 function drawBubble(o, cx, bottom) {
366 const w = 4 * 12 + 4, h = ICON_H + 8, x = clamp(Math.round(cx - w / 2), 2, W - w - 2), y = bottom - h - 4;
367 rect(x, y, w, h, LINE); rect(x + 1, y + 1, w - 2, h - 2, WHITE);
368 const tx = clamp(Math.round(cx), x + 4, x + w - 5);
369 rect(tx - 2, y + h, 5, 1, LINE); rect(tx - 1, y + h + 1, 3, 1, LINE); rect(tx, y + h + 2, 1, 1, LINE);
370 rect(tx - 1, y + h - 1, 3, 1, WHITE); rect(tx, y + h, 1, 1, WHITE);
371 M.PARTS.forEach((p, k) => drawIcon(p, o[p], x + 4 + k * 12, y + 4));
372 }
373 // served guests show four pips: green for each right part, red for each wrong one, gold when the cup was perfect
374 function drawPips(r, cx, y) {
375 for (let k = 0; k < 4; k++) rect(Math.round(cx) - 7 + k * 4, y, 3, 3, r.perfect ? GOLD : k < r.matched ? GREEN : RED);
376 }
377 function drawMarker(cx, y, c) { rect(cx - 2, y, 5, 1, c); rect(cx - 1, y + 1, 3, 1, c); rect(cx, y + 2, 1, 1, c); }
378 function drawOverlay() {
379 const talking = P.status === 'playing' && P.phase === 'order';
380 for (let i = 0; i < P.guests; i++) {
381 const [cx, cy] = pointOf(i), top = cy - 26;
382 if (talking && P.shown === i + 1) drawBubble(P.orders[i], cx, top);
383 else if (G.results[i]) drawPips(G.results[i], cx, top - 2);
384 else if (G.sel === i) { drawMarker(cx, top - 4, LINE); drawMarker(cx, top - 5, PINK); }
385 }
386 if (G.sel !== null) {
387 // what is poured so far, above each pot
388 for (const id of STATIONS) {
389 const [cx, cy] = pointOf(id), x = cx - 4, y = cy - 28;
390 if (id === 'tea' || id === 'coffee') { if (G.cup.drink === id) { drawMarker(cx, y + 6, LINE); drawMarker(cx, y + 5, PINK); } }
391 else if (id === 'milk' && G.cup.milk) drawIcon('milk', G.cup.milk, x, y);
392 else if (id === 'sugar' && G.cup.sugars !== null) drawIcon('sugars', G.cup.sugars, x, y);
393 }
394 }
395 if (G.keyed) {
396 const f = G.focus, [cx, cy] = pointOf(f), box = typeof f === 'number' ? [26, 52, cy - 26] : [18, 26, cy - 13];
397 frameRect(cx - box[0] / 2 - 1, box[2] - 1, box[0] + 2, box[1] + 2, WHITE);
398 frameRect(cx - box[0] / 2, box[2], box[0], box[1], LINE);
399 }
400 }
401 function draw() {
402 pix.set(bakedPix);
403 zb.set(bakedZ);
404 pendingShadows.length = 0;
405 const t = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS;
406 for (let i = 0; i < P.guests; i++) drawGuest(i);
407 drawCake();
408 drawLeaves(t);
409 drawTufts(t);
410 flushShadows();
411 applyShadows(bakedZ);
412 shadeEdges();
413 drawOverlay();
414 ctx.putImageData(image, 0, 0);
415 }
416
417 /* ---------- game: every rule is the rules script's ---------- */
418 function saveBest() {
419 if (P.score <= G.best) return;
420 G.best = P.score;
421 try { localStorage.setItem(BEST_KEY, String(G.best)); } catch (e) { /* private window: keep it for this visit */ }
422 }
423 const SERVE_HELP = 'Everyone has ordered. Tap a guest, then the pots, milk, sugar and cake, then the guest again to serve.';
424 function announce(text) { say(G.carry ? `${G.carry} ${text}` : text); G.carry = ''; }
425 function update(dt) {
426 G.time += dt;
427 if (P.status === 'playing' && P.phase === 'order') {
428 const before = P, r = M.tick(P, dt);
429 if (r.ok) {
430 P = r.state;
431 G.dirty = true;
432 if (before.phase === 'order' && P.phase === 'serve') announce(SERVE_HELP);
433 else if (P.shown !== before.shown) announce(`${P.shown === 1 ? P.line + '. ' : ''}Guest ${P.shown} orders ${orderText(P.orders[P.shown - 1])}.`);
434 }
435 }
436 const wind = STILL ? 0 : Math.floor(G.time * WIND_FPS);
437 if (wind !== G.wind) { G.wind = wind; G.dirty = true; }
438 renderHud();
439 }
440 function begin() {
441 announce(`${P.line}. Guest 1 orders ${orderText(P.orders[0])}.`);
442 }
443 function restart() {
444 P = M.start(Math.floor(Math.random() * 4294967296));
445 G.sel = null; G.cup = blankCup(); G.results = {}; G.focus = 0; G.dirty = true;
446 begin();
447 }
448 function serveGuest() {
449 const g = G.sel, before = P, r = M.serve(P, g, G.cup);
450 if (!r.ok) { say(`Cannot serve: ${r.why}.`); sound(150, .12, 'square'); return; }
451 P = r.state;
452 const hit = P.last;
453 G.dirty = true;
454 const text = `Guest ${g + 1}: ${hit.matched} of 4 right${hit.perfect ? ', a perfect cup' : ''}.`;
455 sound(hit.perfect ? 784 : hit.matched >= 3 ? 560 : 180, .14, hit.matched >= 3 ? 'triangle' : 'sawtooth');
456 G.sel = null; G.cup = blankCup();
457 if (P.round !== before.round && P.status === 'playing') {
458 G.results = {};
459 G.carry = text;
460 announce(`${P.line}. Guest 1 orders ${orderText(P.orders[0])}.`);
461 G.focus = 0;
462 } else {
463 G.results[g] = hit;
464 say(P.status === 'playing' ? text : `${text} ${P.line}. Tap or press Enter to play again.`);
465 }
466 if (P.status !== 'playing') { G.overAt = G.time; saveBest(); sound(P.status === 'won' ? 880 : 110, .4, P.status === 'won' ? 'triangle' : 'sawtooth', .15); }
467 }
468 // one choice, from a tap or a key: a guest, or one of the things on the table
469 function choose(t) {
470 ensureAudio();
471 G.dirty = true;
472 if (P.status !== 'playing') { if (G.time - G.overAt > .6) restart(); return; }
473 if (P.phase === 'order') { say('Still listening: wait for every order before serving.'); return; }
474 if (typeof t === 'number') {
475 if (P.served.includes(t)) { say(`${guestName(t)} is already served.`); return; }
476 if (G.sel !== t) { G.sel = t; G.cup = blankCup(); say(`Serving ${guestName(t)}. Choose a pot, milk, sugar and cake, then choose the guest again.`); sound(400, .06, 'triangle'); return; }
477 if (!cupDone(G.cup)) { say(`The cup is not ready: ${cupText(G.cup)}.`); sound(150, .1, 'square'); return; }
478 serveGuest();
479 return;
480 }
481 if (G.sel === null) { say('Choose a guest first.'); return; }
482 const c = G.cup;
483 if (t === 'tea' || t === 'coffee') c.drink = t;
484 else if (t === 'milk') c.milk = c.milk === 'milk' ? 'none' : 'milk';
485 else if (t === 'sugar') c.sugars = c.sugars === null ? 1 : (c.sugars + 1) % (M.SUGARS.length);
486 else c.cake = M.CAKES[(c.cake === null ? 0 : M.CAKES.indexOf(c.cake) + 1) % M.CAKES.length];
487 sound(300 + 40 * STATIONS.indexOf(t), .06, 'triangle');
488 say(`${cupText(c)}.`);
489 }
490
491 /* ---------- input ---------- */
492 const point = e => { const r = canvas.getBoundingClientRect(); return [(e.clientX - r.left) / r.width * W, (e.clientY - r.top) / r.height * H]; };
493 canvas.addEventListener('pointerdown', e => {
494 canvas.focus({ preventScroll: true });
495 G.keyed = false;
496 const [sx, sy] = point(e), t = targetAt(sx, sy);
497 if (t === null) { ensureAudio(); if (P.status !== 'playing') choose(0); else say(P.phase === 'order' ? 'Listen to each guest in turn.' : 'Tap a guest, then the pots, milk, sugar and cake.'); G.dirty = true; return; }
498 G.focus = t;
499 choose(t);
500 });
501 canvas.addEventListener('contextmenu', e => e.preventDefault());
502 canvas.addEventListener('keydown', e => {
503 if (e.ctrlKey || e.metaKey || e.altKey) return;
504 const list = ring();
505 if (G.focus !== 0 && !list.includes(G.focus)) G.focus = 0;
506 const at = list.indexOf(G.focus);
507 let step = 0;
508 if (e.key === 'ArrowRight' || e.key === 'ArrowDown') step = 1;
509 else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') step = -1;
510 else if (e.key === 'Tab') {
511 step = e.shiftKey ? -1 : 1;
512 if (G.keyed && (at + step < 0 || at + step >= list.length)) { G.keyed = false; G.dirty = true; return; } // Tab leaves the canvas at either end
513 } else if (e.key !== 'Enter' && e.key !== ' ') return;
514 e.preventDefault();
515 G.dirty = true;
516 if (step) {
517 G.focus = list[(at + step + list.length) % list.length];
518 G.keyed = true;
519 const f = G.focus;
520 say(typeof f === 'number' ? `${guestName(f)}${P.served.includes(f) ? ', served' : ''}` : STATION_NAME[f]);
521 return;
522 }
523 if (e.repeat) return;
524 G.keyed = true;
525 choose(G.focus);
526 });
527
528 /* ---------- sound ---------- */
529 let audio = null, muted = false;
530 function ensureAudio() {
531 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
532 const AC = window.AudioContext || window.webkitAudioContext;
533 if (AC) audio = new AC();
534 }
535 function sound(freq, life, type, delay = 0) {
536 if (!audio || muted) return;
537 const now = audio.currentTime + delay, gain = audio.createGain(), osc = audio.createOscillator();
538 osc.type = type;
539 osc.frequency.setValueAtTime(freq, now);
540 gain.gain.setValueAtTime(.0001, now);
541 gain.gain.exponentialRampToValueAtTime(.06, now + .01);
542 gain.gain.exponentialRampToValueAtTime(.0005, now + life);
543 osc.connect(gain).connect(audio.destination);
544 osc.start(now); osc.stop(now + life + .02);
545 }
546 const muteButton = document.getElementById('mute');
547 muteButton.addEventListener('click', () => {
548 muted = !muted;
549 muteButton.textContent = muted ? 'sound off' : 'sound on';
550 muteButton.setAttribute('aria-pressed', String(muted));
551 });
552
553 /* ---------- fit and boot ---------- */
554 addEventListener('resize', fit);
555 fit();
556 bake();
557 renderHud();
558 begin();
559 canvas.focus({ preventScroll: true });
560 let last = performance.now();
561 function frame(now) {
562 update(Math.min(.04, (now - last) / 1000));
563 last = now;
564 if (G.dirty) { G.dirty = false; draw(); }
565 requestAnimationFrame(frame);
566 }
567 requestAnimationFrame(frame);
568 </script>
569 </body>
570 </html>
tea-party/page.test.mjs added +110
@@ -0,0 +1,110 @@
1 import { test, expect } from 'bun:test';
2 import { boot } from '../playtest.mjs';
3
4 const listen = g => { while (g.read('P.phase') === 'order') g.run(.5); };
5 const tap = (g, t) => g.tap(...g.read(`pointOf(${JSON.stringify(t)})`));
6
7 test('each order is shown in a bubble in turn, and tapping before the orders end serves nothing', () => {
8 const g = boot('tea-party');
9 expect(g.read('P.phase')).toBe('order');
10 const first = g.picture();
11 tap(g, 0);
12 expect(g.read('G.sel')).toBeNull();
13 expect(g.el('status').textContent).toContain('Still listening');
14 g.run(1.6);
15 expect(g.read('P.shown')).toBe(2);
16 expect(g.el('status').textContent).toMatch(/^Guest 2 orders /);
17 expect(g.picture()).not.toBe(first);
18 listen(g);
19 expect(g.read('P.phase')).toBe('serve');
20 });
21
22 test('guest, pots, milk, sugar and cake, then the guest again, serve through the rules and the HUD reports the rules state', () => {
23 const g = boot('tea-party');
24 listen(g);
25 tap(g, 0);
26 expect(g.read('G.sel')).toBe(0);
27 const want = g.read('({ ...P.orders[0] })');
28 tap(g, want.drink);
29 tap(g, 'milk');
30 if (want.milk === 'none') tap(g, 'milk');
31 for (let i = 0; i < (want.sugars || 4); i++) tap(g, 'sugar');
32 for (let i = 0; i <= g.read(`M.CAKES.indexOf(${JSON.stringify(want.cake)})`); i++) tap(g, 'cake');
33 expect(g.el('cup').textContent).toContain(`for guest 1: ${want.drink}`);
34 tap(g, 0);
35 expect(g.read('P.served')).toEqual([0]);
36 expect(g.read('P.perfect')).toBe(1);
37 expect(g.el('score').textContent).toBe(String(g.read('P.score')));
38 expect(g.el('perfect').textContent).toBe('1');
39 expect(g.el('status').textContent).toContain('a perfect cup');
40 });
41
42 test('an unfinished cup is not served, and a served guest cannot be served again', () => {
43 const g = boot('tea-party');
44 listen(g);
45 tap(g, 1);
46 tap(g, 1);
47 expect(g.read('P.served')).toEqual([]);
48 expect(g.el('status').textContent).toContain('not ready');
49 tap(g, 'tea'); tap(g, 'milk'); tap(g, 'sugar'); tap(g, 'cake');
50 tap(g, 1);
51 expect(g.read('P.served')).toEqual([1]);
52 tap(g, 1);
53 expect(g.el('status').textContent).toContain('already served');
54 });
55
56 test('Tab, the arrow keys and Enter do the same as taps', () => {
57 const g = boot('tea-party');
58 listen(g);
59 g.press('Enter');
60 expect(g.read('G.sel')).toBe(0);
61 g.press('Tab');
62 expect(g.read('G.focus')).toBe(1);
63 g.press('ArrowLeft');
64 expect(g.read('G.focus')).toBe(0);
65 g.press('ArrowLeft');
66 expect(g.read('G.focus')).toBe('cake');
67 g.press('Enter');
68 expect(g.read('G.cup.cake')).toBe('scone');
69 expect(g.el('status').textContent).toContain('scone');
70 });
71
72 test('three wrong parts end the game with the rules line, and a tap starts it again', () => {
73 const g = boot('tea-party');
74 listen(g);
75 for (const i of [0, 1]) {
76 const want = g.read(`({ ...P.orders[${i}] })`);
77 tap(g, i);
78 tap(g, want.drink === 'tea' ? 'coffee' : 'tea');
79 tap(g, 'milk'); if (want.milk === 'milk') tap(g, 'milk');
80 tap(g, 'sugar'); if (want.sugars === 1) tap(g, 'sugar');
81 tap(g, 'cake'); if (want.cake === 'scone') tap(g, 'cake');
82 tap(g, i);
83 }
84 expect(g.read('P.status')).toBe('lost');
85 expect(g.el('status').textContent).toContain(g.read('P.line'));
86 g.run(1);
87 g.tap(180, 140);
88 expect(g.read('P.status')).toBe('playing');
89 expect(g.read('P.round')).toBe(1);
90 });
91
92 test('mute toggles its label and aria-pressed', () => {
93 const g = boot('tea-party');
94 g.el('mute').fire('click');
95 expect(g.el('mute').textContent).toBe('sound off');
96 expect(g.el('mute').attrs['aria-pressed']).toBe('true');
97 });
98
99 test('the page source says how to play, stills the grass, differs by hat, holds the rules to four lines and names no .mp3', async () => {
100 const html = await Bun.file(new URL('./index.html', import.meta.url)).text();
101 expect(html).toMatch(/<canvas id="c"[^>]*aria-label="[^"]*tap a guest[^"]*Enter/);
102 expect(html).toMatch(/min-height: 44px; min-width: 44px/);
103 expect(html).toMatch(/id="mute"[^>]*aria-pressed="false"/);
104 expect(html).toContain('const t = STILL ? 0');
105 expect(html).toMatch(/role="status" aria-live="polite"/);
106 expect(html).not.toContain('.mp3');
107 expect(html.match(/name: 'in the [a-z ]+'/g).length).toBe(5);
108 const rules = html.match(/rules: \[([\s\S]*?)\]/)[1].split('\n').filter(l => l.trim());
109 expect(rules.length).toBeLessThanOrEqual(4);
110 });
tea-party/table.js +1 −1
@@ -105,7 +105,7 @@
105105 if (s.served.length === s.guests) {
106106 if (s.wrong >= MAX_WRONG) s.status = 'lost';
107107 else if (s.round >= LAST_ROUND) s.status = 'won';
108 else s = lay(s.seed, s.round + 1, s.rng, { seed: s.seed, score: s.score, perfect: s.perfect });
108 else s = { ...lay(s.seed, s.round + 1, s.rng, { seed: s.seed, score: s.score, perfect: s.perfect }), last: s.last }; // `last` is still the cup just served
109109 }
110110 s.line = describe(s);
111111 return { ok: true, state: s, why: '' };
tea-party/table.test.mjs +8
@@ -119,3 +119,11 @@ test('fewer wrong parts than the limit let the round pass; clearing the last rou
119119 expect(s.score).toBe(total * 4 * PART_POINTS + (total - 1) * PERFECT_BONUS - PART_POINTS);
120120 expect(s.line).toBe(`You win: score ${s.score}, ${s.perfect} perfect cups`);
121121 });
122
123 test('a serve that clears the round into the next one still reports the cup just served', () => {
124 let s = listen(start(11));
125 s = serve(s, 0, exact(s, 0)).state;
126 const next = serve(s, 1, wrongly(s, 1, 1)).state;
127 expect(next.round).toBe(2);
128 expect(next.last).toEqual({ guest: 1, matched: 3, perfect: false });
129 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs