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

- 규칙 모듈 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'] },
];

View File

@@ -41,6 +41,7 @@
| `mafia` | 마피아 | 4~12 | M8 |
| `apple` | 사과 게임(합 10 만들기, 같은 판 경주) | 1~8 | M9 |
| `clue` | 클루 | 3~6 | M9 |
| `connect-four` | 커넥트 포(사목) | 2 | M9 |
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).

134
docs/games/connect-four.md Normal file
View File

@@ -0,0 +1,134 @@
# 커넥트 포 (사목) (`connect-four`)
> 마일스톤: M9 · 인원: 최소 2 ~ 최대 2명 · 예상 시간: 약 3~10분 · 난이도: 쉬움
## 1. 개요
- 세워 놓은 판의 열을 골라 돌을 떨어뜨리고, 가로·세로·대각선으로 내 돌 4개를 먼저 잇는 2인 게임. 1974년 밀턴 브래들리(하워드 웩슬러·네드 스트롱긴) 출시. 규칙이 10초면 설명되고 5분이면 끝나 아이와도 자주 한다.
- 인원 근거: 원작이 빨강·노랑 2인 게임. 최소 2, 최대 2.
- 표시 이름은 **커넥트 포**(일반 이름 "사목"은 카탈로그 소개 문구에 함께 적음). 친구끼리 쓰는 사이트라 원래 이름을 그대로 쓰는 방침(`README.md` 5절)을 따른다.
- 완전 정보 게임. view에서 뺄 것이 없다(`secretsOf` 없음).
- 참고: 7×6 판은 1988년에 완전히 풀렸다(먼저 두는 쪽이 가운데 열부터 완벽하게 두면 이긴다). 그래서 컴퓨터 상대는 단계별로 일부러 실수를 섞는다(8.7).
## 2. 모드와 옵션
| 옵션 키 | 설명 | 선택지 | 기본값 |
|---|---|---|---|
| `boardSize` | 판 크기(가로 열 × 세로 줄) | `7x6` / `8x7` / `9x7` | `7x6` |
| `colorAssignment` | 먼저 두는 사람(빨강) 정하기 — 오목·오셀로와 같은 관례 | `random` / `hostRed`(방장이 먼저) / `hostYellow`(방장이 나중) / `alternate`(판마다 번갈아, `gameNo` 홀수 판은 방장이 빨강) | `random` |
| `timeControl.kind` | 시간 방식 | `none` / `perMove` / `fischer` | `perMove` |
| `timeControl.perMoveSec` | 한 수당 제한 | 10 / 20 / 30 / 60 (5~600) | 30 |
| `timeControl.baseSec` / `incSec` | 전체 시간 / 수당 추가 | 1분+2초, 3분+2초, 5분+3초 | 3분+2초 |
| `timeoutPolicy` | `perMove` 시간 초과 처리 | `autoMove` / `lose` | `autoMove` |
| `autoMoveLimit` | 연속 자동 두기 허용 횟수(넘으면 시간패) | 0~20 | 2 |
## 3. 구성물
- 세워 놓은 판: 7열 × 6줄(42칸). 옵션으로 8×7(56칸), 9×7(63칸).
- 빨강·노랑 원반. 원작은 21개씩이지만 엔진은 개수를 세지 않는다(칸 수가 상한이고 번갈아 두므로 자연히 반씩).
- 좌표: 열은 왼쪽부터 1, 2, 3…(화면·기보 표기 "4열"), 줄은 아래에서부터 센다. 내부 `(x, y)`는 `x` 0부터, `y` 0이 맨 위 줄(판 배열 `y*cols + x`).
## 4. 준비(셋업)
1. 빈 판.
2. `colorAssignment`로 빨강(먼저)·노랑(나중)을 정한다.
3. 빨강이 먼저 둔다.
## 5. 진행 규칙
- 차례에 꽉 차지 않은 열 하나를 고른다. 원반은 그 열의 가장 아래 빈칸으로 떨어진다.
- 꽉 찬 열은 고를 수 없다("그 줄은 꽉 찼어요."). 패스는 없다(판이 다 차기 전엔 항상 둘 곳이 있다).
- 번갈아 계속한다.
- 예시: 맨 아래 줄 2·3·4열에 내 원반이 있고 1열과 5열이 비어 있으면, 상대가 한쪽을 막아도 반대쪽이 남아 다음 차례에 4개가 이어진다.
## 6. 승패와 점수 계산
- 놓은 원반을 포함해 가로·세로·대각선 중 하나로 같은 색 4개 이상이 이어지면 그 즉시 승리. 5개 이상 이어져도 승리(원작과 같음).
- 모든 칸이 찼는데 아무도 못 이으면 무승부.
- 점수는 없다(결과 화면에 `scoreText` 없음, `result-score.test.ts`의 NO_SCORE).
- 그 외 종료: 기권, 시간패. 무승부 합의는 없다(7절).
## 7. 지역 룰 / 하우스 룰 (옵션으로 켜고 끄기)
- 판 크기 8×7, 9×7: 원작 변형 판(대형판)에 맞춘 크기. 규칙은 같고 이기기 조건도 4개.
- **일부러 뺀 것**
- 무르기, 무승부 제안: 한 판이 몇 분이고 판이 차면 저절로 비기므로 넣지 않았다(오목·오셀로와 다른 점).
- "Pop Out"(맨 아래 원반 빼기), "5개 잇기" 같은 변형: 원작 기본 규칙만.
- 처음 몇 수를 정해 두는 대회식 오프닝: 친구끼리 하는 사이트라 넣지 않음.
## 8. 엔진 설계
### 8.1 상태(State)
```ts
type Color = 'red' | 'yellow'; // 빨강 = 디스크 1 = 먼저
type Cell = 0 | 1 | 2;
interface ConnectFourState {
options: ConnectFourOptions;
cols: number; rows: number; // 7×6 / 8×7 / 9×7
board: Cell[]; // y*cols + x, y = 0 이 맨 위 줄
players: Record<Color, PlayerId>;
turn: Color;
moves: { color: Color; x: number; y: number; at: number; auto: boolean }[];
phase: 'playing' | 'finished';
winLine: { x: number; y: number }[] | null; // 이긴 줄(4개 이상, 두 줄을 동시에 만들면 둘 다)
clock: { remainingMs: Record<Color, number>; turnStartedAt: number; autoMoveStreak: Record<Color, number> };
result: { winner: Color | null; reason: 'four' | 'boardFull' | 'resign' | 'timeLoss'; moveCount: number; summary: string } | null;
}
```
### 8.2 액션
| type | payload | 누가 / 언제 | 검증 조건 |
|---|---|---|---|
| `drop` | `{ col }` | 차례인 플레이어, `playing` | `0 ≤ col < cols`("판 밖이에요."), 맨 위 칸이 비어 있음("그 줄은 꽉 찼어요.") |
| `resign` | `{}` | 플레이어, 언제든(상대 차례에도) | — |
| `timeout` | `{}` | 시스템 | 8.5 |
- 이벤트: `dropped { color, x, y, auto }`(떨어지는 애니메이션·소리), `win`, `draw`, `timeoutAutoMove`, `timeLoss`, `resigned`.
### 8.3 공개/비공개 정보 (view)
- 모두 공개: 판, 차례, 내 색(`myColor`, 관전자는 null), 마지막 수, 기보(`moves`, 시각 제외), 이긴 줄, 시계, 결과.
### 8.4 랜덤 요소 (시드 RNG 사용 지점)
1. `colorAssignment=random`.
2. 자동 두기에서 같은 우선순위의 열이 여러 개일 때 고르기.
### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동
- `deadline`: `perMove` → `turnStartedAt + perMoveSec*1000`, `fischer` → `turnStartedAt + remainingMs[turn]`, `none` → `null`.
- `onTimeout` → `{ type: 'timeout' }`.
- `perMove + autoMove`이고 연속 자동 두기가 `autoMoveLimit` 미만: 자동 두기. 순서: ① 내가 바로 4개를 잇는 열 ② 상대가 바로 4개를 잇는 열 막기 ③ 그 위 칸에서 상대가 이기게 받쳐 주지 않는 열 중 가운데에 가장 가까운 열(같으면 시드 RNG) ④ 아무 열.
- 그 외(`lose`, `fischer`, 횟수 초과): 시간패.
- `fischer`: `drop` 때 쓴 시간을 빼고 0 이하면 시간패, 아니면 `incSec` 더함.
- 나가기(`onLeave`) = 기권.
### 8.6 종료 조건과 결과(GameResult)
- `four`(4개 연결) / `boardFull`(무승부) → `reason: 'normal'`, `resign` → `'resign'`, `timeLoss` → `'timeout'`.
- 순위: 승자 1등, 패자 2등. 무승부는 둘 다 1등.
- 요약(`summary`): "빨강 승 (4개 연결, 17수)", "노랑 기권으로 빨강 승", "빨강 시간패로 노랑 승", "무승부 (42칸이 모두 찼어요)".
### 8.7 컴퓨터 상대 (`bot.ts`, `search.ts`)
- 탐색: 네가맥스 알파베타 + 반복 심화 + 치환표(조브리스트 해시 64비트, 2^17칸, 판마다 세대 표시로 초기화). 열 순서는 가운데부터, 치환표의 최선 수를 먼저.
- 모든 노드에서 먼저 "지금 4개를 잇는 열"(바로 승리)과 "상대가 지금 4개를 잇는 열"을 본다. 상대 위협이 2곳이면 진 판, 1곳이면 그 열만 둔다(강제 수).
- 평가: 4칸짜리 줄(창) 전부를 한쪽 색만 들어 있을 때 1개 1점·2개 4점·3개 16점, 3개짜리 줄의 빈칸이 그 색에 유리한 줄(빨강은 아래에서 홀수 번째 줄, 노랑은 짝수 번째 줄 — 끝까지 가면 그 칸을 차지하는 쪽)이면 +24, 가운데 열 원반 +3. 창 값은 돌을 놓고 뺄 때마다 바뀐 창만 다시 계산(증분)해서 한 노드가 빠르다.
- 단계(1~60): 읽는 깊이 = `1 + round((레벨-1)×9/59)` 수(레벨 1은 자기 수만, 10 → 2수, 30 → 5수, 50 → 8수, 60 → 10수). 어려움(41~)은 빈칸이 24개 이하로 줄면 끝까지 읽기를 시도한다. 한 수에 볼 수 있는 국면은 5만 개(`MAX_NODES`)로 제한하고, 그 안에 못 끝낸 깊이는 버리고 바로 앞 깊이 결과를 쓴다.
- 사람 같은 실수: 루트의 열 점수를 공통 `humanBest`(쉬움은 자주 조금 못한 수, 가끔 실수)에 넘긴다. 내 4목·상대 4목 막기는 "꼭 둬야 하는 수"로 표시해, 낮은 단계는 정해진 확률(`miss`, 레벨 1 약 20%, 10 약 12%, 30 약 3%, 50 이상 0%)로 못 보고 지나친다.
- 측정(이 서버, 7×6, 레벨 60, 한 수): 평균 약 4ms, 최악 약 20~30ms. 9×7도 최악 30ms 안쪽(`BOT_SLOW_MS` = 50ms). 단계별 대결(각 30판, 색 번갈아): 60 vs 10 → 29승 0패, 60 vs 30 → 26승 2패, 60 vs 45 → 21승 5패, 45 vs 30 → 21승 5패, 30 vs 10 → 26승 4패.
- 운(카드 섞기) 조정은 쓰지 않는다(`luck.ts`의 NO_LUCK — 정보가 다 보이는 판 게임).
## 9. UI/UX
- 판: 파란 틀에 구멍이 뚫린 세워진 판(SVG 마스크). 원반은 틀 뒤에 그려 떨어질 때 구멍 사이로 보인다. 맨 위에 "넣을 열" 미리 보기 원반, 떨어질 칸에 점선 동그라미, 아래에 열 번호 1~N.
- 떨어지는 애니메이션: 새 원반만, 떨어지는 높이에 비례해 0.2~0.6초. `prefers-reduced-motion`이면 애니메이션 없음(이긴 줄 깜빡임도 끔). 처음 들어오거나 새로 고침했을 땐 애니메이션 없음.
- 열 전체(미리 보기 줄 포함)가 터치 영역 — 7×6 판이 휴대폰 390px에서 열 너비 약 50px. 마우스는 한 번 누르면 바로 넣기(올려 두면 미리 보기). 터치는 "한 번 더 누르기 확인" 설정이 켜져 있으면 처음 누르면 미리 보기, 같은 열을 다시 누르거나 [N열에 넣기]로 확정.
- 키보드: 판(`role="grid"`)에 초점 → ←·→로 열 고르기, Home·End로 끝 열, Enter·Space로 넣기. 꽉 찬 열이면 스크린리더에 "N열은 꽉 찼어요" 안내. 둘 때마다 "빨강이 4열에 넣었어요. 아래에서 2번째 칸이에요." 읽어 줌.
- 마지막 수에 흰 점, 이긴 줄은 흰 고리로 강조(깜빡임).
- 오른쪽 패널(휴대폰은 판 아래): 두 사람(색, 먼저/나중, 남은 시간), 기권 버튼(확인 창), 기보("1. 🔴 4열", 자동 두기는 *).
- 다크 모드: 틀 색을 조금 어둡게, 구멍은 배경색.
- 30초 요약 3장: 열 골라 넣기 / 4개 이으면 승리 / 3개면 꼭 막기. [?] 도움말: 차례, 꽉 찬 열, 첫 수 가운데 팁, 3개 막기 팁.
## 10. 테스트 체크리스트
- [x] 판 크기 3종, 먼저 두는 사람 4가지(번갈아는 `gameNo` 홀짝).
- [x] 원반이 맨 아래 빈칸으로 떨어지고 쌓임. 꽉 찬 열·판 밖·남의 차례·관전자 거부.
- [x] 가로·세로·두 대각선 4개 즉시 승리, 3개는 계속, 5개 연결은 다섯 칸 모두 강조.
- [x] 42칸이 다 차면 무승부(순위 공동 1등).
- [x] 기권(상대 차례에도), 나가기 = 기권.
- [x] 시간: 수마다 마감 갱신, 자동 두기 승리 > 막기 > 받쳐 주지 않는 가운데 열, 같은 시드 같은 수, 허용 횟수 넘으면 시간패, `lose`·`autoMoveLimit 0`, 피셔 증가·초과패, 제한 없음.
- [x] 무작위 대국(판 크기별) 끝까지·결정적·빠름.
- [x] 컴퓨터: 첫 수 가운데, 이기는 수 > 막기, 4목 막기, 상대 승리 칸 밑에 안 두기, 양쪽 열린 3 미리 막기, 강한 단계는 몇 수 앞 강제 승 찾기, 레벨별 깊이, 낮은 단계만 막기를 가끔 놓침, 강한 단계가 약한 단계를 이김, 모든 판 크기에서 한 수 100ms 미만(실제 수십 ms 안쪽).
- [x] E2E(`e2e/games.e2e.ts` `connect-four`): PC 방장 키보드 + 휴대폰 친구 터치로 13수, 꽉 찬 열 누름 무시, 맨 아래 줄 5개로 빨강 승, 이긴 줄 5칸 강조, 결과 창.
## 11. 참고 자료
- 원작 규칙서(Hasbro Connect 4), 존 트롬프(John Tromp)의 7×6 해 풀이, 빅터 앨리스(Victor Allis) "A Knowledge-based Approach of Connect-Four"(1988, 홀짝 줄 위협 규칙).
## 12. 메모 (상표·법적 주의 등)
- "Connect 4"는 해즈브로 상표. `README.md` 5절 방침대로 이름은 "커넥트 포"를 쓰고, 일반 이름 "사목"을 소개 문구에 함께 적어 둔다. 표시 이름은 관리자 사이트에서 언제든 바꿀 수 있다. 판·원반 그림은 직접 만든 SVG.

