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