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

Migrated from github.com/amirmushichge/pixel-plays

Add Sheepdog: guide the flock through the gate and into the pen before the light goes #93

Merged opened this

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

Merged

quill/pixel-plays:quill/74-add-sheepdog-guide-the-flock-through-the → main 5 commits fork

  • Merged. quill/74-add-sheepdog-guide-the-flock-through-the was merged into main as 6f1ec61.

Review

Sign in to review this change.
14 files changed +871 −7
README.md +3 −2
@@ -41,6 +41,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
4141 | [Espresso Bar](espresso-bar/) | Twenty cups slide past under an espresso spout, each with a painted fill line and an order card (espresso a short line, latte a tall one): hold to pour, and the stream keeps falling for a quarter second after you let go; within 3% of the line scores 3, within 10% scores 1, over the brim spills and costs a life, and a cup that passes untouched costs a life; cups come faster as the round goes, three lives end it (forged by the crew on the engine and shell above, not by the original creators) | Hold space, or press and hold the canvas |
4242 | [Goalkeeper](goalkeeper/) | Ten penalties in a village football ground: each taker runs up and their hips and plant foot lean toward the side they will shoot (arms spread wide is down the middle), readable for a short tell window before the kick that shrinks with every penalty; tap the left third of the canvas to dive left, the right third to dive right and the middle third to stay up, and a dive to the right side before the ball arrives saves it, while diving before the tell window opens lets the taker switch side half the time; seven saves wins; the concept is the ordinary football penalty, with no particular game as its source (forged by the crew on the engine and shell above, not by the original creators) | Tap left, middle or right; Left and Right arrows dive, Up stays |
4343 | [Soapbox Derby](soapbox-derby/) | A 360 m cobbled hill in a wooden cart that rolls and gathers speed by itself: steer between the gaps in gates of hay bales that narrow down the hill (the cart answers late, so steer early); a bale slows it hard and costs one of three lives, a smooth flagstone strip gives a short boost, and the banner scores your time against your best (forged by the crew on the engine and shell above, not by the original creators) | Drag left or right; left/right arrows |
44 | [Sheepdog](sheepdog/) | A 90-second dusk over three hillside fields, five sheep each, scattered at the top: drag the dog (or use the arrow keys) so they flee it inside a set radius, flock together and wander when calm, and push one too hard and it bolts the wrong way; each sheep that goes through the dry-stone wall's gate and then into the hurdle pen scores, one that goes round the gate scores nothing once penned; the gate moves every field, the sun lowers with the clock, and 10 or more of 15 wins (forged by the crew on the engine and shell above, not by the original creators) | Drag the dog; arrow keys |
4445 | [Firefly Jar](firefly-jar/) | A 90-second summer night in a back garden: tap a firefly while it glows to catch it into the jar (+1, golden +3), a dim one is scared off and breaks the streak, shoo the moths before they reach the lantern; the third moth ends the night (forged by the crew on the engine and shell above, not by the original creators) | Tap; Tab or arrows + space |
4546
4647 ## Run
@@ -61,7 +62,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
6162 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.
6263
6364 ## Add a game
64 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 and Firefly Jar 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`.
65 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 and Firefly Jar 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`.
6566
6667 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
6768 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
@@ -77,7 +78,7 @@ Create `<id>/index.html`, load `../shell.js`, call `PixelPlays.mount({ id, rules
7778 - Depth-buffer edges: darker where an object sits in front, a warm rim on upper-left edges.
7879 - Large flat surfaces use closely spaced tones; wide steps make the dither read as a checkerboard.
7980 - Characters stay sharp: flat bands with no dither, a dark silhouette on their own pixels, patterns at least 3px wide.
80 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, and Espresso Bar's machine steam and awning fringe move; all of it stops under `prefers-reduced-motion`.
81 - Ambient motion only where the scene names it: grass and leaves sway in whole pixels at 8 fps, Tram Line's waiting passengers shift their weight, Espresso Bar's machine steam and awning fringe move, and Sheepdog's crow on the wall shifts and dips its head; all of it stops under `prefers-reduced-motion`.
8182
8283 ## License
8384 The code is under the [MIT License](LICENSE). The music is not: see [MUSIC.md](MUSIC.md).
firefly-jar/index.html +1 −1
@@ -22,7 +22,7 @@
2222 <style>
2323 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #c9b43a; }
2424 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
2626 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
2727 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
2828 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
index.html +1
@@ -91,6 +91,7 @@ footer a::after { content: none; }
9191 <li data-kind="Precision" data-input="Hold" style="--accent:#6f4a33"><a href="espresso-bar/">Espresso Bar</a><span>Pour twenty coffees to the line as cups slide past: hold to pour, let go early, over the brim costs a life</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li>
9292 <li data-kind="Sport" data-input="Tap" style="--accent:#3f7a3a"><a href="goalkeeper/">Goalkeeper</a><span>Read the taker and dive left or right to save ten penalties</span><span>Game forged by the crew</span><span class="tags">Sport · Tap</span></li>
9393 <li data-kind="Racing" data-input="Drag" style="--accent:#b5562b"><a href="soapbox-derby/">Soapbox Derby</a><span>Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins</span><span>Game forged by the crew</span><span class="tags">Racing · Drag</span></li>
94 <li data-kind="Catching" data-input="Drag" style="--accent:#5b8a3a"><a href="sheepdog/">Sheepdog</a><span>Drag the dog to steer five sheep through the gate and into the pen before dusk</span><span>Game forged by the crew</span><span class="tags">Catching · Drag</span></li>
9495 <li data-kind="Catching" data-input="Tap" style="--accent:#c9b43a"><a href="firefly-jar/">Firefly Jar</a><span>Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern</span><span>Game forged by the crew</span><span class="tags">Catching · Tap</span></li>
9596 </ul>
9697 <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>
og/home.png
Binary file not shown.
og/sheepdog.png added
Binary file not shown.
rounds.mjs +41
@@ -18,6 +18,18 @@ export const ROUNDS = {
1818 // tend the fire: a twig whenever the flames sink toward the lower mark
1919 'campfire': { over: /play again/, outcome: /dawn, the fire held · \d+ s/, beat: g => { if (g.read('G.heat') < 55 && g.read('G.fuel.length') < 3) g.press(' '); g.step(5); } },
2020 'domino-run': { over: /play again/, outcome: /\d+ points/, beat: g => { g.press(' '); g.press('ArrowRight'); g.press('Enter'); g.run(1); } },
21 // pour while the cup is under the spout, and let go in time for the stream's tail to land on the line
22 'espresso-bar': { over: /pour again/, outcome: /twenty cups poured · \d+/, beat: g => {
23 const pour = g.read('R.phase === "play" && !R.done && Math.abs(R.x) <= Pour.WINDOW && R.fill + Pour.RATE * Pour.DELAY < Pour.lineOf(R.cup)');
24 if (pour) g.keyDown(' '); else g.keyUp(' ');
25 g.step(1);
26 } },
27 // shoo any moth first, else catch a firefly that is glowing
28 'firefly-jar': { over: /another night/, outcome: /the night is survived · \d+ in the jar/, beat: g => {
29 const at = g.read('(() => { const t = Night.targets(R); const m = t.find(x => x.kind === "moth") || t.find(x => x.kind === "fly" && Night.glow(R.flies.find(f => f.id === x.id)).on); if (!m) return null; const p = scr(m.u, m.v, m.z); return [p.sx, p.sy]; })()');
30 if (at) g.tap(at[0], at[1]);
31 g.step(2);
32 } },
2133 'free-throw': { over: /play again/, outcome: /\d+ of 30/, beat: g => { g.hold(...MID, .6); g.run(.45); g.tap(...MID); g.run(1.5); g.tap(...MID); } },
2234 // dive the way the taker leans, once the tell shows
2335 'goalkeeper': { over: /play again/, outcome: /you win: \d+ saves/, beat: g => {
@@ -37,7 +49,36 @@ export const ROUNDS = {
3749 'pizza-toss': { over: /play again/, outcome: /\d+ px across/, beat: g => { g.hold(...MID, 1); g.run(1); g.tap(...MID); } },
3850 'pottery-wheel': { over: /new round/, outcome: /\d+ px in total/, beat: g => { g.hold(...MID, 2); g.drag([180, 200], [180, 60], 1); g.tap(...MID); } },
3951 'row-home': { over: /row again/, outcome: /[\d.]+s · (new best|best)|you won/, beat: tapping(.8) },
52 // herd by pointer: hold the dog 3 units beyond the sheep furthest from its goal (the gate, then the pen)
53 'sheepdog': { over: /play again/, outcome: /the flock is home · \d+ of 15/, beat: (() => {
54 let down = false;
55 return g => {
56 const loose = g.read('R.sheep.filter(s => !s.penned).map(s => [s.x, s.y, s.gated])');
57 if (g.read('R.phase') === 'play' && loose.length) {
58 const gate = g.read('Flock.gateOf(R.field)'), goalOf = s => (s[2] ? { x: 0, y: 15 } : gate);
59 let far = loose[0], reach = -1;
60 for (const s of loose) { const q = goalOf(s), d = Math.hypot(s[0] - q.x, s[1] - q.y); if (d > reach) { reach = d; far = s; } }
61 const q = goalOf(far), dx = far[0] - q.x, dy = far[1] - q.y, n = Math.hypot(dx, dy) || 1;
62 const [sx, sy] = g.read(`screenOf(${far[0] + dx / n * 3}, ${far[1] + dy / n * 3})`);
63 if (!down) { g.down(sx, sy); down = true; } else g.move(sx, sy);
64 }
65 g.step(1);
66 };
67 })() },
4068 'sled-run': { over: /ride again/, outcome: /[1-9]\d* m · \d+ clean/, beat: g => { g.hold(...MID, .6); g.run(.6); } },
69 // pull the lever the lamp showed for two trains, then a wrong one each turn until three trains are lost
70 'signal-box': { over: /run again/, outcome: /\d+ trains routed · the junction needs 8 to run on time/, beat: g => {
71 if (g.read('P.phase') === 'input') g.press(String((g.read('P.seq[P.got]') + (g.read('P.routed') < 2 ? 0 : 1)) % 5 + 1));
72 g.run(.3);
73 } },
74 // steer to the middle of the next gap in the bales
75 'soapbox-derby': { over: /roll again/, outcome: /banner! [\d.]+ s/, beat: g => {
76 const want = g.read('(() => { for (let n = 0; n < Cart.GATES; n++) { const t = Cart.gateAt(n, R.seed); if (R.x < t.x + Cart.GATE_DEPTH + 1.6) return t.centre / Cart.LANE_MAX; } return 0; })()');
77 const have = g.read('G.steer'), k = have < want - .04 ? 'ArrowRight' : have > want + .04 ? 'ArrowLeft' : null;
78 if (k) g.keyDown(k);
79 g.step(1);
80 if (k) g.keyUp(k);
81 } },
4182 'stari-most': { over: /dive again/, outcome: /total [\d.]+/, beat: g => { g.hold(...MID, .4); g.run(.5); g.hold(...MID, .6); g.run(2); g.tap(...MID); } },
4283 'stone-skip': { over: /play again/, outcome: /\d+ bounces/, beat: g => { g.drag([180, 140], [140, 170], .4); g.run(3); g.tap(...MID); } },
4384 // brake for the mark by the distance it takes to stop, drive off when the doors close
serve.test.mjs +7
@@ -423,6 +423,13 @@ test('Soapbox Derby and its rules script are served without a track', async () =
423423 expect((await fetch(base + '/soapbox-derby/cart.js')).status).toBe(200);
424424 });
425425
426 test('Sheepdog and its rules script are served without a track', async () => {
427 const page = await fetch(base + '/sheepdog/');
428 expect(page.status).toBe(200);
429 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
430 expect((await fetch(base + '/sheepdog/flock.js')).status).toBe(200);
431 });
432
426433 test('Espresso Bar and its rules script are served without a track', async () => {
427434 const page = await fetch(base + '/espresso-bar/');
428435 expect(page.status).toBe(200);
sheepdog/flock.js added +177
@@ -0,0 +1,177 @@
1 'use strict';
2 // The sheepdog rules: a dog the player steers, five sheep that flee it, flock together and wander when calm, a gate
3 // halfway down a hillside and a pen at the bottom. Positions are in field units: x runs across, y runs downhill
4 // (the page lays this frame onto its camera). Every random choice comes from the game's seed, so one seed and one
5 // sequence of inputs always play out the same. Plain numbers in, plain numbers out, no DOM.
6 (function (root) {
7 const SHEEP = 5, FIELDS = 3, TOTAL = SHEEP * FIELDS, ROUND_TIME = 90, WIN_AT = 10;
8 const FIELD = { x0: -12, x1: 12, y0: -17, y1: 17 };
9 const PEN = { x0: -3.5, x1: 3.5, y0: 13, y1: 17 }; // open at the top, hurdles on the other three sides
10 const GATES = [{ x: 0, y: -1 }, { x: -5, y: 1 }, { x: 5, y: -2 }]; // one per field
11 const GATE_HALF = 2.2, WALL = 6; // the gate is 4.4 wide; the wall runs 6 to each side of it
12 const DOG_SPEED = 9, START_DOG = { x: 0, y: 6 };
13 const FLEE_R = 6, FLEE_SPEED = 4.2, BOLT_R = 1.6, BOLT_SPEED = 6, BOLT_TIME = .7, BOLT_TURN = 110 * Math.PI / 180;
14 const COHESION_R = 7, COHESION_PULL = .9, SEPARATION = 1.1, WANDER_SPEED = .9, WANDER_TURN = 3, ACCEL = 4;
15 const STEP = 1 / 30, EPS = 1e-9;
16
17 const finite = v => (Number.isFinite(v) ? v : 0);
18 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
19 function rand(s) { // mulberry32 over the game's own state
20 s.rng = (s.rng + 0x6D2B79F5) >>> 0;
21 let t = s.rng;
22 t = Math.imul(t ^ t >>> 15, t | 1);
23 t ^= t + Math.imul(t ^ t >>> 7, t | 61);
24 return ((t ^ t >>> 14) >>> 0) / 4294967296;
25 }
26 const gateOf = field => GATES[clamp(Math.floor(finite(field)), 0, FIELDS - 1)];
27 // the two stretches of dry-stone wall either side of the gate, clipped to the field
28 function wallsOf(field) {
29 const g = gateOf(field);
30 return [[Math.max(FIELD.x0, g.x - GATE_HALF - WALL), g.x - GATE_HALF], [g.x + GATE_HALF, Math.min(FIELD.x1, g.x + GATE_HALF + WALL)]];
31 }
32 const inWall = (field, x) => wallsOf(field).some(([a, b]) => x >= a && x <= b);
33 const inPen = (x, y) => x >= PEN.x0 && x <= PEN.x1 && y >= PEN.y0 && y <= PEN.y1;
34
35 // a fresh scatter of five at the top of the field: the same for one seed and field
36 function scatter(field, seed = 1) {
37 const r = { rng: (Math.imul(finite(seed) | 0, 2654435761) + field * 7919 + 1) >>> 0 }, out = [];
38 for (let tries = 0; out.length < SHEEP && tries < 500; tries++) {
39 const p = { x: -9 + rand(r) * 18, y: -15 + rand(r) * 5 };
40 if (out.every(q => Math.hypot(q.x - p.x, q.y - p.y) >= 2.4)) out.push(p);
41 }
42 return out;
43 }
44 const sheepAt = p => ({ x: p.x, y: p.y, vx: 0, vy: 0, heading: 0, gated: false, penned: false, scored: false, bolt: 0, bx: 0, by: 0 });
45 function startField(s) {
46 s.sheep = scatter(s.field, s.seed).map(sheepAt);
47 s.sheep.forEach(sh => { sh.heading = rand(s) * Math.PI * 2; });
48 s.dog = { ...START_DOG }; s.target = null; s.dir = { x: 0, y: 0 };
49 }
50 function newGame(best = 0, seed = 1) {
51 const s = {
52 phase: 'play', time: ROUND_TIME, elapsed: 0, field: 0, fieldScores: [0, 0, 0], total: 0, seed: finite(seed) | 0,
53 rng: (finite(seed) | 0) >>> 0, best: Math.max(0, finite(best)), record: false, win: false, reason: '', timer: 0,
54 };
55 startField(s);
56 return s;
57 }
58 const verdict = total => (finite(total) >= WIN_AT ? 'win' : 'loss');
59
60 // where the dog is told to go: a point on the field (a drag), or a heading (the arrow keys)
61 function aim(s, x, y) {
62 if (!Number.isFinite(x) || !Number.isFinite(y)) return;
63 s.target = { x: clamp(x, FIELD.x0, FIELD.x1), y: clamp(y, FIELD.y0, FIELD.y1) };
64 }
65 function steer(s, dx, dy) {
66 dx = clamp(finite(dx), -1, 1); dy = clamp(finite(dy), -1, 1);
67 s.dir = { x: dx, y: dy };
68 if (dx || dy) s.target = null;
69 }
70 function moveDog(s, dt) {
71 const d = s.dog;
72 if (s.dir.x || s.dir.y) {
73 const n = Math.hypot(s.dir.x, s.dir.y);
74 d.x += s.dir.x / n * DOG_SPEED * dt; d.y += s.dir.y / n * DOG_SPEED * dt;
75 } else if (s.target) {
76 const dx = s.target.x - d.x, dy = s.target.y - d.y, dist = Math.hypot(dx, dy), go = DOG_SPEED * dt;
77 if (dist <= go) { d.x = s.target.x; d.y = s.target.y; } else { d.x += dx / dist * go; d.y += dy / dist * go; }
78 }
79 d.x = clamp(d.x, FIELD.x0, FIELD.x1); d.y = clamp(d.y, FIELD.y0, FIELD.y1);
80 }
81
82 function moveSheep(s, sh, h, events) {
83 const px = sh.x, py = sh.y;
84 sh.x = clamp(sh.x + sh.vx * h, FIELD.x0, FIELD.x1);
85 sh.y = clamp(sh.y + sh.vy * h, FIELD.y0, FIELD.y1);
86 const g = gateOf(s.field);
87 if ((py - g.y) * (sh.y - g.y) <= 0 && py !== sh.y) { // crossed the line of the wall
88 if (inWall(s.field, sh.x)) { sh.y = py; sh.vy = 0; } // stone: it slides along the wall
89 else if (py < g.y && Math.abs(sh.x - g.x) <= GATE_HALF) {
90 if (!sh.gated) { sh.gated = true; events.push({ type: 'gate', index: s.sheep.indexOf(sh) }); }
91 } else if (py > g.y) sh.gated = false; // back up the hill: it must come through again
92 }
93 if (!sh.penned && sh.y >= PEN.y0 && py < PEN.y0 && sh.x >= PEN.x0 && sh.x <= PEN.x1) {
94 sh.penned = true; sh.scored = sh.gated; // in over the top rail; only the gate makes it count
95 sh.vx = sh.vy = 0;
96 if (sh.scored) { s.total++; s.fieldScores[s.field]++; }
97 events.push({ type: 'penned', index: s.sheep.indexOf(sh), scored: sh.scored, total: s.total, field: s.field });
98 } else if (!sh.penned && inPen(sh.x, sh.y) && !inPen(px, py)) { sh.x = px; sh.vx = 0; } // hurdles on the sides
99 if (sh.penned) {
100 sh.x = clamp(sh.x, PEN.x0 + .5, PEN.x1 - .5); sh.y = clamp(sh.y, PEN.y0 + .8, PEN.y1 - .5);
101 }
102 }
103
104 function stepSheep(s, h, events) {
105 const loose = s.sheep.filter(sh => !sh.penned), dog = s.dog;
106 for (const sh of s.sheep) {
107 if (sh.penned) { // penned sheep only shuffle about
108 sh.heading += (rand(s) - .5) * WANDER_TURN * h * 4;
109 sh.vx = Math.cos(sh.heading) * WANDER_SPEED * .4; sh.vy = Math.sin(sh.heading) * WANDER_SPEED * .4;
110 moveSheep(s, sh, h, events);
111 continue;
112 }
113 let dx = sh.x - dog.x, dy = sh.y - dog.y, d = Math.hypot(dx, dy);
114 if (d < EPS) { dx = 0; dy = 1; d = EPS; }
115 const ax = dx / d, ay = dy / d; // away from the dog
116 if (sh.bolt <= 0 && d < BOLT_R) { // pushed too hard: it bolts the wrong way
117 const turn = rand(s) < .5 ? BOLT_TURN : -BOLT_TURN, c = Math.cos(turn), n = Math.sin(turn);
118 sh.bx = ax * c - ay * n; sh.by = ax * n + ay * c; sh.bolt = BOLT_TIME;
119 events.push({ type: 'bolt', index: s.sheep.indexOf(sh) });
120 }
121 let tx = 0, ty = 0;
122 if (sh.bolt > 0) {
123 sh.bolt -= h;
124 tx = sh.bx * BOLT_SPEED; ty = sh.by * BOLT_SPEED;
125 } else {
126 if (d < FLEE_R) { const f = FLEE_SPEED * (1 - d / FLEE_R) + .6; tx += ax * f; ty += ay * f; }
127 let cx = 0, cy = 0, n = 0;
128 for (const o of loose) {
129 if (o === sh) continue;
130 const ox = o.x - sh.x, oy = o.y - sh.y, od = Math.hypot(ox, oy);
131 if (od < SEPARATION && od > EPS) { tx -= ox / od * .8; ty -= oy / od * .8; }
132 if (od < COHESION_R) { cx += ox; cy += oy; n++; }
133 }
134 if (n) { const m = Math.hypot(cx, cy); if (m > SEPARATION) { tx += cx / m * COHESION_PULL; ty += cy / m * COHESION_PULL; } }
135 if (d >= FLEE_R) { // calm: wander
136 sh.heading += (rand(s) - .5) * WANDER_TURN * h * 6;
137 tx += Math.cos(sh.heading) * WANDER_SPEED; ty += Math.sin(sh.heading) * WANDER_SPEED;
138 }
139 }
140 const k = Math.min(1, h * ACCEL);
141 sh.vx += (tx - sh.vx) * k; sh.vy += (ty - sh.vy) * k;
142 moveSheep(s, sh, h, events);
143 }
144 }
145
146 function finish(s, reason, events) {
147 s.phase = 'over'; s.reason = reason; s.timer = 0; s.win = verdict(s.total) === 'win';
148 if (s.total > s.best) { s.best = s.total; s.record = true; }
149 events.push({ type: 'over', reason, total: s.total, win: s.win, record: s.record });
150 }
151 // move the dog and the flock over dt seconds
152 function advance(s, dt) {
153 const events = [];
154 dt = clamp(finite(dt), 0, .1);
155 if (s.phase !== 'play') { s.timer += dt; return events; }
156 for (let left = dt; left > EPS && s.phase === 'play'; left -= STEP) {
157 const h = Math.min(STEP, left);
158 moveDog(s, h);
159 stepSheep(s, h, events);
160 s.time = Math.max(0, s.time - h); s.elapsed += h;
161 if (s.sheep.every(sh => sh.penned)) {
162 events.push({ type: 'field', field: s.field, scored: s.fieldScores[s.field], total: s.total });
163 if (s.field + 1 >= FIELDS) finish(s, 'fields', events);
164 else { s.field++; startField(s); }
165 } else if (s.time <= 0) finish(s, 'dusk', events);
166 }
167 return events;
168 }
169 const again = (s, seed) => (s.phase === 'over' && s.timer > .6 ? newGame(s.best, seed == null ? s.seed + 1 : seed) : null);
170
171 const api = {
172 SHEEP, FIELDS, TOTAL, ROUND_TIME, WIN_AT, FIELD, PEN, GATES, GATE_HALF, WALL, DOG_SPEED, FLEE_R, FLEE_SPEED, BOLT_R, BOLT_SPEED,
173 BOLT_TIME, COHESION_R, WANDER_SPEED,
174 gateOf, wallsOf, inPen, scatter, newGame, aim, steer, advance, again, verdict,
175 };
176 if (typeof module !== 'undefined') module.exports = api; else root.Flock = api;
177 })(typeof window !== 'undefined' ? window : globalThis);
sheepdog/flock.test.mjs added +227
@@ -0,0 +1,227 @@
1 import { test, expect } from 'bun:test';
2 import {
3 SHEEP, FIELDS, TOTAL, ROUND_TIME, WIN_AT, FIELD, PEN, FLEE_R, BOLT_R, COHESION_R,
4 gateOf, wallsOf, scatter, newGame, aim, steer, advance, again, verdict,
5 } from './flock.js';
6
7 const DT = 1 / 30;
8 const run = (s, seconds, each) => { const out = []; for (let t = 0; t < seconds - 1e-9; t += DT) { each?.(s); out.push(...advance(s, DT)); } return out; };
9 const sheepAt = (s, spots) => { s.sheep.forEach((sh, i) => { Object.assign(sh, { x: spots[i][0], y: spots[i][1], vx: 0, vy: 0, bolt: 0 }); }); };
10 const far = (s, from = 0) => { for (let i = from; i < SHEEP; i++) Object.assign(s.sheep[i], { x: -11 + i * .2, y: -16, vx: 0, vy: 0 }); };
11
12 test('five sheep start scattered at the top, and the scatter is new for each field and the same for a seed', () => {
13 expect(SHEEP).toBe(5);
14 const a = scatter(0, 1), b = scatter(1, 1);
15 expect(a.length).toBe(5);
16 for (const p of a) { expect(p.y).toBeLessThan(-9); expect(p.x).toBeGreaterThanOrEqual(-9); expect(p.x).toBeLessThanOrEqual(9); }
17 expect(b).not.toEqual(a);
18 expect(scatter(0, 1)).toEqual(a);
19 expect(scatter(0, 2)).not.toEqual(a);
20 expect(newGame(0, 1).sheep.map(s => [s.x, s.y])).toEqual(a.map(p => [p.x, p.y]));
21 });
22
23 test('the gate moves from field to field and sits about halfway down', () => {
24 const xs = [0, 1, 2].map(f => gateOf(f).x);
25 expect(new Set(xs).size).toBe(3);
26 for (let f = 0; f < FIELDS; f++) expect(Math.abs(gateOf(f).y)).toBeLessThan(4);
27 });
28
29 test('a sheep flees the dog inside the radius and ignores it outside', () => {
30 const s = newGame(0, 1);
31 sheepAt(s, [[0, -8], [10, -16], [10, -15], [-10, -16], [-10, -15]]);
32 s.dog = { x: 0, y: -8 - (FLEE_R - 2) }; // 4 units above it, inside the radius
33 run(s, 1);
34 expect(s.sheep[0].y).toBeGreaterThan(-8 + .5); // pushed downhill, away from the dog
35 const t = newGame(0, 1);
36 sheepAt(t, [[0, -8], [10, -16], [10, -15], [-10, -16], [-10, -15]]);
37 t.dog = { x: 0, y: -8 - (FLEE_R + 3) };
38 const calm = run(t, 1);
39 expect(Math.hypot(t.sheep[0].x, t.sheep[0].y + 8)).toBeLessThan(1.6); // only a wander
40 expect(calm.some(e => e.type === 'bolt')).toBe(false);
41 });
42
43 test('sheep flock towards each other', () => {
44 const s = newGame(0, 1);
45 sheepAt(s, [[-2.5, -3], [2.5, -3], [10, -16], [-10, -16], [10, -14]]);
46 s.dog = { x: 0, y: 14 };
47 const gap = () => Math.abs(s.sheep[0].x - s.sheep[1].x);
48 const before = gap();
49 run(s, 3);
50 expect(before).toBeLessThan(COHESION_R);
51 expect(gap()).toBeLessThan(before - 1);
52 });
53
54 test('calm sheep wander, and the same seed wanders the same way', () => {
55 const a = newGame(0, 5), b = newGame(0, 5), c = newGame(0, 6);
56 for (const s of [a, b, c]) s.dog = { x: 11, y: 16 };
57 const start = a.sheep.map(sh => [sh.x, sh.y]);
58 run(a, 4); run(b, 4); run(c, 4);
59 expect(a.sheep.some((sh, i) => Math.hypot(sh.x - start[i][0], sh.y - start[i][1]) > .5)).toBe(true);
60 expect(a.sheep.map(sh => [sh.x, sh.y])).toEqual(b.sheep.map(sh => [sh.x, sh.y]));
61 expect(c.sheep.map(sh => [sh.x, sh.y])).not.toEqual(a.sheep.map(sh => [sh.x, sh.y]));
62 });
63
64 test('a sheep pushed hard enough bolts the wrong way, back past the dog', () => {
65 const s = newGame(0, 1);
66 sheepAt(s, [[0, 0], [10, -16], [10, -15], [-10, -16], [-10, -15]]);
67 s.dog = { x: 0, y: -(BOLT_R - .5) }; // right on top of it, uphill
68 const ev = run(s, .3);
69 expect(ev.some(e => e.type === 'bolt' && e.index === 0)).toBe(true);
70 const away = { x: 0, y: 1 }, sh = s.sheep[0];
71 expect(sh.bx * away.x + sh.by * away.y).toBeLessThan(0); // its bolt runs against "away from the dog"
72 expect(sh.bolt).toBeGreaterThan(0);
73 });
74
75 test('a dog held behind the flock drives it downhill and through the gate', () => {
76 for (const field of [0, 1, 2]) {
77 const s = newGame(0, 3);
78 s.field = field;
79 const g = gateOf(field);
80 sheepAt(s, [[g.x - 1.2, g.y - 9], [g.x + 1.2, g.y - 9], [g.x, g.y - 10.5], [g.x - .6, g.y - 12], [g.x + .6, g.y - 12]]);
81 s.dog = { x: g.x, y: g.y - 16 };
82 const gated = new Set();
83 let done = false;
84 for (let i = 0; i < 25 * 30 && !done; i++) {
85 const loose = s.sheep.filter(sh => !sh.penned);
86 const cx = loose.reduce((a, sh) => a + sh.x, 0) / loose.length, cy = loose.reduce((a, sh) => a + sh.y, 0) / loose.length;
87 const goal = loose.every(sh => sh.gated) ? { x: 0, y: PEN.y0 + 2 } : g; // the gate first, then the pen
88 const dx = cx - goal.x, dy = cy - goal.y, n = Math.hypot(dx, dy) || 1;
89 aim(s, cx + dx / n * 4.5, cy + dy / n * 4.5); // held behind the flock, on the line to the goal
90 for (const e of advance(s, DT)) { if (e.type === 'gate') gated.add(e.index); if (e.type === 'field') done = true; }
91 }
92 expect(done).toBe(true); // all five penned before the round ran out
93 expect(gated.size).toBeGreaterThanOrEqual(4);
94 }
95 });
96
97 test('a sheep through the gate and then into the pen scores; one that goes round the gate scores nothing', () => {
98 const s = newGame(0, 1);
99 const g = gateOf(0), [left] = wallsOf(0);
100 sheepAt(s, [[g.x, g.y - .4], [left[0] - 1.5, g.y - .4], [10, -16], [-10, -16], [-10, -15]]);
101 s.dog = { x: 11, y: 16 };
102 s.sheep[0].vy = 3; s.sheep[1].vy = 3;
103 run(s, .4);
104 expect(s.sheep[0].gated).toBe(true);
105 expect(s.sheep[1].gated).toBe(false);
106 // both reach the mouth of the pen
107 Object.assign(s.sheep[0], { x: 0, y: PEN.y0 - .2, vx: 0, vy: 4 });
108 Object.assign(s.sheep[1], { x: 0, y: PEN.y0 - .2, vx: 0, vy: 4 });
109 const ev = run(s, .5).filter(e => e.type === 'penned');
110 expect(ev).toEqual([expect.objectContaining({ index: 0, scored: true }), expect.objectContaining({ index: 1, scored: false })]);
111 expect(s.total).toBe(1);
112 expect(s.fieldScores[0]).toBe(1);
113 });
114
115 test('the wall stops a sheep, and a sheep that comes back up the hill must pass the gate again', () => {
116 const s = newGame(0, 1);
117 const g = gateOf(0), [, right] = wallsOf(0);
118 sheepAt(s, [[right[0] + 1, g.y - .3], [g.x, g.y + .2], [10, -16], [-10, -16], [-10, -15]]);
119 s.dog = { x: 11, y: 16 };
120 s.sheep[0].vy = 4; s.sheep[1].gated = true; s.sheep[1].vy = -4;
121 run(s, .3);
122 expect(s.sheep[0].y).toBeLessThan(g.y); // held by stone
123 expect(s.sheep[1].gated).toBe(false);
124 });
125
126 test('the pen has hurdles on its sides: a sheep cannot walk in from beside it', () => {
127 const s = newGame(0, 1);
128 sheepAt(s, [[PEN.x1 + .3, PEN.y0 + 1], [10, -16], [10, -15], [-10, -16], [-10, -15]]);
129 s.dog = { x: 11, y: 16 };
130 s.sheep[0].vx = -4;
131 run(s, .3);
132 expect(s.sheep[0].penned).toBe(false);
133 expect(s.sheep[0].x).toBeGreaterThan(PEN.x1);
134 });
135
136 test('the round lasts 90 seconds, the sun lowers with it, and dusk ends the game', () => {
137 expect(ROUND_TIME).toBe(90);
138 const s = newGame(0, 1);
139 s.dog = { x: 11, y: 16 };
140 run(s, 30);
141 expect(s.time).toBeCloseTo(60, 0);
142 expect(s.phase).toBe('play');
143 const ev = run(s, 61);
144 expect(s.phase).toBe('over');
145 expect(s.time).toBe(0);
146 expect(ev.at(-1)).toMatchObject({ type: 'over', reason: 'dusk' });
147 });
148
149 test('one game is three fields: filling a pen brings a new scatter and a moved gate', () => {
150 const s = newGame(0, 1);
151 const before = s.sheep.map(sh => [sh.x, sh.y]);
152 s.sheep.forEach(sh => { sh.penned = true; sh.scored = true; sh.gated = true; });
153 s.total = 5; s.fieldScores[0] = 5;
154 const ev = advance(s, DT);
155 expect(ev.some(e => e.type === 'field')).toBe(true);
156 expect(s.field).toBe(1);
157 expect(s.sheep.map(sh => [sh.x, sh.y])).not.toEqual(before);
158 expect(s.sheep.every(sh => !sh.penned)).toBe(true);
159 expect(gateOf(s.field)).not.toEqual(gateOf(0));
160 expect(s.total).toBe(5);
161 for (let k = 0; k < 2; k++) { s.sheep.forEach(sh => { sh.penned = true; }); advance(s, DT); }
162 expect(s.phase).toBe('over');
163 expect(s.reason).toBe('fields');
164 });
165
166 test('the win line is 10 of 15 sheep and the loss line is anything below', () => {
167 expect(TOTAL).toBe(15);
168 expect(WIN_AT).toBe(10);
169 expect(verdict(10)).toBe('win');
170 expect(verdict(15)).toBe('win');
171 expect(verdict(9)).toBe('loss');
172 expect(verdict(0)).toBe('loss');
173 for (const [total, win] of [[10, true], [9, false]]) {
174 const s = newGame(0, 1);
175 s.total = total; s.time = DT / 2;
176 s.dog = { x: 11, y: 16 };
177 const ev = advance(s, DT);
178 expect(ev.at(-1)).toMatchObject({ type: 'over', win, total });
179 expect(s.win).toBe(win);
180 }
181 });
182
183 test('a best is kept only when beaten, and a finished game can be played again after a beat', () => {
184 const s = newGame(7, 1);
185 s.total = 8; s.time = .01;
186 advance(s, DT);
187 expect(s.record).toBe(true);
188 expect(s.best).toBe(8);
189 expect(again(s)).toBeNull();
190 run(s, 1);
191 const next = again(s);
192 expect(next.phase).toBe('play');
193 expect(next.best).toBe(8);
194 expect(next.total).toBe(0);
195 const t = newGame(12, 1);
196 t.total = 8; t.time = .01;
197 advance(t, DT);
198 expect(t.record).toBe(false);
199 expect(t.best).toBe(12);
200 });
201
202 test('the dog follows the arrow keys and a dragged target at its top speed, inside the field', () => {
203 const s = newGame(0, 1);
204 far(s);
205 s.dog = { x: 0, y: 0 };
206 steer(s, 1, 0);
207 run(s, 1);
208 expect(s.dog.x).toBeGreaterThan(8);
209 expect(s.dog.x).toBeLessThan(10);
210 steer(s, 0, 0);
211 aim(s, -5, 0);
212 run(s, 3);
213 expect(s.dog.x).toBeCloseTo(-5, 3);
214 aim(s, 1e9, NaN);
215 steer(s, 1, 1);
216 run(s, 10);
217 expect(s.dog.x).toBe(FIELD.x1);
218 expect(s.dog.y).toBe(FIELD.y1);
219 });
220
221 test('odd input never breaks the state', () => {
222 const s = newGame(NaN, NaN);
223 steer(s, NaN, Infinity);
224 expect(() => advance(s, NaN)).not.toThrow();
225 expect(() => advance(s, -5)).not.toThrow();
226 expect(Number.isFinite(s.dog.x)).toBe(true);
227 });
sheepdog/index.html added +372
@@ -0,0 +1,372 @@
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>Sheepdog</title>
7 <!-- og:begin -->
8 <meta name="description" content="Drag the dog to steer five sheep through the gate and into the pen before dusk">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/sheepdog/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Sheepdog">
13 <meta property="og:description" content="Drag the dog to steer five sheep through the gate and into the pen before dusk">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/sheepdog/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/sheepdog.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="Sheepdog: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #5b8a3a; }
24 * { box-sizing: border-box; }
25 html, body { -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent; height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
27 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
28 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; }
29 .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; }
30 #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; }
31 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
32 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
33 .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; }
34 .row span { color: var(--muted); }
35 #status { color: var(--muted); min-height: 1.35em; }
36 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
37 button:hover, button:focus-visible { color: var(--ink); }
38 </style>
39 </head>
40 <body>
41 <div id="stage"><canvas id="c" tabindex="0" aria-label="A hillside pasture of dry-stone walls with a gate halfway down and a hurdle pen at the bottom, five sheep scattered at the top and a sheepdog. Drag on the canvas, or press the arrow keys, to run the dog: sheep flee the dog inside a short radius, flock together and wander when calm, and one pushed too hard bolts the wrong way. Drive them through the gate and then into the pen before the sun sets; a sheep that goes round the gate scores nothing. Three fields, 90 seconds, and ten or more of fifteen sheep wins."></canvas></div>
42 <div id="scores">
43 <div class="row"><b id="field">1</b><span>of 3 fields</span></div>
44 <div class="row"><b id="penned">0</b><span>of 5 penned</span></div>
45 <div class="row"><b id="time">90</b><span>seconds left</span></div>
46 <div class="row"><b id="total">0</b><span>of 15 in all</span></div>
47 <div class="row"><b id="best">0</b><span>best</span></div>
48 </div>
49 <div class="hud" id="bottom">
50 <div id="status" role="status" aria-live="polite"></div>
51 <button id="mute" type="button" aria-pressed="false">sound on</button>
52 </div>
53 <script src="../shell.js"></script>
54 <script>
55 PixelPlays.mount({
56 id: 'sheepdog',
57 rules: [
58 'Drag, or press the arrow keys, to run the dog. Sheep flee it, flock together and wander when calm; push one hard and it bolts.',
59 'Each sheep that goes through the gate and then into the pen scores. Round the gate scores nothing.',
60 'Three fields, 90 seconds in all as the sun lowers. Ten or more of fifteen wins.',
61 ],
62 });
63 </script>
64 <script>window.PP_SCENE = { originY: 0, shadowX: 1.3, shadowY: -.12 };</script>
65 <script src="../engine.js"></script>
66 <script src="flock.js"></script>
67 <script>
68 'use strict';
69
70 const K = .8; // field units to world units; field x runs across (screen right-up), field y runs downhill (screen right-down)
71 const BEST_KEY = 'pixel-plays-sheepdog-best';
72 const WOOL = [236, 232, 220], WOOL_STAINED = [172, 156, 130], FACE = [58, 50, 48];
73 const FUR = [40, 38, 46], BLAZE = [244, 242, 236], TONGUE = [210, 90, 90];
74 const STONE = [[158, 152, 142], [132, 128, 122], [176, 168, 154], [120, 116, 112]];
75 const WOOD = [168, 118, 70], WOOD_DARK = [112, 76, 46], CREAM = [236, 226, 200], STRAW = [200, 170, 96], CROW = [30, 30, 40];
76 const SUN_TOP = [255, 232, 140], SUN_LOW = [236, 112, 56];
77 const world = (fx, fy) => [K * fy, -K * fx];
78 const screenOf = (fx, fy) => { const [x, y] = world(fx, fy), p = project(x, y, 0); return [p.sx, p.sy]; };
79 const fieldOf = (sx, sy) => { const g = unproject(sx, sy); return { x: -g.y / K, y: g.x / K }; };
80
81 /* ---------- state ---------- */
82 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
83 let R = Flock.newGame(best0, Date.now() & 0xffff);
84 const G = { time: 0, status: '', noteUntil: 0, keys: new Set(), facing: [], dogFace: 0, dogAt: {} };
85 const nodes = {};
86 for (const id of ['field', 'penned', 'time', 'total', 'best', 'status']) nodes[id] = document.getElementById(id);
87 function renderHud() {
88 nodes.field.textContent = R.field + 1;
89 nodes.penned.textContent = R.fieldScores[R.field];
90 nodes.time.textContent = Math.ceil(R.time);
91 nodes.total.textContent = R.total;
92 nodes.best.textContent = R.best;
93 }
94 function setStatus(text) {
95 if (text === G.status) return;
96 G.status = text;
97 nodes.status.textContent = text;
98 }
99 function note(text) { setStatus(text); G.noteUntil = G.time + 2.4; }
100 const HINT = 'drag or arrow keys to run the dog · gate first, then the pen';
101
102 /* ---------- baked field: grass, walls, gate, pen ---------- */
103 function groundColor(ix, iy, i) {
104 const f = fieldOf(ix + .5, iy + .5), fx = f.x, fy = f.y;
105 const edge = Math.pow(Math.pow(Math.abs(fx) / 13, 10) + Math.pow(Math.abs(fy) / 18.5, 10), .1);
106 const rough = edge + (noise(fx * .5, fy * .5) - .5) * .06;
107 if (rough > 1.04) return 0;
108 if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0;
109 const { PEN } = Flock;
110 if (fx >= PEN.x0 - .2 && fx <= PEN.x1 + .2 && fy >= PEN.y0 && fy <= PEN.y1 + 1) {
111 const t = .85 + hash(ix, iy) * .3;
112 return rgb(STRAW[0] * t, STRAW[1] * t, STRAW[2] * t);
113 }
114 kinds[i] = KIND_GRASS;
115 const t = noise(fx * .22, fy * .22) * .9 + (hash(ix, iy) - .5) * .5 + (1 - (fy + 18) / 36) * .5 - .12; // lighter up the hill
116 return rgb(...GRASS[clamp(Math.floor(t * 4), 0, 4)]);
117 }
118 function wall(field) {
119 const g = Flock.gateOf(field), x = K * g.y;
120 Flock.wallsOf(field).forEach(([a, b], side) => {
121 for (const course of [0, 1]) {
122 let fx = a - course * .3, n = 0;
123 while (fx < b) {
124 const len = .5 + hash(n + side * 31, course + field * 7) * .35, lo = Math.max(fx, a), hi = Math.min(fx + len, b);
125 if (hi - lo > .1) {
126 const colour = STONE[(n * 3 + course + side) % STONE.length], h = course ? .72 : .4;
127 box(x - .25 + course * .03, -K * hi + .015, course ? .4 : 0, x + .25 - course * .03, -K * lo - .015, h + hash(n, side) * .06, colour, n + course * 50);
128 }
129 fx += len; n++;
130 }
131 }
132 for (let fx = a; fx <= b; fx += .35) { const [wx, wy] = world(fx, g.y); castShadow(wx, wy, .35, .3, 1, 0); castShadow(wx, wy, .7, .25, 1, 0); }
133 });
134 for (const px of [g.x - Flock.GATE_HALF, g.x + Flock.GATE_HALF]) { // gate posts, with a pale cap
135 const [wx, wy] = world(px, g.y);
136 capsule([wx, wy, 0], [wx, wy, 1.25], .11, .1, () => WOOD, 'rough');
137 sphere(wx, wy, 1.32, .14, CREAM, 'solid');
138 for (let z = .2; z < 1.2; z += .3) castShadow(wx, wy, z, .12, 1, 0);
139 }
140 }
141 function hurdles() {
142 const { PEN } = Flock;
143 const run = (a, b) => { // a hurdle from field point a to b: posts every ~.9 and two rails
144 const n = Math.max(1, Math.round(Math.hypot(b[0] - a[0], b[1] - a[1]) / .9));
145 for (let k = 0; k <= n; k++) {
146 const [wx, wy] = world(a[0] + (b[0] - a[0]) * k / n, a[1] + (b[1] - a[1]) * k / n);
147 capsule([wx, wy, 0], [wx, wy, .78], .06, .06, () => WOOD_DARK, 'rough');
148 castShadow(wx, wy, .5, .1, 1, 0);
149 }
150 for (const z of [.28, .6]) {
151 const [x0, y0] = world(...a), [x1, y1] = world(...b);
152 capsule([x0, y0, z], [x1, y1, z], .035, .035, () => WOOD, 'rough');
153 const m = Math.ceil(Math.hypot(x1 - x0, y1 - y0) / .3);
154 for (let k = 0; k <= m; k++) castShadow(x0 + (x1 - x0) * k / m, y0 + (y1 - y0) * k / m, z, .08, 1, 0);
155 }
156 };
157 run([PEN.x0, PEN.y0], [PEN.x0, PEN.y1]);
158 run([PEN.x1, PEN.y0], [PEN.x1, PEN.y1]);
159 run([PEN.x0, PEN.y1], [PEN.x1, PEN.y1]);
160 }
161 function bake() {
162 tufts.length = 0;
163 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
164 zb.fill(-1e9);
165 pix.fill(rgb(255, 255, 255));
166 for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) {
167 const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(ix, iy, i);
168 if (!c) continue;
169 pix[i] = c; ground[i] = 1;
170 zb[i] = (g.x + g.y) / R2 * COS;
171 }
172 growGrass();
173 groundZ.set(zb);
174 wall(R.field);
175 hurdles();
176 bakeOcclusion();
177 staticShadow.set(shadowMask);
178 applyShadows(groundZ);
179 bakedPix.set(pix);
180 bakedZ.set(zb);
181 }
182
183 /* ---------- figures ---------- */
184 function turn(i, vx, vy) { // keep the way a sheep last moved, in world terms
185 if (Math.hypot(vx, vy) > .35) G.facing[i] = Math.atan2(-vx * K, vy * K);
186 return G.facing[i] || 0;
187 }
188 function sheep(sh, i) {
189 const [x, y] = world(sh.x, sh.y), a = turn(i, sh.vx, sh.vy), fx = Math.cos(a), fy = Math.sin(a);
190 const wool = sh.penned && !sh.scored ? WOOL_STAINED : WOOL;
191 sphere(x, y, .46, .4, wool, 'rough');
192 sphere(x - fx * .12, y - fy * .12 + .0, .62, .3, wool, 'rough');
193 sphere(x + fx * .44, y + fy * .44, .5, .17, FACE, 'solid');
194 for (const s of [-1, 1]) capsule([x + fx * .18 - fy * s * .18, y + fy * .18 + fx * s * .18, 0], [x + fx * .18 - fy * s * .18, y + fy * .18 + fx * s * .18, .22], .05, .05, () => FACE, 'solid');
195 castShadow(x, y, .5, .42, 1, 0);
196 castShadow(x, y, .15, .3, 1, 0);
197 }
198 function dog(d) {
199 const [x, y] = world(d.x, d.y);
200 const gx = x - G.dogAt.wx, gy = y - G.dogAt.wy;
201 if (Math.hypot(gx, gy) > .02) G.dogFace = Math.atan2(gy, gx);
202 G.dogAt.wx = x; G.dogAt.wy = y;
203 const fx = Math.cos(G.dogFace), fy = Math.sin(G.dogFace), run = Math.floor(G.time * 8) & 1;
204 const P = (a, z) => [x + fx * a, y + fy * a, z];
205 capsule(P(-.5, .5), P(.3, .52), .21, .24, () => FUR, 'solid');
206 sphere(...P(.3, .56), .25, BLAZE, 'solid');
207 capsule(P(-.5, .5), P(-.95, .62 + run * .06), .1, .06, () => FUR, 'solid'); // tail
208 sphere(...P(-.97, .64 + run * .06), .07, BLAZE, 'solid');
209 sphere(...P(.62, .72), .2, FUR, 'solid');
210 sphere(...P(.8, .66), .11, BLAZE, 'solid');
211 sphere(x + fx * .62 - fy * .15, y + fy * .62 + fx * .15, .9, .08, FUR, 'solid'); // ears
212 sphere(x + fx * .62 + fy * .15, y + fy * .62 - fx * .15, .9, .08, FUR, 'solid');
213 for (const [a, s] of [[.25, 1], [.25, -1], [-.4, 1], [-.4, -1]]) {
214 const lift = (a > 0) === !!run ? .08 : 0;
215 capsule([x + fx * (a + lift) - fy * s * .14, y + fy * (a + lift) + fx * s * .14, .35], [x + fx * a - fy * s * .14, y + fy * a + fx * s * .14, .02], .06, .05, () => FUR, 'solid');
216 }
217 castShadow(x, y, .55, .5, 1, 0);
218 castShadow(x + fx * .6, y + fy * .6, .6, .22, 1, 0);
219 }
220 // a crow on the wall nearest the gate: it shifts and dips its head, and sits still under reduced motion
221 function crow(t) {
222 const [a, b] = Flock.wallsOf(R.field)[0], g = Flock.gateOf(R.field), fx = Math.max(a + .5, b - 1.4);
223 const [x, y] = world(fx, g.y), beat = STILL ? 0 : Math.floor(t * 2) % 7, dip = beat === 1 || beat === 2, hop = beat === 4 ? .08 : 0;
224 sphere(x, y, .95 + hop, .15, CROW, 'solid');
225 sphere(x, y - .09, 1.08 + hop - (dip ? .13 : 0), .09, CROW, 'solid');
226 capsule([x, y + .05, .95 + hop], [x - .3, y + .15, .88 + hop - (beat === 3 ? .05 : 0)], .06, .03, () => CROW, 'solid');
227 castShadow(x, y, 1, .16, 1, 0);
228 }
229 function sun() { // the clock: it sinks and reddens as the 90 seconds run out
230 const f = 1 - R.time / Flock.ROUND_TIME, cx = 36, cy = 22 + f * 62, r = 8;
231 const c = SUN_TOP.map((v, k) => v + (SUN_LOW[k] - v) * f), lit = rgb(...c), dim = rgb(c[0] * .86, c[1] * .84, c[2] * .8);
232 for (let iy = -r; iy <= r; iy++) for (let ix = -r; ix <= r; ix++) {
233 const d = ix * ix + iy * iy;
234 if (d > r * r) continue;
235 const x = Math.round(cx) + ix, y = Math.round(cy) + iy;
236 if (x >= 0 && y >= 0 && x < W && y < H) pix[y * W + x] = d > r * r * .55 && bayerAt(x, y) < .5 ? dim : lit;
237 }
238 }
239 function draw() {
240 pix.set(bakedPix);
241 zb.set(bakedZ);
242 pendingShadows.length = 0;
243 const windT = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS;
244 R.sheep.forEach(sheep);
245 dog(R.dog);
246 crow(G.time);
247 drawTufts(windT);
248 flushShadows();
249 applyShadows(bakedZ);
250 shadeEdges();
251 sun();
252 ctx.putImageData(image, 0, 0);
253 }
254
255 /* ---------- game ---------- */
256 function act(events) {
257 for (const e of events) {
258 if (e.type === 'penned') {
259 if (e.scored) { note(`penned · ${e.total} of 15`); sound('chime'); } else { note('round the gate · no score'); sound('buzz'); }
260 } else if (e.type === 'bolt') { sound('bleat'); note('too close: it bolted'); }
261 else if (e.type === 'field') {
262 bake();
263 G.facing.length = 0; G.dogAt.wx = undefined; G.dogAt.wy = undefined;
264 if (R.phase === 'play') note(`field ${R.field + 1} of 3 · the gate has moved`);
265 } else if (e.type === 'over') {
266 if (R.record) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: keep it for this visit */ }
267 const tail = `${R.record ? ' · new best' : ` · best ${R.best}`} · tap or press space to play again`;
268 setStatus(R.win ? `the flock is home · ${R.total} of 15${tail}` : `dusk falls · ${R.total} of 15, ten wins${tail}`);
269 sound(R.win ? 'chime' : 'buzz');
270 }
271 }
272 renderHud();
273 }
274 function restart() {
275 const next = Flock.again(R);
276 if (!next) return false;
277 R = next;
278 G.facing.length = 0; G.dogAt.wx = undefined; G.dogAt.wy = undefined;
279 bake();
280 note(HINT);
281 renderHud();
282 return true;
283 }
284 // arrow keys in screen terms: right is field (+x,+y), up is (+x,-y)
285 const KEYMAP = { ArrowLeft: 'left', a: 'left', A: 'left', ArrowRight: 'right', d: 'right', D: 'right', ArrowUp: 'up', w: 'up', W: 'up', ArrowDown: 'down', s: 'down', S: 'down' };
286 function update(dt) {
287 G.time += dt;
288 if (R.phase === 'play') {
289 const h = (G.keys.has('right') ? 1 : 0) - (G.keys.has('left') ? 1 : 0), v = (G.keys.has('down') ? 1 : 0) - (G.keys.has('up') ? 1 : 0);
290 Flock.steer(R, h - v, h + v);
291 }
292 act(Flock.advance(R, dt));
293 if (R.phase === 'play' && G.time >= G.noteUntil) setStatus(`${R.sheep.filter(s => s.penned).length} of 5 in the pen · ${R.sheep.filter(s => !s.penned && Math.hypot(s.x - R.dog.x, s.y - R.dog.y) < Flock.FLEE_R).length} on the run`);
294 }
295
296 /* ---------- input ---------- */
297 function pointTo(e) {
298 const r = canvas.getBoundingClientRect(), f = fieldOf((e.clientX - r.left) / (r.width || W) * W, (e.clientY - r.top) / (r.height || H) * H);
299 Flock.aim(R, f.x, f.y);
300 }
301 let dragging = null;
302 canvas.addEventListener('pointerdown', e => {
303 ensureAudio();
304 canvas.focus({ preventScroll: true });
305 if (restart()) return;
306 dragging = e.pointerId;
307 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
308 G.keys.clear();
309 pointTo(e);
310 });
311 canvas.addEventListener('pointermove', e => { if (dragging === e.pointerId) pointTo(e); });
312 for (const type of ['pointerup', 'pointercancel']) canvas.addEventListener(type, e => { if (dragging === e.pointerId) dragging = null; });
313 canvas.addEventListener('keydown', e => {
314 const k = KEYMAP[e.key];
315 if (!k && e.key !== ' ' && e.key !== 'Enter') return;
316 e.preventDefault();
317 ensureAudio();
318 if (e.repeat) return;
319 if (restart()) return;
320 if (k) { dragging = null; G.keys.add(k); }
321 });
322 canvas.addEventListener('keyup', e => { const k = KEYMAP[e.key]; if (k) G.keys.delete(k); });
323 canvas.addEventListener('blur', () => { G.keys.clear(); dragging = null; });
324
325 /* ---------- sound ---------- */
326 let audio = null, muted = false;
327 function ensureAudio() {
328 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
329 const AC = window.AudioContext || window.webkitAudioContext;
330 if (AC) audio = new AC();
331 }
332 function sound(kind) {
333 if (!audio || muted) return;
334 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
335 const spec = {
336 chime: [520, 880, .22, .07, 'sine'],
337 buzz: [160, 70, .3, .06, 'sawtooth'],
338 bleat: [380, 300, .18, .05, 'triangle'],
339 }[kind];
340 osc.type = spec[4];
341 osc.frequency.setValueAtTime(spec[0], now);
342 osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]);
343 gain.gain.setValueAtTime(spec[3], now);
344 gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]);
345 osc.connect(gain).connect(audio.destination);
346 osc.start(now); osc.stop(now + spec[2] + .01);
347 }
348 const muteButton = document.getElementById('mute');
349 muteButton.addEventListener('click', () => {
350 muted = !muted;
351 muteButton.textContent = muted ? 'sound off' : 'sound on';
352 muteButton.setAttribute('aria-pressed', String(muted));
353 });
354
355 /* ---------- fit and boot ---------- */
356 addEventListener('resize', fit);
357 fit();
358 bake();
359 note(HINT);
360 renderHud();
361 canvas.focus({ preventScroll: true });
362 let last = performance.now();
363 function frame(now) {
364 update(Math.min(.04, (now - last) / 1000));
365 last = now;
366 draw();
367 requestAnimationFrame(frame);
368 }
369 requestAnimationFrame(frame);
370 </script>
371 </body>
372 </html>
sheepdog/page.test.mjs added +39
@@ -0,0 +1,39 @@
1 import { readFileSync, readdirSync } from 'node:fs';
2 import { test, expect } from 'bun:test';
3 import { boot } from '../playtest.mjs';
4
5 const state = g => g.read('R');
6
7 test('the page shows field, penned, time, total and best, and dragging runs the dog', () => {
8 const g = boot('sheepdog');
9 g.run(.5);
10 expect(String(g.el('field').textContent)).toBe('1');
11 expect(String(g.el('penned').textContent)).toBe('0');
12 expect(Number(g.el('time').textContent)).toBeLessThanOrEqual(90);
13 expect(String(g.el('total').textContent)).toBe('0');
14 expect(String(g.el('best').textContent)).toBe('0');
15 const from = state(g).dog.x, [sx, sy] = g.read('screenOf(-8, -4)');
16 g.drag([180, 140], [sx, sy], .8);
17 expect(state(g).dog.x).toBeLessThan(from - 3);
18 expect(g.errors).toEqual([]);
19 });
20
21 test('the arrow keys run the dog in screen directions', () => {
22 const g = boot('sheepdog');
23 const sx = () => g.read('screenOf(R.dog.x, R.dog.y)');
24 const [x0, y0] = sx();
25 g.keyDown('ArrowRight'); g.run(.6); g.keyUp('ArrowRight'); g.run(.1);
26 const [x1] = sx();
27 expect(x1).toBeGreaterThan(x0 + 10);
28 g.keyDown('ArrowUp'); g.run(.6); g.keyUp('ArrowUp'); g.run(.1);
29 const [, y2] = sx();
30 expect(y2).toBeLessThan(y0 - 4);
31 expect(g.errors).toEqual([]);
32 });
33
34 test('the page has a mute button, says how to play on the canvas and ships no track', () => {
35 const html = readFileSync(new URL('./index.html', import.meta.url), 'utf8');
36 expect(html).toContain('id="mute"');
37 expect(html).toMatch(/<canvas id="c"[^>]*aria-label="[^"]*Drag[^"]*arrow keys/);
38 expect(readdirSync(import.meta.dir).filter(f => f.endsWith('.mp3'))).toEqual([]);
39 });
shell.js +1
@@ -35,6 +35,7 @@ window.PixelPlays = (() => {
3535 { id: 'espresso-bar', title: 'Espresso Bar', blurb: 'Pour twenty coffees to the line as cups slide past: hold to pour, let go early, over the brim costs a life', kind: 'Precision', input: 'Hold', accent: '#6f4a33', music: false, forged: true },
3636 { id: 'goalkeeper', title: 'Goalkeeper', blurb: 'Read the taker and dive left or right to save ten penalties', kind: 'Sport', input: 'Tap', accent: '#3f7a3a', music: false, forged: true },
3737 { id: 'soapbox-derby', title: 'Soapbox Derby', blurb: 'Steer a wooden cart down a cobbled hill between the hay bales, fastest time wins', kind: 'Racing', input: 'Drag', accent: '#b5562b', music: false, forged: true },
38 { id: 'sheepdog', title: 'Sheepdog', blurb: 'Drag the dog to steer five sheep through the gate and into the pen before dusk', kind: 'Catching', input: 'Drag', accent: '#5b8a3a', music: false, forged: true },
3839 { id: 'firefly-jar', title: 'Firefly Jar', blurb: 'Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern', kind: 'Catching', input: 'Tap', accent: '#c9b43a', music: false, forged: true },
3940 ];
4041 const MUSIC_VOLUME = .4;
signal-box/page.test.mjs +1 −2
@@ -1,9 +1,8 @@
1 import vm from 'node:vm';
21 import { test, expect } from 'bun:test';
32 import { boot } from '../playtest.mjs';
43
54 // the five levers stand at x = 120, 165, 210, 255 and 300 on the 360-wide canvas
6 const state = g => vm.runInContext('P', g.window);
5 const state = g => g.read('P');
76 const X = lever => 120 + lever * 45;
87 function untilTurn(g) { for (let n = 0; state(g).phase !== 'input' && n < 400; n++) g.run(.05); expect(state(g).phase).toBe('input'); }
98
soapbox-derby/page.test.mjs +1 −2
@@ -1,8 +1,7 @@
1 import vm from 'node:vm';
21 import { test, expect } from 'bun:test';
32 import { boot } from '../playtest.mjs';
43
5 const state = g => vm.runInContext('R', g.window);
4 const state = g => g.read('R');
65
76 test('dragging steers the cart and the HUD follows the run', () => {
87 const g = boot('soapbox-derby');

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs