사과 게임: 같은 판(17×10) 합 10 만들기 경주, 1~8명·혼자 가능, 레벨별 컴퓨터(라이브 봇)
- 규칙 모듈 packages/games/src/apple: 시드로 만든 한 판(1~9, 합 10의 배수)을 모두 각자 풀고, 직사각형 합이 딱 10이면 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 합≠10·빈 직사각형은 거절(벌점 없음). 3초 카운트다운(판 숨김) → 제한 시간 1/2/3분(기본 2분), 서버 시계 마감(deadline = timeoutNotBefore, 끊긴 사람 조기 시간 초과 없음), 1초 5번 속도 제한, 더 지울 게 없으면 막힘 → 모두 막히면 조기 종료, 나가면 맨 아래 순위·혼자 남으면 끝. 동점은 같은 순위, 결과 "사과 N개". - view는 내 판(170자 문자열)과 모두의 점수만(남의 판 없음). findMoves는 누적합으로 가장 좁은 합 10 직사각형 전부. - 컴퓨터: 마피아처럼 LIVE_BOT_STRATEGIES.apple. live 전략에 level 전달(서버 bots.ts, live-playout). 레벨 따라 찾는 시간(6초→2초)·시야·놓침(쉬움 30%)·고르기가 달라짐. 2분 평균 레벨1 약 28개 ~ 레벨60 약 99개. - 화면 apps/web/src/games/apple: SVG 사과, 포인터 드래그(마우스·터치), 합계 실시간·10이면 초록, 낙관적 지우기와 튀어 오르는 애니메이션, 휴대폰은 판을 돌려 10열×17줄, 키보드(화살표+스페이스 두 번, Esc), 다른 사람 점수 칩, 다크 모드, 도움말·30초 요약. - 등록(GAMES, CATALOG, BOT_GAMES, 화면 레지스트리, 아이콘·파티 탭), 문서 docs/games/apple.md, 09 §9 라이브 봇 줄. - 테스트: 규칙 15개(무차별 대조, 무작위 대국 1·2·5·8명), 컴퓨터 5개, 도움말 2개, 방 통합 2개(컴퓨터와 끝까지), E2E(PC 마우스·키보드, 휴대폰 CDP 터치, 320px, 1분 뒤 결과). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
247
packages/games/src/apple/apple.test.ts
Normal file
247
packages/games/src/apple/apple.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
|
||||
import {
|
||||
CELLS,
|
||||
COLS,
|
||||
COUNTDOWN_MS,
|
||||
ROWS,
|
||||
SELECTS_PER_SEC,
|
||||
apple,
|
||||
findMoves,
|
||||
hasMove,
|
||||
makeBoard,
|
||||
rankRows,
|
||||
rectSum,
|
||||
type AppleAction,
|
||||
type AppleOptions,
|
||||
type AppleState,
|
||||
type Rect,
|
||||
} from './index';
|
||||
|
||||
const T0 = 1_000_000;
|
||||
const START = T0 + COUNTDOWN_MS;
|
||||
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
|
||||
|
||||
function make(players = ['A', 'B'], opts: Partial<AppleOptions> = {}, seed = 1): AppleState {
|
||||
return apple.setup({ players, options: apple.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
|
||||
}
|
||||
function act(s: AppleState, p: string, a: AppleAction, now: number): AppleState {
|
||||
const v = apple.validate(s, p, a, { now });
|
||||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||||
return apple.apply(s, p, a, { rng: rng(), now }).state;
|
||||
}
|
||||
const tick = (s: AppleState, now: number) => apple.apply(s, s.order[0]!, { type: 'tick' }, { rng: rng(), now }).state;
|
||||
const sel = (r: Rect): AppleAction => ({ type: 'select', ...r });
|
||||
const reason = (s: AppleState, p: string, a: AppleAction, now?: number) => {
|
||||
const v = apple.validate(s, p, a, now === undefined ? undefined : { now });
|
||||
return v.ok ? 'ok' : v.reason;
|
||||
};
|
||||
|
||||
/** A board from rows of text ('.' or '0' = empty), padded with empty cells. */
|
||||
function board(rows: string[]): string {
|
||||
const out: string[] = [];
|
||||
for (let r = 0; r < ROWS; r++) out.push((rows[r] ?? '').replace(/\./g, '0').padEnd(COLS, '0').slice(0, COLS));
|
||||
return out.join('');
|
||||
}
|
||||
function rigged(cells: string, players = ['A', 'B']): AppleState {
|
||||
const s = tick(make(players), START);
|
||||
for (const p of players) s.boards[p] = cells;
|
||||
s.initial = cells;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Brute force: every rectangle with sum 10, reduced to its apples' bounding box, deduplicated. */
|
||||
function bruteMoves(cells: string): string[] {
|
||||
const keys = new Set<string>();
|
||||
for (let r0 = 0; r0 < ROWS; r0++)
|
||||
for (let r1 = r0; r1 < ROWS; r1++)
|
||||
for (let c0 = 0; c0 < COLS; c0++)
|
||||
for (let c1 = c0; c1 < COLS; c1++) {
|
||||
if (rectSum(cells, { r0, c0, r1, c1 }).sum !== 10) continue;
|
||||
let a = ROWS, b = COLS, c = -1, d = -1;
|
||||
for (let r = r0; r <= r1; r++)
|
||||
for (let k = c0; k <= c1; k++)
|
||||
if (cells[r * COLS + k] !== '0') {
|
||||
a = Math.min(a, r); b = Math.min(b, k); c = Math.max(c, r); d = Math.max(d, k);
|
||||
}
|
||||
keys.add(`${a},${b},${c},${d}`);
|
||||
}
|
||||
return [...keys].sort();
|
||||
}
|
||||
|
||||
describe('판 만들기', () => {
|
||||
test('17×10 칸에 1~9, 합은 10의 배수, 같은 시드면 같은 판, 모두 같은 판으로 시작', () => {
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
const b = makeBoard(SeededRng.fromSeed(seedN(i)));
|
||||
expect(b).toHaveLength(CELLS);
|
||||
expect(b).toMatch(/^[1-9]+$/);
|
||||
expect([...b].reduce((a, c) => a + Number(c), 0) % 10).toBe(0);
|
||||
expect(makeBoard(SeededRng.fromSeed(seedN(i)))).toBe(b);
|
||||
}
|
||||
const s = make(['A', 'B', 'C']);
|
||||
expect(new Set(Object.values(s.boards))).toEqual(new Set([s.initial]));
|
||||
expect(s.endsAt).toBe(START + 120_000);
|
||||
expect(make(['A'], { timeLimitSec: 60 }).endsAt).toBe(START + 60_000);
|
||||
});
|
||||
|
||||
test('findMoves = 손으로 센 모든 합 10 직사각형(가장 좁게), 빈 칸 너머도 포함', () => {
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
const r = SeededRng.fromSeed(seedN(100 + i));
|
||||
// Sparse boards so long rectangles across cleared cells show up too.
|
||||
const cells = [...makeBoard(r)].map((c) => (r.int(10) < 6 ? '0' : c)).join('');
|
||||
const got = findMoves(cells).map((m) => `${m.r0},${m.c0},${m.r1},${m.c1}`).sort();
|
||||
expect(got).toEqual(bruteMoves(cells));
|
||||
}
|
||||
expect(findMoves(board(['19', '..', '.5', '.5']))).toEqual([
|
||||
{ r0: 0, c0: 0, r1: 0, c1: 1 },
|
||||
{ r0: 2, c0: 1, r1: 3, c1: 1 },
|
||||
]);
|
||||
expect(hasMove(board(['55']))).toBe(true);
|
||||
expect(hasMove(board(['54', '..', '9']))).toBe(false);
|
||||
});
|
||||
|
||||
test('한 수 계산은 1ms 안쪽(판 전체를 훑어도)', () => {
|
||||
const cells = makeBoard(SeededRng.fromSeed(seedN(3)));
|
||||
const t0 = performance.now();
|
||||
for (let i = 0; i < 50; i++) findMoves(cells);
|
||||
expect((performance.now() - t0) / 50).toBeLessThan(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('진행', () => {
|
||||
test('카운트다운 동안에는 판이 안 보이고 고를 수 없어요. 시간이 되면 바로 시작(타이머 전이라도)', () => {
|
||||
const s = make();
|
||||
expect(apple.view(s, 'A').cells).toBeNull();
|
||||
checkNoLeak(apple, s, 'A', s.order);
|
||||
const m = findMoves(s.initial)[0]!;
|
||||
expect(reason(s, 'A', sel(m), START - 1)).toBe('곧 시작해요. 잠시만 기다려 주세요.');
|
||||
// The countdown is over but the room timer has not ticked yet: the select still counts.
|
||||
const s2 = act(s, 'A', sel(m), START + 5);
|
||||
expect(s2.phase).toBe('playing');
|
||||
expect(s2.score.A).toBeGreaterThanOrEqual(2);
|
||||
expect(apple.view(s2, 'A').cells).toBe(s2.boards.A!);
|
||||
expect(apple.view(s2, null).cells).toBeNull();
|
||||
// Others never get my board, only my score.
|
||||
expect(JSON.stringify(apple.view(s2, 'B'))).not.toContain(s2.boards.A!);
|
||||
expect(apple.view(s2, 'B').seats.find((x) => x.id === 'A')!.score).toBe(s2.score.A!);
|
||||
});
|
||||
|
||||
test('합이 딱 10이면 지워지고 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 모서리 순서 무관', () => {
|
||||
const s = rigged(board(['1.9', '...', '28.', '...', '55.']));
|
||||
expect(reason(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 2 }), START + 10)).toBe('ok');
|
||||
let t = act(s, 'A', sel({ r0: 0, c0: 2, r1: 0, c1: 0 }), START + 10);
|
||||
expect(t.score.A).toBe(2);
|
||||
expect(t.clears.A).toBe(1);
|
||||
expect(t.boards.A!.slice(0, 3)).toBe('000');
|
||||
// B's copy is untouched.
|
||||
expect(t.boards.B).toBe(s.boards.B);
|
||||
// A rectangle over cleared cells: 2 + 8 (rows 0~2) still adds to 10.
|
||||
t = act(t, 'A', sel({ r0: 0, c0: 0, r1: 2, c1: 2 }), START + 600);
|
||||
expect(t.score.A).toBe(4);
|
||||
expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 1, c1: 2 }), START + 1200)).toBe('고른 칸에 사과가 없어요.');
|
||||
expect(reason(t, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 1200)).toBe('합이 5이에요. 딱 10이 되게 골라 주세요.');
|
||||
// The whole board (only 5 + 5 left) is a fine rectangle too.
|
||||
expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 9, c1: 16 }), START + 1200)).toBe('ok');
|
||||
});
|
||||
|
||||
test('너무 빨리 연달아 고르면 거절(1초에 5번까지)', () => {
|
||||
let s = rigged(board(['55555555555555555', '55555555555555555']));
|
||||
let now = START + 100;
|
||||
for (let i = 0; i < SELECTS_PER_SEC; i++) s = act(s, 'A', sel({ r0: 0, c0: 2 * i, r1: 0, c1: 2 * i + 1 }), (now += 10));
|
||||
expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('조금 천천히 해 주세요.');
|
||||
expect(reason(s, 'B', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('ok');
|
||||
expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), START + 100 + 10 + 1000)).toBe('ok');
|
||||
});
|
||||
|
||||
test('서버 시계로 끝: 마감 뒤 고르기는 거절, 타이머 tick으로 끝나고 점수 순위(동점 같은 순위)', () => {
|
||||
let s = make(['A', 'B', 'C']);
|
||||
s = tick(s, START);
|
||||
const m1 = findMoves(s.initial)[0];
|
||||
s = act(s, 'A', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(findMoves(s.boards.B!)[0]!), START + 2000);
|
||||
expect(apple.deadline!(s)).toBe(s.endsAt);
|
||||
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt);
|
||||
expect(reason(s, 'C', sel(m1!), s.endsAt)).toBe('시간이 다 됐어요.');
|
||||
s = tick(s, s.endsAt);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['B'], ['A'], ['C']]);
|
||||
expect(r.scoreText!.C).toBe('사과 0개');
|
||||
expect(r.summary).toContain('시간이 다 됐어요');
|
||||
// Tie → shared rank.
|
||||
s.score.A = s.score.B!;
|
||||
expect(rankRows(s).map((x) => x.rank)).toEqual([1, 1, 3]);
|
||||
});
|
||||
|
||||
test('혼자 하기: 1명도 시작, 끝나면 내 점수 요약', () => {
|
||||
let s = make(['A']);
|
||||
s = tick(s, START);
|
||||
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
s = tick(s, s.endsAt + 5);
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A']]);
|
||||
expect(r.summary).toBe(`시간이 다 됐어요. 사과 ${s.score.A}개를 지웠어요`);
|
||||
});
|
||||
|
||||
test('더 지울 게 없으면 "막힘", 모두 막히면 시간 전에 끝나요', () => {
|
||||
let s = rigged(board(['19', '..', '37', '..', '4']));
|
||||
s = act(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 100);
|
||||
expect(s.status.A).toBe('playing');
|
||||
s = act(s, 'A', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 700);
|
||||
expect(s.status.A).toBe('stuck');
|
||||
expect(apple.activePlayers(s)).toEqual(['B']);
|
||||
expect(apple.timeoutPlayers!(s)).toEqual(['A', 'B']);
|
||||
expect(reason(s, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 800)).toBe('더 지울 수 있는 사과가 없어요.');
|
||||
s = act(s, 'B', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 900);
|
||||
s = act(s, 'B', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 1500);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A', 'B']]);
|
||||
expect(r.summary).toContain('모두 더 지울 사과가 없어요');
|
||||
expect(r.summary).toContain('공동 1등 2명');
|
||||
});
|
||||
|
||||
test('나가기: 남은 사람이 1명이면 끝, 나간 사람은 맨 뒤 순위', () => {
|
||||
let s = tick(make(['A', 'B', 'C']), START);
|
||||
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
expect(apple.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
||||
s = act(s, 'A', { type: 'leave' }, START + 600);
|
||||
expect(s.phase).toBe('playing');
|
||||
expect(reason(s, 'A', sel(findMoves(s.boards.A!)[0]!), START + 700)).toBe('게임에서 빠졌어요.');
|
||||
expect(apple.onLeave!(s, 'A')).toBeNull();
|
||||
s = act(s, 'B', { type: 'leave' }, START + 800);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['C'], ['A'], ['B']]);
|
||||
expect(r.summary).toBe('다른 사람이 모두 나가서 남은 사람이 이겼어요');
|
||||
// Solo leaver: the game just ends. Leaving during the countdown works too.
|
||||
const solo = act(make(['A']), 'A', { type: 'leave' }, T0 + 100);
|
||||
expect(solo.phase).toBe('ended');
|
||||
});
|
||||
|
||||
test('클라이언트 액션 스키마에는 select만(tick/leave는 시스템 전용)', () => {
|
||||
expect(apple.actionSchema.safeParse({ type: 'tick' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 9, c1: 16 }).success).toBe(true);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 10, c1: 16 }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 1, c1: 1.5 }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('무작위 대국', () => {
|
||||
test.each([1, 2, 5, 8])('%i명: 엔진 randomPlayout(유출·JSON·결정성) 끝까지', (n) => {
|
||||
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
|
||||
for (let i = 0; i < playoutSeeds(20); i++) {
|
||||
const a = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
|
||||
expect(a.finished).toBe(true);
|
||||
const b = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
|
||||
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
|
||||
const r = apple.result(a.finalState as AppleState)!;
|
||||
expect(r.ranking.flat().sort()).toEqual([...players].sort());
|
||||
const s = a.finalState as AppleState;
|
||||
// Score = apples gone from the board.
|
||||
for (const p of players) expect(s.score[p]).toBe([...s.boards[p]!].filter((c) => c === '0').length);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user