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

Migrated from github.com/amirmushichge/pixel-plays

Chimney Sweep rules: a tested `chimney-sweep/roofs.js` where you climb a row of chimneys by brush pulls and duck the smoke puffs, from plain data, in a two-file pull with a test file that runs in under a second #306

Merged opened this

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

Merged

torque/pixel-plays:torque/287-chimney-sweep-rules-a-tested-chimney-swe → main 1 commit fork

  • Merged. torque/287-chimney-sweep-rules-a-tested-chimney-swe was merged into main as 2223de0.

Review

Sign in to review this change.
2 files changed +308 −0
chimney-sweep/roofs.js added +157
@@ -0,0 +1,157 @@
1 'use strict';
2 // The Chimney Sweep rules: climb a chimney stack by timed brush pulls, slip sideways between flues to dodge puffs
3 // of smoke, and come out on the roof. Plain data in, plain data out, no DOM, no timers, no Math.random: every puff
4 // comes from the seed. A rejected call returns the very same state and says why.
5 //
6 // Units: metres and seconds. Height is measured from the bottom of the stack.
7 // A puff begins at time `at` in its flue and rises with initial speed v0 and constant acceleration a:
8 // h(τ) = v0·τ + a·τ²/2 for 0 ≤ τ ≤ PUFF_LIFE, τ = time since it began (uniformly accelerated motion)
9 // so a puff's height is closed-form in absolute time. Hits are tested at the fixed grid times k·STEP that fall in the
10 // span being advanced, never at tick boundaries, so a hit does not depend on how time was sliced into ticks.
11 // The sweep rests while the brush cools down, then slides back at SLIDE m/s (never below 0):
12 // h(t) = max(0, h0 − SLIDE·(t − max(t0, cooldownUntil)))
13 (function (root) {
14 const HEIGHT = 20; // m, reaching this height is the roof
15 const FLUES = 4; // flues side by side, numbered 0..FLUES-1
16 const START_FLUE = 1; // the sweep starts at the bottom of this flue
17 const PULL_LIFT = 1; // m gained by one brush pull
18 const COOLDOWN = 0.5; // s after a pull during which pulling is refused and the sweep does not slide
19 const SLIDE = 1.5; // m/s the sweep slides back down once the cooldown is over
20 const KNOCK = 3; // m the sweep is knocked down by a puff
21 const LIVES = 3;
22 const HIT_RANGE = 0.5; // m, a puff within this height of the sweep, in its flue, hits
23 const PUFFS = 60; // puffs in the schedule
24 const FIRST_AT = 1.5; // s, the first puff begins
25 const PUFF_GAP = 1; // s between puff starts
26 const PUFF_LIFE = 8; // s a puff lasts
27 const V0_MIN = 2, V0_MAX = 4; // m/s initial rise speed
28 const ACC_MIN = 0.5, ACC_MAX = 1.5; // m/s² rise acceleration
29 const STEP = 0.01; // s, the grid hits are tested on
30 const TIME_LIMIT = 60; // s, the game is lost at this time
31 const TOP_SCORE = 1000; // points for reaching the top
32 const LIFE_BONUS = 200; // points per life left
33 const TIME_BONUS = 500; // points at time 0, falling linearly to 0 at TIME_LIMIT
34
35 // mulberry32 as a pure step: next(seed) -> [value in [0,1), nextSeed]
36 function next(r) {
37 r = (r + 0x6D2B79F5) >>> 0;
38 let t = r;
39 t = Math.imul(t ^ (t >>> 15), t | 1);
40 t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
41 return [((t ^ (t >>> 14)) >>> 0) / 4294967296, r];
42 }
43
44 // puffHeight(puff, time) -> height of the puff at an absolute time, or null when it is not in the stack
45 function puffHeight(puff, time) {
46 const t = time - puff.at;
47 if (t < 0 || t > PUFF_LIFE) return null;
48 return puff.speed * t + puff.rise * t * t / 2;
49 }
50
51 // sweepHeight(sweep, time) -> height at a time not before sweep.since
52 function sweepHeight(sw, time) {
53 const from = Math.max(sw.since, sw.restUntil);
54 return time <= from ? sw.h : Math.max(0, sw.h - SLIDE * (time - from));
55 }
56
57 // timeBonus(time) -> points, falling linearly to zero at TIME_LIMIT
58 const timeBonus = time => Math.round(TIME_BONUS * Math.max(0, 1 - time / TIME_LIMIT));
59
60 function describe(s) {
61 if (s.status === 'won') return `You win: reached the roof with ${s.lives} ${s.lives === 1 ? 'life' : 'lives'} left in ${s.time.toFixed(1)} s, score ${s.score}`;
62 if (s.status === 'lost') return `You lose: ${s.lives <= 0 ? 'no lives left' : 'out of time'} at ${s.sweep.h.toFixed(1)} m of ${HEIGHT} m`;
63 return `${s.sweep.h.toFixed(1)} m of ${HEIGHT} m, flue ${s.sweep.flue + 1} of ${FLUES}, ${s.lives} ${s.lives === 1 ? 'life' : 'lives'}`;
64 }
65
66 // start(seed) -> the sweep at the bottom of the start flue and the whole seeded schedule of puffs
67 function start(seed) {
68 const sd = Number.isFinite(seed) ? Math.trunc(seed) >>> 0 : 0;
69 let rng = sd;
70 const puffs = [];
71 for (let i = 0; i < PUFFS; i++) {
72 let a, b, c;
73 [a, rng] = next(rng); [b, rng] = next(rng); [c, rng] = next(rng);
74 puffs.push({
75 id: i,
76 flue: Math.min(FLUES - 1, Math.floor(a * FLUES)),
77 at: FIRST_AT + i * PUFF_GAP,
78 speed: V0_MIN + b * (V0_MAX - V0_MIN),
79 rise: ACC_MIN + c * (ACC_MAX - ACC_MIN),
80 hit: false,
81 });
82 }
83 const s = {
84 seed: sd, status: 'playing', time: 0, puffs, lives: LIVES, score: 0,
85 sweep: { flue: START_FLUE, h: 0, since: 0, restUntil: 0 },
86 line: '',
87 };
88 s.line = describe(s);
89 return s;
90 }
91
92 const reject = (state, why) => ({ ok: false, state, why });
93
94 // win(s): the sweep is out on the roof
95 function win(s) {
96 s.status = 'won';
97 s.score = TOP_SCORE + LIFE_BONUS * s.lives + timeBonus(s.time);
98 s.sweep = { ...s.sweep, h: HEIGHT, since: s.time };
99 }
100
101 // tick(state, dt) -> { ok, state, why }: advances dt seconds, testing every grid time on the way for puff hits
102 function tick(state, dt) {
103 if (typeof dt !== 'number' || !Number.isFinite(dt) || dt <= 0) return reject(state, 'bad-dt');
104 if (state.status !== 'playing') return reject(state, 'game-over');
105 const end = Math.min(state.time + dt, TIME_LIMIT);
106 const s = { ...state, puffs: state.puffs.map(p => ({ ...p })), sweep: { ...state.sweep } };
107 let k = Math.floor(state.time / STEP + 1e-9) + 1;
108 for (; k * STEP <= end + 1e-9; k++) {
109 const g = k * STEP, h = sweepHeight(s.sweep, g);
110 const p = s.puffs.find(q => !q.hit && q.flue === s.sweep.flue && puffHeight(q, g) !== null &&
111 Math.abs(puffHeight(q, g) - h) <= HIT_RANGE);
112 if (!p) continue;
113 p.hit = true;
114 s.lives -= 1;
115 s.sweep = { ...s.sweep, h: Math.max(0, h - KNOCK), since: g };
116 if (s.lives <= 0) { s.status = 'lost'; s.time = g; break; }
117 }
118 if (s.status === 'playing') {
119 s.time = end;
120 s.sweep = { ...s.sweep, h: sweepHeight(s.sweep, end), since: end };
121 if (end >= TIME_LIMIT) s.status = 'lost';
122 } else s.sweep = { ...s.sweep, h: sweepHeight(s.sweep, s.time), since: s.time };
123 s.line = describe(s);
124 return { ok: true, state: s, why: '' };
125 }
126
127 // pull(state) -> { ok, state, why }: lifts the sweep PULL_LIFT and starts the cooldown; reaching HEIGHT wins
128 function pull(state) {
129 if (state.status !== 'playing') return reject(state, 'game-over');
130 if (state.time < state.sweep.restUntil) return reject(state, 'cooldown');
131 const s = { ...state, sweep: { ...state.sweep } };
132 const h = sweepHeight(s.sweep, s.time) + PULL_LIFT;
133 s.sweep = { ...s.sweep, h, since: s.time, restUntil: s.time + COOLDOWN };
134 if (h >= HEIGHT) win(s);
135 s.line = describe(s);
136 return { ok: true, state: s, why: '' };
137 }
138
139 // shift(state, dir) -> { ok, state, why }: moves one flue left (-1) or right (1); the outer walls stop it
140 function shift(state, dir) {
141 if (dir !== -1 && dir !== 1) return reject(state, 'bad-dir');
142 if (state.status !== 'playing') return reject(state, 'game-over');
143 const flue = state.sweep.flue + dir;
144 if (flue < 0 || flue >= FLUES) return reject(state, 'wall');
145 const h = sweepHeight(state.sweep, state.time);
146 const s = { ...state, sweep: { ...state.sweep, flue, h, since: state.time } };
147 s.line = describe(s);
148 return { ok: true, state: s, why: '' };
149 }
150
151 const api = {
152 HEIGHT, FLUES, START_FLUE, PULL_LIFT, COOLDOWN, SLIDE, KNOCK, LIVES, HIT_RANGE, PUFFS, FIRST_AT, PUFF_GAP,
153 PUFF_LIFE, V0_MIN, V0_MAX, ACC_MIN, ACC_MAX, STEP, TIME_LIMIT, TOP_SCORE, LIFE_BONUS, TIME_BONUS,
154 start, tick, pull, shift, puffHeight, sweepHeight, timeBonus, describe,
155 };
156 if (typeof module !== 'undefined') module.exports = api; else root.ChimneySweep = api;
157 })(typeof window !== 'undefined' ? window : globalThis);
chimney-sweep/roofs.test.mjs added +151
@@ -0,0 +1,151 @@
1 import { test, expect } from 'bun:test';
2 import {
3 HEIGHT, FLUES, START_FLUE, PULL_LIFT, COOLDOWN, SLIDE, KNOCK, LIVES, PUFFS, PUFF_LIFE, V0_MIN, V0_MAX, ACC_MIN,
4 ACC_MAX, TIME_LIMIT, TOP_SCORE, LIFE_BONUS, TIME_BONUS,
5 start, tick, pull, shift, puffHeight, sweepHeight, timeBonus,
6 } from './roofs.js';
7
8 const puff = (id, flue, at, speed = 2, rise = 1) => ({ id, flue, at, speed, rise, hit: false });
9 const game = (puffs = [], over = {}) => ({ ...start(1), puffs, ...over });
10 const withSweep = (s, sw) => ({ ...s, sweep: { ...s.sweep, ...sw } });
11
12 test('start: stated height, flues, sweep at the bottom of a stated flue, seeded puffs; same seed, same puffs', () => {
13 const a = start(7), b = start(7), c = start(8);
14 expect([HEIGHT, FLUES, a.status, a.lives, a.score]).toEqual([20, 4, 'playing', LIVES, 0]);
15 expect([a.sweep.flue, a.sweep.h]).toEqual([START_FLUE, 0]);
16 expect(a.puffs.length).toBe(PUFFS);
17 expect(a.puffs).toEqual(b.puffs);
18 expect(a.puffs).not.toEqual(c.puffs);
19 for (const p of a.puffs) {
20 expect(p.flue).toBeGreaterThanOrEqual(0); expect(p.flue).toBeLessThan(FLUES);
21 expect(p.speed).toBeGreaterThanOrEqual(V0_MIN); expect(p.speed).toBeLessThanOrEqual(V0_MAX);
22 expect(p.rise).toBeGreaterThanOrEqual(ACC_MIN); expect(p.rise).toBeLessThanOrEqual(ACC_MAX);
23 }
24 expect(new Set(a.puffs.map(p => p.flue)).size).toBe(FLUES);
25 expect(start(NaN).seed).toBe(0);
26 });
27
28 test('a puff height is closed-form: h = v0·τ + a·τ²/2 by hand calculation', () => {
29 const p = puff(0, 0, 3, 2, 1); // at τ = 2: 2·2 + 1·4/2 = 6 m
30 expect(puffHeight(p, 5)).toBe(6);
31 expect(puffHeight(p, 3)).toBe(0);
32 expect(puffHeight(p, 2.9)).toBeNull();
33 expect(puffHeight(p, 3 + PUFF_LIFE + 0.1)).toBeNull();
34 });
35
36 test('tick refuses a dt that is not a finite number above 0, and a finished game', () => {
37 const s = game();
38 for (const dt of [0, -1, NaN, Infinity, '1', null, undefined]) {
39 const r = tick(s, dt);
40 expect([r.ok, r.why, r.state]).toEqual([false, 'bad-dt', s]);
41 }
42 const done = { ...s, status: 'lost' };
43 expect(tick(done, 1).why).toBe('game-over');
44 expect(pull(done).why).toBe('game-over');
45 expect(shift(done, 1).why).toBe('game-over');
46 expect(tick(s, 0.25).state.time).toBe(0.25);
47 });
48
49 test('a pull lifts a stated distance and is refused during the cooldown, allowed after it', () => {
50 let s = game();
51 const r = pull(s);
52 expect([r.ok, r.state.sweep.h]).toEqual([true, PULL_LIFT]);
53 const again = pull(r.state);
54 expect([again.ok, again.why, again.state]).toEqual([false, 'cooldown', r.state]);
55 s = tick(r.state, COOLDOWN - 0.01).state;
56 expect(pull(s).why).toBe('cooldown');
57 s = tick(s, 0.01).state;
58 expect(s.sweep.h).toBe(PULL_LIFT); // no slide during the cooldown
59 const third = pull(s);
60 expect([third.ok, third.state.sweep.h]).toEqual([true, 2 * PULL_LIFT]);
61 });
62
63 test('the sweep slides back at a stated rate once not pulling, and never below the bottom', () => {
64 let s = pull(game()).state; // 1 m, resting until 0.5 s
65 s = tick(s, COOLDOWN + 0.2).state; // 0.2 s of slide
66 expect(s.sweep.h).toBeCloseTo(PULL_LIFT - SLIDE * 0.2, 9);
67 expect(sweepHeight(pull(game()).state.sweep, COOLDOWN + 0.2)).toBeCloseTo(0.7, 9);
68 s = tick(s, 5).state;
69 expect(s.sweep.h).toBe(0);
70 });
71
72 test('the walls refuse a shift past the outer flues; a shift moves exactly one flue', () => {
73 let s = game();
74 expect(shift(s, 1).state.sweep.flue).toBe(START_FLUE + 1);
75 expect(shift(s, -1).state.sweep.flue).toBe(START_FLUE - 1);
76 for (let i = 0; i < FLUES; i++) { const r = shift(s, -1); if (r.ok) s = r.state; }
77 expect(s.sweep.flue).toBe(0);
78 const r = shift(s, -1);
79 expect([r.ok, r.why, r.state]).toEqual([false, 'wall', s]);
80 for (let i = 0; i < FLUES; i++) { const q = shift(s, 1); if (q.ok) s = q.state; }
81 expect([s.sweep.flue, shift(s, 1).why]).toEqual([FLUES - 1, 'wall']);
82 for (const d of [0, 2, '1', NaN]) expect(shift(s, d).why).toBe('bad-dir');
83 });
84
85 test('a puff in the sweep flue at its height costs a life and knocks the sweep down; another flue costs nothing', () => {
86 // sweep at 5 m in flue 1; puff in flue 1 begins at t=0 with v0=2, a=1: h(τ)=2τ+τ²/2 = 5 at τ = -2+sqrt(14) ≈ 1.7417
87 const base = withSweep(game([puff(0, 1, 0)]), { h: 5, since: 0, restUntil: 100 });
88 const r = tick(base, 3).state;
89 expect(r.lives).toBe(LIVES - 1);
90 expect(r.puffs[0].hit).toBe(true);
91 expect(r.sweep.h).toBe(5 - KNOCK);
92 expect(tick(r, 3).state.lives).toBe(LIVES - 1); // a puff costs one life only once
93 const other = withSweep(game([puff(0, 2, 0)]), { h: 5, since: 0, restUntil: 100 });
94 expect(tick(other, 3).state.lives).toBe(LIVES);
95 const high = withSweep(game([puff(0, 1, 0)]), { h: 15, since: 0, restUntil: 100 });
96 expect(tick(high, 3).state.lives).toBe(LIVES); // by t=3 the puff is only at 10.5 m, not yet at the sweep
97 const dodged = shift(withSweep(game([puff(0, 1, 0)]), { h: 5, since: 0, restUntil: 100 }), 1).state;
98 expect(tick(dodged, 3).state.lives).toBe(LIVES);
99 });
100
101 test('a hit is the same however time is sliced', () => {
102 const ps = start(5).puffs.map(p => ({ ...p, flue: START_FLUE }));
103 const run = dts => {
104 let s = withSweep(game(ps, { lives: 99 }), { h: 6, restUntil: 1e9 });
105 for (const dt of dts) s = tick(s, dt).state;
106 return [s.lives, s.sweep.h, s.puffs.map(p => p.hit), s.time];
107 };
108 const whole = run([20]);
109 expect(whole[0]).toBeLessThan(99);
110 for (const sliced of [Array(2000).fill(0.01), Array(400).fill(0.05), [0.37, 5.013, 0.003, 14.614], Array(97).fill(20 / 97)]) {
111 const r = run(sliced);
112 expect(r[0]).toBe(whole[0]); expect(r[2]).toEqual(whole[2]); expect(r[1]).toBeCloseTo(whole[1], 9);
113 expect(r[3]).toBeCloseTo(20, 9);
114 }
115 });
116
117 test('losing every life ends the game with a loss line', () => {
118 const s = withSweep(game([puff(0, 1, 0)], { lives: 1 }), { h: 5, restUntil: 100 });
119 const r = tick(s, 3).state;
120 expect([r.status, r.lives]).toEqual(['lost', 0]);
121 expect(r.line).toBe('You lose: no lives left at 2.0 m of 20 m');
122 expect(r.time).toBeLessThan(3);
123 expect(tick(r, 1).why).toBe('game-over');
124 });
125
126 test('the time limit ends the game with a loss line', () => {
127 const r = tick(game(), TIME_LIMIT + 10).state;
128 expect([r.status, r.time]).toEqual(['lost', TIME_LIMIT]);
129 expect(r.line).toBe('You lose: out of time at 0.0 m of 20 m');
130 });
131
132 test('reaching the top wins, scoring the top, a bonus per life left and a time bonus falling to zero', () => {
133 const near = (time, lives) => withSweep(game([], { time, lives }), { h: HEIGHT - PULL_LIFT, since: time, restUntil: 0 });
134 const w = pull(near(30, 2)).state; // 30 s of 60 s: half the time bonus
135 expect(w.status).toBe('won');
136 expect(w.score).toBe(TOP_SCORE + 2 * LIFE_BONUS + TIME_BONUS / 2);
137 expect(w.score).toBe(1650);
138 expect(w.line).toBe('You win: reached the roof with 2 lives left in 30.0 s, score 1650');
139 expect(pull(near(0, 3)).state.score).toBe(1000 + 600 + 500);
140 expect(pull(near(TIME_LIMIT, 3)).state.score).toBe(1000 + 600);
141 expect(timeBonus(TIME_LIMIT + 5)).toBe(0);
142 expect(timeBonus(15)).toBe(375);
143 expect(pull(near(30, 1)).state.line).toContain('1 life left');
144 });
145
146 test('a full climb by pulling at each cooldown reaches the roof', () => {
147 let s = game();
148 for (let i = 0; i < 100 && s.status === 'playing'; i++) { s = pull(s).state; s = tick(s, COOLDOWN).state; }
149 expect(s.status).toBe('won');
150 expect(s.sweep.h).toBe(HEIGHT);
151 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs