Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Add Firefly Jar: tap the glowing fireflies into a jar on a summer night before the moths put the lantern out #90
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/68-add-firefly-jar-tap-the-glowing-fireflie → main 3 commits fork 2 threads · 2 unresolved
11 files
changed +755
−2
README.md +2 −1
| @@ -41,6 +41,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am | ||
| 41 | 41 | | [](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 | |
| 42 | 42 | | [](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 | |
| 43 | 43 | | [](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 | | [](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 | | |
| 44 | 45 | |
| 45 | 46 | ## Run |
| 46 | 47 | Requires [](https://nodejs.org/); nothing to install. |
| @@ -60,7 +61,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is | ||
| 60 | 61 | 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. |
| 61 | 62 | |
| 62 | 63 | ## Add a game |
| 63 | 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 and Soapbox Derby 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`. | |
| 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`. | |
| 64 | 65 | |
| 65 | 66 | - `shell.js` provides the game menu, the Rules popup, the credits and the background music. |
| 66 | 67 | - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals. |
bell-tower/page.test.mjs +1 −1
| @@ -17,4 +17,4 @@ test('the HUD peal length follows the peal the tower is ringing', () => { | ||
| 17 | 17 | expect(state(g).seq.length).toBe(4); |
| 18 | 18 | expect(String(g.el('length').textContent)).toBe('4'); |
| 19 | 19 | expect(g.errors).toEqual([]); |
| 20 | }); | |
| 20 | }, 30000); |
firefly-jar/index.html added +414
| @@ -0,0 +1,414 @@ | ||
| 1 | ||
| 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>Firefly Jar</title> | |
| 7 | <!-- og:begin --> | |
| 8 | <meta name="description" content="Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern"> | |
| 9 | <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/firefly-jar/"> | |
| 10 | <meta property="og:type" content="website"> | |
| 11 | <meta property="og:site_name" content="Pixel Plays"> | |
| 12 | <meta property="og:title" content="Firefly Jar"> | |
| 13 | <meta property="og:description" content="Tap the fireflies into a jar while they glow, a dim one flies off, shoo the moths before they reach the lantern"> | |
| 14 | <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/firefly-jar/"> | |
| 15 | <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/firefly-jar.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="Firefly Jar: the opening scene of the game"> | |
| 20 | <meta name="twitter:card" content="summary_large_image"> | |
| 21 | <!-- og:end --> | |
| 22 | <style> | |
| 23 | :root { : #1c1b19; : #8b877f; : #fff; : #c9b43a; } | |
| 24 | * { box-sizing: border-box; } | |
| 25 | html, body { height: 100%; margin: 0; background: var(); color: var(); } | |
| 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(); } | |
| 33 | .row b { font-size: 16px; font-weight: 600; min-width: 1ch; font-variant-numeric: tabular-nums; } | |
| 34 | .row span { color: var(); } | |
| 35 | #status { color: var(); min-height: 1.35em; } | |
| 36 | button { pointer-events: auto; font: inherit; color: var(); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; } | |
| 37 | button:hover, button:focus-visible { color: var(); } | |
| 38 | </style> | |
| 39 | </head> | |
| 40 | <body> | |
| 41 | <div id="stage"><canvas id="c" tabindex="0" aria-label="A back garden at dusk with a picket fence, long grass, a lantern on a post and a glass jar. Fireflies drift over the grass and pulse: tap or press space on one while it glows to catch it into the jar for 1 point, 3 for a golden one; a dim one is scared off and breaks your streak. Moths drift in towards the lantern: tap one to shoo it, a moth that reaches the lantern costs a life. Tab or the left and right arrows move a ring between fireflies and moths, space or enter taps the one in the ring. Ninety seconds or three lives."></canvas></div> | |
| 42 | <div id="scores"> | |
| 43 | <div class="row"><b id="left">90</b><span>seconds left</span></div> | |
| 44 | <div class="row"><b id="jar">0</b><span>in the jar</span></div> | |
| 45 | <div class="row"><b id="lives">3</b><span>lives</span></div> | |
| 46 | <div class="row"><b id="best">0</b><span>best</span></div> | |
| 47 | </div> | |
| 48 | <div class="hud" id="bottom"> | |
| 49 | <div id="status" role="status" aria-live="polite"></div> | |
| 50 | <button id="mute" type="button" aria-pressed="false">sound on</button> | |
| 51 | </div> | |
| 52 | <script src="../shell.js"></script> | |
| 53 | <script> | |
| 54 | PixelPlays.mount({ | |
| 55 | id: 'firefly-jar', | |
| 56 | rules: [ | |
| 57 | 'Tap a firefly while it glows to catch it: 1, golden 3.', | |
| 58 | 'A dim one is scared off and breaks your streak.', | |
| 59 | 'Tap moths to shoo them; one at the lantern costs a life.', | |
| 60 | 'Ninety seconds or three lives. Tab or arrows + space.', | |
| 61 | ], | |
| 62 | }); | |
| 63 | </script> | |
| 64 | <script>window.PP_SCENE = { originY: 4, shadowX: 1.3, shadowY: -.12 };</script> | |
| 65 | <script src="../engine.js"></script> | |
| 66 | <script src="night.js"></script> | |
| 67 | <script> | |
| 68 | 'use strict'; | |
| 69 | ||
| 70 | const { LANTERN, JAR } = Night; | |
| 71 | const FENCE_V = -8.4, POST_V = -1; | |
| 72 | const PALE = [238, 233, 218], PALE_DARK = [168, 160, 150], IRON = [58, 54, 62], STUMP = [128, 92, 64], STUMP_TOP = [164, 124, 84]; | |
| 73 | const GLASS_PX = rgb(206, 226, 232), GLASS_EDGE = rgb(120, 156, 170), LID = rgb(176, 150, 70); | |
| 74 | const FLY_GLOW = [255, 244, 160], FLY_GOLD = [255, 190, 56], FLY_DIM = rgb(104, 112, 58), FLY_DIM_EDGE = rgb(30, 40, 30); | |
| 75 | const MOTH_BODY = rgb(236, 226, 206), MOTH_EDGE = rgb(70, 56, 60), MOTH_WING = rgb(250, 246, 234); | |
| 76 | const HIT_CSS = 24; // a tap lands on whatever is within this many screen pixels | |
| 77 | ||
| 78 | // game coordinates are screen-shaped: u across, v into the garden. The engine's world axes sit 45 degrees off them. | |
| 79 | const wx = (u, v) => (u + v) / R2, wy = (u, v) => (v - u) / R2; | |
| 80 | const scr = (u, v, z) => ({ sx: OX + u * S, sy: OY + (v * SIN - z * COS) * S }); | |
| 81 | const mod = (a, n) => ((a % n) + n) % n; | |
| 82 | ||
| 83 | /* ---------- the baked scene: lawn, fence, lantern post, stump ---------- */ | |
| 84 | function groundColor(x, y, ix, iy, i) { | |
| 85 | const u = (x - y) / R2, v = (x + y) / R2; | |
| 86 | const edge = Math.pow(Math.pow(Math.abs(u) / 12.4, 4) + Math.pow(Math.abs(v - 1.4) / 10.2, 4), .25); | |
| 87 | const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .13; | |
| 88 | if (rough > 1.04) return 0; | |
| 89 | if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0; | |
| 90 | kinds[i] = KIND_GRASS; | |
| 91 | const t = noise(x * .9, y * .9) * 1.15 + (hash(ix, iy) - .5) * .55 - .08; | |
| 92 | return rgb(...GRASS[clamp(Math.floor(t * 4.2), 0, 3)]); | |
| 93 | } | |
| 94 | function growFence() { | |
| 95 | for (let u = -11.2; u <= 11.2; u += .72) { | |
| 96 | const x = wx(u, FENCE_V), y = wy(u, FENCE_V), top = 2.5 + (hash(Math.round(u * 10), 3) - .5) * .2; | |
| 97 | capsule([x, y, 0], [x, y, top - .2], .2, .2, () => PALE, 'solid'); | |
| 98 | capsule([x, y, top - .2], [x, y, top + .15], .2, .02, () => PALE, 'solid'); | |
| 99 | } | |
| 100 | for (const z of [.7, 1.7]) capsule([wx(-11.4, FENCE_V + .25), wy(-11.4, FENCE_V + .25), z], [wx(11.4, FENCE_V + .25), wy(11.4, FENCE_V + .25), z], .13, .13, () => PALE_DARK, 'solid'); | |
| 101 | } | |
| 102 | function growLantern() { | |
| 103 | const x = wx(LANTERN.u, POST_V), y = wy(LANTERN.u, POST_V); | |
| 104 | capsule([x, y, 0], [x, y, 1.8], .18, .14, () => IRON, 'solid'); | |
| 105 | capsule([x, y, 0], [x, y, .3], .4, .3, () => IRON, 'solid'); | |
| 106 | box(x - .42, y - .42, 1.8, x + .42, y + .42, 3.1, [255, 226, 140], 21); | |
| 107 | capsule([x, y, 3.1], [x, y, 3.5], .5, .08, () => IRON, 'solid'); | |
| 108 | for (const z of [.6, 1.2, 1.9]) castShadow(x, y, z, .3, 1, 0); | |
| 109 | for (const z of [2.2, 2.8]) castShadow(x, y, z, .5, 1, 0); | |
| 110 | } | |
| 111 | function growStump() { | |
| 112 | const x = wx(JAR.u, JAR.v), y = wy(JAR.u, JAR.v); | |
| 113 | capsule([x, y, 0], [x, y, .6], 1.2, 1.1, () => STUMP, 'solid'); | |
| 114 | capsule([x, y, .55], [x, y, .62], 1.1, 1.1, () => STUMP_TOP, 'solid'); | |
| 115 | for (const z of [.2, .5]) castShadow(x, y, z, 1.1, 1, 0); | |
| 116 | } | |
| 117 | function bake() { | |
| 118 | zb.fill(-1e9); | |
| 119 | pix.fill(rgb(255, 255, 255)); | |
| 120 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 121 | const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i); | |
| 122 | if (!c) continue; | |
| 123 | pix[i] = c; ground[i] = 1; | |
| 124 | zb[i] = (g.x + g.y) / R2 * COS; | |
| 125 | } | |
| 126 | growGrass(); | |
| 127 | groundZ.set(zb); | |
| 128 | growFence(); | |
| 129 | growLantern(); | |
| 130 | growStump(); | |
| 131 | for (let u = -11; u <= 11.2; u += .72) for (const z of [.5, 1.3, 2.1]) castShadow(wx(u, FENCE_V), wy(u, FENCE_V), z, .3, 1, 0); | |
| 132 | bakeOcclusion(); | |
| 133 | staticShadow.set(shadowMask); | |
| 134 | applyShadows(groundZ); | |
| 135 | bakedPix.set(pix); | |
| 136 | bakedZ.set(zb); | |
| 137 | } | |
| 138 | ||
| 139 | /* ---------- drawing ---------- */ | |
| 140 | function px(ix, iy, color) { if (ix >= 0 && iy >= 0 && ix < W && iy < H) pix[iy * W + ix] = color; } | |
| 141 | // a soft dithered halo: more pixels near the middle | |
| 142 | function halo(sx, sy, r, color, strength) { | |
| 143 | const cx = Math.round(sx), cy = Math.round(sy); | |
| 144 | for (let dy = -r; dy <= r; dy++) for (let dx = -r; dx <= r; dx++) { | |
|
||
| 145 | const d = Math.hypot(dx, dy * 1.15); | |
| 146 | if (d > r) continue; | |
| 147 | const ix = cx + dx, iy = cy + dy; | |
| 148 | if (ix < 0 || iy < 0 || ix >= W || iy >= H) continue; | |
| 149 | if ((1 - d / r) * strength > bayerAt(ix, iy)) pix[iy * W + ix] = color; | |
| 150 | } | |
| 151 | } | |
| 152 | function tintHalo(sx, sy, r, c, strength) { halo(sx, sy, r, rgb(...c), strength); } | |
| 153 | ||
| 154 | function drawFly(f) { | |
| 155 | const p = scr(f.u, f.v, f.z), g = Night.glow(f), cx = Math.round(p.sx), cy = Math.round(p.sy); | |
| 156 | if (f.fled) { | |
| 157 | // a scared firefly streaks up and away, dark | |
| 158 | for (let k = 0; k < 3; k++) px(cx, cy + k, FLY_DIM); | |
| 159 | return; | |
| 160 | } | |
| 161 | const color = f.golden ? FLY_GOLD : FLY_GLOW; | |
| 162 | if (g.on) { | |
| 163 | tintHalo(p.sx, p.sy, f.golden ? 8 : 6, color, .35 + g.level * .65); | |
| 164 | for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) px(cx + dx, cy + dy, rgb(255, 255, g.level > .5 ? 235 : 190)); | |
| 165 | if (f.golden) for (const [dx, dy] of [[-1, 0], [2, 0], [0, -1], [0, 2], [1, -1], [1, 2], [-1, 1], [2, 1]]) px(cx + dx, cy + dy, rgb(...FLY_GOLD)); | |
| 166 | } else { | |
| 167 | for (const [dx, dy] of [[-1, 0], [2, 0], [0, -1], [0, 2], [1, -1], [1, 2], [-1, 1], [2, 1]]) px(cx + dx, cy + dy, FLY_DIM_EDGE); | |
| 168 | for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) px(cx + dx, cy + dy, f.golden ? rgb(150, 120, 40) : FLY_DIM); | |
| 169 | } | |
| 170 | } | |
| 171 | function drawMoth(m) { | |
| 172 | const p = scr(m.u, m.v, m.z), cx = Math.round(p.sx), cy = Math.round(p.sy); | |
| 173 | const up = STILL ? 0 : Math.floor(G.time * 8 + m.id) % 2; | |
| 174 | const wing = up ? [[-3, -2], [-2, -2], [-3, -1], [-2, -1], [-1, -1], [3, -2], [2, -2], [3, -1], [2, -1], [1, -1]] | |
| 175 | : [[-3, 0], [-2, 0], [-1, 0], [-3, 1], [-2, 1], [3, 0], [2, 0], [1, 0], [3, 1], [2, 1]]; | |
| 176 | for (const [dx, dy] of wing) for (const [ox, oy] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) px(cx + dx + ox, cy + dy + oy, MOTH_EDGE); | |
| 177 | for (const [dx, dy] of wing) px(cx + dx, cy + dy, MOTH_WING); | |
| 178 | for (let k = -1; k <= 2; k++) { px(cx, cy + k, MOTH_BODY); px(cx - 1, cy + k, MOTH_EDGE); px(cx + 1, cy + k, MOTH_EDGE); } | |
| 179 | } | |
| 180 | function drawLantern() { | |
| 181 | const p = scr(LANTERN.u, LANTERN.v, 2.45); | |
| 182 | halo(p.sx, p.sy + 1, 17, rgb(255, 224, 140), .42); | |
| 183 | halo(p.sx, p.sy, 8, rgb(255, 244, 190), .7); | |
| 184 | } | |
| 185 | // the jar: a glass cylinder on the stump with a lid, the caught fireflies glowing inside | |
| 186 | function drawJar(time) { | |
| 187 | const x = wx(JAR.u, JAR.v), y = wy(JAR.u, JAR.v), base = .66, top = base + 2.3, r = 1; | |
| 188 | const shown = Math.min(R.jar, 24); | |
| 189 | for (let k = 0; k < shown; k++) { | |
| 190 | const a = hash(k, 31) * 6.28, rr = Math.sqrt(hash(k, 32)) * .75, z = base + .25 + hash(k, 33) * 1.8; | |
| 191 | const pulse = STILL ? 1 : (Math.sin(time * 2 + k * 1.9) + 1) / 2; | |
| 192 | const p = project(x + Math.cos(a) * rr, y + Math.sin(a) * rr, z); | |
| 193 | tintHalo(p.sx, p.sy, 3, k % 5 === 0 ? FLY_GOLD : FLY_GLOW, .25 + pulse * .4); | |
| 194 | px(Math.round(p.sx), Math.round(p.sy), rgb(255, 255, 220)); | |
| 195 | } | |
| 196 | for (let z = base; z <= top; z += .1) for (const a of [-.9, 2.25]) { | |
| 197 | plot(x + Math.cos(a) * r, y + Math.sin(a) * r, z, GLASS_EDGE); | |
| 198 | } | |
| 199 | for (let z = base; z <= top; z += .35) for (let a = 0; a < 6.3; a += .25) { | |
| 200 | const c = Math.cos(a), s = Math.sin(a); | |
| 201 | if (s > -.2 || (z + a * 7 | 0) % 3 === 0) plot(x + c * r, y + s * r, z, GLASS_PX); | |
| 202 | } | |
| 203 | for (let a = 0; a < 6.3; a += .12) plot(x + Math.cos(a) * r, y + Math.sin(a) * r, top, GLASS_EDGE); | |
| 204 | for (let rr = 0; rr < r + .15; rr += .15) for (let a = 0; a < 6.3; a += .15) plot(x + Math.cos(a) * rr, y + Math.sin(a) * rr, top + .12, LID); | |
| 205 | for (const z of [0, .3, .8]) castShadow(x, y, base + 1.2 + z, .7, 1, .4); | |
| 206 | } | |
| 207 | function drawSparks() { | |
| 208 | for (const s of G.sparks) { | |
| 209 | const k = s.age / .45, r = 2 + k * 9, n = 14; | |
| 210 | const color = s.golden ? rgb(...FLY_GOLD) : rgb(...FLY_GLOW); | |
| 211 | for (let a = 0; a < n; a++) { | |
| 212 | const an = a / n * 6.283 + (s.kind === 'moth' ? .3 : 0); | |
| 213 | px(Math.round(s.sx + Math.cos(an) * r), Math.round(s.sy + Math.sin(an) * r * .8), s.kind === 'moth' ? MOTH_WING : color); | |
| 214 | } | |
| 215 | } | |
| 216 | } | |
| 217 | function drawRing() { | |
| 218 | const c = G.cursor && cursorTarget(); | |
| 219 | if (!c) return; | |
| 220 | const p = scr(c.u, c.v, c.z), ring = []; | |
| 221 | for (let a = 0; a < 24; a++) ring.push([p.sx + Math.cos(a / 24 * 6.283) * 9, p.sy + Math.sin(a / 24 * 6.283) * 9]); | |
| 222 | haloDots(ring); | |
| 223 | drawDots(ring, INK); | |
| 224 | drawDots(ring.filter((_, i) => i % 2 === 0), SIGNAL); | |
| 225 | } | |
| 226 | function draw() { | |
| 227 | pix.set(bakedPix); | |
| 228 | zb.set(bakedZ); | |
| 229 | const windT = STILL ? 0 : Math.floor(G.time * WIND_FPS) / WIND_FPS; | |
| 230 | drawTufts(windT); | |
| 231 | for (const f of R.flies) { castShadow(wx(f.u, f.v), wy(f.u, f.v), f.z, .22, 1, 0); } | |
| 232 | for (const m of R.moths) castShadow(wx(m.u, m.v), wy(m.u, m.v), m.z, .25, 1, 0); | |
| 233 | drawJar(G.time); | |
| 234 | applyShadows(bakedZ); | |
| 235 | shadeEdges(); | |
| 236 | drawLantern(); | |
| 237 | for (const f of R.flies) drawFly(f); | |
| 238 | for (const m of R.moths) drawMoth(m); | |
| 239 | drawSparks(); | |
| 240 | drawRing(); | |
| 241 | ctx.putImageData(image, 0, 0); | |
| 242 | } | |
| 243 | ||
| 244 | /* ---------- game state ---------- */ | |
| 245 | const BEST_KEY = 'pixel-plays-firefly-jar-best'; | |
| 246 | const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })(); | |
| 247 | let R = Night.newGame(best0, Date.now() & 0xffff); | |
| 248 | const G = { time: 0, status: '', noteUntil: 0, sparks: [], cursor: null }; | |
| 249 | const nodes = {}; | |
| 250 | for (const id of ['left', 'jar', 'lives', 'best', 'status']) nodes[id] = document.getElementById(id); | |
| 251 | const hudText = {}; | |
| 252 | function setText(key, text) { if (hudText[key] !== text) { hudText[key] = text; nodes[key].textContent = text; } } | |
| 253 | function renderHud() { | |
| 254 | setText('left', String(Math.ceil(R.left))); | |
| 255 | setText('jar', String(R.jar)); | |
| 256 | setText('lives', String(R.lives)); | |
| 257 | setText('best', String(Math.max(R.best, R.jar))); | |
| 258 | } | |
| 259 | function setStatus(text) { setText('status', text); G.status = text; } | |
| 260 | function note(text) { setStatus(text); G.noteUntil = G.time + 2.2; } | |
| 261 | const HINT = 'tap a glowing firefly · a dim one flies off · shoo the moths'; | |
| 262 | ||
| 263 | function spark(e, kind) { | |
| 264 | const p = scr(e.u, e.v, e.z); | |
| 265 | G.sparks.push({ sx: p.sx, sy: p.sy, age: 0, golden: !!e.golden, kind }); | |
| 266 | } | |
| 267 | function act(events) { | |
| 268 | for (const e of events) { | |
| 269 | if (e.type === 'catch') { | |
| 270 | spark(e, 'fly'); | |
| 271 | note(e.golden ? 'golden firefly: +3' : e.streak > 2 ? `caught: +1 · streak ${e.streak}` : 'caught: +1'); | |
| 272 | sound(e.golden ? 'chime' : 'pop'); | |
| 273 | } else if (e.type === 'scare') { | |
| 274 | note('too dim: it flew off, streak broken'); | |
| 275 | sound('thud'); | |
| 276 | } else if (e.type === 'shoo') { | |
| 277 | spark(e, 'moth'); | |
| 278 | note('moth shooed'); | |
| 279 | sound('flap'); | |
| 280 | } else if (e.type === 'burn') { | |
| 281 | note('a moth reached the lantern: a life lost'); | |
| 282 | sound('buzz'); | |
| 283 | } else if (e.type === 'over') { | |
| 284 | if (R.record) try { localStorage.setItem(BEST_KEY, String(R.best)); } catch (err) { /* private window: keep it for this visit */ } | |
| 285 | const line = e.verdict === 'win' ? 'the night is survived' : 'the third moth put the lantern out'; | |
| 286 | setStatus(`${line} · ${R.jar} in the jar (${R.caught} caught, best streak ${R.bestStreak})${R.record ? ' · new best' : ` · best ${R.best}`} · tap or press space for another night`); | |
| 287 | sound(e.verdict === 'win' ? 'chime' : 'buzz'); | |
| 288 | } | |
| 289 | } | |
| 290 | renderHud(); | |
| 291 | } | |
| 292 | function restart() { | |
| 293 | const next = Night.again(R); | |
| 294 | if (!next) return false; | |
| 295 | R = next; G.sparks = []; G.cursor = null; | |
| 296 | note(HINT); | |
| 297 | renderHud(); | |
| 298 | return true; | |
| 299 | } | |
| 300 | function update(dt) { | |
| 301 | G.time += dt; | |
| 302 | act(Night.advance(R, dt)); | |
| 303 | for (const s of G.sparks) s.age += dt; | |
| 304 | G.sparks = G.sparks.filter(s => s.age < .45); | |
| 305 | if (G.cursor) { | |
| 306 | const t = cursorTarget(); | |
| 307 | if (t) { const p = scr(t.u, t.v, t.z); G.cursor.sx = p.sx; G.cursor.sy = p.sy; } | |
| 308 | else G.cursor = nearestTo(G.cursor.sx, G.cursor.sy); | |
| 309 | } | |
| 310 | if (R.phase === 'play' && G.time >= G.noteUntil) { | |
| 311 | const glowing = R.flies.filter(f => !f.fled && Night.glow(f).on).length; | |
| 312 | setStatus(R.moths.length ? `${R.moths.length} moth${R.moths.length > 1 ? 's' : ''} coming · ${glowing} glowing` : `${glowing} glowing`); | |
| 313 | } | |
| 314 | renderHud(); | |
| 315 | } | |
| 316 | ||
| 317 | /* ---------- input ---------- */ | |
| 318 | // the target whose screen position is nearest a canvas point, within a generous reach | |
| 319 | function nearestTo(sx, sy, reach = Infinity) { | |
| 320 | let best = null, bestD = reach; | |
| 321 | for (const t of Night.targets(R)) { | |
| 322 | const p = scr(t.u, t.v, t.z), d = Math.hypot(p.sx - sx, p.sy - sy); | |
| 323 | if (d < bestD) { bestD = d; best = { kind: t.kind, id: t.id, sx: p.sx, sy: p.sy }; } | |
| 324 | } | |
| 325 | return best; | |
| 326 | } | |
| 327 | const cursorTarget = () => (G.cursor ? Night.targets(R).find(t => t.kind === G.cursor.kind && t.id === G.cursor.id) : null); | |
| 328 | function hit(kind, id) { act(Night.tap(R, kind, id)); } | |
| 329 | canvas.addEventListener('pointerdown', e => { | |
| 330 | ensureAudio(); | |
| 331 | canvas.focus({ preventScroll: true }); | |
| 332 | if (restart()) return; | |
| 333 | if (R.phase !== 'play') return; | |
| 334 | const rect = canvas.getBoundingClientRect(); | |
| 335 | const scale = rect.width / W; | |
| 336 | const sx = (e.clientX - rect.left) / scale, sy = (e.clientY - rect.top) / scale; | |
| 337 | const t = nearestTo(sx, sy, Math.max(11, HIT_CSS / scale)); | |
| 338 | if (t) { G.cursor = null; hit(t.kind, t.id); } | |
| 339 | }); | |
| 340 | // the ring goes through everything tappable, nearest the jar first | |
| 341 | function step(d) { | |
| 342 | const list = Night.targets(R); | |
| 343 | if (!list.length) return; | |
| 344 | const at = G.cursor ? list.findIndex(t => t.kind === G.cursor.kind && t.id === G.cursor.id) : -1; | |
| 345 | const t = list[at < 0 ? (d > 0 ? 0 : list.length - 1) : (at + d + list.length) % list.length]; | |
| 346 | const p = scr(t.u, t.v, t.z); | |
| 347 | G.cursor = { kind: t.kind, id: t.id, sx: p.sx, sy: p.sy }; | |
| 348 | note(`ring on a ${t.kind === 'moth' ? 'moth' : 'firefly'} · space to tap`); | |
| 349 | } | |
| 350 | canvas.addEventListener('keydown', e => { | |
| 351 | const k = e.key; | |
| 352 | if (k === ' ' || k === 'Enter') { | |
| 353 | e.preventDefault(); | |
| 354 | ensureAudio(); | |
| 355 | if (e.repeat) return; | |
| 356 | if (restart()) return; | |
| 357 | if (R.phase !== 'play') return; | |
| 358 | const t = cursorTarget(); | |
| 359 | if (t) hit(t.kind, t.id); else step(1); | |
| 360 | } else if (k === 'ArrowLeft' || k === 'ArrowUp' || k === 'a' || k === 'A') { e.preventDefault(); if (R.phase === 'play') step(-1); } | |
| 361 | else if (k === 'ArrowRight' || k === 'ArrowDown' || k === 'd' || k === 'D') { e.preventDefault(); if (R.phase === 'play') step(1); } | |
| 362 | else if (k === 'Tab' && R.phase === 'play' && Night.targets(R).length) { e.preventDefault(); step(e.shiftKey ? -1 : 1); } | |
| 363 | }); | |
| 364 | ||
| 365 | /* ---------- sound ---------- */ | |
| 366 | let audio = null, muted = false; | |
| 367 | function ensureAudio() { | |
| 368 | if (audio) { if (audio.state === 'suspended') audio.resume(); return; } | |
| 369 | const AC = window.AudioContext || window.webkitAudioContext; | |
| 370 | if (AC) audio = new AC(); | |
| 371 | } | |
| 372 | function sound(kind) { | |
| 373 | if (!audio || muted) return; | |
| 374 | const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator(); | |
| 375 | const spec = { | |
| 376 | pop: [520, 880, .12, .06, 'sine'], | |
| 377 | chime: [660, 1180, .3, .07, 'sine'], | |
| 378 | thud: [200, 110, .12, .06, 'sine'], | |
| 379 | flap: [300, 200, .08, .04, 'triangle'], | |
| 380 | buzz: [150, 70, .3, .06, 'sawtooth'], | |
| 381 | }[kind]; | |
| 382 | osc.type = spec[4]; | |
| 383 | osc.frequency.setValueAtTime(spec[0], now); | |
| 384 | osc.frequency.exponentialRampToValueAtTime(spec[1], now + spec[2]); | |
| 385 | gain.gain.setValueAtTime(spec[3], now); | |
| 386 | gain.gain.exponentialRampToValueAtTime(.0005, now + spec[2]); | |
| 387 | osc.connect(gain).connect(audio.destination); | |
| 388 | osc.start(now); osc.stop(now + spec[2] + .01); | |
| 389 | } | |
| 390 | const muteButton = document.getElementById('mute'); | |
| 391 | muteButton.addEventListener('click', () => { | |
| 392 | muted = !muted; | |
| 393 | muteButton.textContent = muted ? 'sound off' : 'sound on'; | |
| 394 | muteButton.setAttribute('aria-pressed', String(muted)); | |
| 395 | }); | |
| 396 | ||
| 397 | /* ---------- fit and boot ---------- */ | |
| 398 | addEventListener('resize', fit); | |
| 399 | fit(); | |
| 400 | bake(); | |
| 401 | note(HINT); | |
| 402 | renderHud(); | |
| 403 | canvas.focus({ preventScroll: true }); | |
| 404 | let last = performance.now(); | |
| 405 | function frame(now) { | |
| 406 | update(Math.min(.04, (now - last) / 1000)); | |
| 407 | last = now; | |
| 408 | draw(); | |
| 409 | requestAnimationFrame(frame); | |
| 410 | } | |
| 411 | requestAnimationFrame(frame); | |
| 412 | </script> | |
| 413 | </body> | |
| 414 | </html> |
firefly-jar/night.js added +180
| @@ -0,0 +1,180 @@ | ||
| 1 | 'use strict'; | |
| 2 | // The firefly jar rules: a back garden on a summer night. Fireflies drift over the grass and pulse; one that is | |
| 3 | // glowing is caught into the jar when tapped (+1, +3 for a golden one), one that is dim is scared off and breaks the | |
| 4 | // streak. Moths drift in to the lantern: a tapped moth is shooed, a moth that reaches the lantern costs a life. | |
| 5 | // The night lasts 90 seconds or three lives; more fireflies and faster moths as it goes on. | |
| 6 | // Plain numbers in, plain numbers out, no DOM. The page draws and sounds what this decides. | |
| 7 | (function (root) { | |
| 8 | const NIGHT = 90; // seconds in a night | |
| 9 | const LIVES = 3; | |
| 10 | const PERIOD = 2.4; // seconds for one glow cycle | |
| 11 | const GLOW_FRAC = .5; // share of the cycle a firefly glows: 1.2 s, long enough to tap on purpose | |
| 12 | const GOLD_ODDS = .12; // share of fireflies that are golden | |
| 13 | const GOLD_PERIOD = 2; // golden ones pulse a little faster, and glow for 1 s | |
| 14 | const FLY_LIFE = 16; // seconds before a firefly drifts off by itself | |
| 15 | const MAX_FLIES = 12; | |
| 16 | const START_FLIES = 4; | |
| 17 | const FLEE = .8; // seconds a scared firefly takes to fly out of reach | |
| 18 | const LANTERN = { u: -8, v: -1, z: 2.5 }; | |
| 19 | const JAR = { u: 9, v: 6, z: 1 }; | |
| 20 | const FIELD = { u0: -11, u1: 11, v0: -7, v1: 9.5 }; | |
| 21 | const REACH = .8; // a moth this close to the lantern has reached it | |
| 22 | const RESTART_AFTER = .8; | |
| 23 | const MAX_STEP = .05; | |
| 24 | ||
| 25 | const finite = v => (Number.isFinite(v) ? v : 0); | |
| 26 | const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); | |
| 27 | const progress = t => clamp(finite(t) / NIGHT, 0, 1); | |
| 28 | // the generator is a 32-bit state kept on the game, so a night replays from its seed | |
| 29 | function rand(s) { | |
| 30 | s.rng = (s.rng + 0x6d2b79f5) >>> 0; | |
| 31 | let t = s.rng; | |
| 32 | t = Math.imul(t ^ t >>> 15, t | 1); | |
| 33 | t ^= t + Math.imul(t ^ t >>> 7, t | 61); | |
| 34 | return ((t ^ t >>> 14) >>> 0) / 4294967296; | |
| 35 | } | |
| 36 | // arrivals per second as the night goes on | |
| 37 | const flyRate = t => .45 + progress(t) * .9; | |
| 38 | const mothRate = t => .1 + progress(t) * .3; | |
| 39 | const mothSpeed = t => 1.4 + progress(t) * 1.8; | |
| 40 | ||
| 41 | // is a firefly glowing at this moment; 0 to 1 brightness, and whether a tap would catch it | |
| 42 | function glow(f) { | |
| 43 | const phase = (((f.age + f.offset) % f.period) + f.period) % f.period / f.period; | |
| 44 | if (phase >= f.frac) return { on: false, level: 0 }; | |
| 45 | return { on: true, level: Math.sin(phase / f.frac * Math.PI) }; | |
| 46 | } | |
| 47 | ||
| 48 | function newFly(s, entering) { | |
| 49 | const golden = rand(s) < GOLD_ODDS; | |
| 50 | const f = { | |
| 51 | id: s.nextId++, u: lerpAt(FIELD.u0, FIELD.u1, rand(s)), v: lerpAt(FIELD.v0, FIELD.v1, rand(s)), z: 0, | |
| 52 | zBase: 1 + rand(s) * 1.6, heading: rand(s) * Math.PI * 2, turn: 0, retarget: 0, speed: .7 + rand(s) * .7, | |
| 53 | age: 0, offset: rand(s) * PERIOD, golden, period: golden ? GOLD_PERIOD : PERIOD, frac: golden ? .5 : GLOW_FRAC, | |
| 54 | fled: false, out: 0, | |
| 55 | }; | |
| 56 | if (entering) { f.u = rand(s) < .5 ? FIELD.u0 : FIELD.u1; } | |
| 57 | f.z = f.zBase; | |
| 58 | return f; | |
| 59 | } | |
| 60 | const lerpAt = (a, b, t) => a + (b - a) * t; | |
| 61 | ||
| 62 | function newMoth(s) { | |
| 63 | // from the right and the near and far edges: always far from a lantern on the left | |
| 64 | const side = Math.floor(rand(s) * 3); | |
| 65 | const m = { id: s.nextId++, u: 0, v: 0, z: 2 + rand(s) * 1.2, age: 0, wob: rand(s) * 6.28, gone: false }; | |
| 66 | if (side === 0) { m.u = FIELD.u1 + 1.5; m.v = lerpAt(FIELD.v0, FIELD.v1, rand(s)); } | |
| 67 | else { m.u = lerpAt(-2, FIELD.u1, rand(s)); m.v = side === 1 ? FIELD.v0 - .5 : FIELD.v1 + .5; } | |
| 68 | return m; | |
| 69 | } | |
| 70 | ||
| 71 | function newGame(best = 0, seed = 1) { | |
| 72 | const s = { | |
| 73 | phase: 'play', verdict: '', t: 0, left: NIGHT, jar: 0, lives: LIVES, streak: 0, bestStreak: 0, caught: 0, | |
| 74 | best: Math.max(0, Math.floor(finite(best))), record: false, rng: (finite(seed) >>> 0) || 1, nextId: 1, | |
| 75 | flies: [], moths: [], flyAcc: 0, mothAcc: .6, timer: 0, | |
| 76 | }; | |
| 77 | for (let i = 0; i < START_FLIES; i++) s.flies.push(newFly(s, false)); | |
| 78 | return s; | |
| 79 | } | |
| 80 | ||
| 81 | // everything that can be tapped, nearest the jar first; a firefly that has fled cannot be tapped | |
| 82 | function targets(s) { | |
| 83 | const list = []; | |
| 84 | for (const f of s.flies) if (!f.fled) list.push({ kind: 'fly', id: f.id, u: f.u, v: f.v, z: f.z }); | |
| 85 | for (const m of s.moths) list.push({ kind: 'moth', id: m.id, u: m.u, v: m.v, z: m.z }); | |
| 86 | const d = p => Math.hypot(p.u - JAR.u, p.v - JAR.v); | |
| 87 | return list.sort((a, b) => d(a) - d(b) || a.id - b.id); | |
| 88 | } | |
| 89 | ||
| 90 | function end(s, verdict, events) { | |
| 91 | s.phase = 'over'; s.verdict = verdict; s.timer = 0; | |
| 92 | if (s.jar > s.best) { s.best = s.jar; s.record = true; } | |
| 93 | events.push({ type: 'over', verdict, jar: s.jar, lives: s.lives, record: s.record }); | |
| 94 | } | |
| 95 | ||
| 96 | // a tap on a firefly or a moth | |
| 97 | function tap(s, kind, id) { | |
| 98 | const events = []; | |
| 99 | if (s.phase !== 'play') return events; | |
| 100 | if (kind === 'fly') { | |
| 101 | const f = s.flies.find(x => x.id === id); | |
| 102 | if (!f || f.fled) return events; | |
| 103 | if (glow(f).on) { | |
| 104 | const points = f.golden ? 3 : 1; | |
| 105 | s.flies.splice(s.flies.indexOf(f), 1); | |
| 106 | s.jar += points; s.caught++; s.streak++; | |
| 107 | s.bestStreak = Math.max(s.bestStreak, s.streak); | |
| 108 | events.push({ type: 'catch', id, points, golden: f.golden, streak: s.streak, u: f.u, v: f.v, z: f.z }); | |
| 109 | } else { | |
| 110 | f.fled = true; f.out = 0; s.streak = 0; | |
| 111 | events.push({ type: 'scare', id, u: f.u, v: f.v, z: f.z }); | |
| 112 | } | |
| 113 | } else if (kind === 'moth') { | |
| 114 | const m = s.moths.find(x => x.id === id); | |
| 115 | if (!m) return events; | |
| 116 | s.moths.splice(s.moths.indexOf(m), 1); | |
| 117 | events.push({ type: 'shoo', id, u: m.u, v: m.v, z: m.z }); | |
| 118 | } | |
| 119 | return events; | |
| 120 | } | |
| 121 | ||
| 122 | function moveFly(s, f, dt) { | |
| 123 | f.age += dt; | |
| 124 | if (f.fled) { f.out += dt; f.z += dt * 5; f.u += Math.cos(f.heading) * dt * 4; f.v += Math.sin(f.heading) * dt * 4; return; } | |
| 125 | f.retarget -= dt; | |
| 126 | if (f.retarget <= 0) { f.retarget = 1 + rand(s) * 1.5; f.turn = (rand(s) - .5) * 2.2; } | |
| 127 | f.heading += f.turn * dt; | |
| 128 | // near the edge, steer back towards the middle | |
| 129 | const mu = (FIELD.u0 + FIELD.u1) / 2, mv = (FIELD.v0 + FIELD.v1) / 2; | |
| 130 | if (f.u < FIELD.u0 + 1 || f.u > FIELD.u1 - 1 || f.v < FIELD.v0 + 1 || f.v > FIELD.v1 - 1) { | |
| 131 | let d = Math.atan2(mv - f.v, mu - f.u) - f.heading; | |
| 132 | d = Math.atan2(Math.sin(d), Math.cos(d)); | |
| 133 | f.heading += clamp(d, -3 * dt, 3 * dt); | |
| 134 | } | |
| 135 | f.u = clamp(f.u + Math.cos(f.heading) * f.speed * dt, FIELD.u0 - .5, FIELD.u1 + .5); | |
| 136 | f.v = clamp(f.v + Math.sin(f.heading) * f.speed * dt, FIELD.v0 - .5, FIELD.v1 + .5); | |
| 137 | f.z = f.zBase + Math.sin(f.age * 1.3 + f.offset) * .4; | |
| 138 | } | |
| 139 | ||
| 140 | function advance(s, dt) { | |
| 141 | const events = []; | |
| 142 | dt = clamp(finite(dt), 0, MAX_STEP); | |
| 143 | if (s.phase !== 'play') { s.timer += dt; return events; } | |
| 144 | s.t += dt; s.left = Math.max(0, NIGHT - s.t); | |
| 145 | for (const f of s.flies) moveFly(s, f, dt); | |
| 146 | s.flies = s.flies.filter(f => (f.fled ? f.out < FLEE : f.age < FLY_LIFE)); | |
| 147 | // fireflies arrive; a crowded garden waits | |
| 148 | s.flyAcc += flyRate(s.t) * dt; | |
| 149 | while (s.flyAcc >= 1) { s.flyAcc -= 1; if (s.flies.filter(f => !f.fled).length < MAX_FLIES) s.flies.push(newFly(s, true)); } | |
| 150 | s.mothAcc += mothRate(s.t) * dt; | |
| 151 | while (s.mothAcc >= 1) { s.mothAcc -= 1; s.moths.push(newMoth(s)); } | |
| 152 | for (const m of s.moths) { | |
| 153 | m.age += dt; | |
| 154 | const dx = LANTERN.u - m.u, dv = LANTERN.v - m.v, dz = LANTERN.z - m.z, d = Math.hypot(dx, dv) || 1; | |
| 155 | const step = mothSpeed(s.t) * dt; | |
| 156 | // straight at the lantern, with a sideways flutter | |
| 157 | const flutter = Math.cos(m.age * 4 + m.wob) * 1.1 * dt; | |
| 158 | m.u += dx / d * step - dv / d * flutter; | |
| 159 | m.v += dv / d * step + dx / d * flutter; | |
| 160 | m.z += dz * Math.min(1, dt * .8); | |
| 161 | if (Math.hypot(LANTERN.u - m.u, LANTERN.v - m.v) < REACH) { | |
| 162 | m.gone = true; s.lives--; | |
| 163 | events.push({ type: 'burn', id: m.id, lives: s.lives }); | |
| 164 | } | |
| 165 | } | |
| 166 | s.moths = s.moths.filter(m => !m.gone); | |
| 167 | if (s.lives <= 0) end(s, 'loss', events); | |
| 168 | else if (s.left <= 0) end(s, 'win', events); | |
| 169 | return events; | |
| 170 | } | |
| 171 | ||
| 172 | // a tap after the night has been over for a moment starts the next one; otherwise null | |
| 173 | function again(s) { return s.phase === 'over' && s.timer > RESTART_AFTER ? newGame(s.best, s.rng + 1) : null; } | |
| 174 | ||
| 175 | const api = { | |
| 176 | NIGHT, LIVES, PERIOD, GLOW_FRAC, GOLD_ODDS, FLY_LIFE, MAX_FLIES, FLEE, LANTERN, JAR, FIELD, REACH, RESTART_AFTER, | |
| 177 | flyRate, mothRate, mothSpeed, glow, targets, newGame, tap, advance, again, | |
| 178 | }; | |
| 179 | if (typeof module !== 'undefined') module.exports = api; else root.Night = api; | |
| 180 | })(typeof window !== 'undefined' ? window : globalThis); |
firefly-jar/night.test.mjs added +140
| @@ -0,0 +1,140 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { NIGHT, LIVES, PERIOD, GLOW_FRAC, FLEE, LANTERN, FIELD, flyRate, mothRate, mothSpeed, glow, targets, newGame, tap, advance, again } from './night.js'; | |
| 3 | ||
| 4 | const run = (s, seconds, dt = .02) => { const ev = []; for (let t = 0; t < seconds - 1e-9; t += dt) ev.push(...advance(s, dt)); return ev; }; | |
| 5 | // a quiet garden with one firefly set to a known point in its glow cycle, no spawns to get in the way | |
| 6 | function garden(age) { | |
| 7 | const s = newGame(0, 5); | |
| 8 | s.flies = [s.flies[0]]; s.flyAcc = -1e6; s.mothAcc = -1e6; | |
| 9 | Object.assign(s.flies[0], { age, offset: 0, golden: false, period: PERIOD, frac: GLOW_FRAC }); | |
| 10 | return s; | |
| 11 | } | |
| 12 | const moth = (s, u, v) => { s.moths.push({ id: 900 + s.moths.length, u, v, z: LANTERN.z, age: 0, wob: 0, gone: false }); return s.moths.at(-1); }; | |
| 13 | ||
| 14 | test('a firefly glows for a window of each cycle and is dim for the rest', () => { | |
| 15 | const f = garden(0).flies[0]; | |
| 16 | expect(glow(f).on).toBe(true); | |
| 17 | f.age = PERIOD * GLOW_FRAC * .5; expect(glow(f).level).toBeGreaterThan(.99); | |
| 18 | f.age = PERIOD * GLOW_FRAC + .05; expect(glow(f)).toEqual({ on: false, level: 0 }); | |
| 19 | f.age = PERIOD + .1; expect(glow(f).on).toBe(true); | |
| 20 | expect(PERIOD * GLOW_FRAC).toBeGreaterThanOrEqual(1); | |
| 21 | }); | |
| 22 | ||
| 23 | test('a tap inside the glow window catches the firefly and scores one', () => { | |
| 24 | const s = garden(.3), id = s.flies[0].id; | |
| 25 | const ev = tap(s, 'fly', id); | |
| 26 | expect(ev[0]).toMatchObject({ type: 'catch', points: 1, golden: false }); | |
| 27 | expect(s.jar).toBe(1); | |
| 28 | expect(s.streak).toBe(1); | |
| 29 | expect(s.flies.length).toBe(0); | |
| 30 | }); | |
| 31 | ||
| 32 | test('a tap while the firefly is dim scares it off and scores nothing', () => { | |
| 33 | const s = garden(.3); s.streak = 4; s.jar = 2; | |
| 34 | s.flies[0].age = PERIOD * GLOW_FRAC + .3; | |
| 35 | const id = s.flies[0].id, ev = tap(s, 'fly', id); | |
| 36 | expect(ev[0].type).toBe('scare'); | |
| 37 | expect(s.jar).toBe(2); | |
| 38 | expect(s.streak).toBe(0); | |
| 39 | expect(targets(s).length).toBe(0); | |
| 40 | expect(tap(s, 'fly', id)).toEqual([]); | |
| 41 | run(s, FLEE + .1); | |
| 42 | expect(s.flies.length).toBe(0); | |
| 43 | }); | |
| 44 | ||
| 45 | test('a golden firefly scores three', () => { | |
| 46 | const s = garden(.2); s.flies[0].golden = true; | |
| 47 | tap(s, 'fly', s.flies[0].id); | |
| 48 | expect(s.jar).toBe(3); | |
| 49 | }); | |
| 50 | ||
| 51 | test('a moth reaches the lantern and costs a life; a tapped moth costs nothing', () => { | |
| 52 | const s = garden(0); | |
| 53 | moth(s, LANTERN.u + 1.5, LANTERN.v); | |
| 54 | const ev = run(s, 2); | |
| 55 | expect(ev.some(e => e.type === 'burn')).toBe(true); | |
| 56 | expect(s.lives).toBe(LIVES - 1); | |
| 57 | expect(s.moths.length).toBe(0); | |
| 58 | ||
| 59 | const t = garden(0), m = moth(t, 6, 3); | |
| 60 | expect(tap(t, 'moth', m.id)[0].type).toBe('shoo'); | |
| 61 | run(t, 10); | |
| 62 | expect(t.lives).toBe(LIVES); | |
| 63 | expect(t.moths.length).toBe(0); | |
| 64 | }); | |
| 65 | ||
| 66 | test('moths fly towards the lantern', () => { | |
| 67 | const s = garden(0), m = moth(s, 8, 5); | |
| 68 | const d = () => Math.hypot(m.u - LANTERN.u, m.v - LANTERN.v), before = d(); | |
| 69 | run(s, 1); | |
| 70 | expect(d()).toBeLessThan(before - 1); | |
| 71 | }); | |
| 72 | ||
| 73 | test('fireflies arrive and moths get faster and more frequent as the night goes on', () => { | |
| 74 | expect(flyRate(60)).toBeGreaterThan(flyRate(0)); | |
| 75 | expect(mothRate(60)).toBeGreaterThan(mothRate(0)); | |
| 76 | expect(mothSpeed(80)).toBeGreaterThan(mothSpeed(10)); | |
| 77 | const early = newGame(0, 2), late = newGame(0, 2); | |
| 78 | late.t = 70; | |
| 79 | for (const s of [early, late]) { s.flies = []; s.moths = []; s.flyAcc = 0; s.mothAcc = 0; } | |
| 80 | const count = s => { run(s, 10); return s.flies.length + s.moths.length + s.caught; }; | |
| 81 | expect(count(late)).toBeGreaterThan(count(early)); | |
| 82 | }); | |
| 83 | ||
| 84 | test('fireflies wander smoothly and stay near the garden', () => { | |
| 85 | const s = newGame(0, 9); | |
| 86 | s.mothAcc = -1e6; | |
| 87 | const f = s.flies[0]; let prev = [f.u, f.v], worst = 0; | |
| 88 | for (let i = 0; i < 1500; i++) { | |
| 89 | advance(s, .02); | |
| 90 | worst = Math.max(worst, Math.hypot(f.u - prev[0], f.v - prev[1])); | |
| 91 | prev = [f.u, f.v]; | |
| 92 | for (const x of s.flies) { expect(x.u).toBeGreaterThanOrEqual(FIELD.u0 - 5); expect(x.u).toBeLessThanOrEqual(FIELD.u1 + 5); } | |
| 93 | if (!s.flies.includes(f)) break; | |
| 94 | } | |
| 95 | expect(worst).toBeLessThan(.1); | |
| 96 | }); | |
| 97 | ||
| 98 | test('the clock ends the night as a win', () => { | |
| 99 | const s = newGame(0, 3); s.mothAcc = -1e6; s.flyAcc = -1e6; | |
| 100 | const ev = run(s, NIGHT + 1); | |
| 101 | expect(s.phase).toBe('over'); | |
| 102 | expect(ev.filter(e => e.type === 'over')).toEqual([expect.objectContaining({ verdict: 'win' })]); | |
| 103 | expect(s.verdict).toBe('win'); | |
| 104 | }); | |
| 105 | ||
| 106 | test('the third moth ends the night as a loss', () => { | |
| 107 | const s = garden(0); | |
| 108 | let over = []; | |
| 109 | for (let i = 0; i < LIVES; i++) { moth(s, LANTERN.u + 1, LANTERN.v); over = run(s, 1).filter(e => e.type === 'over'); } | |
| 110 | expect(s.lives).toBe(0); | |
| 111 | expect(s.verdict).toBe('loss'); | |
| 112 | expect(over.length).toBe(1); | |
| 113 | expect(tap(s, 'fly', 1)).toEqual([]); | |
| 114 | }); | |
| 115 | ||
| 116 | test('a record is kept and a tap after the pause starts a fresh night', () => { | |
| 117 | const s = garden(.2); s.best = 0; | |
| 118 | tap(s, 'fly', s.flies[0].id); | |
| 119 | s.t = NIGHT - .01; run(s, .1); | |
| 120 | expect(s.record).toBe(true); | |
| 121 | expect(again(s)).toBeNull(); | |
| 122 | run(s, 1); | |
| 123 | const next = again(s); | |
| 124 | expect(next.phase).toBe('play'); | |
| 125 | expect(next.best).toBe(1); | |
| 126 | expect(next.jar).toBe(0); | |
| 127 | }); | |
| 128 | ||
| 129 | test('targets are listed nearest the jar first', () => { | |
| 130 | const s = garden(0); s.flies = []; | |
| 131 | moth(s, -5, 0); moth(s, 8, 5); | |
| 132 | const list = targets(s); | |
| 133 | expect(list.map(t => t.id)).toEqual([901, 900]); | |
| 134 | }); | |
| 135 | ||
| 136 | test('the same seed plays the same night', () => { | |
| 137 | const a = newGame(0, 4), b = newGame(0, 4); | |
| 138 | run(a, 20); run(b, 20); | |
| 139 | expect(a.flies.map(f => [f.u, f.v])).toEqual(b.flies.map(f => [f.u, f.v])); | |
| 140 | }); |
firefly-jar/page.test.mjs added +9
| @@ -0,0 +1,9 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { boot } from '../playtest.mjs'; | |
| 3 | ||
| 4 | test('the over line reports the catches and the best streak', () => { | |
| 5 | const g = boot('firefly-jar'); | |
| 6 | g.run(100); | |
| 7 | expect(String(g.el('status').textContent)).toMatch(/\d+ in the jar \(\d+ caught, best streak \d+\)/); | |
| 8 | expect(g.errors).toEqual([]); | |
| 9 | }, 30000); |
index.html +1
| @@ -91,6 +91,7 @@ footer a::after { content: none; } | ||
| 91 | 91 | <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> |
| 92 | 92 | <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> |
| 93 | 93 | <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="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> | |
| 94 | 95 | </ul> |
| 95 | 96 | <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> |
| 96 | 97 | </main> |
og/firefly-jar.png added
Binary file not shown.
og/home.png
Binary file not shown.
serve.test.mjs +7
| @@ -409,6 +409,13 @@ test('Tram Line and its rules script are served without a track', async () => { | ||
| 409 | 409 | expect((await fetch(base + '/tram-line/line.js')).status).toBe(200); |
| 410 | 410 | }); |
| 411 | 411 | |
| 412 | test('Firefly Jar and its rules script are served without a track', async () => { | |
| 413 | const page = await fetch(base + '/firefly-jar/'); | |
| 414 | expect(page.status).toBe(200); | |
| 415 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); | |
| 416 | expect((await fetch(base + '/firefly-jar/night.js')).status).toBe(200); | |
| 417 | }); | |
| 418 | ||
| 412 | 419 | test('Soapbox Derby and its rules script are served without a track', async () => { |
| 413 | 420 | const page = await fetch(base + '/soapbox-derby/'); |
| 414 | 421 | expect(page.status).toBe(200); |
shell.js +1
| @@ -35,6 +35,7 @@ window.PixelPlays = (() => { | ||
| 35 | 35 | { 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 }, |
| 36 | 36 | { 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 }, |
| 37 | 37 | { 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: '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 }, | |
| 38 | 39 | ]; |
| 39 | 40 | const MUSIC_VOLUME = .4; |
| 40 | 41 | const CREDITS = [ |
new above
offline
FIELD is destructured but never used in the page; remove it.