Files
joke-app/packages/games/src/janggi/janggi.test.ts
EJClaw 8175cebd2c 체스·장기·쿼리도 소리·움직임, 장기 상차림 시간 무제한
- 체스: 기물이 출발 칸에서 미끄러져 와 내려앉음(내가 끌어다 놓은 수는 제외), 캐슬링은 룩도 같이, 잡힌 기물(앙파상 폰 포함) 사라짐, 체크 칸 빛·말풍선 튀어나옴, 마지막 수 칸 살짝 나타남
- 체스 소리: 나무 기물 톡, 잡기, 캐슬링, 승진, 체크, 체크메이트 순간, 무르기, 기물 집기, 안 되는 칸 (fx.ts 순수 함수 + 테스트)
- 장기: 묵직한 기물 미끄러짐·내려앉기, 잡힌 기물 사라짐, 장군 궁 자리 고동, 상차림 마·상 하나씩 튀어나옴
- 장기 소리: 두꺼운 나무 "딱", 잡기, 장군·멍군·빅장, 외통 순간, 한수쉼, 무르기, 상차림 놓기 (fx.ts + 테스트)
- 장기 상차림 고르는 시간에 무제한(0) 추가, 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 (기본 1분 그대로), 무제한이면 상차림 시계 숨김, 끊긴 사람만 접속 유예 뒤 자동 선택
- 쿼리도: 말 한 칸은 살짝 튀며, 점프는 높이 뛰어 넘음, 도착 칸 고리, 벽 내려앉기+먼지, 무르기로 빠진 벽 사라짐, 안 되는 벽 흔들림, 목표 도착 띠 깜빡임·금빛 고리
- 쿼리도 소리: 말 톡, 점프, 벽 끼우기, 안 되는 곳, 목표 도착, 무르기
- 상대·컴퓨터 수도 화면 변화로 같은 소리·움직임, 새로 열면 다시 재생 안 함, 숨은 탭 내 차례 소리는 방 화면에 맡김

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:08:18 +09:00

