1567 lines
76 KiB
TypeScript
1567 lines
76 KiB
TypeScript
/** 마작 화면 (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<string, string> = { none: '', mangan: '만관', haneman: '하네만', baiman: '배만', sanbaiman: '삼배만', kazoe: '헤아림 역만', yakuman: '역만' };
|
||
const ABORT_KO: Record<string, string> = { kyuushu: '구종구패', suufon: '사풍연타', suukan: '사깡유국', suucha: '사가리치', sanchaho: '삼가화' };
|
||
const CALL_KO: Record<string, string> = { chi: '치!', pon: '퐁!', kan: '깡!', riichi: '리치!', kita: '북!', tsumo: '쯔모!', ron: '론!' };
|
||
const END_KO: Record<string, string> = { normal: '마지막 국이 끝났어요', tobi: '0점 미만이 나와 끝났어요(토비)', agariYame: '올라스트 친이 1위로 끝냈어요(아가리야메)', westEntryEnd: '연장전에서 끝났어요' };
|
||
|
||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||
const userOf = (players: Record<string, PublicUser>, 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<MahjongView, 'roundWind' | 'handNumber' | 'honba'>) => `${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<string, () => 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<Seen>(() => ({
|
||
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 (
|
||
<span key={value} className={moved.current ? 'anim-bump' : undefined} style={{ display: 'inline-block' }}>
|
||
{children ?? fmt(value)}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
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<T extends HTMLElement>(): [React.RefObject<T | null>, number, number] {
|
||
const ref = useRef<T>(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<T extends HTMLElement>(): [React.RefObject<T | null>, number] {
|
||
const ref = useRef<T>(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 (
|
||
<span className={`mj-meld${fresh ? ' anim-pop' : ''}`} role="img" aria-label={meldLabel(m)}>
|
||
{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 <Tile key={`${t}-${i}`} code={hidden ? null : t} w={w} sideways={side} />;
|
||
})}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
/** `seen`: how many melds / 북 were already there when the screen opened (later ones pop in). */
|
||
function Melds({ s, w, seen }: { s: Pick<SeatView, 'melds' | 'kita'>; w: number; seen?: [number, number] }) {
|
||
if (s.melds.length === 0 && s.kita.length === 0) return null;
|
||
const [m0, k0] = seen ?? [Infinity, Infinity];
|
||
return (
|
||
<div className="mj-melds">
|
||
{s.melds.map((m, i) => (
|
||
<Meld key={i} m={m} w={w} fresh={i >= m0} />
|
||
))}
|
||
{s.kita.length > 0 && (
|
||
<span className="mj-meld" role="img" aria-label={`북 뽑기 ${s.kita.length}장`}>
|
||
{s.kita.map((t, i) => (
|
||
<Tile key={t} code={t} w={w} className={i >= k0 ? 'anim-pop' : undefined} />
|
||
))}
|
||
</span>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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<string, PublicUser>, 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<string, PublicUser>; 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 (
|
||
<li className={`mj-seat${turn ? ' turn anim-glow' : ''}${s.left ? ' gone' : ''}`} aria-label={seatLabel(v, s, players, me)}>
|
||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }} aria-hidden>
|
||
<Avatar user={u} size={22} />
|
||
<span className="nm">{u.nickname}</span>
|
||
<span className="pos">{POS_KO[relPos(v, s.seat)]}</span>
|
||
{turn && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={false} size={26} />}
|
||
</div>
|
||
<div className="row" style={{ gap: 4 }} aria-hidden>
|
||
<span className={`mj-badge ${s.isDealer ? 'mj-b-dealer' : 'mj-b-wind'}`}>
|
||
{WIND[s.wind]}
|
||
{s.isDealer ? ' 친' : ''}
|
||
</span>
|
||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||
<Bump value={s.points} />
|
||
</strong>
|
||
{s.riichi && <span className={`mj-badge mj-b-riichi${seen?.riichi[s.seat] ? '' : ' anim-pop'}`}>리치</span>}
|
||
{(s.away || s.left) && <span className="mj-badge mj-b-away">{s.left ? '나감' : '자리 비움'}</span>}
|
||
{v.phase === 'playing' && (
|
||
<span className="mj-back-count" title="손패 장수">
|
||
<Tile code={null} w={10} />
|
||
{s.handCount}
|
||
</span>
|
||
)}
|
||
</div>
|
||
<Melds s={s} w={w} seen={meldSeen(seen, s.seat)} />
|
||
</li>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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) => (
|
||
<div key={ri} className="mj-pond-row">
|
||
{row.map((d, ci) => {
|
||
const idx = ri * 6 + ci;
|
||
return (
|
||
<Tile
|
||
key={idx}
|
||
code={d.tile}
|
||
w={tw}
|
||
sideways={d.riichi}
|
||
dim={d.called}
|
||
className={[idx === lastIndex ? 'last' : '', idx >= fromIndex ? 'mj-toss' : ''].filter(Boolean).join(' ') || undefined}
|
||
label={`${tileName(d.tile)}${d.tsumogiri ? ', 쯔모기리' : ''}${d.riichi ? ', 리치 선언' : ''}${d.called ? ', 울려 감' : ''}`}
|
||
/>
|
||
);
|
||
})}
|
||
</div>
|
||
))}
|
||
</>
|
||
);
|
||
}
|
||
|
||
const ROT = [0, -90, 180, 90];
|
||
|
||
function Table({ v, players, width, callout, seen }: { v: MahjongView; players: Record<string, PublicUser>; 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 <div className="mj-cell" style={style} />;
|
||
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 (
|
||
<div className="mj-cell" style={style} role="group" aria-label={`${nick(players, s.id)}님 버림패 ${s.discards.length}장`}>
|
||
<div className={`mj-pond${turn ? ' turn' : ''}`} style={{ width: W, height: H, transform: `translate(-50%, -50%) rotate(${ROT[pos]}deg)` }}>
|
||
<Pond discards={s.discards} tw={tw} lastIndex={lastIndex} fromIndex={seen ? (seen.disc[s.seat] ?? 0) : 0} />
|
||
</div>
|
||
</div>
|
||
);
|
||
};
|
||
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 (
|
||
<span key={pos} className={`mj-edge ${['b', 'r', 't', 'l'][pos]}${turn ? ' turn' : ''}`} aria-hidden>
|
||
{WIND[s.wind]} <Bump value={s.points} />
|
||
{s.riichi && <i className={`stick${seen?.riichi[s.seat] ? '' : ' new'}`} />}
|
||
</span>
|
||
);
|
||
};
|
||
const dw = Math.max(12, Math.round(tw * 0.8));
|
||
return (
|
||
<div
|
||
className="mj-table"
|
||
role="region"
|
||
aria-label={`마작 판. ${roundLabel(v)}, 공탁 ${v.riichiPool}점, 남은 패 ${v.wallCount}장, 도라 표시패 ${v.doraIndicators.map(tileName).join(', ')}`}
|
||
style={{ gridTemplateColumns: `${H}px ${W}px ${H}px`, gridTemplateRows: `${H}px ${W}px ${H}px`, '--tw': `${tw}px` } as CSSProperties}
|
||
>
|
||
<div />
|
||
{cell(2)}
|
||
<div />
|
||
{cell(3)}
|
||
<div className="mj-center" style={{ width: W, height: W }}>
|
||
<span className="rl">{roundLabel(v).split(' ')[0]}</span>
|
||
<span className="sub">
|
||
{v.honba}본장 · 공탁 <Bump value={v.riichiPool / 1000} />개
|
||
</span>
|
||
<span className="sub">남은 패 {v.wallCount}</span>
|
||
<div className="mj-dora" title="도라 표시패">
|
||
{v.doraIndicators.map((t, i) => (
|
||
<Tile key={t} code={t} w={dw} className={i >= (seen?.dora ?? 0) ? 'anim-flip' : undefined} style={{ '--anim-delay': '120ms' } as CSSProperties} />
|
||
))}
|
||
{Array.from({ length: Math.max(0, 5 - v.doraIndicators.length) }, (_, i) => (
|
||
<Tile key={`b${i}`} code={null} w={dw} />
|
||
))}
|
||
</div>
|
||
{[0, 1, 2, 3].map(edge)}
|
||
{callout}
|
||
</div>
|
||
{cell(1)}
|
||
<div />
|
||
{cell(0)}
|
||
<div />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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<string, PublicUser>;
|
||
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<string | null>(null);
|
||
const [riichiMode, setRiichiMode] = useState(false);
|
||
const [kanPick, setKanPick] = useState(false);
|
||
const [note, setNote] = useState('');
|
||
const [ref, width] = useWidth<HTMLDivElement>();
|
||
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<HTMLDivElement>) => {
|
||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||
const btns = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>('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 (
|
||
<div className={`mj-panel mj-me${myTurn ? ' anim-glow' : ''}`} aria-label="내 패">
|
||
<div className="mj-myhead">
|
||
<div className="row" style={{ gap: 6 }}>
|
||
<strong>내 패</strong>
|
||
<span className={`mj-badge ${me.isDealer ? 'mj-b-dealer' : 'mj-b-wind'}`}>
|
||
{WIND[me.wind]}
|
||
{me.isDealer ? ' 친' : ''}
|
||
</span>
|
||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||
<Bump value={me.points} />점
|
||
</strong>
|
||
{my.riichi && <span className={`mj-badge mj-b-riichi${seen?.riichi[my.seat] ? '' : ' anim-pop'}`}>리치</span>}
|
||
{my.furiten && <span className="mj-badge mj-b-furiten">{beginner ? '후리텐: 론 불가, 쯔모만 가능' : '후리텐'}</span>}
|
||
{my.autoPilot && <span className="mj-badge mj-b-away">자리 비움 · 아무 패나 누르면 돌아와요</span>}
|
||
</div>
|
||
{myTurn && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={36} />}
|
||
</div>
|
||
<Melds s={me} w={meldW} seen={meldSeen(seen, my.seat)} />
|
||
<div ref={ref} className="mj-hand" role="group" aria-label="내 손패. 좌우 방향키로 고르고 Enter로 고른 뒤 한 번 더 누르면 버려요" onKeyDown={onKey}>
|
||
{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 (
|
||
<span key={`${code}-${i}`} style={{ display: 'contents' }}>
|
||
{isDrawn && <span className="gap" aria-hidden />}
|
||
<button
|
||
type="button"
|
||
className="mj-htile"
|
||
data-legal={myTurn ? ok : undefined}
|
||
aria-pressed={picked}
|
||
onClick={() => tap(code)}
|
||
aria-label={`${tileName(code)}${isDrawn ? ', 방금 쯔모한 패' : ''}${tenpai ? ', 버리면 텐파이' : ''}${locked.has(code) ? ', 구이가에로 못 버림' : ''}${picked ? ', 골랐음. 한 번 더 누르면 버려요' : ''}`}
|
||
>
|
||
{tenpai && (
|
||
<span className="mark" aria-hidden>
|
||
텐
|
||
</span>
|
||
)}
|
||
<Tile
|
||
code={code}
|
||
w={tw}
|
||
className={isDrawn ? 'mj-drawn' : dealing ? 'anim-deal' : undefined}
|
||
style={dealing ? ({ '--anim-delay': `${i * 30}ms`, '--from-y': '-70px' } as CSSProperties) : undefined}
|
||
/>
|
||
{locked.has(code) && (
|
||
<span className="lock" aria-hidden>
|
||
🔒
|
||
</span>
|
||
)}
|
||
</button>
|
||
</span>
|
||
);
|
||
})}
|
||
</div>
|
||
{(note || selAfter || (sel && beginner && myTurn && !my.riichi)) && (
|
||
<p className={`mj-hint${note ? ' warn' : ''}`} aria-live="polite">
|
||
{note ||
|
||
(selAfter
|
||
? `${eulReul(tileShort(sel!))} 버리면 텐파이 · 대기 ${waitText(selAfter)}${selAfter.every((w) => !w.yaku) && !me.melds.some((m) => m.type !== 'ankan') ? ' · 역이 없으면 리치해 주세요' : ''}`
|
||
: `${eulReul(tileShort(sel!))} 버리면 아직 텐파이가 아니에요.`)}
|
||
</p>
|
||
)}
|
||
{!myTurn && my.waits.length > 0 && <p className="mj-hint">대기: {waitText(my.waits)}</p>}
|
||
{beginner && my.yakuHints.length > 0 && (
|
||
<p className="mj-hint" style={{ color: 'var(--text-sub)' }}>
|
||
💡 {my.yakuHints.join(' · ')}
|
||
</p>
|
||
)}
|
||
{myTurn && (
|
||
<div className="mj-actions">
|
||
{winNow && (
|
||
<button
|
||
type="button"
|
||
className={`btn mj-big ${beginner ? 'mj-win-btn' : 'btn-primary'}`}
|
||
disabled={pending}
|
||
onClick={() => {
|
||
haptic(60);
|
||
act({ type: 'tsumo' });
|
||
}}
|
||
>
|
||
쯔모!
|
||
</button>
|
||
)}
|
||
{phone && sel && (
|
||
<span className="mj-preview" aria-hidden>
|
||
<Tile code={sel} w={40} />
|
||
</span>
|
||
)}
|
||
<button type="button" className={`btn ${winNow ? 'btn-secondary' : 'btn-primary'}`} disabled={!sel || pending} onClick={() => sel && send(sel)}>
|
||
{sel ? `${tileShort(sel)} ${riichiMode ? '리치하고 버리기' : '버리기'}` : riichiMode ? '리치할 패를 골라 주세요' : '버릴 패를 골라 주세요'}
|
||
</button>
|
||
{my.riichiDiscards.length > 0 && (
|
||
<button
|
||
type="button"
|
||
className={`btn ${riichiMode ? 'btn-danger' : 'btn-soft'}`}
|
||
aria-pressed={riichiMode}
|
||
disabled={pending}
|
||
onClick={() => {
|
||
setRiichiMode(!riichiMode);
|
||
if (sel && !my.riichiDiscards.includes(sel)) setSel(null);
|
||
}}
|
||
>
|
||
{riichiMode ? '리치 취소' : '리치'}
|
||
</button>
|
||
)}
|
||
{kanOpts.length > 0 && !kanPick && (
|
||
<button
|
||
type="button"
|
||
className="btn btn-soft"
|
||
disabled={pending}
|
||
onClick={() => {
|
||
if (kanOpts.length === 1) act(kanOpts[0]);
|
||
else setKanPick(true);
|
||
}}
|
||
>
|
||
깡{kanOpts.length === 1 ? ` (${tileShort(kanOpts[0]!.tile)})` : ''}
|
||
</button>
|
||
)}
|
||
{kanPick &&
|
||
kanOpts.map((k) => (
|
||
<button key={k.type + k.tile} type="button" className="btn btn-soft" disabled={pending} onClick={() => act(k)} aria-label={`${tileName(k.tile)} ${k.type === 'ankan' ? '안깡' : '가깡'}`}>
|
||
<span className="mj-choice">
|
||
<Tile code={k.tile} w={22} /> {k.type === 'ankan' ? '안깡' : '가깡'}
|
||
</span>
|
||
</button>
|
||
))}
|
||
{my.canKita && (
|
||
<button type="button" className="btn btn-soft" disabled={pending} onClick={() => act({ type: 'kita' })}>
|
||
북 뽑기
|
||
</button>
|
||
)}
|
||
{my.canKyuushu && (
|
||
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'kyuushu' })}>
|
||
구종구패(유국)
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
{riichiMode && <p className="mj-hint">밝은 패를 버리면 리치예요. 리치하면 1,000점을 공탁에 내고, 그다음부터는 쯔모한 패만 버려요.</p>}
|
||
{!myTurn && v.phase === 'playing' && v.turn !== null && v.stage !== 'claim' && <p className="mj-hint muted">{nick(players, v.seats[v.turn]!.id)}님 차례예요.</p>}
|
||
<ClaimPanel v={v} my={my} act={act} pending={pending} players={players} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||
const c = my.claim;
|
||
const beginner = my.prefs.beginner && v.options.beginnerMode;
|
||
const [chiPick, setChiPick] = useState(false);
|
||
const box = useRef<HTMLDivElement>(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 <p className="mj-hint muted" aria-live="polite">다른 플레이어 확인 중…</p>;
|
||
return null;
|
||
}
|
||
if (c.responded) return <p className="mj-hint muted">응답했어요. 다른 플레이어 확인 중…</p>;
|
||
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[]) => (
|
||
<span className="mj-choice">
|
||
{sortCodes([...tiles, c.tile]).map((t, i) => (
|
||
<Tile key={`${t}-${i}`} code={t} w={20} />
|
||
))}
|
||
</span>
|
||
);
|
||
return (
|
||
<div ref={box} className="mj-panel claim" role="group" aria-label="울기·론 선택">
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<span className="row" style={{ gap: 8 }}>
|
||
<Tile code={c.tile} w={32} />
|
||
<strong>
|
||
{from}님이 {what} {tileShort(c.tile)}
|
||
</strong>
|
||
</span>
|
||
<TurnTimer deadline={c.deadline} totalMs={c.totalMs} mine size={40} />
|
||
</div>
|
||
<div className="mj-actions">
|
||
{c.ron && (
|
||
<button type="button" className={`btn mj-big ${beginner ? 'mj-win-btn' : 'btn-danger'}`} disabled={pending} onClick={() => call('ron')}>
|
||
론!
|
||
</button>
|
||
)}
|
||
{c.pon.map((tiles, i) => (
|
||
<button key={`p${i}`} type="button" className="btn btn-primary" disabled={pending} onClick={() => call('pon', tiles)} aria-label={`퐁 ${tiles.map(tileName).join(', ')}`}>
|
||
퐁{c.pon.length > 1 && variant(tiles)}
|
||
</button>
|
||
))}
|
||
{c.kan.map((tiles, i) => (
|
||
<button key={`k${i}`} type="button" className="btn btn-primary" disabled={pending} onClick={() => call('kan', tiles)}>
|
||
깡
|
||
</button>
|
||
))}
|
||
{c.chi.length > 0 && !chiPick && (
|
||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => (c.chi.length === 1 ? call('chi', c.chi[0]) : setChiPick(true))}>
|
||
치{c.chi.length > 1 ? ` (${c.chi.length}가지)` : ''}
|
||
</button>
|
||
)}
|
||
{chiPick &&
|
||
c.chi.map((tiles, i) => (
|
||
<button key={`c${i}`} type="button" className="btn btn-soft" disabled={pending} onClick={() => call('chi', tiles)} aria-label={`치 ${tiles.map(tileName).join(', ')}`}>
|
||
{variant(tiles)}
|
||
</button>
|
||
))}
|
||
<button type="button" className="btn btn-secondary" disabled={pending} onClick={() => act({ type: 'pass' })}>
|
||
패스
|
||
</button>
|
||
</div>
|
||
{beginner && (c.pon.length > 0 || c.chi.length > 0 || c.kan.length > 0) && !my.riichi && (
|
||
<p className="mj-hint" style={{ color: 'var(--text-sub)' }}>
|
||
울면 리치를 못 해요. 역패·탕야오·혼일색 같은 역이 있어야 화료할 수 있어요.
|
||
</p>
|
||
)}
|
||
{c.ron && beginner && <p className="mj-hint">이 패로 화료할 수 있어요! [론]을 눌러 주세요.</p>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- results
|
||
|
||
function WinnerBlock({ w, v, players }: { w: WinnerView; v: MahjongView; players: Record<string, PublicUser> }) {
|
||
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 (
|
||
<div className="mj-panel win anim-slide-up">
|
||
<strong style={{ fontSize: '1.1rem' }}>
|
||
🀄 {name}님 {how}
|
||
</strong>
|
||
<div className="mj-res-hand" role="img" aria-label={`손패 ${sortCodes(w.hand).map(tileShort).join(' ')}, 화료패 ${tileName(w.winTile)}`}>
|
||
{sortCodes(w.hand).map((t, i) => (
|
||
<Tile key={`${t}-${i}`} code={t} w={26} />
|
||
))}
|
||
{w.melds.map((m, i) => (
|
||
<span key={i} style={{ marginLeft: 6 }}>
|
||
<Meld m={m} w={26} />
|
||
</span>
|
||
))}
|
||
<Tile code={w.winTile} w={26} className="win" />
|
||
</div>
|
||
<ul className="mj-yaku">
|
||
{w.yaku.map((y, i) => (
|
||
<li key={i}>
|
||
<span>{y.name}</span>
|
||
<span style={{ textAlign: 'right', fontWeight: 700 }}>{y.yakuman ? (y.yakuman > 1 ? '더블 역만' : '역만') : `${y.han}판`}</span>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{w.uraIndicators.length > 0 && (
|
||
<div className="row small" style={{ gap: 4 }}>
|
||
우라도라 표시패
|
||
{w.uraIndicators.map((t) => (
|
||
<Tile key={t} code={t} w={18} />
|
||
))}
|
||
</div>
|
||
)}
|
||
<span className="mj-total">
|
||
{yakumanTotal > 0 && w.limit === 'yakuman' ? (yakumanTotal > 1 ? `${yakumanTotal}배 역만` : '역만') : `${w.han}판 ${w.fu}부`}
|
||
{limit && w.limit !== 'yakuman' ? ` · ${limit}` : ''} · {fmt(w.points)}점
|
||
</span>
|
||
{w.paoSeat !== null && <span className="small">책임지불: {nick(players, v.seats[w.paoSeat]!.id)}님</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ResultPanel({ v, players, me, act, pending, deadline }: { v: MahjongView; players: Record<string, PublicUser>; 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 (
|
||
<section className="mj-panel" aria-live="polite" aria-label={`${roundLabel(r)} 결과`}>
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<h2 style={{ margin: 0, fontSize: '1.3rem' }}>
|
||
{roundLabel(r)} · {title}
|
||
</h2>
|
||
<TurnTimer deadline={deadline} totalMs={15_000} mine={!ready} size={36} />
|
||
</div>
|
||
<div className="row small" style={{ gap: 4 }}>
|
||
도라 표시패
|
||
{r.doraIndicators.map((t) => (
|
||
<Tile key={t} code={t} w={18} />
|
||
))}
|
||
</div>
|
||
{r.winners.map((w) => (
|
||
<WinnerBlock key={w.seat} w={w} v={v} players={players} />
|
||
))}
|
||
{r.kind === 'exhaustive' && (
|
||
<p style={{ margin: 0 }}>
|
||
텐파이: {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(', ')}`}
|
||
</p>
|
||
)}
|
||
{r.kind !== 'agari' &&
|
||
r.shown.map((x) => (
|
||
<div key={x.seat} className="row small" style={{ gap: 6 }}>
|
||
<span style={{ minWidth: 70 }}>{nick(players, v.seats[x.seat]!.id)}</span>
|
||
<span className="mj-res-hand" role="img" aria-label={`${nick(players, v.seats[x.seat]!.id)}님 손패 ${x.hand.map(tileShort).join(' ')}`}>
|
||
{sortCodes(x.hand).map((t, i) => (
|
||
<Tile key={`${t}-${i}`} code={t} w={20} />
|
||
))}
|
||
</span>
|
||
</div>
|
||
))}
|
||
<table className="mj-deltas small">
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">이름</th>
|
||
<th scope="col" className="num">
|
||
변화
|
||
</th>
|
||
<th scope="col" className="num">
|
||
점수
|
||
</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{v.seats.map((s, i) => (
|
||
<tr key={s.seat} className="anim-slide-up" style={{ '--anim-delay': `${250 + i * 90}ms` } as CSSProperties}>
|
||
<td>
|
||
{WIND[s.wind]} {nick(players, s.id)}
|
||
{s.id === me ? ' (나)' : ''}
|
||
</td>
|
||
<td className={`num ${r.deltas[s.seat]! > 0 ? 'mj-plus' : r.deltas[s.seat]! < 0 ? 'mj-minus' : ''}`}>{signed(r.deltas[s.seat]!)}</td>
|
||
<td className="num">{fmt(r.pointsAfter[s.seat]!)}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
{r.poolTaken > 0 && <span className="small">공탁 {fmt(r.poolTaken)}점은 화료한 사람이 가져가요.</span>}
|
||
<p style={{ margin: 0, fontWeight: 700 }}>{v.gameOver ? `대국이 끝났어요 · ${END_KO[v.gameOver]}` : v.nextHand ? `다음: ${roundLabel(v.nextHand)}` : ''}</p>
|
||
{mySeat !== undefined && (
|
||
<button type="button" className="btn btn-primary btn-block" disabled={ready || pending} onClick={() => act({ type: 'ready' })}>
|
||
{ready ? `다른 사람을 기다리는 중이에요 (${readyCount}/${v.n})` : v.gameOver ? '최종 결과 보기' : '다음 국으로'}
|
||
</button>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|
||
|
||
function FinalPanel({ v, players, me }: { v: MahjongView; players: Record<string, PublicUser>; me: string | null }) {
|
||
const f = v.final;
|
||
if (!f) return null;
|
||
return (
|
||
<section className="mj-panel" aria-label="최종 결과">
|
||
<h2 style={{ margin: 0, fontSize: '1.3rem' }}>최종 결과 · {END_KO[f.endReason]}</h2>
|
||
<table className="mj-deltas">
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">순위</th>
|
||
<th scope="col">이름</th>
|
||
<th scope="col" className="num">
|
||
점수
|
||
</th>
|
||
<th scope="col" className="num">
|
||
결과(우마·오카)
|
||
</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{f.ranking.map((r, i) => (
|
||
<tr key={r.player} className="anim-slide-up" style={{ '--anim-delay': `${i * 110}ms` } as CSSProperties}>
|
||
<td>{r.rank}위</td>
|
||
<td>
|
||
{nick(players, r.player)}
|
||
{r.player === me ? ' (나)' : ''}
|
||
</td>
|
||
<td className="num">{fmt(r.points)}</td>
|
||
<td className={`num ${r.score > 0 ? 'mj-plus' : r.score < 0 ? 'mj-minus' : ''}`}>
|
||
{r.score > 0 ? '+' : ''}
|
||
{r.score.toFixed(1)}
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
{f.bestHand && (
|
||
<p style={{ margin: 0 }}>
|
||
최고 화료: {nick(players, f.bestHand.player)}님 · {f.bestHand.yaku.filter((y) => !/^(도라|적도라|우라도라|북) /.test(y)).join(', ')} · {fmt(f.bestHand.points)}점
|
||
</p>
|
||
)}
|
||
<table className="mj-deltas small">
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">이름</th>
|
||
<th scope="col" className="num">
|
||
화료
|
||
</th>
|
||
<th scope="col" className="num">
|
||
방총
|
||
</th>
|
||
<th scope="col" className="num">
|
||
리치
|
||
</th>
|
||
<th scope="col" className="num">
|
||
울기
|
||
</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{f.perPlayer.map((p) => (
|
||
<tr key={p.player}>
|
||
<td>{nick(players, p.player)}</td>
|
||
<td className="num">{p.wins}</td>
|
||
<td className="num">{p.dealIns}</td>
|
||
<td className="num">{p.riichi}</td>
|
||
<td className="num">{p.calls}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
<span className="small muted">{f.rounds}국을 했어요. 점수는 이 방에서만 쓰는 놀이용 점수예요.</span>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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<MahjongView>) {
|
||
const [announce, setAnnounce] = useState('');
|
||
const [callout, setCallout] = useState<{ seq: number; text: string; call: string } | null>(null);
|
||
const [banner, setBanner] = useState<Banner | null>(null);
|
||
const [dealing, setDealing] = useState(false);
|
||
const [ref, width, mainH] = useBox<HTMLDivElement>();
|
||
const seen = useSeen(v);
|
||
const mine = isMyTurn(v, me);
|
||
const prevMine = useRef(false);
|
||
const snap = useRef<Snap | null>(null);
|
||
const bannerSeq = useRef(0);
|
||
const showBanner = (b: Omit<Banner, 'key'>) => 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 (
|
||
<div className={`mj${wide ? ' wide' : ''}`} ref={ref}>
|
||
<style>{CSS}</style>
|
||
<ul className="mj-opps" aria-label="다른 사람">
|
||
{others.map((s) => (
|
||
<SeatChip key={s.seat} v={v} s={s} players={players} me={me} deadline={deadline} w={phone ? 13 : 18} seen={seen} />
|
||
))}
|
||
</ul>
|
||
<div className="mj-main" style={wide ? { width: tableWidth, maxHeight: mainH > 0 ? mainH - 12 : undefined } : undefined}>
|
||
{v.phase === 'handResult' && v.result && <ResultPanel v={v} players={players} me={me} act={act} pending={pending} deadline={deadline} />}
|
||
{v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||
{showTable && (
|
||
<div className="mj-table-wrap">
|
||
<Table v={v} players={players} width={tableWidth} callout={callout ? <span key={callout.seq} className={`mj-callout c-${callout.call}`}>{callout.text}</span> : null} seen={seen} />
|
||
</div>
|
||
)}
|
||
</div>
|
||
{v.phase === 'playing' && v.my && <MyArea v={v} my={v.my} act={act} pending={pending} players={players} deadline={deadline} tapConfirm={tapConfirm} seen={seen} dealing={dealing} />}
|
||
{banner && (
|
||
<div key={banner.key} className={`mj-banner ${banner.kind}`} aria-hidden>
|
||
<span className="anim-banner">
|
||
{banner.text}
|
||
{banner.sub && <small>{banner.sub}</small>}
|
||
</span>
|
||
</div>
|
||
)}
|
||
<p className="sr-only" aria-live="polite">
|
||
{announce}
|
||
</p>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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 (
|
||
<div className="card mj-toggles" style={{ padding: 12 }}>
|
||
<strong>내 설정</strong>
|
||
<label>
|
||
<input type="checkbox" checked={p.autoWin} disabled={pending} onChange={(e) => act({ type: 'setPref', autoWin: e.target.checked })} />
|
||
자동 화료(쯔모·론을 바로 해요)
|
||
</label>
|
||
<label>
|
||
<input type="checkbox" checked={p.noCalls} disabled={pending} onChange={(e) => act({ type: 'setPref', noCalls: e.target.checked })} />
|
||
울기 안 함(퐁·치·깡은 자동 패스)
|
||
</label>
|
||
{v.options.beginnerMode && (
|
||
<label>
|
||
<input type="checkbox" checked={p.beginner} disabled={pending} onChange={(e) => act({ type: 'setPref', beginner: e.target.checked })} />
|
||
초보 모드(대기패·역 힌트)
|
||
</label>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProps<MahjongView>) {
|
||
const turnSeat = v.phase === 'playing' && v.stage !== 'claim' ? v.turn : null;
|
||
return (
|
||
<>
|
||
<style>{CSS}</style>
|
||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<strong>
|
||
{v.mode === 'sanma' ? '3인 마작(산마)' : '4인 마작'} · {v.options.length === 'tonpuu' ? '동풍전' : '반장전'}
|
||
</strong>
|
||
{turnSeat !== null && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={v.my?.seat === turnSeat} size={36} />}
|
||
</div>
|
||
<span className="small muted">
|
||
{roundLabel(v)} · 공탁 {fmt(v.riichiPool)}점 · 남은 패 {v.wallCount}장
|
||
</span>
|
||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||
{v.seats.map((s) => (
|
||
<li key={s.seat} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.left ? 0.6 : 1 }} aria-label={seatLabel(v, s, players, me)}>
|
||
<span className={`mj-badge ${s.isDealer ? 'mj-b-dealer' : 'mj-b-wind'}`} aria-hidden>
|
||
{WIND[s.wind]}
|
||
</span>
|
||
<Avatar user={userOf(players, s.id)} size={22} />
|
||
<span aria-hidden style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
|
||
{turnSeat === s.seat ? '▶ ' : ''}
|
||
{nick(players, s.id)}
|
||
{s.id === me ? ' (나)' : ''}
|
||
{s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||
</span>
|
||
{s.riichi && (
|
||
<span className="mj-badge mj-b-riichi" aria-hidden>
|
||
리치
|
||
</span>
|
||
)}
|
||
<strong aria-hidden style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||
<Bump value={s.points} />
|
||
</strong>
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</div>
|
||
<Toggles v={v} act={act} pending={pending} />
|
||
{v.history.length > 0 && (
|
||
<details className="card" open style={{ padding: 12 }}>
|
||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>국별 점수 변화</summary>
|
||
<ol className="mj-hist">
|
||
{[...v.history].reverse().map((h, i) => (
|
||
<li key={i}>
|
||
<strong>{h.label}</strong> {h.kind === 'agari' ? '화료' : h.kind === 'exhaustive' ? '유국' : '도중유국'} ·{' '}
|
||
{v.seats.map((s) => `${nick(players, s.id)} ${signed(h.deltas[s.seat]!)}`).join(' / ')}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</details>
|
||
)}
|
||
<details className="card" style={{ padding: 12 }}>
|
||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>역 목록</summary>
|
||
<YakuTable />
|
||
</details>
|
||
</>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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, PublicUser>): 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<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||
return (
|
||
<div className="segmented" role="group" aria-label={label}>
|
||
{options.map(([k, l]) => (
|
||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||
{l}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||
return (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>{label}</strong>
|
||
{children}
|
||
{help && <span className="small muted">{help}</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<MahjongOptions>) {
|
||
const [more, setMore] = useState(false);
|
||
const set = (patch: Partial<MahjongOptions>) => onChange({ ...o, ...patch });
|
||
return (
|
||
<div className="stack" style={{ gap: 16 }}>
|
||
<p className="small muted" style={{ margin: 0 }}>
|
||
4명이면 4인 마작, 3명이면 3인 마작(산마)으로 해요.
|
||
</p>
|
||
<Field label="대국 길이" help="동풍전 약 25분, 반장전 약 50분">
|
||
<Seg label="대국 길이" value={o.length} options={[['tonpuu', '동풍전'], ['hanchan', '반장전']]} onChange={(length) => set({ length })} />
|
||
</Field>
|
||
<Field label="타패 제한 시간" help={o.turnSeconds === 0 ? '무제한이면 울기·론 응답도 시간 없이 기다려요.' : undefined}>
|
||
<Seg label="타패 제한 시간" value={o.turnSeconds} options={[[10, '10초'], [15, '15초'], [20, '20초'], [30, '30초'], [60, '60초'], [0, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||
</Field>
|
||
<Field label="초보 모드 허용" help="켜면 각자 대기패·역 힌트를 켜고 끌 수 있어요.">
|
||
<Seg label="초보 모드 허용" value={o.beginnerMode} options={onOff} onChange={(beginnerMode) => set({ beginnerMode })} />
|
||
</Field>
|
||
<Field label="적도라(빨간 5)">
|
||
<Seg label="적도라" value={o.akaDora} options={[['auto', '기본(4인 3장 · 3인 2장)'], [0, '없음'], [2, '2장'], [3, '3장']]} onChange={(akaDora) => set({ akaDora })} />
|
||
</Field>
|
||
<Field label="울어도 탕야오(쿠이탕)">
|
||
<Seg label="쿠이탕" value={o.kuitan} options={onOff} onChange={(kuitan) => set({ kuitan })} />
|
||
</Field>
|
||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||
</button>
|
||
{more && (
|
||
<>
|
||
<Field label="시작 점수 / 반환점">
|
||
<div className="row">
|
||
<select className="input" aria-label="시작 점수" value={String(o.startPoints)} onChange={(e) => set({ startPoints: (e.target.value === 'auto' ? 'auto' : Number(e.target.value)) as MahjongOptions['startPoints'] })} style={{ maxWidth: 220 }}>
|
||
{POINTS.map((p) => (
|
||
<option key={p} value={p}>
|
||
시작 {pointLabel(p, '기본(4인 25,000 · 3인 35,000)')}
|
||
</option>
|
||
))}
|
||
</select>
|
||
<select className="input" aria-label="반환점" value={String(o.returnPoints)} onChange={(e) => set({ returnPoints: (e.target.value === 'auto' ? 'auto' : Number(e.target.value)) as MahjongOptions['returnPoints'] })} style={{ maxWidth: 220 }}>
|
||
{POINTS.map((p) => (
|
||
<option key={p} value={p}>
|
||
반환 {pointLabel(p, '기본(4인 30,000 · 3인 40,000)')}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
</Field>
|
||
<Field label="순위 우마">
|
||
<Seg
|
||
label="순위 우마"
|
||
value={o.uma}
|
||
options={[['auto', '기본'], ['none', '없음(4인)'], ['5-10', '5-10'], ['10-20', '10-20'], ['10-30', '10-30'], ['0', '없음(3인)'], ['15', '15(3인)']]}
|
||
onChange={(uma) => set({ uma })}
|
||
/>
|
||
</Field>
|
||
<Field label="동시 론">
|
||
<Seg label="동시 론" value={o.doubleRon} options={[['allow', '더블론 허용'], ['headBump', '머리튀기']]} onChange={(doubleRon) => set({ doubleRon })} />
|
||
</Field>
|
||
<Field label="3명 동시 론">
|
||
<Seg label="3명 동시 론" value={o.tripleRon} options={[['abort', '삼가화 유국'], ['allow', '모두 화료']]} onChange={(tripleRon) => set({ tripleRon })} />
|
||
</Field>
|
||
<Field label="친 연장 조건">
|
||
<Seg label="친 연장 조건" value={o.renchanOn} options={[['tenpai', '화료 또는 텐파이'], ['agari', '화료만']]} onChange={(renchanOn) => set({ renchanOn })} />
|
||
</Field>
|
||
{(
|
||
[
|
||
['tobi', '0점 미만이면 바로 종료(토비)'],
|
||
['agariYame', '올라스트 친 1위면 종료(아가리야메)'],
|
||
['westEntry', '반환점 넘는 사람이 없으면 연장(서입)'],
|
||
['kiriageMangan', '절상만관(4판30부·3판60부 → 만관)'],
|
||
['kazoeYakuman', '헤아림 역만(13판 이상)'],
|
||
['doubleYakuman', '더블 역만'],
|
||
['abortiveDraws', '도중유국(구종구패 등)'],
|
||
['nagashiMangan', '유국만관'],
|
||
['pao', '책임지불(대삼원·대사희)'],
|
||
['ankanChankanKokushi', '국사무쌍 안깡 창깡'],
|
||
] as const
|
||
).map(([k, label]) => (
|
||
<Field key={k} label={label}>
|
||
<Seg label={label} value={o[k]} options={onOff} onChange={(val) => set({ [k]: val } as Partial<MahjongOptions>)} />
|
||
</Field>
|
||
))}
|
||
<Field label="연풍패 머리 부수">
|
||
<Seg label="연풍패 머리 부수" value={o.renpuuPairFu} options={[[2, '2부'], [4, '4부']]} onChange={(renpuuPairFu) => set({ renpuuPairFu })} />
|
||
</Field>
|
||
{o.turnSeconds !== 0 && (
|
||
<>
|
||
<Field label="울기·론 응답 시간">
|
||
<Seg label="울기·론 응답 시간" value={o.claimSeconds} options={[[5, '5초'], [8, '8초'], [12, '12초'], [20, '20초']]} onChange={(claimSeconds) => set({ claimSeconds })} />
|
||
</Field>
|
||
<Field label="개인 예비 시간" help="타패 시간을 넘기면 깎이고, 매 국 5초씩 다시 채워져요.">
|
||
<Seg label="개인 예비 시간" value={o.timeBankSeconds} options={[[0, '없음'], [30, '30초'], [60, '60초'], [120, '120초']]} onChange={(timeBankSeconds) => set({ timeBankSeconds })} />
|
||
</Field>
|
||
</>
|
||
)}
|
||
<Field label="(3인) 쯔모 지불">
|
||
<Seg label="3인 쯔모 지불" value={o.sanmaTsumo} options={[['tsumoLoss', '쯔모손'], ['northBisection', '북가 몫 반씩']]} onChange={(sanmaTsumo) => set({ sanmaTsumo })} />
|
||
</Field>
|
||
<Field label="(3인) 본장 1개당">
|
||
<Seg label="3인 본장" value={o.sanmaHonba} options={[[200, '200점'], [300, '300점'], [1000, '1,000점']]} onChange={(sanmaHonba) => set({ sanmaHonba })} />
|
||
</Field>
|
||
<Field label="(3인) 유국 텐파이료 합계">
|
||
<Seg label="3인 텐파이료" value={o.sanmaNotenPool} options={[[2000, '2,000점'], [3000, '3,000점']]} onChange={(sanmaNotenPool) => set({ sanmaNotenPool })} />
|
||
</Field>
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<table className="mj-rules small" style={{ borderCollapse: 'collapse', width: '100%', marginTop: 8 }}>
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">역</th>
|
||
<th scope="col">조건</th>
|
||
<th scope="col">멘젠</th>
|
||
<th scope="col">울기</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{YAKU.map(([name, desc, closed, open]) => (
|
||
<tr key={name}>
|
||
<th scope="row" style={{ whiteSpace: 'nowrap' }}>
|
||
{name}
|
||
</th>
|
||
<td>{desc}</td>
|
||
<td>{closed === '역만' ? closed : `${closed}판`}</td>
|
||
<td>{open === '-' ? '안 됨' : open === '일부' ? open : `${open}판`}</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
);
|
||
}
|
||
|
||
function Rules({ options }: { options?: MahjongOptions }) {
|
||
const o = options;
|
||
return (
|
||
<div className="stack">
|
||
<p>
|
||
<strong>리치 마작</strong>이에요. 손패 13장에 1장을 더해 <strong>면자 4개 + 머리 1개</strong>(면자 = 같은 패 3장 또는 같은 종류 연속 3장, 머리 = 같은 패 2장)를 먼저 만들면 화료예요. 칠대자(대자 7개)와
|
||
국사무쌍도 화료형이에요.
|
||
</p>
|
||
<div className="row" style={{ gap: 4 }} aria-label="화료형 예: 2·3·4만, 5·6·7통, 6·7·8삭, 2·2통, 3·4·5삭">
|
||
{['2m', '3m', '4m', '5p', '6p', '7p', '6s', '7s', '8s', '2p', '2p', '3s', '4s', '5s'].map((t, i) => (
|
||
<Tile key={i} code={t} w={26} />
|
||
))}
|
||
</div>
|
||
<p>
|
||
차례가 오면 1장을 가져오고(쯔모) 1장을 버려요. 남이 버린 패로 <strong>퐁</strong>(같은 패 2장 + 1), <strong>치</strong>(왼쪽 사람 패로 연속 3장, 3인은 안 됨), <strong>깡</strong>(같은 패 4장)을 할 수 있지만,
|
||
울면 리치를 못 하고 일부 역의 판수가 내려가요.
|
||
</p>
|
||
<p>
|
||
<strong>역이 1개 이상</strong> 있어야 화료할 수 있어요. 도라는 역이 아니에요. 가장 쉬운 역은 <strong>리치</strong>(울지 않고 텐파이하면 1,000점을 내고 선언), <strong>탕야오</strong>(2~8만으로), <strong>역패</strong>(백·발·중
|
||
같은 패 3장)예요.
|
||
</p>
|
||
<p>
|
||
<strong>후리텐</strong>: 내가 기다리는 패를 전에 버린 적이 있거나, 방금 론할 수 있었는데 넘겼다면 론할 수 없어요(쯔모는 돼요).
|
||
</p>
|
||
<p>
|
||
점수는 판(역 + 도라)과 부(손 모양)로 계산해요. 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점'}, 마지막에 순위 우마와 오카를 더해 결과를 내요.
|
||
</p>
|
||
<p>
|
||
<strong>3인(산마)</strong>: 2만~8만이 없고, 치를 못 해요. 북은 옆에 빼고(북 뽑기) 1장을 더 가져올 수 있어요. 뺀 북은 도라 1개예요.
|
||
</p>
|
||
<YakuTable />
|
||
<p className="small muted">점수는 이 방에서만 쓰는 놀이용 점수예요. 재화나 포인트로 바뀌지 않아요.</p>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const ui: GameUI<MahjongView, MahjongOptions> = {
|
||
Board: MahjongBoard,
|
||
Side: MahjongSide,
|
||
statusText,
|
||
isMyTurn,
|
||
Options,
|
||
optionsSummary,
|
||
Rules,
|
||
quickStart,
|
||
helpNow,
|
||
};
|
||
|
||
export default ui;
|