Files
joke-app/packages/games/src/connect-four/connect-four.test.ts
EJClaw 3fffcec52b 커넥트 포(사목) 규칙·컴퓨터 상대·화면·테스트
- 규칙 모듈 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>
2026-10-13 03:09:33 +09:00

210 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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));
}
}
});
});