사과 게임: 같은 판(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,102 @@
/** 사과 게임 through a real Room: a practice race against a computer to the end, the server clock, away players (docs/games/apple.md §8.5, §13). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { findMoves, type AppleState, type AppleView } from '@bg/games/apple';
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from './manager';
import { Room, type Conn } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness() {
const store = new RoomStore(openDb(':memory:'));
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
return { clock, manager, conn };
}
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as AppleView;
describe('사과 게임 room flow', () => {
test('컴퓨터와 연습: 사람은 화면에 보이는 판으로 합 10을 지우고, 컴퓨터도 자기 판을 풀고, 2분 뒤 서버 시계로 끝나요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'apple') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
const bot = room.game!.players.find(isBotId)!;
expect(bot).toBeDefined();
let cs = 0;
let rejects = 0;
for (let i = 0; i < 4 * 200 && !room.game!.finished; i++) {
h.clock.advance(250);
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
const d = room.effectiveDeadline();
if (d !== null && d <= h.clock.now()) room.onTimer();
// The person clears one rectangle every 2 seconds, read from their own screen.
const v = lastView(a);
if (i % 8 === 0 && v.phase === 'playing' && v.cells) {
const m = findMoves(v.cells, 1)[0];
if (m) room.act('A', ++cs, { type: 'select', ...m });
}
rejects = a.msgs.filter((m) => m.t === 'reject').length;
}
expect(room.game!.finished).toBe(true);
expect(rejects).toBe(0);
const s = room.game!.state as AppleState;
expect(s.final!.endReason === 'time' || s.final!.endReason === 'cleared').toBe(true);
expect(s.score.A).toBeGreaterThan(20);
expect(s.score[bot]).toBeGreaterThan(10);
// My view never carried the computer's board.
expect(JSON.stringify(lastView(a))).not.toContain(s.boards[bot]!);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('합이 10이 아닌 직사각형은 거절(벌점 없음), 연결이 끊긴 사람은 일찍 시간 초과되지 않아요', () => {
const h = harness();
const r = h.manager.create('A', 'apple', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r as Room;
rooms.push(room);
const a = h.conn('A');
const b = h.conn('B');
room.join(a, 'player');
room.join(b, 'player');
room.ready('B', true);
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
const s = () => room.game!.state as AppleState;
expect(s().phase).toBe('playing');
// Find a 2-cell rectangle that does not add up to 10.
const cells = s().boards.A!;
const c = [...Array(16).keys()].find((k) => Number(cells[k]) + Number(cells[k + 1]) !== 10)!;
room.act('A', 1, { type: 'select', r0: 0, c0: c, r1: 0, c1: c + 1 });
const rej = a.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string };
expect(rej.reason).toMatch(/^합이 \d+이에요/);
expect(s().score.A).toBe(0);
// B drops off: 70 s later (past the 60 s grace) nothing happened to B, the race goes on.
room.disconnect(b);
expect(room.effectiveDeadline()).toBe(s().endsAt);
h.clock.advance(70_000);
room.onTimer();
expect(s().phase).toBe('playing');
expect(s().status.B).toBe('playing');
h.clock.advance(s().endsAt - h.clock.now());
room.onTimer();
expect(room.game!.finished).toBe(true);
});
});

View File

@@ -159,7 +159,8 @@ export class BotDriver {
let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 };
const t0 = performance.now();
try {
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, this.room.profile?.(bot).base), names, memory });
const profile = this.room.profile?.(bot);
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, profile?.base), level: profile?.level ?? idLevel(bot), names, memory });
} catch (err) {
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
}