컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업

- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위
- 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말)
- humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60)
- 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로
- 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수
- 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕]
- 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 17:46:13 +09:00
parent 3cbc3698d3
commit 84d64b27f2
40 changed files with 1349 additions and 133 deletions

View File

@@ -6,6 +6,7 @@ import { useToasts, toast } from '../store/toast';
import { useRoom } from '../net/socket';
import { haptic } from '../lib/feedback';
import { useOnline } from '../lib/pwa';
import { dismissUpdate, useUpdateAvailable } from '../lib/update';
const AVATAR_COLORS = ['#2563eb', '#db2777', '#16a34a', '#ea580c', '#7c3aed', '#0891b2', '#ca8a04', '#dc2626'];
@@ -146,6 +147,23 @@ export function ConnectionBanner() {
return null;
}
/** The site was updated while this page was open (docs/07 §11.1): refresh, or ✕ to close until the next update. */
export function UpdateBanner() {
const show = useUpdateAvailable();
if (!show) return null;
return (
<div className="update-banner" role="alert">
<span className="update-text">업데이트 내용이 있습니다.</span>
<button type="button" className="btn btn-primary btn-sm" onClick={() => location.reload()}>
지금 새로고침하기
</button>
<button type="button" className="update-close" onClick={dismissUpdate} aria-label="업데이트 알림 닫기">
✕
</button>
</div>
);
}
export function CodeLabel({ code }: { code: string }) {
return <span style={{ fontVariantNumeric: 'tabular-nums', letterSpacing: '0.08em' }}>{formatRoomCode(code)}</span>;
}

View File

@@ -0,0 +1,61 @@
/**
* "업데이트 내용이 있습니다" (docs/07 §11.1). The page knows its own build (`<meta name="bg-build">`, written by
* vite.config.ts); the server tells its build in `welcome` and at `/api/version`. When they differ the page offers a
* refresh at the top; ✕ hides it until the next update. Dev builds have no meta and never ask.
*/
import { useSyncExternalStore } from 'react';
const POLL_MS = 5 * 60_000;
const mine = typeof document === 'undefined' ? null : (document.querySelector<HTMLMetaElement>('meta[name="bg-build"]')?.content ?? null);
/** Build the server has that this page doesn't ('protocol' = the server speaks a newer protocol). */
let latest: string | null = null;
let dismissed: string | null = null;
const listeners = new Set<() => void>();
const emit = () => listeners.forEach((l) => l());
/** The server's build (welcome message, `/api/version`). */
export function noteServerBuild(build: string | null | undefined): void {
if (!mine || !build || build === mine || build === latest) return;
latest = build;
emit();
}
/** The server speaks a different protocol: this page must be refreshed whatever its build. */
export function markOutdated(): void {
if (latest) return;
latest = 'protocol';
emit();
}
export function dismissUpdate(): void {
dismissed = latest;
emit();
}
async function check(): Promise<void> {
try {
const res = await fetch('/api/version', { cache: 'no-store' });
if (res.ok) noteServerBuild(((await res.json()) as { build?: string | null }).build);
} catch {
// Offline or restarting: the next check (or the socket's welcome) will tell.
}
}
/** Call once at startup: checks now and then, and whenever the tab comes back into view. */
export function initUpdateCheck(): void {
if (!mine) return;
setInterval(() => void check(), POLL_MS);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') void check();
});
}
const subscribe = (l: () => void) => {
listeners.add(l);
return () => void listeners.delete(l);
};
export function useUpdateAvailable(): boolean {
return useSyncExternalStore(subscribe, () => latest !== null && latest !== dismissed, () => false);
}

View File

