새 게임 5개(같은 판 경주): 지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직

- 공통 틀 race: 같은 시드 판을 모두 각자 동시에, 3초 카운트다운, 제한 시간/무제한, 포기, 다 푼 시간 → 푼 만큼 순위, live 컴퓨터
- 지뢰찾기: 초급·중급·고급, 모두에게 같은 곳이 열린 채 시작, 깃발·한꺼번에 열기, 휴대폰 길게 누르기·깃발 모드
- 사천성: 마작패 72·112·136장, 두 번 이하로 꺾이는 선, 항상 풀리는 배치, 막히면 자동 섞기, 힌트
- 솔리테어: 클론다이크(1장·3장)·프리셀·스파이더(1·2·4무늬), 되돌리기, 자동 정리
- 스도쿠: 답이 하나인 문제 생성기(쉬움·보통·어려움), 메모, 겹침 표시, 힌트
- 네모네모 로직: 그림 37개(5×5·10×10·15×15, 모두 줄 논리만으로 풀림), 드래그 칠하기·X 표시, 풀면 그림과 이름
- 게임 46개, 컴퓨터 상대 42개, 게임 고르기에 혼자·퍼즐 탭
(아발론·모노레일은 아직 공개 전이라 이 배포에서 뺌; 작업 갈래 codex/owner/grp_discord_joke-app 2773f5c..에서 옮김)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-24 14:29:01 +09:00
parent 35f2310f8d
commit 1b9acb9fc1
66 changed files with 8958 additions and 3 deletions

View File

