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 = {}, 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(); 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)); } } }); });