589 lines
28 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import { SeededRng, randomPlayout, seedN, playoutSeeds } from '@bg/engine';
import { janggi, type JanggiAction, type JanggiOptions, type JanggiState } from './index';
import { idx, inCheck, initialBoard, kingsFacing, makeMove, positionKey, type Board, type PieceKind, type Side } from './rules';
const rng = () => SeededRng.fromSeed([1, 2, 3, 4]);
type P = [Side, PieceKind, number, number];
function opts(o: Partial<JanggiOptions> = {}): JanggiOptions {
return janggi.optionsSchema.parse({ sideAssignment: 'hostCho', ...o });
}
/** Fresh game in setup phase. A = 초, B = 한. */
function fresh(o: Partial<JanggiOptions> = {}): JanggiState {
return janggi.setup({ players: ['A', 'B'], options: opts(o), rng: rng(), now: 0 });
}
/** Game in play with a custom board. */
function custom(pieces: P[], o: Partial<JanggiOptions> = {}, turn: Side = 'cho'): JanggiState {
const s = fresh(o);
const b: Board = new Array(90).fill(null);
for (const [side, kind, f, r] of pieces) b[idx(f, r)] = { side, kind };
s.board = b;
s.startBoard = b.slice();
s.phase = 'playing';
s.turn = turn;
s.inCheck = inCheck(b, turn) ? turn : null;
s.positionCounts = { [positionKey(b, turn)]: 1 };
return s;
}
/** Standard opening (both 상차림 chosen), 초 to move. */
function standard(o: Partial<JanggiOptions> = {}, cho: string = 'MSSM', han: string = 'MSSM'): JanggiState {
let s = fresh(o);
s = act(s, 'B', { type: 'chooseSetup', arrangement: han as 'MSSM' });
return act(s, 'A', { type: 'chooseSetup', arrangement: cho as 'MSSM' });
}
const pl = (s: JanggiState, side: Side = s.turn) => s.players[side];
function act(s: JanggiState, who: string, a: JanggiAction, now = 1000): JanggiState {
const v = janggi.validate(s, who, a);
if (!v.ok) throw new Error(v.reason);
return janggi.apply(s, who, a, { rng: rng(), now }).state;
}
const mv = (f1: number, r1: number, f2: number, r2: number): JanggiAction => ({ type: 'move', from: { f: f1, r: r1 }, to: { f: f2, r: r2 } });
function check(s: JanggiState, f1: number, r1: number, f2: number, r2: number) {
return janggi.validate(s, pl(s), mv(f1, r1, f2, r2));
}
function play(s: JanggiState, f1: number, r1: number, f2: number, r2: number, now = 1000) {
return act(s, pl(s), mv(f1, r1, f2, r2), now);
}
/** Destinations of the piece at (f,r) from the mover's legal list. */
function targets(s: JanggiState, f: number, r: number): string[] {
return (janggi.legalActions!(s, pl(s)) as JanggiAction[])
.filter((a): a is Extract<JanggiAction, { type: 'move' }> => a.type === 'move' && a.from.f === f && a.from.r === r)
.map((a) => `${a.to.f},${a.to.r}`)
.sort();
}
const kingsOnly: P[] = [
['cho', 'king', 3, 0],
['han', 'king', 5, 9],
];
describe('setup (§4)', () => {
test('SMSM maps to the correct squares for both seats', () => {
const s = standard({}, 'SMSM', 'SMSM');
const k = (f: number, r: number) => s.board[idx(f, r)]?.kind;
expect([k(1, 0), k(2, 0), k(6, 0), k(7, 0)]).toEqual(['sang', 'ma', 'sang', 'ma']);
expect([k(7, 9), k(6, 9), k(2, 9), k(1, 9)]).toEqual(['sang', 'ma', 'sang', 'ma']);
expect(s.board[idx(7, 9)]?.side).toBe('han');
});
test.each([
['MSSM', ['ma', 'sang', 'sang', 'ma']],
['SMMS', ['sang', 'ma', 'ma', 'sang']],
['SMSM', ['sang', 'ma', 'sang', 'ma']],
['MSMS', ['ma', 'sang', 'ma', 'sang']],
])('%s left→right from own seat', (arr, kinds) => {
const s = standard({}, arr, arr);
expect([[1, 0], [2, 0], [6, 0], [7, 0]].map(([f, r]) => s.board[idx(f!, r!)]?.kind as string | undefined)).toEqual(kinds);
expect([[7, 9], [6, 9], [2, 9], [1, 9]].map(([f, r]) => s.board[idx(f!, r!)]?.kind as string | undefined)).toEqual(kinds);
});
test('fixed pieces, 초 moves first, initial position counted once', () => {
const s = standard();
expect(s.phase).toBe('playing');
expect(s.turn).toBe('cho');
expect(s.board[idx(4, 1)]).toEqual({ side: 'cho', kind: 'king' });
expect(s.board[idx(4, 8)]).toEqual({ side: 'han', kind: 'king' });
expect(s.board[idx(1, 7)]).toEqual({ side: 'han', kind: 'po' });
expect(s.board.filter(Boolean)).toHaveLength(32);
expect(Object.values(s.positionCounts)).toEqual([1]);
expect(janggi.view(s, 'A').scores).toEqual({ cho: 72, han: 73.5 });
});
test('hanFirst: 초 must wait, 한 choice is public immediately', () => {
const s = fresh();
expect(janggi.activePlayers(s)).toEqual(['B']);
expect(janggi.validate(s, 'A', { type: 'chooseSetup', arrangement: 'MSSM' }).ok).toBe(false);
const s2 = act(s, 'B', { type: 'chooseSetup', arrangement: 'SMMS' }, 5000);
expect(janggi.view(s2, 'A').setup.choice.han).toBe('SMMS');
expect(janggi.view(s2, null).board[idx(7, 9)]?.kind).toBe('sang');
expect(janggi.activePlayers(s2)).toEqual(['A']);
expect(janggi.deadline!(s2)).toBe(5000 + 60_000);
expect(janggi.validate(s2, 'B', { type: 'chooseSetup', arrangement: 'MSSM' }).ok).toBe(false);
});
test('simultaneous: no leak of the hidden choice to the opponent or spectators', () => {
const s = act(fresh({ setupOrder: 'simultaneous' }), 'A', { type: 'chooseSetup', arrangement: 'MSMS' });
expect(janggi.activePlayers(s)).toEqual(['B']);
for (const viewer of ['B', null]) {
const v = janggi.view(s, viewer);
expect(v.setup.choice.cho).toBeNull();
expect(v.setup.ready.cho).toBe(true);
expect(JSON.stringify(v)).not.toContain('MSMS');
}
expect(janggi.view(s, 'A').setup.choice.cho).toBe('MSMS');
expect(janggi.secretsOf!(s, 'A')).toEqual(['MSMS']);
const s2 = act(s, 'B', { type: 'chooseSetup', arrangement: 'SMMS' });
expect(s2.phase).toBe('playing');
expect(janggi.view(s2, null).setup.choice).toEqual({ cho: 'MSMS', han: 'SMMS' });
});
test('setup timeout picks with the seeded RNG, deterministically', () => {
const run = () => {
let s = fresh();
for (let i = 0; i < 2; i++) {
const p = janggi.timeoutPlayers!(s)[0]!;
const a = janggi.onTimeout(s, p);
expect(janggi.validate(s, p, a).ok).toBe(true);
s = janggi.apply(s, p, a, { rng: SeededRng.fromSeed([9, 8, 7, 6]), now: 60_000 * (i + 1) }).state;
}
return s;
};
const a = run();
expect(a.phase).toBe('playing');
expect(a.setup.choice).toEqual(run().setup.choice);
expect(janggi.validate(fresh(), 'A', { type: 'timeout' }).ok).toBe(false);
});
test('setupTimeSec 0 = no setup deadline; a disconnected chooser can still be auto-picked', () => {
expect(opts().setupTimeSec).toBe(60);
expect(janggi.deadline!(fresh())).toBe(60_000);
expect(janggi.optionsSchema.safeParse({ setupTimeSec: 0 }).success).toBe(true);
expect(janggi.optionsSchema.safeParse({ setupTimeSec: -1 }).success).toBe(false);
const none = { setupTimeSec: 0, timeControl: { kind: 'none' as const, mainSec: 600, periodSec: 30, periods: 3 } };
let s = fresh(none);
expect(janggi.deadline!(s)).toBeNull();
// The room only fires the timeout after the disconnect grace (deadline null), so the players stay listed.
expect(janggi.timeoutPlayers!(s)).toEqual(['B']);
s = act(s, 'B', janggi.onTimeout(s, 'B'), 5_000_000);
expect(s.setup.choice.han).not.toBeNull();
expect(janggi.deadline!(s)).toBeNull();
s = act(s, 'A', { type: 'chooseSetup', arrangement: 'SMMS' }, 9_000_000);
expect(s.phase).toBe('playing');
expect(janggi.deadline!(s)).toBeNull();
// The main clock is independent: unlimited setup with byoyomi play still times the moves.
let t = fresh({ setupTimeSec: 0 });
t = act(t, 'B', { type: 'chooseSetup', arrangement: 'MSSM' });
t = act(t, 'A', { type: 'chooseSetup', arrangement: 'MSSM' }, 2000);
expect(janggi.deadline!(t)).toBe(2000 + 600_000 + 3 * 30_000);
expect(janggi.view(t, 'A').rules.setupTimeSec).toBe(0);
});
test('resign during setup aborts without a result ranking', () => {
const s = act(fresh(), 'A', { type: 'resign' });
expect(janggi.result(s)).toMatchObject({ ranking: [], reason: 'abandoned' });
});
});
describe('piece movement (§5.2)', () => {
test('마 멱: a blocked first step removes both targets in that direction', () => {
const base: P[] = [...kingsOnly, ['cho', 'ma', 4, 4]];
expect(targets(custom(base), 4, 4)).toHaveLength(8);
const s = custom([...base, ['cho', 'jol', 4, 5]]);
expect(targets(s, 4, 4)).not.toContain('3,6');
expect(targets(s, 4, 4)).not.toContain('5,6');
expect(targets(s, 4, 4)).toHaveLength(6);
expect(check(s, 4, 4, 5, 6)).toEqual({ ok: false, reason: '마의 길(멱)이 막혀 있어요.' });
});
test('상 멱: first and second steps both matter', () => {
const base: P[] = [...kingsOnly, ['cho', 'sang', 4, 4]];
expect(targets(custom(base), 4, 4).sort()).toEqual(['1,2', '1,6', '2,1', '2,7', '6,1', '6,7', '7,2', '7,6'].sort());
const first = custom([...base, ['han', 'jol', 4, 5]]);
expect(targets(first, 4, 4)).not.toContain('2,7');
expect(targets(first, 4, 4)).not.toContain('6,7');
const second = custom([...base, ['han', 'jol', 5, 6]]);
expect(targets(second, 4, 4)).toContain('2,7');
expect(targets(second, 4, 4)).not.toContain('6,7');
expect(check(second, 4, 4, 6, 7)).toEqual({ ok: false, reason: '상의 길(멱)이 막혀 있어요.' });
});
test('포: needs a screen, cannot jump or capture 포, may land on any square beyond', () => {
const lone = custom([...kingsOnly, ['cho', 'po', 0, 4]]);
expect(targets(lone, 0, 4)).toEqual([]);
expect(check(lone, 0, 4, 0, 6).ok).toBe(false);
const s = custom([...kingsOnly, ['cho', 'po', 0, 4], ['cho', 'jol', 0, 5], ['han', 'cha', 0, 8]]);
expect(targets(s, 0, 4)).toEqual(['0,6', '0,7', '0,8']);
const overPo = custom([...kingsOnly, ['cho', 'po', 0, 4], ['han', 'po', 0, 5]]);
expect(targets(overPo, 0, 4)).toEqual([]);
expect(check(overPo, 0, 4, 0, 7)).toEqual({ ok: false, reason: '포는 포를 넘을 수 없어요.' });
const takePo = custom([...kingsOnly, ['cho', 'po', 0, 4], ['cho', 'jol', 0, 5], ['han', 'po', 0, 7]]);
expect(targets(takePo, 0, 4)).toEqual(['0,6']);
expect(check(takePo, 0, 4, 0, 7)).toEqual({ ok: false, reason: '포는 포를 잡을 수 없어요.' });
});
test('포 over the palace diagonal (corner → centre screen → corner)', () => {
const s = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 9], ['cho', 'po', 3, 7], ['han', 'sa', 4, 8]], {}, 'cho');
expect(targets(s, 3, 7)).toContain('5,9');
const empty = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 9], ['cho', 'po', 3, 7]]);
expect(targets(empty, 3, 7)).not.toContain('5,9');
const poScreen = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 9], ['cho', 'po', 3, 7], ['han', 'po', 4, 8]]);
expect(targets(poScreen, 3, 7)).not.toContain('5,9');
});
test('차 palace diagonal: corner to corner through an empty centre only', () => {
const s = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 8], ['cho', 'cha', 3, 7]]);
expect(targets(s, 3, 7)).toContain('4,8');
expect(targets(s, 3, 7)).toContain('5,9');
const blocked = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 8], ['cho', 'cha', 3, 7], ['han', 'sa', 4, 8]]);
expect(targets(blocked, 3, 7)).toContain('4,8');
expect(targets(blocked, 3, 7)).not.toContain('5,9');
// No diagonal outside the palace or from an edge midpoint.
const mid = custom([['cho', 'king', 3, 0], ['han', 'king', 3, 9], ['cho', 'cha', 4, 7]]);
expect(targets(mid, 4, 7)).not.toContain('5,8');
});
test('궁·사: no diagonal from edge midpoints, never leave the palace', () => {
const s = custom([['cho', 'king', 4, 0], ['cho', 'sa', 3, 1], ['han', 'king', 3, 9]]);
expect(targets(s, 4, 0)).toEqual(['3,0', '4,1', '5,0']);
expect(targets(s, 3, 1)).toEqual(['3,0', '3,2', '4,1']);
const corner = custom([['cho', 'king', 3, 2], ['han', 'king', 5, 9]]);
expect(targets(corner, 3, 2)).toEqual(['3,1', '4,1', '4,2']);
expect(check(corner, 3, 2, 3, 3)).toEqual({ ok: false, reason: '궁은 궁성 밖으로 나갈 수 없어요.' });
const centre = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 9]]);
expect(targets(centre, 4, 1)).toHaveLength(8);
});
test('졸: no backwards, forward diagonal in the enemy palace, not in its own', () => {
const s = custom([...kingsOnly, ['cho', 'jol', 2, 5]]);
expect(targets(s, 2, 5)).toEqual(['1,5', '2,6', '3,5']);
expect(check(s, 2, 5, 2, 4)).toEqual({ ok: false, reason: '졸은 뒤로 갈 수 없어요.' });
const pal = custom([['cho', 'king', 4, 1], ['han', 'king', 5, 9], ['cho', 'jol', 3, 7]]);
expect(targets(pal, 3, 7)).toContain('4,8');
const centre = custom([['cho', 'king', 4, 1], ['han', 'king', 5, 8], ['cho', 'jol', 4, 8]]);
expect(targets(centre, 4, 8)).toEqual(['3,8', '3,9', '4,9', '5,8', '5,9']);
const own = custom([['cho', 'king', 3, 0], ['han', 'king', 5, 9], ['han', 'jol', 3, 7]], {}, 'han');
expect(targets(own, 3, 7)).toEqual(['2,7', '3,6', '4,7']);
// 한 병 in 초's palace goes diagonally toward r=0.
const enemy = custom([['cho', 'king', 5, 0], ['han', 'king', 5, 9], ['han', 'jol', 3, 2]], {}, 'han');
expect(targets(enemy, 3, 2)).toContain('4,1');
// Last rank: sideways only.
const last = custom([['cho', 'king', 4, 1], ['han', 'king', 5, 8], ['cho', 'jol', 0, 9]]);
expect(targets(last, 0, 9)).toEqual(['1,9']);
});
});
describe('장군 (§5.3)', () => {
test('moving into check is rejected; 포 pins (one screen left) are respected', () => {
const s = custom([['cho', 'king', 4, 1], ['han', 'king', 3, 9], ['han', 'cha', 5, 6]]);
expect(check(s, 4, 1, 5, 1)).toEqual({ ok: false, reason: '그 수를 두면 내 궁이 잡혀요(장군).' });
const pin = custom([['cho', 'king', 4, 1], ['cho', 'sa', 4, 2], ['cho', 'jol', 4, 3], ['han', 'king', 3, 9], ['han', 'po', 4, 6]]);
expect(inCheck(pin.board, 'cho')).toBe(false);
expect(check(pin, 4, 3, 3, 3).ok).toBe(false);
expect(check(pin, 4, 3, 4, 4).ok).toBe(true);
// Stepping into a 포 line creates the screen → also illegal.
const screen = custom([['cho', 'king', 4, 1], ['cho', 'jol', 3, 4], ['han', 'king', 3, 9], ['han', 'po', 4, 6]]);
expect(check(screen, 3, 4, 4, 4).ok).toBe(false);
});
test('pass is refused in check; check must be answered', () => {
const s = custom([['cho', 'king', 3, 0], ['han', 'king', 4, 9], ['cho', 'cha', 0, 9]], {}, 'han');
expect(s.inCheck).toBe('han');
expect(janggi.validate(s, 'B', { type: 'pass' })).toEqual({ ok: false, reason: '장군을 받은 상태에서는 쉴 수 없어요.' });
expect(check(s, 4, 9, 5, 9)).toEqual({ ok: false, reason: '장군을 피해야 해요.' });
expect(targets(s, 4, 9)).toEqual(['4,8']);
});
test('외통 ends the game', () => {
const s = custom([['cho', 'king', 3, 0], ['cho', 'cha', 8, 8], ['cho', 'cha', 0, 0], ['han', 'king', 4, 9]]);
const r = janggi.apply(s, 'A', mv(0, 0, 0, 9), { rng: rng(), now: 1000 });
expect(r.state.result).toMatchObject({ winner: 'cho', reason: 'checkmate', summaryKo: '초 외통승 (1수)' });
expect(r.events.map((e) => e.type)).toContain('checkmate');
expect(janggi.result(r.state)?.ranking).toEqual([['A'], ['B']]);
});
test('janggun / meonggun events', () => {
const s = custom([['cho', 'king', 3, 0], ['cho', 'cha', 0, 0], ['han', 'king', 4, 9], ['han', 'sa', 5, 8]]);
const r1 = janggi.apply(s, 'A', mv(0, 0, 0, 9), { rng: rng(), now: 1 });
expect(r1.events.map((e) => e.type)).toContain('janggun');
const r2 = janggi.apply(r1.state, 'B', mv(4, 9, 4, 8), { rng: rng(), now: 2 });
expect(r2.events.map((e) => e.type)).toContain('meonggun');
});
});
describe('빅장 (§5.4)', () => {
// Kings face on file 4 once the 초 졸 on (4,4) steps aside.
const facing: P[] = [
['cho', 'king', 4, 1],
['cho', 'jol', 4, 4],
['cho', 'cha', 0, 0],
['cho', 'sa', 3, 0],
['han', 'king', 4, 8],
['han', 'jol', 0, 6],
['han', 'cha', 8, 5],
['han', 'sa', 3, 9],
];
test('kjf: facing before any capture does nothing', () => {
const s = play(custom(facing), 4, 4, 3, 4);
expect(kingsFacing(s.board)).toBe(true);
expect(s.bikjang).toBeNull();
});
test('kjf: the first capture itself cannot call 빅장', () => {
const s = play(custom([...facing.filter((p) => p[1] !== 'jol' || p[0] !== 'cho'), ['cho', 'ma', 4, 4], ['han', 'jol', 6, 5]]), 4, 4, 6, 5);
expect(s.firstCapturePly).toBe(0);
expect(kingsFacing(s.board)).toBe(true);
expect(s.bikjang).toBeNull();
});
const called = () => {
let s = play(custom(facing), 0, 0, 0, 6); // capture
s = play(s, 3, 9, 3, 8);
return play(s, 4, 4, 3, 4); // 빅장
};
test('kjf: after a capture, facing calls 빅장; blocking continues the game', () => {
const s = called();
expect(s.bikjang).toEqual({ calledBy: 'cho', ply: 2 });
expect(janggi.view(s, 'B').bikjang).toEqual({ calledBy: 'cho' });
const blocked = play(s, 8, 5, 4, 5);
expect(blocked.phase).toBe('playing');
expect(blocked.bikjang).toBeNull();
});
test('kjf: not answering → 빅, score judgement (덤 means no tie)', () => {
const s = act(called(), 'B', { type: 'pass' });
// 초: 차13 + 사3 + 졸2 = 18; 한: 차13 + 사3 + 1.5 = 17.5
expect(s.result).toMatchObject({ winner: 'cho', reason: 'scoreBikjang', scores: { cho: 18, han: 17.5 }, summaryKo: '초 판정승 18 : 17.5 (빅장)' });
const noScore = act(
(() => {
let t = play(custom(facing, { scoring: false }), 0, 0, 0, 6);
t = play(t, 3, 9, 3, 8);
return play(t, 4, 4, 3, 4);
})(),
'B',
{ type: 'pass' },
);
expect(noScore.result).toMatchObject({ winner: null, reason: 'drawBikjang' });
expect(janggi.result(noScore)?.ranking).toEqual([['A', 'B']]);
});
test('kja30: needs both sides under 30 points', () => {
const rich = play(custom([...facing, ['cho', 'cha', 8, 0], ['cho', 'po', 1, 2]], { bikjang: 'kja30' }), 4, 4, 3, 4);
expect(rich.bikjang).toBeNull();
const poor = play(custom(facing, { bikjang: 'kja30' }), 4, 4, 3, 4);
expect(poor.bikjang?.calledBy).toBe('cho');
});
test('off: facing is harmless', () => {
let s = play(custom(facing, { bikjang: 'off' }), 0, 0, 0, 6);
s = play(s, 3, 9, 3, 8);
s = play(s, 4, 4, 3, 4);
expect(s.bikjang).toBeNull();
expect(act(s, 'B', { type: 'pass' }).phase).toBe('playing');
});
});
describe('repetition (§5.5) and passes (§5.6)', () => {
const shuffle: P[] = [...kingsOnly, ['cho', 'cha', 0, 0], ['han', 'cha', 8, 9]];
/** 초 차 0,0↔0,1 and 한 차 8,9↔8,8; the 12th ply would repeat the start a 4th time. */
function cycle(s: JanggiState, plies: number): JanggiState {
const seq: [number, number, number, number][] = [
[0, 0, 0, 1],
[8, 9, 8, 8],
[0, 1, 0, 0],
[8, 8, 8, 9],
];
for (let i = 0; i < plies; i++) s = play(s, ...seq[i % 4]!);
return s;
}
test('forbid: the move creating the 4th repetition is refused, others allowed', () => {
const s = cycle(custom(shuffle), 11);
expect(janggi.view(s, 'B').repeatWarning).toBe(true);
expect(check(s, 8, 8, 8, 9)).toEqual({ ok: false, reason: '같은 수를 너무 많이 반복해서 둘 수 없어요.' });
expect(targets(s, 8, 8)).not.toContain('8,9');
expect(check(s, 8, 8, 8, 7).ok).toBe(true);
});
test('forbid exception: in check with only a repeating move → allowed, then score judgement', () => {
const s = custom([['cho', 'king', 3, 0], ['cho', 'cha', 0, 9], ['han', 'king', 4, 9]], {}, 'han');
s.positionCounts[positionKey(makeMove(s.board, idx(4, 9), idx(4, 8)), 'cho')] = 3;
expect(check(s, 4, 9, 4, 8).ok).toBe(true);
const end = play(s, 4, 9, 4, 8);
expect(end.result).toMatchObject({ reason: 'scoreRepetition', winner: 'cho' });
});
test('lose: the side creating the 4th repetition loses', () => {
const s = cycle(custom(shuffle, { repetition: 'lose' }), 12);
expect(s.result).toMatchObject({ winner: 'cho', reason: 'repetitionLoss' });
});
test('scoreEnd: 4th repetition ends by score', () => {
const s = cycle(custom(shuffle, { repetition: 'scoreEnd' }), 12);
expect(s.result?.reason).toBe('scoreRepetition');
});
test('both pass in a row → score judgement, or draw without scoring', () => {
let s = act(standard(), 'A', { type: 'pass' });
s = act(s, 'B', { type: 'pass' });
expect(s.result).toMatchObject({ winner: 'han', reason: 'scorePasses', summaryKo: '한 판정승 73.5 : 72 (연속 한수쉼)' });
let d = act(standard({ scoring: false }), 'A', { type: 'pass' });
d = act(d, 'B', { type: 'pass' });
expect(d.result).toMatchObject({ winner: null, reason: 'drawPasses' });
});
test('allowPass=false refuses pass unless there is no legal move', () => {
const s = standard({ allowPass: false });
expect(janggi.validate(s, 'A', { type: 'pass' })).toEqual({ ok: false, reason: '이 방은 한수쉼을 쓰지 않아요.' });
// 초 궁 boxed in by defended 한 pieces, no other 초 piece, not in check → pass allowed.
const stuck = custom(
[
['cho', 'king', 3, 0],
['han', 'ma', 4, 0],
['han', 'ma', 3, 1],
['han', 'ma', 4, 1],
['han', 'cha', 3, 5],
['han', 'cha', 4, 5],
['han', 'jol', 5, 0],
['han', 'king', 5, 9],
],
{ allowPass: false },
);
expect(stuck.inCheck).toBeNull();
expect(janggi.view(stuck, 'A').legalMoves).toEqual([]);
expect(janggi.validate(stuck, 'A', { type: 'pass' }).ok).toBe(true);
});
test('moveLimit reached → score judgement', () => {
let s = standard({ moveLimit: 2 });
s = play(s, 0, 3, 1, 3);
s = play(s, 0, 6, 1, 6);
expect(s.result?.reason).toBe('scoreMoveLimit');
});
});
describe('clocks (§8.5)', () => {
test('byoyomi: main time, then periods, then time loss', () => {
const tc = { kind: 'byoyomi' as const, mainSec: 60, periodSec: 30, periods: 3 };
let s = standard({ timeControl: tc });
s.clock.turnStartedAt = 0;
expect(janggi.deadline!(s)).toBe(60_000 + 90_000);
s = play(s, 0, 3, 1, 3, 50_000); // 초 used 50s
expect(s.clock.mainMs.cho).toBe(10_000);
s = play(s, 0, 6, 1, 6, 60_000);
s = play(s, 1, 3, 0, 3, 60_000 + 35_000); // 10s main + 25s of a period → keeps 3
expect(s.clock).toMatchObject({ mainMs: { cho: 0 }, periodsLeft: { cho: 3 } });
s = play(s, 1, 6, 0, 6, 100_000);
s = play(s, 0, 3, 1, 3, 100_000 + 31_000); // over one period
expect(s.clock.periodsLeft.cho).toBe(2);
s = play(s, 0, 6, 1, 6, 140_000);
expect(janggi.deadline!(s)).toBe(140_000 + 60_000);
s = play(s, 1, 3, 0, 3, 140_000 + 61_000); // used both remaining periods
expect(s.result).toMatchObject({ winner: 'han', reason: 'timeLoss' });
expect(s.board[idx(1, 3)]?.kind).toBe('jol'); // the late move was not played
});
test('timeout action → time loss for the side to move; none has no deadline', () => {
const s = standard();
expect(janggi.timeoutPlayers!(s)).toEqual(['A']);
const t = act(s, 'A', janggi.onTimeout(s, 'A'));
expect(janggi.result(t)).toMatchObject({ ranking: [['B'], ['A']], reason: 'timeout' });
const n = standard({ timeControl: { kind: 'none', mainSec: 600, periodSec: 30, periods: 3 } });
expect(janggi.deadline!(n)).toBeNull();
});
});
describe('requests, undo, views', () => {
test('undo restores firstCapturePly, 빅장 and repetition counts', () => {
const facing: P[] = [
['cho', 'king', 4, 1],
['cho', 'jol', 4, 4],
['cho', 'cha', 0, 0],
['han', 'king', 4, 8],
['han', 'jol', 0, 6],
['han', 'cha', 8, 5],
['han', 'sa', 3, 9],
];
const s0 = custom(facing);
const s1 = play(s0, 0, 0, 0, 6);
const s2 = play(s1, 3, 9, 3, 8);
const s3 = play(s2, 4, 4, 3, 4);
expect(s3.bikjang).not.toBeNull();
const s4 = play(s3, 8, 5, 4, 5);
expect(s4.bikjang).toBeNull();
// 한 takes back its block → 빅장 pending again.
let u = act(s4, 'B', { type: 'requestUndo' });
expect(u.undo.pending).toEqual({ by: 'han', plies: 1 });
u = act(u, 'A', { type: 'respondUndo', accept: true });
expect(u.bikjang).toEqual(s3.bikjang);
expect(u.positionCounts).toEqual(s3.positionCounts);
expect(u.board).toEqual(s3.board);
expect(u.turn).toBe('han');
// 초 takes back two plies (its 빅장 + 한's reply), then its capture.
u = act(u, 'A', { type: 'requestUndo' });
expect(u.undo.pending?.plies).toBe(1);
u = act(u, 'B', { type: 'respondUndo', accept: true });
expect(u.positionCounts).toEqual(s2.positionCounts);
u = act(u, 'A', { type: 'requestUndo' });
expect(u.undo.pending?.plies).toBe(2);
u = act(u, 'B', { type: 'respondUndo', accept: true });
expect(u.firstCapturePly).toBeNull();
expect(u.board).toEqual(s0.board);
expect(u.positionCounts).toEqual(s0.positionCounts);
expect(u.undo.usedBy).toEqual({ cho: 2, han: 1 });
expect(janggi.validate(u, 'A', { type: 'requestUndo' })).toEqual({ ok: false, reason: '아직 무를 수가 없어요.' });
});
test('draw offer: decline, re-offer gap, accept', () => {
let s = act(standard({ drawReofferMoves: 1 }), 'A', { type: 'offerDraw' });
expect(janggi.activePlayers(s)).toEqual(['A', 'B']);
s = act(s, 'B', { type: 'respondDraw', accept: false });
expect(janggi.validate(s, 'A', { type: 'offerDraw' }).ok).toBe(false);
s = play(play(s, 0, 3, 1, 3), 0, 6, 1, 6);
s = act(s, 'A', { type: 'offerDraw' });
s = act(s, 'B', { type: 'respondDraw', accept: true });
expect(janggi.result(s)).toMatchObject({ ranking: [['A', 'B']], reason: 'draw-agreed' });
});
test('resign during play', () => {
const s = act(standard(), 'B', { type: 'resign' });
expect(s.result).toMatchObject({ winner: 'cho', reason: 'resign' });
});
test('view: no rng, legal moves only for the player to move, threats only when the admin enables them', () => {
const s = standard();
expect(JSON.stringify(janggi.view(s, 'A'))).not.toContain('rng');
expect(janggi.view(s, null).legalMoves).toBeNull();
expect(janggi.view(s, 'B').legalMoves).toBeNull();
const v = janggi.view(s, 'A');
expect(v.legalMoves!.length).toBeGreaterThan(20);
expect(v.canPass).toBe(true);
expect(janggi.view(custom([...kingsOnly, ['cho', 'ma', 4, 4], ['han', 'cha', 4, 7]]), 'A').threatened).toEqual([]);
const t = custom([...kingsOnly, ['cho', 'ma', 4, 4], ['han', 'cha', 4, 7]], { threatHints: true });
expect(janggi.view(t, 'A').threatened).toEqual([{ f: 4, r: 4 }]);
});
test('포 legal moves carry their screen for the UI', () => {
const v = janggi.view(custom([...kingsOnly, ['cho', 'po', 0, 4], ['cho', 'jol', 0, 5]]), 'A');
expect(v.legalMoves!.find((m) => m.from.f === 0 && m.from.r === 4)?.via).toEqual({ f: 0, r: 5 });
});
test('initial board helper is symmetric', () => {
const b = initialBoard();
for (let r = 0; r < 10; r++)
for (let f = 0; f < 9; f++) expect(b[idx(f, r)]?.kind).toBe(b[idx(f, 9 - r)]?.kind);
});
});
describe('random playouts', () => {
const kings = (st: unknown) => {
const s = st as JanggiState;
if (s.phase !== 'setup' && s.board.filter((p) => p?.kind === 'king').length !== 2) throw new Error('king missing');
};
test.each([
['default + limit 200', { moveLimit: 200 }],
['no scoring, kja30, simultaneous, limit 150', { scoring: false, bikjang: 'kja30', setupOrder: 'simultaneous', moveLimit: 150 }],
['repetition lose, no pass, limit 250', { repetition: 'lose', allowPass: false, moveLimit: 250 }],
] as const)('%s: finish, deterministic, JSON-safe', (_n, o) => {
for (let i = 0; i < playoutSeeds(6); i++) {
const options = opts(o as Partial<JanggiOptions>);
const a = randomPlayout(janggi, { players: ['A', 'B'], options, seed: seedN(i), maxApplyMs: 50, invariant: kings, maxSteps: 400 });
const b = randomPlayout(janggi, { players: ['A', 'B'], options, seed: seedN(i), maxApplyMs: 50, maxSteps: 400 });
expect(a.finished).toBe(true);
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
expect(janggi.result(a.finalState as JanggiState)).not.toBeNull();
}
});
test('defaults without a move limit stay valid for 300 steps', () => {
for (let i = 10; i < 13; i++) {
randomPlayout(janggi, { players: ['A', 'B'], options: janggi.defaultOptions, seed: seedN(i), maxApplyMs: 50, invariant: kings, maxSteps: 300 });
}
});
});