/** 마작 화면 (docs/games/mahjong.md §9). */ import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; import type { DiscardView, HandResultView, MahjongOptions, MahjongView, MeldView, MyView, SeatView, WaitView, WinnerView } from '@bg/games/mahjong'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { Tile, tileName, tileOrder, tileShort } from './Tile'; const WIND = ['동', '남', '서', '북']; const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽']; const LIMIT_KO: Record = { none: '', mangan: '만관', haneman: '하네만', baiman: '배만', sanbaiman: '삼배만', kazoe: '헤아림 역만', yakuman: '역만' }; const ABORT_KO: Record = { kyuushu: '구종구패', suufon: '사풍연타', suukan: '사깡유국', suucha: '사가리치', sanchaho: '삼가화' }; const CALL_KO: Record = { chi: '치!', pon: '퐁!', kan: '깡!', riichi: '리치!', kita: '북!', tsumo: '쯔모!', ron: '론!' }; const END_KO: Record = { normal: '마지막 국이 끝났어요', tobi: '0점 미만이 나와 끝났어요(토비)', agariYame: '올라스트 친이 1위로 끝냈어요(아가리야메)', westEntryEnd: '연장전에서 끝났어요' }; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const fmt = (n: number) => n.toLocaleString('ko-KR'); const signed = (n: number) => (n > 0 ? `+${fmt(n)}` : n < 0 ? `-${fmt(-n)}` : '0'); const roundLabel = (v: Pick) => `${WIND[v.roundWind]}${v.handNumber + 1}국${v.honba ? ` ${v.honba}본장` : ''}`; const sortCodes = (codes: string[]) => [...codes].sort((a, b) => tileOrder(a) - tileOrder(b)); /** 을/를 by the last syllable's final consonant ("5만을", "서를"). */ const eulReul = (word: string) => { const c = word.charCodeAt(word.length - 1); return c >= 0xac00 && c <= 0xd7a3 && (c - 0xac00) % 28 === 0 ? `${word}를` : `${word}을`; }; const waitText = (ws: WaitView[]) => ws.map((w) => `${tileShort(w.kind)}(${w.left}장${w.yaku ? '' : ', 역 없음'})`).join(', '); // ---------------------------------------------------------------- sounds (synthesized: bone/plastic tiles on felt) const mjSound = { /** One tile knocking another / the table. */ clack: (delay = 0, g = 1) => { noise(26, 0.15 * g, delay, 'highpass', 3200); tone(2100, 24, 'triangle', 0.06 * g, delay); tone(720, 42, 'sine', 0.08 * g, delay); }, /** 타패: the tile lands in the river. */ discard: () => { mjSound.clack(0, 1.15); noise(55, 0.07, 14, 'lowpass', 900); }, /** 쯔모: a tile slid off the wall into the hand. */ draw: () => { noise(60, 0.06, 0, 'bandpass', 1800, 0.7); mjSound.clack(55, 0.55); }, /** Picking a tile up in my hand. */ lift: () => tone(1700, 22, 'triangle', 0.05), /** 새 국: the wall washed and built (자라자라). */ shuffle: () => { for (let i = 0; i < 16; i++) mjSound.clack(i * 42 + (i % 3) * 9, 0.35 + (i % 4) * 0.08); noise(520, 0.05, 0, 'lowpass', 700); }, pon: () => { mjSound.clack(0); mjSound.clack(70); tone(560, 150, 'triangle', 0.13, 110, { slideTo: 400 }); }, chi: () => { [0, 50, 100].forEach((d) => mjSound.clack(d, 0.8)); tone(784, 80, 'triangle', 0.1, 150); tone(1046, 110, 'triangle', 0.09, 210); }, kan: () => { [0, 60, 120, 180].forEach((d) => mjSound.clack(d)); tone(196, 280, 'sawtooth', 0.035, 220); tone(392, 240, 'triangle', 0.09, 220); }, kita: () => { mjSound.clack(0, 0.9); tone(660, 90, 'triangle', 0.09, 60); }, /** 리치: the 1,000-point stick put down, then a rising chime. */ riichi: () => { tone(1600, 26, 'square', 0.035); noise(32, 0.12, 0, 'highpass', 3600); tone(1046, 120, 'triangle', 0.1, 110); tone(1568, 220, 'triangle', 0.09, 210); }, tsumo: () => { mjSound.clack(0, 1.3); [784, 988, 1175, 1568].forEach((f, i) => tone(f, 170, 'triangle', 0.12, 90 + i * 85)); }, ron: () => { mjSound.clack(0, 1.4); noise(140, 0.08, 0, 'lowpass', 500); [1046, 1318, 1568].forEach((f) => tone(f, 260, 'square', 0.035, 90)); tone(2093, 380, 'triangle', 0.09, 220); }, /** Points moving after a win. */ payout: (delay = 0) => { for (let i = 0; i < 6; i++) tone(2200 + i * 130, 50, 'triangle', 0.045, delay + i * 45); }, /** 유국. */ ryuukyoku: () => [523, 440, 349].forEach((f, i) => tone(f, 200, 'sine', 0.11, i * 150)), /** A dora indicator turned over. */ flip: (delay = 0) => { noise(60, 0.11, delay, 'highpass', 2500); tone(1400, 40, 'triangle', 0.05, delay + 10); }, /** A call / ron window opened for me. */ prompt: (ron: boolean) => { if (ron) [1318, 1760, 1318, 1760].forEach((f, i) => tone(f, 80, 'triangle', 0.1, i * 85)); else { tone(988, 70, 'triangle', 0.1); tone(1318, 100, 'triangle', 0.09, 75); } }, }; const CALL_SOUND: Record void> = { pon: mjSound.pon, chi: mjSound.chi, kan: mjSound.kan, kita: mjSound.kita, riichi: mjSound.riichi, tsumo: mjSound.tsumo, ron: mjSound.ron }; /** One id for a hand from its deal through its result screen (handsPlayed goes up when the hand ends). */ const handId = (v: MahjongView) => (v.phase === 'playing' ? v.handsPlayed : v.handsPlayed - 1); /** What was already on the table when this screen opened, so only things added later animate (not a reconnect's whole table). */ interface Seen { hand: number; disc: number[]; melds: number[]; kita: number[]; riichi: boolean[]; dora: number; } function useSeen(v: MahjongView): Seen | null { const [s] = useState(() => ({ hand: handId(v), disc: v.seats.map((x) => x.discards.length), melds: v.seats.map((x) => x.melds.length), kita: v.seats.map((x) => x.kita.length), riichi: v.seats.map((x) => x.riichi), dora: v.doraIndicators.length, })); // A later hand: everything in it is new. return s.hand === handId(v) ? s : null; } /** A number that pops when it changes (not on the first render). */ function Bump({ value, children }: { value: number; children?: ReactNode }) { const prev = useRef(value); const moved = useRef(false); if (prev.current !== value) { prev.current = value; moved.current = true; } return ( {children ?? fmt(value)} ); } const CSS = ` .game-main:has(> .mj) { justify-content: flex-start; } .mj { position: relative; width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 8px; align-self: center; } .mj.wide { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-areas: 'table side' 'me me'; align-items: start; gap: 8px 12px; } .mj.wide .mj-opps { grid-area: side; flex-direction: column; flex-wrap: nowrap; } .mj.wide .mj-seat { max-width: none; flex: none; } .mj.wide .mj-main { grid-area: table; } .mj.wide .mj-me { grid-area: me; } .mj-main { display: flex; flex-direction: column; gap: 8px; min-width: 0; } .mj-main > .mj-panel { overflow: auto; } .mj-opps { display: flex; gap: 8px; padding: 0; margin: 0; list-style: none; flex-wrap: wrap; justify-content: center; } .mj-seat { flex: 1 1 0; min-width: 0; max-width: 340px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px; border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 4px; font-size: .88rem; } .mj-seat.turn { border-color: var(--focus); } .mj-seat.gone { opacity: .6; } .mj-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } .mj-seat .pos { color: var(--text-sub); font-size: .78rem; white-space: nowrap; } .mj-badge { display: inline-block; border-radius: 999px; padding: 0 7px; font-weight: 800; font-size: .75rem; line-height: 1.6; white-space: nowrap; } .mj-b-dealer { background: #b91c1c; color: #fff; } .mj-b-riichi { background: #fde68a; color: #7c2d12; border: 1px solid #b45309; } .mj-b-away { background: var(--warning); color: #fff; } .mj-b-furiten { background: var(--danger); color: #fff; } .mj-b-wind { background: var(--surface-2); color: var(--text); border: 1px solid var(--border); } .mj-melds { display: flex; flex-wrap: wrap; gap: 6px; align-items: flex-end; } .mj-meld { display: inline-flex; align-items: flex-end; gap: 1px; } .mj-back-count { display: inline-flex; align-items: center; gap: 4px; font-weight: 800; font-variant-numeric: tabular-nums; } .mj-tile.dim { opacity: .38; } .mj-table-wrap { width: 100%; display: flex; justify-content: center; } .mj-table { position: relative; display: grid; border-radius: 22px; background: radial-gradient(ellipse at center, rgba(255,255,255,.10), rgba(255,255,255,0) 65%), var(--felt); border: 7px solid var(--wood); box-shadow: var(--shadow); padding: 6px; box-sizing: content-box; } .mj-cell { position: relative; } .mj-pond { position: absolute; left: 50%; top: 50%; display: flex; flex-direction: column; gap: 1px; align-items: flex-start; } .mj-pond-row { display: flex; gap: 1px; align-items: flex-end; } .mj-pond .last { outline: 3px solid #fde047; outline-offset: 0; border-radius: 3px; } .mj-pond.turn { filter: drop-shadow(0 0 5px rgba(253,224,71,.9)); } .mj-center { position: relative; background: rgba(0,0,0,.28); border-radius: 12px; color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; text-align: center; text-shadow: 0 1px 2px rgba(0,0,0,.5); } .mj-center .rl { font-weight: 900; font-size: max(13px, calc(var(--tw) * .62)); line-height: 1.1; } .mj-center .sub { font-size: max(10px, calc(var(--tw) * .4)); font-weight: 700; line-height: 1.25; } .mj-dora { display: flex; gap: 1px; justify-content: center; } .mj-edge { position: absolute; display: flex; align-items: center; gap: 3px; font-size: max(10px, calc(var(--tw) * .4)); font-weight: 800; white-space: nowrap; background: rgba(0,0,0,.35); border-radius: 999px; padding: 0 6px; line-height: 1.5; } .mj-edge.turn { background: #fde047; color: #1c1e21; text-shadow: none; } .mj-edge .stick { display: inline-block; inline-size: calc(var(--tw) * .9); block-size: 5px; background: #fff; border-radius: 3px; position: relative; } .mj-edge .stick::after { content: ''; position: absolute; left: 50%; top: 50%; width: 4px; height: 4px; margin: -2px; border-radius: 50%; background: #dc2626; } .mj-edge.b { bottom: 3px; left: 50%; transform: translateX(-50%); } .mj-edge.t { top: 3px; left: 50%; transform: translateX(-50%) rotate(180deg); } .mj-edge.r { right: 3px; top: 50%; transform: translateY(-50%) rotate(180deg); writing-mode: vertical-rl; text-orientation: sideways; padding: 6px 0; } .mj-edge.l { left: 3px; top: 50%; transform: translateY(-50%); writing-mode: vertical-rl; text-orientation: sideways; padding: 6px 0; } .mj-callout { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 5; background: #b91c1c; color: #fff; font-weight: 900; font-size: 2rem; padding: 4px 18px; border-radius: 14px; box-shadow: 0 6px 18px rgba(0,0,0,.35); pointer-events: none; animation: mj-call 1.3s ease both; white-space: nowrap; } .mj-callout.c-riichi { background: #f59e0b; color: #1c1e21; text-shadow: none; } .mj-callout.c-chi { background: #15803d; } .mj-callout.c-kan { background: #6d28d9; } .mj-callout.c-kita { background: #1d4ed8; } /* 론·쯔모·유국: over the whole board (the table is hidden on the PC result screen). */ .mj-banner { position: absolute; left: 0; right: 0; top: 18%; z-index: 20; display: flex; justify-content: center; pointer-events: none; } .mj-banner > span { display: flex; flex-direction: column; align-items: center; gap: 2px; font-size: 3.2rem; font-weight: 900; line-height: 1.1; color: #fff; background: #b91c1c; padding: 8px 34px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,.4); text-shadow: 0 2px 4px rgba(0,0,0,.35); white-space: nowrap; border: 3px solid #fde047; } .mj-banner.tsumo > span { background: linear-gradient(160deg, #f59e0b, #b45309); } .mj-banner.draw > span { background: #334155; border-color: #94a3b8; font-size: 2.2rem; } .mj-banner.final > span { background: linear-gradient(160deg, #15803d, #14532d); font-size: 2.4rem; } .mj-banner small { font-size: 1rem; font-weight: 800; } /* 타패: the newest tile lands in the river from its owner's side (ponds are rotated, so +Y is always toward the owner). */ .mj-toss { animation: mj-toss .34s cubic-bezier(.25,.8,.35,1.25) both; } @keyframes mj-toss { 0% { transform: translateY(calc(var(--tw) * 1.3)) scale(1.3); opacity: 0; } 55% { opacity: 1; } 100% { transform: none; } } .mj-drawn { animation: mj-draw .3s ease-out both; animation-delay: var(--anim-delay, 0ms); } @keyframes mj-draw { from { transform: translateY(-24px) rotate(6deg); opacity: 0; } } .mj-edge .stick.new { animation: mj-stick .45s cubic-bezier(.3,1.5,.5,1) both; } @keyframes mj-stick { from { transform: translateY(-14px) scale(1.7); opacity: 0; } } .mj-panel { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .mj-panel.claim { border: 3px solid var(--primary); box-shadow: 0 6px 20px rgba(0,0,0,.25); } .mj-panel.win { border: 3px solid var(--success); } .mj-myhead { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: space-between; } .mj-hand { display: flex; align-items: flex-end; gap: 1px; padding-top: 12px; min-height: 64px; } .mj-hand .gap { width: 10px; flex: none; } .mj-htile { position: relative; padding: 0; border: 0; background: none; cursor: pointer; border-radius: 6px; transition: transform .12s ease; flex: none; } .mj-htile[aria-pressed='true'] { transform: translateY(-10px); box-shadow: 0 0 0 3px var(--primary); } .mj-htile[data-legal='false'] { cursor: not-allowed; } .mj-htile[data-legal='false'] .mj-tile { opacity: .45; filter: grayscale(.5); } .mj-htile:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; z-index: 2; } .mj-htile .mark { position: absolute; top: -12px; left: 50%; transform: translateX(-50%); font-size: .68rem; font-weight: 900; background: var(--success); color: #fff; border-radius: 999px; padding: 0 4px; line-height: 1.4; white-space: nowrap; } .mj-htile .lock { position: absolute; bottom: 2px; right: 1px; font-size: .7rem; } .mj-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .mj-actions .btn { flex: 1 1 auto; min-height: 52px; } .mj-big { font-size: 1.25rem !important; font-weight: 900 !important; min-height: 60px !important; } .mj-win-btn { background: #dc2626 !important; color: #fff !important; border-color: #dc2626 !important; animation: mj-pulse 1s ease-in-out infinite; } .mj-choice { display: inline-flex; align-items: center; gap: 2px; } .mj-hint { margin: 0; font-size: .9rem; } .mj-hint.warn { color: var(--danger); font-weight: 700; } .mj-preview { display: flex; align-items: center; gap: 8px; } .mj-res-hand { display: flex; flex-wrap: wrap; gap: 1px; align-items: flex-end; } .mj-res-hand .win { margin-left: 8px; box-shadow: 0 0 0 3px var(--success); border-radius: 4px; } .mj-yaku { margin: 0; padding: 0; list-style: none; display: grid; grid-template-columns: 1fr auto; gap: 2px 16px; max-width: 360px; } .mj-yaku li { display: contents; } .mj-total { font-size: 1.15rem; font-weight: 900; } .mj-deltas { width: 100%; border-collapse: collapse; } .mj-deltas td, .mj-deltas th { padding: 3px 6px; text-align: left; border-bottom: 1px solid var(--border); } .mj-deltas .num { text-align: right; font-variant-numeric: tabular-nums; } .mj-plus { color: var(--success); font-weight: 800; } .mj-minus { color: var(--danger); font-weight: 800; } .mj-toggles { display: flex; flex-direction: column; gap: 6px; } .mj-toggles label { display: flex; gap: 8px; align-items: center; cursor: pointer; min-height: 32px; } .mj-toggles input { width: 22px; height: 22px; } .mj-hist { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; max-height: 220px; overflow: auto; font-size: .85rem; } .mj-rules td, .mj-rules th { padding: 3px 6px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: top; } @keyframes mj-call { 0% { transform: translate(-50%, -50%) scale(.4); opacity: 0; } 14% { transform: translate(-50%, -50%) scale(1.15); opacity: 1; } 24% { transform: translate(-50%, -50%) scale(1); } 80% { opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1.04); opacity: 0; } } @keyframes mj-pulse { 0%,100% { transform: scale(1); } 50% { transform: scale(1.04); } } @media (prefers-reduced-motion: reduce) { /* Banners stay readable (shown still, removed by their timer) instead of fading out at once. */ .mj-callout, .mj-win-btn, .mj-banner .anim-banner { animation: none; } .mj-htile { transition: none; } } @media (max-width: 719px) { .mj { gap: 6px; } .mj-seat { padding: 4px 6px; font-size: .8rem; flex-basis: 30%; } .mj-table { border-width: 5px; padding: 4px; border-radius: 16px; } .mj-callout { font-size: 1.5rem; } .mj-banner > span { font-size: 2.3rem; padding: 6px 22px; } .mj-banner.draw > span, .mj-banner.final > span { font-size: 1.7rem; } .mj-actions .btn { min-height: 48px; } } `; // ---------------------------------------------------------------- helpers /** Board width and the height of the game column it lives in (fixed on PC, content-sized on phones). */ function useBox(): [React.RefObject, number, number] { const ref = useRef(null); const [box, setBox] = useState<[number, number]>([0, 0]); useLayoutEffect(() => { const el = ref.current; if (!el) return; const parent = el.parentElement; const read = () => setBox([el.clientWidth, parent && window.innerWidth >= 1100 ? parent.clientHeight : 0]); read(); const ro = new ResizeObserver(read); ro.observe(el); if (parent) ro.observe(parent); return () => ro.disconnect(); }, []); return [ref, box[0], box[1]]; } function useWidth(): [React.RefObject, number] { const ref = useRef(null); const [w, setW] = useState(0); useLayoutEffect(() => { const el = ref.current; if (!el) return; setW(el.clientWidth); const ro = new ResizeObserver(() => setW(el.clientWidth)); ro.observe(el); return () => ro.disconnect(); }, []); return [ref, w]; } /** Relative position of a seat on my screen: 0 me (bottom), 1 right (next), 2 across, 3 left. 3인은 0·1·3. */ function relPos(v: MahjongView, seat: number): number { const mine = v.my?.seat ?? 0; const r = (seat - mine + v.n) % v.n; return v.n === 3 && r === 2 ? 3 : r; } function meldLabel(m: MeldView): string { const name = m.type === 'chi' ? '치' : m.type === 'pon' ? '퐁' : m.type === 'ankan' ? '안깡' : m.type === 'kakan' ? '가깡' : '대명깡'; return `${name} ${m.tiles.map(tileShort).join(' ')}`; } function Meld({ m, w, fresh }: { m: MeldView; w: number; fresh?: boolean }) { return ( {m.tiles.map((t, i) => { const hidden = m.type === 'ankan' && (i === 0 || i === 3); const side = m.called !== null && t === m.called && m.type !== 'ankan'; return ; })} ); } /** `seen`: how many melds / 북 were already there when the screen opened (later ones pop in). */ function Melds({ s, w, seen }: { s: Pick; w: number; seen?: [number, number] }) { if (s.melds.length === 0 && s.kita.length === 0) return null; const [m0, k0] = seen ?? [Infinity, Infinity]; return (
{s.melds.map((m, i) => ( = m0} /> ))} {s.kita.length > 0 && ( {s.kita.map((t, i) => ( = k0 ? 'anim-pop' : undefined} /> ))} )}
); } // ---------------------------------------------------------------- seats const meldSeen = (seen: Seen | null, seat: number): [number, number] => (seen ? [seen.melds[seat] ?? 0, seen.kita[seat] ?? 0] : [0, 0]); function seatLabel(v: MahjongView, s: SeatView, players: Record, me: string | null): string { const parts = [`${POS_KO[relPos(v, s.seat)]}`, `${nick(players, s.id)}${s.id === me ? '(나)' : ''}`, `${WIND[s.wind]}${s.isDealer ? '(친)' : ''}`, `${fmt(s.points)}점`]; if (s.riichi) parts.push('리치'); if (s.id !== me && v.phase === 'playing') parts.push(`손패 ${s.handCount}장`); if (s.melds.length) parts.push(`울기: ${s.melds.map(meldLabel).join(', ')}`); if (s.kita.length) parts.push(`북 ${s.kita.length}장`); if (s.left) parts.push('나감'); else if (s.away) parts.push('자리 비움'); if (v.turn === s.seat && v.stage !== 'claim') parts.push('차례'); return parts.join(', '); } function SeatChip({ v, s, players, me, deadline, w, seen }: { v: MahjongView; s: SeatView; players: Record; me: string | null; deadline: number | null; w: number; seen: Seen | null }) { const u = userOf(players, s.id); const turn = v.phase === 'playing' && v.turn === s.seat && v.stage !== 'claim'; return (
  • {u.nickname} {POS_KO[relPos(v, s.seat)]} {turn && }
    {WIND[s.wind]} {s.isDealer ? ' 친' : ''} {s.riichi && 리치} {(s.away || s.left) && {s.left ? '나감' : '자리 비움'}} {v.phase === 'playing' && ( {s.handCount} )}
  • ); } // ---------------------------------------------------------------- table /** `fromIndex`: tiles from here on were discarded while watching and land with a toss. */ function Pond({ discards, tw, lastIndex, fromIndex }: { discards: DiscardView[]; tw: number; lastIndex: number | null; fromIndex: number }) { const rows: DiscardView[][] = []; for (let i = 0; i < discards.length; i += 6) rows.push(discards.slice(i, i + 6)); return ( <> {rows.map((row, ri) => (
    {row.map((d, ci) => { const idx = ri * 6 + ci; return ( = fromIndex ? 'mj-toss' : ''].filter(Boolean).join(' ') || undefined} label={`${tileName(d.tile)}${d.tsumogiri ? ', 쯔모기리' : ''}${d.riichi ? ', 리치 선언' : ''}${d.called ? ', 울려 감' : ''}`} /> ); })}
    ))} ); } const ROT = [0, -90, 180, 90]; function Table({ v, players, width, callout, seen }: { v: MahjongView; players: Record; width: number; callout: ReactNode; seen: Seen | null }) { // Pond: 6 tiles per row (+ room for one sideways riichi tile) × 4 rows. Table = H + W + H. // Total width ≈ 2H + W + padding/border = 17·tw + 37. const tw = Math.max(14, Math.min(30, Math.floor((width - 37) / 17))); const th = Math.round((tw * 4) / 3); const W = 5 * (tw + 1) + th + 2; const H = 4 * (th + 1) + 2; const bySeat = (pos: number) => v.seats.find((s) => relPos(v, s.seat) === pos); const cell = (pos: number) => { const s = bySeat(pos); const vertical = pos === 1 || pos === 3; const style: CSSProperties = { width: vertical ? H : W, height: vertical ? W : H }; if (!s) return
    ; const lastIndex = v.lastDiscard && v.lastDiscard.seat === s.seat ? v.lastDiscard.index : null; const turn = v.phase === 'playing' && v.turn === s.seat && v.stage !== 'claim'; return (
    ); }; const edge = (pos: number) => { const s = bySeat(pos); if (!s) return null; const turn = v.phase === 'playing' && v.turn === s.seat && v.stage !== 'claim'; return ( {WIND[s.wind]} {s.riichi && } ); }; const dw = Math.max(12, Math.round(tw * 0.8)); return (
    {cell(2)}
    {cell(3)}
    {roundLabel(v).split(' ')[0]} {v.honba}본장 · 공탁 개 남은 패 {v.wallCount}
    {v.doraIndicators.map((t, i) => ( = (seen?.dora ?? 0) ? 'anim-flip' : undefined} style={{ '--anim-delay': '120ms' } as CSSProperties} /> ))} {Array.from({ length: Math.max(0, 5 - v.doraIndicators.length) }, (_, i) => ( ))}
    {[0, 1, 2, 3].map(edge)} {callout}
    {cell(1)}
    {cell(0)}
    ); } // ---------------------------------------------------------------- my hand function MyArea({ v, my, act, pending, players, deadline, tapConfirm, seen, dealing, }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record; deadline: number | null; tapConfirm: boolean; seen: Seen | null; /** A new hand was just dealt: the hand tiles fly in one by one. */ dealing: boolean; }) { const [sel, setSel] = useState(null); const [riichiMode, setRiichiMode] = useState(false); const [kanPick, setKanPick] = useState(false); const [note, setNote] = useState(''); const [ref, width] = useWidth(); const turnKey = `${v.seq}-${v.stage}-${v.turn}`; useEffect(() => { setSel(null); setKanPick(false); setNote(''); }, [turnKey]); useEffect(() => { if (my.riichiDiscards.length === 0) setRiichiMode(false); }, [my.riichiDiscards.length]); const me = v.seats[my.seat]!; const hand = sortCodes(my.hand); const all = my.drawn ? [...hand, my.drawn] : hand; const n = all.length; const myTurn = my.canDiscard; const legal = new Set(riichiMode ? my.riichiDiscards : my.discardable); const locked = new Set(my.locked); const beginner = my.prefs.beginner && v.options.beginnerMode; const phone = width > 0 && width < 600; const meldW = phone ? 18 : 26; const tw = width > 0 ? Math.max(20, Math.min(phone ? 40 : 48, Math.floor((width - 14 - n) / n))) : 40; const send = (code: string) => { if (pending) return; act({ type: 'discard', tile: code, ...(riichiMode ? { riichi: true } : {}) }); setSel(null); setRiichiMode(false); }; const tap = (code: string) => { if (!myTurn || pending) return; if (!legal.has(code)) { sounds.warn(); setNote(locked.has(code) ? `${tileShort(code)}: 방금 울은 패와 같은 패(또는 스지)라 버릴 수 없어요.` : riichiMode ? '이 패를 버리면 텐파이가 아니라 리치할 수 없어요.' : my.riichi ? '리치 후에는 쯔모한 패만 버릴 수 있어요.' : '지금은 버릴 수 없어요.'); return; } setNote(''); if (sel === code || !tapConfirm) send(code); else { mjSound.lift(); setSel(code); } }; const onKey = (e: KeyboardEvent) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; const btns = Array.from(e.currentTarget.querySelectorAll('button.mj-htile')); const i = btns.indexOf(document.activeElement as HTMLButtonElement); if (i < 0) return; e.preventDefault(); btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus(); }; const kanOpts = [...my.ankan.map((t) => ({ type: 'ankan', tile: t })), ...my.kakan.map((t) => ({ type: 'kakan', tile: t }))]; const selAfter = sel ? my.tenpaiAfter[sel] : undefined; const winNow = my.canTsumo; return (
    내 패 {WIND[me.wind]} {me.isDealer ? ' 친' : ''} 점 {my.riichi && 리치} {my.furiten && {beginner ? '후리텐: 론 불가, 쯔모만 가능' : '후리텐'}} {my.autoPilot && 자리 비움 · 아무 패나 누르면 돌아와요}
    {myTurn && }
    {all.map((code, i) => { const isDrawn = my.drawn === code && i === n - 1; const ok = myTurn && legal.has(code); const picked = sel === code; const tenpai = beginner && myTurn && !my.riichi && my.tenpaiAfter[code]; return ( {isDrawn && } ); })}
    {(note || selAfter || (sel && beginner && myTurn && !my.riichi)) && (

    {note || (selAfter ? `${eulReul(tileShort(sel!))} 버리면 텐파이 · 대기 ${waitText(selAfter)}${selAfter.every((w) => !w.yaku) && !me.melds.some((m) => m.type !== 'ankan') ? ' · 역이 없으면 리치해 주세요' : ''}` : `${eulReul(tileShort(sel!))} 버리면 아직 텐파이가 아니에요.`)}

    )} {!myTurn && my.waits.length > 0 &&

    대기: {waitText(my.waits)}

    } {beginner && my.yakuHints.length > 0 && (

    💡 {my.yakuHints.join(' · ')}

    )} {myTurn && (
    {winNow && ( )} {phone && sel && ( )} {my.riichiDiscards.length > 0 && ( )} {kanOpts.length > 0 && !kanPick && ( )} {kanPick && kanOpts.map((k) => ( ))} {my.canKita && ( )} {my.canKyuushu && ( )}
    )} {riichiMode &&

    밝은 패를 버리면 리치예요. 리치하면 1,000점을 공탁에 내고, 그다음부터는 쯔모한 패만 버려요.

    } {!myTurn && v.phase === 'playing' && v.turn !== null && v.stage !== 'claim' &&

    {nick(players, v.seats[v.turn]!.id)}님 차례예요.

    }
    ); } function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record }) { const c = my.claim; const beginner = my.prefs.beginner && v.options.beginnerMode; const [chiPick, setChiPick] = useState(false); const box = useRef(null); useEffect(() => setChiPick(false), [c?.tile]); useEffect(() => { if (!c || c.responded) return; haptic(c.ron ? [80, 40, 80] : 40); // Phones: bring the buttons (right below my hand) into view. const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; box.current?.scrollIntoView?.({ block: 'nearest', behavior: reduce ? 'auto' : 'smooth' }); }, [c?.tile]); // eslint-disable-line react-hooks/exhaustive-deps if (!c) { if (v.claimOn) return

    다른 플레이어 확인 중…

    ; return null; } if (c.responded) return

    응답했어요. 다른 플레이어 확인 중…

    ; const from = nick(players, v.seats[v.claimOn?.from ?? 0]!.id); const what = c.source === 'discard' ? '버린' : c.source === 'kakan' ? '가깡한' : c.source === 'ankan' ? '안깡한' : '뽑은 북'; const call = (type: string, tiles?: string[]) => act({ type: 'claim', call: type, ...(tiles ? { tiles } : {}) }); const variant = (tiles: string[]) => ( {sortCodes([...tiles, c.tile]).map((t, i) => ( ))} ); return (
    {from}님이 {what} {tileShort(c.tile)}
    {c.ron && ( )} {c.pon.map((tiles, i) => ( ))} {c.kan.map((tiles, i) => ( ))} {c.chi.length > 0 && !chiPick && ( )} {chiPick && c.chi.map((tiles, i) => ( ))}
    {beginner && (c.pon.length > 0 || c.chi.length > 0 || c.kan.length > 0) && !my.riichi && (

    울면 리치를 못 해요. 역패·탕야오·혼일색 같은 역이 있어야 화료할 수 있어요.

    )} {c.ron && beginner &&

    이 패로 화료할 수 있어요! [론]을 눌러 주세요.

    }
    ); } // ---------------------------------------------------------------- results function WinnerBlock({ w, v, players }: { w: WinnerView; v: MahjongView; players: Record }) { const name = nick(players, v.seats[w.seat]!.id); const how = w.from === null ? '쯔모' : `론 ← ${nick(players, v.seats[w.from]!.id)}`; const limit = LIMIT_KO[w.limit] ?? ''; const yakumanTotal = w.yakuman; return (
    🀄 {name}님 {how}
    {sortCodes(w.hand).map((t, i) => ( ))} {w.melds.map((m, i) => ( ))}
      {w.yaku.map((y, i) => (
    • {y.name} {y.yakuman ? (y.yakuman > 1 ? '더블 역만' : '역만') : `${y.han}판`}
    • ))}
    {w.uraIndicators.length > 0 && (
    우라도라 표시패 {w.uraIndicators.map((t) => ( ))}
    )} {yakumanTotal > 0 && w.limit === 'yakuman' ? (yakumanTotal > 1 ? `${yakumanTotal}배 역만` : '역만') : `${w.han}판 ${w.fu}부`} {limit && w.limit !== 'yakuman' ? ` · ${limit}` : ''} · {fmt(w.points)}점 {w.paoSeat !== null && 책임지불: {nick(players, v.seats[w.paoSeat]!.id)}님}
    ); } function ResultPanel({ v, players, me, act, pending, deadline }: { v: MahjongView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean; deadline: number | null }) { const r = v.result as HandResultView; const mySeat = v.my?.seat; const ready = mySeat !== undefined && v.seats[mySeat]!.ready; const readyCount = v.seats.filter((s) => s.ready).length; let title: string; if (r.kind === 'agari') title = r.winners.length > 1 ? `${r.winners.length}명 동시 론!` : r.winners[0]!.from === null ? '쯔모 화료' : '론 화료'; else if (r.kind === 'exhaustive') title = r.nagashi.length ? '유국 · 유국만관' : '유국(패가 다 떨어졌어요)'; else title = `도중유국 · ${ABORT_KO[r.abortiveReason ?? ''] ?? ''}`; return (

    {roundLabel(r)} · {title}

    도라 표시패 {r.doraIndicators.map((t) => ( ))}
    {r.winners.map((w) => ( ))} {r.kind === 'exhaustive' && (

    텐파이: {r.tenpai.length ? r.tenpai.map((s) => nick(players, v.seats[s]!.id)).join(', ') : '없음'} {r.nagashi.length > 0 && ` · 유국만관: ${r.nagashi.map((s) => nick(players, v.seats[s]!.id)).join(', ')}`}

    )} {r.kind !== 'agari' && r.shown.map((x) => (
    {nick(players, v.seats[x.seat]!.id)} {sortCodes(x.hand).map((t, i) => ( ))}
    ))} {v.seats.map((s, i) => ( ))}
    이름 변화 점수
    {WIND[s.wind]} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} 0 ? 'mj-plus' : r.deltas[s.seat]! < 0 ? 'mj-minus' : ''}`}>{signed(r.deltas[s.seat]!)} {fmt(r.pointsAfter[s.seat]!)}
    {r.poolTaken > 0 && 공탁 {fmt(r.poolTaken)}점은 화료한 사람이 가져가요.}

    {v.gameOver ? `대국이 끝났어요 · ${END_KO[v.gameOver]}` : v.nextHand ? `다음: ${roundLabel(v.nextHand)}` : ''}

    {mySeat !== undefined && ( )}
    ); } function FinalPanel({ v, players, me }: { v: MahjongView; players: Record; me: string | null }) { const f = v.final; if (!f) return null; return (

    최종 결과 · {END_KO[f.endReason]}

    {f.ranking.map((r, i) => ( ))}
    순위 이름 점수 결과(우마·오카)
    {r.rank}위 {nick(players, r.player)} {r.player === me ? ' (나)' : ''} {fmt(r.points)} 0 ? 'mj-plus' : r.score < 0 ? 'mj-minus' : ''}`}> {r.score > 0 ? '+' : ''} {r.score.toFixed(1)}
    {f.bestHand && (

    최고 화료: {nick(players, f.bestHand.player)}님 · {f.bestHand.yaku.filter((y) => !/^(도라|적도라|우라도라|북) /.test(y)).join(', ')} · {fmt(f.bestHand.points)}점

    )} {f.perPlayer.map((p) => ( ))}
    이름 화료 방총 리치 울기
    {nick(players, p.player)} {p.wins} {p.dealIns} {p.riichi} {p.calls}
    {f.rounds}국을 했어요. 점수는 이 방에서만 쓰는 놀이용 점수예요.
    ); } // ---------------------------------------------------------------- board /** Public facts compared between views to play sounds (only what everyone can see, plus my own hand/prompt). */ interface Snap { hand: number; phase: MahjongView['phase']; disc: number[]; dora: number; call: number; drawn: string | null; claim: string | null; canDiscard: boolean; } const snapOf = (v: MahjongView): Snap => ({ hand: handId(v), phase: v.phase, disc: v.seats.map((s) => s.discards.length), dora: v.doraIndicators.length, call: v.lastCall?.seq ?? -1, drawn: v.my?.drawn ?? null, claim: v.my?.claim && !v.my.claim.responded ? `${v.seq}:${v.my.claim.tile}` : null, canDiscard: !!v.my?.canDiscard, }); type Banner = { key: number; kind: 'ron' | 'tsumo' | 'draw' | 'final'; text: string; sub?: string }; function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm }: BoardProps) { const [announce, setAnnounce] = useState(''); const [callout, setCallout] = useState<{ seq: number; text: string; call: string } | null>(null); const [banner, setBanner] = useState(null); const [dealing, setDealing] = useState(false); const [ref, width, mainH] = useBox(); const seen = useSeen(v); const mine = isMyTurn(v, me); const prevMine = useRef(false); const snap = useRef(null); const bannerSeq = useRef(0); const showBanner = (b: Omit) => setBanner({ ...b, key: ++bannerSeq.current }); // Sounds follow the view (my own clicks too), so nothing plays twice; the first view only sets the baseline. useEffect(() => { const prev = snap.current; const cur = snapOf(v); snap.current = cur; if (!prev) return; const call = cur.call !== prev.call ? v.lastCall : null; if (call) { CALL_SOUND[call.call]?.(); const who = nick(players, v.seats[call.seat]!.id); setAnnounce(`${who}님 ${CALL_KO[call.call]?.replace('!', '') ?? ''}`); if (call.call === 'ron' || call.call === 'tsumo') { const many = (v.result?.winners.length ?? 1) > 1; showBanner({ kind: call.call, text: many ? `${v.result!.winners.length}명 론!` : CALL_KO[call.call]!, sub: many ? undefined : who }); } else setCallout({ seq: call.seq, text: `${who} ${CALL_KO[call.call] ?? ''}`, call: call.call }); } if (cur.phase === 'finished') { if (prev.phase === 'finished') return; const top = v.final?.ranking[0]; // Players hear the win/lose sound from the room page's result panel; spectators get a fanfare here. if (!(me && v.final?.ranking.some((r) => r.player === me))) sfx.fanfare(); if (top) showBanner({ kind: 'final', text: `🏆 ${top.player === me ? '내가' : `${nick(players, top.player)}님`} 1위!`, sub: `${fmt(top.points)}점` }); return; } if (cur.phase === 'handResult') { if (prev.phase !== 'handResult' && v.result) { if (v.result.kind === 'agari') mjSound.payout(call ? 950 : 0); else { mjSound.ryuukyoku(); showBanner({ kind: 'draw', text: v.result.kind === 'exhaustive' ? '유국' : '도중유국', sub: v.result.kind === 'abortive' ? ABORT_KO[v.result.abortiveReason ?? ''] : undefined }); } } return; } if (cur.phase !== 'playing') return; const newHand = prev.phase !== 'playing' || prev.hand !== cur.hand; if (newHand) mjSound.shuffle(); else { if (cur.disc.some((n, i) => n > (prev.disc[i] ?? 0))) mjSound.discard(); if (cur.dora > prev.dora) mjSound.flip(150); if (cur.drawn && cur.drawn !== prev.drawn) mjSound.draw(); } if (cur.claim && cur.claim !== prev.claim) mjSound.prompt(!!v.my?.claim?.ron); // My turn to discard (not right after my own call — that already made its sound). else if (cur.canDiscard && !prev.canDiscard && !(call && call.seat === v.my?.seat)) sounds.myTurn(); }, [v]); // eslint-disable-line react-hooks/exhaustive-deps // A new hand dealt while watching: my tiles fly in (not on the first view). const hand = handId(v); const firstHand = useRef(hand); useEffect(() => { if (v.phase !== 'playing' || hand === firstHand.current) return; firstHand.current = hand; setDealing(true); }, [hand, v.phase]); useEffect(() => { if (!dealing) return; const t = setTimeout(() => setDealing(false), 900); return () => clearTimeout(t); }, [dealing]); useEffect(() => { if (!banner) return; const t = setTimeout(() => setBanner((b) => (b && b.key === banner.key ? null : b)), 1700); return () => clearTimeout(t); }, [banner]); useEffect(() => { if (mine && !prevMine.current) { haptic(40); if (v.my?.claim) setAnnounce(v.my.claim.ron ? '론할 수 있어요!' : '울 수 있어요. 고르거나 패스해 주세요.'); else if (v.phase === 'playing') setAnnounce(v.my?.canTsumo ? '내 차례예요. 쯔모할 수 있어요!' : '내 차례예요.'); } prevMine.current = mine; }, [mine]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!callout) return; const t = setTimeout(() => setCallout((x) => (x && x.seq === callout.seq ? null : x)), 1300); return () => clearTimeout(t); }, [callout]); useEffect(() => { if (v.claimOn && v.claimOn.source === 'discard' && v.claimOn.from !== v.my?.seat) setAnnounce(`${nick(players, v.seats[v.claimOn.from]!.id)}님이 ${eulReul(tileName(v.claimOn.tile))} 버렸어요.`); }, [v.claimOn?.tile, v.claimOn?.from]); // eslint-disable-line react-hooks/exhaustive-deps const mySeat = v.my?.seat ?? -1; const others = v.seats.filter((s) => s.seat !== mySeat).sort((a, b) => relPos(v, a.seat) - relPos(v, b.seat)); const phone = width > 0 && width < 600; // PC: table on the left sized to the screen height, other players on the right, my hand below. const wide = width >= 900; const reserve = v.my ? 290 : 20; const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560, 600)) : width || 360; const showTable = v.phase === 'playing' || (v.phase === 'handResult' && !wide); return (
      {others.map((s) => ( ))}
    0 ? mainH - 12 : undefined } : undefined}> {v.phase === 'handResult' && v.result && } {v.phase === 'finished' && } {showTable && (
    {callout.text} : null} seen={seen} /> )} {v.phase === 'playing' && v.my && } {banner && (
    {banner.text} {banner.sub && {banner.sub}}
    )}

    {announce}

    ); } // ---------------------------------------------------------------- side function Toggles({ v, act, pending }: { v: MahjongView; act: (a: unknown) => void; pending: boolean }) { const my = v.my; if (!my || v.phase === 'finished') return null; const p = my.prefs; return (
    내 설정 {v.options.beginnerMode && ( )}
    ); } function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProps) { const turnSeat = v.phase === 'playing' && v.stage !== 'claim' ? v.turn : null; return ( <>
    {v.mode === 'sanma' ? '3인 마작(산마)' : '4인 마작'} · {v.options.length === 'tonpuu' ? '동풍전' : '반장전'} {turnSeat !== null && }
    {roundLabel(v)} · 공탁 {fmt(v.riichiPool)}점 · 남은 패 {v.wallCount}장
      {v.seats.map((s) => (
    1. {WIND[s.wind]} {turnSeat === s.seat ? '▶ ' : ''} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} {s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''} {s.riichi && ( 리치 )}
    2. ))}
    {v.history.length > 0 && (
    국별 점수 변화
      {[...v.history].reverse().map((h, i) => (
    1. {h.label} {h.kind === 'agari' ? '화료' : h.kind === 'exhaustive' ? '유국' : '도중유국'} ·{' '} {v.seats.map((s) => `${nick(players, s.id)} ${signed(h.deltas[s.seat]!)}`).join(' / ')}
    2. ))}
    )}
    역 목록
    ); } // ---------------------------------------------------------------- status function isMyTurn(v: MahjongView, me: string | null): boolean { const my = v.my; if (!me || !my) return false; if (v.phase === 'handResult') return !v.seats[my.seat]!.ready; if (v.phase !== 'playing') return false; if (my.claim) return !my.claim.responded; return my.canDiscard; } function statusText(v: MahjongView, me: string | null, players: Record): string { if (v.phase === 'finished') return v.final?.summary ?? '대국이 끝났어요'; const my = v.my; if (v.phase === 'handResult') { const done = my && v.seats[my.seat]!.ready; return `${roundLabel(v.result ?? v)} 결과예요. ${my ? (done ? '다른 사람을 기다리는 중이에요' : v.gameOver ? '[최종 결과 보기]를 눌러 주세요' : '[다음 국으로]를 눌러 주세요') : ''}`.trim(); } if (my?.claim && !my.claim.responded) { if (my.claim.ron) return '론할 수 있어요! [론] 또는 [패스]를 골라 주세요'; return '울 수 있어요. 고르거나 [패스]를 눌러 주세요'; } if (v.stage === 'claim') return '다른 플레이어 확인 중이에요'; if (me && my?.canDiscard) { if (my.canTsumo) return '내 차례예요 · 쯔모할 수 있어요!'; if (my.riichi) return '내 차례예요 · 리치 중이라 쯔모한 패를 버려요'; if (v.stage === 'afterCall') return '내 차례예요 · 울고 나서 버릴 패를 골라 주세요'; return '내 차례예요 · 버릴 패를 골라 주세요'; } if (v.turn === null) return '잠시만 기다려 주세요'; return `${nick(players, v.seats[v.turn]!.id)}님 차례예요`; } // ---------------------------------------------------------------- options function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
    {options.map(([k, l]) => ( ))}
    ); } function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { return (
    {label} {children} {help && {help}}
    ); } const onOff: [boolean, string][] = [ [true, '켜기'], [false, '끄기'], ]; const POINTS = ['auto', 15000, 20000, 25000, 30000, 35000, 40000, 50000] as const; const pointLabel = (p: (typeof POINTS)[number], auto: string) => (p === 'auto' ? auto : `${fmt(p)}점`); function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); return (

    4명이면 4인 마작, 3명이면 3인 마작(산마)으로 해요.

    set({ length })} /> set({ turnSeconds })} /> set({ beginnerMode })} /> set({ akaDora })} /> set({ kuitan })} /> {more && ( <>
    set({ uma })} /> set({ doubleRon })} /> set({ tripleRon })} /> set({ renchanOn })} /> {( [ ['tobi', '0점 미만이면 바로 종료(토비)'], ['agariYame', '올라스트 친 1위면 종료(아가리야메)'], ['westEntry', '반환점 넘는 사람이 없으면 연장(서입)'], ['kiriageMangan', '절상만관(4판30부·3판60부 → 만관)'], ['kazoeYakuman', '헤아림 역만(13판 이상)'], ['doubleYakuman', '더블 역만'], ['abortiveDraws', '도중유국(구종구패 등)'], ['nagashiMangan', '유국만관'], ['pao', '책임지불(대삼원·대사희)'], ['ankanChankanKokushi', '국사무쌍 안깡 창깡'], ] as const ).map(([k, label]) => ( set({ [k]: val } as Partial)} /> ))} set({ renpuuPairFu })} /> {o.turnSeconds !== 0 && ( <> set({ claimSeconds })} /> set({ timeBankSeconds })} /> )} set({ sanmaTsumo })} /> set({ sanmaHonba })} /> set({ sanmaNotenPool })} /> )}
    ); } function optionsSummary(o: MahjongOptions): string { const parts = [o.length === 'tonpuu' ? '동풍전' : '반장전']; parts.push(o.akaDora === 0 ? '적도라 없음' : '적도라'); if (o.kuitan) parts.push('쿠이탕'); if (o.doubleRon === 'headBump') parts.push('머리튀기'); if (o.beginnerMode) parts.push('초보 모드'); parts.push(o.turnSeconds === 0 ? '시간 무제한' : `${o.turnSeconds}초`); return parts.join(' · '); } // ---------------------------------------------------------------- rules const YAKU: [string, string, string, string][] = [ ['리치', '멘젠 텐파이에서 1,000점을 내고 선언', '1', '-'], ['일발', '리치 후 한 바퀴 안에 화료', '1', '-'], ['멘젠쯔모', '울지 않고 쯔모 화료', '1', '-'], ['핑후', '순쯔 4개 + 역패 아닌 머리 + 양면 대기', '1', '-'], ['탕야오', '2~8 수패만', '1', '1'], ['이페코', '같은 순쯔 2개', '1', '-'], ['역패', '백·발·중, 장풍, 자풍 각쯔', '1', '1'], ['해저·하저', '마지막 패로 쯔모 / 마지막 버림패로 론', '1', '1'], ['영상개화·창깡', '깡 보충패로 쯔모 / 남의 가깡 패로 론', '1', '1'], ['칠대자', '서로 다른 대자 7개', '2', '-'], ['삼색동순', '만·통·삭 같은 숫자 순쯔', '2', '1'], ['일기통관', '한 종류 123·456·789', '2', '1'], ['찬타', '모든 면자·머리에 1·9·자패', '2', '1'], ['또이또이', '각쯔 4개', '2', '2'], ['산안커', '암각 3개', '2', '2'], ['소삼원', '삼원패 각쯔 2개 + 머리', '2', '2'], ['혼노두', '1·9·자패만', '2', '2'], ['혼일색', '한 종류 수패 + 자패', '3', '2'], ['준찬타', '모든 면자·머리에 1·9', '3', '2'], ['량페코', '이페코 2개', '3', '-'], ['청일색', '한 종류 수패만', '6', '5'], ['역만', '국사무쌍·사암각·대삼원·소사희·대사희·자일색·청노두·녹일색·구련보등·사깡쯔·천화·지화', '역만', '일부'], ]; function YakuTable() { return (
    {YAKU.map(([name, desc, closed, open]) => ( ))}
    역 조건 멘젠 울기
    {name} {desc} {closed === '역만' ? closed : `${closed}판`} {open === '-' ? '안 됨' : open === '일부' ? open : `${open}판`}
    ); } function Rules({ options }: { options?: MahjongOptions }) { const o = options; return (

    리치 마작이에요. 손패 13장에 1장을 더해 면자 4개 + 머리 1개(면자 = 같은 패 3장 또는 같은 종류 연속 3장, 머리 = 같은 패 2장)를 먼저 만들면 화료예요. 칠대자(대자 7개)와 국사무쌍도 화료형이에요.

    {['2m', '3m', '4m', '5p', '6p', '7p', '6s', '7s', '8s', '2p', '2p', '3s', '4s', '5s'].map((t, i) => ( ))}

    차례가 오면 1장을 가져오고(쯔모) 1장을 버려요. 남이 버린 패로 퐁(같은 패 2장 + 1), 치(왼쪽 사람 패로 연속 3장, 3인은 안 됨), 깡(같은 패 4장)을 할 수 있지만, 울면 리치를 못 하고 일부 역의 판수가 내려가요.

    역이 1개 이상 있어야 화료할 수 있어요. 도라는 역이 아니에요. 가장 쉬운 역은 리치(울지 않고 텐파이하면 1,000점을 내고 선언), 탕야오(2~8만으로), 역패(백·발·중 같은 패 3장)예요.

    후리텐: 내가 기다리는 패를 전에 버린 적이 있거나, 방금 론할 수 있었는데 넘겼다면 론할 수 없어요(쯔모는 돼요).

    점수는 판(역 + 도라)과 부(손 모양)로 계산해요. 5판 만관 8,000점, 6판 하네만 12,000점, 8판 배만, 11판 삼배만, 역만 32,000점(친은 1.5배). 시작 점수{' '} {o && o.startPoints !== 'auto' ? `${fmt(o.startPoints)}점` : '4인 25,000점 · 3인 35,000점'}, 마지막에 순위 우마와 오카를 더해 결과를 내요.

    3인(산마): 2만~8만이 없고, 치를 못 해요. 북은 옆에 빼고(북 뽑기) 1장을 더 가져올 수 있어요. 뺀 북은 도라 1개예요.

    점수는 이 방에서만 쓰는 놀이용 점수예요. 재화나 포인트로 바뀌지 않아요.

    ); } const ui: GameUI = { Board: MahjongBoard, Side: MahjongSide, statusText, isMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;