사과 게임: 같은 판(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:
EJClaw
2026-10-12 22:20:49 +09:00
parent 2ec622ebf6
commit b98775b0a6
24 changed files with 2056 additions and 8 deletions

View 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);
}
});
});

View File

@@ -0,0 +1,95 @@
/** 사과 게임 computers (docs/games/apple.md §13): never refused, finish the race, stronger levels clear more apples. */
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { botPersona } from '../bots/persona';
import { liveBotPlayout } from '../bots/live-playout';
import { appleBot, pickMove, skillOf, thinkMs } from './bot';
import { COUNTDOWN_MS, apple, findMoves, rectSum, type AppleState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
const T0 = 1_000_000;
describe('한 판 전체', () => {
test('사람 1명(가만히) + 컴퓨터 1~7명, 컴퓨터끼리만: 거절 0, 시간 맞춰 끝, 빠른 판단', () => {
for (const n of [2, 4, 8]) {
for (const humans of [1, 0]) {
const players = Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:t${n}${i}`));
const r = liveBotPlayout(apple, appleBot, { players, seed: seedN(n * 10 + humans), isBot, levelOf: (p) => 1 + ((p.length * 7) % 60) });
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as AppleState;
for (const p of players) {
if (isBot(p)) expect(s.score[p]).toBeGreaterThan(0);
else expect(s.score[p]).toBe(0);
}
// Time ran out on the server clock (2 minutes + countdown), unless every computer ran out of moves first.
expect(r.elapsed).toBeLessThanOrEqual(COUNTDOWN_MS + 120_000 + 1000);
}
}
});
test('레벨이 높을수록 더 많이 지워요(쉬움 < 보통 < 어려움, 같은 판 여러 번 평균)', () => {
const avg: Record<string, number> = { easy: 0, normal: 0, hard: 0 };
const level: Record<string, number> = { easy: 8, normal: 30, hard: 55 };
const runs = 8;
for (let i = 0; i < runs; i++) {
const players = ['bot:1:easy', 'bot:2:normal', 'bot:3:hard'];
const r = liveBotPlayout(apple, appleBot, {
players,
seed: seedN(300 + i),
isBot,
levelOf: (p) => level[p.split(':')[2]!]!,
// Same pace for all three so only the level differs.
personaOf: (p) => ({ ...botPersona(p), pace: 1 }),
});
const s = r.state as AppleState;
for (const p of players) avg[p.split(':')[2]!]! += s.score[p]! / runs;
}
expect(avg.easy).toBeGreaterThan(15);
expect(avg.normal).toBeGreaterThan(avg.easy! * 1.3);
expect(avg.hard).toBeGreaterThan(avg.normal! * 1.2);
// A person who knows the game gets ~80~120; the strongest computer should be a fair match, not a machine.
expect(avg.hard).toBeLessThan(160);
});
});
describe('판단', () => {
const board = apple.setup({ players: ['bot:1:x'], options: apple.defaultOptions, rng: SeededRng.fromSeed(seedN(9)), now: T0 }).initial;
test('고르는 직사각형은 언제나 합 10', () => {
const r = SeededRng.fromSeed(seedN(1));
for (const level of [1, 20, 40, 60]) {
for (let i = 0; i < 200; i++) {
const m = pickMove(board, 17, skillOf(level), () => r.next());
if (m) expect(rectSum(board, m).sum).toBe(10);
}
}
});
test('쉬움은 가끔 못 찾고 느려요, 어려움은 거의 늘 찾고 빨라요', () => {
const r = SeededRng.fromSeed(seedN(2));
const misses = (level: number) => Array.from({ length: 400 }, () => pickMove(board, 17, skillOf(level), () => r.next())).filter((m) => m === null).length;
expect(misses(1)).toBeGreaterThan(60);
expect(misses(60)).toBe(0);
const mean = (level: number) => Array.from({ length: 400 }, () => thinkMs(skillOf(level), 1, () => r.next())).reduce((a, b) => a + b, 0) / 400;
expect(mean(1)).toBeGreaterThan(5000);
expect(mean(60)).toBeLessThan(2500);
});
test('카운트다운에는 기다리고, 시작하면 생각할 시간을 둔 뒤에 골라요', () => {
let s = apple.setup({ players: ['bot:1:x'], options: apple.defaultOptions, rng: SeededRng.fromSeed(seedN(9)), now: T0 });
const memory: Record<string, unknown> = {};
const ask = (now: number) => appleBot({ me: 'bot:1:x', view: apple.view(s, 'bot:1:x'), now, random: () => 0.5, persona: botPersona('bot:1:x'), level: 60, names: {}, memory });
const d0 = ask(T0 + 100);
expect(d0.action).toBeNull();
expect(d0.next).toBeGreaterThanOrEqual(COUNTDOWN_MS - 100);
s = apple.apply(s, 'bot:1:x', { type: 'tick' }, { rng: SeededRng.fromSeed([1, 1, 1, 1]), now: T0 + COUNTDOWN_MS }).state;
const d1 = ask(T0 + COUNTDOWN_MS);
expect(d1.action).toBeNull();
const d2 = ask(T0 + COUNTDOWN_MS + d1.next);
expect(d2.action).not.toBeNull();
expect(apple.validate(s, 'bot:1:x', d2.action!, { now: T0 + COUNTDOWN_MS + d1.next }).ok).toBe(true);
expect(findMoves(s.boards['bot:1:x']!).length).toBeGreaterThan(0);
});
});

View File

@@ -0,0 +1,75 @@
/**
* 사과 게임 computer players (docs/games/apple.md §13). A live bot: everybody races on their own copy of the board, so
* the server asks each computer again and again on its own timer (like 마피아). It only looks at its own board (`view`).
*
* The level (1~60) sets how it plays, like a person getting better:
* - how long it takes to spot a rectangle that adds up to 10 (about 6 s at level 1 … 2 s at level 60),
* - how far it sees: a weak computer mostly spots small neighbouring pairs, a strong one any rectangle,
* - how often a look finds nothing (a weak computer sometimes stares and misses),
* - what it takes: a strong computer prefers the rectangle with the most apples (more points), a weak one the first it sees.
* The computer's own pace (`persona.pace`) makes some a little quicker or slower than others of the same level.
*/
import type { LiveBotDecision, LiveBotInput } from '../bots/types';
import { findMoves, type Rect } from './index';
import type { AppleView, SelectAction } from './types';
type In = LiveBotInput<AppleView>;
const DEFAULT_LEVEL = 30;
const area = (m: Rect) => (m.r1 - m.r0 + 1) * (m.c1 - m.c0 + 1);
const apples = (cells: string, cols: number, m: Rect) => {
let n = 0;
for (let r = m.r0; r <= m.r1; r++) for (let c = m.c0; c <= m.c1; c++) if (cells[r * cols + c] !== '0') n++;
return n;
};
/** 0 (level 1) … 1 (level 60). */
export const skillOf = (level: number | undefined): number => Math.max(0, Math.min(1, ((level ?? DEFAULT_LEVEL) - 1) / 59));
/** Time to spot the next rectangle (ms). */
export function thinkMs(skill: number, pace: number, random: () => number): number {
const mean = 6000 - 4000 * skill;
return Math.max(700, Math.round(mean * (0.75 + 0.25 * pace) * (0.6 + 0.8 * random())));
}
/** Which rectangle it takes out of those that add up to 10, or null when this look finds nothing. */
export function pickMove(cells: string, cols: number, skill: number, random: () => number): Rect | null {
const all = findMoves(cells);
if (!all.length) return null;
if (random() < 0.3 * (1 - skill)) return null; // stared and missed
// How far it sees: small neighbouring pairs first; a strong computer sees every rectangle.
const reach = 2 + Math.floor(skill * 18);
const seen = all.filter((m) => area(m) <= reach);
const pool = seen.length ? seen : random() < 0.4 + 0.6 * skill ? all : [];
if (!pool.length) return null;
if (random() < skill) {
// Most apples first (more points); among equals the smallest box (quickest to drag).
let best = pool[0]!;
for (const m of pool) {
const d = apples(cells, cols, m) - apples(cells, cols, best);
if (d > 0 || (d === 0 && area(m) < area(best))) best = m;
}
return best;
}
return pool[Math.floor(random() * pool.length)]!;
}
export function appleBot({ me, view: v, now, random, persona, level, memory }: In): LiveBotDecision<SelectAction> {
if (v.phase === 'ended') return { action: null, next: 10_000 };
if (v.phase === 'countdown' || !v.cells) return { action: null, next: Math.max(200, v.countdownEndsAt - now + 50) };
const seat = v.seats.find((s) => s.id === me);
if (!seat || seat.status !== 'playing') return { action: null, next: 10_000 };
const skill = skillOf(level);
// The first look after the start (and after each clear) is a moment of searching, not an instant answer.
const readyAt = typeof memory.readyAt === 'number' ? memory.readyAt : null;
if (readyAt === null || now < readyAt) {
const at = readyAt ?? now + thinkMs(skill, persona.pace, random);
memory.readyAt = at;
return { action: null, next: Math.max(100, at - now) };
}
const m = pickMove(v.cells, v.cols, skill, random);
const wait = thinkMs(skill, persona.pace, random);
memory.readyAt = now + wait;
if (!m) return { action: null, next: wait };
return { action: { type: 'select', ...m }, next: wait };
}

View File

@@ -0,0 +1,368 @@
/**
* 사과 게임 (docs/games/apple.md). Pure and deterministic; state is JSON; time only via ctx.now.
* Everyone solves the same board (one seeded deal) on their own copy at the same time; the server clock ends the game.
*/
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
import {
CELLS,
COLS,
ROWS,
TARGET,
appleActionSchema,
appleOptionsSchema,
type AppleAction,
type AppleFinal,
type AppleOptions,
type AppleState,
type AppleView,
type EndReason,
type RankRow,
type SeatStatus,
type SelectAction,
} from './types';
export * from './types';
type S = AppleState;
type A = AppleAction;
export const COUNTDOWN_MS = 3000;
/** Rate limit: at most this many selects per second per player (a person manages 2~3). */
export const SELECTS_PER_SEC = 5;
export const MAX_PLAYERS = 8;
// ---------------------------------------------------------------- board math
export interface Rect {
r0: number;
c0: number;
r1: number;
c1: number;
}
/** Corners in any order → top-left / bottom-right. */
export function normRect(a: Rect): Rect {
return { r0: Math.min(a.r0, a.r1), c0: Math.min(a.c0, a.c1), r1: Math.max(a.r0, a.r1), c1: Math.max(a.c0, a.c1) };
}
/** Sum and apple count inside a rectangle (cleared cells count as nothing). */
export function rectSum(cells: string, rect: Rect): { sum: number; count: number } {
const { r0, c0, r1, c1 } = normRect(rect);
let sum = 0;
let count = 0;
for (let r = r0; r <= r1; r++) {
for (let c = c0; c <= c1; c++) {
const v = cells.charCodeAt(r * COLS + c) - 48;
if (v > 0) {
sum += v;
count++;
}
}
}
return { sum, count };
}
/**
* Every rectangle whose apples add up to exactly 10, each once in its tightest form (its edges touch apples).
* Prefix sums keep it to ~8k rectangle checks (well under a millisecond). `limit` stops early.
*/
export function findMoves(cells: string, limit = Infinity): Rect[] {
const W = COLS + 1;
const P = new Int32Array((ROWS + 1) * W);
const N = new Int32Array((ROWS + 1) * W);
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const v = cells.charCodeAt(r * COLS + c) - 48;
const i = (r + 1) * W + c + 1;
P[i] = v + P[i - 1]! + P[i - W]! - P[i - W - 1]!;
N[i] = (v > 0 ? 1 : 0) + N[i - 1]! + N[i - W]! - N[i - W - 1]!;
}
}
const box = (T: Int32Array, r0: number, c0: number, r1: number, c1: number) =>
T[(r1 + 1) * W + c1 + 1]! - T[r0 * W + c1 + 1]! - T[(r1 + 1) * W + c0]! + T[r0 * W + c0]!;
const out: Rect[] = [];
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++) {
const sum = box(P, r0, c0, r1, c1);
if (sum > TARGET) break; // only grows with c1
if (sum < TARGET) continue;
// Tight: every edge row / column holds an apple.
if (!box(N, r0, c0, r0, c1) || !box(N, r1, c0, r1, c1) || !box(N, r0, c0, r1, c0) || !box(N, r0, c1, r1, c1)) continue;
out.push({ r0, c0, r1, c1 });
if (out.length >= limit) return out;
}
}
}
}
return out;
}
export const hasMove = (cells: string): boolean => findMoves(cells, 1).length > 0;
/** CELLS apples 1~9 from the seeded RNG; the total is a multiple of 10 (as in the original). */
export function makeBoard(rng: Rng): string {
const v = Array.from({ length: CELLS }, () => 1 + rng.int(9));
let total = v.reduce((a, b) => a + b, 0);
while (total % TARGET !== 0) {
const i = rng.int(CELLS);
total -= v[i]!;
v[i] = 1 + rng.int(9);
total += v[i]!;
}
return v.join('');
}
// ---------------------------------------------------------------- helpers
function clone(s: S): S {
return {
...s,
order: [...s.order],
boards: { ...s.boards },
score: { ...s.score },
clears: { ...s.clears },
status: { ...s.status },
recent: Object.fromEntries(Object.entries(s.recent).map(([k, v]) => [k, [...v]])),
};
}
interface Ctx {
now: number;
events: GameEvent[];
}
const inGame = (s: S, p: PlayerId) => s.status[p] === 'playing' || s.status[p] === 'stuck';
/** The countdown is over (the room timer may not have ticked yet). */
const started = (s: S, now: number | undefined) => s.phase === 'playing' || (s.phase === 'countdown' && now !== undefined && now >= s.countdownEndsAt);
function rateOk(times: readonly number[] | undefined, now: number | undefined): boolean {
if (now === undefined || !times || times.length < SELECTS_PER_SEC) return true;
return now - times[times.length - SELECTS_PER_SEC]! >= 1000;
}
/** Brings the phase up to the clock: countdown → playing → ended (time). */
function catchUp(s: S, ctx: Ctx): void {
if (s.phase === 'countdown' && ctx.now >= s.countdownEndsAt) {
s.phase = 'playing';
ctx.events.push({ type: 'start' });
}
if (s.phase === 'playing' && ctx.now >= s.endsAt) finish(s, 'time', ctx);
}
function select(s: S, p: PlayerId, a: SelectAction, ctx: Ctx): void {
const { r0, c0, r1, c1 } = normRect(a);
const b = s.boards[p]!.split('');
let count = 0;
for (let r = r0; r <= r1; r++) {
for (let c = c0; c <= c1; c++) {
if (b[r * COLS + c] !== '0') {
b[r * COLS + c] = '0';
count++;
}
}
}
s.boards[p] = b.join('');
s.score[p] = (s.score[p] ?? 0) + count;
s.clears[p] = (s.clears[p] ?? 0) + 1;
s.recent[p] = [...(s.recent[p] ?? []).slice(-(SELECTS_PER_SEC - 1)), ctx.now];
ctx.events.push({ type: 'clear', player: p, count, score: s.score[p] });
if (!hasMove(s.boards[p]!)) {
s.status[p] = 'stuck';
ctx.events.push({ type: 'stuck', player: p });
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
}
}
function leave(s: S, p: PlayerId, ctx: Ctx): void {
s.status[p] = 'left';
ctx.events.push({ type: 'left', player: p });
const still = s.order.filter((q) => inGame(s, q));
// Nobody left to race against (or nobody at all): the game is decided.
if (still.length === 0 || (still.length === 1 && s.order.length > 1)) finish(s, 'left', ctx);
else if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
}
// ---------------------------------------------------------------- ending
/** Shared ranks by score (ties share a rank); players who left come after everyone who stayed. */
export function rankRows(s: Pick<S, 'order' | 'score' | 'clears' | 'status'>): RankRow[] {
const rows: RankRow[] = [];
for (const left of [false, true]) {
const group = s.order.filter((p) => (s.status[p] === 'left') === left).sort((a, b) => (s.score[b] ?? 0) - (s.score[a] ?? 0));
group.forEach((id, i) => {
const prev = rows.at(-1);
const score = s.score[id] ?? 0;
const tie = i > 0 && prev && prev.score === score;
rows.push({ rank: tie ? prev.rank : rows.length + 1, id, score, clears: s.clears[id] ?? 0, left });
});
}
return rows;
}
function finish(s: S, reason: EndReason, ctx: Ctx): void {
if (s.phase === 'ended') return;
s.phase = 'ended';
const ranking = rankRows(s);
const top = ranking.filter((r) => r.rank === 1);
let summary: string;
if (s.order.length === 1) {
const n = ranking[0]!.score;
summary = reason === 'cleared' ? `더 지울 사과가 없어요. 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
} else if (reason === 'left') summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요';
else {
summary = reason === 'cleared' ? '모두 더 지울 사과가 없어요. 가장 많이 지운 사람이 이겼어요' : '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요';
if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`;
}
s.final = { endReason: reason, ranking, summary } satisfies AppleFinal;
ctx.events.push({ type: 'gameEnd', reason });
}
// ---------------------------------------------------------------- definition
type Def = GameDefinition<S, A, AppleView, AppleOptions>;
export const apple: Def = {
id: 'apple',
nameKo: '사과 게임',
minPlayers: 1,
maxPlayers: MAX_PLAYERS,
stateVersion: 1,
defaultOptions: appleOptionsSchema.parse({}),
optionsSchema: appleOptionsSchema as unknown as Def['optionsSchema'],
actionSchema: appleActionSchema as unknown as Def['actionSchema'],
setup({ players, options, rng, now }) {
if (players.length < 1 || players.length > MAX_PLAYERS) throw new Error(`apple: ${players.length} players not allowed`);
// One board for everybody, from the seeded RNG (§8.4).
const initial = makeBoard(rng);
const per0 = <T>(v: () => T) => Object.fromEntries(players.map((p) => [p, v()])) as Record<PlayerId, T>;
const countdownEndsAt = now + COUNTDOWN_MS;
return {
options,
order: [...players],
initial,
boards: per0(() => initial),
score: per0(() => 0),
clears: per0(() => 0),
status: per0<SeatStatus>(() => 'playing'),
recent: per0<number[]>(() => []),
phase: 'countdown',
countdownEndsAt,
endsAt: countdownEndsAt + options.timeLimitSec * 1000,
final: null,
};
},
validate(s, actor, a, vctx) {
if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase === 'ended') return fail('게임이 이미 끝났어요.');
const now = vctx?.now;
switch (a.type) {
case 'tick':
return ok;
case 'leave':
return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.');
case 'select': {
if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
if (now !== undefined && now >= s.endsAt) return fail('시간이 다 됐어요.');
if (s.status[actor] === 'stuck') return fail('더 지울 수 있는 사과가 없어요.');
if (!rateOk(s.recent[actor], now)) return fail('조금 천천히 해 주세요.');
const { sum, count } = rectSum(s.boards[actor]!, a);
if (count === 0) return fail('고른 칸에 사과가 없어요.');
if (sum !== TARGET) return fail(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`);
return ok;
}
}
},
apply(prev, actor, a, { now }) {
const s = clone(prev);
const ctx: Ctx = { now, events: [] };
catchUp(s, ctx);
if (s.phase !== 'ended') {
if (a.type === 'leave') leave(s, actor, ctx);
else if (a.type === 'select' && s.phase === 'playing') select(s, actor, a, ctx);
}
return { state: s, events: ctx.events };
},
view(s, viewer) {
const me = viewer && s.order.includes(viewer) ? viewer : null;
return {
options: s.options,
me,
phase: s.phase,
rows: ROWS,
cols: COLS,
cells: me && s.phase !== 'countdown' ? s.boards[me]! : null,
countdownEndsAt: s.countdownEndsAt,
endsAt: s.endsAt,
seats: s.order.map((id) => ({ id, score: s.score[id] ?? 0, clears: s.clears[id] ?? 0, status: s.status[id]! })),
result: s.final,
};
},
/** No turns: everyone still in may clear apples at any time. */
activePlayers(s) {
if (s.phase === 'ended') return [];
return s.order.filter((p) => s.status[p] === 'playing');
},
deadline(s) {
if (s.phase === 'ended') return null;
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
},
/** Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else). */
timeoutPlayers(s) {
if (s.phase === 'ended') return [];
return s.order.filter((p) => inGame(s, p));
},
/** A disconnected player is never timed out early: their score simply stays until the server clock ends the game. */
timeoutNotBefore(s) {
if (s.phase === 'ended') return null;
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
},
onTimeout() {
return { type: 'tick' };
},
onLeave(s, player) {
if (s.phase === 'ended' || !inGame(s, player)) return null;
return { type: 'leave' };
},
result(s): GameResult | null {
const f = s.final;
if (!f) return null;
const groups = new Map<number, PlayerId[]>();
for (const r of f.ranking) groups.set(r.rank, [...(groups.get(r.rank) ?? []), r.id]);
return {
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ids]) => ids),
scores: Object.fromEntries(f.ranking.map((r) => [r.id, r.score])),
scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `사과 ${r.score}개`])),
summary: f.summary,
reason: 'normal',
};
},
/** Test helper: the clock tick and the first few rectangles that add up to 10. */
legalActions(s, p) {
if (s.phase === 'ended' || !s.order.includes(p)) return [];
const out: A[] = [{ type: 'tick' }];
if (s.phase === 'playing' && s.status[p] === 'playing') {
for (const m of findMoves(s.boards[p]!, 8)) out.push({ type: 'select', ...m });
}
return out.filter((x) => apple.validate(s, p, x).ok);
},
/** The board is the same for everyone; only the countdown hides it (so nobody gets a head start). */
secretsOf(s) {
return s.phase === 'countdown' ? [s.initial] : [];
},
};

