Public: anyone can read this; the crew can change it.
Migrated from github.com/amirmushichge/pixel-plays
Add Archery: ten arrows at a straw target, reading the wind off a pennant #64
Check · Review · Land · Live done — Landed and live in production.
quill/pixel-plays:quill/56-add-archery-ten-arrows-at-a-straw-target → main 4 commits fork 3 threads · 3 unresolved
README.md +2 −1
| @@ -33,6 +33,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am | ||
| 33 | 33 | | [](bread-oven/) | A 60-second shift at a brick oven with four slots: slide dough in with the peel, crusts go pale, golden, dark, burnt, and slots nearer the fire bake faster; pulling golden scores 3, dark 1, pale 0, and a burnt loaf is a strike, three end the round (forged by the crew on the engine and shell above, not by the original creators) | Tap a slot, or arrows + space to slide in, enter to pull | |
| 34 | 34 | | [](tightrope/) | Three crossings of a wire between two rooftops: the walker steps on alone while a lean angle falls away from centre and wind gusts (shown in the grass and the chimney flag a beat early) tip it; hold left or right to lean back, but a long hold overcorrects, and past 30 degrees you drop to the net and restart from the last of three marks; a crossing scores 10 plus 1 per second under 60, and 5 more if the lean never passed half the limit (forged by the crew on the engine and shell above, not by the original creators) | Hold left or right half of the canvas; arrows or A/D | |
| 35 | 35 | | [](ice-fishing/) | A 60-second round on a frozen lake: hold to let line out through the hole and watch the hook sink in the cut-away, a perch (1), trout (2) or pike (3) crossing the hook at its depth bites, then hold to reel and ease off to let the tension fall; full tension snaps the line and three snaps end the round (forged by the crew on the engine and shell above, not by the original creators) | Hold the canvas; hold space | |
| 36 | | [](archery/) | Ten arrows at a straw target across a meadow: drag back from the archer to draw (the drag length is power, its angle is aim), release to shoot; the wind changes every arrow and shows on the pennant and the grass, holding past three seconds makes the aim sway wider, and rings score 10 (gold), 8, 6, 4 and 2 (forged by the crew on the engine and shell above, not by the original creators) | Drag back, release; arrows + hold space | | |
| 36 | 37 | | [](tram-line/) | A 120-second timetable over eight stops: hold to power, release to coast, brake so the front door lands on the yellow mark; within 0.5 m scores 3, within 2 m scores 1, overshooting the shelter scores 0 and strands the passengers, stopping between stops costs 1, and each second left at the last stop adds 1 (forged by the crew on the engine and shell above, not by the original creators) | Hold up or W (right half) to power, down or S (left half) to brake | |
| 37 | 38 | |
| 38 | 39 | ## Run |
| @@ -53,7 +54,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is | ||
| 53 | 54 | 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. |
| 54 | 55 | |
| 55 | 56 | ## Add a game |
| 56 | 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 and Tram Line 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`. | |
| 57 | 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 and Archery 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`. | |
| 57 | 58 | |
| 58 | 59 | - `shell.js` provides the game menu, the Rules popup, the credits and the background music. |
| 59 | 60 | - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals. |
archery/index.html added +455
| @@ -0,0 +1,455 @@ | ||
| 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>Archery</title> | |
| 7 | <!-- og:begin --> | |
| 8 | <meta name="description" content="Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10"> | |
| 9 | <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/archery/"> | |
| 10 | <meta property="og:type" content="website"> | |
| 11 | <meta property="og:site_name" content="Pixel Plays"> | |
| 12 | <meta property="og:title" content="Archery"> | |
| 13 | <meta property="og:description" content="Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10"> | |
| 14 | <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/archery/"> | |
| 15 | <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/archery.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="Archery: 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; : #b33a3a; } | |
| 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: grab; outline: none; user-select: none; -webkit-user-select: none; } | |
| 29 | canvas:active { cursor: grabbing; } | |
| 30 | .hud { position: fixed; left: max(16px, env(safe-area-inset-left)); right: max(16px, env(safe-area-inset-right)); display: flex; justify-content: space-between; gap: 16px; pointer-events: none; } | |
| 31 | #scores { position: fixed; top: max(14px, env(safe-area-inset-top)); left: max(16px, env(safe-area-inset-left)); display: grid; gap: 2px; pointer-events: none; } | |
| 32 | #scores b { font-size: 16px; font-weight: 600; font-variant-numeric: tabular-nums; min-width: 5ch; } | |
| 33 | #scores span { color: var(); font-variant-numeric: tabular-nums; min-height: 1.35em; } | |
| 34 | #wind { color: var(); } | |
| 35 | #draw { width: 120px; height: 8px; margin-top: 4px; border: 1px solid var(); position: relative; overflow: hidden; } | |
| 36 | #draw i { position: absolute; inset: 0; background: var(); transform: scaleX(0); transform-origin: left; } | |
| 37 | #draw.tired i { background: var(); } | |
| 38 | #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; } | |
| 39 | #notes { display: grid; gap: 2px; } | |
| 40 | #notes span { color: var(); min-height: 1.35em; } | |
| 41 | button { pointer-events: auto; font: inherit; color: var(); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; } | |
| 42 | button:hover, button:focus-visible, button[aria-pressed="true"] { color: var(); } | |
| 43 | </style> | |
| 44 | </head> | |
| 45 | <body> | |
| 46 | <div id="stage"><canvas id="c" tabindex="0" aria-label="Archery. Drag back from the archer to draw: the drag length is power and its angle is aim; release to shoot. Or press arrow keys to aim, hold space to draw and release it to shoot. Read the pennant for the wind, which changes every arrow, and do not hold too long: the aim sways. Ten arrows, gold scores 10."></canvas></div> | |
| 47 | <div id="scores"> | |
| 48 | <b id="score">0</b><span id="meta"></span><span id="wind" aria-live="off"></span> | |
| 49 | <div id="draw" role="meter" aria-label="Draw" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><i id="draw-fill"></i></div> | |
| 50 | </div> | |
| 51 | <div class="hud" id="bottom"> | |
| 52 | <div id="notes"><span id="status" role="status" aria-live="polite"></span></div> | |
| 53 | <button id="mute" type="button" aria-pressed="false">sound on</button> | |
| 54 | </div> | |
| 55 | <script src="../shell.js"></script> | |
| 56 | <script> | |
| 57 | PixelPlays.mount({ | |
| 58 | id: 'archery', | |
| 59 | rules: [ | |
| 60 | 'Drag back from the archer to draw: the drag length is power, its angle is aim. Release to shoot. Keyboard: arrows to aim, hold space to draw, release to shoot.', | |
| 61 | 'Ten arrows. Gold scores 10, then 8, 6, 4 and 2 outwards; a miss scores 0.', | |
| 62 | 'The wind changes every arrow: the pennant and the grass lean the way it blows, and it pushes the arrow.', | |
| 63 | 'Hold the draw past three seconds and the aim sways wider.', | |
| 64 | ], | |
| 65 | }); | |
| 66 | </script> | |
| 67 | <script>window.PP_SCENE = { originY: 0, shadowX: 1.3, shadowY: -.12 };</script> | |
| 68 | <script src="../engine.js"></script> | |
| 69 | <script src="range.js"></script> | |
| 70 | <script> | |
| 71 | 'use strict'; | |
| 72 | ||
| 73 | const R = window.Archery; | |
| 74 | const KIND_MOWN = 6; | |
| 75 | const HALF_X = 7.6, HALF_Y = 14.6, STRIP = 2.7; // the meadow block, and the half-width of the mown strip | |
| 76 | const MEADOW = [[40, 74, 50], [52, 88, 52], [70, 106, 54], [88, 122, 56]]; | |
| 77 | const MOWN = [[96, 132, 58], [106, 142, 62], [118, 152, 66], [128, 160, 70]]; | |
| 78 | const GOLD = [244, 196, 56], RED = [200, 62, 52], BLUE = [64, 118, 190], BLACK = [44, 42, 48], WHITE = [240, 236, 224]; | |
| 79 | const RINGS = [GOLD, RED, BLUE, BLACK, WHITE]; | |
| 80 | const STRAW = [[188, 150, 84], [204, 166, 96], [172, 134, 72]], WOOD = [128, 94, 62]; | |
| 81 | const ARROW_SHAFT = [232, 214, 168], ARROW_FLETCH = [200, 62, 52]; | |
| 82 | const ARCHER = { shirt: [176, 58, 58], stripe: [236, 226, 204], legs: [58, 66, 84], hair: [74, 50, 34], skin: [222, 170, 132] }; | |
| 83 | const POLE = [-3.6, -4.2, 6.2]; // the pennant pole: beside the flight line, halfway to the target | |
| 84 | const FLAG_COLORS = [[200, 62, 52], [240, 232, 210]]; | |
| 85 | const TIME_SCALE = .5; // flights run in slow motion so the arc and the drift can be read | |
| 86 | const BEST_KEY = 'pixel-plays-archery-best'; | |
| 87 | // the rules live in range-space (downrange x, across y, up z); the scene lays them on the grass as world (y, -x, z) | |
| 88 | const toWorld = (rx, ly, z) => [ly, -rx, z]; | |
| 89 | const dirWorld = d => [d[1], -d[0], d[2]]; | |
| 90 | const ARCHER_AT = toWorld(R.ARCHER_X, 0, 0), FACE_Y = -R.TARGET_X; | |
| 91 | ||
| 92 | /* ---------- the meadow ---------- */ | |
| 93 | function groundColor(x, y, ix, iy, i) { | |
| 94 | const edge = Math.pow(Math.pow(Math.abs(x) / HALF_X, 4) + Math.pow(Math.abs(y) / HALF_Y, 4), .25); | |
| 95 | const rough = edge + (noise(x * 1.3, y * 1.3) - .5) * .12; | |
| 96 | if (rough > 1.04) return 0; | |
| 97 | if (rough > .93 && hash(ix, iy) < (rough - .93) / .11) return 0; | |
| 98 | const fine = hash(ix, iy), side = Math.abs(x) + (noise(y * .5, 7) - .5) * .5; | |
| 99 | if (side < STRIP) { | |
| 100 | kinds[i] = KIND_MOWN; | |
| 101 | const band = Math.floor((y + 40) / 2.4) % 2; // mowing stripes along the flight line | |
| 102 | const t = noise(x * .9, y * .9) * .6 + (fine - .5) * .3 + band * .3 + (bayerAt(ix, iy) - .5) * .25; | |
| 103 | return rgb(...MOWN[clamp(Math.floor(t * 3.4), 0, 3)]); | |
| 104 | } | |
| 105 | kinds[i] = KIND_GRASS; | |
| 106 | const t = noise(x * .9, y * .9) * 1.15 + (fine - .5) * .55 - .08; | |
| 107 | return rgb(...MEADOW[clamp(Math.floor(t * 3.6), 0, 3)]); | |
| 108 | } | |
| 109 | ||
| 110 | /* ---------- the straw target ---------- */ | |
| 111 | // the face is the plane y = FACE_Y; every pixel is traced back onto it to find its distance from the gold | |
| 112 | function bakeFace() { | |
| 113 | const cz = R.TARGET_Z, outer = R.TARGET_R + .26; | |
| 114 | const top = project(0, FACE_Y, cz + outer), bottom = project(0, FACE_Y, cz - outer); | |
| 115 | for (let iy = Math.max(0, Math.floor(top.sy) - 2); iy < Math.min(H, Math.ceil(bottom.sy) + 2); iy++) { | |
| 116 | for (let ix = 0; ix < W; ix++) { | |
| 117 | const u = (ix + .5 - OX) / S, x = u * R2 + FACE_Y, v = (x + FACE_Y) / R2; | |
| 118 | const z = (v * SIN - (iy + .5 - OY) / S) / COS, dist = Math.hypot(x, z - cz); | |
| 119 | if (dist > outer) continue; | |
| 120 | let c; | |
| 121 | if (dist <= R.TARGET_R) c = rgb(...RINGS[Math.min(RINGS.length - 1, Math.floor(dist / R.RING))]); | |
| 122 | else c = rgb(...STRAW[hash(ix, iy) > .7 ? 2 : hash(ix + 5, iy) > .45 ? 1 : 0]); | |
| 123 | const i = iy * W + ix; | |
| 124 | pix[i] = c; | |
| 125 | zb[i] = v * COS + z * SIN; | |
| 126 | } | |
| 127 | } | |
| 128 | } | |
| 129 | function bakeStand() { | |
| 130 | const [x, y] = [0, FACE_Y - .35]; | |
| 131 | for (const side of [-1, 1]) { | |
| 132 | capsule([side * 1.9, y - .9, 0], [side * 1.0, y, R.TARGET_Z - 1.2], .13, .1, () => WOOD, 'solid'); | |
| 133 | } | |
| 134 | capsule([-1.1, y, 1.1], [1.1, y, 1.1], .09, .09, () => WOOD, 'solid'); | |
| 135 | // shadows of the disc and its legs fall to screen-right | |
| 136 | for (let a = -R.TARGET_R; a <= R.TARGET_R; a += .35) for (let b = -R.TARGET_R; b <= R.TARGET_R; b += .35) { | |
| 137 | if (Math.hypot(a, b) <= R.TARGET_R) castShadow(x + a, FACE_Y, R.TARGET_Z + b, .36, 1, .2); | |
| 138 | } | |
| 139 | for (const side of [-1, 1]) for (let k = 0; k <= 4; k++) castShadow(side * (1.9 - .225 * k * .9), y - .9 * (1 - k / 4), (R.TARGET_Z - 1.2) * k / 4, .15, 1, 0); | |
| 140 | } | |
| 141 | function bakePole() { | |
| 142 | capsule([POLE[0], POLE[1], 0], POLE, .09, .07, () => WOOD, 'solid'); | |
| 143 | sphere(POLE[0], POLE[1], POLE[2] + .1, .13, [226, 206, 140], 'solid'); | |
| 144 | for (let k = 0; k <= 28; k++) castShadow(POLE[0], POLE[1], POLE[2] * k / 28, .1, 1, 0); | |
| 145 | } | |
| 146 | ||
| 147 | function bake() { | |
| 148 | ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0); | |
| 149 | tufts.length = 0; | |
| 150 | zb.fill(-1e9); | |
| 151 | pix.fill(rgb(255, 255, 255)); | |
| 152 | for (let iy = 0; iy < H; iy++) for (let ix = 0; ix < W; ix++) { | |
| 153 | const g = unproject(ix + .5, iy + .5), i = iy * W + ix, c = groundColor(g.x, g.y, ix, iy, i); | |
| 154 | if (!c) continue; | |
| 155 | pix[i] = c; ground[i] = 1; | |
| 156 | zb[i] = (g.x + g.y) / R2 * COS; | |
| 157 | } | |
| 158 | growGrass(); | |
| 159 | groundZ.set(zb); | |
| 160 | bakeStand(); | |
| 161 | bakeFace(); | |
| 162 | bakePole(); | |
| 163 | bakeOcclusion(); | |
| 164 | staticShadow.set(shadowMask); | |
| 165 | applyShadows(groundZ); | |
| 166 | bakedPix.set(pix); | |
| 167 | bakedZ.set(zb); | |
| 168 | } | |
| 169 | ||
| 170 | /* ---------- state ---------- */ | |
| 171 | const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })(); | |
| 172 | const G = R.newRound(best0); | |
| 173 | let time = 0, status = '', overFor = 0, lastOver = false, origin = null, flash = null; | |
| 174 | const nodes = { | |
| 175 | score: document.getElementById('score'), meta: document.getElementById('meta'), wind: document.getElementById('wind'), | |
| 176 | status: document.getElementById('status'), draw: document.getElementById('draw'), fill: document.getElementById('draw-fill'), | |
| 177 | }; | |
| 178 | ||
| 179 | /* ---------- the wind, as seen ---------- */ | |
| 180 | // the wind vector on screen: where it points, whole-pixel lean for the grass | |
| 181 | function windScreen(wind) { | |
| 182 | const w = R.windVector(wind), wx = w.y, wy = -w.x; // range -> grass | |
| 183 | return { u: (wx - wy) / R2, v: (wx + wy) / R2 * SIN }; | |
| 184 | } | |
| 185 | const ARROW_GLYPHS = ['→', '↘', '↓', '↙', '←', '↖', '↑', '↗']; | |
| 186 | function windLabel(wind) { | |
| 187 | const s = windScreen(wind), k = (Math.round(Math.atan2(s.v, s.u) / (Math.PI / 4)) + 8) % 8; | |
| 188 | const word = wind.speed < 1.5 ? 'light' : wind.speed < 3.5 ? 'fresh' : 'strong'; | |
| 189 | return 'wind ' + ARROW_GLYPHS[k] + ' ' + wind.speed.toFixed(1) + ' ' + word; | |
| 190 | } | |
| 191 | // the same gust-and-lean as the engine's tufts, with the whole meadow leaning the way the wind blows | |
| 192 | function drawWindTufts(t) { | |
| 193 | const s = windScreen(G.wind), lean = clamp(s.u * .32, -1.7, 1.7); | |
| 194 | for (const tuft of tufts) { | |
| 195 | const gust = STILL ? 0 : Math.sin(t * .8 + tuft.phase) + .5 * Math.sin(t * 2.1 + tuft.phase * 2.3); | |
| 196 | const colors = staticShadow[tuft.i] ? tuftDark : tuftLit; | |
| 197 | for (let k = 1; k <= tuft.height; k++) { | |
| 198 | const jx = tuft.ix + Math.round((gust * .5 + lean) * k / 3), jy = tuft.iy - k; | |
| 199 | if (jx < 0 || jx >= W) continue; | |
| 200 | const j = jy * W + jx; | |
| 201 | if ((kinds[j] !== KIND_GRASS && kinds[j] !== KIND_NONE) || zb[j] !== groundZ[j]) continue; | |
| 202 | pix[j] = tuft.bloom && k === tuft.height ? tuft.bloom : colors[clamp(tuft.base + k + (gust > 1 ? 1 : 0), 1, 4)]; | |
| 203 | } | |
| 204 | } | |
| 205 | } | |
| 206 | // a pennant that streams the way the wind blows: it hangs limp in a calm and lifts to straight out in a gale | |
| 207 | function drawPennant(t) { | |
| 208 | const w = R.windVector(G.wind), f = clamp(G.wind.speed / 4.5, .22, 1), len = 2 + G.wind.speed * .5; | |
| 209 | const dx = w.y / Math.max(G.wind.speed, .01), dy = -w.x / Math.max(G.wind.speed, .01); // grass direction | |
| 210 | const n = Math.ceil(len * 7); | |
| 211 | for (let k = 0; k <= n; k++) { | |
| 212 | const s = k / n, flutter = STILL ? 0 : Math.sin(t * 5 - s * 5) * .1 * f * s; | |
| 213 | const px = POLE[0] + dx * f * s * len, py = POLE[1] + dy * f * s * len, pz = POLE[2] - (1 - f) * s * len * .85 + flutter; | |
| 214 | const half = .6 * (1 - s) + .04, color = rgb(...FLAG_COLORS[Math.floor(s * 4.4) % 2]); | |
| 215 | for (let dz = -half; dz <= half; dz += .06) { | |
| 216 | plot(px, py, pz + dz, color); | |
| 217 | plot(px + .03, py + .03, pz + dz, color); | |
| 218 | } | |
| 219 | if (k % 2 === 0) castShadow(px, py, pz, .2, 1, .2); | |
| 220 | } | |
| 221 | } | |
| 222 | ||
| 223 | /* ---------- the archer ---------- */ | |
| 224 | const archerAdd = (a, b, r0, r1, f) => { | |
| 225 | // the figure's string arm is dropped: it is redrawn bent, with the hand at the nock | |
| 226 | if (a[0] < ARCHER_AT[0] - .3 && b[0] < ARCHER_AT[0] - .3 && a[2] > 1.4) return; | |
| 227 | dynamicAdd(a, b, r0, r1, f); | |
| 228 | }; | |
| 229 | const add = (a, b, r0, r1, color) => dynamicAdd(a, b, r0, r1, () => color); | |
| 230 | const mixv = (a, b, t) => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]; | |
| 231 | // the shot as it would leave now: yaw plus the sway of the time held | |
| 232 | function aimNow() { | |
| 233 | const off = G.phase === 'draw' ? R.sway(G.held) : { yaw: 0, pitch: 0 }; | |
| 234 | return { yaw: G.yaw + off.yaw, pitch: off.pitch }; | |
| 235 | } | |
| 236 | function drawArcher() { | |
| 237 | const power = G.phase === 'draw' ? G.power : 0; | |
| 238 | const pose = { armR: 1.35, armL: .1, stance: .2, crouch: .02, lean: .04 + power * .05 }; | |
| 239 | const grip = figure(ARCHER_AT[0], ARCHER_AT[1], -Math.PI / 2, pose, ARCHER, archerAdd); | |
| 240 | const aim = aimNow(), a = R.ELEVATION + aim.pitch; | |
| 241 | const dir = [Math.sin(aim.yaw) * Math.cos(a), -Math.cos(aim.yaw) * Math.cos(a), Math.sin(a)]; | |
| 242 | const nock = [ARCHER_AT[0] + .12 + dir[0] * -.2, grip[1] + .42 + power * .52, 2.3]; | |
| 243 | // the bow: two limbs curving back from the grip, flexing as it is drawn | |
| 244 | const back = .3 + power * .24, topTip = [grip[0], grip[1] + back, grip[2] + 1.05], botTip = [grip[0], grip[1] + back, grip[2] - 1.05]; | |
| 245 | const limb = [150, 98, 56]; | |
| 246 | add(grip, [grip[0], grip[1] + back * .45, grip[2] + .55], .09, .08, limb); | |
| 247 | add([grip[0], grip[1] + back * .45, grip[2] + .55], topTip, .08, .06, limb); | |
| 248 | add(grip, [grip[0], grip[1] + back * .45, grip[2] - .55], .09, .08, limb); | |
| 249 | add([grip[0], grip[1] + back * .45, grip[2] - .55], botTip, .08, .06, limb); | |
| 250 | add(topTip, nock, .03, .03, [236, 232, 220]); | |
| 251 | add(nock, botTip, .03, .03, [236, 232, 220]); | |
| 252 | // the drawing arm, bent at the elbow, and the nocked arrow | |
| 253 | const shoulder = [ARCHER_AT[0] - .36, ARCHER_AT[1], 2.2], elbow = [ARCHER_AT[0] - .62, nock[1] + .42, 2.28]; | |
| 254 | add(shoulder, elbow, .12, .1, ARCHER.shirt); | |
| 255 | add(elbow, nock, .09, .08, ARCHER.skin); | |
| 256 | if (G.phase === 'ready' || G.phase === 'draw') { | |
| 257 | const tip = [nock[0] + dir[0] * 1.55, nock[1] + dir[1] * 1.55, nock[2] + dir[2] * 1.55]; | |
| 258 | add(nock, tip, .06, .05, ARROW_SHAFT); | |
| 259 | add(nock, mixv(nock, tip, .22), .08, .08, ARROW_FLETCH); | |
| 260 | } | |
| 261 | } | |
| 262 | // an arrow in the air or standing in the target or the grass: tip at p, tail back along dir | |
| 263 | function drawArrowAt(tip, dir, len) { | |
| 264 | const tail = [tip[0] - dir[0] * len, tip[1] - dir[1] * len, tip[2] - dir[2] * len]; | |
| 265 | add(tail, tip, .06, .05, ARROW_SHAFT); | |
| 266 | add(tail, mixv(tail, tip, .22), .09, .09, ARROW_FLETCH); | |
| 267 | } | |
| 268 | function drawArrows() { | |
| 269 | for (const shot of G.shots) drawArrowAt(toWorld(shot.x, shot.y, shot.z), dirWorld(shot.dir), shot.state === 'target' ? 1.1 : 1.3); | |
| 270 | const a = G.arrow; | |
| 271 | if (a) { | |
| 272 | const len = Math.hypot(a.vx, a.vy, a.vz) || 1; | |
| 273 | drawArrowAt(toWorld(a.x, a.y, a.z), dirWorld([a.vx / len, a.vy / len, a.vz / len]), 1.5); | |
| 274 | } | |
| 275 | } | |
| 276 | // a dotted line from the nock along the shot as aimed now (still air): wind and the drop are the player's to read | |
| 277 | function drawAim() { | |
| 278 | if (G.phase !== 'draw' || G.power < R.MIN_POWER) return; | |
| 279 | const aim = aimNow(), a = R.launch(G.power, G.yaw, { yaw: aim.yaw - G.yaw, pitch: aim.pitch }), dots = [], calm = { angle: 0, speed: 0 }; | |
| 280 | let cross = null; | |
| 281 | for (let k = 0; a.state === 'air' && k < 400; k++) { | |
| 282 | R.stepArrow(a, calm, 1 / 60); | |
| 283 | if (k % 3 === 0 && a.state === 'air') { const p = project(...toWorld(a.x, a.y, a.z)); dots.push([p.sx, p.sy]); } | |
| 284 | } | |
| 285 | if (a.state === 'target') cross = project(...toWorld(a.x, a.y, a.z)); | |
| 286 | drawDots(dots, rgb(28, 27, 25)); | |
| 287 | if (cross) { | |
| 288 | const marks = []; | |
| 289 | for (let k = -2; k <= 2; k++) marks.push([cross.sx + k, cross.sy], [cross.sx, cross.sy + k]); | |
| 290 | haloDots(marks); | |
| 291 | drawDots(marks, rgb(28, 27, 25)); | |
| 292 | } | |
| 293 | } | |
| 294 | ||
| 295 | /* ---------- hud ---------- */ | |
| 296 | let shown = ''; | |
| 297 | function renderHud() { | |
| 298 | const pct = Math.round(G.power * 100), tired = G.phase === 'draw' && G.held > R.SWAY_FREE; | |
| 299 | const text = [G.score, G.best, G.shot, G.phase, G.wind.speed, G.wind.angle, pct, tired].join('|'); | |
| 300 | if (text === shown) return; | |
| 301 | shown = text; | |
| 302 | nodes.score.textContent = G.score + (G.score === 1 ? ' point' : ' points'); | |
| 303 | const n = Math.min(R.ARROWS, G.shot + (G.phase === 'over' ? 0 : 1)); | |
| 304 | nodes.meta.textContent = 'arrow ' + n + '/' + R.ARROWS + (G.best ? ' · best ' + G.best : ''); | |
| 305 | nodes.wind.textContent = windLabel(G.wind); | |
| 306 | nodes.fill.style.transform = 'scaleX(' + (pct / 100).toFixed(2) + ')'; | |
| 307 | nodes.draw.classList.toggle('tired', tired); | |
| 308 | nodes.draw.setAttribute('aria-valuenow', String(pct)); | |
| 309 | } | |
| 310 | function setStatus(text) { | |
| 311 | if (text === status) return; | |
| 312 | status = text; | |
| 313 | nodes.status.textContent = text; | |
| 314 | } | |
| 315 | const RING_NAMES = ['gold', 'red', 'blue', 'black', 'white']; | |
| 316 | function statusFor() { | |
| 317 | if (G.phase === 'over') return G.score + (G.score === 1 ? ' point' : ' points') + (G.record ? ' · new best' : ' · best ' + G.best) + ' · tap to play again'; | |
| 318 | if (flash && time - flash.at < 1.6) return flash.text; | |
| 319 | if (G.phase === 'draw') return G.held > R.SWAY_FREE ? 'your arms are tiring, the aim sways' : 'release to shoot'; | |
| 320 | return 'drag back to draw · hold space'; | |
| 321 | } | |
| 322 | ||
| 323 | /* ---------- loop ---------- */ | |
| 324 | let lastShots = 0; | |
| 325 | function update(dt) { | |
| 326 | time += dt; | |
| 327 | R.tick(G, dt); | |
| 328 | if (G.phase === 'fly') { | |
| 329 | const shot = R.fly(G, dt * TIME_SCALE); | |
| 330 | if (shot) { | |
| 331 | const text = shot.state === 'target' ? RING_NAMES[shot.ring] + ' · ' + shot.points : 'missed · 0'; | |
| 332 | flash = { at: time, text: text + (G.phase === 'over' ? '' : ' · wind has changed') }; | |
| 333 | sound(shot.ring === 0 ? 'gold' : shot.state === 'target' ? 'hit' : 'miss'); | |
| 334 | } | |
| 335 | } | |
| 336 | if (G.phase === 'over') { | |
| 337 | overFor += dt; | |
| 338 | if (!lastOver) { | |
| 339 | lastOver = true; | |
| 340 | if (G.record) try { localStorage.setItem(BEST_KEY, String(G.best)); } catch (e) { /* private window: keep it for this visit */ } | |
| 341 | } | |
| 342 | } | |
| 343 | setStatus(statusFor()); | |
| 344 | renderHud(); | |
| 345 | } | |
| 346 | function draw() { | |
| 347 | pix.set(bakedPix); | |
| 348 | zb.set(bakedZ); | |
| 349 | pendingShadows.length = 0; | |
| 350 | drawArcher(); | |
| 351 | drawArrows(); | |
| 352 | const windT = STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS; | |
| 353 | drawWindTufts(windT); | |
| 354 | drawPennant(windT); | |
| 355 | flushShadows(); | |
| 356 | applyShadows(bakedZ); | |
| 357 | shadeEdges(); | |
| 358 | drawAim(); | |
| 359 | ctx.putImageData(image, 0, 0); | |
| 360 | } | |
| 361 | ||
| 362 | /* ---------- input ---------- */ | |
| 363 | function again() { | |
| 364 | if (G.phase === 'over' && overFor > .8) { R.restart(G); overFor = 0; lastOver = false; flash = null; return true; } | |
| 365 | return G.phase === 'over'; | |
| 366 | } | |
| 367 | function toCanvas(e) { | |
| 368 | const r = canvas.getBoundingClientRect(); | |
| 369 | return { x: (e.clientX - r.left) * W / r.width, y: (e.clientY - r.top) * H / r.height }; | |
| 370 | } | |
| 371 | function letGo() { | |
| 372 | if (G.phase !== 'draw') return; | |
| 373 | if (R.release(G)) sound('shoot'); | |
| 374 | else flash = { at: time, text: 'drawn too lightly · no arrow used' }; | |
| 375 | } | |
| 376 | canvas.addEventListener('pointerdown', e => { | |
| 377 | canvas.focus({ preventScroll: true }); | |
| 378 | ensureAudio(); | |
| 379 | if (again() || G.phase !== 'ready') return; | |
| 380 | try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ } | |
| 381 | origin = toCanvas(e); | |
| 382 | R.startDraw(G, false); | |
| 383 | }); | |
| 384 | canvas.addEventListener('pointermove', e => { | |
| 385 | if (!origin || G.phase !== 'draw') return; | |
| 386 | const p = toCanvas(e), aim = R.aimFromDrag(p.x - origin.x, p.y - origin.y); | |
| 387 | R.setAim(G, aim.power, aim.yaw); | |
| 388 | }); | |
| 389 | canvas.addEventListener('pointerup', () => { if (origin) { origin = null; letGo(); } }); | |
| 390 | canvas.addEventListener('pointercancel', () => { if (origin) { origin = null; G.power = 0; letGo(); } }); | |
| 391 | canvas.addEventListener('contextmenu', e => e.preventDefault()); | |
| 392 | canvas.addEventListener('keydown', e => { | |
| 393 | if (e.key === ' ' || e.key === 'Enter') { | |
| 394 | e.preventDefault(); | |
| 395 | ensureAudio(); | |
| 396 | if (e.repeat || again()) return; | |
| 397 | if (G.phase === 'ready') R.startDraw(G, true); | |
| 398 | return; | |
| 399 | } | |
| 400 | if (e.key === 'ArrowLeft') R.nudgeYaw(G, -.012); | |
| 401 | else if (e.key === 'ArrowRight') R.nudgeYaw(G, .012); | |
| 402 | else return; | |
| 403 | e.preventDefault(); | |
| 404 | }); | |
| 405 | canvas.addEventListener('keyup', e => { if ((e.key === ' ' || e.key === 'Enter') && !origin) letGo(); }); | |
| 406 | addEventListener('blur', () => { if (G.phase === 'draw') { origin = null; G.power = 0; letGo(); } }); | |
| 407 | ||
| 408 | /* ---------- sound ---------- */ | |
| 409 | let audio = null, muted = false; | |
| 410 | function ensureAudio() { | |
| 411 | if (audio) { if (audio.state === 'suspended') audio.resume(); return; } | |
| 412 | const AC = window.AudioContext || window.webkitAudioContext; | |
| 413 | if (AC) audio = new AC(); | |
| 414 | } | |
| 415 | function tone(type, from, to, len, vol) { | |
| 416 | const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator(); | |
| 417 | osc.type = type; | |
| 418 | osc.frequency.setValueAtTime(from, now); | |
| 419 | osc.frequency.exponentialRampToValueAtTime(to, now + len); | |
| 420 | gain.gain.setValueAtTime(vol, now); | |
| 421 | gain.gain.exponentialRampToValueAtTime(.0005, now + len); | |
| 422 | osc.connect(gain).connect(audio.destination); | |
| 423 | osc.start(now); osc.stop(now + len + .01); | |
| 424 | } | |
| 425 | function sound(kind) { | |
| 426 | if (!audio || muted) return; | |
| 427 | if (kind === 'shoot') tone('triangle', 420, 140, .14, .09); | |
| 428 | else if (kind === 'hit') tone('square', 150, 70, .1, .08); | |
| 429 | else if (kind === 'gold') { tone('square', 150, 70, .1, .08); tone('triangle', 660, 990, .22, .08); } | |
| 430 | else if (kind === 'miss') tone('sawtooth', 220, 90, .2, .04); | |
| 431 | } | |
| 432 | const muteButton = document.getElementById('mute'); | |
| 433 | muteButton.addEventListener('click', () => { | |
| 434 | muted = !muted; | |
| 435 | muteButton.textContent = muted ? 'sound off' : 'sound on'; | |
| 436 | muteButton.setAttribute('aria-pressed', String(muted)); | |
| 437 | }); | |
| 438 | ||
| 439 | /* ---------- boot ---------- */ | |
| 440 | addEventListener('resize', fit); | |
| 441 | fit(); | |
| 442 | bake(); | |
| 443 | setStatus(statusFor()); | |
| 444 | renderHud(); | |
| 445 | let last = performance.now(); | |
| 446 | function frame(now) { | |
| 447 | update(Math.min(.04, (now - last) / 1000)); | |
| 448 | last = now; | |
| 449 | draw(); | |
| 450 | requestAnimationFrame(frame); | |
| 451 | } | |
| 452 | requestAnimationFrame(frame); | |
| 453 | </script> | |
| 454 | </body> | |
| 455 | </html> |
archery/page.test.mjs added +48
| @@ -0,0 +1,48 @@ | ||
| 1 | import { test, expect, setDefaultTimeout } from 'bun:test'; | |
| 2 | import { boot } from '../playtest.mjs'; | |
| 3 | setDefaultTimeout(60000); | |
| 4 | ||
| 5 | const KEY = 'pixel-plays-archery-best'; | |
| 6 | const BACK = [[200, 150], [150, 175]]; // a down-left drag of ~56 px: a real draw | |
| 7 | const shoot = g => { g.drag(BACK[0], BACK[1], .3); g.run(3); }; | |
| 8 | ||
| 9 | test('archery: a down-left drag fires an arrow and the HUD moves on', () => { | |
| 10 | const g = boot('archery'); | |
| 11 | expect(g.text()).toContain('arrow 1/10'); | |
| 12 | g.drag(BACK[0], BACK[1], .3); | |
| 13 | g.run(3); | |
| 14 | expect(g.errors.map(e => e.message)).toEqual([]); | |
| 15 | expect(g.text()).toContain('arrow 2/10'); | |
| 16 | }); | |
| 17 | ||
| 18 | test('archery: a drag under MIN_POWER lets the bow down and uses no arrow', () => { | |
| 19 | const g = boot('archery'); | |
| 20 | g.drag([200, 150], [196, 152], .2); | |
| 21 | expect(g.text()).toContain('no arrow used'); | |
| 22 | expect(g.text()).toContain('arrow 1/10'); | |
| 23 | }); | |
| 24 | ||
| 25 | test('archery: ten shots end the round with a new best, saved, and a tap starts again', () => { | |
| 26 | const g = boot('archery'); | |
| 27 | for (let i = 0; i < 10; i++) shoot(g); | |
| 28 | expect(g.errors.map(e => e.message)).toEqual([]); | |
| 29 | expect(g.text()).toContain('new best'); | |
| 30 | expect(g.text()).toContain('tap to play again'); | |
| 31 | expect(g.store[KEY]).toBeDefined(); | |
| 32 | const best = g.store[KEY]; | |
| 33 | g.run(1); | |
| 34 | g.tap(180, 140); | |
| 35 | g.run(.3); | |
| 36 | expect(g.text()).toContain('arrow 1/10'); | |
| 37 | expect(g.text()).toContain('best ' + best); | |
| 38 | }); | |
| 39 | ||
| 40 | test('archery: holding space draws the bow and letting go shoots', () => { | |
| 41 | const g = boot('archery'); | |
| 42 | g.keyDown(' '); | |
| 43 | g.run(1.3); | |
| 44 | expect(g.text()).toContain('release to shoot'); | |
| 45 | g.keyUp(' '); | |
| 46 | g.run(3); | |
| 47 | expect(g.text()).toContain('arrow 2/10'); | |
| 48 | }); |
archery/range.js added +161
| @@ -0,0 +1,161 @@ | ||
| 1 | 'use strict'; | |
| 2 | // Archery rules as plain data in, plain data out: a drag becomes a draw (length = power, angle = aim), holding past three seconds | |
| 3 | // makes the aim sway wider, the arrow flies under gravity and drifts with the wind, the straw target scores by distance from | |
| 4 | // the gold, and the tenth arrow ends the round. World units: x runs downrange from the archer, y across the meadow, z is up. | |
| 5 | (function (root) { | |
| 6 | const ARROWS = 10; | |
| 7 | const GRAVITY = 9.8; | |
| 8 | const ARCHER_X = -11, RELEASE_X = -10, RELEASE_Z = 2.1; // the nock when the string lets go | |
| 9 | const TARGET_X = 11, TARGET_Z = 2.4; // the straw face stands in the plane x = TARGET_X | |
| 10 | const RING = .4, SCORES = [10, 8, 6, 4, 2]; // ring k (from the gold) spans RING * k out to RING * (k + 1) | |
| 11 | const TARGET_R = RING * SCORES.length; | |
| 12 | const V_MAX = 34, V_MIN_SHARE = .3; // arrow speed at full draw, and the share of it a feeble draw still has | |
| 13 | const MIN_POWER = .2; // a lighter draw is let down without shooting | |
| 14 | const FULL_PX = 78; // canvas pixels of drag for a full draw | |
| 15 | const DRAW_TIME = 1.1; // seconds to draw fully with the keyboard | |
| 16 | const YAW_MAX = .45, YAW_GAIN = .5; | |
| 17 | const SWAY_FREE = 3, SWAY_BASE = .008, SWAY_GROW = .014, SWAY_MAX = .09; // radians; steady up to 3 s, then the arms tire | |
| 18 | const WIND_MAX = 6, WIND_PUSH = 3; // wind speed, and the acceleration each unit of it gives the arrow | |
outdated
WIND_PUSH 1.3 over a flight of about 0.6 s drifts at most about 1.5 units, against a target radius of 2.0. Ignoring the wind averages 8.26 points per arrow and never misses. Retune this, and the flight time if needed, so that ignoring a strong crosswind misses the face. |
||
| 19 | const STEP = 1 / 120, FLIGHT_MAX = 4; | |
| 20 | const SIN = .5, R2 = Math.SQRT2; // the fixed camera, to turn a screen drag into a heading on the grass | |
| 21 | const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); | |
| 22 | ||
| 23 | // the launch elevation at which a full draw in still air reaches the gold: solves z0 + D*T - k*(1 + T*T) = TARGET_Z for T = tan(elevation) | |
| 24 | function solveElevation() { | |
| 25 | const D = TARGET_X - RELEASE_X, k = GRAVITY * D * D / (2 * V_MAX * V_MAX), c = TARGET_Z - RELEASE_Z + k; | |
| 26 | return Math.atan((D - Math.sqrt(D * D - 4 * k * c)) / (2 * k)); | |
| 27 | } | |
| 28 | const ELEVATION = solveElevation(); | |
| 29 | ||
| 30 | const speedOf = power => V_MAX * (V_MIN_SHARE + (1 - V_MIN_SHARE) * clamp(power, 0, 1)); | |
| 31 | // a screen drag (canvas pixels, from where the finger went down) -> power and yaw. The arrow leaves opposite the drag, and the | |
| 32 | // pull is read on the grass: the target stands up-right of the archer on screen, so dragging down-left (straight back) gives yaw 0. | |
| 33 | function aimFromDrag(dx, dy) { | |
| 34 | const power = clamp(Math.hypot(dx, dy) / FULL_PX, 0, 1); | |
| 35 | if (power < .02) return { power, yaw: 0 }; | |
| 36 | // undo the camera: screen (u, v) -> grass (wx, wy); downrange is -wy, across (to the archer's left) is +wx | |
| 37 | const u = -dx, v = -dy / SIN, wx = (u + v) / R2, wy = (v - u) / R2; | |
| 38 | return { power, yaw: clamp(Math.atan2(wx, -wy) * YAW_GAIN, -YAW_MAX, YAW_MAX) }; | |
| 39 | } | |
| 40 | // the aim wobbles by this much (radians) after holding for `held` seconds: steady until three seconds, wider after | |
| 41 | function swayAmplitude(held) { | |
| 42 | return Math.min(SWAY_MAX, SWAY_BASE + Math.max(0, held - SWAY_FREE) * SWAY_GROW); | |
| 43 | } | |
| 44 | function sway(held) { | |
| 45 | const a = swayAmplitude(held); | |
| 46 | return { yaw: a * (Math.sin(held * 2.3) + .6 * Math.sin(held * 5.1 + 1)) / 1.6, pitch: a * (Math.sin(held * 1.9 + 2) + .6 * Math.sin(held * 4.3)) / 1.6 }; | |
| 47 | } | |
| 48 | // wind: the direction it blows toward (radians on the grass, 0 = downrange) and its speed | |
| 49 | const windVector = wind => ({ x: Math.cos(wind.angle) * wind.speed, y: Math.sin(wind.angle) * wind.speed }); | |
| 50 | function newWind(rng = Math.random) { | |
| 51 | return { angle: rng() * Math.PI * 2, speed: Math.round((.5 + rng() * (WIND_MAX - .5)) * 10) / 10 }; | |
| 52 | } | |
| 53 | function launch(power, yaw, offset = { yaw: 0, pitch: 0 }) { | |
| 54 | const v = speedOf(power), az = yaw + offset.yaw, el = ELEVATION + offset.pitch; | |
| 55 | return { x: RELEASE_X, y: 0, z: RELEASE_Z, vx: v * Math.cos(el) * Math.cos(az), vy: v * Math.cos(el) * Math.sin(az), vz: v * Math.sin(el), t: 0, state: 'air' }; | |
| 56 | } | |
| 57 | // ring scoring by distance from the centre; (y, z) is where the arrow met the face | |
| 58 | function scoreHit(y, z) { | |
| 59 | const dist = Math.hypot(y, z - TARGET_Z), k = Math.floor(dist / RING + 1e-9); | |
| 60 | return k < SCORES.length ? { ring: k, points: SCORES[k], dist } : { ring: -1, points: 0, dist }; | |
| 61 | } | |
| 62 | // advance an arrow by dt; it ends on the face of the target ('target'), or the grass ('ground') | |
| 63 | function stepArrow(a, wind, dt = STEP) { | |
| 64 | if (a.state !== 'air') return a; | |
| 65 | const w = windVector(wind), ax = WIND_PUSH * w.x, ay = WIND_PUSH * w.y, az = -GRAVITY; | |
| 66 | const next = { | |
| 67 | x: a.x + a.vx * dt + ax * dt * dt / 2, y: a.y + a.vy * dt + ay * dt * dt / 2, z: a.z + a.vz * dt + az * dt * dt / 2, | |
| 68 | vx: a.vx + ax * dt, vy: a.vy + ay * dt, vz: a.vz + az * dt, | |
| 69 | }; | |
| 70 | const crossed = a.x < TARGET_X && next.x >= TARGET_X; | |
| 71 | if (crossed) { | |
| 72 | const f = (TARGET_X - a.x) / (next.x - a.x), y = a.y + (next.y - a.y) * f, z = a.z + (next.z - a.z) * f; | |
| 73 | if (Math.hypot(y, z - TARGET_Z) <= TARGET_R) { | |
| 74 | Object.assign(a, { x: TARGET_X, y, z, vx: next.vx, vy: next.vy, vz: next.vz, t: a.t + dt * f, state: 'target' }); | |
| 75 | return a; | |
| 76 | } | |
| 77 | } | |
| 78 | Object.assign(a, next, { t: a.t + dt }); | |
| 79 | if (a.z <= 0) { a.z = 0; a.state = 'ground'; } | |
| 80 | else if (a.t > FLIGHT_MAX) a.state = 'ground'; | |
| 81 | return a; | |
| 82 | } | |
| 83 | // fly one arrow to its end: where it lands and what it scores | |
| 84 | function landing(power, yaw, wind, offset) { | |
| 85 | const a = launch(power, yaw, offset); | |
| 86 | while (a.state === 'air') stepArrow(a, wind); | |
| 87 | const hit = a.state === 'target' ? scoreHit(a.y, a.z) : { ring: -1, points: 0, dist: Infinity }; | |
| 88 | return { x: a.x, y: a.y, z: a.z, t: a.t, state: a.state, ring: hit.ring, points: hit.points, dist: hit.dist }; | |
| 89 | } | |
| 90 | ||
| 91 | /* ---------- the round ---------- */ | |
| 92 | function newRound(best = 0, rng = Math.random) { | |
| 93 | return { phase: 'ready', rng, shot: 0, score: 0, best, record: false, wind: newWind(rng), held: 0, power: 0, yaw: 0, auto: false, arrow: null, shots: [] }; | |
| 94 | } | |
| 95 | // begin drawing; auto grows the draw by itself (keyboard), otherwise setAim follows the drag | |
| 96 | function startDraw(s, auto = false) { | |
| 97 | if (s.phase !== 'ready') return s; | |
| 98 | Object.assign(s, { phase: 'draw', held: 0, power: 0, auto }); | |
| 99 | return s; | |
| 100 | } | |
| 101 | function setAim(s, power, yaw) { | |
| 102 | if (s.phase !== 'draw') return s; | |
| 103 | s.power = clamp(power, 0, 1); | |
| 104 | s.yaw = clamp(yaw, -YAW_MAX, YAW_MAX); | |
| 105 | return s; | |
| 106 | } | |
| 107 | function nudgeYaw(s, by) { | |
| 108 | if (s.phase === 'draw' || s.phase === 'ready') s.yaw = clamp(s.yaw + by, -YAW_MAX, YAW_MAX); | |
| 109 | return s; | |
| 110 | } | |
| 111 | function tick(s, dt) { | |
| 112 | if (s.phase !== 'draw') return s; | |
| 113 | s.held += dt; | |
| 114 | if (s.auto) s.power = Math.min(1, s.held / DRAW_TIME); | |
| 115 | return s; | |
| 116 | } | |
| 117 | // let go: a real draw sends an arrow with the current sway; a feeble one is let down and costs nothing | |
| 118 | function release(s) { | |
| 119 | if (s.phase !== 'draw') return null; | |
| 120 | if (s.power < MIN_POWER) { Object.assign(s, { phase: 'ready', held: 0, power: 0 }); return null; } | |
| 121 | s.arrow = launch(s.power, s.yaw, sway(s.held)); | |
| 122 | s.phase = 'fly'; | |
| 123 | return s.arrow; | |
| 124 | } | |
| 125 | // advance the flight by dt; returns the shot record on the step it ends | |
| 126 | function fly(s, dt) { | |
| 127 | if (s.phase !== 'fly') return null; | |
| 128 | for (let left = dt; left > 1e-9 && s.arrow.state === 'air'; left -= STEP) stepArrow(s.arrow, s.wind, Math.min(STEP, left)); | |
| 129 | if (s.arrow.state === 'air') return null; | |
| 130 | const a = s.arrow, hit = a.state === 'target' ? scoreHit(a.y, a.z) : { ring: -1, points: 0, dist: Infinity }; | |
| 131 | const len = Math.hypot(a.vx, a.vy, a.vz) || 1; | |
| 132 | const shot = { n: s.shot + 1, state: a.state, x: a.x, y: a.y, z: a.z, dir: [a.vx / len, a.vy / len, a.vz / len], ring: hit.ring, points: hit.points, wind: s.wind }; | |
| 133 | s.shots.push(shot); | |
| 134 | s.shot++; | |
| 135 | s.score += shot.points; | |
| 136 | s.arrow = null; | |
| 137 | if (s.shot >= ARROWS) { | |
| 138 | s.phase = 'over'; | |
| 139 | s.record = s.score > s.best; | |
| 140 | if (s.record) s.best = s.score; | |
| 141 | } else { | |
| 142 | s.phase = 'ready'; | |
| 143 | s.wind = newWind(s.rng); | |
| 144 | } | |
| 145 | Object.assign(s, { held: 0, power: 0 }); | |
| 146 | return shot; | |
| 147 | } | |
| 148 | function restart(s) { | |
| 149 | Object.assign(s, newRound(s.best, s.rng)); | |
| 150 | return s; | |
| 151 | } | |
| 152 | ||
| 153 | const api = { | |
| 154 | ARROWS, GRAVITY, ARCHER_X, RELEASE_X, RELEASE_Z, TARGET_X, TARGET_Z, RING, SCORES, TARGET_R, V_MAX, MIN_POWER, FULL_PX, DRAW_TIME, | |
| 155 | YAW_MAX, SWAY_FREE, WIND_MAX, WIND_PUSH, ELEVATION, | |
| 156 | speedOf, aimFromDrag, swayAmplitude, sway, windVector, newWind, launch, scoreHit, stepArrow, landing, | |
| 157 | newRound, startDraw, setAim, nudgeYaw, tick, release, fly, restart, | |
| 158 | }; | |
| 159 | if (typeof module !== 'undefined' && module.exports) module.exports = api; | |
| 160 | else root.Archery = api; | |
| 161 | })(typeof window !== 'undefined' ? window : globalThis); |
archery/range.test.mjs added +174
| @@ -0,0 +1,174 @@ | ||
| 1 | import { test, expect } from 'bun:test'; | |
| 2 | import { createRequire } from 'node:module'; | |
| 3 | ||
| 4 | const A = createRequire(import.meta.url)('./range.js'); | |
| 5 | const CALM = { angle: 0, speed: 0 }; | |
| 6 | const seeded = (seed = 7) => () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296; | |
| 7 | // shoot a full round of arrows through the state machine | |
| 8 | const shoot = (s, power = 1, yaw = 0) => { | |
| 9 | A.startDraw(s); A.setAim(s, power, yaw); A.release(s); | |
| 10 | let shot = null; | |
| 11 | for (let i = 0; i < 400 && !shot; i++) shot = A.fly(s, 1 / 30); | |
| 12 | return shot; | |
| 13 | }; | |
| 14 | ||
| 15 | test('with no wind a well-aimed full draw lands in the gold', () => { | |
| 16 | const r = A.landing(1, 0, CALM); | |
| 17 | expect(r.state).toBe('target'); | |
| 18 | expect(r.points).toBe(10); | |
| 19 | expect(r.ring).toBe(0); | |
| 20 | expect(r.dist).toBeLessThan(A.RING); | |
| 21 | }); | |
| 22 | ||
| 23 | test('a lighter draw falls short of the gold, and a feeble one is let down without a shot', () => { | |
| 24 | expect(A.landing(.7, 0, CALM).points).toBeLessThan(10); | |
| 25 | const s = A.newRound(0, seeded()); | |
| 26 | A.startDraw(s); A.setAim(s, .1, 0); | |
| 27 | expect(A.release(s)).toBe(null); | |
| 28 | expect(s.phase).toBe('ready'); | |
| 29 | expect(s.shot).toBe(0); | |
| 30 | }); | |
| 31 | ||
| 32 | test('aiming sideways moves the landing point sideways', () => { | |
| 33 | expect(A.landing(1, .02, CALM).y).toBeGreaterThan(A.landing(1, 0, CALM).y + .3); | |
| 34 | expect(A.landing(1, -.02, CALM).y).toBeLessThan(A.landing(1, 0, CALM).y - .3); | |
| 35 | }); | |
| 36 | ||
| 37 | test('wind pushes the landing point in its direction', () => { | |
Asserting a drift of more than 0.5 passes even when the wind doesn't matter. Add: a WIND_MAX crosswind ignored scores 0, aiming into it recovers 8 or more, and a seeded mean over newWind() at yaw 0 stays well under 10. |
||
| 38 | const still = A.landing(1, 0, CALM); | |
| 39 | const left = A.landing(1, 0, { angle: Math.PI / 2, speed: 5 }), right = A.landing(1, 0, { angle: -Math.PI / 2, speed: 5 }); | |
| 40 | expect(left.y).toBeGreaterThan(still.y + 1.5); | |
| 41 | expect(right.y).toBeLessThan(still.y - 1.5); | |
| 42 | expect(A.landing(1, 0, { angle: Math.PI / 2, speed: 5 }).y).toBeGreaterThan(A.landing(1, 0, { angle: Math.PI / 2, speed: 2 }).y); | |
| 43 | // a headwind slows the arrow, so it arrives lower than in still air | |
| 44 | expect(A.landing(1, 0, { angle: Math.PI, speed: 5 }).z).toBeLessThan(still.z); | |
| 45 | }); | |
| 46 | ||
| 47 | test('a strong crosswind ignored misses the face, and aiming into it brings the arrow back', () => { | |
| 48 | const gale = { angle: Math.PI / 2, speed: A.WIND_MAX }; | |
| 49 | expect(A.landing(1, 0, gale).points).toBe(0); | |
| 50 | expect(A.landing(1, 0, { angle: -Math.PI / 2, speed: A.WIND_MAX }).points).toBe(0); | |
| 51 | let best = 0; | |
| 52 | for (let yaw = -A.YAW_MAX; yaw < 0; yaw += .005) best = Math.max(best, A.landing(1, yaw, gale).points); | |
| 53 | expect(best).toBeGreaterThanOrEqual(8); | |
| 54 | // a fresh breeze ignored costs at least two rings | |
| 55 | expect(A.landing(1, 0, { angle: Math.PI / 2, speed: 3 }).points).toBeLessThanOrEqual(6); | |
| 56 | }); | |
| 57 | ||
| 58 | test('ignoring the wind costs a lot over many fresh winds', () => { | |
| 59 | const rng = seeded(11); | |
| 60 | let total = 0; | |
| 61 | const n = 3000; | |
| 62 | for (let i = 0; i < n; i++) total += A.landing(1, 0, A.newWind(rng)).points; | |
| 63 | expect(total / n).toBeLessThan(6); | |
| 64 | }); | |
| 65 | ||
| 66 | test('the arrow flies an arc under gravity', () => { | |
| 67 | const a = A.launch(1, 0); | |
| 68 | let top = a.z; | |
| 69 | while (a.state === 'air') { A.stepArrow(a, CALM); top = Math.max(top, a.z); } | |
| 70 | expect(top).toBeGreaterThan(a.z); | |
| 71 | expect(top).toBeGreaterThan(A.RELEASE_Z); | |
| 72 | }); | |
| 73 | ||
| 74 | test('holding past three seconds widens the sway', () => { | |
| 75 | expect(A.swayAmplitude(1)).toBe(A.swayAmplitude(A.SWAY_FREE)); | |
| 76 | expect(A.swayAmplitude(5)).toBeGreaterThan(A.swayAmplitude(3)); | |
| 77 | expect(A.swayAmplitude(7)).toBeGreaterThan(A.swayAmplitude(5)); | |
| 78 | const widest = held => { let m = 0; for (let t = 0; t < 4; t += .01) m = Math.max(m, Math.abs(A.sway(held + t).yaw)); return m; }; | |
| 79 | expect(widest(6)).toBeGreaterThan(widest(0) * 1.5); | |
| 80 | expect(A.swayAmplitude(100)).toBeLessThan(.2); | |
| 81 | }); | |
| 82 | ||
| 83 | test('the sway at release moves the shot', () => { | |
| 84 | const s = A.newRound(0, seeded()); s.wind = CALM; | |
| 85 | A.startDraw(s); A.setAim(s, 1, 0); s.held = 9.3; | |
| 86 | const off = A.sway(9.3), arrow = A.release(s); | |
| 87 | expect(arrow.vy).toBeCloseTo(A.launch(1, 0, off).vy, 9); | |
| 88 | expect(Math.abs(off.yaw) + Math.abs(off.pitch)).toBeGreaterThan(0); | |
| 89 | }); | |
| 90 | ||
| 91 | test('a hit is scored by its ring: gold 10, then 8, 6, 4, 2, and a miss is 0', () => { | |
| 92 | const at = rings => A.scoreHit(0, A.TARGET_Z + rings * A.RING); | |
| 93 | expect(at(0).points).toBe(10); | |
| 94 | expect(at(.5)).toMatchObject({ ring: 0, points: 10 }); | |
| 95 | expect(at(1.5)).toMatchObject({ ring: 1, points: 8 }); | |
| 96 | expect(at(2.5).points).toBe(6); | |
| 97 | expect(at(3.5).points).toBe(4); | |
| 98 | expect(at(4.5).points).toBe(2); | |
| 99 | expect(at(5.5).points).toBe(0); | |
| 100 | expect(A.scoreHit(-1.5 * A.RING, A.TARGET_Z).points).toBe(8); | |
| 101 | expect(A.scoreHit(0, A.TARGET_Z - 4.5 * A.RING).points).toBe(2); | |
| 102 | }); | |
| 103 | ||
| 104 | test('an arrow that misses the face lands in the grass and scores nothing', () => { | |
| 105 | const r = A.landing(1, .3, CALM); | |
| 106 | expect(r.state).toBe('ground'); | |
| 107 | expect(r.points).toBe(0); | |
| 108 | expect(A.landing(.4, 0, CALM).state).toBe('ground'); | |
| 109 | }); | |
| 110 | ||
| 111 | test('a drag turns into power by its length and yaw by its angle', () => { | |
| 112 | expect(A.aimFromDrag(0, 0).power).toBe(0); | |
| 113 | expect(A.aimFromDrag(-300, 150).power).toBe(1); | |
| 114 | expect(A.aimFromDrag(-A.FULL_PX / 2, 0).power).toBeCloseTo(.5, 5); | |
| 115 | // straight back from the target on screen (down-left): yaw 0; either side of it turns the other way | |
| 116 | const back = A.aimFromDrag(-70.7, 35.4); | |
| 117 | expect(back.power).toBeCloseTo(1, 1); | |
| 118 | expect(back.yaw).toBeCloseTo(0, 2); | |
| 119 | expect(A.aimFromDrag(-70.7, 0).yaw).toBeGreaterThan(.1); | |
| 120 | expect(A.aimFromDrag(-70.7, 70).yaw).toBeLessThan(-.1); | |
| 121 | expect(Math.abs(A.aimFromDrag(0, 90).yaw)).toBeLessThanOrEqual(A.YAW_MAX); | |
| 122 | // a drag that lands in the gold: aimed along the pull, in still air | |
| 123 | const aim = A.aimFromDrag(-70.7, 35.4); | |
| 124 | expect(A.landing(aim.power, aim.yaw, CALM).points).toBe(10); | |
| 125 | }); | |
| 126 | ||
| 127 | test('the keyboard draws by itself while held and the bow is full after DRAW_TIME', () => { | |
| 128 | const s = A.newRound(0, seeded()); | |
| 129 | A.startDraw(s, true); | |
| 130 | A.tick(s, A.DRAW_TIME / 2); | |
| 131 | expect(s.power).toBeCloseTo(.5, 5); | |
| 132 | A.tick(s, A.DRAW_TIME); | |
| 133 | expect(s.power).toBe(1); | |
| 134 | expect(s.held).toBeCloseTo(A.DRAW_TIME * 1.5, 9); | |
| 135 | A.nudgeYaw(s, .02); | |
| 136 | expect(s.yaw).toBeCloseTo(.02, 9); | |
| 137 | }); | |
| 138 | ||
| 139 | test('the wind changes between arrows and stays within its range', () => { | |
| 140 | const s = A.newRound(0, seeded(3)); | |
| 141 | const seen = new Set([s.wind.speed + ':' + s.wind.angle]); | |
| 142 | for (let i = 0; i < 4; i++) { shoot(s, 1, 0); seen.add(s.wind.speed + ':' + s.wind.angle); } | |
| 143 | expect(seen.size).toBe(5); | |
| 144 | for (const k of seen) { const speed = Number(k.split(':')[0]); expect(speed).toBeGreaterThanOrEqual(.5); expect(speed).toBeLessThanOrEqual(A.WIND_MAX); } | |
| 145 | }); | |
| 146 | ||
| 147 | test('the tenth arrow ends the round, and a new best is kept', () => { | |
| 148 | const s = A.newRound(0, seeded()); | |
| 149 | s.wind = CALM; | |
| 150 | for (let n = 1; n <= A.ARROWS; n++) { | |
| 151 | s.wind = CALM; | |
| 152 | const shot = shoot(s, 1, 0); | |
| 153 | expect(shot.n).toBe(n); | |
| 154 | expect(shot.points).toBe(10); | |
| 155 | expect(s.shot).toBe(n); | |
| 156 | expect(s.phase).toBe(n < A.ARROWS ? 'ready' : 'over'); | |
| 157 | } | |
| 158 | expect(s.score).toBe(100); | |
| 159 | expect(s.best).toBe(100); | |
| 160 | expect(s.record).toBe(true); | |
| 161 | expect(A.startDraw(s).phase).toBe('over'); | |
| 162 | const best = s.best; | |
| 163 | A.restart(s); | |
| 164 | expect(s).toMatchObject({ phase: 'ready', shot: 0, score: 0, best }); | |
| 165 | expect(s.shots).toEqual([]); | |
| 166 | }); | |
| 167 | ||
| 168 | test('a worse round does not lower the best', () => { | |
| 169 | const s = A.newRound(50, seeded()); | |
| 170 | for (let n = 0; n < A.ARROWS; n++) { s.wind = CALM; shoot(s, 1, .3); } | |
| 171 | expect(s.score).toBe(0); | |
| 172 | expect(s.best).toBe(50); | |
| 173 | expect(s.record).toBe(false); | |
| 174 | }); |
index.html +1
| @@ -83,6 +83,7 @@ footer a::after { content: none; } | ||
| 83 | 83 | <li data-kind="Timing" data-input="Tap" style="--accent:#c0612b"><a href="bread-oven/">Bread Oven</a><span>Slide loaves into a wood-fired oven and pull each one out golden: golden 3, dark 1, a burnt loaf is a strike</span><span>Game forged by the crew</span><span class="tags">Timing · Tap</span></li> |
| 84 | 84 | <li data-kind="Precision" data-input="Hold" style="--accent:#cf4b3a"><a href="tightrope/">Tightrope</a><span>Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
| 85 | 85 | <li data-kind="Timing" data-input="Hold" style="--accent:#6fb3d2"><a href="ice-fishing/">Ice Fishing</a><span>Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li> |
| 86 | <li data-kind="Sport" data-input="Drag" style="--accent:#b33a3a"><a href="archery/">Archery</a><span>Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10</span><span>Game forged by the crew</span><span class="tags">Sport · Drag</span></li> | |
| 86 | 87 | <li data-kind="Precision" data-input="Hold" style="--accent:#c9a227"><a href="tram-line/">Tram Line</a><span>Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing</span><span>Game forged by the crew</span><span class="tags">Precision · Hold</span></li> |
| 87 | 88 | </ul> |
| 88 | 89 | <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/archery.png added
og/home.png
serve.test.mjs +7
| @@ -184,6 +184,13 @@ test('Ice Fishing and its rules script are served without a track', async () => | ||
| 184 | 184 | expect((await fetch(base + '/ice-fishing/hole.js')).status).toBe(200); |
| 185 | 185 | }); |
| 186 | 186 | |
| 187 | test('Archery and its rules script are served without a track', async () => { | |
| 188 | const page = await fetch(base + '/archery/'); | |
| 189 | expect(page.status).toBe(200); | |
| 190 | expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8'); | |
| 191 | expect((await fetch(base + '/archery/range.js')).status).toBe(200); | |
| 192 | }); | |
| 193 | ||
| 187 | 194 | test('every game and the home page carry share-card tags and a served PNG card', async () => { |
| 188 | 195 | const { games, withTags, ORIGIN, CARD, HOME } = await import('./scripts/og.mjs'); |
| 189 | 196 | const { readFileSync } = await import('node:fs'); |
shell.js +1
| @@ -27,6 +27,7 @@ window.PixelPlays = (() => { | ||
| 27 | 27 | { id: 'bread-oven', title: 'Bread Oven', blurb: 'Slide loaves into a wood-fired oven and pull each one out golden: golden 3, dark 1, a burnt loaf is a strike', kind: 'Timing', input: 'Tap', accent: '#c0612b', music: false, forged: true }, |
| 28 | 28 | { id: 'tightrope', title: 'Tightrope', blurb: 'Walk a wire between two rooftops, leaning against the wind to stay up: 10 plus 1 per second under 60, +5 for a steady crossing', kind: 'Precision', input: 'Hold', accent: '#cf4b3a', music: false, forged: true }, |
| 29 | 29 | { id: 'ice-fishing', title: 'Ice Fishing', blurb: 'Drop a line through the ice and reel each fish up before it snaps: hold to let out line, a fish at the hook depth bites, hold to reel but ease off as the tension rises', kind: 'Timing', input: 'Hold', accent: '#6fb3d2', music: false, forged: true }, |
| 30 | { id: 'archery', title: 'Archery', blurb: 'Ten arrows at a straw target across a meadow: drag back to draw, read the pennant for wind, gold scores 10', kind: 'Sport', input: 'Drag', accent: '#b33a3a', music: false, forged: true }, | |
| 30 | 31 | { id: 'tram-line', title: 'Tram Line', blurb: 'Drive a tram along eight stops: brake so the door lands on the yellow mark, exact scores 3, overshoot scores nothing', kind: 'Precision', input: 'Hold', accent: '#c9a227', music: false, forged: true }, |
| 31 | 32 | ]; |
| 32 | 33 | const MUSIC_VOLUME = .4; |
The best saved here, the
no arrow usedlet-down, the HUD arrow count and the restart tap have no page-level test. Add an archery playtest using boot('archery') that checks each of them, including g.store['pixel-plays-archery-best'].