- 규칙 모듈 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>
369 lines
13 KiB
TypeScript
369 lines
13 KiB
TypeScript
/**
|
|
* 사과 게임 (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] : [];
|
|
},
|
|
};
|