From fa53175f512ba8319c05615e73b94cd1faddec7a Mon Sep 17 00:00:00 2001 From: EJClaw Date: Sun, 8 Nov 2026 10:40:48 +0900 Subject: [PATCH] =?UTF-8?q?=EA=B2=B0=EA=B3=BC=EB=8A=94=20=EC=9B=80?= =?UTF-8?q?=EC=A7=81=EC=9E=84=EC=9D=B4=20=EB=81=9D=EB=82=A0=20=EB=95=8C?= =?UTF-8?q?=EA=B9=8C=EC=A7=80(=EC=8B=9C=EA=B0=84=20=EC=83=81=ED=95=9C=20?= =?UTF-8?q?=EC=97=86=EC=9D=8C),=20=EC=A0=9C=ED=95=9C=20=EC=8B=9C=EA=B0=84?= =?UTF-8?q?=EC=9D=80=20=EA=B0=81=EC=9E=90=20=ED=99=94=EB=A9=B4=EC=9D=B4=20?= =?UTF-8?q?=EC=97=B0=EC=B6=9C=EC=9D=84=20=EB=8B=A4=20=EB=B3=B4=EC=97=AC=20?= =?UTF-8?q?=EC=A4=80=20=EB=92=A4=EB=B6=80=ED=84=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - lib/motion: useMotionSettled에서 12초 상한을 없앰(명시한 maxMs만) - 서버: 클라이언트 settled(seq)를 받으면 그 사람의 제한 시간을 연출에 걸린 만큼 늦춤(보고 전에는 최대 15초×속도, 보고한 적 없는 화면·컴퓨터·실시간 게임은 예전 그대로), 마감이 바뀌면 deadline 메시지 - 바퀴벌레 포커: 게임을 끝낸 판정은 패배 배너까지 다 끝난 뒤에 끝 화면 - 증강 윷놀이: 선택 창 열림을 후보 묶음마다 따로, 이의있음! 재선택 창은 이의있음! 화면이 사라진 뒤에 - e2e/motion.e2e.ts: 30초 움직임·바퀴벌레 포커 마지막 판정·이의있음! 재선택·다빈치 ×1/8 회귀 확인, 방 타이머 단위 테스트 Co-Authored-By: Claude Opus 5.5 --- apps/server/src/rooms/room.test.ts | 56 +++++ apps/server/src/rooms/room.ts | 48 +++- apps/server/src/ws/gateway.ts | 3 + apps/web/src/games/cockroach-poker/index.tsx | 5 +- apps/web/src/games/yut/aug-ui.tsx | 21 +- apps/web/src/lib/motion.ts | 10 +- apps/web/src/net/socket.ts | 4 + apps/web/src/pages/RoomPage.tsx | 6 + docs/03-realtime-protocol.md | 2 + docs/07-ui-ux.md | 2 +- e2e/motion.e2e.ts | 223 +++++++++++++++++++ packages/engine/src/types.ts | 5 + packages/games/src/apple/index.ts | 1 + packages/games/src/catchmind/index.ts | 1 + packages/games/src/dobble/index.ts | 1 + packages/games/src/halli-galli/index.ts | 1 + packages/shared/src/protocol.ts | 2 + packages/shared/src/types.ts | 2 + 18 files changed, 371 insertions(+), 22 deletions(-) create mode 100644 e2e/motion.e2e.ts diff --git a/apps/server/src/rooms/room.test.ts b/apps/server/src/rooms/room.test.ts index 4b4c266..e951263 100644 --- a/apps/server/src/rooms/room.test.ts +++ b/apps/server/src/rooms/room.test.ts @@ -61,6 +61,62 @@ describe('Room timers', () => { expect((room.game!.state as any).moves[0].auto).toBe(true); }); + test('a turn clock starts when the player\'s screen has finished animating (settled), not before', () => { + const { room, clock, conn } = harness(); + const a = conn('A'); + const b = conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } }); + expect(room.start('A')).toBeNull(); + room.clearTimer(); + const base = clock.now() + 10_000; + // A screen that never reported keeps the old clock (pages from before this change, computers). + expect(room.effectiveDeadline()).toBe(base); + // A's screen finishes the opening 1.5 s later: A's clock is 1.5 s longer, and everyone is told the new deadline. + clock.advance(1_500); + room.settled('A', room.seq); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 1_500); + expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 1_500 }); + clock.advance(10_000 - 1); + room.onTimer(); + room.clearTimer(); + expect((room.game!.state as any).moves).toHaveLength(0); + clock.advance(1); + room.onTimer(); + room.clearTimer(); + expect((room.game!.state as any).moves).toHaveLength(1); + // Next state, B to move: a late report for an older state counts nothing, and B (who never reported) keeps the plain clock. + const seq = room.seq; + const base2 = clock.now() + 10_000; + room.settled('A', seq - 1); + expect(room.effectiveDeadline()).toBe(base2); // B is to move and B never reported: B's clock is unchanged + room.settled('B', seq); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base2); + }); + + test('a player who reported once but not yet for this state: the timer waits for the screen (at most 15 s at ×1)', () => { + const { room, clock, conn } = harness(); + room.join(conn('A'), 'player'); + room.join(conn('B'), 'player'); + room.configure('A', { options: { colorAssignment: 'hostBlack', timeControl: { kind: 'perMove', perMoveSec: 10 } } }); + room.start('A'); + room.settled('A', room.seq); + room.settled('B', room.seq); + room.clearTimer(); + // A plays; B (to move) has not reported this new state yet + room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]); + room.clearTimer(); + const base = clock.now() + 10_000; + expect(room.effectiveDeadline()).toBe(base + 15_000); + clock.advance(2_000); + room.settled('B', room.seq); + room.clearTimer(); + expect(room.effectiveDeadline()).toBe(base + 2_000); + }); + test('disconnected player is auto-acted after the grace period, not before the turn deadline rules', () => { const { room, clock, conn } = harness(); const a = conn('A'); diff --git a/apps/server/src/rooms/room.ts b/apps/server/src/rooms/room.ts index 1571770..ce38b08 100644 --- a/apps/server/src/rooms/room.ts +++ b/apps/server/src/rooms/room.ts @@ -115,6 +115,11 @@ export const LUCK_BUDGET_MS = 1500; const ERROR_LIMIT = 3; /** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */ const STREAM_FLUSH_MS = 1000; +/** + * Longest a player's clock waits for their screen to finish animating a change (ms at game speed ×1 before the + * shared 1.5× slowdown; scaled like the animations). A screen that never reports (an old tab, a hidden tab) costs at most this. + */ +export const REVEAL_MAX_MS = 10_000; export class Room { status: 'lobby' | 'playing' | 'finished' | 'paused' | 'broken' = 'lobby'; @@ -154,6 +159,13 @@ export class Room { /** When each person last said they were typing (to drop repeats within a second). */ private typingAt = new Map(); private consecutiveErrors = 0; + /** + * The last game state change and when each player's screen finished animating it (client `settled`). A player's + * clock starts then, so a choice shown after the animation still gets its full time (`revealExtra`). + */ + private reveal: { seq: number; at: number; done: Map } | null = null; + /** Players whose screens report `settled` (pages from before 2026-11-08 don't: their clocks run as before). */ + private settles = new Set(); private readonly now: () => number; /** Plays the computer players' moves (docs/06 §12). */ readonly bots: BotDriver; @@ -474,6 +486,7 @@ export class Room { private broadcastState(events: unknown[], actor?: string, cs?: number): void { if (!this.game) return; + this.reveal = { seq: this.seq, at: this.now(), done: new Map() }; let spectatorMsg: ServerMessage | null = null; for (const c of this.conns.values()) { let msg: ServerMessage | null; @@ -1130,13 +1143,40 @@ export class Room { /** The deadline clients see (`def.publicDeadline`, default the effective one); timers use `effectiveDeadline`. */ private publicDeadline(): number | null { - const d = this.effectiveDeadline(); + const d = this.effectiveDeadline(true); const g = this.game; return g && this.def.publicDeadline ? this.def.publicDeadline(g.state, d) : d; } + /** + * How much later than the game's own deadline `u`'s clock runs out: the time their screen took to finish animating + * the last change. Until their screen says so, the timer waits up to `REVEAL_MAX_MS` (scaled like the animations); + * computers and screens that never report get no extra time; + * `provisional` (the deadline shown to clients) counts only the time that has passed so far. + */ + private revealExtra(u: string, provisional = false): number { + const r = this.reveal; + if (!r || !this.game || this.def.realtime || !this.settles.has(u)) return 0; + const cap = Math.round((REVEAL_MAX_MS * BOT_SLOWDOWN) / this.gameSpeed()); + const done = r.done.get(u); + if (done !== undefined) return Math.min(cap, done - r.at); + return provisional ? Math.min(cap, Math.max(0, this.now() - r.at)) : cap; + } + + /** A player's screen finished animating the state `seq` (or a later one): their clock starts now. */ + settled(userId: string, seq: number): void { + const r = this.reveal; + if (!r || seq < r.seq || r.done.has(userId) || !this.game || this.game.finished || !this.game.players.includes(userId)) return; + const before = this.publicDeadline(); + this.settles.add(userId); + r.done.set(userId, this.now()); + this.scheduleTimer(); + const after = this.publicDeadline(); + if (after !== before) for (const c of this.conns.values()) c.send({ t: 'deadline', deadline: after }); + } + /** Earliest time any timed player must be auto-acted for. */ - effectiveDeadline(): number | null { + effectiveDeadline(provisional = false): number | null { const g = this.game; if (!g || g.finished || this.status !== 'playing') return null; const def = this.def; @@ -1146,7 +1186,7 @@ export class Room { const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000; let best: number | null = null; for (const u of timed) { - let d = base; + let d = base === null ? null : base + this.revealExtra(u, provisional); const p = this.presence.get(u); if (p && !p.connected) { const grace = p.since + graceMs; @@ -1190,7 +1230,7 @@ export class Room { const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state); const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000; for (const u of timed) { - let d = base; + let d = base === null ? null : base + this.revealExtra(u); const p = this.presence.get(u); if (p && !p.connected) { const grace = p.since + graceMs; diff --git a/apps/server/src/ws/gateway.ts b/apps/server/src/ws/gateway.ts index 75b8c95..ce145e2 100644 --- a/apps/server/src/ws/gateway.ts +++ b/apps/server/src/ws/gateway.ts @@ -263,6 +263,9 @@ export class Gateway { case 'sync': room.sendSync(this.connFor(ws)); return; + case 'settled': + room.settled(u, m.seq); + return; } if (e) err(e); } diff --git a/apps/web/src/games/cockroach-poker/index.tsx b/apps/web/src/games/cockroach-poker/index.tsx index 8810cc6..2bf1587 100644 --- a/apps/web/src/games/cockroach-poker/index.tsx +++ b/apps/web/src/games/cockroach-poker/index.tsx @@ -529,8 +529,9 @@ function Who({ id, players, me }: { id: string; players: Record; fresh: { slide: boolean; flip: boolean }; over: boolean }) { const r = v.round; - // The call that ended the game is played out like any other (card turns, stamp, flight) before the end shows. - const lastCall = v.phase === 'finished' && fresh.flip && !over ? v.lastReveal : null; + // The call that ended the game is played out like any other (card turns, stamp, flight, the loss banner): the end + // shows only once all of it has finished (`over`), not when the card's own flip is done. + const lastCall = v.phase === 'finished' && !over ? v.lastReveal : null; if (v.phase === 'finished' && !lastCall) { const f = v.final!; return ( diff --git a/apps/web/src/games/yut/aug-ui.tsx b/apps/web/src/games/yut/aug-ui.tsx index 4420b8d..20b0a22 100644 --- a/apps/web/src/games/yut/aug-ui.tsx +++ b/apps/web/src/games/yut/aug-ui.tsx @@ -333,23 +333,26 @@ export function AugSelect({ v, act, pending, players, blocked = false }: { v: Yu const sel = v.aug!.select!; const [choice, setChoice] = useState(null); const [target, setTarget] = useState(''); - const [open, setOpen] = useState(false); const mine = sel.offers.length > 0 && sel.picksLeft > 0; const key = sel.offers.join(','); - // New offers open the window by themselves, but only after the board has stopped moving (the last move's hop, - // the 이의있음! call, `blocked`) so nothing pops up over an animation. - const [autoOpen, setAutoOpen] = useState(mine); - const ready = useMotionSettled(autoOpen && mine && !blocked); + // The window belongs to one set of offers: new offers (혼돈 mode's second pick, the 이의있음! redo) start closed. + const [openKey, setOpenKey] = useState(null); + const open = mine && openKey === key; + const setOpen = (on: boolean) => setOpenKey(on ? key : null); + // New offers open the window by themselves, but only after the board has stopped moving (the last move's hop) + // and the 이의있음! call is gone (`blocked`), so nothing pops up over an animation. + const [autoKey, setAutoKey] = useState(mine ? key : null); + const ready = useMotionSettled(mine && autoKey === key && !blocked); useEffect(() => { setChoice(sel.forced); setTarget(''); - if (mine) setAutoOpen(true); + setAutoKey(mine ? key : null); }, [key]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!ready) return; - setOpen(true); - setAutoOpen(false); - }, [ready]); + setOpenKey(key); + setAutoKey(null); + }, [ready]); // eslint-disable-line react-hooks/exhaustive-deps const tierText = { start: '범용 + 시작 전용', mid: '범용 + 중간 전용', final: '범용 + 마무리 전용' }[sel.tier]; const targets = choice === 'detective' ? sel.detectiveTargets : choice === 'delivery' ? sel.deliveryTargets : []; const needTarget = choice === 'detective' || (choice === 'delivery' && targets.length > 0); diff --git a/apps/web/src/lib/motion.ts b/apps/web/src/lib/motion.ts index cd635ba..cd4913e 100644 --- a/apps/web/src/lib/motion.ts +++ b/apps/web/src/lib/motion.ts @@ -122,12 +122,10 @@ export function useMotionHold(on: boolean): void { /** The screen must stay still this long (real ms) before results show: bridges the gap between two staged steps. */ export const SETTLE_MS = 220; -/** Never wait longer than this (real ms, at least): a stuck or very long animation must not hide the result. */ -const MAX_WAIT_MS = 12_000; - /** * False while `when` is false; once `when` turns true, becomes true after the game screen has been still for - * `SETTLE_MS` (or after the longest wait). Stays true until `when` turns false again. + * `SETTLE_MS`, however long the animation takes (no time limit: a result never shows over a running animation). + * `maxMs` is only for callers that must show something by a deadline of their own (a round break of a real-time game). */ export function useMotionSettled(when = true, maxMs?: number): boolean { const [settled, setSettled] = useState(false); @@ -141,7 +139,7 @@ export function useMotionSettled(when = true, maxMs?: number): boolean { return; } const start = performance.now(); - const limit = maxMs ?? Math.max(MAX_WAIT_MS, fxMs(8000)); + const limit = maxMs ?? Infinity; let stillSince: number | null = null; let raf = 0; const tick = (now: number) => { @@ -161,7 +159,7 @@ export function useMotionSettled(when = true, maxMs?: number): boolean { /** * `value` as of the last time the game screen stood still: a new value shows only after the animation that goes - * with it has played (a status line saying who won, a score, the result of a throw). `maxMs` caps the wait. + * with it has played (a status line saying who won, a score, the result of a throw). `maxMs`: see useMotionSettled. */ export function useAfterMotionValue(value: T, maxMs?: number): T { const [shown, setShown] = useState(value); diff --git a/apps/web/src/net/socket.ts b/apps/web/src/net/socket.ts index 94e3b2d..5b336d3 100644 --- a/apps/web/src/net/socket.ts +++ b/apps/web/src/net/socket.ts @@ -309,6 +309,10 @@ class GameSocket { useRoom.setState(patch); break; } + case 'deadline': + // A player's screen finished animating: their clock started, so the deadline moved (same view). + if (st.game) useRoom.setState({ game: { ...st.game, deadline: m.deadline } }); + break; case 'reject': if (m.cs === st.pending) useRoom.setState({ pending: null, slow: false }); toast(m.reason, 'error'); diff --git a/apps/web/src/pages/RoomPage.tsx b/apps/web/src/pages/RoomPage.tsx index 7a34ca8..fd3c5ea 100644 --- a/apps/web/src/pages/RoomPage.tsx +++ b/apps/web/src/pages/RoomPage.tsx @@ -676,6 +676,12 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui usePlayArea(playArea); const myTurn = ui.isMyTurn(game.view, me.id); const isPlayer = room.seats.some((s) => s?.user.id === me.id) && game.active !== undefined; + // Tell the server when this screen has finished animating the latest state: my clock starts then, so a choice that + // appears after the animation still gets its whole time. + const settledSeq = useAfterMotionValue(game.seq); + useEffect(() => { + if (isPlayer && room.status === 'playing') socket.send({ t: 'settled', seq: settledSeq }); + }, [settledSeq]); // eslint-disable-line react-hooks/exhaustive-deps const props = { view: game.view, me: me.id, diff --git a/docs/03-realtime-protocol.md b/docs/03-realtime-protocol.md index b0cd746..e3ce8be 100644 --- a/docs/03-realtime-protocol.md +++ b/docs/03-realtime-protocol.md @@ -38,6 +38,7 @@ | `rematch` | — | 게임 끝난 뒤 "한 판 더" 투표(2026-10-11부터 화면은 [한 판 더]로 대기실에 돌아가고 이 메시지는 쓰지 않음) | | `void` | — | 방장: 오류로 멈춘 게임을 무효로 끝내기 | | `sync` | — | 전체 상태 다시 요청 | +| `settled` | `seq` | 내 화면이 게임 상태 `seq`의 움직임을 다 보여 줬음(2026-11-08). 그때부터 내 제한 시간이 흐름(실시간 게임 제외). 한 번도 보내지 않은 화면은 예전처럼 상태가 바뀐 때부터, 보낸 적 있는 화면은 이번 상태를 보고하기 전까지 최대 15초(×1 기준, 게임 속도 배율로 늘고 줆) 기다림 | | `ping` | `ts` | 지연 측정(10초마다) | ### 3.2 서버 → 클라이언트 @@ -46,6 +47,7 @@ | `welcome` | `me`, `serverTime`, `protocol`, `activeRoom?`, `build?` | 연결 직후. `build`는 서버가 내주는 웹 빌드 ID(다르면 "업데이트 내용이 있습니다", 07 §11.1) | | `room` | `seq`, `room: RoomView` | 대기실/자리/옵션/접속 상태 전체 | | `state` | `seq`, `view`, `events`, `active: userId[]`, `deadline: number\|null`, `cs?` | 게임 상태. `cs`는 이 상태를 만든 행동이 내 것일 때만 포함(= 성공 응답) | +| `deadline` | `deadline` | 상태는 그대로이고 마감만 바뀜(누군가의 화면이 `settled`를 보내 그 사람의 제한 시간이 시작됨) | | `reject` | `cs`, `reason` | 내 행동 거절(한국어 이유). 화면은 바꾸지 않고 안내만 표시 | | `chat` | `from`, `text`, `at`, `channel?` | 채팅(마피아 등은 채널 구분) | | `emote` | `from`, `id` | 반응 | diff --git a/docs/07-ui-ux.md b/docs/07-ui-ux.md index 3525974..29f9973 100644 --- a/docs/07-ui-ux.md +++ b/docs/07-ui-ux.md @@ -9,7 +9,7 @@ 6. **기다림을 보여 준다.** 남은 시간 링, "OO님이 생각 중…", 연결 상태. 7. **가볍게.** 장식 이미지 최소, 애니메이션은 짧게(150~250ms), `prefers-reduced-motion` 존중. - 게임 속도(2026-10-14): 코드에 적힌 길이는 그대로 두고, 게임 화면 안의 모든 움직임을 `lib/motion.ts`가 `1.5 ÷ 관리자 게임 속도 배율`배로 늘인다(1배여도 적힌 길이보다 1.5배 천천히). CSS 애니메이션·트랜지션은 `.game-layout` 안에서 `useMotionScope`가 재생 속도(`playbackRate`)를 맞추고, Web Animations는 `fxAnim(...)`, 연출 타이머(배너 유지, 다음 단계, 날아가는 복사본 정리, 숫자 세기)는 `fxMs(ms)`로 감싼다. 채팅 칸과 `role="timer"`(남은 시간 막대)는 실제 시간이라 빼고, 주사위 숫자 깜빡임 간격·그림 스트림·두 번 눌러 확인하는 창도 그대로. - - 결과는 움직임 다음(2026-11-08): 결과 창, 위쪽 상태 줄, 게임 안의 결과 팝업·배너·점수는 판이 다 움직인 뒤에 나온다. `lib/motion.ts`의 `motionBusy`(끝이 있는 CSS·Web Animation이 돌고 있거나 `useMotionHold`가 잡고 있으면 움직이는 중), `useMotionSettled`/``(0.22초 동안 멈춰 있으면 보여 줌, 최대 12초), `useAfterMotionValue`(멈춘 뒤에 값을 바꿈)를 쓴다. 타이머로 한 단계씩 보여 주는 연출은 `useMotionHold`로 잡아 둔다. 실시간 게임(할리갈리·도블·사과 게임·그림 맞히기)은 상태 줄을 바로 바꾼다(`liveStatus`). + - 결과는 움직임 다음(2026-11-08): 결과 창, 위쪽 상태 줄, 게임 안의 결과 팝업·배너·점수는 판이 다 움직인 뒤에 나온다. `lib/motion.ts`의 `motionBusy`(끝이 있는 CSS·Web Animation이 돌고 있거나 `useMotionHold`가 잡고 있으면 움직이는 중), `useMotionSettled`/``(0.22초 동안 멈춰 있으면 보여 줌, 움직임이 아무리 길어도 기다림), `useAfterMotionValue`(멈춘 뒤에 값을 바꿈)를 쓴다. 타이머로 한 단계씩 보여 주는 연출은 `useMotionHold`로 잡아 둔다. 실시간 게임(할리갈리·도블·사과 게임·그림 맞히기)은 상태 줄을 바로 바꾼다(`liveStatus`). 연출 뒤에 나오는 선택 창도 제한 시간을 다 쓸 수 있게, 각자의 화면이 움직임을 다 보여 주면 서버에 `settled`를 보내고 그 사람의 제한 시간은 그때부터 흐른다(03 §3.1, 실시간 게임 제외). 8. **한눈에 들어오게 (2026-10-09, "한 화면에 정보가 너무 많다" 피드백).** 참고: NN/g 점진적 공개(자주 쓰는 것만 첫 단계, 나머지는 이름이 분명한 두 번째 단계, 최대 2단계), 토스 "한 화면 한 가지", Board Game Arena 화면 지침(판이 가운데, 정보는 묶어서, 드문 정보는 버튼·접기 뒤로), Hick의 법칙(고를 것이 많으면 묶음 탭으로 나눈다). - 같은 정보를 두 곳에 두지 않는다(방 안에서는 사이트 메뉴를 숨기고 방 막대 한 줄만, 대기실의 규칙 전문은 [📖 규칙]으로). - 목록 카드는 이름 + 한 줄 정보만. 설명·난이도는 들어간 다음 화면에서. diff --git a/e2e/motion.e2e.ts b/e2e/motion.e2e.ts new file mode 100644 index 0000000..0725251 --- /dev/null +++ b/e2e/motion.e2e.ts @@ -0,0 +1,223 @@ +/** + * E2E: results wait for the animation (2026-11-08, "애니메이션 전부 보고나서 결과"). + * - 윷놀이: something on the board moves for 30 s after the winning move; the result window waits for all of it. + * - 바퀴벌레 포커: the call that ends the game — the end table / result never show while its animation still runs. + * - 증강 윷놀이 이의있음!: the redo selection opens only after the full-screen call has gone. + * - 다빈치 코드 at ×1/8: after a correct guess the 계속/멈추기 choice appears after the long flip, and the server + * still gives the full time for it (the clock starts when the screen has settled), so the player can stop. + * Run: bun e2e/motion.e2e.ts (needs apps/web/dist built) + */ +import { chromium, type Page } from 'playwright-core'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { loadConfig } from '../apps/server/src/config'; +import { startServer } from '../apps/server/src/server'; +import { tileOf } from '../packages/games/src/davinci-code'; + +const PORT = Number(process.env.E2E_PORT ?? 4551); +const ORIGIN = `http://localhost:${PORT}`; +const dbDir = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-')); +const app = startServer({ + config: loadConfig({ PORT: String(PORT), DB_PATH: join(dbDir, 'app.db'), PUBLIC_ORIGIN: ORIGIN }), + log: () => {}, + staticDir: join(import.meta.dir, '../apps/web/dist'), +}); +const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true }); +let failed = false; +const step = async (name: string, fn: () => Promise) => { + const t0 = performance.now(); + try { + await fn(); + console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`); + } catch (e) { + failed = true; + console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`); + } +}; +const setSpeed = (gameSpeed: number) => app.settings.setSite({ ...app.settings.getSite(), gameSpeed }, 'e2e'); +let cs = 1_000_000; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AnyRoom = any; + +async function practice(gameId: string, nick: string, options?: (o: Record) => Record): Promise<{ p: Page; room: AnyRoom; me: string; bot: string }> { + const ctx = await browser.newContext({ viewport: { width: 1280, height: 860 }, locale: 'ko-KR' }); + await ctx.addInitScript((g) => localStorage.setItem(`bg:qs:${g}`, '1'), gameId); + const p = await ctx.newPage(); + p.on('pageerror', (e) => console.log(` pageerror: ${e.message}`)); + await p.goto(`${ORIGIN}/g/${gameId}`); + await p.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click(); + await p.getByLabel('내 이름(닉네임)').fill(nick); + await p.getByRole('button', { name: '이 이름으로 시작하기' }).click(); + await p.waitForURL(/\/r\/\d{6}$/); + const room: AnyRoom = app.rooms.get(p.url().split('/').pop()!); + await p.getByLabel('자리').getByText('컴퓨터 1').waitFor(); + if (options) { + room.config.options = options(room.config.options); + room.broadcastRoom(); + } + await p.getByRole('button', { name: '▶ 게임 시작' }).click(); + for (let i = 0; i < 100 && !room.game; i++) await Bun.sleep(50); + const me = room.game.players.find((u: string) => !u.startsWith('bot:'))!; + const bot = room.game.players.find((u: string) => u.startsWith('bot:'))!; + return { p, room, me, bot }; +} + +/** + * Polls until an element matching `sel` (containing `text`, if given) is on screen; fails if it appears while a finite + * animation is still running elsewhere on the page (what lib/motion counts as moving; the shown element's own entrance + * animation, its backdrop and anything that started in the same moment don't count). Returns ms until shown. + */ +async function shownOnlyAfterMotion(p: Page, sel: string, text: string | null, limitMs: number, what: string): Promise { + const t0 = Date.now(); + while (Date.now() - t0 < limitMs) { + const r = await p.evaluate( + ([sel, text]) => { + const hits = [...document.querySelectorAll(sel!)].filter((e) => !text || e.textContent?.includes(text)); + if (!hits.length) return null; + const own = (el: Element) => hits.some((h) => h.contains(el) || h.closest('.sheet-backdrop')?.contains(el)); + return document.getAnimations().filter((a) => { + if (a.playState !== 'running' && !a.pending) return false; + const t = a.effect?.getComputedTiming(); + if (!t || t.endTime === Infinity) return false; + const el = a.effect instanceof KeyframeEffect ? a.effect.target : null; + // started together with what was just shown (the loser's seat turning red): part of it, not before it + if (Number(a.currentTime ?? 0) < 150) return false; + if (!(el instanceof Element)) return true; + return !own(el) && !el.closest('.chat-panel, [role="timer"], .toasts, .toast, [data-motion-free]'); + }).map((a) => { + const el = a.effect instanceof KeyframeEffect ? a.effect.target : null; + return `${(a as CSSAnimation).animationName ?? 'waapi'}@${el instanceof Element ? el.className : '?'}`; + }); + }, + [sel, text] as const, + ); + if (r) { + if (r.length) throw new Error(`${what} showed while animations were still running: ${r.join(', ')} (${Date.now() - t0}ms)`); + return Date.now() - t0; + } + await Bun.sleep(40); + } + throw new Error(`${what} never showed within ${limitMs}ms`); +} + +const RESULT = '[role="dialog"][aria-label="게임 결과"]'; + +try { + await step('윷놀이: 30초짜리 움직임이 끝날 때까지 결과 창이 기다림(시간 상한 없음)', async () => { + setSpeed(1); + const { p, room, me } = await practice('yut', '호랑이', (o) => ({ ...o, augmented: false })); + const s = room.game.state; + const side = s.sideOf[me]; + // My last piece 5 squares before going out; I hold a 모. + let picked: number | null = null; + for (const node of [15, 16, 17, 18, 19]) { + for (const [i, pc] of s.sides[side].pieces.entries()) Object.assign(pc, i === 0 ? { status: 'board', node, trail: [node], lapped: false } : { status: 'done', node: null, trail: [] }); + Object.assign(s, { current: me, turnSide: side, phase: 'move', throwsOwed: 0, pending: ['mo'] }); + const moves = room.def.view(s, me).legalMoves ?? []; + if (moves.some((m: { to: unknown; path: unknown[] }) => m.to === 'goal' && m.path.length >= 4)) { + picked = node; + break; + } + } + if (picked === null) throw new Error('no square 4+ hops from going out'); + room.broadcastState([]); + await Bun.sleep(1500); + // Something on the board keeps moving for 30 s (longer than any time limit the wait used to have, twice over). + await p.evaluate(() => document.querySelector('.yut-board')!.animate([{ opacity: 1 }, { opacity: 0.9 }], { duration: 30_000 })); + room.act(me, cs++, { type: 'MOVE', throwIndex: 0, from: picked }); + const ms = await shownOnlyAfterMotion(p, RESULT, null, 120_000, 'result window'); + if (await p.locator('.yut-hop').count()) throw new Error('result window showed while the piece was still hopping'); + if (ms < 29_000) throw new Error(`result after ${ms}ms, before the 30 s animation ended`); + console.log(` yut: result window ${ms}ms after the winning move`); + await p.context().close(); + }); + + await step('바퀴벌레 포커: 게임을 끝내는 판정 연출이 다 끝난 뒤에 끝 화면·결과 창', async () => { + setSpeed(1); + const { p, room, me, bot } = await practice('cockroach-poker', '호랑이'); + // Whoever takes the next card loses: both fronts already have one too few of every kind it could be. + const s = room.game.state; + const kinds = [...new Set([...Object.values(s.hands as Record).flat()].map((id) => id.slice(0, id.lastIndexOf('-'))))]; + for (const u of [me, bot]) s.fronts[u] = kinds.flatMap((k) => Array.from({ length: s.loseCount - 1 }, (_, i) => `${k}-f${u.length}${i}`)); + room.broadcastState([]); + await Bun.sleep(1500); + // I start: offer a card to the computer; if it comes back to me, I call. + for (let i = 0; i < 600 && !room.game.finished; i++) { + const g = room.game.state; + if (g.round.holder === null && g.round.starter === me) { + const card = g.hands[me][0]; + room.act(me, cs++, { type: 'offer', cardId: card, to: bot, claim: card.slice(0, card.lastIndexOf('-')) }); + } else if (g.round.holder === me && !g.round.peeked) room.act(me, cs++, { type: 'call', call: 'true' }); + await Bun.sleep(100); + } + if (!room.game.finished) throw new Error('the game did not end'); + const ms = await shownOnlyAfterMotion(p, '.cp-table', '게임이 끝났어요', 30_000, 'end of the game'); + await shownOnlyAfterMotion(p, RESULT, null, 30_000, 'result window'); + console.log(` cockroach-poker: end shown ${ms}ms after the last call`); + await p.context().close(); + }); + + await step('증강 윷놀이: 이의있음! 화면이 사라진 뒤에 다시 고르는 창이 열림', async () => { + const { p, room, me, bot } = await practice('yut', '호랑이', (o) => ({ ...o, augmented: true })); + for (let i = 0; i < 100 && !room.game.state.aug?.select; i++) await Bun.sleep(50); + const st = () => room.game.state; + const mine = String(st().sideOf[me]); + const theirs = String(st().sideOf[bot]); + // The computer already picked 이의있음!; I pick last. + const sel = st().aug.select; + sel.offers[mine] = ['shield', 'tiger', 'fog']; + sel.offers[theirs] = []; + sel.left[theirs] = 0; + sel.picks = [{ side: Number(theirs), id: 'objection' }]; + room.broadcastState([]); + if (!(await p.locator('.aug-cards').count())) await p.getByRole('button', { name: '증강 후보 보기' }).click(); + await p.locator('.aug-card').first().click(); + await p.locator('.sheet button.btn-primary').last().click(); + await p.locator('.aug-objection').waitFor({ timeout: 10_000 }); + const t0 = Date.now(); + while (await p.locator('.aug-objection').count()) { + if (await p.getByRole('dialog', { name: /증강 선택/ }).count()) throw new Error('the redo selection opened under the 이의있음! call'); + await Bun.sleep(50); + } + await p.getByRole('dialog', { name: /증강 선택/ }).waitFor({ timeout: 10_000 }); + console.log(` yut-aug: 이의있음! on screen ${Date.now() - t0}ms, then the redo selection`); + await p.context().close(); + }); + + await step('다빈치 코드 ×1/8: 맞힌 뒤 긴 뒤집기 연출 다음에도 계속/멈추기 시간이 남아 있음', async () => { + setSpeed(1 / 8); + const { p, room, me, bot } = await practice('davinci-code', '호랑이'); + if (await p.getByRole('button', { name: '검정 2개 · 흰색 2개' }).count()) { + await p.getByRole('button', { name: '검정 2개 · 흰색 2개' }).click(); + await p.getByRole('button', { name: '이렇게 받기' }).click(); + } + for (let i = 0; i < 600 && !(room.game.state.current === me && room.game.state.phase.kind === 'draw'); i++) await Bun.sleep(100); + if (room.game.state.phase.kind !== 'draw' || room.game.state.current !== me) throw new Error('never my turn to draw'); + await Bun.sleep(1000); + room.act(me, cs++, { type: 'draw', color: room.game.state.pool.black.length ? 'black' : 'white' }); + await Bun.sleep(1000); + const row = room.game.state.rows[bot] as { id: string; revealed: boolean }[]; + const index = row.findIndex((t) => !t.revealed); + room.act(me, cs++, { type: 'guess', target: bot, index, value: tileOf(row[index]!.id).n }); + if (room.game.state.phase.kind !== 'afterCorrect') throw new Error(`guess was not correct (${room.game.state.phase.kind})`); + const t0 = Date.now(); + const stop = p.getByRole('button', { name: '여기서 멈추기' }); + await stop.waitFor({ timeout: 90_000 }); + const waited = Date.now() - t0; + if (waited < 10_000) throw new Error(`the choice showed after ${waited}ms; the flip at ×1/8 should take longer than the 10 s choice time`); + if (room.game.state.phase.kind !== 'afterCorrect' || room.game.state.current !== me) throw new Error('the server timed my choice out while the screen was still animating'); + await Bun.sleep(3000); + await stop.click(); + for (let i = 0; i < 50 && room.game.state.phase.kind === 'afterCorrect'; i++) await Bun.sleep(100); + if (room.game.state.idle[me]) throw new Error('my stop counted as a timeout'); + if (room.game.state.current === me) throw new Error('stopping did not pass the turn'); + console.log(` davinci-code: choice shown ${waited}ms after the guess, stopped 3 s later without a timeout`); + await p.context().close(); + setSpeed(1); + }); +} finally { + await browser.close(); + app.stop?.(); +} +console.log(failed ? 'E2E FAILED' : 'E2E PASSED'); +process.exit(failed ? 1 : 0); diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts index 0cc25fa..8971f2f 100644 --- a/packages/engine/src/types.ts +++ b/packages/engine/src/types.ts @@ -92,6 +92,11 @@ export interface GameDefinition { * secret (아발론's assassin) hide that pull-forward; the room still times out on the effective deadline. */ publicDeadline?(state: S, effective: number | null): number | null; + /** + * Real-time game (할리갈리, 도블, 사과 게임, 그림 맞히기): clocks run from the moment the state changes. In other games a + * player's clock starts once their screen has finished animating the change (client `settled`, room `revealExtra`). + */ + realtime?: boolean; /** Grace period (ms) for disconnected timed players in this state, overriding the room's `graceSec`; null = room default. */ disconnectGraceMs?(state: S): number | null; onTimeout(state: S, player: PlayerId): A; diff --git a/packages/games/src/apple/index.ts b/packages/games/src/apple/index.ts index ea040b2..8115e36 100644 --- a/packages/games/src/apple/index.ts +++ b/packages/games/src/apple/index.ts @@ -289,6 +289,7 @@ type Def = GameDefinition; export const apple: Def = { id: 'apple', nameKo: '사과 게임', + realtime: true, minPlayers: 1, maxPlayers: MAX_PLAYERS, stateVersion: 1, diff --git a/packages/games/src/catchmind/index.ts b/packages/games/src/catchmind/index.ts index 0ac130d..cb5dde8 100644 --- a/packages/games/src/catchmind/index.ts +++ b/packages/games/src/catchmind/index.ts @@ -547,6 +547,7 @@ function buildView(s: S, viewer: PlayerId | null, withCanvas: boolean): Catchmin export const catchmind: GameDefinition = { id: 'catchmind', nameKo: '그림 맞히기', + realtime: true, minPlayers: 2, maxPlayers: 10, stateVersion: 1, diff --git a/packages/games/src/dobble/index.ts b/packages/games/src/dobble/index.ts index 6feb0bb..b74d79c 100644 --- a/packages/games/src/dobble/index.ts +++ b/packages/games/src/dobble/index.ts @@ -652,6 +652,7 @@ const SCORE_TEXT: Record string> = { export const dobble: Def = { id: 'dobble', nameKo: '도블', + realtime: true, minPlayers: 2, maxPlayers: 8, stateVersion: 1, diff --git a/packages/games/src/halli-galli/index.ts b/packages/games/src/halli-galli/index.ts index 42ecf3f..ec0d053 100644 --- a/packages/games/src/halli-galli/index.ts +++ b/packages/games/src/halli-galli/index.ts @@ -389,6 +389,7 @@ const LATE_FLIP = '늦었어요! 그 사이에 카드가 바뀌었어요.'; export const halliGalli: GameDefinition = { id: 'halli-galli', nameKo: '할리갈리', + realtime: true, minPlayers: 2, maxPlayers: 6, stateVersion: 1, diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts index d3d15d6..6f68da8 100644 --- a/packages/shared/src/protocol.ts +++ b/packages/shared/src/protocol.ts @@ -40,6 +40,8 @@ export const ClientMessage = z.discriminatedUnion('t', [ z.object({ t: z.literal('rematch') }), z.object({ t: z.literal('void') }), z.object({ t: z.literal('sync') }), + /** This screen has finished animating the game state `seq` (the player's turn clock starts now). */ + z.object({ t: z.literal('settled'), seq: z.number().int().min(0) }), z.object({ t: z.literal('ping'), ts: z.number() }), ]); export type ClientMessage = z.infer; diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index d8a9bd4..b20e465 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -123,6 +123,8 @@ export type ServerMessage = } /** Events of streaming actions (e.g. drawing), relayed without a full view (docs/games/catchmind.md §5.5). */ | { t: 'stream'; seq: number; events: unknown[]; cs?: number } + /** The game's deadline moved without a state change (a player's screen finished animating: their clock started). */ + | { t: 'deadline'; deadline: number | null } | { t: 'reject'; cs: number; reason: string } /** `replay`: an earlier line resent on (re)joining, so the client shows it without the chat sound. */ | { t: 'chat'; from: PublicUser | null; text: string; at: number; channel?: string; replay?: true }