anvilsign in

collin/mahjong

1import { describe, expect, it } from 'vitest';
2import { makeRng, STACKS_PER_SIDE } from '../game/tiles';
3import {
4 DEALT_STACKS,
5 isBarrier,
6 ringFor,
7 ringLayout,
8 ringOpening,
9 SEAT_WALL_SIDE,
10 sideStacks,
11 wallStacks,
12 type Placed,
13} from '../game/wall';
14import type { SeatId } from '../game/types';
15import {
16 addBody,
17 createWorld,
18 faceOn,
19 liftFor,
20 outside,
21 overlapping,
22 settled,
23 step,
24 type Rect,
25 type Spawn,
26} from './physics';
27import { canThrow, segmentHitsRect, type TableGeometry } from './geometry';
28
29const POOL: Rect = { x: 200, y: 200, w: 220, h: 220 };
30/** Same aspect as a real tile, roughly pool-tile sized. */
31const TILE = { w: 26, h: 36 };
32/** Generous: moving, and then untangling itself, is done well inside this. */
33const SETTLE_CAP = 700;
34
35function throwAt(rng: () => number): Spawn {
36 const centre = { x: POOL.x + POOL.w / 2, y: POOL.y + POOL.h / 2 };
37 // From below the pool, as seat 0 would, but aimed all over the place and
38 // hard enough to be a genuine test of the bounds.
39 const from = { x: 100 + rng() * 400, y: 560 };
40 const spread = (rng() - 0.5) * 260;
41 const dx = centre.x + spread - from.x;
42 const dy = centre.y - from.y;
43 const d = Math.hypot(dx, dy);
44 const speed = 900 + rng() * 1800;
45 return {
46 tile: Math.floor(rng() * 34),
47 seat: 0,
48 x: from.x,
49 y: from.y,
50 vx: (dx / d) * speed,
51 vy: (dy / d) * speed,
52 z: 12,
53 vz: 300 + rng() * 500,
54 angle: rng() * Math.PI * 2,
55 spin: (rng() - 0.5) * 14,
56 w: TILE.w,
57 h: TILE.h,
58 };
59}
60
61function runToRest(world: ReturnType<typeof createWorld>, cap = SETTLE_CAP): number {
62 let steps = 0;
63 while (!settled(world) && steps < cap) {
64 step(world);
65 steps++;
66 }
67 return steps;
68}
69
70describe('physics — the pile', () => {
71 it('never lets a tile out of the pool, however hard it is thrown', () => {
72 const rng = makeRng(20260819);
73 for (let trial = 0; trial < 40; trial++) {
74 const world = createWorld(POOL);
75 // A full hand's worth, thrown one after another into the same pool.
76 for (let i = 0; i < 16; i++) {
77 addBody(world, throwAt(rng));
78 for (let s = 0; s < 40; s++) step(world);
79 }
80 runToRest(world);
81 for (const b of world.bodies) {
82 expect(outside(b, POOL)).toBeLessThan(0.5);
83 expect(b.z).toBe(0);
84 }
85 }
86 });
87
88 it('settles everything, rather than jittering forever', () => {
89 const rng = makeRng(7);
90 const world = createWorld(POOL);
91 for (let i = 0; i < 30; i++) addBody(world, throwAt(rng));
92 const steps = runToRest(world);
93 expect(steps).toBeLessThan(SETTLE_CAP);
94 expect(settled(world)).toBe(true);
95 });
96
97 it('never lets two tiles share the same ground', () => {
98 // A whole hand's worth thrown into one pool, then checked pair by pair as
99 // rotated rectangles — not as circles, which would let two tiles at an angle
100 // sit across each other and call it clear.
101 const rng = makeRng(4242);
102 const world = createWorld(POOL);
103 for (let i = 0; i < 24; i++) {
104 addBody(world, throwAt(rng));
105 for (let s = 0; s < 45; s++) step(world);
106 }
107 runToRest(world);
108
109 for (let i = 0; i < world.bodies.length; i++) {
110 for (let j = i + 1; j < world.bodies.length; j++) {
111 // Sub-pixel contact is how a pile rests against itself; see CONTACT_SLOP.
112 expect(overlapping(world.bodies[i], world.bodies[j])).toBeLessThan(1);
113 }
114 }
115 });
116
117 it('carries a hard throw much further than a soft one', () => {
118 // The whole point of throwing it yourself: how hard you flick has to show.
119 // Friction heavy enough to eat the difference would make every discard land
120 // in the same place however it was let go of.
121 // Ground covered, not distance from where it started: a hard throw crosses
122 // the square and comes back off the far side, which is the point of it.
123 const travel = (speed: number) => {
124 const world = createWorld(POOL);
125 const b = addBody(world, {
126 tile: 0,
127 seat: 0,
128 x: POOL.x + 20,
129 y: POOL.y + POOL.h / 2,
130 vx: speed,
131 vy: 0,
132 z: 0,
133 vz: 0,
134 angle: 0,
135 spin: 0,
136 w: TILE.w,
137 h: TILE.h,
138 });
139 let covered = 0;
140 for (let i = 0; i < SETTLE_CAP && !settled(world); i++) {
141 const x = b.x;
142 const y = b.y;
143 step(world);
144 covered += Math.hypot(b.x - x, b.y - y);
145 }
146 return covered;
147 };
148
149 const soft = travel(220);
150 const hard = travel(2200);
151 expect(hard).toBeGreaterThan(soft * 3);
152 // And a hard one gets right across the square rather than dying halfway.
153 expect(hard).toBeGreaterThan(POOL.w * 0.55);
154 });
155
156 it('bounces a hard throw off the far side instead of sticking to it', () => {
157 const world = createWorld(POOL);
158 const b = addBody(world, {
159 tile: 0,
160 seat: 0,
161 x: POOL.x + 20,
162 y: POOL.y + POOL.h / 2,
163 vx: 2600,
164 vy: 0,
165 z: 0,
166 vz: 0,
167 angle: 0,
168 spin: 0,
169 w: TILE.w,
170 h: TILE.h,
171 });
172 // Run until it has been turned around by the far wall.
173 let bounced = false;
174 for (let i = 0; i < SETTLE_CAP && !bounced; i++) {
175 step(world);
176 if (b.vx < -40) bounced = true;
177 }
178 expect(bounced).toBe(true);
179 runToRest(world);
180 expect(outside(b, POOL)).toBeLessThan(0.5);
181 });
182
183 it('says which edge a tile was thrown into, and whose tile it was', () => {
184 // The middle stops where a player's tiles start, so an edge taken at speed
185 // is a discard thrown into somebody's hand — which is a thing they answer.
186 const world = createWorld(POOL);
187 const b = addBody(world, {
188 tile: 0,
189 seat: 2,
190 x: POOL.x + POOL.w - 30,
191 y: POOL.y + POOL.h / 2,
192 vx: 2400,
193 vy: 0,
194 z: 0,
195 vz: 0,
196 angle: 0,
197 spin: 0,
198 w: TILE.w,
199 h: TILE.h,
200 });
201
202 const edges: string[] = [];
203 for (let i = 0; i < SETTLE_CAP && !settled(world); i++) {
204 for (const hit of step(world)) if (hit.edge) edges.push(`${hit.edge}:${hit.seat}`);
205 }
206 expect(edges[0]).toBe('right:2');
207 // And a tile that merely rolls up to the edge is not an incident.
208 b.resting = false;
209 b.vx = 20;
210 const gentle = [];
211 for (let i = 0; i < 60; i++) for (const hit of step(world)) if (hit.edge) gentle.push(hit);
212 expect(gentle).toHaveLength(0);
213 });
214
215 it('always comes to rest face up, however it tumbles', () => {
216 // A tile lying face down in the discards is a tile nobody can read, so this
217 // is a guarantee rather than something the animation happens to get right.
218 const rng = makeRng(31337);
219 const world = createWorld(POOL);
220 for (let i = 0; i < 20; i++) {
221 const spawn = throwAt(rng);
222 addBody(world, {
223 ...spawn,
224 // Every awkward number of turns, over every awkward flight time.
225 flipTurns: 1 + Math.floor(rng() * 3),
226 flipOver: 0.2 + rng() * 0.5,
227 flipAxis: rng() * Math.PI * 2,
228 });
229 for (let s = 0; s < 40; s++) step(world);
230 }
231 runToRest(world);
232
233 for (const b of world.bodies) {
234 expect(b.resting).toBe(true);
235 // Square on to the table, not edge on and not face down.
236 expect(faceOn(b)).toBeCloseTo(1, 6);
237 }
238 });
239
240 it('turns a lobbed tile over in the air and lands it flat', () => {
241 const world = createWorld(POOL);
242 const b = addBody(world, {
243 tile: 0,
244 seat: 0,
245 x: POOL.x + POOL.w / 2,
246 y: POOL.y + POOL.h + 90,
247 vx: 0,
248 vy: -320,
249 z: 0,
250 vz: liftFor(0.6),
251 angle: 0,
252 spin: 0,
253 flipTurns: 2,
254 flipOver: 0.6,
255 flipAxis: Math.PI / 2,
256 w: TILE.w,
257 h: TILE.h,
258 });
259
260 // Somewhere in the air it must actually show its back, or it never turned.
261 let showedBack = false;
262 for (let i = 0; i < SETTLE_CAP && !settled(world); i++) {
263 step(world);
264 if (faceOn(b) < -0.2) showedBack = true;
265 }
266 expect(showedBack).toBe(true);
267 expect(faceOn(b)).toBeCloseTo(1, 6);
268 });
269
270 it('is deterministic — the same throws give the same pile', () => {
271 const pile = () => {
272 const rng = makeRng(99);
273 const world = createWorld(POOL);
274 for (let i = 0; i < 12; i++) {
275 addBody(world, throwAt(rng));
276 for (let s = 0; s < 30; s++) step(world);
277 }
278 runToRest(world);
279 return world.bodies.map((b) => [b.x, b.y, b.angle]);
280 };
281 // This is what lets a refresh mid-hand come back to the pile it had.
282 expect(pile()).toEqual(pile());
283 });
284
285 it('gets a tile into the pool even when the wall is in the way', () => {
286 // A standing wall right across the throw, with the tile flicked flat at it:
287 // it cannot get in on its own, and must not be left outside.
288 const world = createWorld(POOL, [{ x: 150, y: 440, w: 320, h: 36 }]);
289 addBody(world, {
290 tile: 0,
291 seat: 0,
292 x: 310,
293 y: 520,
294 vx: 0,
295 vy: -400,
296 z: 0,
297 vz: 0,
298 angle: 0,
299 spin: 0,
300 w: TILE.w,
301 h: TILE.h,
302 });
303 runToRest(world);
304 expect(settled(world)).toBe(true);
305 expect(outside(world.bodies[0], POOL)).toBeLessThan(0.5);
306 });
307
308 it('makes room for a tile dropped into a settled pile', () => {
309 // A rebuilt pile — every tile placed at rest on the same spot.
310 const world = createWorld(POOL);
311 const at = (n: number) =>
312 addBody(world, {
313 tile: n,
314 seat: 0,
315 x: 310,
316 y: 310,
317 vx: 0,
318 vy: 0,
319 z: 0,
320 vz: 0,
321 angle: 0,
322 spin: 0,
323 w: TILE.w,
324 h: TILE.h,
325 atRest: true,
326 });
327 for (let i = 0; i < 8; i++) at(i);
328
329 // Placing them is a first shove; the world untangles the rest without
330 // anything appearing to move, and is not settled until it has.
331 runToRest(world);
332 expect(settled(world)).toBe(true);
333 for (const b of world.bodies) expect(outside(b, POOL)).toBeLessThan(0.5);
334 // Nothing sharing ground with anything else.
335 for (let i = 0; i < world.bodies.length; i++) {
336 for (let j = i + 1; j < world.bodies.length; j++) {
337 expect(overlapping(world.bodies[i], world.bodies[j])).toBeLessThan(1);
338 }
339 }
340 });
341});
342
343// ---------------------------------------------------------------------------
344
345/** A seat-0 view: pool up the screen, a wall across it, hand below. */
346function geometry(walls: Rect[]): TableGeometry {
347 return {
348 size: { w: 620, h: 620 },
349 pool: POOL,
350 walls,
351 tile: TILE,
352 felt: { x: 120, y: 120, w: 380, h: 380 },
353 launch: { 0: { x: 310, y: 560 } },
354 throwFrom: { 0: { x: 310, y: 560 } },
355 };
356}
357
358/** The near side of the square, as 18 stacks. */
359const nearSide = (): Rect[] =>
360 Array.from({ length: 18 }, (_, i) => ({ x: 180 + i * 14, y: 440, w: 14, h: 36 }));
361
362describe('the throw gate', () => {
363 it('is shut while the wall in front of the seat is standing', () => {
364 expect(canThrow(geometry(nearSide()), 0)).toBe(false);
365 });
366
367 it('opens once a run of stacks has been drawn', () => {
368 const walls = nearSide().filter((_, i) => i < 6 || i > 11);
369 expect(canThrow(geometry(walls), 0)).toBe(true);
370 });
371
372 it('opens on a gap off to one side, not just straight ahead', () => {
373 // A gap left of centre, with everything dead ahead still standing: the only
374 // way in is at an angle, towards the near corner of the pool.
375 const walls = nearSide().filter((_, i) => i < 2 || i > 7);
376 expect(canThrow(geometry(walls), 0)).toBe(true);
377 });
378
379 it('stays shut for a gap too far round to reach the pool in a line', () => {
380 // Stacks 0-3 are drawn, but that gap sits off the end of the pool: a tile
381 // aimed through it lands beside the square, not in it. Openness is about
382 // getting in, so this is genuinely still shut.
383 const walls = nearSide().filter((_, i) => i > 3);
384 expect(canThrow(geometry(walls), 0)).toBe(false);
385 });
386
387 it('is shut for a seat with no hand on screen', () => {
388 expect(canThrow(geometry([]), 2)).toBe(false);
389 });
390
391 it('is open when the square has been eaten away entirely', () => {
392 expect(canThrow(geometry([]), 0)).toBe(true);
393 });
394});
395
396describe('segmentHitsRect', () => {
397 const r: Rect = { x: 10, y: 10, w: 20, h: 20 };
398
399 it('finds a crossing', () => {
400 expect(segmentHitsRect({ x: 0, y: 20 }, { x: 40, y: 20 }, r)).toBe(true);
401 });
402 it('misses a segment that passes by', () => {
403 expect(segmentHitsRect({ x: 0, y: 40 }, { x: 40, y: 40 }, r)).toBe(false);
404 });
405 it('misses a segment that stops short', () => {
406 expect(segmentHitsRect({ x: 0, y: 20 }, { x: 5, y: 20 }, r)).toBe(false);
407 });
408 it('finds a diagonal through a corner', () => {
409 expect(segmentHitsRect({ x: 0, y: 0 }, { x: 20, y: 20 }, r)).toBe(true);
410 });
411});
412
413// ---------------------------------------------------------------------------
414
415describe('wallStacks', () => {
416 const at = (drawnFront: number, drawnBack = 0) =>
417 wallStacks({ drawnFront, drawnBack, rules: { wallReserve: 16 } });
418
419 it('starts as 72 full stacks', () => {
420 const s = at(0);
421 expect(s).toHaveLength(72);
422 expect(s.every((x) => x.count === 2)).toBe(true);
423 expect(s[0].next).toBe(true);
424 });
425
426 it('eats the square from the front, a stack at a time', () => {
427 // The deal takes 64 tiles plus the dealer's opener.
428 const s = at(65);
429 expect(s.slice(0, 32).every((x) => x.count === 0)).toBe(true);
430 expect(s[32].count).toBe(1);
431 expect(s[33].count).toBe(2);
432 expect(s[32].next).toBe(true);
433 });
434
435 it('eats it from the back too, for kong and flower replacements', () => {
436 const s = at(0, 3);
437 expect(s[71].count).toBe(0);
438 expect(s[70].count).toBe(1);
439 });
440
441 it('marks the 16-tile 底牌 tail dead', () => {
442 const s = at(0);
443 expect(s[71].dead).toBe(true);
444 expect(s[64].dead).toBe(true);
445 expect(s[63].dead).toBe(false);
446 });
447
448 it('counts only a full stack as something to throw over', () => {
449 // The rule both halves of the throw hang off: a stack of two is as tall as
450 // the tile coming at it, one of one is not, and a spent one is not there.
451 const s = at(65);
452 expect(isBarrier(s[33])).toBe(true); // two left
453 expect(isBarrier(s[32])).toBe(false); // one left — sail over it
454 expect(isBarrier(s[0])).toBe(false); // gone
455 });
456
457 it('gives each seat the side of the square in front of it', () => {
458 // Seats run bottom, right, top, left; sides are drawn top, right, bottom,
459 // left — so the two orders are genuinely different and worth pinning.
460 expect(SEAT_WALL_SIDE[0 as SeatId]).toBe(2);
461 expect(SEAT_WALL_SIDE[2 as SeatId]).toBe(0);
462 const s = at(65);
463 // At the deal the top side is gone, so the seat across the table is open
464 // while the near seat's own wall has not been touched.
465 expect(sideStacks(s, SEAT_WALL_SIDE[2 as SeatId]).every((x) => x.count === 0)).toBe(true);
466 expect(sideStacks(s, SEAT_WALL_SIDE[0 as SeatId]).every((x) => x.count === 2)).toBe(true);
467 expect(sideStacks(s, 0)).toHaveLength(STACKS_PER_SIDE);
468 });
469});
470
471describe('ringFor', () => {
472 // A tile as it comes out on an ordinary window, and the stack it makes.
473 const cell = { s: 31, d: 43 };
474 const holds = (cap: { h: number; v: number }) => 2 * (cap.h + cap.v);
475
476 it('builds a square the size of the wall as it is dealt', () => {
477 const cap = ringFor({ w: 990, h: 360 }, cell);
478 expect(cap).toEqual({ h: 10, v: 10 });
479 expect(holds(cap)).toBe(DEALT_STACKS);
480 // And it leaves the middle of itself for the discards.
481 expect(ringOpening(cap, cell).w).toBe(10 * 31 - 43);
482 });
483
484 it('gives up being square before it gives up a tile', () => {
485 // A middle too shallow for ten stacks down its side: the wall gets longer
486 // rather than the tiles getting smaller.
487 const cap = ringFor({ w: 990, h: 220 }, cell);
488 expect(cap.v).toBeLessThan(10);
489 expect(cap.h).toBeGreaterThan(10);
490 expect(holds(cap)).toBeGreaterThanOrEqual(DEALT_STACKS);
491 });
492
493 it('never asks for more room than it has, however small the middle', () => {
494 for (const space of [{ w: 990, h: 360 }, { w: 400, h: 400 }, { w: 300, h: 140 }, { w: 60, h: 40 }]) {
495 const cap = ringFor(space, cell);
496 expect(cap.h).toBeGreaterThanOrEqual(1);
497 expect(cap.v).toBeGreaterThanOrEqual(1);
498 expect(cap.h * cell.s + cell.d).toBeLessThanOrEqual(Math.max(space.w, cell.s + cell.d));
499 expect(cap.v * cell.s + cell.d).toBeLessThanOrEqual(Math.max(space.h, cell.s + cell.d));
500 }
501 });
502});
503
504describe('ringLayout', () => {
505 const at = (drawnFront: number, drawnBack = 0) =>
506 wallStacks({ drawnFront, drawnBack, rules: { wallReserve: 16 } });
507 const flat = (sides: Placed[][]) => sides.flat();
508 // A middle much wider than it is deep, which is what an ordinary window has.
509 const wide = { h: 30, v: 10 };
510
511 it('draws what is still standing and nothing else', () => {
512 const sides = ringLayout(at(65), wide);
513 const placed = flat(sides);
514 expect(placed).toHaveLength(40);
515 expect(placed.every((p) => p.stack.count > 0)).toBe(true);
516 // In order all the way round: the break point first, the 底牌 tail last.
517 expect(placed[0].index).toBe(32);
518 expect(placed[0].stack.next).toBe(true);
519 expect(placed[placed.length - 1].index).toBe(71);
520 expect(placed.every((p, i) => i === 0 || p.index > placed[i - 1].index)).toBe(true);
521 });
522
523 it('fills the square it was built for, then is eaten from the break point', () => {
524 // Built to the wall as dealt, so at the deal it comes out full and square.
525 const square = { h: 10, v: 10 };
526 expect(ringLayout(at(64), square).map((s) => s.length)).toEqual([10, 10, 10, 10]);
527 // From there the gap opens where the drawing is happening and nothing else
528 // moves: the far end stays pinned to the end of the square.
529 const eaten = ringLayout(at(78), square);
530 expect(eaten.map((s) => s.length)).toEqual([3, 10, 10, 10]);
531 expect(eaten[0][0].stack.next).toBe(true);
532 // And the other end shortens when a kong or a flower takes from the tail.
533 expect(ringLayout(at(64, 6), square).map((s) => s.length)).toEqual([10, 10, 10, 7]);
534 });
535
536 it('never puts more on a side than fits, however little ring there is', () => {
537 for (const cap of [
538 { h: 30, v: 10 },
539 { h: 18, v: 18 },
540 { h: 6, v: 2 },
541 { h: 1, v: 1 },
542 ]) {
543 for (const front of [0, 1, 65, 100, 128]) {
544 const sides = ringLayout(at(front), cap);
545 const lengths = [cap.h, cap.v, cap.h, cap.v];
546 sides.forEach((side, i) => expect(side.length).toBeLessThanOrEqual(lengths[i]));
547 const live = at(front).filter((s) => s.count > 0).length;
548 expect(flat(sides)).toHaveLength(Math.min(live, 2 * (cap.h + cap.v)));
549 }
550 }
551 });
552
553 it('keeps the far end of the wall when there is not room for all of it', () => {
554 // Overflow only happens before a hand is dealt. What has to go is the front,
555 // since that is the part about to be drawn anyway.
556 const sides = ringLayout(at(0), { h: 6, v: 2 });
557 const placed = flat(sides);
558 expect(placed).toHaveLength(16);
559 expect(placed[placed.length - 1].index).toBe(71);
560 expect(placed[0].index).toBe(56);
561 });
562});