View File

@@ -1208,6 +1208,80 @@ const PLANS: Record<string, Plan> = {
// cursor starts at d4 (3,3): black d3 = up; then white c3 = up, left
moves: [['ArrowUp', 'Enter'], ['ArrowUp', 'ArrowLeft', 'Enter']],
},
'connect-four': {
// 방장(PC, 빨강, 먼저)은 키보드(Home → 오른쪽 화살표 → Enter)로, 친구(휴대폰, 노랑)는 열을 직접 눌러서 둔다.
// 1열을 끝까지 채운 뒤 친구가 꽉 찬 1열을 눌러도 아무 일이 없는지 보고, 빨강이 맨 아래 줄 다섯 개(1~5열)로 이긴다.
lobby: async (host) => {
await host.getByRole('button', { name: '방장이 먼저', exact: true }).click();
await host.getByText(/방장 먼저/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const grid = (p: Page) => p.locator('svg[role="grid"]').first();
await grid(host).waitFor();
await grid(guest).waitFor();
const discs = (p: Page) => p.locator('svg[role="grid"] circle[r="0.41"]').count();
const myTurn = (p: Page) => p.waitForFunction(() => !!document.querySelector('.turn-status')?.textContent?.includes('내 차례예요'), null, { timeout: 10_000 });
const waitDiscs = async (n: number) => {
for (const p of pages) await p.waitForFunction((k) => document.querySelectorAll('svg[role="grid"] circle[r="0.41"]').length >= k, n, { timeout: 10_000 });
};
const hostDrop = async (col: number) => {
await myTurn(host);
await grid(host).focus();
await host.keyboard.press('Home');
for (let i = 0; i < col; i++) await host.keyboard.press('ArrowRight');
await host.keyboard.press('Enter');
};
const guestDrop = async (col: number) => {
await myTurn(guest);
await guest.locator(`svg[role="grid"] rect[data-col="${col}"]`).tap();
const confirm = guest.getByRole('button', { name: `${col + 1}열에 넣기` });
if (await confirm.isVisible().catch(() => false)) await confirm.click();
};
// 0-based columns: red 0, yellow 0, … fills column 1 (빨노빨노빨노), then the bottom-row fight.
const plan: ['h' | 'g', number][] = [['h', 0], ['g', 0], ['h', 0], ['g', 0], ['h', 0], ['g', 0], ['h', 3], ['g', 3], ['h', 2], ['g', 2], ['h', 4], ['g', 4], ['h', 1]];
let n = 0;
for (const [who, col] of plan) {
if (who === 'g' && n === 7) {
// Column 1 is full: tapping it does nothing (still the guest's turn, same number of discs).
await myTurn(guest);
await guest.locator('svg[role="grid"] rect[data-col="0"]').tap();
await guest.waitForTimeout(400);
if ((await discs(guest)) !== 7) throw new Error('a disc went into the full column');
if (!(await guest.locator('.turn-status').innerText()).includes('내 차례예요')) throw new Error('turn passed after tapping a full column');
}
await (who === 'h' ? hostDrop(col) : guestDrop(col));
n++;
await waitDiscs(n);
if (n === 10) {
await host.waitForTimeout(500);
await host.screenshot({ path: join(SHOTS, 'connect-four-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'connect-four-mid-phone.png') });
await guest.screenshot({ path: join(SHOTS, 'connect-four-mid-phone-full.png'), fullPage: true });
await host.emulateMedia({ colorScheme: 'dark' });
await guest.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(300);
await host.screenshot({ path: join(SHOTS, 'connect-four-mid-pc-dark.png') });
await guest.screenshot({ path: join(SHOTS, 'connect-four-mid-phone-dark.png') });
await host.emulateMedia({ colorScheme: 'light' });
await guest.emulateMedia({ colorScheme: 'light' });
}
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 10_000 });
const rings = await host.locator('svg[role="grid"] circle.c4-win').count();
if (rings !== 5) throw new Error(`expected the 5-disc line lit, got ${rings}`);
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'connect-four-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'connect-four-result-phone.png') });
const summary = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!summary.includes('빨강 승 (5개 연결, 13수)')) throw new Error(`unexpected result: ${summary.slice(0, 120)}`);
// Close the result to look at the lit line.
await host.keyboard.press('Escape');
await host.waitForTimeout(400);
await host.screenshot({ path: join(SHOTS, 'connect-four-final-board-pc.png') });
console.log(` connect-four: ${n} drops (keyboard + taps), full column refused, ${summary.split('\n').find((l) => l.includes('빨강 승'))}`);
},
},
chess: {
// cursor starts on the e-file pawn of whoever is at the bottom: white e2-e4, black d7-d5 (board flipped)
moves: [['Enter', 'ArrowUp', 'ArrowUp', 'Enter'], ['Enter', 'ArrowUp', 'ArrowUp', 'Enter']],

View File

@@ -50,7 +50,7 @@ test('decideBotAction returns null when the bot has nothing to do', () => {
});
describe('levels (docs/09 §9.1)', () => {
const BOARD = ['omok', 'chess', 'janggi', 'othello', 'baduk'];
const BOARD = ['omok', 'chess', 'janggi', 'othello', 'baduk', 'connect-four'];
test.each(BOARD)('%s: the weakest and strongest computers still finish a game against each other', (id) => {
const def = GAMES[id]!;
for (const level of [1, 60]) {

View File

@@ -32,6 +32,7 @@ import { ninetyNineBot } from '../ninety-nine/bot';
import { mafiaBot } from '../mafia/bot';
import { appleBot } from '../apple/bot';
import { clueBot } from '../clue/bot';
import { connectFourBot } from '../connect-four/bot';
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -62,6 +63,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
'cockroach-poker': cockroachPokerBot,
'ninety-nine': ninetyNineBot,
clue: clueBot,
'connect-four': connectFourBot,
};
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */

View File

@@ -33,8 +33,8 @@ describe('luck', () => {
});
test('luck is for games with cards, tiles, dice or hidden roles — not for board games', () => {
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'mafia', 'dobble']) expect(luckApplies(id)).toBe(false);
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor'].includes(g))) {
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four', 'mafia', 'dobble']) expect(luckApplies(id)).toBe(false);
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four'].includes(g))) {
expect(luckApplies(id)).toBe(true);
}
});

View File

@@ -10,7 +10,7 @@ import { BOT_STRATEGIES, decideBotAction } from './index';
import type { BotLevel } from './persona';
/** Games where everything is in view from the start: a shuffle only decides who goes first, so luck stays out. */
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor']);
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'connect-four']);
export const luckApplies = (gameId: string): boolean => gameId in BOT_STRATEGIES && !NO_LUCK.has(gameId);

View File

@@ -0,0 +1,122 @@
/** 커넥트 포 computer player: wins, blocks, reads traps at higher levels, slips like a person at low ones, stays fast. */
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { connectFour, type ConnectFourAction, type ConnectFourOptions, type ConnectFourState } from './index';
import { searchDepth } from './bot';
import { scoreColumns, WIN } from './search';
function make(opts: Partial<ConnectFourOptions> = {}): ConnectFourState {
const options = connectFour.optionsSchema.parse({ colorAssignment: 'hostRed', ...opts });
return connectFour.setup({ players: ['A', 'B'], options, rng: SeededRng.fromSeed([1, 2, 3, 4]), now: 0 });
}
function play(s: ConnectFourState, cols: number[]): ConnectFourState {
for (const col of cols) s = connectFour.apply(s, s.players[s.turn], { type: 'drop', col }, { rng: SeededRng.fromSeed([1, 1, 1, 1]), now: 0 }).state;
return s;
}
const decide = (s: ConnectFourState, seed = 1, level?: number) => {
const r = SeededRng.fromSeed([seed, 9, 9, 9]);
return decideBotAction(connectFour, s, s.players[s.turn], { now: 1000, random: () => r.next(), level }) as ConnectFourAction;
};
const col = (a: ConnectFourAction) => (a as { col: number }).col;
describe('connect-four bot', () => {
test('opens in the centre column', () => {
for (let seed = 1; seed <= 3; seed++) expect(col(decide(make(), seed))).toBe(3);
});
test('takes its four over blocking', () => {
// Red 0-1-2 on the bottom, yellow 4-5-6 on the bottom too; red to move wins at 3 (which also blocks).
const s = play(make(), [0, 0, 1, 1, 2, 6]);
expect(col(decide(s))).toBe(3);
// Yellow with its own vertical three and red's horizontal threat: yellow wins on top of column 6.
const y = play(make(), [0, 6, 1, 6, 5, 6, 2]);
expect(col(decide(y))).toBe(6);
});
test('blocks a four', () => {
const s = play(make(), [0, 0, 1, 1, 2]);
for (let seed = 1; seed <= 4; seed++) expect(col(decide(s, seed))).toBe(3);
});
test('does not drop under the opponent’s winning cell', () => {
// Yellow owns row 2 at columns 0-2 and waits on (3, 1); red must not fill (3, 0).
const s = play(make(), [0, 1, 2, 0, 6, 1, 6, 2]);
for (let seed = 1; seed <= 4; seed++) expect(col(decide(s, seed))).not.toBe(3);
});
test('sees the open-ended three on the bottom row (two threats at once) and stops it early', () => {
// Red on 2 and 3 of the bottom row with 1 and 4 open: yellow must take 1 or 4 now, or red makes 1-2-3 / 2-3-4 open
// at both ends and wins.
const s = play(make(), [3, 3, 2]);
for (let seed = 1; seed <= 4; seed++) expect([1, 4]).toContain(col(decide(s, seed)));
});
test('a strong level finds a forced win a few moves deep', () => {
// Red: bottom 1, 2, 3 is blocked at 0 and 4? No — red makes two threats at once: (1,0) (2,0) open both sides.
const s = play(make(), [3, 3, 2, 2]);
// Red to move: 1 or 4 makes an open three on the bottom row with both ends open → a win in 3 plies.
const scores = scoreColumns(7, 6, s.board, 1, 5);
const best = Math.max(...scores.values());
expect(best).toBeGreaterThan(WIN / 2);
for (let seed = 1; seed <= 4; seed++) expect([1, 4]).toContain(col(decide(s, seed, 60)));
});
test('level sets the reading depth: 1 ply at level 1, 10 at level 60', () => {
expect(searchDepth(1)).toBe(1);
expect(searchDepth(10)).toBe(2);
expect(searchDepth(30)).toBe(5);
expect(searchDepth(50)).toBe(8);
expect(searchDepth(60)).toBe(10);
for (let l = 2; l <= 60; l++) expect(searchDepth(l)).toBeGreaterThanOrEqual(searchDepth(l - 1));
});
test('a weak level sometimes overlooks the block, a strong one never does', () => {
const s = play(make(), [0, 0, 1, 1, 2]);
let missed = 0;
for (let seed = 1; seed <= 300; seed++) if (col(decide(s, seed, 1)) !== 3) missed++;
expect(missed).toBeGreaterThan(20);
expect(missed).toBeLessThan(120);
for (let seed = 1; seed <= 100; seed++) expect(col(decide(s, seed, 50))).toBe(3);
});
test('stronger computers beat weaker ones', () => {
const match = (strong: number, weak: number, games: number) => {
let wins = 0;
let losses = 0;
for (let g = 0; g < games; g++) {
let s = make();
const r = SeededRng.fromSeed(seedN(1000 + g));
// The strong side alternates colours.
const strongColor = g % 2 === 0 ? 'red' : 'yellow';
while (s.phase === 'playing') {
const level = s.turn === strongColor ? strong : weak;
const a = decideBotAction(connectFour, s, s.players[s.turn], { now: 0, random: () => r.next(), level });
s = connectFour.apply(s, s.players[s.turn], a as ConnectFourAction, { rng: r, now: 0 }).state;
}
if (s.result!.winner === strongColor) wins++;
else if (s.result!.winner) losses++;
}
return { wins, losses };
};
const a = match(60, 10, 10);
expect(a.wins).toBeGreaterThanOrEqual(8);
const b = match(50, 25, 10);
expect(b.wins).toBeGreaterThan(b.losses);
});
test('every move stays fast, on every board size and level', () => {
for (const boardSize of ['7x6', '8x7', '9x7'] as const) {
let s = make({ boardSize });
const r = SeededRng.fromSeed(seedN(5));
let worst = 0;
while (s.phase === 'playing') {
const t0 = performance.now();
const a = decideBotAction(connectFour, s, s.players[s.turn], { now: 0, random: () => r.next(), level: 60 });
worst = Math.max(worst, performance.now() - t0);
s = connectFour.apply(s, s.players[s.turn], a as ConnectFourAction, { rng: r, now: 0 }).state;
}
expect(worst).toBeLessThan(100);
}
});
});

View File

@@ -0,0 +1,44 @@
/**
* 커넥트 포 computer player (docs/games/connect-four.md §8.7): reads ahead with alpha-beta (`search.ts`). The level sets how
* far it reads (1 … 10 plies, within a fixed node budget so a move takes a few ms) and, through `humanBest`, how often it
* plays a slightly worse column or overlooks a four — its own or the opponent's.
*/
import type { BotStrategy } from '../bots/types';
import { humanBest, pick, playable, typeOf } from '../bots/policy';
import type { BotLevel } from '../bots/persona';
import type { ConnectFourView } from './index';
import { DECIDED, Position, WIN, scoreColumns } from './search';
type Drop = { type: 'drop'; col: number };
/** Eval units: an open two is 4, an open three 16; a small inaccuracy is about one open two. */
const SMALL = 5;
/** Positions a move may look at (a few ms on the server; docs §8.7 has the measurements). */
export const MAX_NODES = 50_000;
/** Empty cells from which 어려움 computers try to read the game to the end. */
const ENDGAME = 24;
/** Plies read ahead: level 1 only looks at its own move, level 60 ten plies. */
export function searchDepth(level: BotLevel | undefined): number {
const L = Math.min(Math.max(level ?? 60, 1), 60);
return 1 + Math.round(((L - 1) * 9) / 59);
}
export const connectFourBot: BotStrategy<ConnectFourView> = ({ view, legal, random, level }) => {
const drops = legal.filter((a) => typeOf(a) === 'drop') as Drop[];
if (!drops.length || !view.myColor) return pick(playable(legal), random);
const me = view.myColor === 'red' ? 1 : 2;
// 어려움 computers read the endgame to the last disc once few cells are left (the node budget still caps it).
const empty = view.board.filter((c) => c === 0).length;
const depth = (level ?? 60) > 40 && empty <= ENDGAME ? Math.max(empty, searchDepth(level)) : searchDepth(level);
const scores = scoreColumns(view.cols, view.rows, view.board, me, depth, { maxNodes: MAX_NODES, margin: 8 * SMALL });
// Blocking the opponent's four counts as a must-play move like taking our own: low levels sometimes overlook it.
const pos = new Position(view.cols, view.rows, view.board);
const oppWins = drops.filter((d) => pos.winsNow(d.col, 3 - me));
const mustBlock = oppWins.length === 1 && !drops.some((d) => pos.winsNow(d.col, me)) ? oppWins[0]!.col : -1;
return humanBest(drops, (d) => (scores.get(d.col) ?? -WIN) + (d.col === mustBlock ? 2 * WIN : 0), random, level, {
small: SMALL,
critical: DECIDED,
});
};

View File

@@ -0,0 +1,209 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { connectFour, type ConnectFourAction, type ConnectFourOptions, type ConnectFourState } from './index';
/** Host A, guest B; A is 빨강 (moves first) unless the options say otherwise. */
function make(opts: Partial<ConnectFourOptions> = {}, gameNo = 1): ConnectFourState {
const options = connectFour.optionsSchema.parse({ colorAssignment: 'hostRed', ...opts });
return connectFour.setup({ players: ['A', 'B'], options, rng: SeededRng.fromSeed([1, 2, 3, 4]), now: 0, gameNo });
}
const rng = () => SeededRng.fromSeed([4, 3, 2, 1]);
function play(s: ConnectFourState, cols: number[], now = 1000): ConnectFourState {
for (const col of cols) {
const actor = s.players[s.turn];
const a: ConnectFourAction = { type: 'drop', col };
const v = connectFour.validate(s, actor, a);
if (!v.ok) throw new Error(v.reason);
s = connectFour.apply(s, actor, a, { rng: rng(), now }).state;
}
return s;
}
const disc = (s: ConnectFourState, x: number, yFromBottom: number) => s.board[(s.rows - 1 - yFromBottom) * s.cols + x];
describe('setup and options', () => {
test('7 × 6 by default, 8 × 7 and 9 × 7 on request', () => {
expect(make()).toMatchObject({ cols: 7, rows: 6, turn: 'red' });
expect(make().board).toHaveLength(42);
expect(make({ boardSize: '8x7' })).toMatchObject({ cols: 8, rows: 7 });
expect(make({ boardSize: '9x7' }).board).toHaveLength(63);
});
test('who moves first: host / guest / alternating by game number', () => {
expect(make({ colorAssignment: 'hostRed' }).players).toEqual({ red: 'A', yellow: 'B' });
expect(make({ colorAssignment: 'hostYellow' }).players).toEqual({ red: 'B', yellow: 'A' });
expect(make({ colorAssignment: 'alternate' }, 1).players.red).toBe('A');
expect(make({ colorAssignment: 'alternate' }, 2).players.red).toBe('B');
expect(make({ colorAssignment: 'alternate' }, 3).players.red).toBe('A');
const reds = new Set<string>();
for (let i = 0; i < 20; i++) {
const options = connectFour.optionsSchema.parse({ colorAssignment: 'random' });
reds.add(connectFour.setup({ players: ['A', 'B'], options, rng: SeededRng.fromSeed(seedN(i)), now: 0 }).players.red);
}
expect(reds).toEqual(new Set(['A', 'B']));
});
});
describe('dropping', () => {
test('a disc falls to the lowest empty cell and stacks', () => {
const s = play(make(), [3, 3, 3]);
expect(disc(s, 3, 0)).toBe(1);
expect(disc(s, 3, 1)).toBe(2);
expect(disc(s, 3, 2)).toBe(1);
expect(s.moves.map((m) => m.y)).toEqual([5, 4, 3]);
expect(connectFour.view(s, 'A').lastMove).toEqual({ x: 3, y: 3 });
});
test('a full column, a column off the board, the wrong turn and strangers are refused', () => {
const s = play(make(), [0, 0, 0, 0, 0, 0]);
expect(connectFour.validate(s, 'A', { type: 'drop', col: 0 })).toEqual({ ok: false, reason: '그 줄은 꽉 찼어요.' });
expect(connectFour.validate(s, 'A', { type: 'drop', col: 7 })).toEqual({ ok: false, reason: '판 밖이에요.' });
expect(connectFour.validate(s, 'B', { type: 'drop', col: 1 })).toEqual({ ok: false, reason: '지금은 내 차례가 아니에요.' });
expect(connectFour.validate(s, 'Z', { type: 'resign' }).ok).toBe(false);
expect(connectFour.legalActions!(s, 'A').map((a) => (a as { col: number }).col)).toEqual([1, 2, 3, 4, 5, 6]);
expect(connectFour.legalActions!(s, 'B')).toEqual([]);
// 9 columns on the wide board.
expect(connectFour.validate(make({ boardSize: '9x7' }), 'A', { type: 'drop', col: 8 }).ok).toBe(true);
});
});
describe('four in a row', () => {
test.each([
['horizontal', [0, 0, 1, 1, 2, 2, 3]],
['vertical', [4, 5, 4, 5, 4, 5, 4]],
// ↗: red at (0,0) (1,1) (2,2) (3,3)
['diagonal ↗', [0, 1, 1, 2, 2, 3, 2, 3, 3, 6, 3]],
// ↖: red at (6,0) (5,1) (4,2) (3,3)
['diagonal ↖', [6, 5, 5, 4, 4, 3, 4, 3, 3, 0, 3]],
])('%s wins at once and lights the line', (_n, cols) => {
const s = play(make(), cols as number[]);
expect(s.phase).toBe('finished');
expect(s.result).toMatchObject({ winner: 'red', reason: 'four' });
expect(s.winLine).toHaveLength(4);
expect(connectFour.result(s)).toMatchObject({ ranking: [['A'], ['B']], reason: 'normal' });
expect(connectFour.result(s)!.summary).toMatch(/^빨강 승 \(4개 연결, \d+수\)$/);
expect(connectFour.activePlayers(s)).toEqual([]);
expect(connectFour.legalActions!(s, 'B')).toEqual([]);
expect(connectFour.validate(s, 'B', { type: 'drop', col: 6 })).toEqual({ ok: false, reason: '게임이 이미 끝났어요.' });
});
test('yellow wins too; three in a row is not a win', () => {
const three = play(make(), [0, 6, 1, 6, 2]);
expect(three.phase).toBe('playing');
const s = play(make(), [0, 6, 1, 6, 0, 6, 1, 6]);
expect(s.result?.winner).toBe('yellow');
expect(connectFour.result(s)!.ranking).toEqual([['B'], ['A']]);
});
test('a disc filling the gap of 3 + 1 lights all five when the line is longer than four', () => {
// red: 0, 1, 3, 4 on the bottom row, then 2 joins five.
const s = play(make(), [0, 0, 1, 1, 3, 3, 4, 4, 2]);
expect(s.result?.winner).toBe('red');
expect(s.winLine).toHaveLength(5);
expect(s.result?.summary).toContain('5개 연결');
});
});
describe('end of game', () => {
test('a full board without four is a draw', () => {
// Column pairs filled in the order 0,1 / 2,3 / 4,5 / 6 give alternating 2-high stripes, never four.
const order = [0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 2, 3, 2, 3, 3, 2, 3, 2, 2, 3, 2, 3, 4, 5, 4, 5, 5, 4, 5, 4, 4, 5, 4, 5, 6, 6, 6, 6, 6, 6];
let s = make();
s = play(s, order);
expect(s.moves).toHaveLength(42);
expect(s.result).toMatchObject({ winner: null, reason: 'boardFull' });
expect(connectFour.result(s)).toMatchObject({ ranking: [['A', 'B']], reason: 'normal' });
expect(s.result?.summary).toBe('무승부 (42칸이 모두 찼어요)');
});
test('resign (any time, even on the opponent’s turn) and leaving', () => {
const s = connectFour.apply(make(), 'B', { type: 'resign' }, { rng: rng(), now: 0 }).state;
expect(connectFour.result(s)).toMatchObject({ ranking: [['A'], ['B']], reason: 'resign', summary: '노랑 기권으로 빨강 승' });
expect(connectFour.onLeave!(make(), 'A')).toEqual({ type: 'resign' });
});
});
describe('time', () => {
test('per move: the clock restarts on each move; auto moves win > block, then lose after the allowed number', () => {
let s = make();
expect(connectFour.deadline!(s)).toBe(30_000);
s = play(s, [3], 5_000);
expect(connectFour.deadline!(s)).toBe(35_000);
// Red has 0-1-2 on the bottom row: yellow's auto move blocks column 3.
let t = play(make(), [0, 0, 1, 1, 2]);
t = connectFour.apply(t, 'B', { type: 'timeout' }, { rng: rng(), now: 9 }).state;
expect(t.moves.at(-1)).toMatchObject({ color: 'yellow', x: 3, y: 5, auto: true });
// Red's own four comes first.
let w = play(make(), [0, 6, 1, 6, 2, 5]);
w = connectFour.apply(w, 'A', { type: 'timeout' }, { rng: rng(), now: 9 }).state;
expect(w.result).toMatchObject({ winner: 'red', reason: 'four' });
// Two auto moves in a row are allowed, the third timeout loses.
let u = make();
for (let i = 0; i < 4; i++) u = connectFour.apply(u, u.players[u.turn], { type: 'timeout' }, { rng: rng(), now: i }).state;
expect(u.moves.every((m) => m.auto)).toBe(true);
u = connectFour.apply(u, 'A', { type: 'timeout' }, { rng: rng(), now: 9 }).state;
expect(u.result).toMatchObject({ winner: 'yellow', reason: 'timeLoss', summary: '빨강 시간패로 노랑 승' });
expect(connectFour.result(u)!.reason).toBe('timeout');
});
test('auto moves are deterministic, prefer the centre and avoid handing over a four on top', () => {
const a = connectFour.apply(make(), 'A', { type: 'timeout' }, { rng: rng(), now: 0 }).state;
const b = connectFour.apply(make(), 'A', { type: 'timeout' }, { rng: rng(), now: 0 }).state;
expect(a.moves[0]).toEqual(b.moves[0]);
expect(a.moves[0]!.x).toBe(3);
// Yellow holds row 2 (from the bottom) at columns 0-2; (3, 0) is empty. Dropping into column 3 would let yellow
// finish on top of it, so red's auto move takes the next most central column instead.
const s = connectFour.apply(play(make(), [0, 1, 2, 0, 6, 1, 6, 2]), 'A', { type: 'timeout' }, { rng: rng(), now: 0 }).state;
expect([2, 4]).toContain(s.moves.at(-1)!.x);
expect(s.phase).toBe('playing');
});
test('autoMoveLimit 0 and the lose policy end the game at the first timeout', () => {
for (const o of [{ autoMoveLimit: 0 }, { timeoutPolicy: 'lose' as const }]) {
const s = connectFour.apply(make(o), 'A', { type: 'timeout' }, { rng: rng(), now: 0 }).state;
expect(s.result).toMatchObject({ winner: 'yellow', reason: 'timeLoss' });
}
});
test('fischer: increment added, a late move loses', () => {
let s = make({ timeControl: { kind: 'fischer', perMoveSec: 30, baseSec: 60, incSec: 5 } });
expect(connectFour.deadline!(s)).toBe(60_000);
s = play(s, [3], 10_000);
expect(s.clock.remainingMs.red).toBe(55_000);
s = play(s, [3], 80_000); // yellow used 70 s of 60 s
expect(s.result).toMatchObject({ winner: 'red', reason: 'timeLoss' });
});
test('no time control: no deadline at all', () => {
const s = make({ timeControl: { kind: 'none', perMoveSec: 30, baseSec: 180, incSec: 2 } });
expect(connectFour.deadline!(s)).toBeNull();
expect(connectFour.deadline!(play(s, [3], 3_600_000))).toBeNull();
});
});
describe('views and playouts', () => {
test('everyone sees the same board; my colour per viewer', () => {
const s = play(make(), [3, 2]);
expect(connectFour.view(s, 'A').myColor).toBe('red');
expect(connectFour.view(s, 'B').myColor).toBe('yellow');
expect(connectFour.view(s, null).myColor).toBeNull();
expect(connectFour.view(s, null).board).toEqual(s.board);
expect(connectFour.view(s, null).moves).toEqual([
{ color: 'red', x: 3, y: 5, auto: false },
{ color: 'yellow', x: 2, y: 5, auto: false },
]);
});
test('random playouts finish, are deterministic and fast on every board size', () => {
const games = playoutSeeds(30);
for (const boardSize of ['7x6', '8x7', '9x7'] as const) {
for (let i = 0; i < games; i++) {
const options = connectFour.optionsSchema.parse({ boardSize });
const a = randomPlayout(connectFour, { players: ['A', 'B'], options, seed: seedN(i), maxApplyMs: 50 });
const b = randomPlayout(connectFour, { players: ['A', 'B'], options, seed: seedN(i), maxApplyMs: 50 });
expect(a.finished).toBe(true);
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
}
}
});
});

View File

@@ -0,0 +1,325 @@
/** 커넥트 포(사목, Connect Four) (docs/games/connect-four.md). */
import { z } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
import { SIZES, dropWins, landingRow, openColumns, winningCells, type BoardSize, type Cell, type Disc } from './rules';
export type { Cell } from './rules';
export type Color = 'red' | 'yellow';
const DISC: Record<Color, Disc> = { red: 1, yellow: 2 };
const other = (c: Color): Color => (c === 'red' ? 'yellow' : 'red');
const COLOR_KO: Record<Color, string> = { red: '빨강', yellow: '노랑' };
export const connectFourOptionsSchema = z.object({
boardSize: z
.enum(['7x6', '8x7', '9x7'])
.default('7x6')
.meta({ title: '판 크기(가로 × 세로)', labels: { '7x6': '7 × 6 (기본)', '8x7': '8 × 7', '9x7': '9 × 7' } }),
colorAssignment: z
.enum(['random', 'hostRed', 'hostYellow', 'alternate'])
.default('random')
.meta({ title: '먼저 두는 사람(빨강) 정하기', labels: { random: '무작위', hostRed: '방장이 먼저(빨강)', hostYellow: '방장이 나중(노랑)', alternate: '판마다 번갈아' } }),
timeControl: z
.object({
kind: z
.enum(['none', 'perMove', 'fischer'])
.default('perMove')
.meta({ title: '시간 방식', labels: { none: '제한 없음', perMove: '한 수당 제한', fischer: '전체 시간 + 수당 추가' } }),
perMoveSec: z.number().int().min(5).max(600).default(30).meta({ title: '한 수 제한(초)' }),
baseSec: z.number().int().min(60).max(3600).default(180).meta({ title: '전체 시간(초)' }),
incSec: z.number().int().min(0).max(60).default(2).meta({ title: '한 수마다 추가(초)' }),
})
.default({ kind: 'perMove', perMoveSec: 30, baseSec: 180, incSec: 2 })
.meta({ title: '시간 제한' }),
timeoutPolicy: z
.enum(['autoMove', 'lose'])
.default('autoMove')
.meta({ title: '한 수 시간이 다 되면', labels: { autoMove: '자동으로 두기', lose: '시간패' } }),
autoMoveLimit: z.number().int().min(0).max(20).default(2).meta({ title: '연속 자동 두기 허용 횟수(넘으면 시간패)' }),
});
export type ConnectFourOptions = z.infer<typeof connectFourOptionsSchema>;
export const connectFourActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('drop'), col: z.number().int().min(0).max(8) }),
z.object({ type: z.literal('resign') }),
]);
/** Client-sendable actions plus the system-only timeout action (not in the schema). */
export type ConnectFourAction = z.infer<typeof connectFourActionSchema> | { type: 'timeout' };
export interface Pt {
x: number;
y: number;
}
export type ConnectFourReason = 'four' | 'boardFull' | 'resign' | 'timeLoss';
export interface ConnectFourMove {
color: Color;
x: number;
y: number;
auto: boolean;
}
export interface ConnectFourState {
options: ConnectFourOptions;
cols: number;
rows: number;
board: Cell[];
players: Record<Color, PlayerId>;
turn: Color;
moves: (ConnectFourMove & { at: number })[];
phase: 'playing' | 'finished';
winLine: Pt[] | null;
clock: { remainingMs: Record<Color, number>; turnStartedAt: number; autoMoveStreak: Record<Color, number> };
result: { winner: Color | null; reason: ConnectFourReason; moveCount: number; summary: string } | null;
}
export interface ConnectFourView {
cols: number;
rows: number;
board: Cell[];
players: Record<Color, PlayerId>;
myColor: Color | null;
turn: Color;
lastMove: Pt | null;
moveCount: number;
moves: ConnectFourMove[];
phase: ConnectFourState['phase'];
winLine: Pt[] | null;
timeControl: ConnectFourOptions['timeControl'];
remainingMs: Record<Color, number>;
turnStartedAt: number;
result: ConnectFourState['result'];
}
const colorOf = (s: ConnectFourState, p: PlayerId): Color | null =>
s.players.red === p ? 'red' : s.players.yellow === p ? 'yellow' : null;
function finish(s: ConnectFourState, winner: Color | null, reason: ConnectFourReason): void {
s.phase = 'finished';
const n = s.moves.length;
let summary: string;
switch (reason) {
case 'four':
summary = `${COLOR_KO[winner!]} 승 (${s.winLine!.length}개 연결, ${n}수)`;
break;
case 'resign':
summary = `${COLOR_KO[other(winner!)]} 기권으로 ${COLOR_KO[winner!]} 승`;
break;
case 'timeLoss':
summary = `${COLOR_KO[other(winner!)]} 시간패로 ${COLOR_KO[winner!]} 승`;
break;
default:
summary = `무승부 (${n}칸이 모두 찼어요)`;
}
s.result = { winner, reason, moveCount: n, summary };
}
function drop(s: ConnectFourState, color: Color, col: number, now: number, auto: boolean, events: GameEvent[]): void {
const y = landingRow(s.board, s.cols, s.rows, col);
s.board[y * s.cols + col] = DISC[color];
s.moves.push({ color, x: col, y, at: now, auto });
events.push({ type: 'dropped', color, x: col, y, auto });
const line = winningCells(s.board, s.cols, s.rows, col, y, DISC[color]);
if (line.length) {
s.winLine = line.map((i) => ({ x: i % s.cols, y: Math.floor(i / s.cols) }));
finish(s, color, 'four');
events.push({ type: 'win', color });
return;
}
s.turn = other(color);
s.clock.turnStartedAt = now;
if (openColumns(s.board, s.cols).length === 0) {
finish(s, null, 'boardFull');
events.push({ type: 'draw' });
}
}
/**
* Timeout auto move (docs §8.5): connect four > block the opponent's four > a column that doesn't let the opponent win
* right on top of it, nearest the centre (random among equals) > any column.
*/
function chooseAutoMove(s: ConnectFourState, rng: Rng): number {
const board = s.board.slice();
const open = openColumns(board, s.cols);
const me = DISC[s.turn];
const opp = DISC[other(s.turn)];
const win = open.filter((c) => dropWins(board, s.cols, s.rows, c, me));
if (win.length) return win[rng.int(win.length)]!;
const block = open.filter((c) => dropWins(board, s.cols, s.rows, c, opp));
if (block.length) return block[rng.int(block.length)]!;
const safe = open.filter((c) => {
const y = landingRow(board, s.cols, s.rows, c);
board[y * s.cols + c] = me;
const bad = dropWins(board, s.cols, s.rows, c, opp);
board[y * s.cols + c] = 0;
return !bad;
});
const pool = safe.length ? safe : open;
const mid = (s.cols - 1) / 2;
const best = Math.min(...pool.map((c) => Math.abs(c - mid)));
const central = pool.filter((c) => Math.abs(c - mid) === best);
return central[rng.int(central.length)]!;
}
export const connectFour: GameDefinition<ConnectFourState, ConnectFourAction, ConnectFourView, ConnectFourOptions> = {
id: 'connect-four',
nameKo: '커넥트 포',
minPlayers: 2,
maxPlayers: 2,
stateVersion: 1,
defaultOptions: connectFourOptionsSchema.parse({}),
optionsSchema: connectFourOptionsSchema,
actionSchema: connectFourActionSchema as z.ZodType<ConnectFourAction>,
setup({ players, options, rng, now, gameNo }) {
const [host, guest] = players as [PlayerId, PlayerId];
let hostRed: boolean;
switch (options.colorAssignment) {
case 'hostRed':
hostRed = true;
break;
case 'hostYellow':
hostRed = false;
break;
case 'alternate':
hostRed = (gameNo ?? 1) % 2 === 1;
break;
default:
hostRed = rng.int(2) === 0;
}
const [cols, rows] = SIZES[options.boardSize as BoardSize];
const base = options.timeControl.baseSec * 1000;
return {
options,
cols,
rows,
board: new Array<Cell>(cols * rows).fill(0),
players: hostRed ? { red: host, yellow: guest } : { red: guest, yellow: host },
turn: 'red',
moves: [],
phase: 'playing',
winLine: null,
clock: { remainingMs: { red: base, yellow: base }, turnStartedAt: now, autoMoveStreak: { red: 0, yellow: 0 } },
result: null,
};
},
validate(s, actor, a) {
const me = colorOf(s, actor);
if (!me) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase !== 'playing') return fail('게임이 이미 끝났어요.');
switch (a.type) {
case 'drop':
if (s.turn !== me) return fail('지금은 내 차례가 아니에요.');
if (a.col >= s.cols) return fail('판 밖이에요.');
if (s.board[a.col] !== 0) return fail('그 줄은 꽉 찼어요.');
return ok;
case 'resign':
return ok;
case 'timeout':
if (s.turn !== me) return fail('지금은 내 차례가 아니에요.');
return ok;
}
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const me = colorOf(s, actor)!;
const events: GameEvent[] = [];
switch (a.type) {
case 'drop': {
if (s.options.timeControl.kind === 'fischer') {
s.clock.remainingMs[me] -= now - s.clock.turnStartedAt;
if (s.clock.remainingMs[me] <= 0) {
s.clock.remainingMs[me] = 0;
finish(s, other(me), 'timeLoss');
events.push({ type: 'timeLoss', color: me });
break;
}
s.clock.remainingMs[me] += s.options.timeControl.incSec * 1000;
}
s.clock.autoMoveStreak[me] = 0;
drop(s, me, a.col, now, false, events);
break;
}
case 'timeout': {
const tc = s.options.timeControl.kind;
if (tc === 'perMove' && s.options.timeoutPolicy === 'autoMove' && s.clock.autoMoveStreak[me] < s.options.autoMoveLimit) {
s.clock.autoMoveStreak[me]++;
events.push({ type: 'timeoutAutoMove', color: me });
drop(s, me, chooseAutoMove(s, rng), now, true, events);
} else {
if (tc === 'fischer') s.clock.remainingMs[me] = 0;
finish(s, other(me), 'timeLoss');
events.push({ type: 'timeLoss', color: me });
}
break;
}
case 'resign':
finish(s, other(me), 'resign');
events.push({ type: 'resigned', color: me });
break;
}
return { state: s, events };
},
view(s, viewer) {
const last = s.moves[s.moves.length - 1];
return {
cols: s.cols,
rows: s.rows,
board: s.board,
players: s.players,
myColor: viewer ? colorOf(s, viewer) : null,
turn: s.turn,
lastMove: last ? { x: last.x, y: last.y } : null,
moveCount: s.moves.length,
moves: s.moves.map((m) => ({ color: m.color, x: m.x, y: m.y, auto: m.auto })),
phase: s.phase,
winLine: s.winLine,
timeControl: s.options.timeControl,
remainingMs: s.clock.remainingMs,
turnStartedAt: s.clock.turnStartedAt,
result: s.result,
};
},
activePlayers(s) {
return s.phase === 'playing' ? [s.players[s.turn]] : [];
},
deadline(s) {
if (s.phase !== 'playing') return null;
const tc = s.options.timeControl;
const start = s.clock.turnStartedAt;
if (tc.kind === 'perMove') return start + tc.perMoveSec * 1000;
if (tc.kind === 'fischer') return start + s.clock.remainingMs[s.turn];
return null; // 시간 제한 없음: 차례 마감 없음
},
timeoutPlayers(s) {
return s.phase === 'playing' ? [s.players[s.turn]] : [];
},
onTimeout() {
return { type: 'timeout' };
},
onLeave() {
return { type: 'resign' };
},
result(s): GameResult | null {
if (!s.result) return null;
const { winner, reason, summary } = s.result;
const ranking = winner ? [[s.players[winner]], [s.players[other(winner)]]] : [[s.players.red, s.players.yellow]];
const map: Record<ConnectFourReason, GameResult['reason']> = { four: 'normal', boardFull: 'normal', resign: 'resign', timeLoss: 'timeout' };
return { ranking, summary, reason: map[reason] };
},
legalActions(s, p) {
const me = colorOf(s, p);
if (!me || s.phase !== 'playing' || s.turn !== me) return [];
return openColumns(s.board, s.cols).map((col) => ({ type: 'drop' as const, col }));
},
};

