커넥트 포(사목) 규칙·컴퓨터 상대·화면·테스트

- 규칙 모듈 packages/games/src/connect-four: 7×6 기본, 8×7·9×7 판, 열을 고르면 맨 아래 빈칸으로
  떨어짐, 가로·세로·대각선 4개(이상) 즉시 승리(이긴 줄 전부 기록), 판이 차면 무승부. 먼저 두는 사람은
  오목·오셀로와 같은 관례(무작위/방장 먼저/방장 나중/판마다 번갈아 — gameNo). 시간: 한 수당·피셔·없음,
  시간 초과 자동 두기(승리 > 막기 > 위 칸을 내주지 않는 가운데 열), 허용 횟수 넘으면 시간패, 기권·나가기.
- 컴퓨터 상대: 네가맥스 알파베타 + 반복 심화 + 치환표, 바로 이기기/막기·강제 수 판정, 열린 줄과 홀짝 줄
  위협을 증분 평가. 레벨 1~60에 따라 1~10수 읽기(어려움은 빈칸 24개부터 끝까지 시도), 국면 5만 개 상한으로
  한 수 평균 수 ms·최악 수십 ms. humanBest로 사람 같은 실수, 낮은 단계는 4목 막기를 가끔 놓침.
- 화면 apps/web/src/games/connect-four: 구멍 뚫린 파란 판(마스크), 떨어지는 애니메이션(움직임 줄이기
  존중), 이긴 줄 강조, 열 전체 터치 영역, 키보드 ←·→·Home·End·Enter, 스크린리더 안내, 다크 모드,
  30초 요약·도움말.
