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

Migrated from github.com/amirmushichge/pixel-plays

Mill Race rules: a tested `mill-race/race.js` that turns pipe tiles to carry the stream to the water wheel, from plain data #191

Merged opened this

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

Merged

torque/pixel-plays:torque/174-mill-race-rules-a-tested-mill-race-race → main 3 commits fork 3 threads · 3 unresolved

  • Merged. torque/174-mill-race-rules-a-tested-mill-race-race was merged into main as f646af0.

Review

Sign in to review this change.
2 files changed +291 −0
mill-race/race.js added +165
@@ -0,0 +1,165 @@
1 'use strict';

Add a credit here: Mill Race is in the pipe-turning tradition of Pipe Mania (Lucasfilm Games, 1989; Empire Software/Oasis). Name the original creators.

2 // Mill Race is in the pipe-turning tradition of Pipe Mania (The Assembly Line, 1989; published as Pipe Dream by
3 // Lucasfilm Games in the US and as Pipe Mania by Empire Software in Europe). Here the stream is steady and the tiles are
4 // turned by hand; the rules and code are this repository's own.
5 // The Mill Race rules: a stream enters a grid of channel tiles and must be turned until it runs to the water wheel.
6 // Plain data in, plain data out, no DOM, no timers, no Math.random: the grid comes from the seed and the level.
7 // A refused turn returns the very same state and says why. The page draws what this decides.
8 //
9 // The grid is size x size with size = level + 3, x to the east and y to the south. Sides are numbered clockwise from
10 // north: 0 north, 1 east, 2 south, 3 west. At rotation 0 a straight tile opens north and south, a bend north and east,
11 // a tee north, east and west, and a blank tile nothing. A quarter turn clockwise moves every opening one side on.
12 // The sluice is on the west edge, the wheel on the east edge. The water runs from the sluice through every tile that
13 // opens toward the tile it comes from, and the level is cleared when it reaches the wheel's tile and that tile opens east.
14 // Par for a level is the fewest quarter turns that put right the tiles of the path the level was laid from.
15 (function (root) {
16 const LAST_LEVEL = 5;
17 const WIN_OVER = 6; // the win line: this many moves over par in total, or fewer
18 const TYPES = ['straight', 'bend', 'tee', 'blank'];
19 const BASE = { straight: [0, 2], bend: [0, 1], tee: [0, 1, 3], blank: [] };
20 const STEP = [[0, -1], [1, 0], [0, 1], [-1, 0]]; // the neighbour across each side
21
22 const finite = v => (Number.isFinite(v) ? v : 0);
23 const sizeOf = level => level + 3;
24 const clampLevel = l => Math.min(LAST_LEVEL, Math.max(1, Math.floor(finite(l)) || 1));
25 // a repeatable number in [0, 1) for this seed and slot
26 function noise(seed, n) {
27 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
28 h = Math.imul(h ^ (h >>> 13), 1274126177);
29 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
30 }
31
32 // the sides a tile opens on, after its turns
33 const sides = t => BASE[t.type].map(s => (s + t.rot) % 4).sort();
34 const opens = (t, side) => sides(t).includes(side);
35 const inside = (s, x, y) => Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < s.size && y < s.size;
36
37 // The path the level is laid from: left to right, each column a seeded vertical run, so it never crosses itself.
38 function lay(seed, level, size) {
39 const rnd = i => noise(seed, level * 1000 + i);
40 let y = Math.floor(rnd(0) * size), n = 1;
41 const path = [];
42 for (let x = 0; x < size; x++) {
43 const to = Math.floor(rnd(n++) * size);
outdated

Both arms of this ternary are identical. Replace with const to = Math.floor(rnd(n++) * size);.

44 const dy = Math.sign(to - y);
45 while (y !== to) { path.push({ x, y }); y += dy; }
46 path.push({ x, y });
47 }
48 return path;
49 }
50
51 // what each path cell must open on: the side the water comes in by, and the side it leaves by
52 function needs(path) {
53 return path.map((c, i) => {
54 const from = i === 0 ? 3 : STEP.findIndex(([dx, dy]) => c.x + dx === path[i - 1].x && c.y + dy === path[i - 1].y);
55 const to = i === path.length - 1 ? 1 : STEP.findIndex(([dx, dy]) => c.x + dx === path[i + 1].x && c.y + dy === path[i + 1].y);
56 return [from, to];
57 });
58 }
59 const covers = (t, need) => need.every(s => opens(t, s));
60 const turnsToFit = (t, need) => { for (let k = 0; k < 4; k++) if (covers({ type: t.type, rot: (t.rot + k) % 4 }, need)) return k; return 0; };
61
62 function build(seed, level, cleared, over) {
63 seed = finite(seed) >>> 0;
64 const size = sizeOf(level), path = lay(seed, level, size), need = needs(path);
65 const rnd = i => noise(seed, level * 1000 + 500 + i);
66 const tiles = [];
67 for (let y = 0; y < size; y++) {
68 tiles.push([]);
69 for (let x = 0; x < size; x++) tiles[y].push({ type: TYPES[Math.floor(rnd(y * size + x) * TYPES.length)], rot: Math.floor(rnd(100 + y * size + x) * 4) });
70 }
71 const onPath = new Set();
72 const scramble = [];
73 path.forEach((c, i) => {
74 // a path cell is a straight or a bend as the path needs, or now and then a tee, which covers any pair of its sides
75 const [a, b] = need[i], straight = (a + 2) % 4 === b;
76 const type = rnd(200 + i) < 0.25 ? 'tee' : straight ? 'straight' : 'bend';
77 let rot = 0;
78 while (!covers({ type, rot }, need[i])) rot++;
79 const turns = Math.floor(rnd(300 + i) * 4);
80 tiles[c.y][c.x] = { type, rot }; // laid right ...
81 onPath.add(c.y * size + c.x);
82 scramble.push({ x: c.x, y: c.y, turns });
83 });
84 const s = {
85 seed, level, size, last: LAST_LEVEL, status: 'playing', cleared, over, moves: 0,
86 tiles, sluice: { x: 0, y: path[0].y, side: 3 }, wheel: { x: size - 1, y: path[path.length - 1].y, side: 1 },
87 par: 0, scramble: [], wet: [], line: '',
88 };
89 for (const q of scramble) { const t = s.tiles[q.y][q.x]; t.rot = (t.rot + q.turns) % 4; } // ... then turned out of true
90 // never start already cleared: turn path cells on until the water stops short
91 for (let i = 0; reaches(s) && i < path.length * 4; i++) {
92 const c = path[i % path.length], t = s.tiles[c.y][c.x];
93 t.rot = (t.rot + 1) % 4;
94 scramble.find(q => q.x === c.x && q.y === c.y).turns += 1;
95 }
96 // turns is how far the tile was turned out of true; undo is the fewest turns that put it right again
97 s.scramble = scramble.map((q, i) => ({ x: q.x, y: q.y, turns: q.turns % 4, undo: turnsToFit(s.tiles[q.y][q.x], need[i]) }));
98 s.par = s.scramble.reduce((n, q) => n + q.undo, 0);
99 return refresh(s);
100 }
101 // start(seed, level): level 1 unless told otherwise
102 const start = (seed = 1, level = 1) => build(seed, clampLevel(level), 0, 0);
103
104 // the cells the water reaches from the sluice, in the order it reaches them
105 function flow(s) {
106 const { x, y, side } = s.sluice, out = [], seen = new Set();
107 if (!opens(s.tiles[y][x], side)) return out;
108 const queue = [{ x, y }];
109 seen.add(y * s.size + x);
110 while (queue.length) {
111 const c = queue.shift();
112 out.push(c);
113 for (const side of sides(s.tiles[c.y][c.x])) {
114 const nx = c.x + STEP[side][0], ny = c.y + STEP[side][1];
115 if (!inside(s, nx, ny) || seen.has(ny * s.size + nx)) continue;
116 if (!opens(s.tiles[ny][nx], (side + 2) % 4)) continue;
117 seen.add(ny * s.size + nx);
118 queue.push({ x: nx, y: ny });
119 }
120 }
121 return out;
122 }
123 const reaches = s => {
124 const w = s.wheel;
125 return opens(s.tiles[w.y][w.x], w.side) && flow(s).some(c => c.x === w.x && c.y === w.y);
126 };
127
128 const verdict = s => (s.cleared >= LAST_LEVEL && s.over <= WIN_OVER ? 'won' : 'lost');
129 function refresh(s) {
130 s.wet = flow(s);
131 const over = `${s.over} ${s.over === 1 ? 'move' : 'moves'} over par`;
132 if (s.status === 'over') {
133 s.line = verdict(s) === 'won'
134 ? `The wheel turns: ${s.cleared} levels cleared, ${over}`
135 : `The race ran dry: ${s.cleared} of ${LAST_LEVEL} levels cleared, ${over}`;
136 } else {
137 s.line = `Level ${s.level} of ${LAST_LEVEL}: ${s.moves} of par ${s.par} moves, ${over}`;
138 }
139 return s;
140 }
141
142 const copy = s => Object.assign({}, s, { tiles: s.tiles.map(r => r.map(t => ({ ...t }))), scramble: s.scramble.map(q => ({ ...q })) });
143
144 // turn(state, x, y) -> { ok, why, event, state }; event is '', 'cleared' or 'over'.
145 function turn(s, x, y) {
146 if (s.status !== 'playing') return { ok: false, why: 'over', event: '', state: s };
147 if (!inside(s, x, y)) return { ok: false, why: 'off-grid', event: '', state: s };
148 if (s.tiles[y][x].type === 'blank') return { ok: false, why: 'blank', event: '', state: s };
149 const n = copy(s);
150 n.tiles[y][x].rot = (n.tiles[y][x].rot + 1) % 4;
151 n.moves = s.moves + 1;
152 if (reaches(n)) {
153 const over = s.over + Math.max(0, n.moves - n.par), cleared = s.cleared + 1;
154 if (n.level >= LAST_LEVEL) {
155 n.cleared = cleared; n.over = over; n.status = 'over';
156 return { ok: true, why: '', event: 'over', state: refresh(n) };
157 }
158 return { ok: true, why: '', event: 'cleared', state: build(n.seed, n.level + 1, cleared, over) };
159 }
160 return { ok: true, why: '', event: '', state: refresh(n) };
161 }
162
163 const api = { LAST_LEVEL, WIN_OVER, TYPES, sizeOf, sides, opens, start, turn, flow };
164 if (typeof module !== 'undefined') module.exports = api; else root.MillRace = api;
165 })(typeof window !== 'undefined' ? window : globalThis);
mill-race/race.test.mjs added +126
@@ -0,0 +1,126 @@
1 import { test, expect } from 'bun:test';
2 import { LAST_LEVEL, WIN_OVER, sizeOf, sides, opens, start, turn, flow } from './race.js';
3
4 const tile = (type, rot = 0) => ({ type, rot });
5 // a hand-made grid (plain data): rows of tiles, sluice west of the top-left cell, wheel east of the last cell of the top row
6 function hand(rows, extra = {}) {
7 const size = rows.length;
8 return { ...start(1, 1), size, tiles: rows, sluice: { x: 0, y: 0, side: 3 }, wheel: { x: size - 1, y: 0, side: 1 }, moves: 0, par: 1, cleared: 0, over: 0, level: 1, status: 'playing', ...extra };
9 }
10 const blank = () => tile('blank');
11 const reaches = s => flow(s).some(c => c.x === s.wheel.x && c.y === s.wheel.y) && opens(s.tiles[s.wheel.y][s.wheel.x], s.wheel.side);
12 // undo a level's scramble, returning the state once the water reaches the wheel
13 function solve(s) {
14 let res = { state: s, event: '' };
15 for (const q of s.scramble) for (let i = 0; i < q.undo && !res.event; i++) {
16 res = turn(res.state, q.x, q.y);
17 expect(res.ok).toBe(true);
18 }
19 return res;
20 }
21
22 test('the same seed and level give the same grid, other seeds differ, and the grid is the stated size', () => {
23 expect(start(7, 3)).toEqual(start(7, 3));
24 const seen = new Set();
25 for (let seed = 1; seed <= 20; seed++) seen.add(JSON.stringify(start(seed, 2).tiles));
26 expect(seen.size).toBeGreaterThan(5);
27 for (let l = 1; l <= LAST_LEVEL; l++) {
28 const s = start(5, l);
29 expect(s.size).toBe(sizeOf(l));
30 expect(s.tiles).toHaveLength(s.size);
31 for (const row of s.tiles) { expect(row).toHaveLength(s.size); for (const t of row) { expect(['straight', 'bend', 'tee', 'blank']).toContain(t.type); expect(t.rot).toBeGreaterThanOrEqual(0); expect(t.rot).toBeLessThan(4); } }
32 expect(s.sluice.x).toBe(0); expect(s.wheel.x).toBe(s.size - 1);
33 expect(sizeOf(l + 1)).toBeGreaterThan(sizeOf(l));
34 }
35 });
36
37 test('every generated level starts unsolved and is solvable by undoing its turns', () => {
38 for (let seed = 0; seed < 40; seed++) for (let l = 1; l <= LAST_LEVEL; l++) {
39 const s = start(seed, l);
40 expect(reaches(s)).toBe(false);
41 let cur = s, last = { event: '' };
42 for (const q of s.scramble) for (let i = 0; i < (4 - q.turns) % 4 && !last.event; i++) {
43 expect(reaches(cur)).toBe(false);
44 last = turn(cur, q.x, q.y); cur = last.state;
45 }
46 expect([seed, l, last.event]).toEqual([seed, l, l === LAST_LEVEL ? 'over' : 'cleared']);
47 expect(s.par).toBeGreaterThan(0);
48 }
49 });
50
51 test('a refused turn returns the same state and says why', () => {
52 const s = hand([[tile('straight', 1), blank()], [blank(), blank()]]);
53 for (const [x, y, why] of [[1, 0, 'blank'], [-1, 0, 'off-grid'], [0, 2, 'off-grid'], [2, 0, 'off-grid'], [0.5, 0, 'off-grid'], ['0', 0, 'off-grid']]) {
54 const r = turn(s, x, y);
55 expect([x, y, r.ok, r.why]).toEqual([x, y, false, why]);
56 expect(r.state).toBe(s);
57 }
58 expect(s.moves).toBe(0);
59 });
60
61 test('a quarter turn clockwise changes which neighbours connect and counts one move', () => {
62 expect(sides(tile('straight', 0))).toEqual([0, 2]);
63 expect(sides(tile('bend', 0))).toEqual([0, 1]);
64 expect(sides(tile('bend', 1))).toEqual([1, 2]);
65 expect(sides(tile('tee', 0))).toEqual([0, 1, 3]);
66 expect(sides(tile('tee', 3))).toEqual([0, 2, 3]);
67 const s = hand([[tile('straight', 0), tile('straight', 1), tile('straight', 0)], [blank(), blank(), blank()], [blank(), blank(), blank()]]);
68 expect(flow(s)).toEqual([]); // the sluice is not met by a tile that opens north-south
69 const r = turn(s, 0, 0);
70 expect(r.ok).toBe(true);
71 expect(r.state.tiles[0][0].rot).toBe(1);
72 expect(r.state.moves).toBe(1);
73 expect(s.tiles[0][0].rot).toBe(0); // the old state is left alone
74 expect(flow(r.state)).toEqual([{ x: 0, y: 0 }, { x: 1, y: 0 }]); // water now reaches past the first tile, not yet the wheel
75 });
76
77 test('flow stops at a break and reaches the wheel when joined', () => {
78 const broken = hand([[tile('straight', 1), tile('straight', 0), tile('straight', 1)], [blank(), blank(), blank()], [blank(), blank(), blank()]]);
79 expect(flow(broken)).toEqual([{ x: 0, y: 0 }]);
80 expect(reaches(broken)).toBe(false);
81 const r = turn(broken, 1, 0); // the middle tile now joins the sluice to the wheel
82 expect(r.event).toBe('cleared'); // so the level is cleared and the next one is laid
83 expect(r.state.level).toBe(2);
84 const joined = { ...broken, tiles: broken.tiles.map((row, y) => row.map((t, x) => (x === 1 && y === 0 ? tile('straight', 1) : t))) };
85 expect(flow(joined).map(c => c.x)).toEqual([0, 1, 2]);
86 expect(reaches(joined)).toBe(true);
87 });
88