View File

@@ -0,0 +1,63 @@
/**
* 커넥트 포 rule core (docs/games/connect-four.md §5): dropping a disc and finding a line of four.
* Board is a flat array indexed y*cols+x, y = 0 at the top row; 0 empty, 1 red (first player), 2 yellow.
*/
export type Cell = 0 | 1 | 2;
export type Disc = 1 | 2;
export const DIRS: readonly (readonly [number, number])[] = [
[1, 0],
[0, 1],
[1, 1],
[1, -1],
];
/** Board sizes (columns × rows). */
export const SIZES = { '7x6': [7, 6], '8x7': [8, 7], '9x7': [9, 7] } as const;
export type BoardSize = keyof typeof SIZES;
/** Row a disc dropped into `col` lands on, or -1 when the column is full. */
export function landingRow(board: readonly Cell[], cols: number, rows: number, col: number): number {
for (let y = rows - 1; y >= 0; y--) if (board[y * cols + col] === 0) return y;
return -1;
}
/** Columns that still have room, left to right. */
export function openColumns(board: readonly Cell[], cols: number): number[] {
const out: number[] = [];
for (let x = 0; x < cols; x++) if (board[x] === 0) out.push(x);
return out;
}
/**
* Cells of every line of four or more through (x, y) for `disc` (all directions, so a disc closing two lines lights
* both); empty when there is none.
*/
export function winningCells(board: readonly Cell[], cols: number, rows: number, x: number, y: number, disc: Disc): number[] {
const out = new Set<number>();
const at = (cx: number, cy: number) => cx >= 0 && cy >= 0 && cx < cols && cy < rows && board[cy * cols + cx] === disc;
for (const [dx, dy] of DIRS) {
const line = [y * cols + x];
for (const sign of [1, -1]) {
let cx = x + dx * sign;
let cy = y + dy * sign;
while (at(cx, cy)) {
line.push(cy * cols + cx);
cx += dx * sign;
cy += dy * sign;
}
}
if (line.length >= 4) for (const i of line) out.add(i);
}
return [...out].sort((a, b) => a - b);
}
/** Would dropping `disc` into `col` connect four? (`board` is left unchanged.) */
export function dropWins(board: Cell[], cols: number, rows: number, col: number, disc: Disc): boolean {
const y = landingRow(board, cols, rows, col);
if (y < 0) return false;
board[y * cols + col] = disc;
const win = winningCells(board, cols, rows, col, y, disc).length > 0;
board[y * cols + col] = 0;
return win;
}

View File

@@ -0,0 +1,334 @@
/**
* 커넥트 포 search for the computer player (docs/games/connect-four.md §8.7): negamax with alpha-beta, a transposition
* table, centre-first move order, "win now / block now" checks at every node, and an incrementally kept score of the
* lines of four still open to each side (with a bonus for threats on the row parity that side wins the race for:
* 빨강, who moves first, odd rows from the bottom; 노랑 even rows).
*/
export const WIN = 1_000_000;
const INF = 1e9;
/** Scores beyond this are wins / losses found by the search. */
export const DECIDED = WIN / 2;
/** Window values by discs of one side in it (0 … 3); four is a win, handled by the search. */
const LINE = [0, 1, 4, 16];
/** A three whose empty cell is on the row parity its owner wins the race for. */
const PARITY = 24;
const CENTRE = 3;
interface Layout {
cols: number;
rows: number;
/** 4 cell indices per window (cell index = x * rows + h, h = 0 at the bottom). */
winCells: Int16Array;
/** Windows through each cell: `cellWins[cellStart[c] .. cellStart[c + 1])`. */
cellStart: Int32Array;
cellWins: Int32Array;
/** Columns centre first. */
order: number[];
centre: Uint8Array;
}
const layouts = new Map<string, Layout>();
function layoutFor(cols: number, rows: number): Layout {
const key = `${cols}x${rows}`;
const hit = layouts.get(key);
if (hit) return hit;
const win: number[] = [];
for (let x = 0; x < cols; x++)
for (let h = 0; h < rows; h++)
for (const [dx, dh] of [
[1, 0],
[0, 1],
[1, 1],
[1, -1],
] as const) {
const ex = x + 3 * dx;
const eh = h + 3 * dh;
if (ex >= cols || eh < 0 || eh >= rows) continue;
for (let k = 0; k < 4; k++) win.push((x + k * dx) * rows + (h + k * dh));
}
const n = cols * rows;
const lists: number[][] = Array.from({ length: n }, () => []);
for (let w = 0; w < win.length / 4; w++) for (let k = 0; k < 4; k++) lists[win[w * 4 + k]!]!.push(w);
const cellStart = new Int32Array(n + 1);
for (let c = 0; c < n; c++) cellStart[c + 1] = cellStart[c]! + lists[c]!.length;
const mid = (cols - 1) / 2;
const centre = new Uint8Array(cols);
for (let x = Math.floor(mid); x <= Math.ceil(mid); x++) centre[x] = 1;
const l: Layout = {
cols,
rows,
winCells: Int16Array.from(win),
cellStart,
cellWins: Int32Array.from(lists.flat()),
order: Array.from({ length: cols }, (_, i) => i).sort((a, b) => Math.abs(a - mid) - Math.abs(b - mid) || a - b),
centre,
};
layouts.set(key, l);
return l;
}
// Zobrist keys (two 32-bit halves) for up to 9 × 7 cells and both colours; fixed so a search is reproducible.
const MAX_CELLS = 64;
const ZOB = new Int32Array(MAX_CELLS * 2 * 2);
{
let s = 0x9e3779b9;
for (let i = 0; i < ZOB.length; i++) {
s ^= s << 13;
s ^= s >>> 17;
s ^= s << 5;
ZOB[i] = s;
}
}
// Transposition table shared by every search; entries of an earlier search are ignored (generation tag).
const TT_BITS = 17;
const TT_MASK = (1 << TT_BITS) - 1;
const ttKey = new Int32Array(1 << TT_BITS);
const ttGen = new Uint16Array(1 << TT_BITS);
const ttValue = new Int32Array(1 << TT_BITS);
const ttDepth = new Int8Array(1 << TT_BITS);
const ttFlag = new Int8Array(1 << TT_BITS);
const ttMove = new Int8Array(1 << TT_BITS);
let generation = 0;
const EXACT = 0;
const LOWER = 1;
const UPPER = 2;
const ABORT = { abort: true };
/** A position being searched (mutated in place by `make` / `unmake`). */
export class Position {
readonly l: Layout;
readonly cells: Int8Array;
readonly heights: Int8Array;
/** Discs of 빨강 / 노랑 per window. */
private readonly cnt1: Int8Array;
private readonly cnt2: Int8Array;
/** Current value of each window for 빨강 (`windowValue`). */
private readonly wval: Int16Array;
/** Score for 빨강 (disc 1): the sum of `wval` plus centre discs. */
private score = 0;
h1 = 0;
h2 = 0;
nodes = 0;
maxNodes = Infinity;
/** `board`: the game's row-major board (y = 0 at the top). */
constructor(cols: number, rows: number, board: readonly number[]) {
this.l = layoutFor(cols, rows);
this.cells = new Int8Array(cols * rows);
this.heights = new Int8Array(cols);
const w = this.l.winCells.length / 4;
this.cnt1 = new Int8Array(w);
this.cnt2 = new Int8Array(w);
this.wval = new Int16Array(w);
// Replay each column bottom-up (order between columns doesn't change the result).
for (let x = 0; x < cols; x++)
for (let y = rows - 1; y >= 0; y--) {
const v = board[y * cols + x]!;
if (v === 0) break;
this.make(x, v);
}
}
playable(x: number): boolean {
return this.heights[x]! < this.l.rows;
}
/** Value of window `w` for 빨강. */
private windowValue(w: number): number {
const a = this.cnt1[w]!;
const b = this.cnt2[w]!;
if (a && b) return 0;
const n = a || b;
if (n === 4) return 0;
let v = LINE[n]!;
if (n === 3) {
const owner = a ? 1 : 2;
const wc = this.l.winCells;
for (let k = w * 4; k < w * 4 + 4; k++) {
const c = wc[k]!;
if (this.cells[c] === 0) {
if ((c % this.l.rows) % 2 === (owner === 1 ? 0 : 1)) v += PARITY;
break;
}
}
}
return a ? v : -v;
}
private update(c: number, p: number, delta: 1 | -1): boolean {
const { cellStart, cellWins } = this.l;
const cnt = p === 1 ? this.cnt1 : this.cnt2;
let won = false;
for (let i = cellStart[c]!, to = cellStart[c + 1]!; i < to; i++) {
const w = cellWins[i]!;
if ((cnt[w]! += delta) === 4) won = true;
const v = this.windowValue(w);
this.score += v - this.wval[w]!;
this.wval[w] = v;
}
return won;
}
/** Drops `p`'s disc into column `x`; true when it connects four. */
make(x: number, p: number): boolean {
const c = x * this.l.rows + this.heights[x]!;
this.cells[c] = p;
this.heights[x]!++;
const won = this.update(c, p, 1);
if (this.l.centre[x]) this.score += p === 1 ? CENTRE : -CENTRE;
this.h1 ^= ZOB[(c * 2 + p - 1) * 2]!;
this.h2 ^= ZOB[(c * 2 + p - 1) * 2 + 1]!;
return won;
}
unmake(x: number): void {
const c = x * this.l.rows + this.heights[x]! - 1;
const p = this.cells[c]!;
this.cells[c] = 0;
this.heights[x]!--;
this.update(c, p, -1);
if (this.l.centre[x]) this.score -= p === 1 ? CENTRE : -CENTRE;
this.h1 ^= ZOB[(c * 2 + p - 1) * 2]!;
this.h2 ^= ZOB[(c * 2 + p - 1) * 2 + 1]!;
}
/** Who would connect four by dropping into `x` now: bit 1 = 빨강, bit 2 = 노랑 (0 for a full column). */
private fours(x: number): number {
const { rows, cellStart, cellWins } = this.l;
const h = this.heights[x]!;
if (h >= rows) return 0;
const c = x * rows + h;
let r = 0;
for (let i = cellStart[c]!, to = cellStart[c + 1]!; i < to; i++) {
const w = cellWins[i]!;
const a = this.cnt1[w]!;
const b = this.cnt2[w]!;
if (a === 3 && b === 0) r |= 1;
else if (b === 3 && a === 0) r |= 2;
}
return r;
}
/** Would `p` connect four by dropping into `x` now? */
winsNow(x: number, p: number): boolean {
return (this.fours(x) & p) !== 0;
}
/** Static score for `p`. */
evaluate(p: number): number {
return p === 1 ? this.score : -this.score;
}
negamax(depth: number, alpha: number, beta: number, p: number, ply: number): number {
if (++this.nodes > this.maxNodes) throw ABORT;
const { order, rows } = this.l;
const cols = order.length;
const q = 3 - p;
let moves = 0;
let forced = -1;
let threats = 0;
for (let i = 0; i < cols; i++) {
const x = order[i]!;
if (this.heights[x]! >= rows) continue;
moves++;
const f = this.fours(x);
if (f & p) return WIN - ply;
if (f & q) {
threats++;
forced = x;
}
}
if (moves === 0) return 0;
if (threats > 1) return -(WIN - ply - 1);
if (depth <= 0) return this.evaluate(p);
const slot = this.h1 & TT_MASK;
let first = forced;
if (ttGen[slot] === generation && ttKey[slot] === this.h2) {
let v = ttValue[slot]!;
if (v > DECIDED) v -= ply;
else if (v < -DECIDED) v += ply;
if (ttDepth[slot]! >= depth) {
const f = ttFlag[slot];
if (f === EXACT || (f === LOWER && v >= beta) || (f === UPPER && v <= alpha)) return v;
}
if (first < 0) first = ttMove[slot]!;
}
const alpha0 = alpha;
let best = -INF;
let bestMove = -1;
for (let i = -1; i < cols; i++) {
const x = i < 0 ? first : order[i]!;
if (x < 0 || (i >= 0 && x === first) || this.heights[x]! >= rows) continue;
if (forced >= 0 && x !== forced) continue;
this.make(x, p);
const v = -this.negamax(depth - 1, -beta, -alpha, q, ply + 1);
this.unmake(x);
if (v > best) {
best = v;
bestMove = x;
}
if (v > alpha) alpha = v;
if (alpha >= beta) break;
}
ttGen[slot] = generation;
ttKey[slot] = this.h2;
ttValue[slot] = best > DECIDED ? best + ply : best < -DECIDED ? best - ply : best;
ttDepth[slot] = depth;
ttFlag[slot] = best <= alpha0 ? UPPER : best >= beta ? LOWER : EXACT;
ttMove[slot] = bestMove;
return best;
}
}
/**
* Score of every open column for `p` (1 = 빨강, 2 = 노랑) to move: iterative deepening up to `depth` plies, stopping
* when a pass runs past `maxNodes` (that pass is dropped). Columns more than `margin` below the best only get an
* upper bound (they are worse than anything `humanBest` would play anyway).
*/
export function scoreColumns(
cols: number,
rows: number,
board: readonly number[],
p: number,
depth: number,
opts: { maxNodes?: number; margin?: number } = {},
): Map<number, number> {
const margin = opts.margin ?? 40;
generation = (generation + 1) & 0xffff;
if (generation === 0) {
ttGen.fill(0);
generation = 1;
}
const pos = new Position(cols, rows, board);
pos.maxNodes = opts.maxNodes ?? Infinity;
let order = pos.l.order.filter((x) => pos.playable(x));
let scores = new Map<number, number>(order.map((x) => [x, 0]));
for (let d = 1; d <= depth; d++) {
const cur = new Map<number, number>();
let best = -INF;
try {
for (const x of order) {
let v: number;
if (pos.winsNow(x, p)) v = WIN;
else {
pos.make(x, p);
v = -pos.negamax(d - 1, -INF, -(best - margin), 3 - p, 1);
pos.unmake(x);
}
cur.set(x, v);
if (v > best) best = v;
}
} catch (e) {
if (e === ABORT) break;
throw e;
}
scores = cur;
order = [...order].sort((a, b) => cur.get(b)! - cur.get(a)!);
// Decided either way: reading deeper changes nothing.
if (best > DECIDED || [...cur.values()].every((v) => v < -DECIDED)) break;
}
return scores;
}

