사과 게임: 같은 판(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:
102
apps/server/src/rooms/apple.room.test.ts
Normal file
102
apps/server/src/rooms/apple.room.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
42
apps/web/src/games/apple/help.test.ts
Normal file
42
apps/web/src/games/apple/help.test.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const view = (s: unknown, who: string | null) => GAMES.apple!.view(s, who) as any;
|
||||
|
||||
function playing(options: Record<string, unknown> = {}) {
|
||||
const { state } = setupGame('apple', 3, options);
|
||||
state.phase = 'playing';
|
||||
return state;
|
||||
}
|
||||
|
||||
test('사과 게임: 카운트다운 / 진행 중 / 관전', () => {
|
||||
const { state: s0 } = setupGame('apple', 3, { timeLimitSec: 60 });
|
||||
const c = helpNow(view(s0, 'A'), 'A', users);
|
||||
expect(c).toContain('곧 시작해요');
|
||||
expect(c).toContain('1분');
|
||||
const s = playing();
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('딱 10');
|
||||
expect(t).toContain('빈 칸은 합에 들어가지 않아서');
|
||||
expect(t).toContain('아직 아무도');
|
||||
expect(t).toContain('스페이스');
|
||||
s.score.B = 12;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(사과 12개)');
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('지금 1등은 나(사과 12개)');
|
||||
expect(helpNow(view(s, null), null, users)).toContain('가장 많이 지운 사람이 이겨요');
|
||||
});
|
||||
|
||||
test('사과 게임: 막힘 / 나감 / 끝', () => {
|
||||
const s = playing();
|
||||
s.status.A = 'stuck';
|
||||
s.score.A = 40;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('사과 40개를 지웠어요');
|
||||
s.status.B = 'left';
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('게임에서 나갔어요');
|
||||
s.phase = 'ended';
|
||||
s.final = { endReason: 'time', ranking: [], summary: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('시간이 다 됐어요');
|
||||
});
|
||||
33
apps/web/src/games/apple/help.ts
Normal file
33
apps/web/src/games/apple/help.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/** 사과 게임 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { AppleView } from '@bg/games/apple';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const HOW = '사과 여러 개를 직사각형으로 드래그해서 숫자 합이 딱 10이 되면 손을 떼요. 그 사과들이 사라지고 사라진 개수만큼 점수를 얻어요.';
|
||||
const KEYS = '키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. Esc는 취소예요.';
|
||||
|
||||
function leaders(v: AppleView, players: Record<string, PublicUser>, me: string | null): string {
|
||||
const live = v.seats.filter((s) => s.status !== 'left');
|
||||
if (live.length < 2) return '';
|
||||
const best = Math.max(...live.map((s) => s.score));
|
||||
if (best === 0) return '아직 아무도 사과를 지우지 않았어요.';
|
||||
const top = live.filter((s) => s.score === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
|
||||
return `지금 1등은 ${top.join(', ')}(사과 ${best}개)예요.`;
|
||||
}
|
||||
|
||||
export function helpNow(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 지운 사과 개수를 볼 수 있어요.';
|
||||
const secs = v.options.timeLimitSec;
|
||||
const limit = secs % 60 === 0 ? `${secs / 60}분` : `${secs}초`;
|
||||
if (v.phase === 'countdown') return `곧 시작해요. 모두 똑같은 사과 판을 각자 풀어요. 제한 시간은 ${limit}이에요.\n${HOW}`;
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const lead = leaders(v, players, me);
|
||||
if (!mine) return `모두 똑같은 판을 각자 풀고 있어요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.${lead ? `\n${lead}` : ''}`;
|
||||
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
if (mine.status === 'stuck') {
|
||||
return `내 판에는 이제 합이 10이 되는 사과 묶음이 없어요. 사과 ${mine.score}개를 지웠어요. 시간이 끝나거나 모두 막히면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
|
||||
}
|
||||
const lines = [HOW, '빈 칸은 합에 들어가지 않아서, 사이가 비어 있어도 멀리 있는 사과끼리 묶을 수 있어요.', `지금 내 점수는 사과 ${mine.score}개예요.`];
|
||||
if (lead) lines.push(lead);
|
||||
lines.push(KEYS);
|
||||
return lines.join('\n');
|
||||
}
|
||||
600
apps/web/src/games/apple/index.tsx
Normal file
600
apps/web/src/games/apple/index.tsx
Normal file
@@ -0,0 +1,600 @@
|
||||
/** 사과 게임 화면 (docs/games/apple.md §9). */
|
||||
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
|
||||
import type { AppleOptions, AppleView, SeatView } from '@bg/games/apple';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
|
||||
const ROWS = 10;
|
||||
const COLS = 17;
|
||||
/** SVG units per cell. */
|
||||
const S = 40;
|
||||
|
||||
type Cell = [number, number];
|
||||
interface Rect {
|
||||
r0: number;
|
||||
c0: number;
|
||||
r1: number;
|
||||
c1: number;
|
||||
}
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const rectOf = (a: Cell, b: Cell): Rect => ({ r0: Math.min(a[0], b[0]), c0: Math.min(a[1], b[1]), r1: Math.max(a[0], b[0]), c1: Math.max(a[1], b[1]) });
|
||||
|
||||
/** Apples (indices) inside a rectangle and their sum. */
|
||||
function inside(cells: string, r: Rect): { sum: number; idx: number[] } {
|
||||
let sum = 0;
|
||||
const idx: number[] = [];
|
||||
for (let y = r.r0; y <= r.r1; y++) {
|
||||
for (let x = r.c0; x <= r.c1; x++) {
|
||||
const v = cells.charCodeAt(y * COLS + x) - 48;
|
||||
if (v > 0) {
|
||||
sum += v;
|
||||
idx.push(y * COLS + x);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { sum, idx };
|
||||
}
|
||||
|
||||
const clock = (ms: number) => {
|
||||
const s = Math.ceil(Math.max(0, ms) / 1000);
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
};
|
||||
const limitLabel = (sec: number) => (sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
|
||||
|
||||
/** Ranks by score (ties share), players who left last. */
|
||||
function ranked(seats: SeatView[]): (SeatView & { rank: number })[] {
|
||||
const sorted = [...seats].sort((a, b) => Number(a.status === 'left') - Number(b.status === 'left') || b.score - a.score);
|
||||
const out: (SeatView & { rank: number })[] = [];
|
||||
sorted.forEach((s, i) => {
|
||||
const prev = out[i - 1];
|
||||
const tie = prev && prev.score === s.score && (prev.status === 'left') === (s.status === 'left');
|
||||
out.push({ ...s, rank: tie ? prev.rank : i + 1 });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.ap { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
|
||||
.ap-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.ap-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; font-size: 1rem; white-space: nowrap; }
|
||||
.ap-pill b { font-size: 1.2rem; }
|
||||
.ap-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
.ap-pill.sum { min-width: 104px; justify-content: center; border: 2px solid transparent; }
|
||||
.ap-pill.sum[data-s='ok'] { background: var(--success-soft); color: var(--success); border-color: var(--success); }
|
||||
.ap-pill.sum[data-s='over'] { background: var(--danger-soft); color: var(--danger); }
|
||||
.ap-pill.sum[data-s='idle'] { color: var(--text-sub); }
|
||||
.ap-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
|
||||
.ap-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; }
|
||||
.ap-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ap-others li b { font-variant-numeric: tabular-nums; }
|
||||
.ap-others li[data-me='true'] { background: var(--primary-soft); }
|
||||
.ap-others li[data-out='true'] { opacity: .55; }
|
||||
.ap-wrap { position: relative; width: min(100%, 980px, calc((100vh - var(--site-h) - 250px) * 1.7)); min-width: 280px; }
|
||||
.ap-wrap[data-phone='true'] { width: min(100%, 480px, max(280px, calc((100svh - 235px) / 1.7))); }
|
||||
.ap-board { display: block; width: 100%; height: auto; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
|
||||
border-radius: 14px; background: #fff8e7; box-shadow: var(--shadow), inset 0 0 0 3px #e9c98a; cursor: crosshair; outline: none; }
|
||||
.ap-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ap-board[data-off='true'] { cursor: default; }
|
||||
:root[data-theme='dark'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; } }
|
||||
.ap-pop { animation: ap-pop .42s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
|
||||
.ap-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
|
||||
border-radius: 14px; text-align: center; padding: 12px; }
|
||||
.ap-over.count { background: rgba(0,0,0,.35); color: #fff; font-size: 5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
|
||||
.ap-over.count small { font-size: 1.05rem; font-weight: 800; }
|
||||
.ap-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
|
||||
.ap-flash { position: absolute; left: 50%; top: 8px; transform: translateX(-50%); z-index: 3; pointer-events: none; border-radius: 999px; padding: 4px 14px;
|
||||
font-weight: 900; font-size: 1.05rem; background: var(--surface); box-shadow: 0 4px 14px rgba(0,0,0,.25); animation: ap-flash .9s ease forwards; }
|
||||
.ap-flash.ok { color: var(--success); border: 3px solid var(--success); }
|
||||
.ap-flash.bad { color: var(--text-sub); border: 3px solid var(--border); }
|
||||
.ap-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
|
||||
@keyframes ap-pop { 0% { transform: scale(1); opacity: 1; } 40% { transform: scale(1.25); opacity: .9; } 100% { transform: scale(.2) translateY(-30px); opacity: 0; } }
|
||||
@keyframes ap-flash { 0% { opacity: 0; transform: translateX(-50%) scale(.8); } 15% { opacity: 1; transform: translateX(-50%) scale(1.05); } 70% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ap-pop { animation-duration: .01s; } .ap-flash { animation: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- art
|
||||
|
||||
/** The apple shape in a 40×40 cell (number drawn on top). */
|
||||
function AppleDefs() {
|
||||
return (
|
||||
<defs>
|
||||
<radialGradient id="ap-grad" cx="35%" cy="35%" r="70%">
|
||||
<stop offset="0%" stopColor="#ff6b6b" />
|
||||
<stop offset="55%" stopColor="#e11d2e" />
|
||||
<stop offset="100%" stopColor="#a3111f" />
|
||||
</radialGradient>
|
||||
<g id="ap-apple">
|
||||
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
|
||||
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="url(#ap-grad)" stroke="#8f1020" strokeWidth="1.2" />
|
||||
<ellipse cx="12.5" cy="17" rx="3" ry="5" fill="#fff" opacity=".32" />
|
||||
</g>
|
||||
</defs>
|
||||
);
|
||||
}
|
||||
|
||||
function AppleCell({ x, y, n }: { x: number; y: number; n: number }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`}>
|
||||
<use href="#ap-apple" />
|
||||
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff" stroke="#6b0b16" strokeWidth="0.8" paintOrder="stroke">
|
||||
{n}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small stand-alone apple for the rules and options (own defs). */
|
||||
function AppleIcon({ n, size = 34 }: { n: number; size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
|
||||
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
|
||||
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="#e11d2e" stroke="#8f1020" strokeWidth="1.2" />
|
||||
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff">
|
||||
{n}
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function useNarrow(): boolean {
|
||||
const q = '(max-width: 640px)';
|
||||
const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia(q);
|
||||
const on = () => setM(mq.matches);
|
||||
mq.addEventListener('change', on);
|
||||
return () => mq.removeEventListener('change', on);
|
||||
}, []);
|
||||
return m;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
interface Pop {
|
||||
key: number;
|
||||
cells: { i: number; n: number }[];
|
||||
}
|
||||
|
||||
function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
|
||||
const now = useServerNow(200);
|
||||
const phone = useNarrow();
|
||||
const [drag, setDrag] = useState<{ a: Cell; b: Cell } | null>(null);
|
||||
const [cursor, setCursor] = useState<Cell>([0, 0]);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [gone, setGone] = useState<number[]>([]);
|
||||
const [pops, setPops] = useState<Pop[]>([]);
|
||||
const [flash, setFlash] = useState<{ key: number; ok: boolean; text: string } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const dragRef = useRef(drag);
|
||||
dragRef.current = drag;
|
||||
const seq = useRef(0);
|
||||
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const canPlay = !!mine && mine.status === 'playing' && v.phase === 'playing' && !!v.cells && now < v.endsAt;
|
||||
|
||||
// My board as I see it: the server's, minus the apples I just cleared and the server has not confirmed yet.
|
||||
const cells = useMemo(() => {
|
||||
if (!v.cells) return null;
|
||||
if (!gone.length) return v.cells;
|
||||
const a = v.cells.split('');
|
||||
for (const i of gone) a[i] = '0';
|
||||
return a.join('');
|
||||
}, [v.cells, gone]);
|
||||
|
||||
useEffect(() => {
|
||||
setGone((g) => (g.length ? g.filter((i) => v.cells?.[i] !== '0' && v.cells !== null) : g));
|
||||
}, [v.cells]);
|
||||
// A refused select (too fast, time over): show the apples again.
|
||||
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setGone([])), []);
|
||||
useEffect(() => {
|
||||
if (!canPlay) setDrag(null);
|
||||
}, [canPlay]);
|
||||
useEffect(() => {
|
||||
if (!pops.length) return;
|
||||
const t = setTimeout(() => setPops((p) => p.slice(1)), 450);
|
||||
return () => clearTimeout(t);
|
||||
}, [pops]);
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), 900);
|
||||
return () => clearTimeout(t);
|
||||
}, [flash]);
|
||||
|
||||
const dR = phone ? COLS : ROWS;
|
||||
const dC = phone ? ROWS : COLS;
|
||||
const toDisp = (c: Cell): Cell => (phone ? [c[1], ROWS - 1 - c[0]] : c);
|
||||
const toCanon = (dr: number, dc: number): Cell => (phone ? [ROWS - 1 - dc, dr] : [dr, dc]);
|
||||
|
||||
const cellAt = (e: { clientX: number; clientY: number }): Cell => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1);
|
||||
const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1);
|
||||
return toCanon(dr, dc);
|
||||
};
|
||||
|
||||
const sel = drag && cells ? inside(cells, rectOf(drag.a, drag.b)) : null;
|
||||
const say = (t: string) => setAnnounce(t);
|
||||
|
||||
const finish = (a: Cell, b: Cell, fromKey: boolean) => {
|
||||
if (!cells || !canPlay) return;
|
||||
const rect = rectOf(a, b);
|
||||
const { sum, idx } = inside(cells, rect);
|
||||
if (idx.length === 0) {
|
||||
if (fromKey) say('고른 칸에 사과가 없어요.');
|
||||
return;
|
||||
}
|
||||
if (sum !== 10) {
|
||||
if (idx.length >= 2 || fromKey) {
|
||||
setFlash({ key: ++seq.current, ok: false, text: `합 ${sum} · 10이 아니에요` });
|
||||
say(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
setGone((g) => [...g, ...idx]);
|
||||
setPops((p) => [...p, { key: ++seq.current, cells: idx.map((i) => ({ i, n: cells.charCodeAt(i) - 48 })) }]);
|
||||
setFlash({ key: ++seq.current, ok: true, text: `+${idx.length}` });
|
||||
sounds.stone();
|
||||
haptic(15);
|
||||
act({ type: 'select', ...rect });
|
||||
say(`사과 ${idx.length}개를 지웠어요.`);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!canPlay || (e.pointerType === 'mouse' && e.button !== 0)) return;
|
||||
e.preventDefault();
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
const c = cellAt(e);
|
||||
setDrag({ a: c, b: c });
|
||||
setCursor(c);
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const c = cellAt(e);
|
||||
if (c[0] !== d.b[0] || c[1] !== d.b[1]) setDrag({ a: d.a, b: c });
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const c = cellAt(e);
|
||||
setDrag(null);
|
||||
setCursor(c);
|
||||
finish(d.a, c, false);
|
||||
};
|
||||
|
||||
const describe = (c: Cell) => {
|
||||
const [dr, dc] = toDisp(c);
|
||||
const n = cells ? cells.charCodeAt(c[0] * COLS + c[1]) - 48 : 0;
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${n > 0 ? `사과 ${n}` : '빈 칸'}`;
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, Cell> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const [dr, dc] = toDisp(cursor);
|
||||
const next = toCanon(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
if (drag) {
|
||||
setDrag({ a: drag.a, b: next });
|
||||
const s = cells ? inside(cells, rectOf(drag.a, next)).sum : 0;
|
||||
say(`${describe(next)}. 고른 합 ${s}${s === 10 ? ', 지금 누르면 지워져요' : ''}`);
|
||||
} else say(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!canPlay || e.repeat) return;
|
||||
if (!drag) {
|
||||
setDrag({ a: cursor, b: cursor });
|
||||
say('시작점을 정했어요. 화살표로 끝점까지 옮긴 뒤 다시 눌러요.');
|
||||
} else {
|
||||
setDrag(null);
|
||||
finish(drag.a, cursor, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Escape' && drag) {
|
||||
e.preventDefault();
|
||||
setDrag(null);
|
||||
say('고르기를 취소했어요.');
|
||||
}
|
||||
};
|
||||
|
||||
const left = Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
|
||||
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
const sumState = !sel || sel.idx.length === 0 ? 'idle' : sel.sum === 10 ? 'ok' : sel.sum > 10 ? 'over' : 'under';
|
||||
const others = ranked(v.seats);
|
||||
|
||||
// Selection rectangle in display coordinates.
|
||||
let selBox: ReactNode = null;
|
||||
if (drag) {
|
||||
const [ar, ac] = toDisp(drag.a);
|
||||
const [br, bc] = toDisp(drag.b);
|
||||
const color = sumState === 'ok' ? '#16a34a' : sumState === 'over' ? '#dc2626' : '#2563eb';
|
||||
const fill = sumState === 'ok' ? 'rgba(22,163,74,.28)' : sumState === 'over' ? 'rgba(220,38,38,.16)' : 'rgba(37,99,235,.16)';
|
||||
selBox = (
|
||||
<rect
|
||||
x={Math.min(ac, bc) * S + 1.5}
|
||||
y={Math.min(ar, br) * S + 1.5}
|
||||
width={(Math.abs(ac - bc) + 1) * S - 3}
|
||||
height={(Math.abs(ar - br) + 1) * S - 3}
|
||||
rx={7}
|
||||
fill={fill}
|
||||
stroke={color}
|
||||
strokeWidth={3}
|
||||
pointerEvents="none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
const [cr, cc] = toDisp(cursor);
|
||||
|
||||
return (
|
||||
<div className="ap">
|
||||
<style>{CSS}</style>
|
||||
<div className="ap-top">
|
||||
<span className={`ap-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
|
||||
⏱ {clock(left)}
|
||||
</span>
|
||||
{mine && (
|
||||
<span className="ap-pill" aria-label={`내 점수 사과 ${mine.score}개`}>
|
||||
🍎 <b>{mine.score}</b>
|
||||
</span>
|
||||
)}
|
||||
{mine && v.phase !== 'ended' && (
|
||||
<span className="ap-pill sum" data-s={sumState} aria-hidden>
|
||||
합 {sel && sel.idx.length ? sel.sum : '-'} / 10
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{v.seats.length > 1 && (
|
||||
<ol className="ap-others" aria-label="점수">
|
||||
{others.map((s) => (
|
||||
<li key={s.id} data-me={s.id === me} data-out={s.status === 'left'} aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''} 사과 ${s.score}개${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}>
|
||||
<Avatar user={userOf(players, s.id)} size={20} />
|
||||
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<b>{s.score}</b>
|
||||
{s.status === 'stuck' && <span aria-hidden>✔</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
<div className="ap-wrap" data-phone={phone}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ap-board"
|
||||
data-off={!canPlay}
|
||||
viewBox={`0 0 ${dC * S} ${dR * S}`}
|
||||
role="application"
|
||||
aria-roledescription="사과 판"
|
||||
aria-label={
|
||||
canPlay
|
||||
? `사과 판 ${dR}줄 ${dC}칸. 화살표로 칸을 옮기고 스페이스나 Enter로 시작점과 끝점을 정해요. 지금 ${describe(cursor)}`
|
||||
: '사과 판'
|
||||
}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => setDrag(null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<AppleDefs />
|
||||
{cells &&
|
||||
Array.from(cells, (ch, i) => {
|
||||
const n = ch.charCodeAt(0) - 48;
|
||||
if (n <= 0) return null;
|
||||
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
|
||||
return <AppleCell key={i} x={dc * S} y={dr * S} n={n} />;
|
||||
})}
|
||||
{pops.map((p) =>
|
||||
p.cells.map(({ i, n }) => {
|
||||
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
|
||||
return (
|
||||
<g key={`${p.key}-${i}`} className="ap-pop">
|
||||
<AppleCell x={dc * S} y={dr * S} n={n} />
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
{selBox}
|
||||
{focused && canPlay && <rect x={cc * S + 2} y={cr * S + 2} width={S - 4} height={S - 4} rx={8} fill="none" stroke="#f59e0b" strokeWidth={3} strokeDasharray="5 3" pointerEvents="none" />}
|
||||
</svg>
|
||||
{flash && (
|
||||
<div key={flash.key} className={`ap-flash ${flash.ok ? 'ok' : 'bad'}`} aria-hidden>
|
||||
{flash.text}
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="ap-over count" aria-hidden>
|
||||
{countdown}
|
||||
<small>합이 10이 되게 사과를 묶어요!</small>
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
|
||||
<div className="ap-over note" role="status">
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개 · 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
|
||||
</div>
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="ap-keys">마우스로 드래그해서 합이 10이면 손을 떼요 · 키보드: 화살표 + 스페이스(시작점·끝점), Esc 취소</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
|
||||
const rows = ranked(v.seats);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>사과 게임{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
|
||||
<span className="small muted">17×10 판 · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rows.map((s) => (
|
||||
<li
|
||||
key={s.id}
|
||||
className="row"
|
||||
style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}
|
||||
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, 사과 ${s.score}개, ${s.clears}번 지움${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}
|
||||
>
|
||||
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
|
||||
{s.rank}등
|
||||
</span>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }} aria-hidden>
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'left' ? ' · 나감' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
|
||||
🍎 {s.score}
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: AppleView, me: string | null): boolean {
|
||||
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
|
||||
}
|
||||
|
||||
function statusText(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return '곧 시작해요! 합이 10이 되게 사과를 드래그해요';
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!mine) {
|
||||
const top = ranked(v.seats)[0];
|
||||
return top && top.score > 0 ? `${nick(players, top.id)}님이 사과 ${top.score}개로 앞서요` : '모두 같은 판을 풀고 있어요';
|
||||
}
|
||||
if (mine.status === 'left') return '게임에서 나갔어요';
|
||||
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개 · 끝날 때까지 기다려요`;
|
||||
return `사과 ${mine.score}개 지웠어요 · 합이 10이 되게 드래그!`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<AppleOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>제한 시간</strong>
|
||||
<Seg
|
||||
label="제한 시간"
|
||||
value={o.timeLimitSec}
|
||||
options={[
|
||||
[60, '1분'],
|
||||
[120, '2분'],
|
||||
[180, '3분'],
|
||||
]}
|
||||
onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec })}
|
||||
/>
|
||||
<span className="small muted">원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: AppleOptions): string {
|
||||
return `제한 시간 ${limitLabel(o.timeLimitSec)} · 17×10 판`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules({ options }: { options?: AppleOptions }) {
|
||||
const limit = limitLabel(options?.timeLimitSec ?? 120);
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
가로 17칸, 세로 10줄 판에 1부터 9까지 숫자가 적힌 사과 170개가 가득 놓여 있어요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<AppleIcon n={3} />
|
||||
<AppleIcon n={4} />
|
||||
<AppleIcon n={3} />
|
||||
<span>= 10 → 사과 3개가 사라지고 3점!</span>
|
||||
</div>
|
||||
<p>
|
||||
사과들을 <strong>직사각형으로 드래그</strong>해서 그 안의 숫자 합이 <strong>딱 10</strong>이면 손을 뗐을 때 사과가 사라지고, 사라진 개수만큼 점수를 얻어요. 합이 10이 아니면 아무 일도
|
||||
일어나지 않고 벌칙도 없어요. 지운 자리는 빈 칸이 되고 빈 칸은 합에 들어가지 않아서, 사이가 비면 멀리 있는 사과끼리도 묶을 수 있어요.
|
||||
</p>
|
||||
<p>
|
||||
제한 시간은 {limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<p>
|
||||
휴대폰에서는 판을 세로로 돌려서 보여 줘요. 키보드로는 화살표로 칸을 옮기고 <strong>스페이스</strong>(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. <strong>Esc</strong>는 취소예요.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<AppleView, AppleOptions> = {
|
||||
Board: AppleBoard,
|
||||
Side: AppleSide,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
81
apps/web/src/games/apple/quick.tsx
Normal file
81
apps/web/src/games/apple/quick.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
/** 사과 게임 30초 규칙 요약 (docs/07 §5). Simple redraws of the board apples. */
|
||||
import type { ReactNode } from 'react';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** One apple with its number, centred at (x, y), about 26 units wide. */
|
||||
function Apple({ x, y, n, dim = false }: { x: number; y: number; n: number; dim?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} opacity={dim ? 0.3 : 1}>
|
||||
<path d="M0 -11 C1 -15 3 -17 5 -18" stroke="#78350f" strokeWidth={2} fill="none" strokeLinecap="round" />
|
||||
<ellipse cx={5} cy={-15} rx={4.5} ry={2.2} fill="#16a34a" transform="rotate(-25 5 -15)" />
|
||||
<circle cx={0} cy={2} r={12} fill="#dc2626" stroke="#991b1b" strokeWidth={1.5} />
|
||||
<text x={0} y={7.5} textAnchor="middle" fontSize={15} fontWeight={900} fill="#fff">
|
||||
{n}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Frame({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<svg viewBox="0 0 240 150" width={240} height={150} aria-hidden>
|
||||
<rect x={0} y={0} width={240} height={150} rx={14} fill="#fef3c7" />
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
const ROW1 = [3, 7, 5, 2, 8, 1, 6];
|
||||
const ROW2 = [4, 1, 5, 9, 2, 2, 6];
|
||||
const ROW3 = [6, 2, 8, 1, 3, 9, 4];
|
||||
|
||||
function Grid({ gone = [] as number[] }) {
|
||||
return (
|
||||
<>
|
||||
{[ROW1, ROW2, ROW3].map((row, r) =>
|
||||
row.map((n, c) => <Apple key={`${r}-${c}`} x={30 + c * 30} y={36 + r * 38} n={n} dim={gone.includes(r * 7 + c)} />),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid />
|
||||
</Frame>
|
||||
),
|
||||
alt: '숫자 1부터 9가 적힌 빨간 사과가 줄지어 놓인 판이에요',
|
||||
title: '모두 같은 판을 풀어요',
|
||||
text: '숫자가 적힌 사과 판이 나와요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid />
|
||||
<rect x={14} y={18} width={62} height={36} rx={6} fill="rgba(22,163,74,.25)" stroke="#16a34a" strokeWidth={3} />
|
||||
<text x={200} y={140} textAnchor="middle" fontSize={16} fontWeight={900} fill="#15803d">
|
||||
3+7=10!
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '3과 7이 적힌 사과 두 개를 초록 네모로 묶은 모습이에요. 합이 10이에요',
|
||||
title: '합이 10이면 사라져요',
|
||||
text: '사과를 직사각형으로 드래그해서 숫자 합이 딱 10이면 손을 떼요. 사과가 사라지고 개수만큼 점수예요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Grid gone={[0, 1, 7, 14, 2, 9]} />
|
||||
<rect x={150} y={8} width={82} height={26} rx={13} fill="#1f2937" />
|
||||
<text x={191} y={26} textAnchor="middle" fontSize={15} fontWeight={800} fill="#fff">
|
||||
⏱ 1:42
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '몇 개의 사과가 지워져 흐려졌고, 오른쪽 위에 남은 시간 1분 42초가 보여요',
|
||||
title: '2분 동안 많이 지우기',
|
||||
text: '빈 칸은 합에 안 들어가요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(26);
|
||||
expect(IDS).toHaveLength(27);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -28,6 +28,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
dobble: () => import('./dobble'),
|
||||
catchmind: () => import('./catchmind'),
|
||||
mafia: () => import('./mafia'),
|
||||
apple: () => import('./apple'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
@@ -25,6 +25,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
dobble: '👀',
|
||||
catchmind: '🖍️',
|
||||
mafia: '🌙',
|
||||
apple: '🍎',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -34,5 +35,5 @@ export const UPCOMING: string[] = [];
|
||||
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'mahjong', 'rummikub', 'davinci-code'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] },
|
||||
];
|
||||
|
||||
@@ -135,7 +135,7 @@ export interface GameUI<V> {
|
||||
## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12)
|
||||
- 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단).
|
||||
- `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편(§9.1)과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아·사과 게임): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임(사과 게임은 각자 자기 판을 푸는 경주). 전략은 `({ me, view, now, persona, level, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편(§9.1)과 빠르기, `level`은 지금 레벨(1~60), `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다.
|
||||
|
||||
### 9.1 컴퓨터 난이도와 난수 (2026-10-11)
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
| `dobble` | 도블(같은 그림 찾기) | 2~8 | M8 |
|
||||
| `catchmind` | 그림 맞히기 | 2~10 | M8 |
|
||||
| `mafia` | 마피아 | 4~12 | M8 |
|
||||
| `apple` | 사과 게임(합 10 만들기, 같은 판 경주) | 1~8 | M9 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
121
docs/games/apple.md
Normal file
121
docs/games/apple.md
Normal file
@@ -0,0 +1,121 @@
|
||||
# 사과 게임 (`apple`)
|
||||
|
||||
> 마일스톤: M9 · 인원: 최소 1 ~ 최대 8명 · 예상 시간: 약 1~3분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 웹에서 유행한 "사과 게임"(원작 Fruit Box, 일본 플래시 게임). 17×10 칸에 1~9가 적힌 사과가 가득하고, 마우스로 직사각형을 그어 그 안의 숫자 합이 **딱 10**이면 사과가 사라진다. 2분 동안 많이 지울수록 높은 점수.
|
||||
- 원작은 혼자 하는 점수 도전이다. 우리 사이트에서는 **모두 같은 판(같은 시드)** 을 각자 따로 동시에 풀고, 시간이 끝났을 때 점수로 순위를 매기는 "경주"로 만든다. 혼자서도 할 수 있다(요트 다이스처럼 1명 허용).
|
||||
- 인원 근거: 원작 1인. 판이 사람마다 따로라 인원 제한은 화면(점수 목록) 크기 때문이며, 다른 실시간 게임(도블)과 같은 최대 8명으로 정했다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `timeLimitSec` | 제한 시간 | 60(1분) / 120(2분) / 180(3분) | 120 (원작) |
|
||||
|
||||
- 판 크기는 원작의 17×10으로 **고정**한다(단순하게). 휴대폰에서는 판을 돌려서 보여 주므로 작은 판 옵션은 넣지 않았다.
|
||||
|
||||
## 3. 구성물
|
||||
- 가로 17칸 × 세로 10줄, 사과 170개. 사과마다 1~9 숫자.
|
||||
|
||||
## 4. 준비(셋업)
|
||||
1. 시드 RNG로 170칸에 1~9를 고르게 뽑는다.
|
||||
2. 원작처럼 **전체 합이 10의 배수**가 되게, 합이 맞을 때까지 RNG로 고른 칸 하나를 다시 뽑는다(결정적).
|
||||
3. 모든 사람에게 같은 판을 복사해 준다. 자리 순서는 입장 순서 그대로(턴이 없으니 의미 없음).
|
||||
4. 3초 카운트다운 뒤 동시에 시작. 카운트다운 동안에는 판을 보여 주지 않는다(먼저 보는 사람이 없게).
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 턴이 없다. 시작 후 마감 전까지 누구나 언제든 자기 판에서 직사각형을 고를 수 있다.
|
||||
- 직사각형 = 두 꼭짓점 칸(어느 순서든). 그 안의 **사과 숫자 합이 정확히 10**이면 안의 사과가 모두 사라지고, 사라진 개수만큼 점수.
|
||||
- 지운 자리는 빈 칸. **빈 칸은 합에 영향이 없다** → 사이가 비면 멀리 떨어진 사과끼리도 묶을 수 있다.
|
||||
- 직사각형 안에 사과가 0개면 무효.
|
||||
- 합이 10이 아니면 **아무 일도 없다(벌점 없음)**. 서버는 그 행동을 거절하고(`합이 N이에요…`), 화면은 손을 뗄 때 합이 10이 아니면 아예 보내지 않고 "합 N · 10이 아니에요"만 잠깐 보여 준다.
|
||||
- 내 판에 합 10 묶음이 더 없으면 "막힘"(`stuck`): 더 고를 수 없고 시간이 끝날 때까지 기다린다. 모두 막히면(혹은 남은 사람이 전부 막히면) 시간 전에 끝난다(원작에는 없음, 혼자 할 때 기다리지 않게).
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
- 점수 = 지운 사과 개수(= 내 판의 빈 칸 수).
|
||||
- 순위: 점수 높은 순, **같은 점수는 같은 순위**. 중간에 나간 사람은 남은 사람 모두보다 아래(그 안에서도 점수 순).
|
||||
- 결과 화면 점수 문구: `사과 N개`. `GameResult.scores` = 지운 개수.
|
||||
|
||||
## 7. 지역 룰 / 하우스 룰
|
||||
- 없음. 원작 변형(작은 판, 시간 보너스, 연쇄 점수 등)은 넣지 않았다.
|
||||
|
||||
## 8. 엔진 설계
|
||||
### 8.1 상태(State)
|
||||
```ts
|
||||
interface AppleState {
|
||||
options: { timeLimitSec: 60 | 120 | 180 };
|
||||
order: PlayerId[];
|
||||
initial: string; // 170자 '1'..'9' (행 우선), 공용 시작 판
|
||||
boards: Record<PlayerId, string>; // 각자 판, 지운 칸은 '0'
|
||||
score: Record<PlayerId, number>;
|
||||
clears: Record<PlayerId, number>; // 지운 횟수
|
||||
status: Record<PlayerId, 'playing' | 'stuck' | 'left'>;
|
||||
recent: Record<PlayerId, number[]>; // 최근 고르기 서버 시각(속도 제한)
|
||||
phase: 'countdown' | 'playing' | 'ended';
|
||||
countdownEndsAt: number;
|
||||
endsAt: number; // countdownEndsAt + timeLimitSec
|
||||
final: AppleFinal | null;
|
||||
}
|
||||
```
|
||||
판을 숫자 배열이 아닌 170자 문자열로 둬서 상태·view가 작다.
|
||||
|
||||
### 8.2 액션
|
||||
| type | payload | 누가 / 언제 | 검증 조건 |
|
||||
|---|---|---|---|
|
||||
| `select` | `r0, c0, r1, c1` (행 0~9, 열 0~16, 정수) | 게임 중인 사람, 카운트다운 끝 ~ 마감 전 | 나가지 않음, 막히지 않음, 1초에 5번 이하, 안에 사과 1개 이상, 합 = 10 |
|
||||
| `tick` | — | 서버 타이머 전용(스키마에 없음) | — |
|
||||
| `leave` | — | 서버(나가기) 전용 | 아직 게임 중 |
|
||||
|
||||
- 카운트다운이 끝났는데 방 타이머가 아직 안 돌았어도(`now ≥ countdownEndsAt`) `select`는 받는다. `apply`가 먼저 단계를 시계에 맞춘다(`catchUp`: 카운트다운 → 진행 → 마감).
|
||||
- 속도 제한: 그림 맞히기와 같은 방식(`recent` 최근 5개, `ctx.now` 기준 1초). 사람은 1초에 2~3번이 한계라 정상 플레이에는 걸리지 않는다. 클라이언트가 보낸 고르기만 막고, 서버 판정은 언제나 서버 판 기준.
|
||||
|
||||
### 8.3 공개/비공개 정보 (view)
|
||||
- 내 view: 내 판(`cells`, 170자) + 모든 사람의 점수·지운 횟수·상태 + 시간. **다른 사람 판은 보내지 않는다**(같은 판이라 숨길 정보는 없지만 view를 작게, 남의 진행 모양을 엿보지 않게).
|
||||
- 관전자: 판 없이 점수만.
|
||||
- 카운트다운 동안에는 누구에게도 판을 보내지 않는다(`secretsOf` = 카운트다운 중 `initial`).
|
||||
|
||||
### 8.4 랜덤 요소
|
||||
- `setup`의 판 생성만(`ctx.rng`). 모두 같은 판이라 운의 차이가 없다. 컴퓨터 운(셔플 여러 번 중 고르기)도 적용하지 않는다(턴 게임 전략에만 적용, `luckApplies`).
|
||||
|
||||
### 8.5 타이머·시간 초과·연결 끊김
|
||||
- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절.
|
||||
- `timeoutPlayers`: 게임 중인 모두(막힌 사람 포함).
|
||||
- `timeoutNotBefore` = `deadline`: 연결이 끊긴 사람도 **일찍 시간 초과되지 않는다**(할 행동이 없음). 그 사람 점수는 그대로 남고 마감 때 순위에 들어간다.
|
||||
- 나가기: `leave` → 상태 `left`, 더는 못 고름. 여러 명으로 시작했는데 남은 사람이 1명이면 그 사람이 이긴 것으로 바로 끝, 아무도 안 남으면 끝.
|
||||
|
||||
### 8.6 종료 조건과 결과
|
||||
- `time`: 마감. `cleared`: 남은 사람이 모두 막힘. `left`: 혼자 남음/모두 나감.
|
||||
- 요약: 여러 명 `시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요`(+ `공동 1등 N명`), 혼자 `시간이 다 됐어요. 사과 N개를 지웠어요`.
|
||||
|
||||
## 9. UI/UX
|
||||
- PC: 판(17×10, 화면 높이에 맞춰 최대 약 980px) 위에 남은 시간·내 점수·"합 N / 10" 표시, 그 아래 다른 사람 점수 칩(실시간, 순위순). 오른쪽 패널에 순위표.
|
||||
- 휴대폰(폭 640px 이하): 판을 시계 방향 90도로 돌려 **10열 × 17줄**로 보여 준다. 폭 390px에서 칸 약 35px, 320px에서도 최소 28px(판 최소 폭 280px).
|
||||
- 조작: 포인터 이벤트(마우스·터치·펜 공통). 누른 칸 ~ 지금 칸이 직사각형. 드래그 중 합계를 실시간 표시, 합이 10이면 초록, 넘으면 빨강, 모자라면 파랑. 손을 떼서 10이면 바로 지운 것처럼 보이고(낙관적 표시, 서버가 거절하면 되돌림) 사과가 튀어 오르며 사라진다. 판에는 `touch-action: none`(드래그 중 스크롤 안 됨).
|
||||
- 키보드: 판에 포커스 → 화살표로 칸 이동(점선 커서), 스페이스/Enter로 시작점, 한 번 더 눌러 끝점(합 10이면 지움), Esc 취소. 스크린리더는 칸 위치·숫자·지금 합을 aria-live로 읽어 준다.
|
||||
- 사과 그림은 SVG(이미지 파일 없음). 다크 모드에서는 판 바탕만 어두운 나무색.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 판: 170칸 1~9, 합 10의 배수, 같은 시드 = 같은 판, 모두 같은 판으로 시작
|
||||
- [x] `findMoves`(가장 좁은 합 10 직사각형 전부) = 무차별 계산과 같음, 빈 칸 너머 묶음 포함
|
||||
- [x] 카운트다운 중 판 숨김·고르기 거절, 카운트다운 끝 직후(타이머 전) 고르기 인정
|
||||
- [x] 합 10 → 지우고 개수만큼 점수, 모서리 순서 무관, 빈 칸은 합에 영향 없음, 사과 0개·합≠10 거절
|
||||
- [x] 속도 제한(1초 5번), 마감 뒤 거절, 마감 tick으로 끝, 동점 같은 순위
|
||||
- [x] 혼자 하기 요약, 막힘 → 모두 막히면 조기 종료, 나가기 → 혼자 남으면 끝·나간 사람 맨 아래
|
||||
- [x] 엔진 `randomPlayout`(유출·JSON·결정성) 1·2·5·8명
|
||||
- [x] 방 통합: 연습방에서 사람 + 컴퓨터가 끝까지(서버 시계), 합≠10 거절, 끊긴 사람 조기 시간 초과 없음
|
||||
- [x] E2E: PC 마우스 드래그 + 키보드, 휴대폰 실제 터치(CDP) 드래그, 돌린 판 = 같은 판, 상대 점수 반영, 1분 뒤 결과까지
|
||||
|
||||
## 11. 참고 자료
|
||||
- 원작: Fruit Box (フルーツボックス), 2분 · 17×10 · 합 10 규칙.
|
||||
|
||||
## 12. 메모
|
||||
- 원작 이름 대신 한국에서 통하는 "사과 게임"으로 표시.
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 실시간 게임이라 원래는 컴퓨터를 넣지 않았지만(도블·할리갈리), 이 게임은 **각자 자기 판을 푸는 경주**라 컴퓨터가 남의 판을 방해하거나 반응 속도로 이길 수 없다. 그래서 마피아처럼 **live 전략**(`LIVE_BOT_STRATEGIES.apple`)으로 넣었다: 서버가 컴퓨터마다 자기 타이머로 계속 물어보고, 컴퓨터는 자기 view(자기 판)만 본다.
|
||||
- 레벨(1~60, live 전략에도 `level` 전달)에 따라:
|
||||
- 찾는 시간: 레벨 1 평균 약 6초 → 레벨 60 약 2초(±40% 흔들림, 컴퓨터마다 빠르기 `pace`가 조금씩 다름).
|
||||
- 시야: 약한 컴퓨터는 붙어 있는 작은 묶음 위주로 보고, 강할수록 넓은 직사각형까지 본다.
|
||||
- 놓침: 레벨 1은 약 30% 확률로 한 번 볼 때 못 찾고 그냥 지나감, 레벨 60은 0%.
|
||||
- 고르기: 강할수록 사과가 많은 묶음을 우선(점수), 약하면 보이는 것 중 아무거나.
|
||||
- 같은 판 10번 평균(2분): 레벨 1 약 28개, 20 약 57, 30 약 70, 40 약 84, 60 약 99개. 잘하는 사람(100개 안팎)과 비슷한 수준이 최고.
|
||||
182
e2e/games.e2e.ts
182
e2e/games.e2e.ts
@@ -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);
|
||||
|
||||
247
packages/games/src/apple/apple.test.ts
Normal file
247
packages/games/src/apple/apple.test.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
|
||||
import {
|
||||
CELLS,
|
||||
COLS,
|
||||
COUNTDOWN_MS,
|
||||
ROWS,
|
||||
SELECTS_PER_SEC,
|
||||
apple,
|
||||
findMoves,
|
||||
hasMove,
|
||||
makeBoard,
|
||||
rankRows,
|
||||
rectSum,
|
||||
type AppleAction,
|
||||
type AppleOptions,
|
||||
type AppleState,
|
||||
type Rect,
|
||||
} from './index';
|
||||
|
||||
const T0 = 1_000_000;
|
||||
const START = T0 + COUNTDOWN_MS;
|
||||
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
|
||||
|
||||
function make(players = ['A', 'B'], opts: Partial<AppleOptions> = {}, seed = 1): AppleState {
|
||||
return apple.setup({ players, options: apple.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
|
||||
}
|
||||
function act(s: AppleState, p: string, a: AppleAction, now: number): AppleState {
|
||||
const v = apple.validate(s, p, a, { now });
|
||||
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
|
||||
return apple.apply(s, p, a, { rng: rng(), now }).state;
|
||||
}
|
||||
const tick = (s: AppleState, now: number) => apple.apply(s, s.order[0]!, { type: 'tick' }, { rng: rng(), now }).state;
|
||||
const sel = (r: Rect): AppleAction => ({ type: 'select', ...r });
|
||||
const reason = (s: AppleState, p: string, a: AppleAction, now?: number) => {
|
||||
const v = apple.validate(s, p, a, now === undefined ? undefined : { now });
|
||||
return v.ok ? 'ok' : v.reason;
|
||||
};
|
||||
|
||||
/** A board from rows of text ('.' or '0' = empty), padded with empty cells. */
|
||||
function board(rows: string[]): string {
|
||||
const out: string[] = [];
|
||||
for (let r = 0; r < ROWS; r++) out.push((rows[r] ?? '').replace(/\./g, '0').padEnd(COLS, '0').slice(0, COLS));
|
||||
return out.join('');
|
||||
}
|
||||
function rigged(cells: string, players = ['A', 'B']): AppleState {
|
||||
const s = tick(make(players), START);
|
||||
for (const p of players) s.boards[p] = cells;
|
||||
s.initial = cells;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Brute force: every rectangle with sum 10, reduced to its apples' bounding box, deduplicated. */
|
||||
function bruteMoves(cells: string): string[] {
|
||||
const keys = new Set<string>();
|
||||
for (let r0 = 0; r0 < ROWS; r0++)
|
||||
for (let r1 = r0; r1 < ROWS; r1++)
|
||||
for (let c0 = 0; c0 < COLS; c0++)
|
||||
for (let c1 = c0; c1 < COLS; c1++) {
|
||||
if (rectSum(cells, { r0, c0, r1, c1 }).sum !== 10) continue;
|
||||
let a = ROWS, b = COLS, c = -1, d = -1;
|
||||
for (let r = r0; r <= r1; r++)
|
||||
for (let k = c0; k <= c1; k++)
|
||||
if (cells[r * COLS + k] !== '0') {
|
||||
a = Math.min(a, r); b = Math.min(b, k); c = Math.max(c, r); d = Math.max(d, k);
|
||||
}
|
||||
keys.add(`${a},${b},${c},${d}`);
|
||||
}
|
||||
return [...keys].sort();
|
||||
}
|
||||
|
||||
describe('판 만들기', () => {
|
||||
test('17×10 칸에 1~9, 합은 10의 배수, 같은 시드면 같은 판, 모두 같은 판으로 시작', () => {
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
const b = makeBoard(SeededRng.fromSeed(seedN(i)));
|
||||
expect(b).toHaveLength(CELLS);
|
||||
expect(b).toMatch(/^[1-9]+$/);
|
||||
expect([...b].reduce((a, c) => a + Number(c), 0) % 10).toBe(0);
|
||||
expect(makeBoard(SeededRng.fromSeed(seedN(i)))).toBe(b);
|
||||
}
|
||||
const s = make(['A', 'B', 'C']);
|
||||
expect(new Set(Object.values(s.boards))).toEqual(new Set([s.initial]));
|
||||
expect(s.endsAt).toBe(START + 120_000);
|
||||
expect(make(['A'], { timeLimitSec: 60 }).endsAt).toBe(START + 60_000);
|
||||
});
|
||||
|
||||
test('findMoves = 손으로 센 모든 합 10 직사각형(가장 좁게), 빈 칸 너머도 포함', () => {
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
const r = SeededRng.fromSeed(seedN(100 + i));
|
||||
// Sparse boards so long rectangles across cleared cells show up too.
|
||||
const cells = [...makeBoard(r)].map((c) => (r.int(10) < 6 ? '0' : c)).join('');
|
||||
const got = findMoves(cells).map((m) => `${m.r0},${m.c0},${m.r1},${m.c1}`).sort();
|
||||
expect(got).toEqual(bruteMoves(cells));
|
||||
}
|
||||
expect(findMoves(board(['19', '..', '.5', '.5']))).toEqual([
|
||||
{ r0: 0, c0: 0, r1: 0, c1: 1 },
|
||||
{ r0: 2, c0: 1, r1: 3, c1: 1 },
|
||||
]);
|
||||
expect(hasMove(board(['55']))).toBe(true);
|
||||
expect(hasMove(board(['54', '..', '9']))).toBe(false);
|
||||
});
|
||||
|
||||
test('한 수 계산은 1ms 안쪽(판 전체를 훑어도)', () => {
|
||||
const cells = makeBoard(SeededRng.fromSeed(seedN(3)));
|
||||
const t0 = performance.now();
|
||||
for (let i = 0; i < 50; i++) findMoves(cells);
|
||||
expect((performance.now() - t0) / 50).toBeLessThan(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('진행', () => {
|
||||
test('카운트다운 동안에는 판이 안 보이고 고를 수 없어요. 시간이 되면 바로 시작(타이머 전이라도)', () => {
|
||||
const s = make();
|
||||
expect(apple.view(s, 'A').cells).toBeNull();
|
||||
checkNoLeak(apple, s, 'A', s.order);
|
||||
const m = findMoves(s.initial)[0]!;
|
||||
expect(reason(s, 'A', sel(m), START - 1)).toBe('곧 시작해요. 잠시만 기다려 주세요.');
|
||||
// The countdown is over but the room timer has not ticked yet: the select still counts.
|
||||
const s2 = act(s, 'A', sel(m), START + 5);
|
||||
expect(s2.phase).toBe('playing');
|
||||
expect(s2.score.A).toBeGreaterThanOrEqual(2);
|
||||
expect(apple.view(s2, 'A').cells).toBe(s2.boards.A!);
|
||||
expect(apple.view(s2, null).cells).toBeNull();
|
||||
// Others never get my board, only my score.
|
||||
expect(JSON.stringify(apple.view(s2, 'B'))).not.toContain(s2.boards.A!);
|
||||
expect(apple.view(s2, 'B').seats.find((x) => x.id === 'A')!.score).toBe(s2.score.A!);
|
||||
});
|
||||
|
||||
test('합이 딱 10이면 지워지고 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 모서리 순서 무관', () => {
|
||||
const s = rigged(board(['1.9', '...', '28.', '...', '55.']));
|
||||
expect(reason(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 2 }), START + 10)).toBe('ok');
|
||||
let t = act(s, 'A', sel({ r0: 0, c0: 2, r1: 0, c1: 0 }), START + 10);
|
||||
expect(t.score.A).toBe(2);
|
||||
expect(t.clears.A).toBe(1);
|
||||
expect(t.boards.A!.slice(0, 3)).toBe('000');
|
||||
// B's copy is untouched.
|
||||
expect(t.boards.B).toBe(s.boards.B);
|
||||
// A rectangle over cleared cells: 2 + 8 (rows 0~2) still adds to 10.
|
||||
t = act(t, 'A', sel({ r0: 0, c0: 0, r1: 2, c1: 2 }), START + 600);
|
||||
expect(t.score.A).toBe(4);
|
||||
expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 1, c1: 2 }), START + 1200)).toBe('고른 칸에 사과가 없어요.');
|
||||
expect(reason(t, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 1200)).toBe('합이 5이에요. 딱 10이 되게 골라 주세요.');
|
||||
// The whole board (only 5 + 5 left) is a fine rectangle too.
|
||||
expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 9, c1: 16 }), START + 1200)).toBe('ok');
|
||||
});
|
||||
|
||||
test('너무 빨리 연달아 고르면 거절(1초에 5번까지)', () => {
|
||||
let s = rigged(board(['55555555555555555', '55555555555555555']));
|
||||
let now = START + 100;
|
||||
for (let i = 0; i < SELECTS_PER_SEC; i++) s = act(s, 'A', sel({ r0: 0, c0: 2 * i, r1: 0, c1: 2 * i + 1 }), (now += 10));
|
||||
expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('조금 천천히 해 주세요.');
|
||||
expect(reason(s, 'B', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('ok');
|
||||
expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), START + 100 + 10 + 1000)).toBe('ok');
|
||||
});
|
||||
|
||||
test('서버 시계로 끝: 마감 뒤 고르기는 거절, 타이머 tick으로 끝나고 점수 순위(동점 같은 순위)', () => {
|
||||
let s = make(['A', 'B', 'C']);
|
||||
s = tick(s, START);
|
||||
const m1 = findMoves(s.initial)[0];
|
||||
s = act(s, 'A', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(m1!), START + 1000);
|
||||
s = act(s, 'B', sel(findMoves(s.boards.B!)[0]!), START + 2000);
|
||||
expect(apple.deadline!(s)).toBe(s.endsAt);
|
||||
expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt);
|
||||
expect(reason(s, 'C', sel(m1!), s.endsAt)).toBe('시간이 다 됐어요.');
|
||||
s = tick(s, s.endsAt);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['B'], ['A'], ['C']]);
|
||||
expect(r.scoreText!.C).toBe('사과 0개');
|
||||
expect(r.summary).toContain('시간이 다 됐어요');
|
||||
// Tie → shared rank.
|
||||
s.score.A = s.score.B!;
|
||||
expect(rankRows(s).map((x) => x.rank)).toEqual([1, 1, 3]);
|
||||
});
|
||||
|
||||
test('혼자 하기: 1명도 시작, 끝나면 내 점수 요약', () => {
|
||||
let s = make(['A']);
|
||||
s = tick(s, START);
|
||||
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
s = tick(s, s.endsAt + 5);
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A']]);
|
||||
expect(r.summary).toBe(`시간이 다 됐어요. 사과 ${s.score.A}개를 지웠어요`);
|
||||
});
|
||||
|
||||
test('더 지울 게 없으면 "막힘", 모두 막히면 시간 전에 끝나요', () => {
|
||||
let s = rigged(board(['19', '..', '37', '..', '4']));
|
||||
s = act(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 100);
|
||||
expect(s.status.A).toBe('playing');
|
||||
s = act(s, 'A', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 700);
|
||||
expect(s.status.A).toBe('stuck');
|
||||
expect(apple.activePlayers(s)).toEqual(['B']);
|
||||
expect(apple.timeoutPlayers!(s)).toEqual(['A', 'B']);
|
||||
expect(reason(s, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 800)).toBe('더 지울 수 있는 사과가 없어요.');
|
||||
s = act(s, 'B', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 900);
|
||||
s = act(s, 'B', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 1500);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['A', 'B']]);
|
||||
expect(r.summary).toContain('모두 더 지울 사과가 없어요');
|
||||
expect(r.summary).toContain('공동 1등 2명');
|
||||
});
|
||||
|
||||
test('나가기: 남은 사람이 1명이면 끝, 나간 사람은 맨 뒤 순위', () => {
|
||||
let s = tick(make(['A', 'B', 'C']), START);
|
||||
s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500);
|
||||
expect(apple.onLeave!(s, 'A')).toEqual({ type: 'leave' });
|
||||
s = act(s, 'A', { type: 'leave' }, START + 600);
|
||||
expect(s.phase).toBe('playing');
|
||||
expect(reason(s, 'A', sel(findMoves(s.boards.A!)[0]!), START + 700)).toBe('게임에서 빠졌어요.');
|
||||
expect(apple.onLeave!(s, 'A')).toBeNull();
|
||||
s = act(s, 'B', { type: 'leave' }, START + 800);
|
||||
expect(s.phase).toBe('ended');
|
||||
const r = apple.result(s)!;
|
||||
expect(r.ranking).toEqual([['C'], ['A'], ['B']]);
|
||||
expect(r.summary).toBe('다른 사람이 모두 나가서 남은 사람이 이겼어요');
|
||||
// Solo leaver: the game just ends. Leaving during the countdown works too.
|
||||
const solo = act(make(['A']), 'A', { type: 'leave' }, T0 + 100);
|
||||
expect(solo.phase).toBe('ended');
|
||||
});
|
||||
|
||||
test('클라이언트 액션 스키마에는 select만(tick/leave는 시스템 전용)', () => {
|
||||
expect(apple.actionSchema.safeParse({ type: 'tick' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'leave' }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 9, c1: 16 }).success).toBe(true);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 10, c1: 16 }).success).toBe(false);
|
||||
expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 1, c1: 1.5 }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('무작위 대국', () => {
|
||||
test.each([1, 2, 5, 8])('%i명: 엔진 randomPlayout(유출·JSON·결정성) 끝까지', (n) => {
|
||||
const players = Array.from({ length: n }, (_, i) => `p${i + 1}`);
|
||||
for (let i = 0; i < playoutSeeds(20); i++) {
|
||||
const a = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
|
||||
expect(a.finished).toBe(true);
|
||||
const b = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 });
|
||||
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
|
||||
const r = apple.result(a.finalState as AppleState)!;
|
||||
expect(r.ranking.flat().sort()).toEqual([...players].sort());
|
||||
const s = a.finalState as AppleState;
|
||||
// Score = apples gone from the board.
|
||||
for (const p of players) expect(s.score[p]).toBe([...s.boards[p]!].filter((c) => c === '0').length);
|
||||
}
|
||||
});
|
||||
});
|
||||
95
packages/games/src/apple/bot.test.ts
Normal file
95
packages/games/src/apple/bot.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
75
packages/games/src/apple/bot.ts
Normal file
75
packages/games/src/apple/bot.ts
Normal 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 };
|
||||
}
|
||||
368
packages/games/src/apple/index.ts
Normal file
368
packages/games/src/apple/index.ts
Normal 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] : [];
|
||||
},
|
||||
};
|
||||
87
packages/games/src/apple/types.ts
Normal file
87
packages/games/src/apple/types.ts
Normal 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;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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 },
|
||||
];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user