View File

@@ -0,0 +1,87 @@
/** 사과 게임 options, actions, state and view types (docs/games/apple.md §2, §8). */
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
/** The board is 10 rows × 17 columns (the original Fruit Box size). Phones show it turned (17 rows × 10 columns). */
export const ROWS = 10;
export const COLS = 17;
export const CELLS = ROWS * COLS;
export const TARGET = 10;
const lit = <T extends number>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const appleOptionsSchema = z.object({
timeLimitSec: lit<60 | 120 | 180>(60, 120, 180)
.default(120)
.meta({ title: '제한 시간', labels: { 60: '1분', 120: '2분', 180: '3분' } }),
});
export type AppleOptions = z.infer<typeof appleOptionsSchema>;
/** A rectangle by two opposite corners (any order), rows 0..9, columns 0..16. */
export const appleActionSchema = z.object({
type: z.literal('select'),
r0: z.number().int().min(0).max(ROWS - 1),
c0: z.number().int().min(0).max(COLS - 1),
r1: z.number().int().min(0).max(ROWS - 1),
c1: z.number().int().min(0).max(COLS - 1),
});
export type SelectAction = z.infer<typeof appleActionSchema>;
/** Client action plus system-only ones (server timer, leaving) that are not in the schema. */
export type AppleAction = SelectAction | { type: 'tick' } | { type: 'leave' };
export type SeatStatus = 'playing' | 'stuck' | 'left';
export type EndReason = 'time' | 'cleared' | 'left';
export interface RankRow {
rank: number;
id: PlayerId;
score: number;
clears: number;
left: boolean;
}
export interface AppleFinal {
endReason: EndReason;
ranking: RankRow[];
summary: string;
}
export interface AppleState {
options: AppleOptions;
order: PlayerId[];
/** The shared starting board: CELLS digits '1'..'9', row-major. Hidden until the countdown ends. */
initial: string;
/** Each player's own board: same as `initial` with cleared apples as '0'. */
boards: Record<PlayerId, string>;
score: Record<PlayerId, number>;
clears: Record<PlayerId, number>;
status: Record<PlayerId, SeatStatus>;
/** Server times of each player's recent selects (rate limit). */
recent: Record<PlayerId, number[]>;
phase: 'countdown' | 'playing' | 'ended';
countdownEndsAt: number;
endsAt: number;
final: AppleFinal | null;
}
export interface SeatView {
id: PlayerId;
score: number;
clears: number;
status: SeatStatus;
}
export interface AppleView {
options: AppleOptions;
me: PlayerId | null;
phase: AppleState['phase'];
rows: number;
cols: number;
/** My board (CELLS digits, '0' = cleared); null for spectators and during the countdown. */
cells: string | null;
countdownEndsAt: number;
endsAt: number;
seats: SeatView[];
result: AppleFinal | null;
}

View File

@@ -30,6 +30,7 @@ import { lasVegasBot } from '../las-vegas/bot';
import { cockroachPokerBot } from '../cockroach-poker/bot';
import { ninetyNineBot } from '../ninety-nine/bot';
import { mafiaBot } from '../mafia/bot';
import { appleBot } from '../apple/bot';
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -97,7 +98,8 @@ export function decideBotAction(
return rest.length ? pick(playable(rest), random) : null;
}
/** Live strategies (games where everybody acts at once and talks); also in `BOT_GAMES`. */
/** Live strategies (games where everybody acts at once: 마피아 talks, 사과 게임 races on its own board); also in `BOT_GAMES`. */
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
mafia: mafiaBot,
apple: appleBot,
};

View File

@@ -1,6 +1,6 @@
/** Test helper: live bots (마피아) play a whole game on a simulated clock, each on its own timer, like `BotDriver`. */
import { SeededRng, type AnyGameDefinition, type PlayerId, type RngState } from '@bg/engine';
import { botPersona, type BotPersona } from './persona';
import { botPersona, type BotLevel, type BotPersona } from './persona';
import type { LiveBotStrategy } from './types';
export interface LiveLine {
@@ -33,6 +33,8 @@ export function liveBotPlayout(
names?: Record<PlayerId, string>;
/** Override characters (tests): called once after setup with the game state. */
personaOf?: (p: PlayerId, state: unknown) => BotPersona;
/** Each computer's level (default: none, the strategy's own default). */
levelOf?: (p: PlayerId) => BotLevel;
maxMs?: number;
},
): LivePlayoutReport {
@@ -72,7 +74,7 @@ export function liveBotPlayout(
if (bot === null) throw new Error(`${def.id}: stalled`);
now = Math.max(now, due.get(bot)!);
const t0 = performance.now();
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, names, memory: memory.get(bot)! });
const d = strategy({ me: bot, view: structuredClone(def.view(state, bot)), now, random, persona: persona.get(bot)!, level: opts.levelOf?.(bot), names, memory: memory.get(bot)! });
rep.maxBotMs = Math.max(rep.maxBotMs, performance.now() - t0);
due.set(bot, now + Math.max(50, d.next));
if (d.action) {

View File

@@ -35,6 +35,8 @@ export interface LiveBotInput<V = any> {
now: number;
random: () => number;
persona: import('./persona').BotPersona;
/** The computer's level now (1~60, docs/09 §9.1); absent in tests that only care about the character. */
level?: import('./persona').BotLevel;
/** Display names of the players (what people call each other in chat). */
names: Record<PlayerId, string>;
/** The bot's own notes for this game (what it already said or did). Kept by the caller between calls. */

View File

@@ -25,6 +25,7 @@ import { ninetyNine } from './ninety-nine';
import { dobble } from './dobble';
import { catchmind } from './catchmind';
import { mafia } from './mafia';
import { apple } from './apple';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -53,4 +54,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[dobble.id]: dobble,
[catchmind.id]: catchmind,
[mafia.id]: mafia,
[apple.id]: apple,
};

View File

@@ -23,7 +23,8 @@ export function botProfile(id: string): PublicUser | null {
/**
* Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11).
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11). 사과 게임 is a race where everyone solves
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12).
*/
export const BOT_GAMES: readonly string[] = [
'omok',
@@ -49,6 +50,7 @@ export const BOT_GAMES: readonly string[] = [
'cockroach-poker',
'ninety-nine',
'mafia',
'apple',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1). */

View File

@@ -36,6 +36,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'ninety-nine', nameKo: '구십구', minPlayers: 2, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '카드를 내며 숫자를 더해요. 99를 넘기면 탈락!', available: true },
{ id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true },
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
];