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