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

- 규칙 모듈 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

@@ -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 },
];