This only checks moves===1; it does not test that a wasted move is counted over par. Clear the level with extra turns and assert over rose by exactly the extras.

89 test('clearing a level starts the next, larger one and counts moves over par', () => {
90 const s = start(3, 1);
91 const r = solve(s);
92 expect(r.event).toBe('cleared');
93 expect(r.state.level).toBe(2);
94 expect(r.state.size).toBe(sizeOf(2));
95 expect(r.state.cleared).toBe(1);
96 expect(r.state.moves).toBe(0);
97 expect(r.state.over).toBe(Math.max(0, s.scramble.reduce((n, q) => n + (4 - q.turns) % 4, 0) - s.par));
98 // wasted turns are counted over par: four quarter turns on one tile change nothing but cost four moves
99 const t = start(3, 1), q = t.scramble[0];
100 let cur = t;
101 for (let i = 0; i < 4; i++) cur = turn(cur, q.x, q.y).state;
102 expect(cur.tiles).toEqual(t.tiles);
103 expect(cur.moves).toBe(4);
104 const done = solve(cur);
105 expect(done.event).toBe('cleared');
106 expect(done.state.over).toBe(4);
107 });
108
109 test('the last level ends the game: a win line at or under the stated total over par, a loss line over it', () => {
110 const finish = over => solve({ ...start(4, LAST_LEVEL), cleared: LAST_LEVEL - 1, over });
111 const win = finish(0);
112 expect(win.event).toBe('over');
113 expect(win.state.status).toBe('over');
114 expect(win.state.cleared).toBe(LAST_LEVEL);
115 expect(win.state.over).toBe(0);
116 expect(win.state.line).toStartWith('The wheel turns:');
117 expect(win.state.line).toContain(`${LAST_LEVEL} levels cleared`);
118 const edge = finish(WIN_OVER);
119 expect(edge.state.over).toBe(WIN_OVER);
120 expect(edge.state.line).toStartWith('The wheel turns:');
121 const loss = finish(WIN_OVER + 1);
122 expect(loss.state.over).toBe(WIN_OVER + 1);
123 expect(loss.state.line).toStartWith('The race ran dry:');
124 expect(loss.state.line).toContain(`${WIN_OVER + 1} moves over par`);
125 expect(turn(loss.state, 0, 0)).toMatchObject({ ok: false, why: 'over' });
126 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs