anvilsign in

collin/mahjong

1import type { GameState } from '../game/engine';
2import { makeRng, type Tile } from '../game/tiles';
3import type { SeatId } from '../game/types';
4import {
5 aimAt,
6 canThrow,
7 canThrowFrom,
8 centreOf,
9 measure,
10 spanThrough,
11 type Point,
12 type TableGeometry,
13} from './geometry';
14import {
15 addBody,
16 advance as advanceWorld,
17 createWorld,
18 liftFor,
19 reshape,
20 settled,
21 stir,
22 SLIDE_TIME,
23 type Body,
24 type Impact,
25 type Rect,
26 type World,
27} from './physics';
28
29const SEATS: SeatId[] = [0, 1, 2, 3];
30
31/**
32 * The tiles in the middle, kept honest against the game state.
33 *
34 * This *diffs* rather than listening for events, and that is the whole design.
35 * A discard is identified by which seat threw it and how many it had thrown
36 * before — and those keys never shift, because discards are only ever pushed and
37 * `engine.executeClaim` only ever pops the one on top. So every way the pile can
38 * change is the same code path: a key that has appeared is a tile to throw in, a
39 * key that has gone is a tile to take out. Undo, 下一局, a claim, and picking up
40 * a saved game all fall out of that without the engine knowing this exists.
41 *
42 * Nothing here is stored in the game state, so there is no save format to
43 * change. A pile is rebuilt from the discards it can see, seeded off the hand
44 * number and each tile's place in it, which is why a refresh mid-hand comes back
45 * to the pile it had rather than a freshly scattered one.
46 */
47
48/** How long a placed tile is in the air. Long enough to arc over the wall. */
49const PLACE_FLIGHT = 0.62;
50/** A flicked tile hops rather than lofts — across the table, not over a wall. */
51const THROW_LIFT = 0.18;
52/** Fastest flick we will honour, px/s. Beyond this it is a slip, not a throw. */
53export const MAX_THROW_SPEED = 3600;
54/** How long a claimed tile takes to leave the table for the seat taking it. */
55const TAKE_FLIGHT = 0.34;
56
57/** A tile on its way off the table, no longer part of the pile. */
58interface Leaving {
59 body: Body;
60 tx: number;
61 ty: number;
62 /** 0 to 1. */
63 t: number;
64}
65
66/**
67 * Whether a tile turns over on its way in.
68 *
69 * Off for now. Like `LOB_WHEN_WALLED` below, the tumble is kept whole — the
70 * flip is a real axis in `physics.ts` and the renderer already squashes the
71 * tile along it — and this is the only switch that reaches it, so putting it
72 * back is one word rather than a rewrite.
73 */
74const TUMBLE: boolean = false;
75
76/**
77 * Whether a wall standing in the way turns a discard into a lob over the top
78 * rather than a flick across the table.
79 *
80 * Back on now that the square is a square again. It was off while the wall ran
81 * along the edges of the middle, where there was nothing much to get over and
82 * everything read better slid; a square standing in the middle with the pool
83 * inside it is the other case, and a tile slid flat at it simply bounces off
84 * and ends up lying outside — which is not where a discard goes. As the square
85 * is eaten the gaps open and the slide comes back on its own, seat by seat.
86 */
87const LOB_WHEN_WALLED: boolean = true;
88
89/** A tile lifted out of a hand and carried about. Drawn, but not simulated. */
90export interface Held {
91 seat: SeatId;
92 tile: Tile;
93 /** Where it came from in that seat's hand, so the caller knows what to play. */
94 index: number;
95 x: number;
96 y: number;
97 angle: number;
98 /** The size it was in the hand — it shrinks to pool size once thrown. */
99 w: number;
100 h: number;
101}
102
103/** A throw that has been let go of, waiting for the discard it belongs to. */
104interface Release {
105 seat: SeatId;
106 x: number;
107 y: number;
108 angle: number;
109 w: number;
110 h: number;
111 vx: number;
112 vy: number;
113 spin: number;
114}
115
116export class TablePool {
117 world: World | null = null;
118 geo: TableGeometry | null = null;
119 /** The tile in somebody's fingers, if any. */
120 held: Held | null = null;
121 /**
122 * Poke the render loop. Set by ui/Pool.tsx while it is mounted; a gesture
123 * calls it so a carried tile follows the finger without waiting on a re-render.
124 */
125 wake: () => void = () => {};
126
127 private table: HTMLElement | null = null;
128 /** Bodies by `seat:index` into that seat's discards. */
129 private entries = new Map<string, Body>();
130 private release: Release | null = null;
131 /** What the wall looked like when we last measured, so we know to re-measure. */
132 private measuredAt = '';
133 private hand = -1;
134 /** The tile currently on the table to be claimed, so it can be marked. */
135 private newestKey: string | null = null;
136 /** How many melds each seat had last time, to spot who took a tile. */
137 private melds = [0, 0, 0, 0];
138 /** Tiles on their way off the table. Drawn, but out of the physics. */
139 private leaving: Leaving[] = [];
140 /** When the table will have stopped talking. See `heckle`. */
141 private quietAt = 0;
142
143 // Which seats can throw, as a string, so the seats can re-render when it
144 // changes. Read through useSyncExternalStore, the same way the game is.
145 private openness = '----';
146 private listeners = new Set<() => void>();
147
148 attach(table: HTMLElement) {
149 this.table = table;
150 this.measuredAt = '';
151 }
152
153 detach() {
154 this.table = null;
155 this.world = null;
156 this.geo = null;
157 this.held = null;
158 this.release = null;
159 this.entries.clear();
160 this.leaving = [];
161 this.measuredAt = '';
162 }
163
164 subscribe = (cb: () => void) => {
165 this.listeners.add(cb);
166 return () => this.listeners.delete(cb);
167 };
168
169 /** Which seats have a clear line in, as a string — cheap to compare. */
170 getSnapshot = () => this.openness;
171
172 /** Force a re-measure — the window resized, or the layout changed under us. */
173 invalidate() {
174 this.measuredAt = '';
175 }
176
177 /**
178 * Whether this seat can flick a tile in, or has to lift it over the wall.
179 * Unmeasured (or compact, where there is no square) means no.
180 */
181 canThrow(seat: SeatId): boolean {
182 return this.openness[seat] === 'y';
183 }
184
185 /** Where the middle of the table is, for a gesture working out its aim. */
186 get poolCentre(): Point | null {
187 return this.geo ? centreOf(this.geo.pool) : null;
188 }
189
190 /** Whether a point is already inside the square — a tile dropped there stays. */
191 inPool(x: number, y: number): boolean {
192 const p = this.geo?.pool;
193 if (!p) return false;
194 return x >= p.x && x <= p.x + p.w && y >= p.y && y <= p.y + p.h;
195 }
196
197 /** Whether a tile let go of *here* has a clear line in. Not the same question
198 * as `canThrow(seat)`: a carried tile is wherever the player took it. */
199 canThrowFrom(x: number, y: number): boolean {
200 return !!this.geo && canThrowFrom(this.geo, { x, y });
201 }
202
203 /** Where the pool sits on the table, for the patch of it you can reach into. */
204 get poolRect(): Rect | null {
205 return this.geo?.pool ?? null;
206 }
207
208 /**
209 * Push the tiles in the middle about — washing them, the way everybody does
210 * to a pool of discards while waiting. Purely cosmetic: where a discard is
211 * lying is not part of the game.
212 */
213 stir(x: number, y: number, vx: number, vy: number) {
214 if (!this.world || !this.geo) return;
215 // A finger's worth: about a tile across.
216 stir(this.world, x, y, vx, vy, this.geo.tile.w * 0.6);
217 }
218
219 // ---- the tile in your fingers -----------------------------------------
220
221 /** Lifted out of a hand. From here the canvas draws it, not the DOM. */
222 pickUp(held: Held) {
223 this.held = held;
224 }
225
226 moveHeld(x: number, y: number, angle?: number) {
227 if (!this.held) return;
228 this.held.x = x;
229 this.held.y = y;
230 if (angle !== undefined) this.held.angle = angle;
231 }
232
233 /** Put it back in the hand — the throw was not committed to. */
234 cancelHeld() {
235 this.held = null;
236 }
237
238 /**
239 * Let go of it. The body is not made here: the reconciler owns every tile in
240 * the pool, so this leaves the throw where the next `sync` will find it and
241 * the caller goes on to call `game.discard`. The held tile stays drawn until
242 * that happens, so there is no frame with nothing on screen.
243 */
244 throwHeld(vx: number, vy: number, spin: number) {
245 const h = this.held;
246 if (!h) return;
247 const speed = Math.hypot(vx, vy);
248 const scale = speed > MAX_THROW_SPEED ? MAX_THROW_SPEED / speed : 1;
249 this.release = {
250 seat: h.seat,
251 x: h.x,
252 y: h.y,
253 angle: h.angle,
254 w: h.w,
255 h: h.h,
256 vx: vx * scale,
257 vy: vy * scale,
258 spin,
259 };
260 }
261
262 // ---- keeping up with the game ----------------------------------------
263
264 /** Bring the pile in line with the state. Cheap when nothing has changed. */
265 sync(state: GameState) {
266 this.remeasure(state);
267 const geo = this.geo;
268 const world = this.world;
269 if (!geo || !world) return;
270
271 // A new hand is a new pile, and nothing should fly anywhere.
272 const fresh = state.handNumber !== this.hand;
273 this.hand = state.handNumber;
274
275 const want = new Set<string>();
276 const added: { key: string; seat: SeatId; index: number; tile: Tile }[] = [];
277 for (const seat of SEATS) {
278 const discards = state.players[seat].discards;
279 for (let i = 0; i < discards.length; i++) {
280 const key = `${seat}:${i}`;
281 want.add(key);
282 if (!this.entries.has(key)) added.push({ key, seat, index: i, tile: discards[i] });
283 }
284 }
285
286 const taken: Body[] = [];
287 for (const [key, body] of this.entries) {
288 if (want.has(key)) continue;
289 const at = world.bodies.indexOf(body);
290 if (at >= 0) world.bodies.splice(at, 1);
291 this.entries.delete(key);
292 taken.push(body);
293 }
294
295 // Exactly one tile off the table is somebody taking it — a 碰, a 吃, a 槓,
296 // or a discard being taken back. It goes to whoever now has a meld they did
297 // not have a moment ago, and failing that back to the seat that threw it,
298 // which is what an undo is. Several at once is the hand ending, and those
299 // simply go.
300 const claimer = SEATS.find((q) => state.players[q].melds.length > this.melds[q]);
301 this.melds = SEATS.map((q) => state.players[q].melds.length);
302 if (taken.length === 1 && !fresh) {
303 const to = geo.launch[claimer ?? taken[0].seat];
304 if (to) this.leaving.push({ body: taken[0], tx: to.x, ty: to.y, t: 0 });
305 }
306
307 // One tile at a time is somebody playing, and it gets thrown. Several at
308 // once is a pile being rebuilt — a save picked up, an undo, a fresh deal —
309 // and those tiles were thrown long ago, so they are simply already there.
310 const rebuilding = fresh || added.length > 1;
311 for (const a of added) {
312 this.entries.set(a.key, rebuilding ? this.settle(geo, state, a) : this.launch(geo, state, a));
313 }
314
315 // A throw is good for exactly one discard, and the tile it belonged to has
316 // either just arrived or is never going to.
317 if (added.length || this.release) {
318 this.release = null;
319 this.held = null;
320 }
321
322 const ld = state.lastDiscard;
323 this.newestKey = ld ? `${ld.from}:${state.players[ld.from].discards.length - 1}` : null;
324 }
325
326 /** Run the physics on. Returns impacts worth a sound. */
327 advance(seconds: number): Impact[] {
328 this.carryOff(seconds);
329 return this.world ? advanceWorld(this.world, seconds) : [];
330 }
331
332 /** Tiles leaving the table, lifted and carried off to the seat taking them. */
333 private carryOff(seconds: number) {
334 if (this.leaving.length === 0) return;
335 for (const l of this.leaving) {
336 l.t = Math.min(1, l.t + seconds / TAKE_FLIGHT);
337 // Ease out, so it leaves quickly and arrives gently.
338 const k = 1 - (1 - l.t) * (1 - l.t);
339 l.body.x += (l.tx - l.body.x) * k * 0.5;
340 l.body.y += (l.ty - l.body.y) * k * 0.5;
341 // Up off the table on the way, the way a tile picked up would be.
342 l.body.z = Math.sin(l.t * Math.PI) * 40;
343 l.body.angle += seconds * 2.2;
344 }
345 this.leaving = this.leaving.filter((l) => l.t < 1);
346 }
347
348 /** What is on its way off, and how far gone, for the renderer to fade. */
349 get departing(): { body: Body; fade: number }[] {
350 return this.leaving.map((l) => ({ body: l.body, fade: 1 - l.t }));
351 }
352
353 get bodies(): Body[] {
354 return this.world?.bodies ?? [];
355 }
356
357 /** The tile on the table, if there is one — drawn lit, as a lifted tile is. */
358 get newest(): Body | null {
359 return (this.newestKey && this.entries.get(this.newestKey)) || null;
360 }
361
362 /**
363 * A tile is still on its way to the middle. The computer players hold off
364 * while this is true — nobody at a real table reaches across for a tile that
365 * has not landed, and a 碰 called over one still turning over in the air looks
366 * like it was snatched out of flight.
367 */
368 get throwInFlight(): boolean {
369 const b = this.newest;
370 return !!b && !b.resting;
371 }
372
373 /**
374 * Somebody is being told off for where they put that tile. Held for as long
375 * as the line takes to say, told to us by whoever is saying it.
376 */
377 heckle(seconds: number) {
378 this.quietAt = Math.max(this.quietAt, Date.now() + seconds * 1000);
379 }
380
381 /**
382 * Whether the table is mid-something and a computer player should wait: a
383 * tile still in the air, or a player still complaining about the last one.
384 * Reaching for a tile over the top of somebody objecting to it lands the
385 * objection on nobody.
386 */
387 get busy(): boolean {
388 return this.throwInFlight || Date.now() < this.quietAt;
389 }
390
391 /** Nothing is moving, so the render loop can stop until something changes. */
392 get settled(): boolean {
393 return !this.held && this.leaving.length === 0 && (!this.world || settled(this.world));
394 }
395
396 // ---- measuring ---------------------------------------------------------
397
398 /**
399 * Re-read the table when the wall's shape has changed or the window has. The
400 * pile keeps its positions across a re-measure: the wall shrinking does not
401 * move the tiles already on the felt.
402 */
403 private remeasure(state: GameState) {
404 const table = this.table;
405 if (!table) return;
406 const stamp = `${state.drawnFront}/${state.drawnBack}/${Math.round(
407 table.clientWidth,
408 )}x${Math.round(table.clientHeight)}`;
409 if (stamp === this.measuredAt) return;
410
411 const geo = measure(table, state);
412 this.measuredAt = geo ? stamp : '';
413 this.geo = geo;
414 if (!geo) {
415 this.world = null;
416 this.entries.clear();
417 this.setOpenness('----');
418 return;
419 }
420 // Bounded by the felt, not by the square: what keeps a tile in the middle is
421 // the stacks still standing, and once they are gone the pool is free to
422 // spread out through the gap the way a real one does.
423 if (!this.world) this.world = createWorld(geo.felt, geo.walls);
424 else reshape(this.world, geo.felt, geo.walls);
425 // Only here, never per frame: a hundred-odd ray casts is nothing once a
426 // draw, and a great deal every sixtieth of a second.
427 this.setOpenness(SEATS.map((s) => (canThrow(geo, s) ? 'y' : '-')).join(''));
428 }
429
430 private setOpenness(next: string) {
431 if (next === this.openness) return;
432 this.openness = next;
433 for (const cb of this.listeners) cb();
434 }
435
436 // ---- putting tiles in -------------------------------------------------
437
438 /** A tile that is simply there already — a rebuilt pile. */
439 private settle(
440 geo: TableGeometry,
441 state: GameState,
442 a: { seat: SeatId; index: number; tile: Tile },
443 ): Body {
444 const rng = this.seeded(state, a);
445 const { pool } = geo;
446 // Bunched towards the middle rather than spread evenly to the edges, which
447 // is what a pool thrown into from four sides actually looks like.
448 const spread = 0.3;
449 return addBody(this.world!, {
450 tile: a.tile,
451 seat: a.seat,
452 x: pool.x + pool.w * (0.5 + (rng() - 0.5) * 2 * spread),
453 y: pool.y + pool.h * (0.5 + (rng() - 0.5) * 2 * spread),
454 vx: 0,
455 vy: 0,
456 z: 0,
457 vz: 0,
458 angle: (rng() - 0.5) * Math.PI,
459 spin: 0,
460 w: geo.tile.w,
461 h: geo.tile.h,
462 atRest: true,
463 });
464 }
465
466 /** A tile arriving now: thrown if somebody threw it, placed over the wall if
467 * it was tapped, and flat and quick if a bot's wall happens to be open. */
468 private launch(
469 geo: TableGeometry,
470 state: GameState,
471 a: { seat: SeatId; index: number; tile: Tile },
472 ): Body {
473 const rng = this.seeded(state, a);
474 const thrown = this.release?.seat === a.seat ? this.release : null;
475
476 if (thrown) {
477 // Which of the two ways a tile goes in, decided by what is in its way.
478 //
479 // A clear line to the square means it can be *slid* — flat across the
480 // cloth, at exactly the speed it was let go at, which is what a flick
481 // wants to be. A standing wall means it has to be *thrown* instead: lifted
482 // over the top and dropped in, and then the flick's speed decides how far
483 // across the pool it lands rather than how fast it skates.
484 // Sliding is the preferred way in, and the question is asked from where
485 // the tile actually is — a player who carried it out over the square has a
486 // clear line even though the seat they came from does not. Only a tile
487 // with nothing but standing wall in front of it has to be lobbed.
488 const set = this.inPool(thrown.x, thrown.y);
489 const slide = set || !LOB_WHEN_WALLED || this.canThrowFrom(thrown.x, thrown.y);
490 let { vx, vy } = thrown;
491 let vz = 0;
492 const speed = Math.hypot(vx, vy);
493 let flipTurns = 0;
494 let flipOver = 0;
495
496 if (!slide) {
497 // Lofted over a standing wall, and it has to come *down* inside the
498 // square: a lob solved for where it would come to rest touches down
499 // short, on the wrong side of the wall, and stops dead against it.
500 //
501 // So the flick picks a landing spot along its own line, between just
502 // inside the near edge of the square and just short of the far one. A
503 // limp one drops in over the near wall, a hard one carries to the far
504 // side and barges through whatever is lying there, and neither of them
505 // can leave the tile outside.
506 const dir = speed > 0 ? { x: vx / speed, y: vy / speed } : { x: 0, y: -1 };
507 const span = spanThrough(geo.pool, thrown, dir);
508 const centre = centreOf(geo.pool);
509 let carry = speed * PLACE_FLIGHT;
510 if (span) {
511 const near = span.near + geo.tile.h;
512 carry = Math.min(Math.max(near, carry), Math.max(near, span.far - geo.tile.h));
513 } else {
514 // Flicked somewhere that is not the square at all — put it in anyway.
515 carry = Math.hypot(centre.x - thrown.x, centre.y - thrown.y);
516 dir.x = (centre.x - thrown.x) / (carry || 1);
517 dir.y = (centre.y - thrown.y) / (carry || 1);
518 }
519 vx = (dir.x * carry) / PLACE_FLIGHT;
520 vy = (dir.y * carry) / PLACE_FLIGHT;
521 vz = liftFor(PLACE_FLIGHT);
522 // Long enough in the air to turn over properly, and harder means more.
523 flipOver = PLACE_FLIGHT;
524 flipTurns = speed > 1300 ? 2 : 1;
525 } else if (!set) {
526 // A skated tile leaves the fingers off the cloth, and turns over on its
527 // way down — harder means longer in the air and more turns in it.
528 const hop = THROW_LIFT + Math.min(0.22, (speed / MAX_THROW_SPEED) * 0.28);
529 vz = liftFor(hop);
530 flipOver = hop;
531 flipTurns = speed > 2200 ? 2 : speed > 600 ? 1 : 0;
532 }
533 if (!TUMBLE) flipTurns = 0;
534
535 return addBody(this.world!, {
536 tile: a.tile,
537 seat: a.seat,
538 x: thrown.x,
539 y: thrown.y,
540 vx,
541 vy,
542 z: 0,
543 vz,
544 angle: thrown.angle,
545 spin: thrown.spin,
546 flipTurns,
547 flipOver,
548 // It tumbles across its line of travel, the way a thrown tile does.
549 flipAxis: Math.atan2(vy, vx),
550 w: geo.tile.w,
551 h: geo.tile.h,
552 // It was drawn at hand size a moment ago; it shrinks on the way down.
553 scale: thrown.w / geo.tile.w,
554 });
555 }
556
557 // Off the end of the hand, not the middle of it — a tile is thrown from the
558 // hand holding it, which is the one at the right-hand end of the row.
559 const from = geo.throwFrom[a.seat] ?? geo.launch[a.seat] ?? centreOf(geo.pool);
560 const open = !LOB_WHEN_WALLED || this.canThrow(a.seat);
561 const target = this.aimFor(geo, a.seat, rng);
562 const flight = open ? 0.34 + rng() * 0.1 : PLACE_FLIGHT;
563 // A slide is aimed at where it comes to *rest*, since it keeps going after
564 // it lands and SLIDE_TIME is roughly how much further. A lob is aimed at
565 // where it touches *down*, because it has to come down on the inside of the
566 // wall — solving for the resting place lands it short, against the outside.
567 const reach = open ? flight + SLIDE_TIME : flight;
568
569 const vx = (target.x - from.x) / reach;
570 const vy = (target.y - from.y) / reach;
571 return addBody(this.world!, {
572 tile: a.tile,
573 seat: a.seat,
574 x: from.x,
575 y: from.y,
576 vx,
577 vy,
578 z: 0,
579 vz: liftFor(flight),
580 angle: (rng() - 0.5) * Math.PI,
581 spin: (rng() - 0.5) * (open ? 7 : 2.5),
582 // It turns over on its way in, whichever way it is going.
583 flipTurns: TUMBLE ? 1 : 0,
584 flipOver: flight,
585 flipAxis: Math.atan2(vy, vx),
586 w: geo.tile.w,
587 h: geo.tile.h,
588 });
589 }
590
591 /** Where a tile from this seat is headed, with a little scatter. */
592 private aimFor(geo: TableGeometry, seat: SeatId, rng: () => number): Point {
593 const base = aimAt(geo, seat) ?? centreOf(geo.pool);
594 const jitter = Math.min(geo.pool.w, geo.pool.h) * 0.22;
595 return { x: base.x + (rng() - 0.5) * jitter, y: base.y + (rng() - 0.5) * jitter };
596 }
597
598 /**
599 * A tile's own random stream. Keyed on the hand and its place in that seat's
600 * discards, so the same tile scatters the same way every time it is rebuilt —
601 * a refresh mid-hand puts the pile back exactly as it was.
602 */
603 private seeded(state: GameState, a: { seat: SeatId; index: number; tile: Tile }) {
604 return makeRng(state.handNumber * 7919 + a.seat * 977 + a.index * 31 + a.tile + 1);
605 }
606}