View File

@@ -27,6 +27,7 @@ import { catchmind } from './catchmind';
import { mafia } from './mafia';
import { apple } from './apple';
import { clue } from './clue';
import { connectFour } from './connect-four';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -57,4 +58,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[mafia.id]: mafia,
[apple.id]: apple,
[clue.id]: clue,
[connectFour.id]: connectFour,
};

View File

@@ -5,6 +5,7 @@ import { GAMES } from './index';
/** Games without a score (win/lose only, or survival) leave `scoreText` out. */
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'clue']);
const NO_SCORE = new Set(['omok', 'chess', 'quoridor', 'davinci-code', 'ninety-nine', 'bang', 'mafia', 'cockroach-poker', 'connect-four']);
/** Options under which the game keeps score (원카드: only the 색깔 카드 mode has points). */
const SCORED_OPTIONS: Record<string, object> = { 'one-card': { mode: 'uno-style' } };

View File

@@ -52,6 +52,7 @@ export const BOT_GAMES: readonly string[] = [
'mafia',
'apple',
'clue',
'connect-four',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */

View File

@@ -37,6 +37,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true },
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
{ id: 'connect-four', nameKo: '커넥트 포', minPlayers: 2, maxPlayers: 2, minutes: '3~10', level: '쉬움', blurb: '열을 골라 돌을 떨어뜨려 네 개를 먼저 한 줄로! · 사목', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
];