사과 게임 무제한: 스톱워치(시작부터 더 지울 사과가 없거나 여기까지 할 때까지, 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

@@ -30,7 +30,10 @@ export function helpNow(v: AppleView, me: string | null, players: Record<string,
if (mine.status === 'done') return `여기까지 했어요. 사과 ${mine.score}개를 지웠어요. 모두 끝내면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
const lines = [HOW, '빈 칸은 합에 들어가지 않아서, 사이가 비어 있어도 멀리 있는 사과끼리 묶을 수 있어요.', `지금 내 점수는 사과 ${mine.score}개예요.`];
if (lead) lines.push(lead);
if (secs === null) lines.push('제한 시간이 없어요. 그만하고 싶으면 아래 [여기까지 할래요]를 두 번 눌러요.');
if (secs === null) {
lines.push('제한 시간이 없어요. 위의 스톱워치가 더 지울 사과가 없어질 때까지 걸린 시간을 재요. 그만하고 싶으면 아래 [여기까지 할래요]를 두 번 눌러요.');
lines.push('막히면 [💡 힌트]를 눌러요. 판에 합이 10인 묶음 하나가 노란 점선 상자로 보여요. 받은 횟수는 결과에 걸린 시간과 함께 나와요.');
}
lines.push(KEYS);
return lines.join('\n');
}

View File

@@ -1,6 +1,6 @@
/** 사과 게임 화면 (docs/games/apple.md §9). */
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import type { AppleOptions, AppleView, SeatView } from '@bg/games/apple';
import { extraText, formatElapsed, type AppleOptions, type AppleView, type SeatView } from '@bg/games/apple';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
@@ -50,6 +50,11 @@ const clock = (ms: number) => {
const s = Math.ceil(Math.max(0, ms) / 1000);
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};
/** 무제한 stopwatch on the board: "1:05.4". */
const watch = (ms: number) => {
const t = Math.floor(Math.max(0, ms) / 100);
return `${Math.floor(t / 600)}:${String(Math.floor((t % 600) / 10)).padStart(2, '0')}.${t % 10}`;
};
const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
/** Game sounds on top of the shared palette (site volume applies). */
@@ -114,6 +119,9 @@ const CSS = `
.ap-pill b, .ap-others li b { display: inline-block; }
.ap-over.count b { display: block; animation: ap-count .9s ease-out both; }
.ap-stop { min-height: 40px; }
.ap-acts { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
.ap-hint { animation: ap-hint 1s ease-in-out infinite alternate; }
@keyframes ap-hint { from { opacity: .45; } to { opacity: 1; } }
.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); }
@@ -129,7 +137,7 @@ const CSS = `
@keyframes ap-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
@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, .ap-in, .ap-burst, .ap-over.count b { animation: none; } .ap-burst { display: none; } }
@media (prefers-reduced-motion: reduce) { .ap-hint { animation: none; } .ap-pop { animation-duration: .01s; } .ap-flash, .ap-in, .ap-burst, .ap-over.count b { animation: none; } .ap-burst { display: none; } }
`;
// ---------------------------------------------------------------- art
@@ -204,7 +212,8 @@ interface Pop {
}
function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
const now = useServerNow(200);
// 무제한 runs a stopwatch in tenths: a quicker clock there.
const now = useServerNow(v.endsAt === null ? 100 : 200);
const phone = useNarrow();
const [drag, setDrag] = useState<{ a: Cell; b: Cell } | null>(null);
const [cursor, setCursor] = useState<Cell>([0, 0]);
@@ -372,6 +381,8 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
};
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
// 무제한 stopwatch: from the start until I have nothing more to clear (or 「여기까지」); spectators see the room's clock.
const elapsed = mine?.timeMs ?? (v.phase === 'playing' && (!mine || mine.status === 'playing') ? Math.max(0, now - v.countdownEndsAt) : null);
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';
// Sounds that follow the clock and the state: 3·2·1, start, last 10 seconds, "10!" while dragging, finished.
@@ -413,14 +424,36 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
);
}
const [cr, cc] = toDisp(cursor);
// 💡 힌트: a glowing box around one group that adds up to 10 (only mine, only while it still does).
let hintBox: ReactNode = null;
if (v.hint && canPlay && cells && inside(cells, v.hint).sum === 10) {
const [ar, ac] = toDisp([v.hint.r0, v.hint.c0]);
const [br, bc] = toDisp([v.hint.r1, v.hint.c1]);
hintBox = (
<rect
className="ap-hint"
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="rgba(250,204,21,.25)"
stroke="#f59e0b"
strokeWidth={4}
strokeDasharray="8 4"
pointerEvents="none"
data-hint
/>
);
}
return (
<div className="ap">
<style>{CSS}</style>
<div className="ap-top">
{left === null ? (
<span className="ap-pill" aria-label="제한 시간 없음">
⏱ 무제한
<span className="ap-pill" aria-label={elapsed === null ? '제한 시간 없음' : `걸린 시간 ${formatElapsed(elapsed)}`}>
⏱ {elapsed === null ? '무제한' : <b style={{ fontSize: '1rem' }}>{watch(elapsed)}</b>}
</span>
) : (
<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}초`}>
@@ -499,6 +532,7 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
);
}),
)}
{hintBox}
{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>
@@ -515,29 +549,42 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
)}
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
<div className="ap-over note" role="status">
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개 · 끝날 때까지 기다려요
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개{extraText(mine)} · 끝날 때까지 기다려요
</div>
)}
{mine && mine.status === 'done' && v.phase === 'playing' && (
<div className="ap-over note" role="status">
여기까지 했어요! 사과 {mine.score}개 · 모두 끝날 때까지 기다려요
여기까지 했어요! 사과 {mine.score}개{extraText(mine)} · 모두 끝날 때까지 기다려요
</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>
{unlimited && canPlay && (
<button
type="button"
className={`btn ${stopAsk ? 'btn-primary' : 'btn-secondary'} ap-stop`}
onClick={() => {
if (!stopAsk) return setStopAsk(true);
setStopAsk(false);
act({ type: 'stop' });
}}
>
{stopAsk ? '한 번 더 누르면 여기까지 해요' : `여기까지 할래요 (사과 ${mine.score}개)`}
</button>
<div className="ap-acts">
<button
type="button"
className="btn btn-soft ap-stop"
disabled={!!hintBox}
onClick={() => {
act({ type: 'hint' });
say('힌트: 판에 노란 점선 상자로 합이 10인 묶음을 보여 줘요.');
}}
>
💡 힌트{mine.hints ? ` (${mine.hints}번 받음)` : ''}
</button>
<button
type="button"
className={`btn ${stopAsk ? 'btn-primary' : 'btn-secondary'} ap-stop`}
onClick={() => {
if (!stopAsk) return setStopAsk(true);
setStopAsk(false);
act({ type: 'stop' });
}}
>
{stopAsk ? '한 번 더 누르면 여기까지 해요' : `여기까지 할래요 (사과 ${mine.score}개)`}
</button>
</div>
)}
{!phone && mine && v.phase !== 'ended' && <p className="ap-keys">마우스로 드래그해서 합이 10이면 손을 떼요 · 키보드: 화살표 + 스페이스(시작점·끝점), Esc 취소</p>}
<p className="sr-only" aria-live="polite">
@@ -573,6 +620,7 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
{nick(players, s.id)}
{s.id === me ? ' (나)' : ''}
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'done' ? ' · 여기까지' : s.status === 'left' ? ' · 나감' : ''}
{s.timeMs !== null ? ` · ${formatElapsed(s.timeMs)}` : ''}
</span>
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
🍎 {s.score}
@@ -590,6 +638,7 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
<span className="muted small">
{' '}
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
{extraText(r)}
</span>
</span>
))}
@@ -615,8 +664,8 @@ function statusText(v: AppleView, me: string | null, players: Record<string, Pub
return top && top.score > 0 ? `${nick(players, top.id)}님이 사과 ${top.score}개로 앞서요` : '모두 같은 판을 풀고 있어요';
}
if (mine.status === 'left') return '게임에서 나갔어요';
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개 · 끝날 때까지 기다려요`;
if (mine.status === 'done') return `여기까지 했어요 · 사과 ${mine.score}개 · 모두 끝날 때까지 기다려요`;
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개${extraText(mine)} · 끝날 때까지 기다려요`;
if (mine.status === 'done') return `여기까지 했어요 · 사과 ${mine.score}개${extraText(mine)} · 모두 끝날 때까지 기다려요`;
return `사과 ${mine.score}개 지웠어요 · 합이 10이 되게 드래그!`;
}
@@ -652,7 +701,7 @@ function Options({ value: o, onChange }: OptionsProps<AppleOptions>) {
/>
<span className="small muted">
{o.timeLimitSec === null
? '시간 제한 없이 각자 더 지울 사과가 없거나 [여기까지 할래요]를 누를 때까지 해요. 모두 끝나면 가장 많이 지운 사람이 이겨요.'
? '시간 제한 없이 각자 더 지울 사과가 없거나 [여기까지 할래요]를 누를 때까지 해요. 스톱워치로 걸린 시간을 재고, 💡 힌트도 받을 수 있어요(결과에 걸린 시간과 힌트 횟수가 나와요). 모두 끝나면 가장 많이 지운 사람이 이겨요.'
: '원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.'}
</span>
</div>
@@ -686,7 +735,7 @@ function Rules({ options }: { options?: AppleOptions }) {
</p>
<p>
{limitSec === null
? '이 방은 제한 시간이 없어요. 각자 더 지울 수 있는 묶음이 없거나 [여기까지 할래요]를 누르면 끝나고, 모두 끝나면 사과를 가장 많이 지운 사람이 이겨요. 개수가 같으면 같은 순위예요. 연결이 끊긴 채 오래 돌아오지 않으면 그때까지 점수로 끝낸 것으로 봐요.'
? '이 방은 제한 시간이 없어요. 각자 더 지울 수 있는 묶음이 없거나 [여기까지 할래요]를 누르면 끝나고, 모두 끝나면 사과를 가장 많이 지운 사람이 이겨요. 개수가 같으면 같은 순위예요. 연결이 끊긴 채 오래 돌아오지 않으면 그때까지 점수로 끝낸 것으로 봐요. 시작부터 끝낼 때까지 스톱워치로 시간을 재고, 막히면 [💡 힌트]로 합이 10인 묶음 하나를 볼 수 있어요. 결과에 걸린 시간과 힌트를 받은 횟수가 함께 나와요.'
: `제한 시간은 ${limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요.`}{' '}
혼자서도 할 수 있어요.
</p>

View File

@@ -30,11 +30,13 @@
- 직사각형 안에 사과가 0개면 무효.
- 합이 10이 아니면 **아무 일도 없다(벌점 없음)**. 서버는 그 행동을 거절하고(`합이 N이에요…`), 화면은 손을 뗄 때 합이 10이 아니면 아예 보내지 않고 "합 N · 10이 아니에요"만 잠깐 보여 준다.
- 내 판에 합 10 묶음이 더 없으면 "막힘"(`stuck`): 더 고를 수 없고 시간이 끝날 때까지 기다린다. 모두 막히면(혹은 남은 사람이 전부 막히면) 시간 전에 끝난다(원작에는 없음, 혼자 할 때 기다리지 않게).
- 무제한 스톱워치(2026-10-14): 시작(카운트다운 끝)부터 그 사람이 막히거나(`stuck` = 더 지울 사과 없음) 「여기까지」를 누를 때까지의 시간을 서버 시계로 잰다(`finishedAt`). 화면 위에 `0:00.0`(0.1초 단위)으로 흐르고, 끝나면 멈춘다. 제한 시간이 있는 방에는 없다.
- 무제한 힌트(2026-10-14): [💡 힌트]를 누르면 내 판에서 합이 10인 묶음 하나(전부 중 무작위)를 노란 점선 상자로 나에게만 보여 준다. 그 상자가 아직 10인 동안은 다시 받을 수 없고(횟수 중복 없음), 지우거나 다른 곳을 지워 10이 아니게 되면 사라진다. 받은 횟수를 센다.
## 6. 승패와 점수 계산
- 점수 = 지운 사과 개수(= 내 판의 빈 칸 수).
- 순위: 점수 높은 순, **같은 점수는 같은 순위**. 중간에 나간 사람은 남은 사람 모두보다 아래(그 안에서도 점수 순).
- 결과 화면 점수 문구: `사과 N개`. `GameResult.scores` = 지운 개수.
- 결과 화면 점수 문구: `사과 N개`, 무제한이면 `사과 N개 · 걸린 시간 3분 05.4초`(+ 힌트를 받았으면 ` · 힌트 2번`). 혼자 한 판의 요약에도 같은 꼬리가 붙는다. 순위는 그대로 개수만 본다. `GameResult.scores` = 지운 개수.
## 7. 지역 룰 / 하우스 룰
- 없음. 원작 변형(작은 판, 시간 보너스, 연쇄 점수 등)은 넣지 않았다.
@@ -64,6 +66,7 @@ interface AppleState {
|---|---|---|---|
| `select` | `r0, c0, r1, c1` (행 0~9, 열 0~16, 정수) | 게임 중인 사람, 카운트다운 끝 ~ 마감 전 | 나가지 않음, 막히지 않음, 1초에 5번 이하, 안에 사과 1개 이상, 합 = 10 |
| `stop` | — | 「여기까지」, 무제한 방에서 게임 중인 사람 | 시작 뒤, 아직 `playing` |
| `hint` | — | 💡 힌트, 무제한 방에서 게임 중인 사람 | 시작 뒤, 아직 `playing`, 지금 보이는 힌트가 없음(있어도 더는 10이 아니면 됨) |
| `tick` | — | 서버 타이머 전용(스키마에 없음) | — |
| `leave` | — | 서버(나가기) 전용 | 아직 게임 중 |
@@ -73,10 +76,11 @@ interface AppleState {
### 8.3 공개/비공개 정보 (view)
- 내 view: 내 판(`cells`, 170자) + 모든 사람의 점수·지운 횟수·상태 + 시간. **다른 사람 판은 보내지 않는다**(같은 판이라 숨길 정보는 없지만 view를 작게, 남의 진행 모양을 엿보지 않게).
- 관전자: 판 없이 점수만.
- 무제한: 모든 사람의 걸린 시간(`timeMs`, 끝낸 뒤에만)과 힌트 횟수(`hints`)는 모두에게, 힌트 상자(`hint`)는 받은 사람에게만.
- 카운트다운 동안에는 누구에게도 판을 보내지 않는다(`secretsOf` = 카운트다운 중 `initial`).
### 8.4 랜덤 요소
- `setup`의 판 생성만(`ctx.rng`). 모두 같은 판이라 운의 차이가 없다. 컴퓨터 운(셔플 여러 번 중 고르기)도 적용하지 않는다(턴 게임 전략에만 적용, `luckApplies`).
- `setup`의 판 생성과 힌트로 보여 줄 묶음 고르기(`apply`의 `ctx.rng`, 다시 보기에서도 같음). 모두 같은 판이라 운의 차이가 없다. 컴퓨터 운(셔플 여러 번 중 고르기)도 적용하지 않는다(턴 게임 전략에만 적용, `luckApplies`).
### 8.5 타이머·시간 초과·연결 끊김
- `deadline`: 카운트다운 중 `countdownEndsAt`, 진행 중 `endsAt`(서버 시계). 마감 `tick`으로 끝난다. 마감 뒤 도착한 `select`는 `시간이 다 됐어요.`로 거절. 무제한이면 진행 중 마감이 없고, 모두 막히거나 「여기까지」(`stop`)를 누르면 끝난다. 연결이 끊긴 채 방의 유예 시간이 지난 사람은 `tick`으로 `done` 처리된다.

View File

@@ -2950,6 +2950,51 @@ const PLANS: Record<string, Plan> = {
console.log(` apple: ${st.pc} mouse + ${st.key} keyboard clears on PC, ${st.phone}+ touch clears on the phone, ${st.miss} miss; final PC ${await appleScore(host)} / phone ${await appleScore(guest)}`);
},
},
appleUnlimited: {
// 2026-10-14: 무제한 — the stopwatch runs (tenths) and stops when I finish; 💡 힌트 shows a glowing box that adds up
// to 10 (button off while it shows), using it clears the box; the result shows 걸린 시간 and 힌트 N번.
game: 'apple',
lobby: async (host) => {
await host.getByRole('group', { name: '제한 시간' }).getByRole('button', { name: '무제한', exact: true }).click();
await host.getByText(/제한 시간 무제한/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
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 watchText = () => host.locator('.ap-top .ap-pill').first().innerText();
const w1 = await watchText();
await host.waitForTimeout(1200);
const w2 = await watchText();
if (!/⏱\s*\d+:\d\d\.\d/.test(w2) || w1 === w2) throw new Error(`stopwatch not running: "${w1}" → "${w2}"`);
const hintBtn = host.getByRole('button', { name: /^💡 힌트/ });
await hintBtn.click();
const box = host.locator('svg.ap-board rect[data-hint]');
await box.waitFor({ timeout: 3000 });
if (await hintBtn.isEnabled()) throw new Error('hint button should be off while a hint shows');
if (await guest.locator('svg.ap-board rect[data-hint]').count()) throw new Error('the other player sees my hint');
await host.screenshot({ path: join(SHOTS, 'apple-hint-pc.png') });
const r = await box.evaluate((el) => ['x', 'y', 'width', 'height'].map((k) => Number(el.getAttribute(k))));
const rect: [number, number, number, number] = [Math.floor(r[1]! / 40), Math.floor(r[0]! / 40), Math.floor((r[1]! + r[3]!) / 40), Math.floor((r[0]! + r[2]!) / 40)];
const before = await appleScore(host);
await appleDrag(host, rect, false);
await host.waitForFunction((b) => Number(document.querySelector('.ap-top')?.textContent?.match(/🍎\s*(\d+)/)?.[1] ?? -1) > b, before, { timeout: 3000 });
await box.waitFor({ state: 'detached', timeout: 3000 });
await host.getByRole('button', { name: '💡 힌트 (1번 받음)' }).waitFor();
// 여기까지 (two presses): my stopwatch stops.
for (const p of pages) {
await p.getByRole('button', { name: /^여기까지 할래요/ }).click();
await p.getByRole('button', { name: '한 번 더 누르면 여기까지 해요' }).click();
await host.waitForTimeout(300);
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 10_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'apple-unlimited-result-pc.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!/사과 \d+개 · 걸린 시간 [\d분 .]+초 · 힌트 1번/.test(text)) throw new Error(`no time / hints in the result: ${text.replace(/\n/g, ' ')}`);
if (!/사과 0개 · 걸린 시간 [\d분 .]+초(?! · 힌트)/.test(text)) throw new Error(`guest line: ${text.replace(/\n/g, ' ')}`);
console.log(` apple 무제한: stopwatch ${w1} → ${w2}; result: ${text.replace(/\n/g, ' ').slice(0, 160)}`);
},
},
clue: {
// PC host + 2 phones, dice movement, 30-second turns. Real turns through the UI: roll (PC once by keyboard), a secret
// passage, rooms picked on the map, suggestions from the chips, cards shown from the refute panel. Only the suggester

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;
}