@@ -3,12 +3,13 @@ import { createRoot } from 'react-dom/client';
import { BrowserRouter, Route, Routes, useLocation, useNavigate } from 'react-router';
import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css';
import './styles/global.css';
import { ConnectionBanner, Toasts } from './components/ui';
import { ConnectionBanner, Toasts, UpdateBanner } from './components/ui';
import { useSession } from './store/session';
import { toast } from './store/toast';
import { Home } from './pages/Home';
import { SiteHeader } from './components/SiteHeader';
import { initPwa } from './lib/pwa';
import { initUpdateCheck } from './lib/update';
const JoinPage = lazy(() => import('./pages/JoinPage'));
const RoomPage = lazy(() => import('./pages/RoomPage'));
@@ -58,6 +59,7 @@ function Shell() {
return (
<>
<ConnectionBanner />
<UpdateBanner />
<SiteHeader />
<Announcement />
<Toasts />
@@ -82,6 +84,7 @@ function Shell() {
}
initPwa();
initUpdateCheck();
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>

View File

@@ -5,6 +5,7 @@
import { create } from 'zustand';
import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite';
import { toast } from '../store/toast';
import { markOutdated, noteServerBuild } from '../lib/update';
export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline';
@@ -39,7 +40,6 @@ interface RoomStore {
clockOffset: number;
joinError: string | null;
kicked: boolean;
needsRefresh: boolean;
}
export const useRoom = create<RoomStore>(() => ({
@@ -58,7 +58,6 @@ export const useRoom = create<RoomStore>(() => ({
clockOffset: 0,
joinError: null,
kicked: false,
needsRefresh: false,
}));
const BACKOFF = [500, 1000, 2000, 4000, 8000];
@@ -256,7 +255,8 @@ class GameSocket {
const st = useRoom.getState();
switch (m.t) {
case 'welcome': {
if (m.protocol !== PROTOCOL) useRoom.setState({ needsRefresh: true });
if (m.protocol !== PROTOCOL) markOutdated();
else noteServerBuild(m.build);
useRoom.setState({ status: 'open', me: m.me });
this.offsets = [m.serverTime - Date.now()];
useRoom.setState({ clockOffset: this.offsets[0]! });

View File

@@ -1,7 +1,7 @@
/** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Link, useNavigate, useParams } from 'react-router';
import { botsAllowed, formatRoomCode, isBotId, type PublicUser, type RoomView } from '@bg/shared/lite';
import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, 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';
@@ -88,7 +88,7 @@ function RoomGone({ message }: { message: string }) {
function Room({ code, me }: { code: string; me: PublicUser }) {
const nav = useNavigate();
const { room, game, result, status, joinError, pending, slow, needsRefresh } = useRoom();
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);
@@ -224,14 +224,6 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
</button>
</div>
</nav>
{needsRefresh && (
<div className="card row" style={{ margin: 12, justifyContent: 'space-between' }}>
<span>새 버전이 있어요.</span>
<button className="btn btn-primary btn-sm" onClick={() => location.reload()}>
새로고침
</button>
</div>
)}
{inGame && game ? (
<GameView room={room} ui={ui} me={me} players={players} pending={pending !== null} slow={slow} />
) : (
@@ -331,18 +323,38 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
<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 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>
<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 && (
<button className="btn btn-ghost" onClick={() => socket.send({ t: 'removeBot', userId: s.user.id })} aria-label={`${s.user.nickname} 빼기`}>
✕
</button>
<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 ? (
@@ -428,8 +440,8 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
<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} onClick={() => (notReady > 0 ? setAskStart(true) : socket.send({ t: 'start' }))}>
{need > 0 ? `${need}명 더 필요해요` : '▶ 게임 시작'}
<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 ? (
@@ -751,7 +763,7 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView;
방 나가기
</button>
{room.lastSeed && (
<FairnessCheck seedHash={room.seedHash} seed={room.lastSeed} />
<FairnessCheck seedHash={room.seedHash} seed={room.lastSeed} bots={room.lastBots} shuffles={room.lastShuffles} players={players} />
)}
</Sheet>
);
@@ -761,7 +773,19 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView;
* 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 }: { seedHash: string | null; seed: string }) {
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));
@@ -771,6 +795,17 @@ function FairnessCheck({ seedHash, seed }: { seedHash: string | null; seed: stri
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}>

View File

@@ -307,6 +307,16 @@ label.field {
background: var(--primary-soft);
font-weight: 700;
}
/* Computer difficulty in the lobby (docs/06 §12): four even pills. */
.segmented.bot-level {
flex-wrap: nowrap;
gap: 6px;
}
.segmented.bot-level button {
flex: 1;
padding: 0 6px;
min-width: 0;
}
/* ---------- top bar ---------- */
.topbar {
@@ -368,6 +378,54 @@ label.field {
font-weight: 700;
}
/* "업데이트 내용이 있습니다" (docs/07 §11.1): a card at the top, above everything but the connection banner. */
.update-banner {
position: fixed;
top: calc(8px + env(safe-area-inset-top));
left: 50%;
transform: translateX(-50%);
z-index: 70;
width: min(94vw, 480px);
display: flex;
align-items: center;
gap: 10px;
background: var(--surface);
color: var(--text);
border: 2px solid var(--primary);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 10px 8px 10px 16px;
animation: update-in 0.2s ease;
}
@keyframes update-in {
from {
opacity: 0;
transform: translate(-50%, -8px);
}
}
.update-banner .update-text {
flex: 1;
min-width: 0;
font-weight: 700;
}
.update-banner .btn {
white-space: nowrap;
}
.update-close {
flex: none;
width: var(--tap);
height: var(--tap);
border: 0;
background: transparent;
color: var(--text-sub);
font-size: 1.2rem;
cursor: pointer;
border-radius: var(--radius);
}
.update-close:hover {
background: var(--surface-2);
}
.toasts {
position: fixed;
top: calc(var(--site-h) + env(safe-area-inset-top));