@@ -10,6 +10,12 @@ import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { plan960 } from './chess960-plan';
import { sureMove } from '../packages/games/src/minesweeper/bot';
import { findPair as ssFindPair } from '../packages/games/src/shisen';
import { chooseMove as solChoose } from '../packages/games/src/solitaire/bot';
import type { SolitaireBoardView, SolitaireMove } from '../packages/games/src/solitaire';
import { solve } from '../packages/games/src/sudoku';
import { solveGrid } from '../packages/games/src/nonogram/solver';
const PORT = Number(process.env.E2E_PORT ?? 4519);
const ORIGIN = `http://localhost:${PORT}`;
@@ -849,6 +855,240 @@ async function appleDrag(p: Page, rect: [number, number, number, number], touch:
await cdp.detach();
}
/** 지뢰찾기: my board as the screen draws it (canonical cells in index order) plus where each cell sits. */
async function msGrid(p: Page) {
return p.evaluate(() => {
const out: { ch: string; x: number; y: number }[] = [];
for (const g of document.querySelectorAll('svg.ms-board g[data-i]')) {
const b = g.getBoundingClientRect();
out[Number(g.getAttribute('data-i'))] = { ch: g.getAttribute('data-ch')!, x: b.left + b.width / 2, y: b.top + b.height / 2 };
}
return out;
});
}
/** 지뢰찾기: one real tap on the phone through CDP (pointerType "touch"); `holdMs` makes it a long press. */
async function touchTap(p: Page, x: number, y: number, holdMs = 0) {
const cdp = await p.context().newCDPSession(p);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
if (holdMs) await p.waitForTimeout(holdMs);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 사천성: my board as drawn (cells by index, from the tiles on screen) plus where each tile sits. */
async function ssGrid(p: Page) {
return p.evaluate(() => {
const board = document.querySelector('.ss-board')!;
const rows = Number(board.getAttribute('data-rows'));
const cols = Number(board.getAttribute('data-cols'));
const cells: (string | null)[] = Array(rows * cols).fill(null);
const pos: { x: number; y: number }[] = [];
for (const el of board.querySelectorAll('.ss-cell[data-i]')) {
const i = Number(el.getAttribute('data-i'));
const b = el.getBoundingClientRect();
cells[i] = el.getAttribute('data-k');
pos[i] = { x: b.left + b.width / 2, y: b.top + b.height / 2 };
}
return { rows, cols, cells, pos };
});
}
/** 사천성: one real tap on the phone through CDP (pointerType "touch"). */
async function ssTap(p: Page, x: number, y: number) {
const cdp = await p.context().newCDPSession(p);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 사천성: waits until my board shows `n` tiles. */
async function ssWaitTiles(p: Page, n: number) {
await p.waitForFunction((k) => document.querySelectorAll('.ss-board .ss-cell[data-i]').length === k, n, { timeout: 5000 });
}
/** 솔리테어: my table as the screen draws it (face-down = null, only the waste top), read from the data attributes. */
async function solRead(p: Page): Promise<SolitaireBoardView> {
return p.evaluate(() => {
const mode = document.querySelector('.sl-felt')!.getAttribute('data-mode') as 'klondike' | 'freecell' | 'spider';
const n = mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10;
const cardsIn = (sel: string) => [...document.querySelectorAll(`${sel} [data-card]`)].map((e) => e.getAttribute('data-card') || null);
const t = Array.from({ length: n }, (_, i) => cardsIn(`[data-pile="t${i}"]`));
const waste = cardsIn('[data-pile="w"]').filter((c): c is string => !!c);
const f = mode === 'spider' ? [] : [0, 1, 2, 3].map((i) => document.querySelector(`[data-pile="f${i}"]`)?.getAttribute('data-top') ?? '');
const cells = mode === 'freecell' ? [0, 1, 2, 3].map((i) => cardsIn(`[data-pile="c${i}"]`)[0] ?? '') : [];
const stock = Number(document.querySelector('[data-pile="s"]')?.getAttribute('data-count') ?? 0);
const done = 'S'.repeat(document.querySelectorAll('.sl-done-card').length);
return { mode, draw: 1 as const, t, stock, waste, cells, f, done, canUndo: false, undos: 0 };
});
}
const solKey = async (p: Page) => JSON.stringify(await solRead(p));
/** 솔리테어: one real tap on the phone through CDP (pointerType "touch"). */
async function solTap(p: Page, x: number, y: number) {
const cdp = await p.context().newCDPSession(p);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 솔리테어: where to press card `k` of a pile (the visible strip of a covered card), or the pile's slot / stock. */
async function solSpot(p: Page, pile: string, k: number | 'top'): Promise<{ x: number; y: number }> {
const cards = p.locator(`[data-pile="${pile}"] [data-card]`);
const n = await cards.count();
const idx = k === 'top' ? n - 1 : k;
const el = n ? cards.nth(idx) : p.locator(`[data-pile="${pile}"] button`).first();
await el.scrollIntoViewIfNeeded();
const b = await el.boundingBox();
if (!b) throw new Error(`nothing to press on ${pile}`);
const covered = n > 0 && idx < n - 1;
return { x: b.x + b.width / 2, y: covered ? b.y + Math.min(9, b.height / 5) : b.y + b.height / 2 };
}
/** 솔리테어: plays one move the way a person would — PC mouse (click, click / double-click), phone touch (tap, tap / double tap). */
async function solDo(p: Page, m: SolitaireMove, phone: boolean, v: SolitaireBoardView) {
const press = async (pt: { x: number; y: number }) => (phone ? solTap(p, pt.x, pt.y) : p.mouse.click(pt.x, pt.y));
if (m.type === 'draw' || m.type === 'deal') return press(await solSpot(p, 's', 'top'));
if (m.type !== 'move') throw new Error(`unexpected ${m.type}`);
if (m.to === 'f') {
const pt = await solSpot(p, m.from, 'top');
if (!phone) return p.mouse.dblclick(pt.x, pt.y);
await solTap(p, pt.x, pt.y);
await p.waitForTimeout(60);
return solTap(p, pt.x, pt.y);
}
const len = m.from[0] === 't' ? v.t[Number(m.from.slice(1))]!.length : 1;
await press(await solSpot(p, m.from, m.from[0] === 't' ? len - m.n : 'top'));
await p.locator(`[data-pile="${m.from}"] button[aria-pressed="true"]`).first().waitFor({ timeout: 3000 });
await p.waitForTimeout(420); // not a double tap
await press(await solSpot(p, m.to, 'top'));
}
/** 솔리테어: what each page's chooser already tried (so it never repeats a move from the same table). */
const solMem = new WeakMap<Page, Record<string, unknown>>();
/** 솔리테어: both screens start from the same deal, then each plays `steps` moves the computer's rules pick from that screen. */
async function solPlay(pages: Page[], steps: number) {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('.sl-felt [data-pile="t0"] [data-card]').first().waitFor({ timeout: 10_000 });
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 });
if ((await solKey(host)) !== (await solKey(guest))) throw new Error('the two screens do not start from the same deal');
const st = { pcF: 0, pcMove: 0, pcDraw: 0, phoneF: 0, phoneMove: 0, phoneDraw: 0 };
const step = async (p: Page, phone: boolean) => {
const v = await solRead(p);
if (!solMem.has(p)) solMem.set(p, {});
const m = solChoose(v, 0, () => 0.3, solMem.get(p)!);
if (m.type === 'stop') return false;
const before = JSON.stringify(v);
await solDo(p, m, phone, v);
for (let t = 0; t < 40 && (await solKey(p)) === before; t++) await p.waitForTimeout(100);
if ((await solKey(p)) === before) throw new Error(`${phone ? 'phone' : 'PC'}: ${JSON.stringify(m)} did not change the table`);
st[`${phone ? 'phone' : 'pc'}${m.type === 'move' ? (m.to === 'f' ? 'F' : 'Move') : 'Draw'}` as keyof typeof st]++;
await p.waitForTimeout(150);
return true;
};
for (let i = 0; i < steps; i++) {
const a = await step(host, false);
const b = await step(guest, true);
if (!a && !b) break;
}
return st;
}
/** 솔리테어: both give up (press twice) and the final ranking shows. */
async function solGiveUp(pages: Page[]) {
for (const p of pages) {
if (await p.locator('.rc-over.note').count()) continue;
await p.getByRole('button', { name: '포기할래요' }).click();
await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click();
}
for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 });
}
/** 스도쿠: my board as the screen draws it (per cell in index order: digit, given, red, where it sits). */
async function sdGrid(p: Page) {
return p.evaluate(() =>
[...document.querySelectorAll('.sd-grid [data-i]')].map((el) => {
const b = el.getBoundingClientRect();
return { v: el.getAttribute('data-v')!, given: el.getAttribute('data-given') === 'true', bad: el.getAttribute('data-bad') === 'true', x: b.left + b.width / 2, y: b.top + b.height / 2 };
}),
);
}
/** 스도쿠: waits until cell `i` on the screen shows `v` ('0' = empty). */
async function sdWaitCell(p: Page, i: number, v: string) {
await p.waitForFunction(([k, d]) => document.querySelector(`.sd-grid [data-i="${k}"]`)?.getAttribute('data-v') === d, [i, v] as const, { timeout: 3000 });
}
/** 스도쿠: one real tap on the phone through CDP (pointerType "touch"). */
async function sdTouch(p: Page, x: number, y: number) {
const cdp = await p.context().newCDPSession(p);
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 스도쿠: taps a button's centre on the phone. */
async function sdTouchButton(p: Page, l: Locator) {
const b = (await l.boundingBox())!;
await sdTouch(p, b.x + b.width / 2, b.y + b.height / 2);
}
/** 네모네모 로직: my marks as the screen draws them ('0' / '1' / '2' in index order), each cell's centre and the clues per line. */
async function ngBoard(p: Page) {
return p.evaluate(() => {
const cells: { m: string; x: number; y: number; w: number }[] = [];
for (const g of document.querySelectorAll('svg.ng-board g[data-i]')) {
const b = g.querySelector('rect')!.getBoundingClientRect();
cells[Number(g.getAttribute('data-i'))] = { m: g.getAttribute('data-m')!, x: b.left + b.width / 2, y: b.top + b.height / 2, w: b.width };
}
const clues: number[][] = [];
for (const t of document.querySelectorAll('svg.ng-board text[data-line]')) {
const line = Number(t.getAttribute('data-line'));
(clues[line] ??= [])[Number(t.getAttribute('data-k'))] = Number(t.textContent);
}
return { cells, clues: clues.map((c) => c.filter((x) => x > 0)), size: Math.round(Math.sqrt(cells.length)) };
});
}
/** 네모네모 로직: one straight drag from cell `a` to cell `b`, with the mouse (PC) or a real touch through CDP (phone). */
async function ngDrag(p: Page, a: { x: number; y: number }, b: { x: number; y: number }, touch: boolean) {
const steps = 6;
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 k = 1; k <= steps; k++) await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: a.x + ((b.x - a.x) * k) / steps, y: a.y + ((b.y - a.y) * k) / steps }] });
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
await cdp.detach();
}
/** 네모네모 로직: fill row r's answer runs that are not filled yet, one drag per run; waits until the screen shows them. */
async function ngFillRow(p: Page, answer: string, r: number, touch: boolean): Promise<number> {
const { cells, size } = await ngBoard(p);
let drags = 0;
let c = 0;
while (c < size) {
if (answer[r * size + c] !== '#') {
c++;
continue;
}
const run: number[] = [];
while (c < size && answer[r * size + c] === '#') run.push(r * size + c++);
const todo = run.filter((i) => cells[i]!.m === '0');
if (!todo.length) continue;
await ngDrag(p, cells[todo[0]!]!, cells[todo.at(-1)!]!, touch);
await p.waitForFunction((ids) => ids.every((i) => document.querySelector(`svg.ng-board g[data-i="${i}"]`)?.getAttribute('data-m') === '1'), todo, { timeout: 3000 });
drags++;
}
return drags;
}
/** 그림 맞히기: non-white pixels on a page's drawing canvas (proves streamed strokes were rendered). */
async function cmInk(p: Page): Promise<number> {
return p.evaluate(() => {
@@ -3613,6 +3853,454 @@ const PLANS: Record<string, Plan> = {
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)}`);
},
},
minesweeper: {
// PC host + phone guest on the same 초급 field. Sure moves only (read from each screen): PC with left click (open /
// chord) and right click (flag), phone with taps and a long press (flag) plus the 깃발 mode button; progress reaches the
// other screen; both give up (press twice) and the result ranks them.
lobby: async (host) => {
await host.getByRole('group', { name: '난이도' }).getByRole('button', { name: '초급', exact: true }).click();
await host.getByText(/초급 9×9/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('svg.ms-board g[data-i]').first().waitFor({ timeout: 10_000 });
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 });
const a = await msGrid(host);
const b = await msGrid(guest);
if (a.map((c) => c.ch).join('') !== b.map((c) => c.ch).join('')) throw new Error('the two screens do not start from the same opening');
const st = { pcOpen: 0, pcFlag: 0, phoneOpen: 0, phoneFlag: 0 };
const cellsOf = (g: { ch: string }[]) => g.map((c) => c.ch).join('');
const step = async (p: Page, phone: boolean) => {
const g = await msGrid(p);
const v = { rows: 9, cols: 9, mines: 10, cells: cellsOf(g), flags: 0 };
const m = sureMove(v, true);
if (!m) return false;
const c = g[m.i]!;
const before = v.cells;
if (!phone) {
if (m.type === 'flag') await p.mouse.click(c.x, c.y, { button: 'right' });
else await p.mouse.click(c.x, c.y);
} else if (m.type === 'flag') await touchTap(p, c.x, c.y, 600);
else await touchTap(p, c.x, c.y);
await p.waitForFunction((was) => [...document.querySelectorAll('svg.ms-board g[data-i]')].map((x) => x.getAttribute('data-ch')).join('') !== was, before, { timeout: 3000 });
const k = `${phone ? 'phone' : 'pc'}${m.type === 'flag' ? 'Flag' : 'Open'}` as keyof typeof st;
st[k]++;
return true;
};
for (let i = 0; i < 12; i++) {
const pc = await step(host, false);
const ph = await step(guest, true);
if (!pc && !ph) break;
if (await host.locator('.rc-over.note').count()) break;
}
// The 깃발 mode button on the phone turns a plain tap into a flag (and back).
const g = await msGrid(guest);
const closed = g.findIndex((c) => c.ch === '#');
if (closed >= 0 && !(await guest.locator('.rc-over.note').count())) {
await guest.getByRole('button', { name: '깃발 모드' }).click();
await touchTap(guest, g[closed]!.x, g[closed]!.y);
await guest.locator(`svg.ms-board g[data-i="${closed}"][data-ch="F"]`).waitFor({ timeout: 3000 });
await touchTap(guest, g[closed]!.x, g[closed]!.y);
await guest.locator(`svg.ms-board g[data-i="${closed}"][data-ch="#"]`).waitFor({ timeout: 3000 });
await guest.getByRole('button', { name: '깃발 모드' }).click();
}
// The host's progress shows on the phone.
const opened = (await msGrid(host)).filter((c) => /[0-8]/.test(c.ch)).length;
await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/71`)), opened, { timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'minesweeper-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'minesweeper-mid-phone.png') });
for (const p of pages) {
if (await p.locator('.rc-over.note').count()) continue;
await p.getByRole('button', { name: '포기할래요' }).click();
await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click();
}
for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 });
await host.screenshot({ path: join(SHOTS, 'minesweeper-result-pc.png') });
if (st.pcOpen + st.pcFlag + st.phoneOpen + st.phoneFlag < 4) throw new Error(`too few sure moves ${JSON.stringify(st)}`);
console.log(` minesweeper: ${JSON.stringify(st)}, flag mode, progress shared, both gave up → result`);
},
},
shisen: {
// PC host + phone guest on the same 작게 12×6 board. The PC removes pairs with the mouse and one with the keyboard,
// tries a wrong pair (shake + reason) and deselects; the phone (board turned upright) taps pairs and uses a hint;
// progress reaches the other screen; both give up (press twice) and the result ranks them.
lobby: async (host) => {
await host.getByRole('group', { name: '판 크기' }).getByRole('button', { name: '작게', exact: true }).click();
await host.getByText(/작게 12×6/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('.ss-board .ss-cell[data-i]').first().waitFor({ timeout: 10_000 });
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 });
const a = await ssGrid(host);
const b = await ssGrid(guest);
if (JSON.stringify(a.cells) !== JSON.stringify(b.cells) || a.cells.some((k) => !k)) throw new Error('the two screens do not start from the same full board');
// Phone: the 12×6 board is turned upright and fits the screen without scrolling.
const box = await guest.locator('.ss-board').boundingBox();
if (!box || box.height <= box.width || box.x < 0 || box.x + box.width > 390 || box.y + box.height > 844) throw new Error(`phone board ${JSON.stringify(box)}`);
const st = { pcMouse: 0, pcKey: 0, phoneTap: 0, phoneHint: 0 };
const left = { host: 72, guest: 72 };
/** Removes one pair that goes now, by mouse (PC) or touch (phone). */
const pair = async (p: Page, phone: boolean, shot?: string) => {
const g = await ssGrid(p);
const two = ssFindPair(g.cells, g.rows, g.cols)!;
for (const i of two) {
const c = g.pos[i]!;
if (phone) await ssTap(p, c.x, c.y);
else await p.mouse.click(c.x, c.y);
}
if (shot) await p.screenshot({ path: join(SHOTS, shot) });
const k = phone ? 'guest' : 'host';
left[k] -= 2;
await ssWaitTiles(p, left[k]);
};
for (let i = 0; i < 4; i++) {
await pair(host, false, i === 1 ? 'shisen-line-pc.png' : undefined);
st.pcMouse++;
await pair(guest, true, i === 1 ? 'shisen-line-phone.png' : undefined);
st.phoneTap++;
}
// PC keyboard: back to the top-left corner, then arrows + Space on both tiles of a pair.
{
const g = await ssGrid(host);
const two = ssFindPair(g.cells, g.rows, g.cols)!;
await host.locator('.ss-board').focus();
for (let k = 0; k < g.rows; k++) await host.keyboard.press('ArrowUp');
for (let k = 0; k < g.cols; k++) await host.keyboard.press('ArrowLeft');
let at = [0, 0];
for (const i of two) {
const to = [Math.floor(i / g.cols), i % g.cols];
for (let k = 0; k < Math.abs(to[0]! - at[0]!); k++) await host.keyboard.press(to[0]! > at[0]! ? 'ArrowDown' : 'ArrowUp');
for (let k = 0; k < Math.abs(to[1]! - at[1]!); k++) await host.keyboard.press(to[1]! > at[1]! ? 'ArrowRight' : 'ArrowLeft');
await host.keyboard.press('Space');
if (i === two[0]) {
await host.locator(`.ss-cell.sel.cur[data-i="${i}"]`).waitFor({ timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'shisen-keys-pc.png') });
}
at = to;
}
left.host -= 2;
await ssWaitTiles(host, left.host);
st.pcKey++;
}
// PC: a wrong pair shakes and says why; the tile picked last stays picked, and picking it again deselects.
{
const g = await ssGrid(host);
const i = g.cells.findIndex((k) => k);
const j = g.cells.findIndex((k) => k && k !== g.cells[i]);
await host.mouse.click(g.pos[i]!.x, g.pos[i]!.y);
await host.mouse.click(g.pos[j]!.x, g.pos[j]!.y);
await host.locator('.ss-toast', { hasText: '같은 패가 아니에요' }).waitFor({ timeout: 3000 });
await host.locator(`.ss-cell.sel[data-i="${j}"]`).waitFor({ timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'shisen-wrong-pc.png') });
await host.mouse.click(g.pos[j]!.x, g.pos[j]!.y);
await host.waitForFunction(() => !document.querySelector('.ss-cell.sel'), null, { timeout: 3000 });
}
// Phone: 💡 힌트 lights a pair; tapping those two removes them.
await guest.getByRole('button', { name: /힌트/ }).click();
await guest.waitForFunction(() => document.querySelectorAll('.ss-cell.hint').length === 2, null, { timeout: 3000 });
await guest.screenshot({ path: join(SHOTS, 'shisen-hint-phone.png') });
{
const g = await ssGrid(guest);
const lit = await guest.$$eval('.ss-cell.hint', (els) => els.map((e) => Number(e.getAttribute('data-i'))));
for (const i of lit) await ssTap(guest, g.pos[i]!.x, g.pos[i]!.y);
left.guest -= 2;
await ssWaitTiles(guest, left.guest);
st.phoneHint++;
}
// The host's progress shows on the phone and the other way round.
const hostPairs = (72 - left.host) / 2;
await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/36`)), hostPairs, { timeout: 3000 });
await host.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('친구') && li.textContent?.includes(`${n}/36`)), (72 - left.guest) / 2, { timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'shisen-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone.png') });
for (const p of pages) await p.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(300);
await host.screenshot({ path: join(SHOTS, 'shisen-mid-pc-dark.png') });
await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone-dark.png') });
for (const p of pages) await p.emulateMedia({ colorScheme: 'light' });
// The smallest phone (320 px wide): the board still fits the width.
await guest.setViewportSize({ width: 320, height: 640 });
await guest.waitForTimeout(300);
await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone-320.png') });
const b320 = await guest.locator('.ss-board').boundingBox();
if (!b320 || b320.x < 0 || b320.x + b320.width > 320) throw new Error(`320px board: ${JSON.stringify(b320)}`);
await guest.setViewportSize({ width: 390, height: 844 });
for (const p of pages) {
await p.getByRole('button', { name: '포기할래요' }).click();
await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click();
}
for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 });
await host.screenshot({ path: join(SHOTS, 'shisen-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'shisen-result-phone.png') });
console.log(` shisen: ${JSON.stringify(st)}, wrong pair shakes, hint, progress shared, both gave up → result`);
},
},
solitaire: {
// PC host + phone guest on the same Klondike deal (draw 1). Each plays real moves the computer's rules pick from their
// own screen: PC with mouse clicks (pick, drop), double-clicks (to the foundation) and the stock; the phone with CDP
// taps and double taps. 되돌리기 on PC restores the table; progress reaches the other screen; both give up → result.
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const st = await solPlay(pages, 1);
await host.screenshot({ path: join(SHOTS, 'solitaire-start-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'solitaire-start-phone.png') });
// 되돌리기 (PC): one draw, then back to the same table.
const before = await solKey(host);
await host.locator('[data-pile="s"] button').first().click();
for (let t = 0; t < 30 && (await solKey(host)) === before; t++) await host.waitForTimeout(100);
await host.getByRole('button', { name: '↶ 되돌리기' }).click();
for (let t = 0; t < 30 && (await solKey(host)) !== before; t++) await host.waitForTimeout(100);
if ((await solKey(host)) !== before) throw new Error('되돌리기 did not restore the table');
await host.locator('.rc-pill', { hasText: '↶ 1' }).waitFor({ timeout: 3000 });
const more = await solPlay(pages, 30);
for (const k of Object.keys(st) as (keyof typeof st)[]) st[k] += more[k];
// The host's progress shows on the phone.
const up = (await solRead(host)).f.reduce((n, c) => n + (c ? 'A23456789TJQK'.indexOf(c[0]!) + 1 : 0), 0);
await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/52`)), up, { timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'solitaire-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'solitaire-mid-phone.png'), fullPage: true });
for (const p of pages) await p.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(300);
await host.screenshot({ path: join(SHOTS, 'solitaire-mid-pc-dark.png') });
await guest.screenshot({ path: join(SHOTS, 'solitaire-mid-phone-dark.png') });
for (const p of pages) await p.emulateMedia({ colorScheme: 'light' });
await solGiveUp(pages);
await host.screenshot({ path: join(SHOTS, 'solitaire-result-pc.png') });
if (st.pcMove + st.pcF < 1 || st.phoneMove + st.phoneF < 1 || st.pcDraw + st.phoneDraw < 1) throw new Error(`too few moves ${JSON.stringify(st)}`);
console.log(` solitaire: ${JSON.stringify(st)}, same deal, undo, progress shared (${up}/52), both gave up → result`);
},
},
solitaireSpider: {
// 스파이더 1가지 무늬: 10 columns on the phone (≈34 px cards), a few real moves on both screens, then give up.
game: 'solitaire',
lobby: async (host) => {
await host.getByRole('group', { name: '종류' }).getByRole('button', { name: '스파이더', exact: true }).click();
await host.getByText(/스파이더 · 무늬 1가지/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const st = await solPlay(pages, 6);
await host.screenshot({ path: join(SHOTS, 'solitaire-spider-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'solitaire-spider-phone.png'), fullPage: true });
await guest.setViewportSize({ width: 320, height: 700 });
await guest.waitForTimeout(300);
await guest.screenshot({ path: join(SHOTS, 'solitaire-spider-phone-320.png'), fullPage: true });
await guest.setViewportSize({ width: 390, height: 844 });
await solGiveUp(pages);
console.log(` solitaireSpider: ${JSON.stringify(st)} → result`);
},
},
solitaireFreecell: {
// 프리셀: 8 columns all face up, free cells; a few real moves on both screens, then give up.
game: 'solitaire',
lobby: async (host) => {
await host.getByRole('group', { name: '종류' }).getByRole('button', { name: '프리셀', exact: true }).click();
await host.getByText(/프리셀 · 빈 칸 4개/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const st = await solPlay(pages, 6);
await host.screenshot({ path: join(SHOTS, 'solitaire-freecell-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'solitaire-freecell-phone.png'), fullPage: true });
await solGiveUp(pages);
console.log(` solitaireFreecell: ${JSON.stringify(st)} → result`);
},
},
sudoku: {
// PC host + phone guest on the same 쉬움 puzzle (solved from the givens on screen). PC: mouse click + keyboard (a
// clashing digit turns red and is erased with Backspace, memo mode with N, arrows to move, a pad click); phone: taps on
// cells and the pad, a hint. Progress reaches the other screen; the PC solves it all, the phone gives up → result.
lobby: async (host) => {
await host.getByRole('group', { name: '난이도' }).getByRole('button', { name: '쉬움', exact: true }).click();
await host.getByText(/숫자 38~40개/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('.sd-grid [data-i]').first().waitFor({ timeout: 10_000 });
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 });
const g0 = await sdGrid(host);
if (g0.map((c) => c.v).join('') !== (await sdGrid(guest)).map((c) => c.v).join('')) throw new Error('the two screens do not start from the same puzzle');
const sol = solve(g0.map((c) => (c.given ? Number(c.v) : 0)))!;
const blanks = g0.flatMap((c, i) => (c.given ? [] : [i]));
const st = { pcKeys: 0, pcPad: 0, phone: 0 };
// PC: click the first blank, type a digit that is already in its row → red; Backspace clears it.
const e1 = blanks[0]!;
const clash = g0.find((c, j) => c.given && Math.floor(j / 9) === Math.floor(e1 / 9))!.v;
await host.mouse.click(g0[e1]!.x, g0[e1]!.y);
await host.keyboard.press(clash);
await sdWaitCell(host, e1, clash);
await host.locator(`.sd-grid [data-i="${e1}"][data-bad="true"]`).waitFor({ timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'sudoku-clash-pc.png') });
await host.keyboard.press('Backspace');
await sdWaitCell(host, e1, '0');
// Memo mode (N): two pencil marks, then the real digit wipes them.
await host.keyboard.press('n');
await host.getByRole('button', { name: '✏️ 메모 켬' }).waitFor();
const other = (sol[e1]! % 9) + 1;
for (const d of [sol[e1]!, other]) await host.keyboard.press(String(d));
await host.waitForFunction((k) => (document.querySelector(`.sd-grid [data-i="${k}"] .sd-notes`)?.textContent ?? '').length === 2, e1, { timeout: 3000 });
await host.keyboard.press('n');
await host.keyboard.press(String(sol[e1]));
await sdWaitCell(host, e1, String(sol[e1]));
st.pcKeys++;
let at = e1;
/** PC: walk to cell `i` with the arrow keys and type its digit. */
const pcKey = async (i: number) => {
const dr = Math.floor(i / 9) - Math.floor(at / 9);
const dc = (i % 9) - (at % 9);
for (let k = 0; k < Math.abs(dr); k++) await host.keyboard.press(dr > 0 ? 'ArrowDown' : 'ArrowUp');
for (let k = 0; k < Math.abs(dc); k++) await host.keyboard.press(dc > 0 ? 'ArrowRight' : 'ArrowLeft');
at = i;
await host.keyboard.press(String(sol[i]));
await sdWaitCell(host, i, String(sol[i]));
await host.waitForTimeout(90); // under 12 moves a second
st.pcKeys++;
};
await pcKey(blanks[1]!);
// A pad click with the mouse.
const e3 = blanks[2]!;
await host.mouse.click(g0[e3]!.x, g0[e3]!.y);
at = e3;
await host.locator(`.sd-key[data-n="${sol[e3]}"]`).click();
await sdWaitCell(host, e3, String(sol[e3]));
st.pcPad++;
// Phone: tap a blank from the end, then the pad digit (touch); then a hint.
const gp = await sdGrid(guest);
for (const i of blanks.slice(-3)) {
await sdTouch(guest, gp[i]!.x, gp[i]!.y);
await sdTouchButton(guest, guest.locator(`.sd-key[data-n="${sol[i]}"]`));
await sdWaitCell(guest, i, String(sol[i]));
st.phone++;
}
await sdTouchButton(guest, guest.getByRole('button', { name: '💡 힌트' }));
await guest.getByLabel('힌트 1번').first().waitFor({ timeout: 3000 });
// Progress reaches the other screen.
const total = blanks.length;
await guest.waitForFunction(([n, t]) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/${t}`)), [3, total] as const, { timeout: 3000 });
await host.waitForFunction(([n, t]) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('친구') && li.textContent?.includes(`${n}/${t}`)), [4, total] as const, { timeout: 3000 });
await host.screenshot({ path: join(SHOTS, 'sudoku-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'sudoku-mid-phone.png') });
// Dark mode on the PC and the narrowest phone (320px): nothing spills sideways, the pad stays on screen.
await host.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(600); // colour transitions settle
await host.screenshot({ path: join(SHOTS, 'sudoku-mid-pc-dark.png') });
await host.emulateMedia({ colorScheme: 'light' });
await guest.setViewportSize({ width: 320, height: 640 });
await guest.waitForTimeout(200);
const fit = await guest.evaluate(() => ({ page: document.documentElement.scrollWidth, grid: document.querySelector('.sd-grid')!.getBoundingClientRect().right, pad: document.querySelector('.sd-key[data-n="9"]')!.getBoundingClientRect().right }));
if (fit.page > 320 || fit.grid > 320 || fit.pad > 320) throw new Error(`320px phone overflows ${JSON.stringify(fit)}`);
await guest.screenshot({ path: join(SHOTS, 'sudoku-mid-phone320.png'), fullPage: true });
await guest.setViewportSize({ width: 390, height: 844 });
// The PC fills the rest with the keyboard.
for (const i of blanks.slice(3)) await pcKey(i);
await host.getByText(/다 풀었어요!/).first().waitFor({ timeout: 5000 });
await guest.waitForFunction(() => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes('✔')), null, { timeout: 5000 });
await guest.getByRole('button', { name: '포기할래요' }).click();
await guest.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click();
for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 });
await host.screenshot({ path: join(SHOTS, 'sudoku-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'sudoku-result-phone.png'), fullPage: true });
console.log(` sudoku: ${JSON.stringify(st)}, clash red + erase, memo, hint, progress shared, PC solved, phone gave up → result`);
},
},
nonogram: {
// PC host + phone guest on the same 15×15 picture (the tightest phone layout). The answer comes from the clues on
// screen (line logic). PC: keyboard fill + X, right click X, then mouse drags solve it → the picture's name shows.
// Phone: touch drags fill rows, the ✕ mode button marks a cell; progress reaches the other screen; the phone gives up
// (twice) → 최종 순위 on both. The phone also has to fit 15×15 at 390px and stay usable at 320px.
lobby: async (host) => {
await host.getByRole('group', { name: '크기' }).getByRole('button', { name: '15×15 어려움', exact: true }).click();
await host.getByText(/15×15 어려움 · 힌트 켬/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
for (const p of pages) await p.locator('svg.ng-board g[data-i]').first().waitFor({ timeout: 10_000 });
for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 });
const a = await ngBoard(host);
const b = await ngBoard(guest);
if (a.size !== 15 || JSON.stringify(a.clues) !== JSON.stringify(b.clues)) throw new Error('the two screens do not show the same clues');
if (![...a.cells, ...b.cells].every((c) => c.m === '0')) throw new Error('boards should start empty');
const n = a.size;
const g = solveGrid(n, a.clues.slice(0, n), a.clues.slice(n));
if (!g || g.includes(-1)) throw new Error('clues on screen are not solvable by line logic');
const answer = g.map((x) => (x === 1 ? '#' : '.')).join('');
// Phone layout: 15×15 with its clues fits 390px, cells about 18–20px.
const box = (await guest.locator('svg.ng-board').boundingBox())!;
if (box.x < 0 || box.x + box.width > 390 + 0.5) throw new Error(`phone board overflows: ${JSON.stringify(box)}`);
if (b.cells[0]!.w < 17) throw new Error(`phone cells too small: ${b.cells[0]!.w}px`);
const st = { pcKey: 0, pcRight: 0, pcDrag: 0, phoneDrag: 0, phoneX: 0 };
// PC keyboard: cursor starts at the top-left cell; Space fills an answer cell of row 0, X marks an empty one.
const svg = host.locator('svg.ng-board');
await svg.focus();
const fillAt = [...answer].findIndex((ch) => ch === '#');
const xAt = [...answer].findIndex((ch, i) => ch === '.' && i > fillAt && i < n);
for (let c = 0; c < fillAt; c++) await host.keyboard.press('ArrowRight');
await host.keyboard.press('Space');
await host.locator(`svg.ng-board g[data-i="${fillAt}"][data-m="1"]`).waitFor({ timeout: 3000 });
for (let c = fillAt; c < xAt; c++) await host.keyboard.press('ArrowRight');
await host.keyboard.press('x');
await host.locator(`svg.ng-board g[data-i="${xAt}"][data-m="2"]`).waitFor({ timeout: 3000 });
st.pcKey += 2;
// PC right click: X on an empty cell of row 1.
const rx = [...answer].findIndex((ch, i) => ch === '.' && i >= n && i < 2 * n);
const hc = (await ngBoard(host)).cells;
await host.mouse.click(hc[rx]!.x, hc[rx]!.y, { button: 'right' });
await host.locator(`svg.ng-board g[data-i="${rx}"][data-m="2"]`).waitFor({ timeout: 3000 });
st.pcRight++;
// Phone: touch drags fill the first rows; the ✕ mode turns a tap into an X (and a second tap clears it).
for (let r = 0; r < 4; r++) st.phoneDrag += await ngFillRow(guest, answer, r, true);
const px = [...answer].findIndex((ch, i) => ch === '.' && i >= 5 * n);
await guest.getByRole('button', { name: '✕ 표시' }).click();
const gc = (await ngBoard(guest)).cells;
await touchTap(guest, gc[px]!.x, gc[px]!.y);
await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="2"]`).waitFor({ timeout: 3000 });
await touchTap(guest, gc[px]!.x, gc[px]!.y);
await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="0"]`).waitFor({ timeout: 3000 });
await touchTap(guest, gc[px]!.x, gc[px]!.y);
await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="2"]`).waitFor({ timeout: 3000 });
st.phoneX++;
await guest.getByRole('button', { name: '■ 채우기' }).click();
// PC drags its first rows, then each side sees the other's progress.
for (let r = 0; r < 5; r++) st.pcDrag += await ngFillRow(host, answer, r, false);
const chip = (p: Page, who: string) =>
p.evaluate((w) => [...document.querySelectorAll('.rc-others li')].find((li) => li.textContent?.includes(w))?.querySelector('b')?.textContent ?? '', who);
const hostOk = async () => Number((await host.locator('.rc-pill', { hasText: '✔' }).innerText()).match(/(\d+)\s*\//)![1]);
const want = await hostOk();
if (want < 5) throw new Error(`host should have at least 5 lines right, has ${want}`);
await guest.waitForFunction((w) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${w}/30`)), want, { timeout: 3000 });
if (!(await chip(host, '친구')).match(/^\d+\/30$/)) throw new Error('host does not see the phone progress');
await host.screenshot({ path: join(SHOTS, 'nonogram-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone.png') });
await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone-full.png'), fullPage: true });
await guest.emulateMedia({ colorScheme: 'dark' });
await guest.waitForTimeout(400);
await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone-dark.png') });
await guest.emulateMedia({ colorScheme: 'light' });
// 320px phone: still on screen and tappable.
await guest.setViewportSize({ width: 320, height: 700 });
await guest.waitForTimeout(300);
const small = (await guest.locator('svg.ng-board').boundingBox())!;
if (small.x < 0 || small.x + small.width > 320 + 0.5) throw new Error(`320px board overflows: ${JSON.stringify(small)}`);
st.phoneDrag += await ngFillRow(guest, answer, 4, true);
await guest.screenshot({ path: join(SHOTS, 'nonogram-320-phone.png') });
await guest.setViewportSize({ width: 390, height: 844 });
// PC solves the rest; the picture's name shows.
for (let r = 5; r < n; r++) st.pcDrag += await ngFillRow(host, answer, r, false);
await host.locator('.ng-title', { hasText: '다 풀었어요!' }).waitFor({ timeout: 5000 });
await host.locator('svg.ng-board .ng-color').first().waitFor();
await host.waitForTimeout(1500);
await host.screenshot({ path: join(SHOTS, 'nonogram-solved-pc.png') });
await guest.waitForFunction(() => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes('✔')), null, { timeout: 3000 });
await guest.getByRole('button', { name: '포기할래요' }).click();
await guest.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click();
for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 });
await guest.locator('.ng-title', { hasText: '정답 그림:' }).waitFor({ timeout: 5000 });
await host.screenshot({ path: join(SHOTS, 'nonogram-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'nonogram-result-phone.png'), fullPage: true });
console.log(` nonogram: ${JSON.stringify(st)}, same clues, progress shared, PC solved (${await host.locator('.ng-title').innerText()}), phone gave up → result`);
},
},
typing: {
// 2026-11-12 타자 대결, 가장 먼저 입력 · 짧은글 · 1라운드: host and phone take turns typing each sentence for real
// (keyboard, one key at a time). A wrong Enter shakes the box and keeps the text; the other side sees the "먼저 쳤어요"