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

Migrated from github.com/amirmushichge/pixel-plays

Add Wood Split: split logs on a chopping block by bringing the axe down on the crack #67

Merged opened this

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

Merged

quill/pixel-plays:quill/57-add-wood-split-split-logs-on-a-chopping → main 5 commits fork 4 threads · 4 unresolved

  • Merged. quill/57-add-wood-split-split-logs-on-a-chopping was merged into main as 553ae24.

Review

Sign in to review this change.
9 files changed +776 −1
README.md +2 −1
@@ -32,6 +32,7 @@ Concept by [abhi](https://x.com/awwbhi2). Game by [AmirMushich](https://x.com/Am
3232 | [Campfire](campfire/) | A 90-second night: keep a campfire at a good height by dragging twigs, branches and logs into the ring; a log smothers a small fire and rain damps the flames (forged by the crew on the engine and shell above, not by the original creators) | Drag from the pile; arrows or 1/2/3 + space |
3333 | [Bread Oven](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 |
3434 | [Tightrope](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 | [Wood Split](wood-split/) | A 60-second round at a chopping block in a farmyard: hold to raise the axe (the longer the hold the stronger the swing, up to a peak, then your arms tire) while the blade sways across the log top, release to swing; on the grain crack at full strength splits it clean for 3, near it for 1, off it or too weak sticks the axe and costs two seconds, and knotty logs need full strength; split halves stack on the woodpile (forged by the crew on the engine and shell above, not by the original creators) | Press and hold the canvas; hold space |
3536 | [Bell Tower](bell-tower/) | The tower rings a peal on four bells of different sizes and you ring it back by pulling the ropes in the same order; a bell must swing back before it rings again, a right peal scores its length and the next is the same peal plus one bell (it starts at three), and a wrong bell ends that peal without scoring, three wrong peals end the game; each bell flashes as it swings, so it plays muted too (forged by the crew on the engine and shell above, not by the original creators) | Tap a rope; 1-4 or the arrows, one per bell |
3637 | [Ice Fishing](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 |
3738 | [Archery](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 |
@@ -56,7 +57,7 @@ On the forge, `forge.json` runs `bun serve.mjs` with health check `/`. State is
5657 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.
5758
5859 ## Add a game
59 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 and Goalkeeper 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`.
60 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, Goalkeeper and Wood Split 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`.
6061
6162 - `shell.js` provides the game menu, the Rules popup, the credits and the background music.
6263 - `engine.js` provides the camera, depth buffer, colour ramps, shadows, edges, figures, trees and wind as globals.
index.html +1
@@ -82,6 +82,7 @@ footer a::after { content: none; }
8282 <li data-kind="Precision" data-input="Drag" style="--accent:#e0793a"><a href="campfire/">Campfire</a><span>Keep a campfire burning through a 90 second night: drag twigs, branches and logs into the ring, a log smothers a small fire and rain damps the flames</span><span>Game forged by the crew</span><span class="tags">Precision · Drag</span></li>
8383 <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>
8484 <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 <li data-kind="Timing" data-input="Hold" style="--accent:#9a6b3c"><a href="wood-split/">Wood Split</a><span>Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds</span><span>Game forged by the crew</span><span class="tags">Timing · Hold</span></li>
8586 <li data-kind="Memory" data-input="Tap" style="--accent:#a8863a"><a href="bell-tower/">Bell Tower</a><span>Ring the peal back: the tower plays a sequence on four bells, pull the ropes in the same order, each round one bell longer</span><span>Game forged by the crew</span><span class="tags">Memory · Tap</span></li>
8687 <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>
8788 <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>
og/home.png
Binary file not shown.
og/wood-split.png added
Binary file not shown.
serve.test.mjs +7
@@ -177,6 +177,13 @@ test('Tightrope and its rules script are served without a track', async () => {
177177 expect((await fetch(base + '/tightrope/wire.js')).status).toBe(200);
178178 });
179179
180 test('Wood Split and its rules script are served without a track', async () => {
181 const page = await fetch(base + '/wood-split/');
182 expect(page.status).toBe(200);
183 expect(page.headers.get('content-type')).toBe('text/html; charset=utf-8');
184 expect((await fetch(base + '/wood-split/block.js')).status).toBe(200);
185 });
186
180187 test('Bell Tower and its rules script are served without a track', async () => {
181188 const page = await fetch(base + '/bell-tower/');
182189 expect(page.status).toBe(200);
shell.js +1
@@ -26,6 +26,7 @@ window.PixelPlays = (() => {
2626 { id: 'campfire', title: 'Campfire', blurb: 'Keep a campfire burning through a 90 second night: drag twigs, branches and logs into the ring, a log smothers a small fire and rain damps the flames', kind: 'Precision', input: 'Drag', accent: '#e0793a', music: false, forged: true },
2727 { 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 },
2828 { 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 { id: 'wood-split', title: 'Wood Split', blurb: 'Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds', kind: 'Timing', input: 'Hold', accent: '#9a6b3c', music: false, forged: true },
2930 { id: 'bell-tower', title: 'Bell Tower', blurb: 'Ring the peal back: the tower plays a sequence on four bells, pull the ropes in the same order, each round one bell longer', kind: 'Memory', input: 'Tap', accent: '#a8863a', music: false, forged: true },
3031 { 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 },
3132 { 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 },
wood-split/block.js added +124
@@ -0,0 +1,124 @@
1 'use strict';
2 // Wood Split rules as plain data in, plain data out: the log and its grain crack, the swing (hold to strength with a tiring peak),
3 // the sway of the aim across the log top, the score for how close the blade lands, the stuck axe, and the end of the round.
4 // Positions are in log units across the top of the log: a runs left to right, the log radius is 1. The page draws from this state.
5 (function (root) {
6 const ROUND = 60; // seconds
7 const PEAK_AT = 1; // seconds of holding to reach full strength
8 const PEAK_HOLD = .45; // seconds the arms stay at full strength before they tire
9 const TIRE_RATE = .9; // strength lost per second of holding past the peak
10 const TIRE_FLOOR = .15;
11 const FULL = .9; // strength that counts as a full swing: a clean split and a knotty log both need it
12 const WEAK = .5; // below this the axe sticks
13 const CLEAN = .16, NEAR = .38; // distance from the crack for a clean split and for a split at all
14 const SWAY_AMP = .75, SWAY_PERIOD = 3; // the aim swings across the log top, slowly enough to read
15 const STUCK_COST = 2; // seconds to work a stuck axe free
16 const KNOTTY = .25; // chance of a knotty log after the first
17 const CRACK_REACH = .5, CRACK_TURN = .6; // how far off centre the crack crosses, and how far it can lean (radians)
18 const FOOT = .18; // half the length of the blade's mark along the row it lands on
19 const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
20 const STEP = 1 / 30;
21
22 // strength 0..1 after holding `h` seconds: it climbs to the peak, stays there a moment, then the arms tire
23 function strengthAt(h) {
24 if (!(h > 0)) return 0;
25 if (h < PEAK_AT) return h / PEAK_AT;
26 if (h <= PEAK_AT + PEAK_HOLD) return 1;
27 return Math.max(TIRE_FLOOR, 1 - (h - PEAK_AT - PEAK_HOLD) * TIRE_RATE);
28 }
29 // where the blade is over the log top after holding `h` seconds; `dir` (+1 or -1) is which way the sway starts
30 function aimAt(dir, h) { return (dir < 0 ? -1 : 1) * SWAY_AMP * Math.sin(2 * Math.PI * Math.max(0, h) / SWAY_PERIOD); }
31
32 function newLog(rng, first) {
33 return {
34 offset: (rng() * 2 - 1) * CRACK_REACH, // where the crack crosses the line the blade sways along
35 angle: (rng() * 2 - 1) * CRACK_TURN, // how far the crack leans from upright, for the eye
36 knotty: !first && rng() < KNOTTY,
37 dir: rng() < .5 ? -1 : 1,
38 knotAt: rng() * 2 - 1, // which side of the crack the knot sits on, for the eye
39 };
40 }
41 // where the crack crosses the row `b` towards the viewer; the blade lands on b = 0, so crackAt(log, 0) is the point that is judged
42 const crackAt = (log, b) => log.offset + b * Math.tan(log.angle || 0);
outdated

Scoring ignores log.angle, but the page draws the crack leaning up to 0.6 rad and the blade as a full chord. The judged point (b=0) is invisible, and any aim 'crosses' the drawn crack. Either judge where the axe head actually lands against the drawn crack, or make the marker show only that point. Then add a test with a non-zero angle.

43 // a swing that lands at `aim` with `strength` against `log`: what happens and what it scores
44 function judge(log, aim, strength) {
45 const dist = Math.abs(aim - crackAt(log, 0));
46 const needFull = log.knotty;
47 if (strength < WEAK || (needFull && strength < FULL) || dist > NEAR) return { result: 'stuck', points: 0, dist, strength };
48 if (dist <= CLEAN && strength >= FULL) return { result: 'clean', points: 3, dist, strength };
49 return { result: 'split', points: 1, dist, strength };
50 }
51
52 function newState(best = 0, rng = Math.random) {
53 return {
54 phase: 'play', time: 0, rng, log: newLog(rng, true), holding: false, hold: 0, aim: 0, strength: 0, stuck: 0,
55 score: 0, split: 0, pile: 0, swings: 0, last: null, lastAt: -99,
56 best: Math.max(0, Math.floor(best) || 0), record: false,
57 };
58 }
59 const ready = state => state.phase === 'play' && state.stuck <= 0;
60
61 function end(state) {
62 state.phase = 'over';
63 state.holding = false;
64 state.stuck = 0;
65 if (state.score > state.best) { state.best = state.score; state.record = true; }
66 }
67 // let go: the blade comes down where the aim is, with the strength the hold built
68 function swing(state) {
69 const strength = strengthAt(state.hold), aim = aimAt(state.log.dir, state.hold);
70 const out = judge(state.log, aim, strength);
71 out.aim = aim; out.crack = state.log.offset; out.knotty = state.log.knotty;
72 state.holding = false; state.hold = 0; state.strength = 0;
73 state.swings++;
74 state.last = out; state.lastAt = state.time;
75 if (out.result === 'stuck') state.stuck = STUCK_COST;
76 else {
77 state.score += out.points;
78 state.split++;
79 state.pile += 2;
80 state.log = newLog(state.rng, false);
81 }
82 return out;
83 }
84 // press starts raising the axe, release swings it; returns the swing's outcome on release
85 function setHold(state, on) {
86 if (on) {
87 if (ready(state) && !state.holding) { state.holding = true; state.hold = 0; state.aim = aimAt(state.log.dir, 0); state.strength = 0; }
88 return null;
89 }
90 return state.holding ? swing(state) : null;
91 }
92 function tick(state, dt) {
93 state.time += dt;
94 if (state.stuck > 0) state.stuck = Math.max(0, state.stuck - dt);
95 if (state.holding) {
96 state.hold += dt;
97 state.strength = strengthAt(state.hold);
98 state.aim = aimAt(state.log.dir, state.hold);
99 }
100 if (state.time >= ROUND) { state.time = ROUND; end(state); }
101 }
102 function step(state, dt) {
103 if (state.phase !== 'play' || !(dt > 0)) return state;
104 let left = Math.min(dt, 1);
105 while (left > 1e-9 && state.phase === 'play') {
106 const h = Math.min(STEP, left);
107 tick(state, h);
108 left -= h;
109 }
110 return state;
111 }
112 function restart(state) {
113 Object.assign(state, newState(state.best, state.rng));
114 return state;
115 }
116 const tired = state => state.holding && state.hold > PEAK_AT + PEAK_HOLD;
117
118 const api = {
119 ROUND, PEAK_AT, PEAK_HOLD, FULL, WEAK, CLEAN, NEAR, SWAY_AMP, SWAY_PERIOD, STUCK_COST, CRACK_REACH,
120 FOOT, strengthAt, aimAt, crackAt, judge, newLog, newState, setHold, step, restart, tired,
121 };
122 if (typeof module !== 'undefined' && module.exports) module.exports = api;
123 else root.WoodSplit = api;
124 })(typeof window !== 'undefined' ? window : globalThis);
wood-split/block.test.mjs added +209
@@ -0,0 +1,209 @@
1 import { test, expect } from 'bun:test';
2 import { createRequire } from 'node:module';
3
4 const B = createRequire(import.meta.url)('./block.js');
5 const seeded = (seed = 7) => () => (seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296;
6 // a state whose log has its crack at `offset`, with the sway starting rightwards
7 const fresh = (offset = 0, knotty = false) => {
8 const s = B.newState(0, seeded());
9 s.log = { offset, angle: 0, knotty, dir: 1, knotAt: .5 };
10 return s;
11 };
12 const run = (s, seconds) => { for (let i = 0; i < Math.round(seconds * 30) && s.phase === 'play'; i++) B.step(s, 1 / 30); return s; };
13 // hold for `h` seconds, then let go
14 const swing = (s, h) => { B.setHold(s, true); run(s, h); return B.setHold(s, false); };
15 // the hold time at which the aim crosses `x` while swaying out to the right and back (first crossing)
16 const timeAt = x => Math.asin(x / B.SWAY_AMP) * B.SWAY_PERIOD / (2 * Math.PI);
17
18 test('strength climbs to the peak, stays, then the arms tire', () => {
19 expect(B.strengthAt(0)).toBe(0);
20 expect(B.strengthAt(B.PEAK_AT / 2)).toBeCloseTo(.5, 5);
21 expect(B.strengthAt(B.PEAK_AT)).toBe(1);
22 expect(B.strengthAt(B.PEAK_AT + B.PEAK_HOLD)).toBe(1);
23 expect(B.strengthAt(B.PEAK_AT + B.PEAK_HOLD + .3)).toBeLessThan(1);
24 expect(B.strengthAt(B.PEAK_AT + B.PEAK_HOLD + .6)).toBeLessThan(B.strengthAt(B.PEAK_AT + B.PEAK_HOLD + .3));
25 expect(B.strengthAt(60)).toBeGreaterThan(0);
26 });
27
28 test('holding past the peak lowers the strength of the swing', () => {
29 const s = fresh();
30 B.setHold(s, true);
31 run(s, B.PEAK_AT + .1);
32 const peak = s.strength;
33 expect(peak).toBe(1);
34 run(s, 1.2);
35 expect(s.strength).toBeLessThan(peak);
36 expect(B.tired(s)).toBe(true);
37 });
38
39 test('while held the aim sways across the log top and back', () => {
40 const s = fresh();
41 B.setHold(s, true);
42 const seen = [];
43 for (let i = 0; i < 90; i++) { B.step(s, 1 / 30); seen.push(s.aim); }
44 expect(Math.max(...seen)).toBeGreaterThan(B.SWAY_AMP * .95);
45 expect(Math.min(...seen)).toBeLessThan(-B.SWAY_AMP * .95);
46 expect(Math.max(...seen)).toBeLessThanOrEqual(B.SWAY_AMP + 1e-9);
47 });
48
49 test('a full-strength swing on the crack splits it clean for 3', () => {
50 const s = fresh(.5);
51 const need = timeAt(.5);
52 expect(need).toBeLessThan(B.PEAK_AT); // sanity: the aim crosses .5 on its way out, before the peak
53 // hold until the aim sits on the crack again on the way back, inside the full-strength window
54 const s2 = fresh(.5);
55 const back = B.SWAY_PERIOD / 2 - need;
56 expect(back).toBeGreaterThan(B.PEAK_AT);
57 expect(back).toBeLessThan(B.PEAK_AT + B.PEAK_HOLD + .3);
58 const clean = swing(s2, back);
59 expect(clean.result).toBe('clean');
60 expect(clean.points).toBe(3);
61 expect(s2.score).toBe(3);
62 expect(s2.split).toBe(1);
63 expect(s2.pile).toBe(2);
64 });
65
66 test('judge: on the crack with full strength is 3, near it is 1, off it sticks', () => {
67 const log = { offset: .2, knotty: false };
68 expect(B.judge(log, .2, 1)).toMatchObject({ result: 'clean', points: 3 });
69 expect(B.judge(log, .2 + B.CLEAN - .01, B.FULL)).toMatchObject({ points: 3 });
70 expect(B.judge(log, .2 + B.NEAR - .01, 1)).toMatchObject({ result: 'split', points: 1 });
71 expect(B.judge(log, .2 - B.NEAR + .01, 1)).toMatchObject({ result: 'split', points: 1 });
72 expect(B.judge(log, .2 + B.NEAR + .05, 1)).toMatchObject({ result: 'stuck', points: 0 });
73 });
74
75 test('a near miss scores 1 and brings a new log', () => {
76 const s = fresh(-.1);
77 const before = s.log;
78 const near = s.log.offset + (B.CLEAN + B.NEAR) / 2;
79 const t = Math.asin(near / B.SWAY_AMP) * B.SWAY_PERIOD / (2 * Math.PI);
80 const out = swing(s, B.SWAY_PERIOD / 2 - t);
81 expect(out.result).toBe('split');
82 expect(s.score).toBe(1);
83 expect(s.log).not.toBe(before);
84 });
85
86 test('a weak swing sticks the axe and costs two seconds', () => {
87 const s = fresh(.3);
88 const out = swing(s, .2); // aim is still near the crack, strength is not
89 expect(out.dist).toBeLessThan(B.CLEAN);
90 expect(out.result).toBe('stuck');
91 expect(s.score).toBe(0);
92 expect(s.stuck).toBe(2);
93 const log = s.log;
94 expect(s.log).toBe(log); // the same log waits
95 // no swing while the axe is stuck
96 B.setHold(s, true);
97 expect(s.holding).toBe(false);
98 const at = s.time;
99 run(s, 1);
100 expect(s.stuck).toBeCloseTo(1, 1);
101 B.setHold(s, true);
102 expect(s.holding).toBe(false);
103 run(s, 1.05);
104 expect(s.stuck).toBe(0);
105 expect(s.time - at).toBeGreaterThanOrEqual(2);
106 B.setHold(s, true);
107 expect(s.holding).toBe(true);
108 });
109
110 test('off the crack sticks the axe even at full strength', () => {
111 const s = fresh(-.6);
112 const out = swing(s, B.PEAK_AT + .1); // the aim is on the other side by now
113 expect(out.dist).toBeGreaterThan(B.NEAR);
114 expect(out.result).toBe('stuck');
115 expect(s.stuck).toBe(B.STUCK_COST);
116 });
117
118 test('a knotty log needs full strength: a weaker swing on the crack sticks', () => {
119 expect(B.judge({ offset: 0, knotty: true }, 0, .8)).toMatchObject({ result: 'stuck' });
120 expect(B.judge({ offset: 0, knotty: false }, 0, .8)).toMatchObject({ result: 'split', points: 1 });
121 expect(B.judge({ offset: 0, knotty: true }, 0, 1)).toMatchObject({ result: 'clean', points: 3 });
122 expect(B.judge({ offset: 0, knotty: true }, .25, 1)).toMatchObject({ result: 'split', points: 1 });
123 });
124
125 test('a swing too tired sticks, however well it is aimed', () => {
126 expect(B.judge({ offset: 0, knotty: false }, 0, .15)).toMatchObject({ result: 'stuck' });
127 expect(B.judge({ offset: 0, knotty: false }, 0, B.WEAK - .01).result).toBe('stuck');
128 });
129
130 test('the first log is never knotty and later ones sometimes are', () => {
131 const rng = seeded(3);
132 expect(B.newState(0, rng).log.knotty).toBe(false);
133 let knots = 0;
134 for (let i = 0; i < 400; i++) { const l = B.newLog(rng, false); if (l.knotty) knots++; expect(Math.abs(l.offset)).toBeLessThanOrEqual(B.CRACK_REACH); }
135 expect(knots).toBeGreaterThan(40);
136 expect(knots).toBeLessThan(200);
137 });
138
139 test('each log gets a new crack angle', () => {
140 const rng = seeded(9), angles = new Set();
141 for (let i = 0; i < 10; i++) angles.add(B.newLog(rng, false).angle.toFixed(3));
142 expect(angles.size).toBeGreaterThan(8);
143 });
144
145 test('the clock ends the round at 60 seconds, and a stuck axe does not stop it', () => {
146 const s = fresh();
147 run(s, B.ROUND - 1);
148 expect(s.phase).toBe('play');
149 run(s, 2);
150 expect(s.phase).toBe('over');
151 expect(s.time).toBe(B.ROUND);
152 expect(B.setHold(s, true)).toBeNull();
153 expect(s.holding).toBe(false);
154 });
155
156 test('a round ending mid-hold swings nothing, and the best is kept', () => {
157 const s = B.newState(2, seeded());
158 s.score = 5;
159 B.setHold(s, true);
160 run(s, B.ROUND + 1);
161 expect(s.phase).toBe('over');
162 expect(s.holding).toBe(false);
163 expect(s.best).toBe(5);
164 expect(s.record).toBe(true);
165 const keep = B.newState(9, seeded());
166 keep.score = 3;
167 run(keep, B.ROUND + 1);
168 expect(keep.best).toBe(9);
169 expect(keep.record).toBe(false);
170 });
171
172 test('restart begins a fresh round and keeps the best', () => {
173 const s = fresh();
174 s.score = 7; run(s, B.ROUND + 1);
175 B.restart(s);
176 expect(s.phase).toBe('play');
177 expect(s.score).toBe(0);
178 expect(s.time).toBe(0);
179 expect(s.best).toBe(7);
180 });
181
182 test('a first-time player who lets go as the aim passes the crack splits within a few swings', () => {
183 const s = B.newState(0, seeded(5));
184 let splits = 0;
185 for (let n = 0; n < 4 && splits === 0; n++) {
186 // let go when the aim first comes within the near band of the crack after the arms are half up
187 B.setHold(s, true);
188 while (s.holding && Math.abs(s.aim - s.log.offset) > B.NEAR * .8 || s.hold < B.PEAK_AT * .8) B.step(s, 1 / 30);
189 if (B.setHold(s, false).result !== 'stuck') splits++;
190 run(s, B.STUCK_COST + .1);
191 }
192 expect(splits).toBeGreaterThan(0);
193 });
194
195 test('a leaning crack is judged where the blade lands, on the row b = 0', () => {
196 const log = { offset: .3, angle: .5, knotty: false };
197 const at0 = B.crackAt(log, 0), atRim = B.crackAt(log, 1);
198 expect(at0).toBeCloseTo(.3, 9);
199 expect(Math.abs(atRim - at0)).toBeGreaterThan(B.NEAR); // the lean carries the crack well clear of the landing row at the rim
200 expect(B.judge(log, at0, 1)).toMatchObject({ result: 'clean', points: 3 });
201 expect(B.judge(log, atRim, 1)).toMatchObject({ result: 'stuck' }); // a line that only crosses the crack elsewhere is not on it
202 });
203
204 test('the blade mark is short, so the crack under it stays within the clean band', () => {
205 for (const angle of [-.6, .6]) {
206 const log = { offset: 0, angle, knotty: false };
207 expect(Math.abs(B.crackAt(log, B.FOOT) - B.crackAt(log, 0))).toBeLessThan(B.CLEAN);
208 }
209 });
wood-split/index.html added +432
@@ -0,0 +1,432 @@
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
6 <title>Wood Split</title>
7 <!-- og:begin -->
8 <meta name="description" content="Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds">
9 <link rel="canonical" href="https://pixel-plays--forge-trevato-apps.open-platform.sh/wood-split/">
10 <meta property="og:type" content="website">
11 <meta property="og:site_name" content="Pixel Plays">
12 <meta property="og:title" content="Wood Split">
13 <meta property="og:description" content="Split logs on a chopping block for 60 seconds: hold to raise the axe, release on the crack, a stuck axe costs two seconds">
14 <meta property="og:url" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/wood-split/">
15 <meta property="og:image" content="https://pixel-plays--forge-trevato-apps.open-platform.sh/og/wood-split.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="Wood Split: the opening scene of the game">
20 <meta name="twitter:card" content="summary_large_image">
21 <!-- og:end -->
22 <style>
23 :root { --ink: #1c1b19; --muted: #8b877f; --paper: #fff; --accent: #9a6b3c; --warn: #d6452f; }
24 * { box-sizing: border-box; }
25 html, body { height: 100%; margin: 0; background: var(--paper); color: var(--ink); }
26 body { font: 13px/1.35 ui-monospace, "Cascadia Mono", Consolas, Menlo, monospace; overflow: hidden; }
27 #stage { position: fixed; inset: 0; display: grid; place-items: center; }
28 canvas { display: block; image-rendering: pixelated; touch-action: none; cursor: pointer; outline: none; user-select: none; -webkit-user-select: 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 .row { display: flex; align-items: center; gap: 8px; color: var(--accent); }
32 .row b { font-size: 16px; font-weight: 600; min-width: 2ch; font-variant-numeric: tabular-nums; }
33 .row span { color: var(--muted); }
34 #power { position: fixed; top: max(14px, env(safe-area-inset-top)); right: max(16px, env(safe-area-inset-right)); width: 120px; pointer-events: none; }
35 #power small { display: block; color: var(--muted); margin-bottom: 4px; text-align: right; }
36 #bar { height: 8px; border: 1px solid var(--ink); position: relative; overflow: hidden; }
37 #bar i { position: absolute; inset: 0; background: var(--ink); transform: scaleX(0); transform-origin: left; }
38 #bar.tired i { background: var(--warn); }
39 #bar::after { content: ""; position: absolute; top: 0; bottom: 0; left: 90%; border-left: 1px dotted var(--muted); }
40 #bottom { bottom: max(14px, env(safe-area-inset-bottom)); align-items: flex-end; }
41 #status { color: var(--muted); min-height: 1.35em; }
42 button { pointer-events: auto; font: inherit; color: var(--muted); background: none; border: 0; padding: 10px; margin: -10px; cursor: pointer; }
43 button:hover, button:focus-visible, button[aria-pressed="true"] { color: var(--ink); }
44 </style>
45 </head>
46 <body>
47 <div id="stage"><canvas id="c" tabindex="0" aria-label="A log stands on a chopping block in a farmyard with a grain crack across its top, a woodpile beside it, a figure with an axe and two hens pecking. Press and hold the canvas, or hold space, to raise the axe: the longer you hold the stronger the swing, up to a peak, and holding past it tires your arms. While held the blade sways across the log top; release to bring it down on the crack. On the crack at full strength splits it clean for 3, near it for 1, off it or too weak sticks the axe for two seconds. Knotty logs need full strength. The round lasts 60 seconds."></canvas></div>
48 <div id="scores">
49 <div class="row"><b id="score">0</b><span>score</span></div>
50 <div class="row"><b id="split">0</b><span>logs split</span></div>
51 <div class="row"><b id="clock">60</b><span>seconds</span></div>
52 <div class="row"><b id="best">0</b><span>best</span></div>
53 </div>
54 <div id="power" aria-hidden="true"><small>strength</small><div id="bar"><i id="fill"></i></div></div>
55 <div class="hud" id="bottom">
56 <div id="status" role="status" aria-live="polite"></div>
57 <button id="mute" type="button" aria-pressed="false">sound on</button>
58 </div>
59 <script src="../shell.js"></script>
60 <script>
61 PixelPlays.mount({
62 id: 'wood-split',
63 rules: [
64 'Hold the canvas or space to raise the axe; the blade sways across the log. Let go to swing.',
65 'On the crack at full strength splits it clean for 3, near it for 1. Holding past the peak tires you.',
66 'Off the crack or too weak sticks the axe: two seconds to work it free. Knotty logs need full strength.',
67 '60 seconds: split as many logs as you can.',
68 ],
69 });
70 </script>
71 <script>window.PP_SCENE = { originY: 2, shadowX: 1.3, shadowY: -.12 };</script>
72 <script src="../engine.js"></script>
73 <script src="block.js"></script>
74 <script>
75 'use strict';
76
77 const BEST_KEY = 'pixel-plays-wood-split-best';
78 const LOG_R = 1.6, LOG_TOP = 2.8, BLOCK_R = 2.1, BLOCK_TOP = .9;
79 const FIGURE_AT = [-3.3, .5], FIGURE_SCALE = 1.25, SHAFT = 2.05;
80 const PILE_AT = [4.9, -.9], PILE_ROWS = [6, 5, 4, 3, 2, 1], STACK_GAP = 1.5; // a full stack of 21 halves, then another beside it
outdated

21 halves means the pile stops at 10 logs, well short of a 60 s round for a steady player. Let it keep growing.

81 const PILE_STACK = PILE_ROWS.reduce((n, k) => n + k, 0), PILE_MAX = PILE_STACK * 3;
82 const LOG_BARK = [118, 84, 58], STUMP = [140, 118, 94], STEEL = [170, 176, 190], HANDLE = [150, 104, 64];
83 const RING = [[224, 184, 126], [204, 158, 104]], CRACK = rgb(52, 30, 20), KNOT = rgb(70, 40, 26), KNOT_CORE = rgb(40, 22, 16);
84 const FARMER = { shirt: [188, 64, 56], stripe: [236, 226, 206], legs: [60, 72, 104], hair: [84, 56, 36], skin: [226, 176, 138] };
85 const HENS = [{ a: 3.4, b: 4.3, dir: 1, phase: 0, body: [244, 240, 228] }, { a: 6.3, b: 3.3, dir: -1, phase: 2, body: [176, 108, 64] }];
86
87 // log-local coordinates: a runs to screen-right, b towards the viewer; the world axes are turned 45 degrees from them
88 const world = (a, b, z) => [(a + b) / R2, (b - a) / R2, z];
89 const proj = (a, b, z) => project(...world(a, b, z));
90
91 /* ---------- state ---------- */
92 const best0 = (() => { try { return Number(localStorage.getItem(BEST_KEY)) || 0; } catch (e) { return 0; } })();
93 const G = WoodSplit.newState(best0);
94 let time = 0, status = '', note = '', noteUntil = 0, overFor = 0, lastOver = false, seenAt = -99, shownLog = G.log, logBorn = -99;
95 const nodes = {
96 score: document.getElementById('score'), split: document.getElementById('split'), clock: document.getElementById('clock'), best: document.getElementById('best'),
97 status: document.getElementById('status'), bar: document.getElementById('bar'), fill: document.getElementById('fill'),
98 };
99
100 /* ---------- solids painted point by point: the engine's spheres can't make a flat top ---------- */
101 const shade = (c, idx) => rampOf(c)[clamp(idx, 0, 4)];
102 function cylinder(ca, cb, z0, z1, r, color, seed) {
103 for (let th = 0; th < Math.PI * 2; th += .022) {
104 const nx = Math.cos(th), ny = Math.sin(th);
105 if (ny < -.35) continue; // the far side is never seen
106 const light = -.6 * nx + .5 * ny;
107 for (let z = z0; z <= z1; z += .045) {
108 const grain = noise(th * 7 + seed, z * 1.6 + seed) - .5;
109 plot(...world(ca + nx * r, cb + ny * r, z), shade(color, Math.floor(2.5 + light * 2 + grain * 1.2)));
110 }
111 }
112 }
113 function disc(ca, cb, z, r, colorAt) {
114 for (let a = -r; a <= r; a += .028) for (let b = -r; b <= r; b += .028) {
115 if (a * a + b * b > r * r) continue;
116 plot(...world(ca + a, cb + b, z), colorAt(a, b));
117 }
118 }
119 const rings = (a, b, tone) => {
120 const d = Math.hypot(a - .18, b + .1) * (1 + .12 * Math.sin(Math.atan2(b + .1, a - .18) * 3));
121 const band = Math.floor(d * 4.2 + noise(a * 2, b * 2) * .6) % 2;
122 return rgb(RING[band][0] * tone, RING[band][1] * tone, RING[band][2] * tone);
123 };
124
125 /* ---------- baked scene ---------- */
126 function groundColor(a, b, ix, iy, i) {
127 const d = Math.hypot(a / 9.4, b / 7) + (noise(a * .5, b * .5) - .5) * .16;
128 if (d > 1.04) return 0;
129 if (d > .92 && hash(ix, iy) < (d - .92) / .12) return 0;
130 const yard = Math.hypot((a - .6) / 4.6, (b - .8) / 3.4) + (noise(a * .8 + 3, b * .8) - .5) * .35;
131 const t = .92 + (hash(ix, iy) - .5) * .14;
132 if (yard < 1) return rgb(176 * t, 140 * t, 100 * t); // trodden earth round the block
133 kinds[i] = KIND_GRASS;
134 return rgb(104 * t, 140 * t, 70 * t);
135 }
136 function halfLog(add, a, b, z) {
137 add(world(a, b - .9, z), world(a, b + .9, z), .3, .3, () => LOG_BARK);
138 add(world(a, b + .86, z), world(a, b + .86, z), .22, .22, () => RING[0]);
139 }
140 function bakePile() { // a small stack behind the block, so the yard has wood before the first split
141 const rows = [4, 3, 2];
142 rows.forEach((n, k) => {
143 for (let i = 0; i < n; i++) halfLog((p, q, r0, r1, f) => capsule(p, q, r0, r1, f, 'solid'), -6.2 + (i - (n - 1) / 2) * .64, -4.6, .3 + k * .5);
144 for (let i = 0; i < n; i++) castShadow(...world(-6.2 + (i - (n - 1) / 2) * .64, -4.6, .3 + k * .5), .5, 1, 0);
145 });
146 }
147 function bake() {
148 ground.fill(0); shadowMask.fill(0); staticShadow.fill(0); kinds.fill(0);
149 tufts.length = 0; leaves.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;
154 const c = groundColor((g.x - g.y) / R2, (g.x + g.y) / R2, ix, iy, i);
155 if (!c) continue;
156 pix[i] = c; ground[i] = 1;
157 zb[i] = (g.x + g.y) / R2 * COS;
158 }
159 growGrass();
160 groundZ.set(zb);
161 cylinder(0, 0, 0, BLOCK_TOP, BLOCK_R, STUMP, 3);
162 disc(0, 0, BLOCK_TOP, BLOCK_R, (a, b) => rings(a, b, .9));
163 for (let z = .2; z <= BLOCK_TOP; z += .35) castShadow(...world(0, 0, z), BLOCK_R * .9, 1, 0);
164 bakePile();
165 bakeOcclusion();
166 staticShadow.set(shadowMask);
167 applyShadows(groundZ);
168 bakedPix.set(pix);
169 bakedZ.set(zb);
170 }
171
172 /* ---------- the log ---------- */
173 // where on the log top the knot and the crack sit, for this log
174 const knotSpot = log => [clamp(log.offset + (log.knotAt < 0 ? -.72 : .72), -.9, .9), log.knotAt * .3];
175 function crackDistance(log, a, b) { // across the crack, which leans by log.angle from upright and crosses the aim line at log.offset
176 return Math.abs(a - WoodSplit.crackAt(log, b)) * Math.cos(log.angle);
177 }
178 function drawLog(log, lift) {
179 const z0 = BLOCK_TOP + lift, top = LOG_TOP + lift;
180 cylinder(0, 0, z0, top, LOG_R, LOG_BARK, log.offset * 9);
181 const [ka, kb] = knotSpot(log);
182 disc(0, 0, top, LOG_R, (a, b) => {
183 if (log.knotty) {
184 const k = Math.hypot(a - ka, b - kb);
185 if (k < .13) return KNOT_CORE;
186 if (k < .3) return KNOT;
187 }
188 if (crackDistance(log, a, b) < .085) return CRACK;
189 return rings(a, b, 1);
190 });
191 if (log.knotty) sphere(...world(ka * .7, LOG_R - .06, top - .7), .26, [70, 42, 28], 'solid');
192 // the sliver of bark over the rim, so the top reads as the end of a round log
193 for (let th = 0; th < Math.PI; th += .025) plot(...world(Math.cos(th) * LOG_R, Math.sin(th) * LOG_R, top + .01), shade(LOG_BARK, 1));
194 }
195
196 /* ---------- the figure and the axe ---------- */
197 const ease3 = t => t * t * (3 - 2 * t);
198 // the arms' angle from hanging down, and where the axe head is: resting, rising with the hold, striking, or stuck
199 function axePose() {
200 const since = G.time - G.lastAt, last = G.last;
201 const raised = 2.65, rest = .85, strikeAng = 1.3;
202 const target = last ? world(last.aim, 0, LOG_TOP) : null;
203 if (since >= 0 && since < .14 && last) return { ang: lerp(raised, strikeAng, ease3(since / .14)), strike: ease3(since / .14), shake: 0 };
204 if (G.stuck > 0 && last) return { ang: strikeAng, strike: 1, shake: STILL ? 0 : (Math.floor(time * 12) % 2 ? 1 : -1) * Math.min(1, G.stuck) * .05 };
205 if (since >= .14 && since < .5 && last) return { ang: lerp(strikeAng, rest, ease3((since - .14) / .36)), strike: 1 - ease3((since - .14) / .36), shake: 0 };
206 if (G.holding) {
207 const up = Math.min(1, G.hold / WoodSplit.PEAK_AT), droop = WoodSplit.tired(G) ? (1 - G.strength) * .55 : 0;
208 const tremble = WoodSplit.tired(G) && !STILL ? (Math.floor(time * 14) % 2 ? .05 : -.05) : 0;
209 return { ang: lerp(rest, raised, ease3(up)) - droop + tremble, strike: 0, shake: 0 };
210 }
211 return { ang: rest, strike: 0, shake: 0 };
212 }
213 function farmer() {
214 const p = axePose(), last = G.last, yaw = -Math.PI / 4;
215 const [fa, fb] = FIGURE_AT;
216 const hand = figure(...world(fa, fb, 0).slice(0, 2), yaw, { scale: FIGURE_SCALE, stance: .25, armR: p.ang, armL: p.ang - .05, lean: .12 + p.strike * .2, crouch: p.strike * .3 }, FARMER, dynamicAdd);
217 // the shaft runs on from the hands along the arms' line; in a strike it ends on the blade's mark
218 const d = [Math.sin(p.ang + .18), -Math.cos(p.ang + .18)]; // forward in the figure's direction, then up
219 const handA = (hand[0] - hand[1]) / R2, handB = (hand[0] + hand[1]) / R2;
220 let headA = handA + d[0] * SHAFT, headZ = hand[2] + d[1] * SHAFT;
221 if (p.strike > 0 && last) { headA = lerp(headA, last.aim, p.strike); headZ = lerp(headZ, LOG_TOP + .05, p.strike); }
222 headA += p.shake;
223 const headB = lerp(handB, 0, p.strike);
224 dynamicAdd(world(handA - d[0] * .5, handB, hand[2] - d[1] * .5), world(headA, headB, headZ), .08, .08, () => HANDLE);
225 dynamicAdd(world(headA, headB - .5, headZ), world(headA, headB + .5, headZ), .22, .22, () => STEEL);
outdated

These aliases only rename headZ and headA; use the originals.

226 dynamicAdd(world(headA + .14, headB - .46, headZ - .16), world(headA + .14, headB + .46, headZ - .16), .13, .13, () => STEEL);
227 }
228
229 /* ---------- the pile of split wood ---------- */
230 function pile() {
231 const n = Math.min(G.pile, PILE_MAX);
232 let k = 0, row = 0;
233 while (k < n) {
234 const stack = Math.floor(k / PILE_STACK), count = PILE_ROWS[row % PILE_ROWS.length];
235 for (let i = 0; i < count && k < n; i++, k++) halfLog(dynamicAdd, PILE_AT[0] + (i - (count - 1) / 2) * .64, PILE_AT[1] - stack * STACK_GAP, .3 + (row % PILE_ROWS.length) * .5);
236 row++;
237 }
238 }
239 // the two halves fly apart and drop the moment a log splits
240 function halves() {
241 const since = G.time - G.lastAt, last = G.last;
242 if (!last || last.result === 'stuck' || since < .08 || since > .6) return;
243 const t = ease3((since - .08) / .52);
244 for (const side of [-1, 1]) {
245 const a = side * (1.2 + t * 2.4), z = BLOCK_TOP + .4 + Math.sin(Math.min(1, t * 1.3) * Math.PI) * .6 - t * .6;
246 dynamicAdd(world(a, 0, z), world(a + side * .5 * t, 0, z + 1.1), .5, .5, () => LOG_BARK);
247 }
248 }
249
250 /* ---------- hens ---------- */
251 function hens() {
252 for (const h of HENS) {
253 const step = STILL ? 0 : Math.floor(time * 4 + h.phase), peck = !STILL && step % 6 < 2;
254 const d = h.dir, body = h.body;
255 sphere2(dynamicAdd, world(h.a, h.b, .62), .46, body);
256 sphere2(dynamicAdd, world(h.a - d * .5, h.b, .9), .26, body.map(v => v * .88));
257 const head = world(h.a + d * (peck ? .62 : .5), h.b, peck ? .36 : .98);
258 sphere2(dynamicAdd, head, .21, body);
259 sphere2(dynamicAdd, [head[0] + d * .1 * (peck ? 1 : 0), head[1], head[2] + .22], .09, [200, 52, 44]);
260 dynamicAdd(world(h.a + d * (peck ? .82 : .7), h.b, peck ? .32 : .96), world(h.a + d * (peck ? .9 : .78), h.b, peck ? .26 : .93), .06, .04, () => [236, 168, 52]);
261 for (const s of [-.12, .12]) dynamicAdd(world(h.a, h.b + s, .3), world(h.a, h.b + s, 0), .045, .04, () => [226, 150, 52]);
262 }
263 }
264
265 /* ---------- aim marker and crack guide ---------- */
266 function drawBlade(lift) {
267 if (!G.holding) return;
268 const top = LOG_TOP + lift; // the blade's footprint on b = 0, the row the rules judge
269 const p0 = proj(G.aim, -WoodSplit.FOOT, top), p1 = proj(G.aim, WoodSplit.FOOT, top);
outdated

This marker spans the whole log top, so against a tilted crack it always crosses it somewhere. Draw the axe-head footprint at b=0, the spot judge measures and the spot the head lands in farmer(), or change judge to match this line.

270 const x = Math.round(p0.sx), y0 = Math.round(p0.sy), y1 = Math.round(p1.sy), ink = [], gold = [];
271 for (let y = y0; y <= y1; y++) { ink.push([x - 1, y], [x + 1, y]); gold.push([x, y]); }
272 ink.push([x - 1, y0 - 1], [x, y0 - 1], [x + 1, y0 - 1], [x - 1, y1 + 1], [x, y1 + 1], [x + 1, y1 + 1]);
273 drawDots(ink, INK);
274 drawDots(gold, SIGNAL);
275 }
276
277 /* ---------- hud ---------- */
278 let shown = '';
279 function renderHud() {
280 const left = Math.max(0, Math.ceil(WoodSplit.ROUND - G.time));
281 const pct = Math.round(G.strength * 100);
282 const text = [G.score, G.split, left, G.best, pct, WoodSplit.tired(G)].join('|');
283 if (text === shown) return;
284 shown = text;
285 nodes.score.textContent = G.score;
286 nodes.split.textContent = G.split;
287 nodes.clock.textContent = left;
288 nodes.best.textContent = Math.max(G.best, G.score);
289 nodes.fill.style.transform = 'scaleX(' + (pct / 100).toFixed(2) + ')';
290 nodes.bar.classList.toggle('tired', WoodSplit.tired(G));
291 }
292 function setStatus(text) {
293 if (text === status) return;
294 status = text;
295 nodes.status.textContent = text;
296 }
297 const HINT = 'hold to raise the axe · let go with the blade on the crack';
298 function why(r) {
299 if (r.strength < WoodSplit.WEAK) return 'too weak';
300 if (r.knotty && r.strength < WoodSplit.FULL) return 'a knotty log needs a full swing';
301 return 'missed the crack';
302 }
303 function statusFor() {
304 if (G.phase === 'over') {
305 return 'time · ' + G.score + (G.score === 1 ? ' point' : ' points') + ' · ' + G.split + ' logs' + (G.record ? ' · new best' : '') + ' · tap or press space to play again';
306 }
307 if (G.stuck > 0) return 'axe stuck · ' + why(G.last) + ' · working it free ' + G.stuck.toFixed(1) + ' s';
308 if (G.holding) {
309 if (WoodSplit.tired(G)) return 'arms tiring · let go now';
310 return G.strength >= WoodSplit.FULL ? 'full strength · let go on the crack' : 'raising the axe · ' + Math.round(G.strength * 100) + '%';
311 }
312 if (time < noteUntil) return note;
313 return G.log.knotty ? 'knotty log · needs a full-strength swing' : HINT;
314 }
315
316 /* ---------- loop ---------- */
317 function again() {
318 if (G.phase === 'over' && overFor > .8) { WoodSplit.restart(G); time = 0; overFor = 0; lastOver = false; seenAt = -99; noteUntil = 0; shownLog = G.log; logBorn = -99; }
319 }
320 function update(dt) {
321 time += dt;
322 WoodSplit.step(G, dt);
323 if (G.lastAt !== seenAt) {
324 seenAt = G.lastAt;
325 const r = G.last;
326 if (r) {
327 sound(r.result);
328 if (r.result === 'clean') { note = 'clean split · +3'; noteUntil = time + 1.6; }
329 else if (r.result === 'split') { note = 'split · +1'; noteUntil = time + 1.6; }
330 }
331 }
332 if (G.log !== shownLog) { shownLog = G.log; logBorn = time; }
333 if (G.phase === 'over') {
334 overFor += dt;
335 if (!lastOver) {
336 lastOver = true;
337 if (G.record) try { localStorage.setItem(BEST_KEY, String(G.best)); } catch (e) { /* private window: keep it for this visit */ }
338 }
339 }
340 setStatus(statusFor());
341 renderHud();
342 }
343 function draw() {
344 pix.set(bakedPix);
345 zb.set(bakedZ);
346 pendingShadows.length = 0;
347 const windT = STILL ? 0 : Math.floor(time * WIND_FPS) / WIND_FPS;
348 drawTufts(windT);
349 const born = time - logBorn, lift = born >= 0 && born < .2 ? (1 - ease3(born / .2)) * 1.6 : 0; // a new log drops onto the block
350 drawLog(G.log, lift);
351 for (const z of [1.6, 2.3, 2.9]) castShadow(...world(0, 0, z + lift), LOG_R * .7, 1, 0);
352 farmer();
353 pile();
354 halves();
355 hens();
356 flushShadows();
357 applyShadows(bakedZ);
358 shadeEdges();
359 drawBlade(lift);
360 ctx.putImageData(image, 0, 0);
361 }
362
363 /* ---------- input ---------- */
364 function hold(on) {
365 if (on && G.phase !== 'play') { again(); return; }
366 WoodSplit.setHold(G, on);
367 }
368 canvas.addEventListener('pointerdown', e => {
369 canvas.focus({ preventScroll: true });
370 ensureAudio();
371 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic pointers have nothing to capture */ }
372 hold(true);
373 });
374 for (const kind of ['pointerup', 'pointercancel']) canvas.addEventListener(kind, () => hold(false));
375 canvas.addEventListener('lostpointercapture', () => hold(false));
376 canvas.addEventListener('contextmenu', e => e.preventDefault());
377 canvas.addEventListener('keydown', e => {
378 if (e.key !== ' ' && e.key !== 'Enter') return;
379 e.preventDefault();
380 if (!e.repeat) { ensureAudio(); hold(true); }
381 });
382 canvas.addEventListener('keyup', e => { if (e.key === ' ' || e.key === 'Enter') hold(false); });
383 addEventListener('blur', () => hold(false));
384
385 /* ---------- sound ---------- */
386 let audio = null, muted = false;
387 function ensureAudio() {
388 if (audio) { if (audio.state === 'suspended') audio.resume(); return; }
389 const AC = window.AudioContext || window.webkitAudioContext;
390 if (AC) audio = new AC();
391 }
392 function tone(type, from, to, len, vol) {
393 const now = audio.currentTime, gain = audio.createGain(), osc = audio.createOscillator();
394 osc.type = type;
395 osc.frequency.setValueAtTime(from, now);
396 osc.frequency.exponentialRampToValueAtTime(to, now + len);
397 gain.gain.setValueAtTime(vol, now);
398 gain.gain.exponentialRampToValueAtTime(.0005, now + len);
399 osc.connect(gain).connect(audio.destination);
400 osc.start(now); osc.stop(now + len + .01);
401 }
402 function sound(kind) {
403 if (!audio || muted) return;
404 if (kind === 'clean') { tone('triangle', 240, 70, .16, .16); tone('square', 880, 1320, .12, .04); }
405 else if (kind === 'split') tone('triangle', 200, 80, .14, .12);
406 else if (kind === 'stuck') tone('sawtooth', 150, 55, .22, .07);
407 }
408 const muteButton = document.getElementById('mute');
409 muteButton.addEventListener('click', () => {
410 muted = !muted;
411 muteButton.textContent = muted ? 'sound off' : 'sound on';
412 muteButton.setAttribute('aria-pressed', String(muted));
413 });
414
415 /* ---------- boot ---------- */
416 addEventListener('resize', fit);
417 fit();
418 bake();
419 setStatus(statusFor());
420 renderHud();
421 canvas.focus({ preventScroll: true });
422 let last = performance.now();
423 function frame(now) {
424 update(Math.min(.04, (now - last) / 1000));
425 last = now;
426 draw();
427 requestAnimationFrame(frame);
428 }
429 requestAnimationFrame(frame);
430 </script>
431 </body>
432 </html>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs