anvilsign in

collin/mahjong

1import { useEffect, useRef, useState } from 'react';
2import type { TableCtl } from '../game/ctl';
3import { labelOf, WIND_EN, WIND_NAMES } from '../game/tiles';
4import type { SeatId } from '../game/types';
5import type { TablePool } from '../table/pool';
6import { Bi, BiEm, CLAIM_LABEL } from './Bi';
7import { showingColliders } from './colliders';
8import { useT } from './lang';
9import { Hand } from './Hand';
10import { SEAT_ROT, SEAT_SLOT } from './rotation';
11import { TileView } from './TileView';
12
13/**
14 * A seat that exists somewhere else — a phone at the party table, or an online
15 * player. What of it shows on this screen is decided here.
16 */
17export interface RemoteSeat {
18 /** Who holds it from their own device, or null while nobody does. */
19 holder?: string | null;
20 /** Party screen: holding the 📱 tag re-shows the table's shared join QR,
21 * for the player who lost theirs. The QR itself lives in the table's
22 * corner — see App — because the strip clips its own contents. */
23 onPeek?: (show: boolean) => void;
24 /** Online host: the seat's player is gone; offer it to the computer. */
25 onHandToBot?: () => void;
26}
27
28interface Props {
29 game: TableCtl;
30 seat: SeatId;
31 /**
32 * Which edge of this screen the seat is drawn at. At a shared table that is
33 * the seat itself; online the table is turned so your own seat is at the
34 * bottom, wherever you are actually sitting.
35 */
36 pos?: SeatId;
37 /**
38 * Whether this device may act for the seat. The hotseat table says yes to
39 * everyone, the online table only to your own chair — everything private
40 * (the tiles' faces, the 聽 and 過水 badges, the buttons) keys off this.
41 */
42 local?: boolean;
43 remote?: RemoteSeat;
44 /** Phone-sized table: nothing is rotated and only the bottom gets a full strip. */
45 compact?: boolean;
46 /** The tiles in the middle. Absent on a phone, which has no middle. */
47 pool?: TablePool;
48 onHelp: () => void;
49}
50
51export function Seat({ game, seat, pos = seat, local = true, remote, compact, pool, onHelp }: Props) {
52 const t = useT();
53 const s = game.state;
54 const p = s.players[seat];
55 const [sel, setSel] = useState<number | null>(null);
56 const bot = s.bots[seat];
57 // Somebody this device answers for: a person here, not the computer, not a
58 // hand that lives on another screen.
59 const acts = local && !bot;
60 // A hand this device may not read goes face down and its 聽 / 過水 badges
61 // stay off, since both would give it away. At the end of a hand everyone
62 // turns their tiles over, as they would.
63 const concealed = !acts && s.phase !== 'handEnd' && s.phase !== 'gameEnd';
64 const myTurn = s.phase === 'turn' && s.turn === seat && acts;
65 const opts = acts ? s.options[seat] : undefined;
66 const responded = s.responses[seat] !== undefined;
67 const claiming = (s.phase === 'claims' || s.phase === 'robkong') && !!opts && !responded;
68 // Whoever draws next closes the claim window — nobody has to wait on a
69 // player who hasn't noticed their buttons.
70 const canProceed = game.nextDrawer() === seat && acts;
71
72 useEffect(() => {
73 setSel(null);
74 }, [myTurn, s.handNumber, p.hand.length, s.drawnTile]);
75
76 const seatWind = (seat - s.dealer + 4) % 4;
77 const isDealer = seat === s.dealer;
78 const live = s.phase !== 'handEnd' && s.phase !== 'lobby';
79 const tenpai = live && acts ? game.tenpai(seat) : [];
80 const sacred = live && acts ? game.sacredTiles(seat) : [];
81 const concealedKongs = myTurn ? game.concealedKongs(seat) : [];
82 const addedKongs = myTurn ? game.addedKongs(seat) : [];
83 const canHu = myTurn && game.canSelfDrawWin(seat);
84 const delta = s.phase === 'handEnd' ? s.result?.deltas[seat] ?? 0 : 0;
85 // 一炮多響 can put more than one seat here, so this is a `some`, not a find.
86 const won = s.phase === 'handEnd' && !!s.result?.winners.some((w) => w.seat === seat);
87 // A deserted online seat, waiting for its person to come back — or for the
88 // host to hand it to the computer so the table can move.
89 const deserted = !!remote?.onHandToBot && !bot && remote.holder == null && live;
90
91 // Compact lays the discards out as one line that scrolls rather than a block
92 // that wraps, so the newest tile — the only one anybody is looking for — has
93 // to be kept in view. Harmless at full size, where nothing overflows.
94 const discardsRef = useRef<HTMLDivElement>(null);
95 useEffect(() => {
96 const el = discardsRef.current;
97 if (!el) return;
98 el.scrollLeft = el.scrollWidth;
99 el.scrollTop = el.scrollHeight;
100 }, [p.discards.length]);
101
102 const doDiscard = (i: number) => {
103 // Tapping plays the tile for real, which would end the sandbox's turn and
104 // set the computer going. Throwing is the thing being tested; tapping just
105 // puts the tile down again.
106 if (showingColliders()) return setSel(null);
107 game.discard(seat, p.hand[i]);
108 setSel(null);
109 };
110
111 // The tile just drawn is held apart at the end of the hand until it is played
112 // or the player slides it in, so it stays obvious which tile just arrived.
113 const drawnIndex = myTurn && s.drawnSeparate && s.drawnTile !== null ? p.hand.length - 1 : null;
114 const selTile = sel === null ? null : p.hand[sel] ?? null;
115
116 // Picking a tile up and throwing it in. Only on your own turn, and only where
117 // there is a middle of the table to throw into — the phone layout has none, so
118 // there the row goes back to only ever being rearranged.
119 const carry =
120 pool && myTurn
121 ? {
122 onPickUp: (i: number, x: number, y: number, size: number) => {
123 pool.pickUp({
124 seat,
125 tile: p.hand[i],
126 index: i,
127 x,
128 y,
129 // Facing the way it did in the hand, so it does not snap round the
130 // instant it is lifted.
131 angle: (SEAT_ROT[pos] * Math.PI) / 180,
132 w: size,
133 h: size * 1.375,
134 });
135 pool.wake();
136 },
137 onMoveTo: (x: number, y: number) => {
138 pool.moveHeld(x, y);
139 pool.wake();
140 },
141 onThrow: (i: number, t: { x: number; y: number; vx: number; vy: number; spin: number }) => {
142 const tile = p.hand[i];
143 if (tile === undefined) return pool.cancelHeld();
144 // Where it left the fingers is where the throw starts from.
145 pool.moveHeld(t.x, t.y);
146 // With the colliders drawn the table is a sandbox: the throw is the
147 // real throw, but it is not a discard. The tile stays in the hand
148 // and the game does not move, so the same flick can be made again
149 // and again against the boxes on screen.
150 if (showingColliders()) {
151 pool.throwLoose(t.vx, t.vy, t.spin);
152 setSel(null);
153 return;
154 }
155 pool.throwHeld(t.vx, t.vy, t.spin);
156 game.discard(seat, tile);
157 setSel(null);
158 },
159 onCancel: () => {
160 pool.cancelHeld();
161 pool.wake();
162 },
163 }
164 : undefined;
165
166 return (
167 // `data-seat` is how table/geometry.ts finds this seat's hand to work out
168 // where it throws from — see measure(). It carries the seat itself, not the
169 // edge it is drawn at: the physics is about who threw the tile.
170 <div className={`slot ${SEAT_SLOT[pos]} ${pos === 0 ? 'mine' : 'opp'}`} data-seat={seat}>
171 <div
172 className={`seat ${myTurn ? 'active' : ''} ${claiming ? 'claiming' : ''}`}
173 style={compact ? undefined : { transform: `translate(-50%, -50%) rotate(${SEAT_ROT[pos]}deg)` }}
174 >
175 {/* Points down the strip at whoever won. It is inside the seat, so it
176 turns with it and lands on their edge of the table wherever they
177 are sitting — no working out which way is which. */}
178 {won && (
179 <div className="win-arrow" aria-hidden>
180 ▼
181 </div>
182 )}
183
184 {/* Only on a phone. At full size a discard is thrown into the middle
185 and stays there for the hand, so the row would be the same tiles
186 listed twice. */}
187 {compact && (
188 <div className="discards" ref={discardsRef}>
189 {p.discards.map((t, i) => (
190 <TileView
191 key={i}
192 tile={t}
193 size="small"
194 highlight={s.lastDiscard?.from === seat && i === p.discards.length - 1}
195 />
196 ))}
197 </div>
198 )}
199
200 <div className="melds">
201 {p.melds.map((m, i) => (
202 <div className="meld" key={i}>
203 {m.tiles.map((t, j) => (
204 <TileView key={j} tile={t} size="meld" faceDown={m.kind === 'ankong' && j > 0 && j < 3} />
205 ))}
206 </div>
207 ))}
208 {p.flowers.length > 0 && (
209 <div className="meld flowers">
210 {p.flowers.map((t, i) => (
211 <TileView key={i} tile={t} size="meld" />
212 ))}
213 </div>
214 )}
215 </div>
216
217 <div className="actionbar">
218 {claiming && (
219 <>
220 {opts!.map((o, i) => (
221 <button
222 key={i}
223 className={`btn claim ${o.type}`}
224 onClick={() => game.respond(seat, { type: o.type, with: o.with })}
225 >
226 <Bi
227 zh={CLAIM_LABEL[o.type][0]}
228 en={CLAIM_LABEL[o.type][1]}
229 sub={o.with && o.with.map(labelOf).join(' ')}
230 />
231 </button>
232 ))}
233 {/* The seat that draws next declines by picking up — see below. */}
234 {!canProceed && (
235 <button className="btn pass" onClick={() => game.respond(seat, 'pass')}>
236 <Bi zh="過" en="Pass" />
237 </button>
238 )}
239 </>
240 )}
241 {canProceed && (
242 <button
243 className={`btn proceed ${claiming ? 'pass' : ''}`}
244 onClick={() => game.resolveNow()}
245 >
246 <Bi
247 zh={s.phase === 'robkong' ? '繼續' : claiming ? '過.摸牌' : '摸牌'}
248 en={s.phase === 'robkong' ? 'Continue' : claiming ? 'Pass & draw' : 'Draw'}
249 />
250 </button>
251 )}
252 {!claiming && !canProceed && responded && s.phase !== 'turn' && (
253 <div className="waiting">{t('已回應', 'Responded')}</div>
254 )}
255 {deserted && (
256 <button className="btn ghost" onClick={remote!.onHandToBot}>
257 <Bi zh="電腦代打" en="Hand to computer" />
258 </button>
259 )}
260 {myTurn && (
261 <>
262 {canHu && (
263 <button className="btn claim hu" onClick={() => game.declareSelfDraw(seat)}>
264 <Bi zh="自摸" en="Self-draw" />
265 </button>
266 )}
267 {concealedKongs.map((t) => (
268 <button key={`ak${t}`} className="btn claim kong" onClick={() => game.declareConcealedKong(seat, t)}>
269 <Bi zh="暗槓" en="Concealed kong" sub={labelOf(t)} />
270 </button>
271 ))}
272 {addedKongs.map((t) => (
273 <button key={`gk${t}`} className="btn claim kong" onClick={() => game.declareAddedKong(seat, t)}>
274 <Bi zh="加槓" en="Added kong" sub={labelOf(t)} />
275 </button>
276 ))}
277 {selTile !== null && sel !== null && (
278 <button className="btn discard" onClick={() => doDiscard(sel)}>
279 <Bi zh="打出" en="Discard" sub={labelOf(selTile)} />
280 </button>
281 )}
282 </>
283 )}
284 {delta !== 0 && <div className={`delta ${delta > 0 ? 'up' : 'down'}`}>{delta > 0 ? `+${delta}` : delta}</div>}
285 </div>
286
287 <Hand
288 tiles={p.hand}
289 faceDown={concealed}
290 drawnIndex={drawnIndex}
291 selected={sel}
292 canDiscard={myTurn}
293 onSelect={setSel}
294 onDiscard={doDiscard}
295 onMove={(from, to) => game.reorderHand(seat, from, to)}
296 carry={carry}
297 />
298
299 <div className="nameplate">
300 <span className={`wind ${isDealer ? 'dealer' : ''}`}>
301 <BiEm zh={WIND_NAMES[seatWind]} en={WIND_EN[seatWind]} />
302 </span>
303 <span className="pname">{p.name}</span>
304 {remote?.holder != null && (
305 <span
306 className="tag phone"
307 title={`${t('這手牌在手機上', 'played from a phone', ' · ')}. ${t(
308 '按住看 QR',
309 'hold to show the QR again',
310 ' · ',
311 )}`}
312 onPointerDown={() => remote.onPeek?.(true)}
313 onPointerUp={() => remote.onPeek?.(false)}
314 onPointerCancel={() => remote.onPeek?.(false)}
315 onPointerLeave={() => remote.onPeek?.(false)}
316 >
317 📱 {remote.holder}
318 </span>
319 )}
320 {deserted && <span className="tag sacred">{t('已離線', 'offline')}</span>}
321 {isDealer && (
322 <span className="tag">
323 {t('莊', 'Dealer')}
324 {s.dealerStreak > 0 ? ` ${t(`連${s.dealerStreak}`, `×${s.dealerStreak + 1}`)}` : ''}
325 </span>
326 )}
327 {tenpai.length > 0 && (
328 <span className="tag ting">
329 {t('聽', 'Ready')} {tenpai.map(labelOf).join('·')}
330 </span>
331 )}
332 {/* Without this the 胡 button just quietly fails to appear. */}
333 {sacred.length > 0 && (
334 <span
335 className="tag sacred"
336 title={t(
337 '過水 — 放棄過這幾張的胡,到自己再摸牌前不能胡',
338 '過水 — passed on winning with these until your next draw',
339 )}
340 >
341 {t('過水', 'Sacred')} {sacred.map(labelOf).join('·')}
342 </span>
343 )}
344 <span className="chips">{p.score}</span>
345 {p.hand.length > 0 && s.phase !== 'handEnd' && acts && (
346 <button className="btn ghost sort" onClick={() => game.sortHand(seat)}>
347 {t('理牌', 'Sort')}
348 </button>
349 )}
350 <button className="helpbtn" onClick={onHelp} aria-label={t('規則', 'rules')}>
351 ?
352 </button>
353 </div>
354 </div>
355 </div>
356 );
357}