사과 게임: 같은 판(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

@@ -676,6 +676,76 @@ async function dobbleTap(p: Page, wrong: boolean): Promise<string | null> {
return bubble;
}
/** 사과 게임: my board as the screen draws it (display rows × columns, 0 = empty) and where the SVG sits on the page. */
async function appleGrid(p: Page) {
return p.evaluate(() => {
const svg = document.querySelector('svg.ap-board')!;
const [, , w, h] = svg.getAttribute('viewBox')!.split(' ').map(Number);
const dC = w! / 40;
const dR = h! / 40;
const grid = Array.from({ length: dR }, () => Array<number>(dC).fill(0));
for (const g of svg.querySelectorAll(':scope > g[transform]')) {
const m = /translate\(([\d.]+) ([\d.]+)\)/.exec(g.getAttribute('transform') ?? '');
if (m) grid[Number(m[2]) / 40]![Number(m[1]) / 40] = Number(g.textContent);
}
const b = svg.getBoundingClientRect();
return { grid, dR, dC, box: { x: b.left, y: b.top, w: b.width, h: b.height } };
});
}
/** 사과 게임: a rectangle (display cells) whose apples add up to `want` (10, or anything else for a deliberate miss), smallest first. */
function appleFind(grid: number[][], want: number): [number, number, number, number] | null {
const R = grid.length;
const C = grid[0]!.length;
let best: [number, number, number, number] | null = null;
let bestArea = Infinity;
for (let r0 = 0; r0 < R; r0++)
for (let c0 = 0; c0 < C; c0++)
for (let r1 = r0; r1 < R; r1++)
for (let c1 = c0; c1 < C; c1++) {
const area = (r1 - r0 + 1) * (c1 - c0 + 1);
if (area >= bestArea || area < 2) continue;
let sum = 0;
let n = 0;
for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) if (grid[r]![c]) (sum += grid[r]![c]!), n++;
if (n >= 2 && (want === 10 ? sum === 10 : sum !== 10 && sum < 10)) {
best = [r0, c0, r1, c1];
bestArea = area;
}
}
return best;
}
/** 사과 게임: my score from the 🍎 pill. */
const appleScore = (p: Page) => p.locator('.ap-top .ap-pill', { hasText: '🍎' }).innerText().then((t) => Number(t.replace(/\D/g, '')));
/**
* 사과 게임: one real drag on `p` from display cell (r0, c0) to (r1, c1) — PC: the mouse, phone: touch through CDP (real
* touch events, so the board gets pointerType "touch"). Moves in a few steps like a finger.
*/
async function appleDrag(p: Page, rect: [number, number, number, number], touch: boolean) {
await p.locator('svg.ap-board').evaluate((el) => el.scrollIntoView({ block: 'nearest' }));
const { box, dR, dC } = await appleGrid(p);
const at = (r: number, c: number) => ({ x: box.x + ((c + 0.5) * box.w) / dC, y: box.y + ((r + 0.5) * box.h) / dR });
const a = at(rect[0], rect[1]);
const b = at(rect[2], rect[3]);
const steps = 5;
if (!touch) {
await p.mouse.move(a.x, a.y);
await p.mouse.down();
await p.mouse.move(b.x, b.y, { steps });
await p.mouse.up();
return;
}
const cdp = await p.context().newCDPSession(p);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: a.x, y: a.y }] });
for (let i = 1; i <= steps; i++) {
await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: a.x + ((b.x - a.x) * i) / steps, y: a.y + ((b.y - a.y) * i) / steps }] });
}
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 그림 맞히기: non-white pixels on a page's drawing canvas (proves streamed strokes were rendered). */
async function cmInk(p: Page): Promise<number> {
return p.evaluate(() => {
@@ -2023,6 +2093,118 @@ const PLANS: Record<string, Plan> = {
console.log(' mafia: night kill, police result, dead chat, vote → defense → 찬반 → town won');
},
},
apple: {
// PC host + phone guest, 1-minute race on the same board. Real drags: PC with the mouse (+ one clear with the keyboard:
// arrows + Space for both corners), phone with touch on the turned 17×10 board; one deliberate miss (sum ≠ 10, no
// change); scores reach the other screen; the server clock ends the game and the result shows apples per player.
lobby: async (host) => {
await host.getByRole('group', { name: '제한 시간' }).getByRole('button', { name: '1분', exact: true }).click();
await host.getByText(/제한 시간 1분/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('svg.ap-board').waitFor();
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.ap-over.count') && document.querySelector('svg.ap-board > g[transform]'), null, { timeout: 10_000 });
const phoneGrid = await appleGrid(guest);
const pcGrid = await appleGrid(host);
if (phoneGrid.dR !== 17 || phoneGrid.dC !== 10 || pcGrid.dR !== 10 || pcGrid.dC !== 17) throw new Error(`board shape pc ${pcGrid.dR}×${pcGrid.dC}, phone ${phoneGrid.dR}×${phoneGrid.dC}`);
// Same board for both: the phone's is the PC's turned a quarter clockwise.
const same = pcGrid.grid.every((row, r) => row.every((n, c) => phoneGrid.grid[c]![9 - r] === n));
if (!same) throw new Error('the phone does not show the same board turned');
const st = { pc: 0, phone: 0, key: 0, miss: 0 };
const clear = async (p: Page, how: 'mouse' | 'touch' | 'key') => {
const { grid } = await appleGrid(p);
const rect = appleFind(grid, 10);
if (!rect) throw new Error('no rectangle adds up to 10');
const before = await appleScore(p);
if (how === 'key') {
const board = p.locator('svg.ap-board');
await board.focus();
// To the top-left cell first (the cursor follows the last drag), then to the rectangle.
for (let i = 0; i < 17; i++) await p.keyboard.press('ArrowUp');
for (let i = 0; i < 17; i++) await p.keyboard.press('ArrowLeft');
for (let i = 0; i < rect[0]; i++) await p.keyboard.press('ArrowDown');
for (let i = 0; i < rect[1]; i++) await p.keyboard.press('ArrowRight');
await p.keyboard.press('Space');
for (let i = rect[0]; i < rect[2]; i++) await p.keyboard.press('ArrowDown');
for (let i = rect[1]; i < rect[3]; i++) await p.keyboard.press('ArrowRight');
await p.locator('.ap-pill.sum[data-s="ok"]').waitFor({ timeout: 2000 });
await p.keyboard.press('Space');
await board.blur();
} else await appleDrag(p, rect, how === 'touch');
await p.waitForFunction((b) => Number(document.querySelector('.ap-top')?.textContent?.match(/🍎\s*(\d+)/)?.[1] ?? -1) > b, before, { timeout: 3000 });
};
// A drag that does not add up to 10: nothing happens (no penalty).
const miss = appleFind((await appleGrid(host)).grid, 7);
if (miss) {
const before = await appleScore(host);
await appleDrag(host, miss, false);
await host.locator('.ap-flash.bad').waitFor({ timeout: 2000 });
if ((await appleScore(host)) !== before) throw new Error('a miss changed the score');
st.miss++;
}
for (let i = 0; i < 6; i++) {
await clear(host, 'mouse');
st.pc++;
await clear(guest, 'touch');
st.phone++;
await host.waitForTimeout(250);
}
await host.locator('svg.ap-board').evaluate((el) => (el as SVGElement).focus());
await clear(host, 'key');
st.key++;
// The other screen sees my score.
const hs = await appleScore(host);
const gs = await appleScore(guest);
const seen = (p: Page, who: string, n: number) =>
p.waitForFunction(([w, k]) => [...document.querySelectorAll('.ap-others li')].some((li) => li.textContent?.includes(w as string) && li.querySelector('b')?.textContent === String(k)), [who, n] as const, { timeout: 3000 });
await seen(guest, '방장', hs);
await seen(host, '친구', gs);
// Mid-game shots (one drag held on the phone so the live sum shows).
await host.waitForTimeout(500);
await host.screenshot({ path: join(SHOTS, 'apple-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'apple-mid-phone.png') });
await guest.screenshot({ path: join(SHOTS, 'apple-mid-phone-full.png'), fullPage: true });
const held = appleFind((await appleGrid(host)).grid, 10)!;
{
const { box, dR, dC } = await appleGrid(host);
const at = (r: number, c: number) => ({ x: box.x + ((c + 0.5) * box.w) / dC, y: box.y + ((r + 0.5) * box.h) / dR });
await host.mouse.move(at(held[0], held[1]).x, at(held[0], held[1]).y);
await host.mouse.down();
await host.mouse.move(at(held[2], held[3]).x, at(held[2], held[3]).y, { steps: 3 });
await host.locator('.ap-pill.sum[data-s="ok"]').waitFor({ timeout: 2000 });
await host.screenshot({ path: join(SHOTS, 'apple-drag-pc.png') });
await host.mouse.up();
}
// The smallest phone (320 px wide): the turned board still fits the width.
await guest.setViewportSize({ width: 320, height: 640 });
await guest.waitForTimeout(300);
await guest.screenshot({ path: join(SHOTS, 'apple-mid-phone-320.png') });
const w320 = (await appleGrid(guest)).box;
if (w320.x < 0 || w320.x + w320.w > 320 || w320.w / 10 < 26) throw new Error(`320px board: ${JSON.stringify(w320)}`);
await guest.setViewportSize({ width: 390, height: 844 });
await host.emulateMedia({ colorScheme: 'dark' });
await guest.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(400);
await host.screenshot({ path: join(SHOTS, 'apple-mid-pc-dark.png') });
await guest.screenshot({ path: join(SHOTS, 'apple-mid-phone-dark.png') });
await host.emulateMedia({ colorScheme: 'light' });
await guest.emulateMedia({ colorScheme: 'light' });
// Keep playing until the 1-minute clock runs out on the server.
const until = Date.now() + 75_000;
while (Date.now() < until && !(await host.getByRole('dialog', { name: '게임 결과' }).count())) {
await clear(guest, 'touch').catch(() => {});
await host.waitForTimeout(1500);
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'apple-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'apple-result-phone.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!/사과 \d+개/.test(text)) throw new Error(`no apple scores in the result: ${text.replace(/\n/g, ' ')}`);
console.log(` apple: ${st.pc} mouse + ${st.key} keyboard clears on PC, ${st.phone}+ touch clears on the phone, ${st.miss} miss; final PC ${await appleScore(host)} / phone ${await appleScore(guest)}`);
},
},
};
const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS);