- 규칙 모듈 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>
123 lines
5.7 KiB
TypeScript
123 lines
5.7 KiB
TypeScript
/** 커넥트 포 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);
|
||
}
|
||
});
|
||
});
|