제한 시간 보정 2: 같은 마감 안에서는 투표로 답할 사람이 줄어도 준 시간 유지, 마감은 남은 답할 사람 중 가장 늦은 화면 기준, 자체 시계를 쓰는 게임도 늘어난 마감을 표시
- room: reveal 단계 키를 게임 마감만으로, clockExtra = max(본인, 답할 사람들) - 라이어·마피아·아발론 시계, 뱅 반응·차례 타이머, 바둑 계가·마작 울기 타이머가 방 마감(연출 시간 포함)을 따름 - 아발론 암살 마감: 당겨진 마감은 숨기고 늘어난 마감은 보여 줌(무제한이면 그대로 숨김) - 테스트: 공통 재투표(대표자 A·느린 B·A 투표 후 유지), e2e 라이어 화면 시계 = 방 마감 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -107,6 +107,7 @@ describe('Room timers', () => {
|
||||
room.settled('B', room.seq);
|
||||
room.clearTimer();
|
||||
// A plays; B (to move) has not reported this new state yet
|
||||
clock.advance(100); // a moment later (a new step has a new clock)
|
||||
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
|
||||
room.clearTimer();
|
||||
const base = clock.now() + 10_000;
|
||||
@@ -127,6 +128,7 @@ describe('Room timers', () => {
|
||||
room.start('A');
|
||||
room.settled('A', room.seq);
|
||||
room.settled('B', room.seq);
|
||||
clock.advance(100); // a moment later (a new step has a new clock)
|
||||
room.act('A', 1, (room.def.legalActions!(room.game!.state, 'A') as unknown[])[0]);
|
||||
room.clearTimer();
|
||||
const base = clock.now() + 10_000;
|
||||
@@ -399,6 +401,7 @@ describe('Room clocks after the animation (shared steps)', () => {
|
||||
room.start('A');
|
||||
room.settled('A', room.seq);
|
||||
room.settled('B', room.seq);
|
||||
clock.advance(100); // a moment later (a new step has a new clock)
|
||||
room.act('A', 1, { type: 'go' }); // → only B answers now, A is the timed stand-in
|
||||
room.clearTimer();
|
||||
const base = clock.now() + 10_000;
|
||||
@@ -426,4 +429,44 @@ describe('Room clocks after the animation (shared steps)', () => {
|
||||
room.clearTimer();
|
||||
expect((room.game!.state as any).chats).toBe(1);
|
||||
});
|
||||
// A re-vote: A and B both vote under one shared clock that the room times through A.
|
||||
const revote: AnyGameDefinition = {
|
||||
...guess,
|
||||
id: 'revote',
|
||||
actionSchema: z.object({ type: z.enum(['go', 'vote', 'chat']) }),
|
||||
setup: ({ players, now }) => ({ players, step: 'start', deadlineAt: now + 10_000, voted: [] as string[], chats: 0 }),
|
||||
apply: (s: any, p, a: any, { now }) => ({
|
||||
state: a.type === 'go' ? { ...s, step: 'vote', deadlineAt: now + 10_000 } : a.type === 'vote' ? { ...s, voted: [...s.voted, p] } : { ...s, chats: s.chats + 1 },
|
||||
events: [],
|
||||
}),
|
||||
activePlayers: (s: any) => (s.step === 'vote' ? s.players.filter((p: string) => !s.voted.includes(p)) : s.players),
|
||||
timeoutPlayers: (s: any) => (s.step === 'vote' ? [s.players[0]] : s.players),
|
||||
};
|
||||
|
||||
test('a shared vote: the clock waits for the slowest voter\'s screen, and someone voting keeps that time', () => {
|
||||
const { room, clock, conn } = harness({ revote });
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.start('A');
|
||||
room.settled('A', room.seq);
|
||||
room.settled('B', room.seq);
|
||||
clock.advance(100); // a moment later (a new step has a new clock)
|
||||
room.act('A', 1, { type: 'go' });
|
||||
room.clearTimer();
|
||||
const base = clock.now() + 10_000;
|
||||
clock.advance(220);
|
||||
room.settled('A', room.seq); // A (also the timed stand-in) is done in 0.22 s …
|
||||
clock.advance(5_780);
|
||||
room.settled('B', room.seq); // … B only after 6 s: the shared clock gives everybody those 6 s
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 6_000);
|
||||
expect(a.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
|
||||
// A votes: only B is left to answer, same clock: still 6 s more.
|
||||
room.act('A', 2, { type: 'vote' });
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 6_000);
|
||||
expect((b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number }).deadline).toBe(base + 6_000);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1168,22 +1168,22 @@ export class Room {
|
||||
return provisional ? Math.min(cap, Math.max(0, this.now() - r.at)) : cap;
|
||||
}
|
||||
|
||||
/** What a step is: its clock and who acts / is timed in it. */
|
||||
/**
|
||||
* What a step is: its clock. Players answering one by one inside a shared clock (votes) or a chat line keep the
|
||||
* time already given; a new clock (next turn, next phase) is a new step.
|
||||
*/
|
||||
private revealKey(): string {
|
||||
const g = this.game!;
|
||||
const def = this.def;
|
||||
return JSON.stringify([def.deadline?.(g.state) ?? null, def.activePlayers(g.state), def.timeoutPlayers?.(g.state) ?? null]);
|
||||
return JSON.stringify(this.def.deadline?.(this.game!.state) ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra time on `u`'s clock. A player who has to answer gets their own screen's animation time; a player timed for
|
||||
* a step others answer (the room times one stand-in for a shared clock) gets the slowest answerer's, so the
|
||||
* people who really answer are never cut short by someone else's faster screen.
|
||||
* Extra time on `u`'s clock: the slowest screen among the players who still have to answer (and `u`). A shared
|
||||
* clock (a vote, a stand-in the room times for everybody) thus never cuts short someone whose screen is still
|
||||
* animating because another screen was faster.
|
||||
*/
|
||||
private clockExtra(u: string, provisional = false): number {
|
||||
const answer = this.def.activePlayers(this.game!.state);
|
||||
if (answer.includes(u)) return this.revealExtra(u, provisional);
|
||||
return Math.max(0, ...answer.map((p) => this.revealExtra(p, provisional)));
|
||||
return Math.max(this.revealExtra(u, provisional), ...answer.map((p) => this.revealExtra(p, provisional)));
|
||||
}
|
||||
|
||||
/** A player's screen finished animating the state `seq` (or a later one): their clock starts now. */
|
||||
|
||||
@@ -506,7 +506,7 @@ function ScoreTable({ score, heading }: { score: ScoreBreakdown; heading?: boole
|
||||
);
|
||||
}
|
||||
|
||||
function ScoringPanel({ view: v, act, pending }: { view: BadukView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function ScoringPanel({ view: v, act, pending, deadline }: { view: BadukView; act: (a: unknown) => void; pending: boolean; deadline: number | null }) {
|
||||
const [confirmResume, setConfirmResume] = useState(false);
|
||||
const sc = v.scoring!;
|
||||
const p = sc.preview;
|
||||
@@ -516,7 +516,7 @@ function ScoringPanel({ view: v, act, pending }: { view: BadukView; act: (a: unk
|
||||
<div className="card stack" style={{ padding: 14, gap: 10 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong style={{ fontSize: '1.1rem' }}>사석 확인</strong>
|
||||
<TurnTimer deadline={sc.deadlineAt} totalMs={sc.durationMs} mine={!!mine && !sc.agreed[mine]} size={40} />
|
||||
<TurnTimer deadline={sc.deadlineAt === null ? null : Math.max(sc.deadlineAt, deadline ?? sc.deadlineAt)} totalMs={sc.durationMs} mine={!!mine && !sc.agreed[mine]} size={40} />
|
||||
</div>
|
||||
<p className="small" style={{ margin: 0 }}>
|
||||
대국이 멈췄어요. 판 위의 <strong>죽은 돌</strong>을 눌러 ✕ 표시를 맞춘 뒤 두 사람 모두 <strong>동의</strong>하면 계가가 끝나요. 처음 표시는 컴퓨터의 추정이라 틀릴 수 있어요.
|
||||
@@ -585,7 +585,7 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
{/* The counted score and the result show once the 계가 banner / territory marks / winner banner have played. */}
|
||||
{v.phase === 'scoring' && (
|
||||
<AfterMotion>
|
||||
<ScoringPanel view={v} act={act} pending={pending} />
|
||||
<ScoringPanel view={v} act={act} pending={pending} deadline={deadline} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.phase === 'finished' && v.result?.score && (
|
||||
|
||||
@@ -374,6 +374,7 @@ function Seat({
|
||||
mark,
|
||||
onPick,
|
||||
style,
|
||||
shift,
|
||||
}: {
|
||||
p: PlayerView;
|
||||
v: BangView;
|
||||
@@ -382,6 +383,8 @@ function Seat({
|
||||
mark: TargetMark | null;
|
||||
onPick: (id: string) => void;
|
||||
style?: CSSProperties;
|
||||
/** How much later than its own the room times this table (see BangBoard). */
|
||||
shift: number;
|
||||
}) {
|
||||
const u = userOf(players, p.id);
|
||||
const r = v.reactions.find((x) => x.who === p.id);
|
||||
@@ -389,9 +392,9 @@ function Seat({
|
||||
const alive = useAfterMotionValue(p.alive);
|
||||
const role = shownRole(p, v, me);
|
||||
const timer = r ? (
|
||||
<TurnTimer deadline={r.deadline} totalMs={v.reactionTotalMs} mine={p.id === me} size={26} />
|
||||
<TurnTimer deadline={r.deadline === null ? null : r.deadline + shift} totalMs={v.reactionTotalMs} mine={p.id === me} size={26} />
|
||||
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
||||
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
<TurnTimer deadline={v.turnDeadline === null ? null : v.turnDeadline + shift} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
) : null;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!alive ? ' dead' : ''}`;
|
||||
const body = (
|
||||
@@ -820,7 +823,7 @@ function DrawPanel({ prompt, act, pending, players }: { prompt: Extract<Prompt,
|
||||
|
||||
// ---------------------------------------------------------------- reaction prompt
|
||||
|
||||
function PromptModal({ v, act, pending, players }: { v: BangView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
function PromptModal({ v, act, pending, players, shift }: { v: BangView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser>; shift: number }) {
|
||||
const my = v.my!;
|
||||
const p = my.prompt;
|
||||
const [picked, setPicked] = useState<string[]>([]);
|
||||
@@ -836,7 +839,7 @@ function PromptModal({ v, act, pending, players }: { v: BangView; act: (a: unkno
|
||||
}, [p?.kind]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
if (!p || p.kind === 'discard' || p.kind === 'draw') return null;
|
||||
const r = v.reactions.find((x) => x.who === v.me);
|
||||
const timer = r ? <TurnTimer deadline={r.deadline} totalMs={v.reactionTotalMs} mine size={44} /> : null;
|
||||
const timer = r ? <TurnTimer deadline={r.deadline === null ? null : r.deadline + shift} totalMs={v.reactionTotalMs} mine size={44} /> : null;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
const hand = my.hand;
|
||||
const sidBox = my.canSidHeal && (
|
||||
@@ -1056,8 +1059,13 @@ function logText(e: LogEntry, players: Record<string, PublicUser>): string {
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>) {
|
||||
function BangBoard({ view: v, me, players, act, pending, deadline }: BoardProps<BangView>) {
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
// The room's deadline is the game's (the earliest reaction, else the turn) plus the time the screens took to finish
|
||||
// animating: every clock on the table moves by that much.
|
||||
const ds = v.reactions.flatMap((r) => (r.deadline === null ? [] : [r.deadline]));
|
||||
const own = v.winner ? null : ds.length ? Math.min(...ds) : v.reactions.length ? null : v.turnDeadline;
|
||||
const shift = own !== null && deadline !== null ? Math.max(0, deadline - own) : 0;
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
@@ -1110,6 +1118,7 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
me={me}
|
||||
mark={markOf(p.id)}
|
||||
onPick={pick}
|
||||
shift={shift}
|
||||
style={{ '--x': `${50 + 41 * Math.cos(ang)}%`, '--y': `${50 + 37 * Math.sin(ang)}%`, order: rel } as CSSProperties}
|
||||
/>
|
||||
);
|
||||
@@ -1120,7 +1129,7 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
{/* A reaction / choice window opens once the card that caused it has landed (it mounts then, so focus works). */}
|
||||
{v.my && (
|
||||
<AfterMotion key={v.my.prompt?.kind} when={!!v.my.prompt && v.my.prompt.kind !== 'discard' && v.my.prompt.kind !== 'draw'}>
|
||||
<PromptModal v={v} act={act} pending={pending} players={players} />
|
||||
<PromptModal v={v} act={act} pending={pending} players={players} shift={shift} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
|
||||
@@ -834,7 +834,7 @@ function useLiarFx(v: LiarView, me: string | null, players: Record<string, Publi
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>) {
|
||||
function LiarBoard({ view: v, me, players, act, pending, deadline }: BoardProps<LiarView>) {
|
||||
// The room chat is closed while playing, so the 토론 chat lines play the chat sound.
|
||||
useChatSound(v.chat.at(-1)?.n);
|
||||
const ph = v.phase;
|
||||
@@ -881,7 +881,8 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{/* The room's deadline is the phase clock plus the time the screens took to finish animating (it only moves later). */}
|
||||
<Clock endsAt={ph.endsAt === null ? null : Math.max(ph.endsAt, deadline ?? ph.endsAt)} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <WordCard v={v} always={finalShown} />}
|
||||
</section>
|
||||
<News v={v} players={players} shownN={shownN} finalShown={finalShown} />
|
||||
|
||||
@@ -883,7 +883,7 @@ function useShownEvents(v: MafiaView): PublicEvent[] {
|
||||
return useMemo(() => (v.events.at(-1)?.n ?? 0) <= shownN ? v.events : v.events.filter((e) => e.n <= shownN), [v.events, shownN]);
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView>) {
|
||||
function MafiaBoard({ view: v, me, players, act, pending, deadline }: BoardProps<MafiaView>) {
|
||||
// The room chat is closed while playing, so this game's own chat lines play the chat sound.
|
||||
useChatSound(v.chat.at(-1)?.key);
|
||||
const ph = v.phase;
|
||||
@@ -956,7 +956,8 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{/* The room's deadline is the phase clock plus the time the screens took to finish animating (it only moves later). */}
|
||||
<Clock endsAt={ph.endsAt === null ? null : Math.max(ph.endsAt, deadline ?? ph.endsAt)} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <RoleCard role={my.role} mates={my.mates} players={players} always={!!v.winner || !actV.my!.alive} />}
|
||||
</section>
|
||||
<News v={shownV} players={players} />
|
||||
|
||||
@@ -738,12 +738,12 @@ function MyArea({
|
||||
)}
|
||||
{riichiMode && <p className="mj-hint">밝은 패를 버리면 리치예요. 리치하면 1,000점을 공탁에 내고, 그다음부터는 쯔모한 패만 버려요.</p>}
|
||||
{!myTurn && v.phase === 'playing' && v.turn !== null && v.stage !== 'claim' && <p className="mj-hint muted">{nick(players, v.seats[v.turn]!.id)}님 차례예요.</p>}
|
||||
<ClaimPanel v={v} my={my} act={act} pending={pending} players={players} />
|
||||
<ClaimPanel v={v} my={my} act={act} pending={pending} players={players} deadline={deadline} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
function ClaimPanel({ v, my, act, pending, players, deadline }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
const c = my.claim;
|
||||
const beginner = my.prefs.beginner && v.options.beginnerMode;
|
||||
const [chiPick, setChiPick] = useState(false);
|
||||
@@ -780,7 +780,7 @@ function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyVi
|
||||
{from}님이 {what} {tileShort(c.tile)}
|
||||
</strong>
|
||||
</span>
|
||||
<TurnTimer deadline={c.deadline} totalMs={c.totalMs} mine size={40} />
|
||||
<TurnTimer deadline={c.deadline === null ? null : Math.max(c.deadline, deadline ?? c.deadline)} totalMs={c.totalMs} mine size={40} />
|
||||
</div>
|
||||
<div className="mj-actions">
|
||||
{c.ron && (
|
||||
|
||||
@@ -39,7 +39,12 @@ 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<string, unknown>) => Record<string, unknown>): Promise<{ p: Page; room: AnyRoom; me: string; bot: string }> {
|
||||
async function practice(
|
||||
gameId: string,
|
||||
nick: string,
|
||||
options?: (o: Record<string, unknown>) => Record<string, unknown>,
|
||||
bots = 1,
|
||||
): 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();
|
||||
@@ -55,6 +60,10 @@ async function practice(gameId: string, nick: string, options?: (o: Record<strin
|
||||
room.config.options = options(room.config.options);
|
||||
room.broadcastRoom();
|
||||
}
|
||||
for (let i = 1; i < bots; i++) {
|
||||
await p.getByRole('button', { name: '🤖 컴퓨터 넣기' }).first().click();
|
||||
await p.getByLabel('자리').getByText(`컴퓨터 ${i + 1}`).waitFor();
|
||||
}
|
||||
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:'))!;
|
||||
@@ -228,6 +237,34 @@ try {
|
||||
await p.context().close();
|
||||
setSpeed(1);
|
||||
});
|
||||
|
||||
await step('라이어 게임: 연출이 끝난 만큼 늘어난 마감이 화면 시계에도 그대로', async () => {
|
||||
const { p, room, me } = await practice('liar', '호랑이', undefined, 2);
|
||||
// My screen is made to look 6 s slow to finish each step: the room gives 6 s more, and my clock must show it.
|
||||
const report = room.settled.bind(room);
|
||||
room.settled = (u: string, seq: number) => {
|
||||
if (u === me && room.reveal && !room.reveal.done.has(u)) room.reveal.at -= 6_000;
|
||||
return report(u, seq);
|
||||
};
|
||||
let checked = 0;
|
||||
for (let i = 0; i < 400 && checked < 3; i++) {
|
||||
await Bun.sleep(250);
|
||||
const ph = room.game?.state?.phase;
|
||||
const done = room.reveal?.done.get(me);
|
||||
if (!ph || ph.endsAt == null || done === undefined || Date.now() - done < 1_000) continue;
|
||||
const label = (await p.locator('.lg-clock[role="timer"]').first().getAttribute('aria-label').catch(() => null)) ?? '';
|
||||
const shown = Number(label.match(/(\d+)초/)?.[1] ?? NaN);
|
||||
const left = (room.publicDeadline() - Date.now()) / 1000;
|
||||
const plain = (ph.endsAt - Date.now()) / 1000;
|
||||
if (room.reveal?.done.get(me) !== done || room.game.state.phase !== ph) continue; // the step moved on meanwhile
|
||||
if (left - plain < 5) throw new Error(`room deadline not moved: ${left.toFixed(1)}s vs phase ${plain.toFixed(1)}s`);
|
||||
if (!(Math.abs(shown - left) <= 1.5)) throw new Error(`clock says ${shown}s, the room has ${left.toFixed(1)}s (phase alone ${plain.toFixed(1)}s)`);
|
||||
checked++;
|
||||
}
|
||||
if (checked < 3) throw new Error(`only ${checked} clock checks happened`);
|
||||
console.log(' liar: the clock follows the moved deadline (3 checks)');
|
||||
await p.context().close();
|
||||
});
|
||||
} finally {
|
||||
await browser.close();
|
||||
app.stop?.();
|
||||
|
||||
Reference in New Issue
Block a user