사과 게임 무제한: 스톱워치(시작부터 더 지울 사과가 없거나 여기까지 할 때까지, 0.1초 단위)와 💡 힌트(합 10 묶음 하나를 나에게만 노란 점선 상자로), 결과창·순위·요약에 걸린 시간과 힌트 횟수

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-14 04:52:19 +09:00
parent 96e8cdeb24
commit b93228e5af
7 changed files with 302 additions and 35 deletions

View File

@@ -8,6 +8,7 @@ import {
SELECTS_PER_SEC,
apple,
findMoves,
formatElapsed,
hasMove,
makeBoard,
rankRows,
@@ -267,7 +268,85 @@ describe('제한 시간 무제한', () => {
expect(s.phase).toBe('playing');
const solo = apple.apply(tick(make(['A'], { timeLimitSec: null }), START), 'A', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state;
expect(solo.phase).toBe('ended');
expect(apple.result(solo)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요');
expect(apple.result(solo)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요 · 걸린 시간 1분 00.0초');
});
});
describe('무제한 스톱워치와 힌트 (2026-10-14)', () => {
test('걸린 시간 글자: 0.1초 단위, 1분부터 분', () => {
expect(formatElapsed(25_480)).toBe('25.4초');
expect(formatElapsed(185_400)).toBe('3분 05.4초');
expect(formatElapsed(60_000)).toBe('1분 00.0초');
});
test('더 지울 사과가 없어지는 순간까지 잰 시간이 결과(요약·점수 글자·순위)에 나와요', () => {
const cells = board(['19', '.....55']);
let s = rigged(cells, ['A']);
s.endsAt = null;
s.options = { ...s.options, timeLimitSec: null };
s = act(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 12_300);
expect(apple.view(s, 'A').seats[0]!.timeMs).toBeNull(); // still playing
s = act(s, 'A', sel({ r0: 1, c0: 5, r1: 1, c1: 6 }), START + 83_450);
expect(s.status.A).toBe('stuck');
expect(s.phase).toBe('ended');
expect(apple.view(s, 'A').seats[0]!.timeMs).toBe(83_450);
expect(s.final!.ranking[0]).toMatchObject({ timeMs: 83_450, hints: 0 });
const r = apple.result(s)!;
expect(r.summary).toBe('더 지울 사과가 없어요. 사과 4개를 지웠어요 · 걸린 시간 1분 23.4초');
expect(r.scoreText!.A).toBe('사과 4개 · 걸린 시간 1분 23.4초');
});
test('힌트: 무제한에서만, 합 10인 묶음 하나를 나에게만 보여 주고 받은 횟수가 결과에 나와요', () => {
let s = tick(make(['A', 'B'], { timeLimitSec: null }), START);
expect(reason(tick(make(['A']), START), 'A', { type: 'hint' }, START + 10)).toBe('힌트는 제한 시간이 없는 방에서만 받을 수 있어요.');
s = act(s, 'A', { type: 'hint' }, START + 1000);
const h = apple.view(s, 'A').hint!;
expect(rectSum(s.boards.A!, h).sum).toBe(10);
expect(apple.view(s, 'B').hint).toBeNull();
expect(apple.view(s, null).hint).toBeNull();
expect(apple.view(s, 'B').seats.find((x) => x.id === 'A')!.hints).toBe(1);
// While it is still on the board, asking again is refused (no double counting).
expect(reason(s, 'A', { type: 'hint' }, START + 1100)).toBe('힌트가 이미 판에 보여요.');
// Using it clears it; the next one counts again.
s = act(s, 'A', sel(h), START + 2000);
expect(apple.view(s, 'A').hint).toBeNull();
s = act(s, 'A', { type: 'hint' }, START + 3000);
expect(s.hints!.A).toBe(2);
s = act(s, 'A', { type: 'stop' }, START + 65_000);
expect(apple.view(s, 'A').hint).toBeNull();
expect(reason(s, 'A', { type: 'hint' }, START + 65_100)).toBe('이미 끝냈어요.');
s = act(s, 'B', { type: 'stop' }, START + 70_000);
const r = apple.result(s)!;
expect(r.scoreText!.A).toBe(`사과 ${s.score.A}개 · 걸린 시간 1분 05.0초 · 힌트 2번`);
expect(r.scoreText!.B).toBe('사과 0개 · 걸린 시간 1분 10.0초');
});
test('힌트를 쓰지 않고 다른 곳을 지워도, 힌트가 아직 10이면 그대로 남아요', () => {
let s = rigged(board(['19...28', '.....55']), ['A']);
s.endsAt = null;
s = act(s, 'A', { type: 'hint' }, START + 100);
const h = s.hint!.A!;
const other = [{ r0: 0, c0: 0, r1: 0, c1: 1 }, { r0: 0, c0: 5, r1: 0, c1: 6 }, { r0: 1, c0: 5, r1: 1, c1: 6 }].find((m) => m.r0 !== h.r0 || m.c0 !== h.c0)!;
s = act(s, 'A', sel(other), START + 200);
expect(s.hint!.A).toEqual(h);
});
test('2026-10-14 전에 저장된 게임(스톱워치·힌트 칸 없음)도 이어서 돼요', () => {
let s = tick(make(['A'], { timeLimitSec: null }), START);
delete s.finishedAt;
delete s.hint;
delete s.hints;
s = act(s, 'A', { type: 'hint' }, START + 100);
expect(s.hints!.A).toBe(1);
s = act(s, 'A', { type: 'stop' }, START + 5000);
expect(apple.result(s)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요 · 걸린 시간 5.0초 · 힌트 1번');
});
test('제한 시간이 있으면 시간·힌트 글자는 붙지 않아요', () => {
let s = tick(make(['A']), START);
s = tick(s, START + 120_000);
expect(apple.result(s)!.scoreText!.A).toBe('사과 0개');
expect(apple.view(s, 'A').seats[0]!.timeMs).toBeNull();
});
});

View File

@@ -16,6 +16,7 @@ import {
type AppleState,
type AppleView,
type EndReason,
type HintRect,
type RankRow,
type SeatStatus,
type SelectAction,
@@ -101,6 +102,14 @@ export function findMoves(cells: string, limit = Infinity): Rect[] {
export const hasMove = (cells: string): boolean => findMoves(cells, 1).length > 0;
/** 무제한 stopwatch: "25.4초", "3분 05.4초" (tenths, rounded down so a time never reads longer than it was). */
export function formatElapsed(ms: number): string {
const t = Math.floor(Math.max(0, ms) / 100);
const m = Math.floor(t / 600);
const sec = ((t % 600) / 10).toFixed(1);
return m > 0 ? `${m}분 ${sec.padStart(4, '0')}초` : `${sec}초`;
}
/** 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));
@@ -125,9 +134,28 @@ function clone(s: S): S {
clears: { ...s.clears },
status: { ...s.status },
recent: Object.fromEntries(Object.entries(s.recent).map(([k, v]) => [k, [...v]])),
finishedAt: { ...s.finishedAt },
hint: { ...s.hint },
hints: { ...s.hints },
};
}
/** 무제한 stopwatch: from the start (end of the countdown) until this player finished; null while playing or with a time limit. */
export function timeOf(s: Pick<S, 'endsAt' | 'countdownEndsAt' | 'finishedAt'>, p: PlayerId): number | null {
const at = s.finishedAt?.[p];
return s.endsAt === null && at !== undefined ? Math.max(0, at - s.countdownEndsAt) : null;
}
/** 무제한: the player has nothing more to do (stuck or 「여기까지」) — stop the stopwatch and drop the hint. */
function markFinished(s: S, p: PlayerId, now: number): void {
if (s.endsAt !== null) return;
s.finishedAt![p] = now;
s.hint![p] = null;
}
/** A hint is still good while it adds up to exactly 10. */
const hintOk = (cells: string, h: HintRect | null | undefined): h is HintRect => !!h && rectSum(cells, h).sum === TARGET;
interface Ctx {
now: number;
events: GameEvent[];
@@ -155,6 +183,7 @@ function catchUp(s: S, ctx: Ctx): void {
function stop(s: S, p: PlayerId, ctx: Ctx): void {
if (s.status[p] !== 'playing') return;
s.status[p] = 'done';
markFinished(s, p, ctx.now);
ctx.events.push({ type: 'done', player: p });
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
}
@@ -176,13 +205,24 @@ function select(s: S, p: PlayerId, a: SelectAction, ctx: Ctx): void {
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 (s.hint![p] && !hintOk(s.boards[p]!, s.hint![p])) s.hint![p] = null;
if (!hasMove(s.boards[p]!)) {
s.status[p] = 'stuck';
markFinished(s, p, ctx.now);
ctx.events.push({ type: 'stuck', player: p });
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx);
}
}
/** 💡 힌트: one rectangle that adds up to 10, picked at random among all of them (not always the top-left one). */
function giveHint(s: S, p: PlayerId, rng: Rng, ctx: Ctx): void {
const moves = findMoves(s.boards[p]!);
if (!moves.length) return;
s.hint![p] = moves[rng.int(moves.length)]!;
s.hints![p] = (s.hints![p] ?? 0) + 1;
ctx.events.push({ type: 'hint', player: p });
}
function leave(s: S, p: PlayerId, ctx: Ctx): void {
s.status[p] = 'left';
ctx.events.push({ type: 'left', player: p });
@@ -195,7 +235,8 @@ function leave(s: S, p: PlayerId, ctx: Ctx): void {
// ---------------------------------------------------------------- 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[] {
export function rankRows(s: Pick<S, 'order' | 'score' | 'clears' | 'status'> & Partial<Pick<S, 'endsAt' | 'countdownEndsAt' | 'finishedAt' | 'hints'>>): RankRow[] {
const unlimited = s.endsAt === null && s.countdownEndsAt !== undefined;
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));
@@ -203,7 +244,8 @@ export function rankRows(s: Pick<S, 'order' | 'score' | 'clears' | 'status'>): R
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 });
const extra = unlimited ? { timeMs: left ? null : timeOf(s as S, id), hints: s.hints?.[id] ?? 0 } : {};
rows.push({ rank: tie ? prev.rank : rows.length + 1, id, score, clears: s.clears[id] ?? 0, left, ...extra });
});
}
return rows;
@@ -219,6 +261,7 @@ function finish(s: S, reason: EndReason, ctx: Ctx): void {
const n = ranking[0]!.score;
const why = s.status[s.order[0]!] === 'done' ? '여기까지 했어요.' : '더 지울 사과가 없어요.';
summary = reason === 'cleared' ? `${why} 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`;
summary += extraText(ranking[0]!);
} else if (reason === 'left') summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요';
else {
const anyDone = s.order.some((p) => s.status[p] === 'done');
@@ -232,6 +275,13 @@ function finish(s: S, reason: EndReason, ctx: Ctx): void {
ctx.events.push({ type: 'gameEnd', reason });
}
/** 무제한: " · 걸린 시간 3분 05.4초 · 힌트 2번" (hints only when taken). */
export function extraText(r: Pick<RankRow, 'timeMs' | 'hints'>): string {
let t = r.timeMs != null ? ` · 걸린 시간 ${formatElapsed(r.timeMs)}` : '';
if (r.hints) t += ` · 힌트 ${r.hints}번`;
return t;
}
// ---------------------------------------------------------------- definition
type Def = GameDefinition<S, A, AppleView, AppleOptions>;
@@ -261,6 +311,9 @@ export const apple: Def = {
clears: per0(() => 0),
status: per0<SeatStatus>(() => 'playing'),
recent: per0<number[]>(() => []),
finishedAt: {},
hint: per0<HintRect | null>(() => null),
hints: per0(() => 0),
phase: 'countdown',
countdownEndsAt,
endsAt: options.timeLimitSec === null ? null : countdownEndsAt + options.timeLimitSec * 1000,
@@ -281,6 +334,12 @@ export const apple: Def = {
if (s.endsAt !== null) return fail('제한 시간이 있는 방에서는 끝날 때까지 해요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
return s.status[actor] === 'playing' ? ok : fail('이미 끝냈어요.');
case 'hint':
if (s.endsAt !== null) return fail('힌트는 제한 시간이 없는 방에서만 받을 수 있어요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
if (s.status[actor] !== 'playing') return fail('이미 끝냈어요.');
if (hintOk(s.boards[actor]!, s.hint?.[actor])) return fail('힌트가 이미 판에 보여요.');
return ok;
case 'select': {
if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
@@ -295,7 +354,7 @@ export const apple: Def = {
}
},
apply(prev, actor, a, { now }) {
apply(prev, actor, a, { now, rng }) {
const s = clone(prev);
const ctx: Ctx = { now, events: [] };
const wasPlaying = prev.phase === 'playing';
@@ -304,6 +363,7 @@ export const apple: Def = {
if (a.type === 'leave') leave(s, actor, ctx);
else if (a.type === 'select' && s.phase === 'playing') select(s, actor, a, ctx);
else if (a.type === 'stop' && s.phase === 'playing') stop(s, actor, ctx);
else if (a.type === 'hint' && s.phase === 'playing' && s.status[actor] === 'playing') giveHint(s, actor, rng, ctx);
// 무제한: nothing is due during play, so a tick there means the room timed this player out while away.
else if (a.type === 'tick' && wasPlaying && s.endsAt === null) stop(s, actor, ctx);
}
@@ -321,7 +381,8 @@ export const apple: Def = {
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]! })),
seats: s.order.map((id) => ({ id, score: s.score[id] ?? 0, clears: s.clears[id] ?? 0, status: s.status[id]!, timeMs: timeOf(s, id), hints: s.hints?.[id] ?? 0 })),
hint: me && s.phase === 'playing' ? (s.hint?.[me] ?? null) : null,
result: s.final,
};
},
@@ -370,19 +431,19 @@ export const apple: Def = {
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}개`])),
scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `사과 ${r.score}개${extraText(r)}`])),
summary: f.summary,
reason: 'normal',
};
},
/** Test helper: the clock tick, the first few rectangles that add up to 10 and (무제한) 「여기까지」. */
/** Test helper: the clock tick, the first few rectangles that add up to 10 and (무제한) 「여기까지」 and 힌트. */
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 });
if (s.endsAt === null) out.push({ type: 'stop' });
if (s.endsAt === null) out.push({ type: 'stop' }, { type: 'hint' });
}
return out.filter((x) => apple.validate(s, p, x).ok);
},

View File

@@ -27,8 +27,11 @@ const selectSchema = z.object({
r1: z.number().int().min(0).max(ROWS - 1),
c1: z.number().int().min(0).max(COLS - 1),
});
/** `stop` = 「여기까지」: only with no time limit, ends my game with the score I have. */
export const appleActionSchema = z.discriminatedUnion('type', [selectSchema, z.object({ type: z.literal('stop') })]);
/**
* `stop` = 「여기까지」: only with no time limit, ends my game with the score I have.
* `hint` = 💡 힌트 (무제한 only): shows me one rectangle that adds up to 10; the count goes into the result.
*/
export const appleActionSchema = z.discriminatedUnion('type', [selectSchema, z.object({ type: z.literal('stop') }), z.object({ type: z.literal('hint') })]);
export type SelectAction = z.infer<typeof selectSchema>;
/** Client actions plus system-only ones (server timer, leaving) that are not in the schema. */
export type AppleAction = z.infer<typeof appleActionSchema> | { type: 'tick' } | { type: 'leave' };
@@ -43,6 +46,18 @@ export interface RankRow {
score: number;
clears: number;
left: boolean;
/** 무제한: time from the start until no more apples could be cleared (or 「여기까지」); null otherwise. */
timeMs?: number | null;
/** 무제한: hints taken. */
hints?: number;
}
/** A rectangle by its corners, rows 0..9, columns 0..16 (top-left / bottom-right). */
export interface HintRect {
r0: number;
c0: number;
r1: number;
c1: number;
}
export interface AppleFinal {
@@ -63,6 +78,11 @@ export interface AppleState {
status: Record<PlayerId, SeatStatus>;
/** Server times of each player's recent selects (rate limit). */
recent: Record<PlayerId, number[]>;
/** 무제한 stopwatch: server time each player finished (stuck or 「여기까지」). Absent in games saved before 2026-10-14. */
finishedAt?: Record<PlayerId, number>;
/** 무제한: the hint each player sees now, and how many they took. Absent in older saves. */
hint?: Record<PlayerId, HintRect | null>;
hints?: Record<PlayerId, number>;
phase: 'countdown' | 'playing' | 'ended';
countdownEndsAt: number;
/** null = 무제한. */
@@ -75,6 +95,10 @@ export interface SeatView {
score: number;
clears: number;
status: SeatStatus;
/** 무제한: time taken once finished (stuck / 「여기까지」), else null. */
timeMs: number | null;
/** 무제한: hints taken. */
hints: number;
}
export interface AppleView {
@@ -88,5 +112,7 @@ export interface AppleView {
countdownEndsAt: number;
endsAt: number | null;
seats: SeatView[];
/** 무제한: the rectangle my hint points at (null when none). */
hint: HintRect | null;
result: AppleFinal | null;
}