- 등록: GAMES, CATALOG, BOT_GAMES, BOT_STRATEGIES, NO_LUCK, 화면 레지스트리, 아이콘·판 탭, 공통 테스트 목록.
- 문서 docs/games/connect-four.md, 목록 한 줄. E2E 계획(PC 키보드 + 휴대폰 터치, 꽉 찬 열 무시, 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 22:31:56 +09:00
parent c9f81804cf
commit 3fffcec52b
23 changed files with 1848 additions and 4 deletions

View File

@@ -0,0 +1,30 @@
import { expect, test } from 'bun:test';
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
import { GAMES } from '@bg/games';
import { helpNow } from './help';
const users = usersOf(['A', 'B']);
const view = (s: unknown, who: string | null) => GAMES['connect-four']!.view(s, who) as any;
test('커넥트 포: 내 차례 / 상대 차례 / 관전 / 꽉 찬 열', () => {
const { state } = setupGame('connect-four', 2, { colorAssignment: 'hostRed' });
const first = helpNow(view(state, 'A'), 'A', users);
expect(first).toContain('내 차례예요(빨강)');
expect(first).toContain('가운데 열');
expect(helpNow(view(state, 'B'), 'B', users)).toContain('상대(호랑이님) 차례예요');
expect(helpNow(view(state, null), null, users)).toContain('호랑이님(빨강) 차례예요');
let s = state;
for (let i = 0; i < 6; i++) s = applyAction('connect-four', s, i % 2 ? 'B' : 'A', { type: 'drop', col: 0 });
const t = helpNow(view(s, 'A'), 'A', users);
expect(t).toContain('1열은 꽉 차서');
expect(t).toContain('4개');
});
test('커넥트 포: 끝난 판은 결과와 다시 하기 안내', () => {
const { state } = setupGame('connect-four', 2, { colorAssignment: 'hostRed' });
let s = state;
for (const [who, col] of [['A', 0], ['B', 0], ['A', 1], ['B', 1], ['A', 2], ['B', 2], ['A', 3]] as const) s = applyAction('connect-four', s, who, { type: 'drop', col });
const t = helpNow(view(s, 'B'), 'B', users);
expect(t).toContain('빨강 승');
expect(t).toContain('[한 판 더]');
});

View File

@@ -0,0 +1,20 @@
/** 커넥트 포 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
import type { ConnectFourView } from '@bg/games/connect-four';
import type { PublicUser } from '@bg/shared/lite';
const COLOR_KO = { red: '빨강', yellow: '노랑' } as const;
export function helpNow(v: ConnectFourView, _me: string | null, players: Record<string, PublicUser>): string {
const goal = '가로·세로·대각선 중 한 줄로 내 돌 4개를 먼저 이으면 이겨요.';
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
const turnNick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn];
if (!v.myColor) return `${turnNick}님(${COLOR_KO[v.turn]}) 차례예요. ${goal}`;
const mine = COLOR_KO[v.myColor];
if (v.myColor !== v.turn) return `상대(${turnNick}님) 차례예요. 상대가 돌을 넣을 때까지 기다려 주세요. 나는 ${mine}이에요.`;
const full = Array.from({ length: v.cols }, (_, c) => c).filter((c) => v.board[c] !== 0);
const lines = [`내 차례예요(${mine}). 돌을 넣을 열을 눌러요. 돌은 그 열의 맨 아래 빈칸까지 떨어져요. ${goal}`];
if (v.moveCount === 0) lines.push('처음에는 가운데 열에 넣는 게 좋아요. 가운데일수록 4개를 이을 길이 많아요.');
if (full.length) lines.push(`${full.map((c) => `${c + 1}열`).join(', ')}은 꽉 차서 넣을 수 없어요.`);
lines.push('상대가 3개를 이어 놓았다면 남은 한 칸을 먼저 막아요.');
return lines.join('\n');
}

View File

@@ -0,0 +1,426 @@
/** 커넥트 포 화면 (docs/games/connect-four.md §9). */
import { useEffect, useId, useRef, useState } from 'react';
import type { Color, ConnectFourOptions, ConnectFourView } from '@bg/games/connect-four';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar, ConfirmSheet } from '../../components/ui';
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
const COLOR_KO: Record<Color, string> = { red: '빨강', yellow: '노랑' };
const FILL: Record<Color, [string, string]> = { red: ['#dc2626', '#991b1b'], yellow: ['#facc15', '#b45309'] };
const SIZE_KO: Record<ConnectFourOptions['boardSize'], string> = { '7x6': '7×6', '8x7': '8×7', '9x7': '9×7' };
/** Row counted from the bottom, 1-based (what people say: "아래에서 두 번째 줄"). */
const rowFromBottom = (v: ConnectFourView, y: number) => v.rows - y;
const CSS = `
@keyframes c4drop { from { transform: translateY(var(--c4-from)); } to { transform: translateY(0); } }
.c4-drop { animation: c4drop var(--c4-dur) cubic-bezier(.5, 0, 1, 1) both; }
@keyframes c4glow { 50% { opacity: .35; } }
.c4-win { animation: c4glow 1.1s ease-in-out infinite; }
.c4-svg { --c4-frame: #1d4ed8; --c4-frame-edge: #1e3a8a; }
:root[data-theme='dark'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; }
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; } }
@media (prefers-reduced-motion: reduce) { .c4-drop, .c4-win { animation: none; } }
`;
function Disc({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
const [fill, edge] = FILL[color];
return (
<g opacity={ghost ? 0.5 : 1}>
<circle cx={cx} cy={cy} r={r} fill={fill} stroke={edge} strokeWidth={0.05} />
<circle cx={cx} cy={cy} r={r * 0.68} fill="none" stroke={edge} strokeWidth={0.05} opacity={0.45} />
</g>
);
}
function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourView>) {
const { cols, rows } = v;
const myTurn = v.phase === 'playing' && v.myColor === v.turn;
const [preview, setPreview] = useState<number | null>(null);
const [hover, setHover] = useState<number | null>(null);
const [cursor, setCursor] = useState(Math.floor((cols - 1) / 2));
const [kbd, setKbd] = useState(false);
const [announce, setAnnounce] = useState('');
const maskId = `c4mask${useId().replace(/:/g, '')}`;
const prevCount = useRef(v.moveCount);
const prevTurn = useRef(v.turn);
// The disc dropped since the last render falls in (only for moves seen live, not on page load).
const seen = useRef(v.moveCount);
const falling = useRef<number | null>(null);
if (v.moveCount > seen.current) falling.current = v.moveCount;
seen.current = v.moveCount;
useEffect(() => {
if (v.moveCount > prevCount.current && v.lastMove) {
sounds.stone();
const m = v.moves[v.moves.length - 1]!;
setAnnounce(`${COLOR_KO[m.color]}이 ${m.x + 1}열에 넣었어요. 아래에서 ${rowFromBottom(v, m.y)}번째 칸이에요.${m.auto ? ' (시간이 다 돼서 자동으로)' : ''}`);
}
if (v.phase === 'playing' && myTurn && prevTurn.current !== v.turn && v.moveCount !== prevCount.current) {
haptic(40);
if (document.visibilityState === 'hidden') sounds.myTurn();
}
prevCount.current = v.moveCount;
prevTurn.current = v.turn;
setPreview(null);
}, [v.moveCount, v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
const open = (c: number) => v.board[c] === 0;
const canDrop = (c: number) => myTurn && !pending && open(c);
const landing = (c: number) => {
for (let y = rows - 1; y >= 0; y--) if (v.board[y * cols + c] === 0) return y;
return -1;
};
const drop = (c: number) => {
act({ type: 'drop', col: c });
setPreview(null);
setHover(null);
};
const tap = (c: number, mouse: boolean) => {
setCursor(c);
setKbd(false);
if (!myTurn) return;
if (!open(c)) {
haptic([30, 30, 30]);
setAnnounce(`${c + 1}열은 꽉 찼어요. 다른 열을 골라 주세요.`);
return;
}
// Mouse: one click drops (hover already shows where). Touch: optional two-step confirm.
if (mouse || !tapConfirm) {
if (canDrop(c)) drop(c);
return;
}
if (preview === c) drop(c);
else setPreview(c);
};
const onKey = (e: React.KeyboardEvent) => {
setKbd(true);
const step: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1 };
if (step[e.key]) {
e.preventDefault();
setCursor((c) => Math.min(cols - 1, Math.max(0, c + step[e.key]!)));
} else if (e.key === 'Home' || e.key === 'End') {
e.preventDefault();
setCursor(e.key === 'Home' ? 0 : cols - 1);
} else if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (canDrop(cursor)) drop(cursor);
else if (myTurn && !open(cursor)) setAnnounce(`${cursor + 1}열은 꽉 찼어요.`);
}
};
const ghostCol = preview ?? (hover !== null && canDrop(hover) ? hover : myTurn && kbd && open(cursor) ? cursor : null);
const ghostLand = ghostCol !== null ? landing(ghostCol) : -1;
const winSet = new Set((v.winLine ?? []).map((p) => p.y * cols + p.x));
const last = v.lastMove ? v.lastMove.y * cols + v.lastMove.x : -1;
const pad = 0.15;
const cells = Array.from({ length: cols * rows }, (_, i) => i);
return (
<div className="board-wrap stack" style={{ gap: 10, maxWidth: `min(100%, calc((100vh - var(--site-h, 56px) - 180px) * ${(cols + 2 * pad) / (rows + 1.6)}))` }}>
<style>{CSS}</style>
<svg
className="c4-svg"
viewBox={`${-pad} -1.1 ${cols + 2 * pad} ${rows + 1.1 + 0.6}`}
style={{ width: '100%', display: 'block', touchAction: 'manipulation', cursor: myTurn ? 'pointer' : 'default', userSelect: 'none' }}
onPointerLeave={() => setHover(null)}
tabIndex={0}
role="grid"
aria-label={`커넥트 포 판 ${cols}열 ${rows}줄. 왼쪽·오른쪽 화살표로 열을 고르고 Enter로 돌을 넣어요. 지금 고른 열: ${cursor + 1}열${open(cursor) ? '' : '(꽉 참)'}`}
onKeyDown={onKey}
>
<defs>
<mask id={maskId}>
<rect x={-pad} y={-pad} width={cols + 2 * pad} height={rows + 2 * pad} fill="white" />
{cells.map((i) => (
<circle key={i} cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.42} fill="black" />
))}
</mask>
</defs>
{/* Holes, then discs (behind the frame, so a falling disc shows through the holes), then the frame. */}
<rect x={0} y={0} width={cols} height={rows} fill="var(--bg)" />
{ghostCol !== null && ghostLand >= 0 && (
<circle cx={ghostCol + 0.5} cy={ghostLand + 0.5} r={0.36} fill="none" stroke={v.myColor ? FILL[v.myColor][0] : '#888'} strokeWidth={0.07} strokeDasharray="0.14 0.1" />
)}
{cells.map((i) => {
const c = v.board[i];
if (!c) return null;
const x = i % cols;
const y = Math.floor(i / cols);
const anim = i === last && falling.current === v.moveCount;
return (
<g
key={i}
className={anim ? 'c4-drop' : undefined}
style={anim ? ({ '--c4-from': `${-(y + 1.5)}px`, '--c4-dur': `${0.16 + 0.06 * (y + 1)}s` } as React.CSSProperties) : undefined}
>
<Disc color={c === 1 ? 'red' : 'yellow'} cx={x + 0.5} cy={y + 0.5} r={0.41} />
</g>
);
})}
<rect x={-pad} y={-pad} width={cols + 2 * pad} height={rows + 2 * pad} rx={0.3} fill="var(--c4-frame)" stroke="var(--c4-frame-edge)" strokeWidth={0.05} mask={`url(#${maskId})`} />
{last >= 0 && !winSet.size && <circle cx={(last % cols) + 0.5} cy={Math.floor(last / cols) + 0.5} r={0.09} fill="#fff" opacity={0.85} />}
{[...winSet].map((i) => (
<circle key={`w${i}`} className="c4-win" cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.36} fill="none" stroke="#fff" strokeWidth={0.1} />
))}
{ghostCol !== null && v.myColor && <Disc color={v.myColor} cx={ghostCol + 0.5} cy={-0.55} r={0.41} ghost={preview === null} />}
{myTurn && kbd && <rect x={cursor + 0.04} y={-1.08} width={0.92} height={rows + 1.04} rx={0.12} fill="none" stroke="var(--focus)" strokeWidth={0.07} />}
{Array.from({ length: cols }, (_, c) => (
<text key={`l${c}`} x={c + 0.5} y={rows + 0.42} fontSize={0.34} fontWeight={700} textAnchor="middle" dominantBaseline="central" fill="var(--text-sub)">
{c + 1}
</text>
))}
{/* Tap areas: the whole column, header row included. */}
{Array.from({ length: cols }, (_, c) => (
<rect
key={`t${c}`}
data-col={c}
x={c}
y={-1.1}
width={1}
height={rows + 1.1}
fill="transparent"
onPointerMove={(e) => {
if (e.pointerType === 'mouse' && myTurn && hover !== c) setHover(c);
}}
onPointerUp={(e) => tap(c, e.pointerType === 'mouse')}
/>
))}
</svg>
<p className="sr-only" aria-live="polite">
{announce}
</p>
{preview !== null && myTurn && (
<div className="row" style={{ justifyContent: 'center' }}>
<button className="btn btn-primary" style={{ flex: 2 }} disabled={!canDrop(preview)} onClick={() => drop(preview)}>
{`${preview + 1}열에 넣기`}
</button>
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setPreview(null)}>
취소
</button>
</div>
)}
</div>
);
}
/** Right-hand panel on PC (below the board on narrow screens). */
function C4Side({ view: v, me, players, act, deadline }: BoardProps<ConnectFourView>) {
const [confirm, setConfirm] = useState(false);
const opp: Color = v.myColor === 'yellow' ? 'red' : 'yellow';
const mine: Color = v.myColor ?? 'red';
return (
<>
<PlayerBar view={v} color={v.myColor ? opp : 'red'} players={players} deadline={deadline} me={me} />
<PlayerBar view={v} color={v.myColor ? mine : 'yellow'} players={players} deadline={deadline} me={me} />
{v.phase === 'playing' && v.myColor && (
<button className="btn btn-danger btn-sm" onClick={() => setConfirm(true)}>
🏳 기권
</button>
)}
<MoveList view={v} />
{confirm && <ConfirmSheet title="기권할까요?" body="기권하면 이 판은 상대가 이겨요." confirm="기권하기" danger onConfirm={() => act({ type: 'resign' })} onClose={() => setConfirm(false)} />}
</>
);
}
function MoveList({ view: v }: { view: ConnectFourView }) {
const ref = useRef<HTMLOListElement>(null);
useEffect(() => {
ref.current?.scrollTo({ top: ref.current.scrollHeight });
}, [v.moveCount]);
if (v.moveCount === 0) return null;
return (
<details className="card wide-open" open style={{ padding: 12 }}>
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기보 ({v.moveCount}수)</summary>
<ol ref={ref} style={{ margin: '8px 0 0', paddingLeft: 0, listStyle: 'none', maxHeight: 132, overflow: 'auto', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '2px 8px', fontVariantNumeric: 'tabular-nums' }}>
{v.moves.map((m, i) => (
<li key={i} className="small">
<span className="muted">{i + 1}.</span> <span aria-label={COLOR_KO[m.color]}>{m.color === 'red' ? '🔴' : '🟡'}</span> {m.x + 1}열
{m.auto ? '*' : ''}
</li>
))}
</ol>
</details>
);
}
function PlayerBar({ view: v, color, players, deadline, me }: { view: ConnectFourView; color: Color; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
const id = v.players[color];
const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
const active = v.phase === 'playing' && v.turn === color;
const now = useServerNow(500);
const tc = v.timeControl;
let clock: React.ReactNode = null;
if (tc.kind === 'fischer') {
const ms = Math.max(0, v.remainingMs[color] - (active ? now - v.turnStartedAt : 0));
const s = Math.ceil(ms / 1000);
clock = (
<span style={{ fontVariantNumeric: 'tabular-nums', fontWeight: 700, fontSize: '1.15rem', color: active && s <= 10 ? 'var(--danger)' : undefined }}>
{Math.floor(s / 60)}:{String(s % 60).padStart(2, '0')}
</span>
);
} else if (active && tc.kind === 'perMove') {
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={id === me} />;
}
return (
<div className="card row" style={{ padding: '8px 12px', gap: 10, border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
<svg width={28} height={28} viewBox="-1 -1 2 2" aria-hidden>
<Disc color={color} cx={0} cy={0} r={0.9} />
</svg>
<Avatar user={u} size={32} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{u.nickname}
{id === me && <span className="muted small"> (나)</span>}
</div>
<div className="muted small">
{COLOR_KO[color]}
{color === 'red' ? ' · 먼저' : ' · 나중'}
{active ? ' · 두는 중' : ''}
</div>
</div>
{clock}
</div>
);
}
function statusText(v: ConnectFourView, _me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
if (v.myColor === v.turn) return `내 차례예요 (${COLOR_KO[v.turn]}). 돌을 넣을 열을 눌러 주세요`;
const nick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn];
return v.myColor ? `${nick}님이 생각 중이에요…` : `${nick}님(${COLOR_KO[v.turn]}) 차례예요`;
}
// ---------------------------------------------------------------- options
function Seg<T extends string | number>({ 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>
);
}
type TimeControl = ConnectFourOptions['timeControl'];
const TIME_PRESETS: [string, string, Partial<TimeControl>][] = [
['pm10', '한 수 10초', { kind: 'perMove', perMoveSec: 10 }],
['pm20', '한 수 20초', { kind: 'perMove', perMoveSec: 20 }],
['pm30', '한 수 30초', { kind: 'perMove', perMoveSec: 30 }],
['pm60', '한 수 60초', { kind: 'perMove', perMoveSec: 60 }],
['f1', '1분 + 2초', { kind: 'fischer', baseSec: 60, incSec: 2 }],
['f3', '3분 + 2초', { kind: 'fischer', baseSec: 180, incSec: 2 }],
['f5', '5분 + 3초', { kind: 'fischer', baseSec: 300, incSec: 3 }],
['none', '시간 제한 없음', { kind: 'none' }],
];
function timeKey(tc: TimeControl): string {
if (tc.kind === 'none') return 'none';
if (tc.kind === 'perMove') return `pm${tc.perMoveSec}`;
return `f${Math.round(tc.baseSec / 60)}`;
}
function timeLabel(tc: TimeControl): string {
if (tc.kind === 'none') return '시간 제한 없음';
if (tc.kind === 'perMove') return `한 수 ${tc.perMoveSec}초`;
const m = Math.floor(tc.baseSec / 60);
const sec = tc.baseSec % 60;
return `${m}분${sec ? ` ${sec}초` : ''} + ${tc.incSec}초`;
}
function Options({ value: o, onChange }: OptionsProps<ConnectFourOptions>) {
const [more, setMore] = useState(false);
const set = (patch: Partial<ConnectFourOptions>) => onChange({ ...o, ...patch });
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>판 크기 (가로 × 세로)</strong>
<Seg label="판 크기" value={o.boardSize} options={[['7x6', '7 × 6 (기본)'], ['8x7', '8 × 7'], ['9x7', '9 × 7']]} onChange={(boardSize) => set({ boardSize })} />
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>시간</strong>
<Seg
label="시간"
value={timeKey(o.timeControl)}
options={[
...TIME_PRESETS.map(([k, l]) => [k, l] as [string, string]),
...(TIME_PRESETS.some((p) => p[0] === timeKey(o.timeControl)) ? [] : [[timeKey(o.timeControl), `${timeLabel(o.timeControl)}(관리자 설정)`] as [string, string]]),
]}
onChange={(k) => {
const preset = TIME_PRESETS.find((p) => p[0] === k);
if (preset) set({ timeControl: { ...o.timeControl, ...preset[2] } });
}}
/>
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>빨강(먼저 두는 쪽)</strong>
<Seg
label="먼저 두는 사람"
value={o.colorAssignment}
options={[['random', '무작위'], ['hostRed', '방장이 먼저'], ['hostYellow', '방장이 나중'], ['alternate', '판마다 번갈아']]}
onChange={(colorAssignment) => set({ colorAssignment })}
/>
</div>
{o.timeControl.kind === 'perMove' && (
<>
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
</button>
{more && (
<div className="stack" style={{ gap: 6 }}>
<strong>시간이 다 되면</strong>
<Seg label="시간이 다 되면" value={o.timeoutPolicy} options={[['autoMove', '자동으로 두기'], ['lose', '시간패']]} onChange={(timeoutPolicy) => set({ timeoutPolicy })} />
</div>
)}
</>
)}
</div>
);
}
function optionsSummary(o: ConnectFourOptions): string {
const first = o.colorAssignment === 'alternate' ? '선 번갈아' : o.colorAssignment === 'hostRed' ? '방장 먼저' : o.colorAssignment === 'hostYellow' ? '방장 나중' : '선 무작위';
return [`${SIZE_KO[o.boardSize]} 판`, timeLabel(o.timeControl), first].join(' · ');
}
function Rules({ options }: { options?: ConnectFourOptions }) {
const size = options?.boardSize ?? '7x6';
return (
<div className="stack">
<p>
세워 놓은 {SIZE_KO[size]} 판에 빨강과 노랑이 번갈아 돌을 넣어요. <strong>열을 고르면 돌이 그 열의 맨 아래 빈칸까지 떨어져요.</strong> 빨강이 먼저 둬요.
</p>
<p>
가로, 세로, 대각선 중 한 줄로 내 돌 <strong>4개</strong>를 먼저 이으면 바로 이겨요. 판이 다 찰 때까지 아무도 못 이으면 비겨요.
</p>
<p>꽉 찬 열에는 넣을 수 없어요. 내가 넣은 돌 바로 위 칸은 상대가 쓸 수 있으니, 상대가 이기는 칸을 받쳐 주지 않게 조심해요.</p>
<p>
PC에서는 열을 누르거나 키보드 ←·→로 열을 고르고 Enter를 눌러요. 휴대폰에서는 열 아무 곳이나 누르면 돼요(한 번 더 누르기 확인을 켰다면 같은 열을 한 번 더 누르거나 [넣기]를 눌러요).
</p>
{options?.timeControl.kind === 'perMove' && options.timeoutPolicy === 'autoMove' && <p>한 수 시간이 다 되면 컴퓨터가 대신 한 수를 둬요. 여러 번 계속되면 시간패예요.</p>}
</div>
);
}
const ui: GameUI<ConnectFourView, ConnectFourOptions> = {
Board: C4Board,
Side: C4Side,
statusText,
isMyTurn: (v, me) => v.phase === 'playing' && !!v.myColor && v.players[v.turn] === me,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -0,0 +1,52 @@
/** 커넥트 포 30초 규칙 요약 (docs/07 §5). */
import type { QuickCard } from '../types';
type D = 'r' | 'y';
/** Small 7 × 6 board: discs as [column, row from the bottom, colour]; `arrow` marks a column; `ring` circles cells. */
function MiniBoard({ discs, arrow, ring = [] }: { discs: [number, number, D][]; arrow?: number; ring?: [number, number][] }) {
const cols = 7;
const rows = 6;
const cy = (h: number) => rows - h - 0.5;
return (
<svg viewBox="-0.2 -1.2 7.4 7.4" width={180} height={180} aria-hidden>
<rect x={-0.15} y={-0.15} width={cols + 0.3} height={rows + 0.3} rx={0.3} fill="#1d4ed8" />
{Array.from({ length: cols * rows }, (_, i) => (
<circle key={i} cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.4} fill="#f7f5f0" />
))}
{discs.map(([x, h, c]) => (
<circle key={`${x}-${h}`} cx={x + 0.5} cy={cy(h)} r={0.4} fill={c === 'r' ? '#dc2626' : '#facc15'} stroke={c === 'r' ? '#991b1b' : '#b45309'} strokeWidth={0.05} />
))}
{ring.map(([x, h]) => (
<circle key={`g${x}-${h}`} cx={x + 0.5} cy={cy(h)} r={0.34} fill="none" stroke="#fff" strokeWidth={0.1} />
))}
{arrow !== undefined && (
<g fill="#dc2626">
<circle cx={arrow + 0.5} cy={-0.7} r={0.38} />
<path d={`M ${arrow + 0.25} -0.15 L ${arrow + 0.75} -0.15 L ${arrow + 0.5} 0.15 Z`} />
</g>
)}
</svg>
);
}
export const quickStart: QuickCard[] = [
{
pic: <MiniBoard discs={[[3, 0, 'y'], [2, 0, 'r']]} arrow={3} />,
alt: '세워 놓은 파란 판의 4번째 열 위에 빨간 돌이 있고, 그 열 맨 아래에는 노란 돌이 있어요',
title: '열을 골라 넣어요',
text: '빨강이 먼저예요. 내 차례에 열을 누르면 돌이 그 열의 맨 아래 빈칸까지 떨어져요.',
},
{
pic: <MiniBoard discs={[[0, 0, 'r'], [1, 0, 'r'], [2, 1, 'r'], [3, 2, 'r'], [4, 3, 'r'], [2, 0, 'y'], [3, 0, 'y'], [3, 1, 'y'], [4, 0, 'y'], [4, 1, 'r'], [4, 2, 'y']]} ring={[[1, 0], [2, 1], [3, 2], [4, 3]]} />,
alt: '빨간 돌 4개가 대각선으로 이어져 하얀 테두리로 빛나요',
title: '4개를 이으면 이겨요',
text: '가로·세로·대각선 어느 쪽이든 내 돌 4개를 먼저 한 줄로 이으면 이겨요. 판이 다 차면 비겨요.',
},
{
pic: <MiniBoard discs={[[1, 0, 'y'], [2, 0, 'y'], [3, 0, 'y'], [3, 1, 'r'], [2, 1, 'r'], [6, 0, 'r']]} ring={[[0, 0], [4, 0]]} />,
alt: '맨 아래 줄에 노란 돌 3개가 있고 양쪽 빈칸에 하얀 동그라미가 있어요',
title: '3개면 꼭 막아요',
text: '상대가 3개를 이으면 남은 칸을 먼저 막아요. 양쪽이 다 비어 있으면 하나밖에 못 막으니 미리 조심해요.',
},
];

View File

@@ -25,6 +25,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
'las-vegas': () => import('./las-vegas'),
'cockroach-poker': () => import('./cockroach-poker'),
'ninety-nine': () => import('./ninety-nine'),
'connect-four': () => import('./connect-four'),
dobble: () => import('./dobble'),
catchmind: () => import('./catchmind'),
mafia: () => import('./mafia'),

View File

@@ -27,6 +27,7 @@ export const GAME_ICON: Record<string, string> = {
mafia: '🌙',
apple: '🍎',
clue: '🔎',
'connect-four': '🔴',
};
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
@@ -35,6 +36,7 @@ export const UPCOMING: string[] = [];
/** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
{ key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'clue'] },
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] },
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'mahjong', 'rummikub', 'davinci-code'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] },
];