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

Migrated from github.com/amirmushichge/pixel-plays

Ferris Wheel rules: a tested `ferris-wheel/wheel.js` that seats a queue of riders and keeps the wheel balanced, from plain data #192

Merged opened this

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

Merged

torque/pixel-plays:torque/176-ferris-wheel-rules-a-tested-ferris-wheel → main 3 commits fork 1 thread · 1 unresolved

  • Merged. torque/176-ferris-wheel-rules-a-tested-ferris-wheel was merged into main as 4323674.

Review

Sign in to review this change.
2 files changed +258 −0
ferris-wheel/wheel.js added +120
@@ -0,0 +1,120 @@
1 'use strict';
2 // The Ferris Wheel rules: a queue of riders to seat in the gondolas of a turning wheel without tipping it.
3 // Plain data in, plain data out, no DOM, no timers, no Math.random: the queue comes from the seed.
4 // A rejected move returns the very same state and says why. The page draws what this decides.
5 //
6 // The wheel has GONDOLAS gondolas of SEATS seats each. Gondola g sits at position (g + turns) mod GONDOLAS; position 0 is
7 // the platform, at the bottom. Each position has a horizontal lever arm about the hub, in metres (ARM, east positive).
8 // Rider weights are in kilograms and rides are counted in steps. Imbalance is the torque sum, in kg*m:
9 // imbalance = sum over riders of weight * ARM[position of the rider's gondola] (torque = force x lever arm)
10 // The wheel jams when |imbalance| > LIMIT after a step; otherwise the round ends after STEPS steps.
11 (function (root) {
12 const GONDOLAS = 8, SEATS = 3, STEPS = 24, QUEUE = 20;
13 const ARM = [0, 3, 4, 3, 0, -3, -4, -3]; // m, per position clockwise from the platform: 4 m radius, 45 degrees apart, rounded
14 const LIMIT = 40; // kg*m
15 const WIN_RIDERS = 12; // the win line: this many riders carried
16 const MIN_WEIGHT = 20, MAX_WEIGHT = 95, MIN_TURNS = 2, MAX_TURNS = 6;
17
18 const finite = v => (Number.isFinite(v) ? v : 0);
19 // a repeatable number in [0, 1) for this seed and slot
20 function noise(seed, n) {
21 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
22 h = Math.imul(h ^ (h >>> 13), 1274126177);
23 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
24 }
25 const between = (seed, n, lo, hi) => lo + Math.floor(noise(seed, n) * (hi - lo + 1));
26
27 const copy = s => Object.assign({}, s, {
28 queue: s.queue.map(r => ({ ...r })), gondolas: s.gondolas.map(g => g.map(r => ({ ...r }))),
29 });
30 const positionOf = (s, g) => (g + s.turns) % s.count;
31 const platformGondola = s => (s.count - (s.turns % s.count)) % s.count;
32 // the torque sum about the hub, kg*m
33 function imbalanceOf(s) {
34 let sum = 0;
35 s.gondolas.forEach((g, i) => { for (const r of g) sum += r.weight * s.arm[positionOf(s, i)]; });
36 return sum;
37 }
38 const verdict = s => (s.carried >= WIN_RIDERS ? 'won' : 'lost');
39 function refresh(s) {
40 s.imbalance = imbalanceOf(s);
41 if (s.status === 'over') {
42 const worst = `largest imbalance ${s.worst} kg*m`;
43 const won = verdict(s) === 'won';
44 if (s.jammed) s.line = won
45 ? `The wheel jammed at ${s.imbalance} kg*m, but ${s.carried} riders were carried`
46 : `The wheel jammed at ${s.imbalance} kg*m: ${s.carried} riders carried, ${worst}`;
47 else s.line = won
outdated

This overwrites the line the ternary above just built for the jammed case. Fold it into the ternary above, or branch jammed first, so no string is built and thrown away.

48 ? `Wheel balanced: ${s.carried} riders carried, ${worst}`
49 : `Too few rides: ${s.carried} of ${WIN_RIDERS} riders carried, ${worst}`;
50 } else {
51 s.line = `Step ${s.step} of ${STEPS}: ${s.carried} riders carried, imbalance ${s.imbalance} of ${s.limit} kg*m`;
52 }
53 return s;
54 }
55
56 // start(seed): an empty wheel and a seeded queue
57 function start(seed = 1) {
58 seed = finite(seed) >>> 0;
59 const queue = [];
60 for (let i = 0; i < QUEUE; i++) {
61 queue.push({
62 id: i + 1, weight: between(seed, i * 2, MIN_WEIGHT, MAX_WEIGHT), turns: between(seed, i * 2 + 1, MIN_TURNS, MAX_TURNS),
63 left: 0, skipped: false,
64 });
65 }
66 return refresh({
67 seed, status: 'playing', count: GONDOLAS, seats: SEATS, arm: ARM.slice(), limit: LIMIT, steps: STEPS, winRiders: WIN_RIDERS,
68 step: 0, turns: 0, queue, gondolas: Array.from({ length: GONDOLAS }, () => []),
69 carried: 0, worst: 0, imbalance: 0, jammed: false, line: '',
70 });
71 }
72
73 // board(state) -> { ok, why, state }: the front rider takes a seat in the gondola at the platform
74 function board(s) {
75 if (s.status !== 'playing') return { ok: false, why: 'over', state: s };
76 if (!s.queue.length) return { ok: false, why: 'empty-queue', state: s };
77 const g = platformGondola(s);
78 if (s.gondolas[g].length >= s.seats) return { ok: false, why: 'full', state: s };
79 const n = copy(s), rider = n.queue.shift();
80 rider.left = rider.turns;
81 n.gondolas[g].push(rider);
82 n.carried = s.carried + 1;
83 return { ok: true, why: '', state: refresh(n) };
84 }
85
86 // skip(state) -> { ok, why, state }: the front rider goes to the back of the queue, once
87 function skip(s) {
88 if (s.status !== 'playing') return { ok: false, why: 'over', state: s };
89 if (!s.queue.length) return { ok: false, why: 'empty-queue', state: s };
90 if (s.queue[0].skipped) return { ok: false, why: 'already-skipped', state: s };
91 const n = copy(s), rider = n.queue.shift();
92 rider.skipped = true;
93 n.queue.push(rider);
94 return { ok: true, why: '', state: refresh(n) };
95 }
96
97 // step(state) -> { ok, why, event, state }: turn one gondola, let off finished riders, compute the imbalance.
98 // event is '', 'jam' or 'done'.
99 function step(s) {
100 if (s.status !== 'playing') return { ok: false, why: 'over', event: '', state: s };
101 const n = copy(s);
102 n.turns = s.turns + 1;
103 n.step = s.step + 1;
104 n.gondolas = n.gondolas.map(g => {
105 for (const r of g) r.left -= 1;
106 return g.filter(r => r.left > 0);
107 });
108 n.imbalance = imbalanceOf(n);
109 n.worst = Math.max(s.worst, Math.abs(n.imbalance));
110 let event = '';
111 if (Math.abs(n.imbalance) > n.limit) { n.jammed = true; n.status = 'over'; event = 'jam'; }
112 else if (n.step >= n.steps) { n.status = 'over'; event = 'done'; }
113 return { ok: true, why: '', event, state: refresh(n) };
114 }
115
116 const api = {
117 GONDOLAS, SEATS, STEPS, QUEUE, ARM, LIMIT, WIN_RIDERS, start, board, skip, step, imbalanceOf, verdict,
118 };
119 if (typeof module !== 'undefined') module.exports = api; else root.FerrisWheel = api;
120 })(typeof window !== 'undefined' ? window : globalThis);
ferris-wheel/wheel.test.mjs added +138
@@ -0,0 +1,138 @@
1 import { test, expect } from 'bun:test';
2 import { GONDOLAS, SEATS, STEPS, ARM, LIMIT, WIN_RIDERS, start, board, skip, step, imbalanceOf, verdict } from './wheel.js';
3
4 const rider = (id, weight, turns) => ({ id, weight, turns, left: 0, skipped: false });
5 // a hand-made wheel (plain data) with a chosen queue
6 const hand = (weights, turns = 3, extra = {}) => ({ ...start(1), queue: weights.map((w, i) => rider(i + 1, w, turns)), ...extra });
7 const mustBoard = s => { const r = board(s); expect([r.ok, r.why]).toEqual([true, '']); return r.state; };
8
9 test('the same seed gives the same queue, other seeds differ, and the wheel is as stated', () => {
10 expect(start(7)).toEqual(start(7));
11 expect(JSON.stringify(start(7).queue)).not.toBe(JSON.stringify(start(8).queue));
12 const s = start(3);
13 expect(s.gondolas).toHaveLength(GONDOLAS);
14 expect(s.seats).toBe(SEATS);
15 expect(s.queue.length).toBeGreaterThan(WIN_RIDERS);
16 for (const r of s.queue) { expect(r.weight).toBeGreaterThan(0); expect(r.turns).toBeGreaterThanOrEqual(2); }
17 });
18
19 test('a board into a full gondola is refused and leaves the state untouched', () => {
20 let s = hand([50, 50, 50, 50]);
21 for (let i = 0; i < SEATS; i++) s = mustBoard(s);
22 const r = board(s);
23 expect([r.ok, r.why]).toEqual([false, 'full']);
24 expect(r.state).toBe(s);
25 expect(s.queue).toHaveLength(1);
26 });
27
28 test('skip sends the front rider to the back once; a second skip of the same rider is refused', () => {
29 const s = hand([10, 20, 30]);
30 const a = skip(s);
31 expect(a.ok).toBe(true);
32 expect(a.state.queue.map(r => r.id)).toEqual([2, 3, 1]);
33 const b = skip(a.state); // rider 2 skips fine
34 expect(b.state.queue.map(r => r.id)).toEqual([3, 1, 2]);
35 const c = skip(b.state);
36 expect(c.state.queue.map(r => r.id)).toEqual([1, 2, 3]);
37 const d = skip(c.state); // rider 1 again
38 expect([d.ok, d.why]).toEqual([false, 'already-skipped']);
39 expect(d.state).toBe(c.state);
40 });
41
42 test('riders leave after their turns', () => {
43 let s = mustBoard(hand([30], 2, { limit: 1000 }));
44 expect(s.carried).toBe(1);
45 s = step(s).state;
46 expect(s.gondolas.flat()).toHaveLength(1);
47 s = step(s).state;
48 expect(s.gondolas.flat()).toHaveLength(0);
49 expect(s.imbalance).toBe(0);
50 expect(s.carried).toBe(1);
51 });
52
53 test('imbalance is weight times arm summed about the hub, for a known seating', () => {
54 // two riders (10 and 20 kg) in the platform gondola, no jam so the turning can be followed
55 let s = hand([10, 20], 6, { limit: 1000 });
56 s = mustBoard(s); s = mustBoard(s); // 30 kg in the gondola at position 0 (arm 0)
57 expect(s.imbalance).toBe(30 * ARM[0]);
58 s = step(s).state; // now at position 1: 30 kg * 3 m = 90
59 expect(imbalanceOf(s)).toBe(30 * ARM[1]);
60 expect(s.imbalance).toBe(90);
61 s = step(s).state; // position 2: 30 * 4 = 120
62 expect(s.imbalance).toBe(120);
63 expect(s.worst).toBe(120);
64 });
65
66 test('the wheel jams when the imbalance passes the limit', () => {
67 let s = hand([50, 50], 6);
68 s = mustBoard(s); s = mustBoard(s); // 100 kg; 100 * 3 = 300 > LIMIT after one step
69 expect(300).toBeGreaterThan(LIMIT);
70 const r = step(s);
71 expect(r.event).toBe('jam');
72 expect(r.state.status).toBe('over');
73 expect(r.state.jammed).toBe(true);
74 expect(r.state.line).toContain('jammed');
75 expect(step(r.state).ok).toBe(false);
76 expect(board(r.state).why).toBe('over');
77 });
78
79 test('exactly at the limit does not jam', () => {
80 let s = mustBoard({ ...hand([10], 6), limit: 30 }); // 10 kg * 3 m = 30
81 const r = step(s);
82 expect(r.event).toBe('');
83 expect(r.state.imbalance).toBe(30);
84 });
85
86 test('the round ends after the stated steps: win at the rider line, loss below it', () => {
87 let s = start(1);
88 s = { ...s, queue: Array.from({ length: 20 }, (_, i) => rider(i + 1, 1, 1)) }; // featherweights never jam
89 let carried = 0;
90 for (let i = 0; i < STEPS; i++) {
91 if (carried < WIN_RIDERS) { s = mustBoard(s); carried++; }
92 const r = step(s); s = r.state;
93 if (i < STEPS - 1) expect(r.event).toBe('');
94 else expect(r.event).toBe('done');
95 }
96 expect(s.status).toBe('over');
97 expect(s.carried).toBe(WIN_RIDERS);
98 expect(s.line).toContain('Wheel balanced');
99 expect(s.line).toContain(`${WIN_RIDERS} riders carried`);
100 expect(s.line).toContain('largest imbalance');
101
102 let t = start(1);
103 for (let i = 0; i < STEPS; i++) t = step(t).state;
104 expect(t.status).toBe('over');
105 expect(t.carried).toBe(0);
106 expect(t.line).toContain('Too few rides');
107 expect(t.line).toContain('largest imbalance');
108 });
109
110 test('a jam after the rider line is reached is told as jammed but won', () => {
111 let s = hand([50, 50], 6, { carried: WIN_RIDERS - 2 });
112 s = mustBoard(s); s = mustBoard(s); // carried reaches the line, 100 kg then jams
113 const r = step(s);
114 expect(r.event).toBe('jam');
115 expect(verdict(r.state)).toBe('won');
116 expect(r.state.line).toBe(`The wheel jammed at 300 kg*m, but ${WIN_RIDERS} riders were carried`);
117 const lost = step(mustBoard(mustBoard(hand([50, 50], 6))));
118 expect(lost.state.line).toContain('jammed at 300 kg*m: 2 riders carried');
119 });
120
121 test('after a step the next rider is seated in the gondola now at the platform', () => {
122 let s = mustBoard(hand([10, 10], 6, { limit: 1000 }));
123 s = step(s).state;
124 expect(s.turns).toBe(1);
125 s = mustBoard(s);
126 expect(s.gondolas[0]).toHaveLength(1);
127 expect(s.gondolas[GONDOLAS - 1]).toHaveLength(1);
128 expect(s.gondolas[GONDOLAS - 1][0].id).toBe(2);
129 });
130
131 test('board and skip on an empty queue say why', () => {
132 const s = hand([]);
133 for (const f of [board, skip]) {
134 const r = f(s);
135 expect([r.ok, r.why]).toEqual([false, 'empty-queue']);
136 expect(r.state).toBe(s);
137 }
138 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs