877 lines
38 KiB
TypeScript
877 lines
38 KiB
TypeScript
/** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */
|
||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||
import { Link, useNavigate, useParams } from 'react-router';
|
||
import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botChatRequired, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||
import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui';
|
||
import { GuestWarning, NicknameForm } from '../components/NicknameForm';
|
||
import { GameNotice, gameName } from '../components/GameNotice';
|
||
import { QrModal } from '../components/QrModal';
|
||
import { SettingsPopup } from '../components/SettingsPopup';
|
||
import { api, type RoomPreview } from '../net/api';
|
||
import { socket, useRoom } from '../net/socket';
|
||
import { useSession } from '../store/session';
|
||
import { OptionSync, withLocks } from '../lib/option-sync';
|
||
import { loadGameUI } from '../games/registry';
|
||
import type { GameUI } from '../games/types';
|
||
import { sounds, useChatSound } from '../lib/feedback';
|
||
import { ChatPanel, EmoteBubbles, useChatSeen } from '../components/ChatPanel';
|
||
import { BotActivity } from '../components/BotActivity';
|
||
import { VolumeControl } from '../components/VolumeControl';
|
||
import { useWide } from '../lib/media';
|
||
import { GameHelp } from '../components/GameHelp';
|
||
import { PlayerName } from '../components/PlayerCard';
|
||
import { useMotionScope } from '../lib/motion';
|
||
|
||
export default function RoomPage() {
|
||
const { code = '' } = useParams();
|
||
const me = useSession((s) => s.me);
|
||
const nav = useNavigate();
|
||
const [preview, setPreview] = useState<RoomPreview | null>(null);
|
||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!/^\d{6}$/.test(code)) {
|
||
setPreviewError('방 코드가 올바르지 않아요.');
|
||
return;
|
||
}
|
||
if (!me) api.room(code).then(setPreview, (e) => setPreviewError((e as Error).message));
|
||
}, [code, me]);
|
||
|
||
useEffect(() => {
|
||
if (!me || !/^\d{6}$/.test(code)) return;
|
||
socket.join(code);
|
||
return () => socket.detach(code);
|
||
}, [code, me]);
|
||
|
||
if (!me) {
|
||
return (
|
||
<>
|
||
<TopBar title="방에 들어가기" onBack={() => nav('/')} />
|
||
<main className="page">
|
||
{previewError ? (
|
||
<RoomGone message={previewError} />
|
||
) : (
|
||
<section className="card stack">
|
||
{preview ? (
|
||
<>
|
||
<h1>
|
||
{gameName(preview.gameId)} 방에 초대받았어요
|
||
</h1>
|
||
<p className="muted">
|
||
방장 {preview.host} · {preview.seated}/{preview.maxPlayers}명 · 코드 {preview.codeLabel}
|
||
</p>
|
||
</>
|
||
) : (
|
||
<p className="muted">방 정보를 불러오는 중…</p>
|
||
)}
|
||
<NicknameForm next={`/r/${code}`} submitLabel="이 이름으로 입장하기" />
|
||
</section>
|
||
)}
|
||
</main>
|
||
</>
|
||
);
|
||
}
|
||
return <Room code={code} me={me} />;
|
||
}
|
||
|
||
function RoomGone({ message }: { message: string }) {
|
||
const nav = useNavigate();
|
||
return (
|
||
<section className="card stack">
|
||
<h1>{message}</h1>
|
||
<button className="btn btn-primary btn-block" onClick={() => nav('/j')}>
|
||
다른 코드 입력하기
|
||
</button>
|
||
<button className="btn btn-secondary btn-block" onClick={() => nav('/')}>
|
||
홈으로
|
||
</button>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
function Room({ code, me }: { code: string; me: PublicUser }) {
|
||
const nav = useNavigate();
|
||
const { room, game, result, status, joinError, pending, slow } = useRoom();
|
||
const [ui, setUi] = useState<GameUI | null>(null);
|
||
const [leaveAsk, setLeaveAsk] = useState(false);
|
||
const [chatOpen, setChatOpen] = useState(false);
|
||
// Under 1100px there is no chat column (Lobby/GameView), so the bar carries a 💬 button — phones and narrowed PC windows alike.
|
||
const wide = useWide();
|
||
// 설정 opens as a popup over the room: going to /me would unmount the room and detach from it.
|
||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||
const closeSettings = useCallback(() => setSettingsOpen(false), []);
|
||
// 규칙 too: going to /rules would leave the room page (and, alone in a lobby, the room itself).
|
||
const [rulesOpen, setRulesOpen] = useState(false);
|
||
// [한 판 더] takes me back to this room's lobby after game N (kept per tab so a reload stays there).
|
||
const lobbyKey = `bg:lobby:${code}`;
|
||
const [lobbyAfter, setLobbyAfter] = useState<number | null>(() => Number(sessionStorage.getItem(lobbyKey)) || null);
|
||
const gameId = room?.gameId;
|
||
|
||
useEffect(() => {
|
||
if (gameId) loadGameUI(gameId).then(setUi);
|
||
}, [gameId]);
|
||
|
||
const players = useMemo(() => {
|
||
const map: Record<string, PublicUser> = {};
|
||
for (const s of room?.seats ?? []) if (s) map[s.user.id] = s.user;
|
||
for (const u of room?.spectators ?? []) map[u.id] = u;
|
||
return map;
|
||
}, [room]);
|
||
|
||
useTurnTitle(ui, game?.view, me.id);
|
||
// Every new room chat line (mine too, like StarCraft) plays the chat sound; history resent on joining does not.
|
||
const lastLiveChat = useRoom((s) => {
|
||
const l = s.chat.at(-1);
|
||
return l?.live ? l.id : undefined;
|
||
});
|
||
useChatSound(lastLiveChat);
|
||
// Inside a room the room bar replaces the site header, so the board gets that height back.
|
||
useEffect(() => {
|
||
document.documentElement.classList.add('in-room');
|
||
return () => document.documentElement.classList.remove('in-room');
|
||
}, []);
|
||
|
||
if (status === 'replaced') {
|
||
return (
|
||
<main className="page">
|
||
<section className="card stack">
|
||
<h1>다른 창에서 이 방을 열었어요</h1>
|
||
<p className="muted">한 번에 한 창에서만 할 수 있어요.</p>
|
||
<button className="btn btn-primary btn-block" onClick={() => socket.reclaim()}>
|
||
여기서 계속하기
|
||
</button>
|
||
</section>
|
||
</main>
|
||
);
|
||
}
|
||
if (joinError) {
|
||
return (
|
||
<>
|
||
<TopBar title="방" onBack={() => nav('/')} />
|
||
<main className="page">
|
||
<RoomGone message={joinError} />
|
||
</main>
|
||
</>
|
||
);
|
||
}
|
||
if (!room || room.code !== code || !ui) {
|
||
return (
|
||
<>
|
||
<TopBar title={`방 ${formatRoomCode(code)}`} onBack={() => nav('/')} />
|
||
<main className="page muted">방에 들어가는 중…</main>
|
||
</>
|
||
);
|
||
}
|
||
|
||
const g = { nameKo: gameName(room.gameId) };
|
||
const backInLobby = room.status === 'finished' && lobbyAfter === room.gameNo;
|
||
const inGame = room.status === 'playing' || room.status === 'paused' || (room.status === 'finished' && !!game && !backInLobby);
|
||
const toLobby = () => {
|
||
sessionStorage.setItem(lobbyKey, String(room.gameNo));
|
||
setLobbyAfter(room.gameNo);
|
||
// Seated people come back ready, so the host sees who wants another game.
|
||
const seat = room.seats.find((s) => s?.user.id === me.id);
|
||
if (seat && room.hostId !== me.id && !seat.ready) socket.send({ t: 'ready', ready: true });
|
||
};
|
||
// Games with their own chat channels (마피아) close the room chat while playing (the server refuses it too).
|
||
const roomChatClosed = !!ui.ownChat && (room.status === 'playing' || room.status === 'paused');
|
||
const doLeave = () => {
|
||
socket.leave();
|
||
nav('/');
|
||
};
|
||
// Leaving mid-game forfeits, so only that case asks first; otherwise one tap leaves.
|
||
const forfeits = room.status === 'playing' && room.seats.some((s) => s?.user.id === me.id);
|
||
const askLeave = () => (forfeits ? setLeaveAsk(true) : doLeave());
|
||
|
||
return (
|
||
<>
|
||
<nav className="room-bar" aria-label="방 메뉴">
|
||
<h1 className="sr-only">
|
||
{g.nameKo} 방 {formatRoomCode(code)}
|
||
</h1>
|
||
<div className="room-bar-inner">
|
||
{/* No ⋯ menu: every room action sits on this bar. Phones stack icon over a short label (.rb-btn). */}
|
||
{/* ← 홈 leaves the room, same as [나가기]. */}
|
||
<button className="btn btn-ghost btn-sm rb-btn" onClick={askLeave} aria-label="방 나가고 홈으로">
|
||
<span className="rb-ico">←</span>
|
||
<span className="rb-lbl">홈</span>
|
||
</button>
|
||
<strong className="rb-game" style={{ fontSize: '1.1rem' }}>
|
||
{g.nameKo}
|
||
</strong>
|
||
<CopyButton
|
||
text={`${location.origin}/r/${code}`}
|
||
label={
|
||
<>
|
||
<span className="rb-ico">🔗</span>
|
||
<span className="rb-lbl">
|
||
<span className="wide-only">
|
||
방 <CodeLabel code={code} />
|
||
</span>
|
||
<span className="phone-only">링크</span>
|
||
</span>
|
||
</>
|
||
}
|
||
done={
|
||
<>
|
||
<span className="rb-ico">✓</span>
|
||
<span className="rb-lbl">복사됨</span>
|
||
</>
|
||
}
|
||
className="btn btn-ghost btn-sm rb-btn"
|
||
/>
|
||
<span style={{ flex: 1 }} />
|
||
{!roomChatClosed && !wide && <ChatButton onOpen={() => setChatOpen(true)} />}
|
||
<VolumeControl className="btn btn-ghost btn-sm rb-btn" label />
|
||
<button className="btn btn-ghost btn-sm rb-btn" onClick={() => setRulesOpen(true)} aria-haspopup="dialog" aria-label="규칙 보기">
|
||
<span className="rb-ico">📖</span>
|
||
<span className="rb-lbl">규칙</span>
|
||
</button>
|
||
<button className="btn btn-ghost btn-sm rb-btn" onClick={() => setSettingsOpen(true)} aria-haspopup="dialog" aria-label="글자 크기 · 소리 설정">
|
||
<span className="rb-ico">⚙️</span>
|
||
<span className="rb-lbl">설정</span>
|
||
</button>
|
||
<button className="btn btn-danger btn-sm rb-btn" onClick={askLeave} aria-label="🚪 나가기">
|
||
<span className="rb-ico">🚪</span>
|
||
<span className="rb-lbl">나가기</span>
|
||
</button>
|
||
</div>
|
||
</nav>
|
||
{inGame && game ? (
|
||
<GameView room={room} ui={ui} me={me} players={players} pending={pending !== null} slow={slow} />
|
||
) : (
|
||
<Lobby room={room} ui={ui} me={me} />
|
||
)}
|
||
{room.status === 'finished' && result && game && !backInLobby && <ResultPanel room={room} me={me} players={players} onLeave={doLeave} onAgain={toLobby} />}
|
||
<EmoteBubbles room={room} />
|
||
{chatOpen && !roomChatClosed && !wide && (
|
||
<Sheet onClose={() => setChatOpen(false)} label="채팅">
|
||
<ChatPanel room={room} me={me} />
|
||
<button className="btn btn-secondary btn-block" onClick={() => setChatOpen(false)}>
|
||
닫기
|
||
</button>
|
||
</Sheet>
|
||
)}
|
||
{settingsOpen && <SettingsPopup onClose={closeSettings} />}
|
||
{rulesOpen && (
|
||
<Sheet onClose={() => setRulesOpen(false)} label={`${gameName(room.gameId)} 규칙`}>
|
||
<h2>{gameName(room.gameId)} 규칙</h2>
|
||
<GameNotice gameId={room.gameId} />
|
||
{ui ? <ui.Rules options={room.options} /> : <p className="muted">불러오는 중…</p>}
|
||
<button type="button" className="btn btn-secondary btn-block" onClick={() => setRulesOpen(false)}>
|
||
닫기
|
||
</button>
|
||
</Sheet>
|
||
)}
|
||
{leaveAsk && (
|
||
<ConfirmSheet
|
||
title="방에서 나갈까요?"
|
||
body="게임 중에 나가면 기권으로 처리돼요."
|
||
confirm="나가기"
|
||
danger
|
||
onConfirm={doLeave}
|
||
onClose={() => setLeaveAsk(false)}
|
||
/>
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
/** Blink the tab title when it's my turn and the tab is hidden (docs/07 §6). */
|
||
function useTurnTitle(ui: GameUI | null, view: unknown, me: string) {
|
||
const myTurn = !!ui && !!view && ui.isMyTurn(view, me);
|
||
const prev = useRef(false);
|
||
useEffect(() => {
|
||
if (myTurn && !prev.current && document.visibilityState === 'hidden') sounds.myTurn();
|
||
prev.current = myTurn;
|
||
if (!myTurn) return;
|
||
const base = document.title;
|
||
let on = false;
|
||
const t = setInterval(() => {
|
||
if (document.visibilityState === 'visible') {
|
||
document.title = base;
|
||
return;
|
||
}
|
||
on = !on;
|
||
document.title = on ? '● 내 차례예요' : base;
|
||
}, 1000);
|
||
return () => {
|
||
clearInterval(t);
|
||
document.title = base;
|
||
};
|
||
}, [myTurn]);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- lobby
|
||
|
||
function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser }) {
|
||
const [qr, setQr] = useState(false);
|
||
const [settings, setSettings] = useState(false);
|
||
const isHost = room.hostId === me.id;
|
||
const mySeat = room.seats.findIndex((s) => s?.user.id === me.id);
|
||
const seated = room.seats.filter(Boolean).length;
|
||
const need = Math.max(0, room.minPlayers - seated);
|
||
const url = `${location.origin}/r/${room.code}`;
|
||
const gName = gameName(room.gameId);
|
||
const host = room.seats.find((s) => s?.user.id === room.hostId)?.user.nickname ?? me.nickname;
|
||
const shareText = `${host}님이 ${gName} 방에 초대했어요! 코드 ${formatRoomCode(room.code)}`;
|
||
const notReady = room.seats.filter((s) => s && !s.ready && s.user.id !== room.hostId).length;
|
||
const [askStart, setAskStart] = useState(false);
|
||
// Computer players (docs/06 §12): the host fills empty seats; a room with them is a practice room.
|
||
const canAddBot = isHost && botsAllowed(room.gameId);
|
||
const practice = room.seats.some((s) => s && isBotId(s.user.id));
|
||
// Offered on the first empty seat only, so big rooms don't show a column of the same button.
|
||
const firstEmpty = room.seats.findIndex((s) => s === null);
|
||
|
||
const wide = useWide();
|
||
// Only while a seat is empty: once everyone is in, the room bar's link button is enough.
|
||
const invite = firstEmpty >= 0 && (
|
||
<section className="card stack invite-card" style={{ textAlign: 'center' }} aria-label="초대하기">
|
||
<p className="muted invite-label">친구에게 이 코드를 알려 주세요</p>
|
||
<p className="invite-code" style={{ fontSize: '3.2rem', fontWeight: 800, lineHeight: 1.1 }}>
|
||
<CodeLabel code={room.code} />
|
||
</p>
|
||
{/* QR lives on the empty seat button ("+ 빈자리 · QR로 초대"), so this row stays two buttons. */}
|
||
<div className="invite-buttons" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
|
||
<CopyButton text={url} label="🔗 링크 복사" />
|
||
<ShareButton title={`${gName} 같이 해요`} text={shareText} url={url} />
|
||
</div>
|
||
</section>
|
||
);
|
||
const seats = (
|
||
<section className="stack" aria-label="자리">
|
||
<h2>
|
||
자리 ({seated}/{room.maxPlayers})
|
||
</h2>
|
||
{/* PC: seats are the main column of the lobby, two or three cards per row. */}
|
||
<div style={{ display: 'grid', gridTemplateColumns: wide ? `repeat(${room.seats.length > 4 ? 3 : 2}, minmax(0, 1fr))` : '1fr', gap: 10 }}>
|
||
{room.seats.map((s, i) =>
|
||
s && isBotId(s.user.id) ? (
|
||
<div key={i} className="card stack" style={{ gap: 10 }}>
|
||
<div className="row" style={{ gap: 12, flexWrap: 'nowrap' }}>
|
||
<Avatar user={s.user} size={44} />
|
||
<div style={{ flex: 1, minWidth: 0 }}>
|
||
<div style={{ fontWeight: 700 }}>{s.user.nickname}</div>
|
||
<div className="row small" style={{ gap: 6 }}>
|
||
<span className="badge">🤖 컴퓨터</span>
|
||
{!isHost && <span className="badge">난이도 {BOT_PICK_LABEL[room.botPicks?.[s.user.id] ?? 'random']}</span>}
|
||
</div>
|
||
</div>
|
||
{isHost && (
|
||
<button className="btn btn-ghost" onClick={() => socket.send({ t: 'removeBot', userId: s.user.id })} aria-label={`${s.user.nickname} 빼기`}>
|
||
✕
|
||
</button>
|
||
)}
|
||
</div>
|
||
{/* docs/06 §12: 랜덤 = any level 1~60; a band = a random level inside it. The level shows after the game. */}
|
||
{isHost && (
|
||
<div className="segmented bot-level" role="group" aria-label={`${s.user.nickname} 난이도`}>
|
||
{BOT_PICKS.map((p) => (
|
||
<button
|
||
key={p}
|
||
type="button"
|
||
aria-pressed={(room.botPicks?.[s.user.id] ?? 'random') === p}
|
||
disabled={room.starting}
|
||
title={p === 'random' ? '1~60단계 중 무작위' : `${BOT_BANDS[p][0]}~${BOT_BANDS[p][1]}단계 중 무작위`}
|
||
onClick={() => socket.send({ t: 'botLevel', userId: s.user.id, pick: p })}
|
||
>
|
||
{BOT_PICK_LABEL[p]}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)}
|
||
</div>
|
||
) : s ? (
|
||
<div key={i} className="card row" style={{ gap: 12, flexWrap: 'nowrap' }}>
|
||
<Avatar user={s.user} size={44} />
|
||
<div style={{ flex: 1, minWidth: 0 }}>
|
||
<div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||
{room.hostId === s.user.id && <span aria-label="방장">👑 </span>}
|
||
<PlayerName user={s.user} gameId={room.gameId} session={room.sessionStats[s.user.id]} />
|
||
{s.user.id === me.id && <span className="muted small"> (나)</span>}
|
||
</div>
|
||
<div className="row small" style={{ gap: 6 }}>
|
||
<span className="dot" style={{ background: s.connected ? 'var(--success)' : s.away ? 'var(--text-sub)' : 'var(--warning)' }} />
|
||
{s.connected ? '접속 중' : s.away ? '자리 비움' : '연결 끊김'}
|
||
{room.hostId !== s.user.id && (s.ready ? <span className="badge success">준비 완료</span> : <span className="badge">준비 중</span>)}
|
||
</div>
|
||
</div>
|
||
{isHost && s.user.id !== me.id && <HostMenu room={room} target={s.user} />}
|
||
</div>
|
||
) : (
|
||
<div key={i} className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
|
||
<button className="card row" style={{ flex: 1, border: '2px dashed var(--border)', boxShadow: 'none', cursor: 'pointer', minHeight: 76, justifyContent: 'center', color: 'var(--text-sub)' }} onClick={() => (mySeat < 0 ? socket.send({ t: 'seat', seat: i }) : setQr(true))}>
|
||
{mySeat < 0 ? '+ 여기 앉기' : '+ 빈자리 · 📷 QR로 초대'}
|
||
</button>
|
||
{canAddBot && i === firstEmpty && !wide && (
|
||
<button className="btn btn-secondary" style={{ minHeight: 76 }} onClick={() => socket.send({ t: 'addBot', seat: i })}>
|
||
🤖 컴퓨터 넣기
|
||
</button>
|
||
)}
|
||
</div>
|
||
),
|
||
)}
|
||
</div>
|
||
{room.spectators.length > 0 && (
|
||
<p className="muted small">
|
||
관전 {room.spectators.length}명:{' '}
|
||
{room.spectators.map((u, i) => (
|
||
<span key={u.id}>
|
||
{i > 0 && ', '}
|
||
<PlayerName user={u} gameId={room.gameId} />
|
||
</span>
|
||
))}
|
||
</p>
|
||
)}
|
||
{((wide && canAddBot && firstEmpty >= 0) || (mySeat >= 0 && room.allowSpectators)) && (
|
||
<div className="row">
|
||
{wide && canAddBot && firstEmpty >= 0 && (
|
||
<button className="btn btn-secondary" onClick={() => socket.send({ t: 'addBot', seat: firstEmpty })}>
|
||
🤖 컴퓨터 넣기
|
||
</button>
|
||
)}
|
||
{mySeat >= 0 && room.allowSpectators && (
|
||
<button className="btn btn-ghost" onClick={() => socket.send({ t: 'unseat' })}>
|
||
관전으로 바꾸기
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
</section>
|
||
);
|
||
const settingsCard = (
|
||
<section className="card stack">
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<div>
|
||
<h2>게임 설정</h2>
|
||
<p className="muted">{ui.optionsSummary(room.options)}</p>
|
||
</div>
|
||
{!wide && (
|
||
<button className="btn btn-secondary btn-sm" onClick={() => setSettings(true)}>
|
||
{isHost ? '설정 바꾸기' : '설정 보기'}
|
||
</button>
|
||
)}
|
||
</div>
|
||
{!isHost && <p className="muted small">👑 설정은 방장만 바꿀 수 있어요. 여기서는 볼 수만 있어요.</p>}
|
||
{practice && <p className="small">🤖 연습 게임이에요. 기록에는 남지 않아요.</p>}
|
||
{room.lockedOptions.length > 0 && <p className="muted small">🔒 일부 규칙은 관리자가 정해 두어서 바꿀 수 없어요.</p>}
|
||
<GameNotice gameId={room.gameId} />
|
||
{wide && <SettingsForm room={room} ui={ui} inline readOnly={!isHost} />}
|
||
</section>
|
||
);
|
||
const guestLine = me.kind === 'guest' && !practice && <GuestWarning short />;
|
||
const action = (
|
||
<div className="bottom-bar inline-wide">
|
||
<div className="bottom-bar-inner">
|
||
{isHost ? (
|
||
<button className="btn btn-primary" style={{ minHeight: 64, fontSize: '1.2rem' }} disabled={need > 0 || room.starting} onClick={() => (notReady > 0 ? setAskStart(true) : socket.send({ t: 'start' }))}>
|
||
{room.starting ? '🃏 섞는 중…' : need > 0 ? `${need}명 더 필요해요` : '▶ 게임 시작'}
|
||
</button>
|
||
) : mySeat >= 0 ? (
|
||
room.seats[mySeat]!.ready ? (
|
||
<button className="btn btn-secondary" style={{ minHeight: 64 }} onClick={() => socket.send({ t: 'ready', ready: false })}>
|
||
준비 취소
|
||
</button>
|
||
) : (
|
||
<button className="btn btn-success" style={{ minHeight: 64, fontSize: '1.2rem' }} onClick={() => socket.send({ t: 'ready', ready: true })}>
|
||
✓ 준비하기
|
||
</button>
|
||
)
|
||
) : (
|
||
<button className="btn btn-primary" style={{ minHeight: 64 }} disabled={!room.seats.some((s) => s === null)} onClick={() => socket.send({ t: 'seat' })}>
|
||
{room.seats.some((s) => s === null) ? '자리에 앉기' : '자리가 다 찼어요 (관전 중)'}
|
||
</button>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
|
||
return (
|
||
<main className="page">
|
||
{/* PC: invite → seats → start → chat down the main column (the people), game settings on the side. */}
|
||
<div className="two-col lobby">
|
||
<div className="stack" style={{ gap: 20 }}>
|
||
{invite}
|
||
{seats}
|
||
{wide ? action : settingsCard}
|
||
{wide && guestLine}
|
||
{wide && <ChatPanel room={room} me={me} />}
|
||
</div>
|
||
<div className="stack" style={{ gap: 16 }}>
|
||
{wide ? settingsCard : action}
|
||
{!wide && guestLine}
|
||
</div>
|
||
</div>
|
||
|
||
{qr && <QrModal url={url} code={room.code} onClose={() => setQr(false)} />}
|
||
{settings && <SettingsSheet room={room} ui={ui} readOnly={!isHost} onClose={() => setSettings(false)} />}
|
||
{askStart && (
|
||
<ConfirmSheet title="준비 안 된 사람이 있어요" body="그래도 시작할까요?" confirm="시작하기" onConfirm={() => socket.send({ t: 'start' })} onClose={() => setAskStart(false)} />
|
||
)}
|
||
</main>
|
||
);
|
||
}
|
||
|
||
function HostMenu({ room, target }: { room: RoomView; target: PublicUser }) {
|
||
const [open, setOpen] = useState(false);
|
||
const [kick, setKick] = useState(false);
|
||
void room;
|
||
return (
|
||
<>
|
||
<button className="btn btn-ghost" onClick={() => setOpen(true)} aria-label={`${target.nickname} 관리`}>
|
||
⋯
|
||
</button>
|
||
{open && (
|
||
<Sheet onClose={() => setOpen(false)} label={`${target.nickname} 관리`}>
|
||
<h2>{target.nickname}</h2>
|
||
<button className="btn btn-secondary btn-block" onClick={() => (socket.send({ t: 'host', userId: target.id }), setOpen(false))}>
|
||
👑 방장 넘기기
|
||
</button>
|
||
<button className="btn btn-danger btn-block" onClick={() => (setOpen(false), setKick(true))}>
|
||
내보내기
|
||
</button>
|
||
</Sheet>
|
||
)}
|
||
{kick && (
|
||
<ConfirmSheet
|
||
title={`${target.nickname}님을 내보낼까요?`}
|
||
body="내보낸 사람은 이 방에 다시 들어올 수 없어요."
|
||
confirm="내보내기"
|
||
danger
|
||
onConfirm={() => socket.send({ t: 'kick', userId: target.id })}
|
||
onClose={() => setKick(false)}
|
||
/>
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
function SettingsSheet({ room, ui, readOnly, onClose }: { room: RoomView; ui: GameUI; readOnly: boolean; onClose: () => void }) {
|
||
return (
|
||
<Sheet onClose={onClose} label="게임 설정">
|
||
<h2>게임 설정</h2>
|
||
{readOnly && <p className="muted small">👑 설정은 방장만 바꿀 수 있어요.</p>}
|
||
<SettingsForm room={room} ui={ui} readOnly={readOnly} onDone={onClose} />
|
||
</Sheet>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Game options + room options. Inline on PC, in a sheet on narrow screens.
|
||
* Host: every change is sent right away, so [게임 시작] always uses what is on screen.
|
||
* Everyone else (`readOnly`): the same form showing the room's current options, with every control locked
|
||
* (only "▼ 자세한 설정" still opens, so the hidden rules can be read too). The server refuses non-host config anyway.
|
||
*/
|
||
function SettingsForm({ room, ui, inline, readOnly, onDone }: { room: RoomView; ui: GameUI; inline?: boolean; readOnly?: boolean; onDone?: () => void }) {
|
||
const [options, setOptions] = useState(room.options);
|
||
const sync = useRef(new OptionSync());
|
||
useEffect(() => {
|
||
if (sync.current.received(room.options)) setOptions(room.options);
|
||
}, [room.options]);
|
||
const changeOptions = (next: typeof options) => {
|
||
// Admin-locked rules keep the room's value, exactly as the server will (so the echo matches).
|
||
const out = withLocks(next, room.options, room.lockedOptions);
|
||
sync.current.sent(room.options, out);
|
||
setOptions(out);
|
||
socket.send({ t: 'config', options: out });
|
||
};
|
||
const seg = (value: boolean, set: (v: boolean) => void, on: string, off: string) => (
|
||
<div className="segmented">
|
||
<button type="button" aria-pressed={value} onClick={() => set(true)}>
|
||
{on}
|
||
</button>
|
||
<button type="button" aria-pressed={!value} onClick={() => set(false)}>
|
||
{off}
|
||
</button>
|
||
</div>
|
||
);
|
||
return (
|
||
<div className="stack" style={{ gap: 14 }}>
|
||
{!readOnly && room.lockedOptions.length > 0 && <p className="muted small">🔒 관리자가 고정한 규칙은 바꿔도 저장되지 않아요.</p>}
|
||
{readOnly ? (
|
||
<ReadOnlyControls>
|
||
<ui.Options value={room.options} onChange={() => {}} />
|
||
</ReadOnlyControls>
|
||
) : (
|
||
<ui.Options value={options} onChange={changeOptions} />
|
||
)}
|
||
<hr style={{ border: 0, borderTop: '1px solid var(--border)', width: '100%' }} />
|
||
<div style={{ display: 'grid', gridTemplateColumns: inline ? 'repeat(2, minmax(0, 1fr))' : '1fr', gap: 12 }}>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>관전</strong>
|
||
{readOnly ? <ReadOnlyControls>{seg(room.allowSpectators, () => {}, '허용', '안 됨')}</ReadOnlyControls> : seg(room.allowSpectators, (allowSpectators) => socket.send({ t: 'config', allowSpectators }), '허용', '안 됨')}
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>채팅</strong>
|
||
{readOnly ? <ReadOnlyControls>{seg(room.chatEnabled, () => {}, '켜기', '끄기')}</ReadOnlyControls> : seg(room.chatEnabled, (chatEnabled) => socket.send({ t: 'config', chatEnabled }), '켜기', '끄기')}
|
||
</div>
|
||
{botsAllowed(room.gameId) && (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>컴퓨터 채팅</strong>
|
||
{botChatRequired(room.gameId) ? (
|
||
<p className="muted small" style={{ margin: 0 }}>
|
||
항상 켜짐 · 이 게임은 컴퓨터도 말해야 할 수 있어요
|
||
</p>
|
||
) : readOnly ? (
|
||
<ReadOnlyControls>{seg(room.botChat, () => {}, '켜기', '끄기')}</ReadOnlyControls>
|
||
) : (
|
||
seg(room.botChat, (botChat) => socket.send({ t: 'config', botChat }), '켜기', '끄기')
|
||
)}
|
||
{!botChatRequired(room.gameId) && <span className="muted small">켜면 컴퓨터가 게임하면서 먼저 말을 걸고, 채팅에 대답해요.</span>}
|
||
</div>
|
||
)}
|
||
</div>
|
||
{!inline && (
|
||
<button className="btn btn-primary btn-block" onClick={onDone}>
|
||
닫기
|
||
</button>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Locks every control inside (each game's options form has its own buttons, selects and inputs), except
|
||
* disclosure toggles (`aria-expanded`, e.g. "▼ 자세한 설정") so hidden rules can still be opened and read.
|
||
* Re-locks whatever the form renders later (opening "자세한 설정" adds new controls).
|
||
*/
|
||
function ReadOnlyControls({ children }: { children: ReactNode }) {
|
||
const ref = useRef<HTMLDivElement>(null);
|
||
useLayoutEffect(() => {
|
||
const root = ref.current!;
|
||
const lock = () => {
|
||
root.querySelectorAll<HTMLButtonElement | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>('button:not([aria-expanded]), input, select, textarea').forEach((el) => {
|
||
if (!el.disabled) el.disabled = true;
|
||
});
|
||
};
|
||
lock();
|
||
const mo = new MutationObserver(lock);
|
||
mo.observe(root, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled'] });
|
||
return () => mo.disconnect();
|
||
}, []);
|
||
return (
|
||
<div ref={ref} className="options-view">
|
||
{children}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- game
|
||
|
||
function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui: GameUI; me: PublicUser; players: Record<string, PublicUser>; pending: boolean; slow: boolean }) {
|
||
const game = useRoom((s) => s.game)!;
|
||
const tapConfirm = useSession((s) => s.settings.tapConfirm);
|
||
const wide = useWide();
|
||
const layout = useRef<HTMLDivElement>(null);
|
||
useMotionScope(layout);
|
||
const myTurn = ui.isMyTurn(game.view, me.id);
|
||
const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined;
|
||
const props = {
|
||
view: game.view,
|
||
me: me.id,
|
||
players,
|
||
act: (a: unknown) => socket.act(a),
|
||
pending,
|
||
deadline: game.deadline,
|
||
active: game.active,
|
||
tapConfirm,
|
||
};
|
||
const status = (
|
||
<div
|
||
className="card turn-status"
|
||
role="status"
|
||
aria-live="polite"
|
||
style={{
|
||
padding: '14px 16px',
|
||
fontWeight: 700,
|
||
fontSize: '1.15rem',
|
||
background: myTurn ? 'var(--primary)' : 'var(--surface)',
|
||
color: myTurn ? 'var(--primary-text)' : 'var(--text)',
|
||
width: '100%',
|
||
}}
|
||
>
|
||
{room.status === 'paused' ? '오류로 게임이 멈췄어요. 방장이 끝낼 수 있어요.' : ui.statusText(game.view, me.id, players)}
|
||
{slow && <span className="small"> · 연결 확인 중…</span>}
|
||
{!isPlayer && (
|
||
<span className="badge" style={{ marginLeft: 8 }}>
|
||
관전 중
|
||
</span>
|
||
)}
|
||
</div>
|
||
);
|
||
// [?] 지금 할 수 있는 것 sits right next to the turn status (docs/07 §5).
|
||
// The host's way out of a game stopped by an error sits right under the status that explains it.
|
||
const statusRow = (
|
||
<>
|
||
<div className="row" style={{ flexWrap: 'nowrap', gap: 8, width: '100%', alignItems: 'stretch' }}>
|
||
{status}
|
||
<GameHelp room={room} ui={ui} title={gameName(room.gameId)} me={me.id} players={players} />
|
||
</div>
|
||
<BotActivity room={room} ch={ui.ownChat ? 'game' : undefined} />
|
||
{room.status === 'paused' && room.hostId === me.id && (
|
||
<button className="btn btn-danger btn-block" onClick={() => socket.send({ t: 'void' })}>
|
||
⏹ 게임 끝내기(무효)
|
||
</button>
|
||
)}
|
||
</>
|
||
);
|
||
return (
|
||
<div className="game-layout" ref={layout}>
|
||
<div className="game-main">
|
||
{!wide && statusRow}
|
||
<ui.Board {...props} />
|
||
</div>
|
||
<aside className="game-side" aria-label="게임 정보">
|
||
{wide && statusRow}
|
||
<ui.Side {...props} />
|
||
{wide && !(ui.ownChat && (room.status === 'playing' || room.status === 'paused')) && <ChatPanel room={room} me={me} title={false} />}
|
||
</aside>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView; me: PublicUser; players: Record<string, PublicUser>; onLeave: () => void; onAgain: () => void }) {
|
||
const result = useRoom((s) => s.result)!;
|
||
const [hidden, setHidden] = useState(false);
|
||
const played = useRef(false);
|
||
const seatedAll = room.seats.filter(Boolean).map((s) => s!.user.id);
|
||
const seated = seatedAll.filter((u) => !isBotId(u));
|
||
// Solo games (e.g. 요트 다이스) have one ranked player: neither a draw nor a win.
|
||
const solo = result.ranking.flat().length === 1;
|
||
const allFirst = !solo && result.ranking.length === 1;
|
||
const won = !solo && !allFirst && result.ranking[0]?.includes(me.id);
|
||
const lost = !solo && !allFirst && !won && result.ranking.some((g) => g.includes(me.id));
|
||
useEffect(() => {
|
||
if (played.current) return;
|
||
played.current = true;
|
||
if (won) sounds.win();
|
||
else if (lost) sounds.lose();
|
||
}, [won, lost]);
|
||
if (hidden) {
|
||
return (
|
||
<div className="bottom-bar">
|
||
<div className="bottom-bar-inner">
|
||
<button className="btn btn-primary" onClick={() => setHidden(false)}>
|
||
결과 다시 보기
|
||
</button>
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|
||
return (
|
||
<Sheet onClose={() => setHidden(true)} label="게임 결과">
|
||
<h1 style={{ textAlign: 'center' }}>{allFirst ? '무승부예요' : won ? '🎉 이겼어요!' : lost ? '아쉽게 졌어요' : '게임이 끝났어요'}</h1>
|
||
<p style={{ textAlign: 'center' }}>{result.summary}</p>
|
||
{seatedAll.length > seated.length && <p className="muted small" style={{ textAlign: 'center' }}>🤖 연습 게임이라 기록에는 남지 않아요.</p>}
|
||
<div className="stack">
|
||
{result.ranking.map((group, i) =>
|
||
group.map((u) => (
|
||
<div key={u} className="row">
|
||
<strong style={{ width: 40 }}>{i + 1}등</strong>
|
||
{players[u] && <Avatar user={players[u]!} size={28} />}
|
||
<span style={{ minWidth: 0 }}>{players[u] ? <PlayerName user={players[u]!} gameId={room.gameId} session={room.sessionStats[u]} /> : '나간 사람'}</span>
|
||
<span style={{ marginLeft: 'auto', textAlign: 'right' }}>
|
||
{/* Final score of this game, in the game's own words (35점, +1,200칩, 카드 12장). */}
|
||
{result.scoreText?.[u] && (
|
||
<strong className="result-score" style={{ display: 'block' }}>
|
||
{result.scoreText[u]}
|
||
</strong>
|
||
)}
|
||
<span className="muted small">
|
||
이 방에서 {room.sessionStats[u]?.wins ?? 0}승 / {room.sessionStats[u]?.played ?? 0}판
|
||
</span>
|
||
</span>
|
||
</div>
|
||
)),
|
||
)}
|
||
</div>
|
||
{/* Back to this room's lobby: seats, computers and settings can change before the host starts again. */}
|
||
<button className="btn btn-primary btn-block" onClick={onAgain}>
|
||
🔁 한 판 더
|
||
</button>
|
||
{/* One primary action (한 판 더); the rest share one quieter row. */}
|
||
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
|
||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setHidden(true)}>
|
||
판 보기
|
||
</button>
|
||
{room.lastGamePk && result.ranking.some((g) => g.includes(me.id)) && (
|
||
<Link className="btn btn-secondary" style={{ flex: 1 }} to={`/replay/${room.lastGamePk}`}>
|
||
▶ 다시 보기
|
||
</Link>
|
||
)}
|
||
</div>
|
||
<button className="btn btn-ghost btn-block" onClick={onLeave}>
|
||
방 나가기
|
||
</button>
|
||
{room.lastSeed && (
|
||
<FairnessCheck seedHash={room.seedHash} seed={room.lastSeed} bots={room.lastBots} shuffles={room.lastShuffles} players={players} />
|
||
)}
|
||
</Sheet>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* docs/04 §5: the seed's SHA-256 was published when the game started; the seed is revealed at the end.
|
||
* The browser recomputes the hash itself so players don't have to trust the server's word.
|
||
*/
|
||
function FairnessCheck({
|
||
seedHash,
|
||
seed,
|
||
bots,
|
||
shuffles,
|
||
players,
|
||
}: {
|
||
seedHash: string | null;
|
||
seed: string;
|
||
bots?: RoomView['lastBots'];
|
||
shuffles?: number;
|
||
players: Record<string, PublicUser>;
|
||
}) {
|
||
const [verdict, setVerdict] = useState<null | boolean>(null);
|
||
const check = async () => {
|
||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed));
|
||
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||
setVerdict(hex === seedHash);
|
||
};
|
||
return (
|
||
<details className="small muted">
|
||
<summary>공정성 확인</summary>
|
||
{/* docs/09 §9.1: each computer's level (1~60) and luck in this game; docs/04 §5.1: shuffles tried for luck. */}
|
||
{bots && Object.keys(bots).length > 0 && (
|
||
<div className="stack" style={{ gap: 4, margin: '8px 0' }}>
|
||
{Object.entries(bots).map(([id, b]) => (
|
||
<p key={id} style={{ margin: 0 }}>
|
||
🤖 {players[id]?.nickname ?? '컴퓨터'}: 난이도 <strong>{b.level}단계</strong> ({BOT_PICK_LABEL[bandOf(b.level)]}) · 운 {luckLabel(b.luck)}
|
||
</p>
|
||
))}
|
||
{(shuffles ?? 1) > 1 && <p style={{ margin: 0 }}>이번 판은 컴퓨터의 운에 맞춰, 미리 섞어 본 {shuffles}가지 중 하나로 시작했어요. 고른 결과는 시작할 때 아래 값으로 공개했어요.</p>}
|
||
</div>
|
||
)}
|
||
<p>시작할 때 공개한 값(SHA-256): {seedHash ?? '-'}</p>
|
||
<p>끝나고 공개한 난수 씨앗: {seed}</p>
|
||
<button type="button" className="btn btn-secondary btn-sm" onClick={check}>
|
||
내 브라우저에서 직접 확인하기
|
||
</button>
|
||
{verdict !== null && (
|
||
<p style={{ fontWeight: 700, color: verdict ? 'var(--success)' : 'var(--danger)' }}>
|
||
{verdict ? '✓ 일치해요. 게임 도중 카드 순서나 난수가 바뀌지 않았어요.' : '✗ 일치하지 않아요. 관리자에게 알려 주세요.'}
|
||
</p>
|
||
)}
|
||
</details>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- chat
|
||
|
||
function ChatButton({ onOpen }: { onOpen: () => void }) {
|
||
const seen = useChatSeen((s) => s.seen);
|
||
const unread = useRoom((s) => s.chat.filter((m) => m.id > seen).length);
|
||
return (
|
||
<button className="btn btn-ghost btn-sm rb-btn" onClick={onOpen} aria-label={`채팅${unread ? `, 새 메시지 ${unread}개` : ''}`}>
|
||
<span className="rb-ico">💬</span>
|
||
<span className="rb-lbl">채팅</span>
|
||
{unread > 0 && <span className="badge warning rb-badge">{unread}</span>}
|
||
</button>
|
||
);
|
||
}
|