Compare commits
6 Commits
0cbda8f551
...
f793391b79
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f793391b79 | ||
|
|
bc8cb7ae8c | ||
|
|
fa53175f51 | ||
|
|
4e0eb4d52c | ||
|
|
f18909c44f | ||
|
|
72f4f06e21 |
@@ -61,6 +61,86 @@ 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
|
||||
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;
|
||||
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('a deadline moved by a screen that reported before is told to every client (omok)', () => {
|
||||
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 } } });
|
||||
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;
|
||||
const sent = b.msgs.filter((m) => m.t === 'state').at(-1) as { deadline: number };
|
||||
expect(sent.deadline).toBe(base);
|
||||
clock.advance(2_000);
|
||||
room.settled('B', room.seq);
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 2_000);
|
||||
for (const c of [a, b]) expect(c.msgs.at(-1)).toEqual({ t: 'deadline', deadline: 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');
|
||||
@@ -289,3 +369,104 @@ describe('Room chat (2026-10-13)', () => {
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Room clocks after the animation (shared steps)', () => {
|
||||
// Like 라이어 게임's last guess: everybody votes, then only the liar (B) answers, while the room times a stand-in (A).
|
||||
const guess: AnyGameDefinition = {
|
||||
id: 'guess',
|
||||
nameKo: '맞히기',
|
||||
minPlayers: 2,
|
||||
maxPlayers: 2,
|
||||
stateVersion: 1,
|
||||
defaultOptions: {},
|
||||
optionsSchema: z.object({}),
|
||||
actionSchema: z.object({ type: z.enum(['go', 'chat']) }),
|
||||
setup: ({ players, now }) => ({ players, step: 'vote', deadlineAt: now + 10_000, chats: 0 }),
|
||||
validate: () => ({ ok: true }),
|
||||
apply: (s: any, _p, a: any, { now }) => ({ state: a.type === 'go' ? { ...s, step: 'guess', deadlineAt: now + 10_000 } : { ...s, chats: s.chats + 1 }, events: [] }),
|
||||
view: (s) => s,
|
||||
activePlayers: (s: any) => (s.step === 'guess' ? [s.players[1]] : s.players),
|
||||
timeoutPlayers: (s: any) => (s.step === 'guess' ? [s.players[0]] : s.players),
|
||||
deadline: (s: any) => s.deadlineAt,
|
||||
onTimeout: () => ({ type: 'chat' }),
|
||||
result: () => null,
|
||||
};
|
||||
|
||||
test('the stand-in\'s clock waits for the real answerer\'s screen, and a chat line keeps the time given', () => {
|
||||
const { room, clock, conn } = harness({ guess });
|
||||
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' }); // → only B answers now, A is the timed stand-in
|
||||
room.clearTimer();
|
||||
const base = clock.now() + 10_000;
|
||||
clock.advance(1_000);
|
||||
room.settled('A', room.seq); // A's screen is quick: that must not start B's clock
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 15_000);
|
||||
clock.advance(5_000);
|
||||
room.settled('B', room.seq); // B's screen took 6 s
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 6_000);
|
||||
expect(b.msgs.at(-1)).toEqual({ t: 'deadline', deadline: base + 6_000 });
|
||||
// A chat line in the same step keeps B's 6 s.
|
||||
clock.advance(1_000);
|
||||
room.act('A', 2, { type: 'chat' });
|
||||
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);
|
||||
room.settled('B', room.seq);
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(base + 6_000);
|
||||
// B still gets the whole 10 s from when the screen settled: nothing fires a moment before that.
|
||||
clock.advance(base + 6_000 - clock.now() - 1);
|
||||
room.onTimer();
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,15 @@ export class Room {
|
||||
/** When each person last said they were typing (to drop repeats within a second). */
|
||||
private typingAt = new Map<string, number>();
|
||||
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<string, number>; key: string } | null = null;
|
||||
/** The deadline last sent to the clients (state / deadline messages), so a moved deadline is always told. */
|
||||
private sentDeadline: number | null = null;
|
||||
/** Players whose screens report `settled` (pages from before 2026-11-08 don't: their clocks run as before). */
|
||||
private settles = new Set<string>();
|
||||
private readonly now: () => number;
|
||||
/** Plays the computer players' moves (docs/06 §12). */
|
||||
readonly bots: BotDriver;
|
||||
@@ -462,7 +476,7 @@ export class Room {
|
||||
view,
|
||||
events: [],
|
||||
active: this.game.finished ? [] : def.activePlayers(this.game.state),
|
||||
deadline: this.game.finished ? null : this.effectiveDeadline(),
|
||||
deadline: (this.sentDeadline = this.game.finished ? null : this.publicDeadline()),
|
||||
...(cs !== undefined ? { cs } : {}),
|
||||
};
|
||||
}
|
||||
@@ -474,6 +488,10 @@ export class Room {
|
||||
|
||||
private broadcastState(events: unknown[], actor?: string, cs?: number): void {
|
||||
if (!this.game) return;
|
||||
// A change that leaves the step as it was (a chat line, a move inside the same shared clock) keeps the time
|
||||
// already given for the step's animation; a new step (new clock, new players to act) starts a new reveal.
|
||||
const key = this.revealKey();
|
||||
if (!this.reveal || this.reveal.key !== key) this.reveal = { seq: this.seq, at: this.now(), done: new Map(), key };
|
||||
let spectatorMsg: ServerMessage | null = null;
|
||||
for (const c of this.conns.values()) {
|
||||
let msg: ServerMessage | null;
|
||||
@@ -1128,8 +1146,61 @@ export class Room {
|
||||
|
||||
// ---------------------------------------------------------------- timers
|
||||
|
||||
/** The deadline clients see (`def.publicDeadline`, default the effective one); timers use `effectiveDeadline`. */
|
||||
private publicDeadline(): number | null {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
return JSON.stringify(this.def.deadline?.(this.game!.state) ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
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. */
|
||||
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;
|
||||
this.settles.add(userId);
|
||||
r.done.set(userId, this.now());
|
||||
this.scheduleTimer();
|
||||
const after = this.publicDeadline();
|
||||
if (after === this.sentDeadline) return;
|
||||
this.sentDeadline = after;
|
||||
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;
|
||||
@@ -1139,7 +1210,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.clockExtra(u, provisional);
|
||||
const p = this.presence.get(u);
|
||||
if (p && !p.connected) {
|
||||
const grace = p.since + graceMs;
|
||||
@@ -1183,7 +1254,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.clockExtra(u);
|
||||
const p = this.presence.get(u);
|
||||
if (p && !p.connected) {
|
||||
const grace = p.since + graceMs;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs } from '../../lib/motion';
|
||||
|
||||
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
|
||||
const ROWS = 10;
|
||||
@@ -553,16 +553,17 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
|
||||
<small>합이 10이 되게 사과를 묶어요!</small>
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
|
||||
{/* My final count shows after the last apples have popped. */}
|
||||
<AfterMotion when={!!mine && mine.status === 'stuck' && v.phase === 'playing'}>
|
||||
<div className="ap-over note" role="status">
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개{extraText(mine)} · 끝날 때까지 기다려요
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'done' && v.phase === 'playing' && (
|
||||
</AfterMotion>
|
||||
<AfterMotion when={!!mine && mine.status === 'done' && v.phase === 'playing'}>
|
||||
<div className="ap-over note" role="status">
|
||||
여기까지 했어요! 사과 {mine.score}개{extraText(mine)} · 모두 끝날 때까지 기다려요
|
||||
여기까지 했어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 모두 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
|
||||
</div>
|
||||
@@ -635,22 +636,24 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
{extraText(r)}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
{extraText(r)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -756,6 +759,7 @@ const ui: GameUI<AppleView, AppleOptions> = {
|
||||
Board: AppleBoard,
|
||||
Side: AppleSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { reducedMotion, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
type Color = 'black' | 'white';
|
||||
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
||||
@@ -160,6 +160,9 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
|
||||
// Counting starts / the game ends (for both players and watchers).
|
||||
const prevPhase = useRef(v.phase);
|
||||
// The winner banner waits for the territory marks to finish popping in (held, so the result window waits too).
|
||||
const [endWait, setEndWait] = useState(false);
|
||||
useMotionHold(endWait);
|
||||
useEffect(() => {
|
||||
const before = prevPhase.current;
|
||||
prevPhase.current = v.phase;
|
||||
@@ -168,8 +171,21 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
showBanner('계가', 'blue', '두 사람 모두 패스했어요. 사석을 확인해요');
|
||||
sfx.whoosh();
|
||||
} else if (v.phase === 'finished' && v.result) {
|
||||
const w = v.result.winner;
|
||||
showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', v.result.summaryKo);
|
||||
const r = v.result;
|
||||
const w = r.winner;
|
||||
setEndWait(true);
|
||||
// Marks pop in staggered from the corner (up to 0.9 s) and take 0.32 s each.
|
||||
const t = setTimeout(
|
||||
() => {
|
||||
setEndWait(false);
|
||||
showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', r.summaryKo);
|
||||
},
|
||||
r.score && !reducedMotion() ? fxMs(1250) : 0,
|
||||
);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
setEndWait(false);
|
||||
};
|
||||
}
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -490,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;
|
||||
@@ -500,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>하면 계가가 끝나요. 처음 표시는 컴퓨터의 추정이라 틀릴 수 있어요.
|
||||
@@ -566,18 +582,25 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
<strong>상대가 패스했어요.</strong> 끝내려면 나도 패스하세요. 더 둘 곳이 있으면 계속 둬도 돼요.
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'scoring' && <ScoringPanel view={v} act={act} pending={pending} />}
|
||||
{/* 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} deadline={deadline} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.phase === 'finished' && v.result?.score && (
|
||||
<div className="card stack" style={{ padding: 14, gap: 8 }}>
|
||||
<strong style={{ fontSize: '1.15rem' }}>{v.result.summaryKo}</strong>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 800, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<span className="sr-only">{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`}</span>
|
||||
<span aria-hidden>
|
||||
흑 <CountUp to={v.result.score.black.total} live={ended.current.live} /> : 백 <CountUp to={v.result.score.white.total} live={ended.current.live} />
|
||||
</span>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ padding: 14, gap: 8 }}>
|
||||
<strong style={{ fontSize: '1.15rem' }}>{v.result.summaryKo}</strong>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 800, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<span className="sr-only">{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`}</span>
|
||||
<span aria-hidden>
|
||||
흑 <CountUp to={v.result.score.black.total} live={ended.current.live} /> : 백 <CountUp to={v.result.score.white.total} live={ended.current.live} />
|
||||
</span>
|
||||
</div>
|
||||
<ScoreTable score={v.result.score} heading />
|
||||
</div>
|
||||
<ScoreTable score={v.result.score} heading />
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.phase === 'playing' && v.myColor && (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
@@ -685,6 +708,8 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView;
|
||||
const c = v.clock;
|
||||
const elapsed = active ? Math.max(0, now - c.turnStartedAt) : 0;
|
||||
const mine = id === me;
|
||||
// The capture count goes up once the captured stones have been lifted off the board.
|
||||
const captures = useAfterMotionValue(v.captures[color]);
|
||||
let clock: React.ReactNode = null;
|
||||
let periodSecLeft: number | null = null;
|
||||
if (c.kind === 'byoyomi') {
|
||||
@@ -742,7 +767,7 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView;
|
||||
{mine && <span className="muted small"> (나)</span>}
|
||||
</div>
|
||||
<div className="muted small">
|
||||
{COLOR_KO[color]} · 따낸 돌 {v.captures[color]}
|
||||
{COLOR_KO[color]} · 따낸 돌 {captures}
|
||||
{color === 'white' && v.rules.komi ? ` · 덤 ${v.rules.komi}` : ''}
|
||||
{active ? ' · 두는 중' : ''}
|
||||
{v.phase === 'scoring' && v.scoring?.agreed[color] ? ' · 동의함' : ''}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- names (display names live only here, docs §12)
|
||||
|
||||
@@ -295,7 +295,8 @@ function CardFaceInner({ card, info }: { card: CardFace; info: (typeof CARD_INFO
|
||||
}
|
||||
|
||||
function Hp({ life, max }: { life: number; max: number }) {
|
||||
const n = Math.max(0, life);
|
||||
// Life changes once the shot / beer that caused it has played.
|
||||
const n = Math.max(0, useAfterMotionValue(life));
|
||||
return (
|
||||
<span className="bg-hp" role="img" aria-label={`생명 ${n}/${max}`}>
|
||||
{Array.from({ length: max }, (_, i) => (
|
||||
@@ -373,6 +374,7 @@ function Seat({
|
||||
mark,
|
||||
onPick,
|
||||
style,
|
||||
shift,
|
||||
}: {
|
||||
p: PlayerView;
|
||||
v: BangView;
|
||||
@@ -381,15 +383,20 @@ 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);
|
||||
// A player falls once the shot that downed them has played (the role badge has its own flip, see useBangFx 'dead').
|
||||
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' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!alive ? ' dead' : ''}`;
|
||||
const body = (
|
||||
<>
|
||||
<span className="bg-row nw">
|
||||
@@ -401,10 +408,10 @@ function Seat({
|
||||
{timer}
|
||||
</span>
|
||||
<span className="bg-row nw rc">
|
||||
<RoleBadge role={shownRole(p, v, me)} alive={p.alive} />
|
||||
<RoleBadge role={role} alive={alive} />
|
||||
<span className="bg-char">{p.character ? CHAR_INFO[p.character].name : '캐릭터 고르는 중'}</span>
|
||||
</span>
|
||||
{p.alive ? (
|
||||
{alive ? (
|
||||
<span className="bg-row">
|
||||
<Hp life={p.life} max={p.maxLife} />
|
||||
<span className="bg-cnt" aria-hidden>
|
||||
@@ -438,7 +445,7 @@ function Seat({
|
||||
data-player={p.id}
|
||||
data-fx-seat={p.id}
|
||||
aria-pressed={mark.selected}
|
||||
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
||||
aria-label={`${seatLabel(p, players, me, role)}. 대상으로 고르기`}
|
||||
onClick={() => onPick(p.id)}
|
||||
>
|
||||
{body}
|
||||
@@ -446,7 +453,7 @@ function Seat({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, role) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
@@ -467,6 +474,8 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
const PURPOSE: Record<string, string> = { dynamite: '다이너마이트', jail: '감옥', barrel: '술통', jourdonnais: '주르도네' };
|
||||
const waitingFor = v.reactions.length ? [...new Set(v.reactions.map((r) => r.who))] : [];
|
||||
const last = v.log[v.log.length - 1];
|
||||
// The latest event's text changes once its animation has played.
|
||||
const lastText = useAfterMotionValue(last ? logText(last, players) : '');
|
||||
return (
|
||||
<div className="bg-center">
|
||||
<div className="bg-piles" data-fx="bang-piles">
|
||||
@@ -482,7 +491,7 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
</span>
|
||||
)}
|
||||
{waitingFor.length > 0 && <span className="bg-chip">{waitingFor.map((id) => `${nick(players, id)}님`).join(', ')} 기다리는 중…</span>}
|
||||
{last && <span className="bg-last">{logText(last, players)}</span>}
|
||||
{lastText && <span className="bg-last">{lastText}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -624,6 +633,8 @@ function MyArea({
|
||||
}) {
|
||||
const my = v.my!;
|
||||
const meP = v.players.find((p) => p.id === v.me);
|
||||
// "쓰러졌어요" waits for the shot that downed me.
|
||||
const meAlive = useAfterMotionValue(meP?.alive ?? false);
|
||||
const [multi, setMulti] = useState<string[]>([]);
|
||||
const [sidMode, setSidMode] = useState(false);
|
||||
const [note, setNote] = useState('');
|
||||
@@ -692,7 +703,7 @@ function MyArea({
|
||||
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
||||
<strong>
|
||||
{my.character ? CHAR_INFO[my.character].name : '캐릭터를 고르는 중'}
|
||||
{meP && meP.alive && (
|
||||
{meP && meAlive && (
|
||||
<>
|
||||
{' '}
|
||||
<Hp life={meP.life} max={meP.maxLife} />
|
||||
@@ -707,7 +718,7 @@ function MyArea({
|
||||
</span>
|
||||
{meP && <Equip cards={meP.inPlay} />}
|
||||
</div>
|
||||
{meP && !meP.alive && !v.winner && <strong>쓰러졌어요. 남은 게임을 지켜봐요.</strong>}
|
||||
{meP && !meAlive && !v.winner && <strong>쓰러졌어요. 남은 게임을 지켜봐요.</strong>}
|
||||
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
||||
{meP?.alive && (
|
||||
<HandCards
|
||||
@@ -812,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[]>([]);
|
||||
@@ -828,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 && (
|
||||
@@ -1048,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);
|
||||
@@ -1102,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}
|
||||
/>
|
||||
);
|
||||
@@ -1109,7 +1126,12 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
<Center v={v} players={players} />
|
||||
</div>
|
||||
{v.my && <MyArea v={v} act={act} pending={pending} players={players} sel={sel} setSel={setSel} />}
|
||||
{v.my && <PromptModal v={v} act={act} pending={pending} players={players} />}
|
||||
{/* 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} shift={shift} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -1156,6 +1178,11 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
return place(id);
|
||||
};
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
// The steps below are staged with timers (shots, banners, bumps): results wait until the last one has played.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const stageTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []);
|
||||
|
||||
useNewEntries(
|
||||
keyed,
|
||||
@@ -1389,9 +1416,15 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
case 'end':
|
||||
// The room already plays the win / lose sound.
|
||||
later(at + 300, () => showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner]));
|
||||
t += 300;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (t > 0) {
|
||||
setStaging(true);
|
||||
if (stageTimer.current) clearTimeout(stageTimer.current);
|
||||
stageTimer.current = setTimeout(() => setStaging(false), fxMs(Math.min(t, 3000) + 400));
|
||||
}
|
||||
},
|
||||
30,
|
||||
);
|
||||
@@ -1422,6 +1455,24 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
/** One player in the side list; a fall and the role it shows wait for the shot's animation (like the seat). */
|
||||
function SideRow({ p, v, me, players }: { p: PlayerView; v: BangView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const alive = useAfterMotionValue(p.alive);
|
||||
const role = useAfterMotionValue(shownRole(p, v, me));
|
||||
return (
|
||||
<li className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: alive ? 1 : 0.55 }} aria-label={seatLabel(p, players, me, role)}>
|
||||
<Avatar user={userOf(players, p.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p.id === me ? 800 : 600 }}>
|
||||
{p.isTurn ? '▶ ' : ''}
|
||||
{nick(players, p.id)}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleBadge role={role} alive={alive} />
|
||||
{alive ? <Hp life={p.life} max={p.maxLife} /> : <span className="small">쓰러짐</span>}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
return (
|
||||
<>
|
||||
@@ -1436,34 +1487,27 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.players.map((p) => (
|
||||
<li key={p.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: p.alive ? 1 : 0.55 }} aria-label={seatLabel(p, players, me, shownRole(p, v, me))}>
|
||||
<Avatar user={userOf(players, p.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p.id === me ? 800 : 600 }}>
|
||||
{p.isTurn ? '▶ ' : ''}
|
||||
{nick(players, p.id)}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleBadge role={shownRole(p, v, me)} alive={p.alive} />
|
||||
{p.alive ? <Hp life={p.life} max={p.maxLife} /> : <span className="small">쓰러짐</span>}
|
||||
</li>
|
||||
<SideRow key={p.id} p={p} v={v} me={me} players={players} />
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>{TEAM_KO[v.result.winnerTeam]} 승리</strong>
|
||||
{v.result.ranking.map((id) => {
|
||||
const r = v.result!.players.find((x) => x.id === id)!;
|
||||
return (
|
||||
<span key={id}>
|
||||
{r.won ? '🏆 ' : ''}
|
||||
{nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name}
|
||||
<span className="muted small">{r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>{TEAM_KO[v.result.winnerTeam]} 승리</strong>
|
||||
{v.result.ranking.map((id) => {
|
||||
const r = v.result!.players.find((x) => x.id === id)!;
|
||||
return (
|
||||
<span key={id}>
|
||||
{r.won ? '🏆 ' : ''}
|
||||
{nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name}
|
||||
<span className="muted small">{r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps } from '../types';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
@@ -200,6 +200,24 @@ function useDealQueue(v: BlackjackView) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The cards of `shown` whose fly-in has finished (the screen stood still since they appeared): totals, bust / 블랙잭
|
||||
* tags count only these, so a number never changes while its card is still in the air.
|
||||
*/
|
||||
function useLandedCards(shown: string[]): string[] {
|
||||
const key = shown.join(',');
|
||||
const settled = useAfterMotionValue(key);
|
||||
return settled === key ? shown : settled.split(',').filter((k) => k && shown.includes(k));
|
||||
}
|
||||
|
||||
/** Everyone's chips as of the last still screen: the chip counts change only after the hand's cards have landed. */
|
||||
export function useLandedChips(v: BlackjackView): (id: string) => number {
|
||||
const key = v.seats.map((s) => `${s.id}:${s.chips}`).join(',');
|
||||
const settled = useAfterMotionValue(key);
|
||||
const map = new Map(settled.split(',').filter(Boolean).map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))]));
|
||||
return (id) => map.get(id) ?? v.seats.find((s) => s.id === id)?.chips ?? 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pieces
|
||||
|
||||
function totalOf(cards: string[]): { total: number; soft: boolean } {
|
||||
@@ -235,7 +253,8 @@ function DealtCard({ id, width, anim }: { id: string | null; width: number; anim
|
||||
|
||||
function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; width: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
|
||||
const cards = h.cards.filter((c) => q.shown(c));
|
||||
const done = cards.length === h.cards.length;
|
||||
const landed = useLandedCards(cards);
|
||||
const done = landed.length === h.cards.length;
|
||||
const tag = final && h.outcome ? OUTCOME_KO[h.outcome] : done ? HAND_KO[h.status] : '';
|
||||
const color =
|
||||
h.outcome === 'win' || h.outcome === 'blackjack' || h.outcome === 'bonus' ? '#16a34a' : h.outcome === 'lose' || h.status === 'bust' ? '#dc2626' : h.outcome === 'push' ? '#6b7280' : '#b45309';
|
||||
@@ -247,7 +266,7 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean;
|
||||
))}
|
||||
</div>
|
||||
<div className="meta">
|
||||
<TotalBadge cards={cards} status={h.status} final={done} />
|
||||
<TotalBadge cards={landed} status={h.status} final={done} />
|
||||
<span className="bj-bet" title="건 칩">
|
||||
<ChipIcon size={14} />
|
||||
{h.bet.toLocaleString('ko-KR')}
|
||||
@@ -263,14 +282,14 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean;
|
||||
);
|
||||
}
|
||||
|
||||
function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record<string, PublicUser>; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
|
||||
function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final, chips }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record<string, PublicUser>; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType<typeof useDealQueue>; final: boolean; chips: number }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const isTurn = v.phase === 'playing' && v.turn === seat.id;
|
||||
const style = { ...(pos ? { '--x': `${pos.x}%`, '--y': `${pos.y}%` } : {}), '--mw': `${maxW}px` } as CSSProperties;
|
||||
const hands = seat.hands ?? [];
|
||||
const per = Math.ceil(hands.length / rows);
|
||||
return (
|
||||
<div className={`bj-seat${isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${seat.status !== 'playing' ? ' out' : ''}`} style={style} aria-label={`${u.nickname}${seat.id === me ? '(나)' : ''}, ${formatChips(seat.chips)}`}>
|
||||
<div className={`bj-seat${isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${seat.status !== 'playing' ? ' out' : ''}`} style={style} aria-label={`${u.nickname}${seat.id === me ? '(나)' : ''}, ${formatChips(chips)}`}>
|
||||
{seat.hands ? (
|
||||
<div className="hands">
|
||||
{Array.from({ length: rows }, (_, r) => (
|
||||
@@ -294,7 +313,7 @@ function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat
|
||||
{u.nickname}
|
||||
{seat.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<span className="ch">{seat.chips.toLocaleString('ko-KR')}</span>
|
||||
<span className="ch">{chips.toLocaleString('ko-KR')}</span>
|
||||
{seat.status === 'out' && <span className="small">칩 소진</span>}
|
||||
{seat.status === 'left' && <span className="small">나감</span>}
|
||||
</div>
|
||||
@@ -528,7 +547,7 @@ function Actions({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => v
|
||||
);
|
||||
}
|
||||
|
||||
function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean }) {
|
||||
function Dock({ v, me, players, act, pending, deadline, mine, final, chips }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean; chips: (id: string) => number }) {
|
||||
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||
const u = seat ? userOf(players, seat.id) : null;
|
||||
let main: ReactNode;
|
||||
@@ -597,7 +616,7 @@ function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: Blac
|
||||
<Avatar user={u} size={44} />
|
||||
<span className="nm">{u.nickname} (나)</span>
|
||||
<span className="ch">
|
||||
<ChipIcon size={18} /> {seat.chips.toLocaleString('ko-KR')}
|
||||
<ChipIcon size={18} /> {chips(seat.id).toLocaleString('ko-KR')}
|
||||
</span>
|
||||
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={30} />}
|
||||
</div>
|
||||
@@ -643,11 +662,16 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
const mine = isMyTurn(v, me);
|
||||
const phone = usePhone();
|
||||
const q = useDealQueue(v);
|
||||
// Results (outcome tags, +/-) wait until every card has landed.
|
||||
const final = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy;
|
||||
// Cards still queued (dealt one by one with timers) hold results; then the last fly-in must finish too.
|
||||
useMotionHold(q.busy);
|
||||
const ended = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy;
|
||||
// Results (outcome tags, +/-, banner, 다음 판) wait until every card has landed.
|
||||
const final = useMotionSettled(ended);
|
||||
const chips = useLandedChips(v);
|
||||
const d = v.dealer;
|
||||
const dealerCards = d.cards.map((c) => c ?? holeKey(v)).filter((k) => q.shown(k));
|
||||
const dealerReal = d.cards.filter((c): c is string => !!c && q.shown(c));
|
||||
const dealerLanded = useLandedCards(dealerCards);
|
||||
const dealerReal = dealerLanded.filter((k) => k !== holeKey(v));
|
||||
const slots = seatLayout(v, me);
|
||||
// Table width for fitting cards into each seat's share (phone: my seat a full row, others two per row).
|
||||
const tableRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -707,7 +731,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
prevTurn.current = v.turn;
|
||||
}, [v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const dealerDone = dealerCards.length === d.cards.length;
|
||||
const dealerDone = dealerLanded.length === d.cards.length;
|
||||
const seatEls = slots.map(({ id, x, y, share }) => {
|
||||
const seat = v.seats.find((s) => s.id === id)!;
|
||||
const hands = seat.hands ?? [];
|
||||
@@ -718,7 +742,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
const roomH = (tableH * y) / 100 - (40 + dealerW * 1.4 + 12) - 64;
|
||||
const capH = phone ? 999 : Math.floor((roomH / rows - 50) / 1.4);
|
||||
const width = Math.max(26, Math.min(capH, fitCardWidth(hands, avail, id === me ? myW : otherW, rows)));
|
||||
return <Seat key={id} seat={seat} v={v} me={me} players={players} pos={phone ? null : { x, y }} width={width} rows={rows} maxW={avail} q={q} final={final} />;
|
||||
return <Seat key={id} seat={seat} v={v} me={me} players={players} pos={phone ? null : { x, y }} width={width} rows={rows} maxW={avail} q={q} final={final} chips={chips(id)} />;
|
||||
});
|
||||
return (
|
||||
<div className="bj-wrap">
|
||||
@@ -761,7 +785,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} />
|
||||
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} chips={chips} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard';
|
||||
import { PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { BlackjackBoard, isMyTurn } from './board';
|
||||
import { BlackjackBoard, isMyTurn, useLandedChips } from './board';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
@@ -29,7 +29,9 @@ function statusText(v: BlackjackView, me: string | null, players: Record<string,
|
||||
// ---------------------------------------------------------------- side (standings only; every control is on the board)
|
||||
|
||||
function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
const ranked = [...v.seats].sort((a, b) => b.chips - a.chips);
|
||||
// Chip counts change only once the hand's cards have landed on the board.
|
||||
const chips = useLandedChips(v);
|
||||
const ranked = [...v.seats].sort((a, b) => chips(b.id) - chips(a.id));
|
||||
return (
|
||||
<div className="stack" style={{ gap: 12 }}>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
@@ -42,7 +44,7 @@ function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
{s.status === 'out' && ' (칩 소진)'}
|
||||
{s.status === 'left' && ' (나감)'}
|
||||
</span>
|
||||
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(s.chips)}</span>
|
||||
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(chips(s.id))}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -26,6 +26,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { DieFace, FILL, GOODS_FILL, INK, Pips, SPACE, TileHex, axial, goodsName, hexPoints, monasteryText, tileName } from './hex';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
type M = { a: CobAction; cost: number };
|
||||
type Sel = { kind: 'die'; i: 0 | 1 } | { kind: 'buy' } | { kind: 'pick'; tile: string } | null;
|
||||
@@ -513,7 +514,17 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
const [ask, setAsk] = useState<Ask>(null);
|
||||
const [tab, setTab] = useState<'duchy' | 'depots' | 'others'>('duchy');
|
||||
const [banner, showBanner] = useBanner();
|
||||
// Banners (and their sounds) wait until the placed tile has settled: queued here, played once the board is still.
|
||||
const [due, setDue] = useState<(() => void)[]>([]);
|
||||
const dueReady = useMotionSettled(due.length > 0);
|
||||
useEffect(() => {
|
||||
if (!dueReady) return;
|
||||
for (const f of due) f();
|
||||
setDue([]);
|
||||
}, [dueReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const later = (f: () => void) => setDue((q) => [...q, f]);
|
||||
const myPv = me ? v.players[me] : undefined;
|
||||
const myVp = useAfterMotionValue(myPv?.vp ?? 0);
|
||||
const moves = useMemo(() => moveList(v), [v]);
|
||||
const top = topOf(v);
|
||||
const mineNow = !!v.my;
|
||||
@@ -547,15 +558,19 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
sfx.piece();
|
||||
if (e.p === me) bump(fxEl(`me-${e.space}`));
|
||||
} else if (e.t === 'region' && e.p === me) {
|
||||
sfx.good();
|
||||
showBanner(`+${e.vp}점`, 'green', '구역 완성!');
|
||||
later(() => {
|
||||
sfx.good();
|
||||
showBanner(`+${e.vp}점`, 'green', '구역 완성!');
|
||||
});
|
||||
} else if (e.t === 'colorBonus') {
|
||||
sfx.good();
|
||||
showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`);
|
||||
later(() => {
|
||||
sfx.good();
|
||||
showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`);
|
||||
});
|
||||
} else if (e.t === 'sell') sfx.coin();
|
||||
else if (e.t === 'ship') sfx.whoosh();
|
||||
else if (e.t === 'phase' && e.phase > 0) showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요');
|
||||
else if (e.t === 'soloTarget') showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`);
|
||||
else if (e.t === 'phase' && e.phase > 0) later(() => showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요'));
|
||||
else if (e.t === 'soloTarget') later(() => showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`));
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -712,8 +727,8 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
<span className="cob-res" title="은화" aria-label={`은화 ${myPv.silver}개`}>
|
||||
🪙 {myPv.silver}
|
||||
</span>
|
||||
<span className="cob-res" aria-label={`점수 ${myPv.vp}점`}>
|
||||
⭐ {myPv.vp}
|
||||
<span className="cob-res" aria-label={`점수 ${myVp}점`}>
|
||||
⭐ {myVp}
|
||||
</span>
|
||||
{sel?.kind === 'die' && workersMove(sel.i) && (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => send(workersMove((sel as { i: 0 | 1 }).i)!.a)} disabled={busy}>
|
||||
@@ -1053,6 +1068,9 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
);
|
||||
const order = v.roundOrder.length ? v.roundOrder : v.seats;
|
||||
const rows = v.final ? [...v.final].sort((a, b) => b.total - a.total) : null;
|
||||
// Points change once the tile that scored them has settled on the board.
|
||||
const vps = useAfterMotionValue(v.seats.map((p) => v.players[p]!.vp).join(',')).split(',');
|
||||
const vpOf = (p: string) => vps[v.seats.indexOf(p)] ?? String(v.players[p]!.vp);
|
||||
return (
|
||||
<>
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="참가자">
|
||||
@@ -1076,8 +1094,8 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
{pv.conceded ? '기권' : pv.away ? '자리 비움' : `👷${pv.workers} 🪙${pv.silver} 🎲${pv.dice.join('·')} · 빈칸 ${pv.emptySpaces}`}
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontWeight: 900, fontSize: '1.2rem' }} aria-label={`${nick(players, p)} ${pv.vp}점`}>
|
||||
{pv.vp}
|
||||
<span style={{ fontWeight: 900, fontSize: '1.2rem' }} aria-label={`${nick(players, p)} ${vpOf(p)}점`}>
|
||||
{vpOf(p)}
|
||||
</span>
|
||||
{turn && v.stage !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.deadlineMs || 60_000} mine={p === me} size={34} />}
|
||||
</div>
|
||||
@@ -1092,22 +1110,25 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
{rows && (
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="최종 점수">
|
||||
<strong>최종 점수</strong>
|
||||
{rows.map((r) => (
|
||||
<div key={r.player} className="small">
|
||||
<strong>
|
||||
{nick(players, r.player)} {r.total}점
|
||||
</strong>{' '}
|
||||
= 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers}
|
||||
{r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''}
|
||||
{r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{/* The final scores wait for the last move to finish animating. */}
|
||||
<AfterMotion when={!!rows}>
|
||||
{rows && (
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="최종 점수">
|
||||
<strong>최종 점수</strong>
|
||||
{rows.map((r) => (
|
||||
<div key={r.player} className="small">
|
||||
<strong>
|
||||
{nick(players, r.player)} {r.total}점
|
||||
</strong>{' '}
|
||||
= 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers}
|
||||
{r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''}
|
||||
{r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{log.length > 0 && (
|
||||
<details className="cob-card" open>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- constants (mirror packages/games/src/catchmind/types.ts)
|
||||
|
||||
@@ -685,6 +685,23 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string
|
||||
const prevRole = useRef(v.role);
|
||||
const prevTurn = useRef(v.turnNo);
|
||||
const popTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The answer screen (and its sound) waits until my "정답!" pop has played.
|
||||
const over = v.phase === 'reveal' || v.phase === 'ended';
|
||||
const overShown = useMotionSettled(over);
|
||||
const prevPhase = useRef(v.phase);
|
||||
const revealSound = useRef<(() => void) | null>(null);
|
||||
useEffect(() => {
|
||||
if (prevTurn.current === v.turnNo && prevPhase.current === 'drawing' && v.phase === 'reveal') {
|
||||
revealSound.current = v.endReason === 'report' ? sfx.alarm : v.endReason === 'allSolved' ? sfx.fanfare : v.solvers.length === 0 ? sfx.bad : sfx.cardFlip;
|
||||
}
|
||||
prevPhase.current = v.phase;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [v.phase, v.turnNo]);
|
||||
useEffect(() => {
|
||||
if (!overShown || !revealSound.current) return;
|
||||
revealSound.current();
|
||||
revealSound.current = null;
|
||||
}, [overShown]);
|
||||
useEffect(() => {
|
||||
if (prevTurn.current === v.turnNo && prevRole.current === 'guesser' && v.role === 'solver') {
|
||||
setPop(v.solvers.find((s) => s.id === me)?.points ?? 0);
|
||||
@@ -707,7 +724,7 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string
|
||||
) : null;
|
||||
return (
|
||||
<>
|
||||
<OverlayMain v={v} act={act} players={players} onSave={onSave} />
|
||||
{(!over || overShown) && <OverlayMain v={v} act={act} players={players} onSave={onSave} />}
|
||||
{popEl}
|
||||
</>
|
||||
);
|
||||
@@ -1061,7 +1078,7 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act:
|
||||
);
|
||||
}
|
||||
|
||||
/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */
|
||||
/** Sounds for what happens on the table (my own "정답!" and the answer reveal are played by the overlay). */
|
||||
function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
@@ -1083,12 +1100,6 @@ function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect();
|
||||
if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react();
|
||||
if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close();
|
||||
if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') {
|
||||
if (v.endReason === 'report') sfx.alarm();
|
||||
else if (v.endReason === 'allSolved') sfx.fanfare();
|
||||
else if (v.solvers.length === 0) sfx.bad();
|
||||
else sfx.cardFlip();
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
@@ -1358,6 +1369,7 @@ const ui: GameUI<CatchmindView, CatchmindOptions> = {
|
||||
Board: CatchmindBoard,
|
||||
Side: CatchmindSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import { AfterMotion, useAfterMotionValue } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { CHESS_PIECE_CREDIT, pieceSrc } from './art';
|
||||
import { chessCues, chessMotion } from './fx';
|
||||
@@ -542,12 +543,15 @@ function ChessSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.result && REASON_HELP[v.result.reason] && (
|
||||
<div className="card" style={{ padding: 12 }}>
|
||||
<strong>{v.result.summary}</strong>
|
||||
<div className="muted small">{REASON_HELP[v.result.reason]}</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Checkmate / stalemate explained once the last move has landed. */}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && REASON_HELP[v.result.reason] && (
|
||||
<div className="card" style={{ padding: 12 }}>
|
||||
<strong>{v.result.summary}</strong>
|
||||
<div className="muted small">{REASON_HELP[v.result.reason]}</div>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
<MoveList view={v} />
|
||||
{incoming && (
|
||||
<Sheet onClose={() => {}} label="상대의 요청">
|
||||
@@ -661,8 +665,9 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: ChessView;
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const caps = [...v.captured[color]].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b));
|
||||
const adv = color === 'white' ? v.materialDiff : -v.materialDiff;
|
||||
// A captured piece joins the row (and the material count changes) once the capturing move has landed.
|
||||
const caps = [...useAfterMotionValue(v.captured[color].join(''))].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b));
|
||||
const adv = useAfterMotionValue(color === 'white' ? v.materialDiff : -v.materialDiff);
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<div className="row" style={{ gap: 10 }}>
|
||||
|
||||
@@ -28,7 +28,7 @@ import { cssEsc, flyGhost, reducedMotion } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
export const SUSPECT_COLOR: Record<Suspect, string> = {
|
||||
scarlet: '#dc2626',
|
||||
@@ -302,6 +302,10 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null);
|
||||
|
||||
useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]);
|
||||
// The dice total (and the rooms it reaches) shows once the dice have stopped rolling.
|
||||
const diceKey = v.dice ? `${v.turnNo}-${v.dice[0]}-${v.dice[1]}` : '';
|
||||
const shownDice = useAfterMotionValue(diceKey);
|
||||
const rolling = diceKey !== '' && shownDice !== diceKey;
|
||||
|
||||
// Tokens and weapons slide on the map from where they were (anyone's move, a suggestion pulling them into a room).
|
||||
// Places are kept relative to the map, so scrolling between two moves does not matter.
|
||||
@@ -431,8 +435,8 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
<div className="cl-board" role="region" aria-label="클루 판">
|
||||
<style>{CSS}</style>
|
||||
<div className="cl-top">
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} />
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending && !rolling} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} rolling={rolling} />
|
||||
</div>
|
||||
{amPlayer && <MyCards view={v} me={me!} />}
|
||||
{amPlayer && <Notebook view={v} me={me!} players={players} />}
|
||||
@@ -635,6 +639,9 @@ function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act
|
||||
|
||||
function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const last = lastOf(v.suggestions);
|
||||
// The answer shows once the suggested cards have flown into the envelope / the shown card has reached the suggester.
|
||||
const answerKey = `${v.suggestions.length}|${last?.refuter ?? ''}|${v.phase.kind === 'refute'}`;
|
||||
const answered = useAfterMotionValue(answerKey) === answerKey;
|
||||
if (!last || last.turnNo !== v.turnNo) return null;
|
||||
const by = last.by === me ? '내' : `${nick(players, last.by)}님의`;
|
||||
return (
|
||||
@@ -643,7 +650,7 @@ function LastResult({ view: v, me, players }: { view: ClueView; me: string | nul
|
||||
{by} 추리: <strong>{triple(last)}</strong>
|
||||
{last.passed.length > 0 && <span className="muted"> · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}</span>}
|
||||
</span>
|
||||
{last.refuter ? (
|
||||
{!answered ? null : last.refuter ? (
|
||||
last.shown ? (
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<Card id={last.shown} flip label={`${last.refuter === me ? '내가 보여 준' : `${nick(players, last.refuter)}님이 보여 준`} 카드: ${ITEM_KO[itemOf(last.shown)]}`} />
|
||||
@@ -674,6 +681,7 @@ function ActionPanel({
|
||||
myTurn,
|
||||
sel,
|
||||
setSel,
|
||||
rolling,
|
||||
}: {
|
||||
view: ClueView;
|
||||
me: string | null;
|
||||
@@ -683,6 +691,7 @@ function ActionPanel({
|
||||
myTurn: boolean;
|
||||
sel: Room | null;
|
||||
setSel: (r: Room | null) => void;
|
||||
rolling: boolean;
|
||||
}) {
|
||||
const [accusing, setAccusing] = useState(false);
|
||||
const known = useMemo(() => {
|
||||
@@ -694,18 +703,21 @@ function ActionPanel({
|
||||
const ph = v.phase;
|
||||
|
||||
if (ph.kind === 'finished') {
|
||||
// The answer opens after the accusation banner has played.
|
||||
return (
|
||||
<div className="cl-panel" aria-live="polite">
|
||||
<strong>게임이 끝났어요</strong>
|
||||
<span>{v.final?.summary}</span>
|
||||
{v.solution && (
|
||||
<div className="cl-cards" aria-label="사건 봉투 속 정답">
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
|
||||
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="cl-panel" aria-live="polite">
|
||||
<strong>게임이 끝났어요</strong>
|
||||
<span>{v.final?.summary}</span>
|
||||
{v.solution && (
|
||||
<div className="cl-cards" aria-label="사건 봉투 속 정답">
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
|
||||
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -739,7 +751,7 @@ function ActionPanel({
|
||||
if (!myTurn) {
|
||||
const doing: Record<string, string> = {
|
||||
move: '이동하는 중이에요',
|
||||
moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`,
|
||||
moveTo: rolling ? '주사위를 굴리는 중이에요' : `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`,
|
||||
suggest: '추리할 카드를 고르는 중이에요',
|
||||
afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요',
|
||||
};
|
||||
@@ -822,13 +834,15 @@ function ActionPanel({
|
||||
<span key={`b${v.turnNo}-${v.dice[1]}`} className="anim-roll" style={{ animationDelay: '80ms' }} aria-hidden>
|
||||
{DICE[v.dice[1]]}
|
||||
</span>
|
||||
<b aria-hidden>= {sum}칸</b>
|
||||
{!rolling && <b aria-hidden>= {sum}칸</b>}
|
||||
</div>
|
||||
)}
|
||||
<strong>지도에서 갈 방을 눌러 주세요.</strong>
|
||||
<span className="small muted">
|
||||
{free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
|
||||
</span>
|
||||
<strong>{rolling ? '주사위를 굴리는 중…' : '지도에서 갈 방을 눌러 주세요.'}</strong>
|
||||
{!rolling && (
|
||||
<span className="small muted">
|
||||
{free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
|
||||
</span>
|
||||
)}
|
||||
<div className="cl-btns">
|
||||
{sel && enter && (
|
||||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'go', room: sel })}>
|
||||
@@ -985,7 +999,11 @@ function logLines(v: ClueView, me: string | null, players: Record<string, Public
|
||||
|
||||
function ClueSide({ view: v, me, players, deadline }: BoardProps<ClueView>) {
|
||||
const running = v.phase.kind !== 'finished';
|
||||
const lines = logLines(v, me, players);
|
||||
// Accusation results, the winner and the answer show after the accusation banner has played on the board.
|
||||
const shownAcc = useAfterMotionValue(v.accusations.length);
|
||||
const pendingAcc = v.accusations.slice(shownAcc);
|
||||
const ended = useMotionSettled(!running);
|
||||
const lines = logLines(pendingAcc.length ? { ...v, accusations: v.accusations.slice(0, shownAcc) } : v, me, players);
|
||||
const wait = waitingOn(v);
|
||||
return (
|
||||
<>
|
||||
@@ -1011,14 +1029,14 @@ function ClueSide({ view: v, me, players, deadline }: BoardProps<ClueView>) {
|
||||
카드 {v.handCounts[p]}장
|
||||
</span>
|
||||
{running && wait === p && <span className="cl-badge turn">{v.phase.kind === 'refute' ? '보여 주는 중' : '차례'}</span>}
|
||||
{v.final?.winner === p && <span className="cl-badge ok">승리</span>}
|
||||
{v.left[p] ? <span className="cl-badge out">나감</span> : v.out[p] && <span className="cl-badge out">고발 실패</span>}
|
||||
{ended && v.final?.winner === p && <span className="cl-badge ok">승리</span>}
|
||||
{v.left[p] ? <span className="cl-badge out">나감</span> : v.out[p] && !pendingAcc.some((a) => a.by === p) && <span className="cl-badge out">고발 실패</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
{v.hands && v.solution && (
|
||||
{ended && v.hands && v.solution && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>정답: {triple(v.solution)}</strong>
|
||||
{v.seats.map((p) => (
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, flyGhost, seatEl, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
|
||||
const KINDS: Kind[] = ['cockroach', 'bat', 'fly', 'toad', 'rat', 'scorpion', 'spider', 'stinkbug'];
|
||||
@@ -246,6 +246,9 @@ const CSS = `
|
||||
.cp-chip.danger .cp-mini:last-child { box-shadow: 0 0 0 3px #ef4444, 0 0 12px rgba(239,68,68,.8); }
|
||||
.cp-chip.danger .cp-n { background: #dc2626; animation: cp-breathe 1s ease-in-out infinite; }
|
||||
.cp-chip.new .cp-mini:last-of-type { animation: cp-land .5s cubic-bezier(.3,.7,.3,1.3) 1.4s both; }
|
||||
/* The new count shows as the card lands, not before. */
|
||||
.cp-chip.new .cp-n { animation: cp-pop .25s ease-out 1.65s both; }
|
||||
.cp-chip.new.danger .cp-n { animation: cp-pop .25s ease-out 1.65s both, cp-breathe 1s ease-in-out 1.9s infinite; }
|
||||
${KINDS.map((k) => `.fx-ghost.cp-face-${k} { background: ${KIND_COLOR[k].bg}; color: ${KIND_COLOR[k].ink}; border: 2px solid ${KIND_COLOR[k].ink}; border-radius: 7px; display: flex; align-items: flex-end; justify-content: center; font: 800 9px/1.6 system-ui, sans-serif; box-shadow: 0 3px 8px rgba(0,0,0,.35); }`).join('\n')}
|
||||
.cp-empty { font-size: .8rem; opacity: .75; }
|
||||
.cp-bubble { position: absolute; right: 8px; top: -14px; background: #fff; color: #1c1e21; border-radius: 12px; padding: 3px 10px; font-weight: 800; font-size: .85rem; box-shadow: 0 3px 10px rgba(0,0,0,.3); animation: cp-pop .25s ease-out; z-index: 3; max-width: 80%; }
|
||||
@@ -427,12 +430,13 @@ function HandFan({ n }: { n: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v: CockroachView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null; fresh: Kind | null }) {
|
||||
function Seat({ id, v, me, players, deadline, bubble, fresh, final }: { id: string; v: CockroachView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null; fresh: Kind | null; final: CockroachView['final'] }) {
|
||||
const u = userOf(players, id);
|
||||
const r = v.round;
|
||||
const active = waitingOn(v) === id;
|
||||
const loser = v.final?.loser === id;
|
||||
const loser = final?.loser === id;
|
||||
const front = v.fronts[id]!;
|
||||
const frontTotal = useAfterMotionValue(front.total);
|
||||
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
||||
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
||||
return (
|
||||
@@ -454,12 +458,12 @@ function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v:
|
||||
{role && <span className="cp-badge turn">{role}</span>}
|
||||
{r.holder !== null && r.seen.includes(id) && <span className="cp-badge seen">👁 봤어요</span>}
|
||||
{v.away[id] && <span className="cp-badge">자리 비움</span>}
|
||||
{v.final && <span className={`cp-badge ${loser ? 'lose' : 'win'}`}>{loser ? '패배' : '승리'}</span>}
|
||||
{final && <span className={`cp-badge ${loser ? 'lose' : 'win'}`}>{loser ? '패배' : '승리'}</span>}
|
||||
</div>
|
||||
<div className="cp-meta" aria-hidden>
|
||||
<HandFan n={v.handCounts[id] ?? 0} />
|
||||
<span>손패 {v.handCounts[id]}장</span>
|
||||
<span>· 앞마당 {front.total}장</span>
|
||||
<span>· 앞마당 {frontTotal}장</span>
|
||||
</div>
|
||||
<div className="cp-front" aria-hidden>
|
||||
<FrontChips front={front} loseCount={v.loseCount} fresh={fresh} small />
|
||||
@@ -491,6 +495,9 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players:
|
||||
const truth = rv.kind === rv.claim;
|
||||
const caller = rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`;
|
||||
const taker = rv.takenBy === me ? '내' : `${nick(players, rv.takenBy)}님`;
|
||||
// A fresh verdict is written out only after the card has turned, been stamped and flown to its taker.
|
||||
const settled = useMotionSettled(fresh);
|
||||
const told = !fresh || settled;
|
||||
return (
|
||||
<div className={`cp-reveal${big ? ' big' : ''}`} role="group" aria-label="지난 판정">
|
||||
<span className="cp-revealcard">
|
||||
@@ -501,7 +508,7 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players:
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="small" style={{ lineHeight: 1.45 }}>
|
||||
<span className="small" style={{ lineHeight: 1.45, visibility: told ? undefined : 'hidden' }} aria-hidden={told ? undefined : true}>
|
||||
"{KIND_KO[rv.claim]}"{hasBatchim(KIND_KO[rv.claim]) ? "이라는" : "라는"} 말에 {caller} "{callWord}"{rv.auto ? '(시간 초과)' : ''} → 실제로는 {KIND_KO[rv.kind]}({truth ? '진짜' : '거짓'})
|
||||
<br />
|
||||
<span className={`verdict ${rv.correct ? 'ok' : 'no'}`}>{rv.correct ? '맞혔어요!' : '틀렸어요!'}</span> {kj(rv.kind, '은', '는')} {taker} 앞마당으로
|
||||
@@ -520,9 +527,12 @@ function Who({ id, players, me }: { id: string; players: Record<string, PublicUs
|
||||
}
|
||||
|
||||
/** The middle of the felt: the card being passed (with what was said), or the last verdict while the next card is chosen. */
|
||||
function Table({ v, me, players, fresh }: { v: CockroachView; me: string | null; players: Record<string, PublicUser>; fresh: { slide: boolean; flip: boolean } }) {
|
||||
function Table({ v, me, players, fresh, over }: { v: CockroachView; me: string | null; players: Record<string, PublicUser>; fresh: { slide: boolean; flip: boolean }; over: boolean }) {
|
||||
const r = v.round;
|
||||
if (v.phase === 'finished') {
|
||||
// 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 (
|
||||
<div className="cp-center cp-table" role="group" aria-label="테이블">
|
||||
@@ -564,11 +574,11 @@ function Table({ v, me, players, fresh }: { v: CockroachView; me: string | null;
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const last = v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null;
|
||||
const last = lastCall ?? (v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null);
|
||||
return (
|
||||
<div className="cp-center cp-table" role="group" aria-label="테이블">
|
||||
{last ? <RevealLine rv={last} players={players} me={me} fresh={fresh.flip} big /> : <BackCard size="lg" />}
|
||||
<span className="cp-wait">{r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`}</span>
|
||||
{!lastCall && <span className="cp-wait">{r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -760,8 +770,9 @@ function RespondPanel({ v, players, act, pending }: { v: CockroachView; players:
|
||||
);
|
||||
}
|
||||
|
||||
function WaitPanel({ v, players, me }: { v: CockroachView; players: Record<string, PublicUser>; me: string | null }) {
|
||||
function WaitPanel({ v, players, me, over }: { v: CockroachView; players: Record<string, PublicUser>; me: string | null; over: boolean }) {
|
||||
if (v.phase === 'finished') {
|
||||
if (!over) return null;
|
||||
const f = v.final!;
|
||||
return (
|
||||
<div className="cp-panel" aria-live="polite">
|
||||
@@ -793,21 +804,25 @@ function MyArea({
|
||||
offering,
|
||||
bubble,
|
||||
fresh,
|
||||
final,
|
||||
}: {
|
||||
v: CockroachView;
|
||||
me: string;
|
||||
players: Record<string, PublicUser>;
|
||||
deadline: number | null;
|
||||
offering: boolean;
|
||||
/** The result, once the last call has played out. */
|
||||
final: CockroachView['final'];
|
||||
/** What I just said with 빠른 말: shown over my own area too, like everybody else's. */
|
||||
bubble: string | null;
|
||||
fresh: Kind | null;
|
||||
}) {
|
||||
const front = v.fronts[me]!;
|
||||
const frontTotal = useAfterMotionValue(front.total);
|
||||
const active = waitingOn(v) === me;
|
||||
const total = v.handCounts[me] ?? 0;
|
||||
return (
|
||||
<section className={`cp-me${active ? ' turn' : ''}${v.final?.loser === me ? ' loser' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
<section className={`cp-me${active ? ' turn' : ''}${final?.loser === me ? ' loser' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -838,7 +853,7 @@ function MyArea({
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="small">내 앞마당 {front.total}장</span>
|
||||
<span className="small">내 앞마당 {frontTotal}장</span>
|
||||
<div className="cp-front" role="img" aria-label={`내 ${frontText(front, v.loseCount)}`}>
|
||||
<FrontChips front={front} loseCount={v.loseCount} fresh={fresh} />
|
||||
</div>
|
||||
@@ -856,6 +871,19 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
||||
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
||||
const [banner, showBanner] = useBanner();
|
||||
// A call is played out with timers (verdict, flight, the loss): results wait until its last step.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const stageTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []);
|
||||
const stageFor = (ms: number) => {
|
||||
if (stageTimer.current) clearTimeout(stageTimer.current);
|
||||
setStaging(true);
|
||||
stageTimer.current = setTimeout(() => setStaging(false), ms);
|
||||
};
|
||||
// The end of the game (badges, the table's result, the panel) shows once the last call has played out.
|
||||
const overShown = useMotionSettled(v.phase === 'finished');
|
||||
const final = overShown ? v.final : null;
|
||||
const prev = useRef({
|
||||
claims: v.round.claims.length + v.round.no * 100,
|
||||
reveal: v.lastReveal?.round ?? 0,
|
||||
@@ -887,8 +915,13 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
sfx.cardFlip();
|
||||
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), fxMs(260));
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
// The verdict comes when the 진짜/거짓 stamp has landed on the turned card (flip .6s, stamp .55s + .45s).
|
||||
setTimeout(() => {
|
||||
if (rv.correct) sfx.good();
|
||||
else cpSfx.wrong();
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
}, fxMs(1000));
|
||||
stageFor(fxMs(over ? 2600 : 1600));
|
||||
// After the flip and the stamp, a face-up copy goes to the 앞마당 of whoever takes it.
|
||||
flyGhost(document.querySelector('.cp-revealcard') ?? document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 1000, ms: 480, className: `cp-face-${rv.kind}`, label: KIND_KO[rv.kind] });
|
||||
setTimeout(() => {
|
||||
@@ -904,7 +937,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
|
||||
cpSfx.danger();
|
||||
bump(seatEl(f.loser), 'shake');
|
||||
}, flip ? fxMs(1900) : 0);
|
||||
}, flip ? fxMs(2500) : 0); // after the verdict banner and the card's landing
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
@@ -940,8 +973,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const responding = amPlayer && v.round.holder === me && !v.round.peeked && v.phase === 'respond';
|
||||
const seats = amPlayer ? v.order.slice(v.order.indexOf(me!) + 1).concat(v.order.slice(0, v.order.indexOf(me!))) : v.order;
|
||||
|
||||
// A new verdict counts as fresh from its first render (the effect that sets `fresh` runs after it), so the card
|
||||
// never shows face up or its verdict before the flip.
|
||||
const freshNow = { slide: fresh.slide, flip: fresh.flip || (v.lastReveal?.round ?? 0) !== prev.current.reveal };
|
||||
// The card that just went face up lands in front of whoever took it.
|
||||
const landed = fresh.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null;
|
||||
const landed = freshNow.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null;
|
||||
const landedFor = (id: string) => (landed?.id === id ? landed.kind : null);
|
||||
|
||||
return (
|
||||
@@ -950,11 +986,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
<div className="cp-felt">
|
||||
<div className="cp-opps">
|
||||
{seats.map((p) => (
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} fresh={landedFor(p)} />
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} fresh={landedFor(p)} final={final} />
|
||||
))}
|
||||
</div>
|
||||
<Table v={v} me={me} players={players} fresh={fresh} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} bubble={bubbles[me!] ?? null} fresh={landedFor(me!)} />}
|
||||
<Table v={v} me={me} players={players} fresh={freshNow} over={overShown} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} bubble={bubbles[me!] ?? null} fresh={landedFor(me!)} final={final} />}
|
||||
</div>
|
||||
<div className="cp-actions">
|
||||
{offering || passing ? (
|
||||
@@ -962,7 +998,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
) : responding ? (
|
||||
<RespondPanel v={v} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<WaitPanel v={v} players={players} me={me} />
|
||||
<WaitPanel v={v} players={players} me={me} over={overShown} />
|
||||
)}
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -1002,12 +1038,15 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const running = v.phase !== 'finished';
|
||||
const w = waitingOn(v);
|
||||
const r = v.round;
|
||||
// Who lost (and the 앞마당 counts) show once the last call has played out on the board.
|
||||
const final = useMotionSettled(v.phase === 'finished') ? v.final : null;
|
||||
const fronts = useAfterMotionValue(v.order.map((p) => v.fronts[p]!.total).join(',')).split(',');
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 8, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>{running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : '게임 끝'}</strong>
|
||||
<strong>{running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : final ? '게임 끝' : `${r.no}라운드`}</strong>
|
||||
{running && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine={w === me} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">{optionsSummary(v.options, v.order.length)}</span>
|
||||
@@ -1018,17 +1057,17 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p === me ? 800 : 600 }} aria-hidden>
|
||||
{nick(players, p)}
|
||||
{w === p ? ' · 차례' : ''}
|
||||
{v.final ? (v.final.loser === p ? ' · 패배' : ' · 승리') : ''}
|
||||
{final ? (final.loser === p ? ' · 패배' : ' · 승리') : ''}
|
||||
</span>
|
||||
<span className="small muted" style={{ whiteSpace: 'nowrap' }} aria-hidden>
|
||||
손 {v.handCounts[p]} · 앞 {v.fronts[p]!.total}
|
||||
손 {v.handCounts[p]} · 앞 {fronts[v.order.indexOf(p)] ?? v.fronts[p]!.total}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{v.removedCount > 0 && running && <span className="small muted">2명 게임이라 카드 {v.removedCount}장을 보지 않고 뺐어요.</span>}
|
||||
</div>
|
||||
{v.final && <FinalCard v={v} players={players} />}
|
||||
{final && <FinalCard v={v} players={players} />}
|
||||
{running && v.options.claimHistory && r.claims.length > 0 && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>이번 라운드 주장</strong>
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -132,7 +133,10 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
|
||||
const ghostCol = preview ?? (hover !== null && canDrop(hover) ? hover : myTurn && kbd && open(cursor) ? cursor : null);
|
||||
const ghostLand = ghostCol !== null ? landing(ghostCol) : -1;
|
||||
const winSet = new Set((v.winLine ?? []).map((p) => p.y * cols + p.x));
|
||||
// The winning four light up only once the last disc has landed.
|
||||
const winShown = useMotionSettled(!!v.winLine?.length);
|
||||
const winLine = winShown ? (v.winLine ?? []) : [];
|
||||
const winSet = new Set(winLine.map((p) => p.y * cols + p.x));
|
||||
const last = v.lastMove ? v.lastMove.y * cols + v.lastMove.x : -1;
|
||||
const pad = 0.15;
|
||||
const cells = Array.from({ length: cols * rows }, (_, i) => i);
|
||||
@@ -196,7 +200,7 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
opacity={0.85}
|
||||
/>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
{winLine.map((p, k) => (
|
||||
<circle
|
||||
key={`w${p.x}-${p.y}`}
|
||||
className="c4-win"
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const JESTER = 13;
|
||||
/** Same names as the rules module (kept here so the screen chunk does not pull in the rules code). */
|
||||
@@ -752,7 +752,14 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const prevMine = useRef(false);
|
||||
const lastLog = v.log[v.log.length - 1];
|
||||
const [banner, showBanner] = useBanner();
|
||||
useDalmutiFx(v, me, players, showBanner);
|
||||
const end = useRoundEnd(v);
|
||||
const endDone = useMotionSettled(!!end);
|
||||
const showEnd = end && !endDone ? end : null;
|
||||
const resumeFx = useDalmutiFx(v, me, players, showBanner, !!showEnd);
|
||||
// The next round's panel is on screen now: deal its cards (and the rest of what was held back).
|
||||
useLayoutEffect(() => {
|
||||
if (endDone) resumeFx();
|
||||
}, [endDone]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (mine && !prevMine.current) {
|
||||
haptic(40);
|
||||
@@ -768,17 +775,27 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
<div className="dm">
|
||||
<style>{CSS}</style>
|
||||
<Tip />
|
||||
<Seats v={v} players={players} me={me} deadline={deadline} />
|
||||
<RevolutionBanner v={v} players={players} me={me} />
|
||||
{v.phase === 'revolutionCheck' && <RevolutionPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'taxReturn' && <TaxPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'playing' && <TableArea v={v} players={players} me={me} />}
|
||||
{v.phase === 'playing' && v.my && <PlayHand v={v} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
<div className="dm-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result.summary}</span>
|
||||
</div>
|
||||
{showEnd ? (
|
||||
<>
|
||||
{/* The round is over: its last cards land and the 등 banners play before the results and the next round. */}
|
||||
<Seats v={showEnd} players={players} me={me} deadline={null} />
|
||||
<TableArea v={showEnd} players={players} me={me} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Seats v={v} players={players} me={me} deadline={deadline} />
|
||||
<RevolutionBanner v={v} players={players} me={me} />
|
||||
{v.phase === 'revolutionCheck' && <RevolutionPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'taxReturn' && <TaxPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'playing' && <TableArea v={v} players={players} me={me} />}
|
||||
{v.phase === 'playing' && v.my && <PlayHand v={v} act={act} pending={pending} />}
|
||||
<AfterMotion when={v.phase === 'finished' && !!v.result}>
|
||||
<div className="dm-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result?.summary}</span>
|
||||
</div>
|
||||
</AfterMotion>
|
||||
</>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
@@ -788,10 +805,33 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The table as it stood when the round ended (the last play on top, seats before the new titles), from the moment
|
||||
* the round-ending view arrives until the next playing phase; null otherwise. Computed during render so the cards
|
||||
* are on screen in the same frame as their fly-in.
|
||||
*/
|
||||
function useRoundEnd(v: DalmutiView): DalmutiView | null {
|
||||
const r = useRef<{ cur: DalmutiView; end: DalmutiView | null }>({ cur: v, end: null });
|
||||
const s = r.current;
|
||||
if (s.cur !== v) {
|
||||
const p = s.cur;
|
||||
s.cur = v;
|
||||
if (v.phase === 'playing') s.end = null;
|
||||
else if (p.phase === 'playing') {
|
||||
const seen = new Set(p.log.map(logKey));
|
||||
const play = [...v.log].reverse().find((e): e is Extract<LogEntry, { t: 'play' }> => e.t === 'play' && !seen.has(logKey(e)));
|
||||
const top: PlayView | null = play ? { by: play.p, count: play.count, rank: play.rank, cards: play.cards } : null;
|
||||
const trick = top ? { leader: p.trick?.leader ?? top.by, top, pile: [...(p.trick?.pile ?? []), top] } : p.trick;
|
||||
s.end = { ...p, trick, current: null, seats: p.seats.map((x) => ({ ...x, isTurn: false })) };
|
||||
}
|
||||
}
|
||||
return s.end;
|
||||
}
|
||||
|
||||
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`;
|
||||
|
||||
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1], roundEnding: boolean): () => void {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||
// A new round (or the very first deal): cards go from the middle to everyone.
|
||||
@@ -802,7 +842,14 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 }));
|
||||
for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||
};
|
||||
// While the ended round is still on screen, the new round's part (the deal, tax flights) waits for `resume`.
|
||||
const deferred = useRef<LogEntry[]>([]);
|
||||
useNewEntries(v.log, logKey, (fresh) => {
|
||||
const r = roundEnding ? fresh.findIndex((e) => e.t === 'round') : -1;
|
||||
if (r >= 0) deferred.current = fresh.slice(r);
|
||||
run(r >= 0 ? fresh.slice(0, r) : fresh);
|
||||
});
|
||||
function run(fresh: LogEntry[]) {
|
||||
const lastPlay = [...fresh].reverse().find((e) => e.t === 'play');
|
||||
let t = 0;
|
||||
for (const e of fresh) {
|
||||
@@ -863,7 +910,7 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
if (started.current) return;
|
||||
@@ -876,6 +923,11 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
: v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done));
|
||||
if (fresh) deal();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return () => {
|
||||
const d = deferred.current;
|
||||
deferred.current = [];
|
||||
if (d.length) run(d);
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
@@ -896,7 +948,13 @@ function rulesLine(o: DalmutiOptions): string {
|
||||
|
||||
function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>) {
|
||||
const phaseKo = v.phase === 'revolutionCheck' ? '손패 확인' : v.phase === 'taxReturn' ? '세금 교환' : v.phase === 'playing' ? '진행 중' : '게임 끝';
|
||||
const rounds = v.roundResults;
|
||||
// Points and round ranks change once the round's last cards and banners have played on the board.
|
||||
const shownRounds = useAfterMotionValue(v.roundResults.length);
|
||||
const shownRef = useRef(v);
|
||||
if (shownRounds === v.roundResults.length) shownRef.current = v;
|
||||
const sv = shownRef.current;
|
||||
const totalOf = (id: string) => (sv.seats.find((x) => x.id === id) ?? v.seats.find((x) => x.id === id))?.total ?? 0;
|
||||
const rounds = sv.roundResults;
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -921,7 +979,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
{s.id === me ? ' (나)' : ''} <span className="small muted">{s.title}</span>
|
||||
</span>
|
||||
<span className="small" aria-hidden>
|
||||
{s.total}점
|
||||
{totalOf(s.id)}점
|
||||
</span>
|
||||
<span className="dm-count" aria-hidden>
|
||||
<i />
|
||||
@@ -947,7 +1005,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(v.result ? v.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => (
|
||||
{(sv.result ? sv.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => (
|
||||
<tr key={p}>
|
||||
<th scope="row" style={{ fontWeight: p === me ? 800 : 600 }}>
|
||||
{nick(players, p)}
|
||||
@@ -956,13 +1014,13 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
<td key={r.round}>{r.order.indexOf(p) + 1}등</td>
|
||||
))}
|
||||
<td>
|
||||
<b>{v.seats.find((s) => s.id === p)?.total ?? 0}점</b>
|
||||
<b>{totalOf(p)}점</b>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{v.result && <p className="small muted" style={{ margin: '6px 0 0' }}>{v.result.summary}</p>}
|
||||
{sv.result && <p className="small muted" style={{ margin: '6px 0 0' }}>{sv.result.summary}</p>}
|
||||
</div>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const COLOR_KO: Record<TColor, string> = { black: '검은색', white: '흰색' };
|
||||
const COLOR_SHORT: Record<TColor, string> = { black: '검정', white: '흰색' };
|
||||
@@ -251,6 +251,15 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const [banner, setBanner] = useTimed<{ text: string; s: number }>();
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const seq = useRef(0);
|
||||
// "○○님 탈락!" waits for the flip of the tile that put them out; meanwhile the screen counts as moving.
|
||||
const [bannerWait, setBannerWait] = useState(false);
|
||||
const bannerTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useMotionHold(bannerWait);
|
||||
useEffect(() => () => clearTimeout(bannerTimer.current), []);
|
||||
// A new guess is told (panel, last guess line) only once its tile has turned over; the end panel after the reveal.
|
||||
const shownHist = useAfterMotionValue(v.history.length);
|
||||
const endShown = useMotionSettled(v.phase === 'finished');
|
||||
const settling = shownHist !== v.history.length ? 'guess' : v.phase === 'finished' && !endShown ? 'end' : null;
|
||||
const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record<string, boolean[]> } | null>(null);
|
||||
const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`);
|
||||
|
||||
@@ -325,9 +334,16 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
if (now.elim > prev.elim) {
|
||||
const out = v.eliminationOrder[v.eliminationOrder.length - 1]!;
|
||||
if (!v.left[out]) {
|
||||
setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700);
|
||||
// The match result sound itself is played by the room page.
|
||||
if (v.phase !== 'finished') snd.out(t + 250);
|
||||
const text = out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`;
|
||||
const more = v.phase !== 'finished';
|
||||
clearTimeout(bannerTimer.current);
|
||||
setBannerWait(true);
|
||||
bannerTimer.current = setTimeout(() => {
|
||||
setBannerWait(false);
|
||||
setBanner({ text, s: ++seq.current }, 1700);
|
||||
// The match result sound itself is played by the room page.
|
||||
if (more) snd.out(0);
|
||||
}, fxMs(t + 500));
|
||||
}
|
||||
}
|
||||
if (prev.phase !== 'finished' && v.phase === 'finished') {
|
||||
@@ -377,8 +393,8 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
))}
|
||||
</div>
|
||||
<div className="dv-mid">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} lastNo={shownHist} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} settling={settling} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
</div>
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx ?? NO_FX} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -395,9 +411,11 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
|
||||
function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: DavinciView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
const u = userOf(players, id);
|
||||
const row = v.rows[id] ?? [];
|
||||
const st = v.stats[id] ?? { guesses: 0, correct: 0 };
|
||||
const outRank = v.eliminationOrder.indexOf(id);
|
||||
// Counts, 탈락 and 승리 change once the tile that changed them has turned over (`r`); the turn is live (`v`).
|
||||
const r = useAfterMotionValue(v);
|
||||
const row = r.rows[id] ?? [];
|
||||
const st = r.stats[id] ?? { guesses: 0, correct: 0 };
|
||||
const outRank = r.eliminationOrder.indexOf(id);
|
||||
const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id;
|
||||
const choosing = v.phase === 'chooseStart' && v.alive[id] && v.picked && !v.picked[id];
|
||||
return (
|
||||
@@ -408,12 +426,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view:
|
||||
{id === me && <span className="muted"> (나)</span>}
|
||||
</span>
|
||||
{isTurn && <span className="dv-badge turn">차례</span>}
|
||||
{v.final?.winner === id && <span className="dv-badge ok">승리</span>}
|
||||
{!v.alive[id] && <span className="dv-badge out">{v.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${v.seats.length - outRank}위` : ''}</span>}
|
||||
{r.final?.winner === id && <span className="dv-badge ok">승리</span>}
|
||||
{!r.alive[id] && <span className="dv-badge out">{r.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${r.seats.length - outRank}위` : ''}</span>}
|
||||
{v.alive[id] && (v.idle[id] ?? 0) >= 3 && <span className="dv-badge">자리 비움</span>}
|
||||
{v.phase === 'chooseStart' && v.alive[id] && <span className={`dv-badge${choosing ? '' : ' ok'}`}>{choosing ? '고르는 중' : '다 골랐어요'}</span>}
|
||||
<span className="small muted" style={{ marginLeft: 'auto' }}>
|
||||
{v.phase !== 'chooseStart' && (
|
||||
{r.phase !== 'chooseStart' && (
|
||||
<>
|
||||
숨은 타일 <Bump value={hiddenLeft(row)}>{hiddenLeft(row)}</Bump>개 ·{' '}
|
||||
</>
|
||||
@@ -558,6 +576,7 @@ function Center({
|
||||
pending,
|
||||
myTurn,
|
||||
pendFx,
|
||||
lastNo,
|
||||
}: {
|
||||
view: DavinciView;
|
||||
me: string | null;
|
||||
@@ -566,10 +585,12 @@ function Center({
|
||||
pending: boolean;
|
||||
myTurn: boolean;
|
||||
pendFx: Fx | null;
|
||||
/** How many guesses have been shown so far (the newest one waits for its tile to turn). */
|
||||
lastNo: number;
|
||||
}) {
|
||||
const drawing = myTurn && v.phase === 'draw' && !pending;
|
||||
const total = v.pool.black + v.pool.white;
|
||||
const last = v.history[v.history.length - 1];
|
||||
const last = v.history[Math.min(lastNo, v.history.length) - 1];
|
||||
return (
|
||||
<div className="dv-center" role="group" aria-label="더미">
|
||||
{v.options.chooseColors ? (
|
||||
@@ -643,6 +664,7 @@ function ActionPanel({
|
||||
act,
|
||||
pending,
|
||||
myTurn,
|
||||
settling,
|
||||
sel,
|
||||
val,
|
||||
setVal,
|
||||
@@ -654,11 +676,21 @@ function ActionPanel({
|
||||
act: (a: unknown) => void;
|
||||
pending: boolean;
|
||||
myTurn: boolean;
|
||||
/** A tile is still turning over: say what was guessed, not yet whether it was right (or who won). */
|
||||
settling: 'guess' | 'end' | null;
|
||||
sel: Sel | null;
|
||||
val: TileValue | null;
|
||||
setVal: (v: TileValue | null) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
if (settling) {
|
||||
const g = settling === 'guess' ? v.history[v.history.length - 1] : undefined;
|
||||
return (
|
||||
<div className="dv-panel">
|
||||
<strong>{g ? `${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리했어요…` : '…'}</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (v.phase === 'finished') {
|
||||
return (
|
||||
<div className="dv-panel" aria-live="polite">
|
||||
@@ -886,7 +918,9 @@ function StartChooser({ view: v, me, act, pending }: { view: DavinciView; me: st
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function DavinciSide({ view: v, me, players, deadline }: BoardProps<DavinciView>) {
|
||||
function DavinciSide({ view, me, players, deadline }: BoardProps<DavinciView>) {
|
||||
// The side panel (counts, ranks, the guess log) follows the board once its tiles have turned over.
|
||||
const v = useAfterMotionValue(view);
|
||||
const running = v.phase !== 'finished';
|
||||
const ranking = v.final?.ranking ?? null;
|
||||
return (
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { ICON_NAMES, SymbolArt } from './art';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
/** Taps this soon after one of the two cards changed are dropped as late (they were aimed at the previous card). */
|
||||
const TAP_GRACE_MS = 250;
|
||||
@@ -283,6 +283,10 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
const [shake, setShake] = useState(false);
|
||||
const [hitArt, setHitArt] = useState<number | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
// The round result waits until the last find has played (its bubble and the cards changing); the next round's
|
||||
// countdown is real time and never waits.
|
||||
const [roundNote, setRoundNote] = useState<{ bubble: Bubble; bad: boolean } | null>(null);
|
||||
const roundReady = useMotionSettled(roundNote !== null, fxMs(1000));
|
||||
const prev = useRef<DobbleView | null>(null);
|
||||
const changed = useRef({ sig: '', at: 0 });
|
||||
|
||||
@@ -380,10 +384,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
const r = v.lastRound;
|
||||
if (r && r.round !== p.lastRound?.round) {
|
||||
const text = r.loser ? `${r.round}라운드 끝! ${r.loser === me ? '내가' : `${nick(players, r.loser)}님이`} 카드 ${r.cards}장을 벌점으로 받아요` : `${r.round}라운드는 무효예요`;
|
||||
setBubble({ key: `r${r.round}`, kind: r.loser === me ? 'bad' : 'info', text });
|
||||
setAnnounce(text);
|
||||
if (r.loser === me) sfx.bad();
|
||||
else sfx.whoosh();
|
||||
setRoundNote({ bubble: { key: `r${r.round}`, kind: r.loser === me ? 'bad' : 'info', text }, bad: r.loser === me });
|
||||
}
|
||||
// Someone emptied their cards / escaped this round.
|
||||
const done = v.seats.filter((s) => (s.status === 'finished' || s.status === 'escaped') && p.seats.find((x) => x.id === s.id)?.status === 'playing');
|
||||
@@ -392,6 +393,15 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
if (v.hint.length && v.hintUntil !== p.hintUntil && v.hintUntil > 0) sfx.select();
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!roundReady || !roundNote) return;
|
||||
setBubble(roundNote.bubble);
|
||||
setAnnounce(roundNote.bubble.text);
|
||||
if (roundNote.bad) sfx.bad();
|
||||
else sfx.whoosh();
|
||||
setRoundNote(null);
|
||||
}, [roundReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubble) return;
|
||||
const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1700));
|
||||
@@ -554,7 +564,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="db-count" aria-hidden>
|
||||
<div className="db-count" aria-hidden data-motion-free>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>{v.phase === 'roundEnd' ? '다음 라운드를 준비해요' : '두 카드에 똑같이 있는 그림을 찾아요!'}</small>
|
||||
</div>
|
||||
@@ -903,6 +913,7 @@ const ui: GameUI<DobbleView, DobbleOptions> = {
|
||||
Board: DobbleBoard,
|
||||
Side: DobbleSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -24,6 +24,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic } from '../../lib/feedback';
|
||||
import { toast } from '../../store/toast';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GEM, GemCell, MiniHex, PieceIcon, SQ3, hexPoints, hx } from './draw';
|
||||
import { helpNow } from './help';
|
||||
@@ -302,6 +303,14 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
const fresh = before && forward ? before.n : Infinity;
|
||||
const glowKey = v.placements.length;
|
||||
const prevHist = useRef(v.history.length);
|
||||
// "더 놓을 곳이 없어요" / "모두 놓았어요" toasts wait until the block has landed.
|
||||
const [toastQ, setToastQ] = useState<string[]>([]);
|
||||
const toastReady = useMotionSettled(toastQ.length > 0);
|
||||
useEffect(() => {
|
||||
if (!toastReady) return;
|
||||
toastQ.forEach((t) => toast(t));
|
||||
setToastQ([]);
|
||||
}, [toastReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useLayoutEffect(() => {
|
||||
const prev = prevHist.current;
|
||||
prevHist.current = v.history.length;
|
||||
@@ -316,10 +325,10 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
for (const m of added) {
|
||||
if (m.kind !== 'out') continue;
|
||||
if (m.reason === 'blocked') {
|
||||
toast(`${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`);
|
||||
setToastQ((q) => [...q, `${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`]);
|
||||
gmSound.out();
|
||||
} else if (m.reason === 'allPlaced') {
|
||||
toast(`${eun(m.color)} 18개를 모두 놓았어요!`);
|
||||
setToastQ((q) => [...q, `${eun(m.color)} 18개를 모두 놓았어요!`]);
|
||||
gmSound.allPlaced();
|
||||
}
|
||||
}
|
||||
@@ -823,7 +832,9 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'finished' && <LeftPieces view={v} players={players} />}
|
||||
<AfterMotion when={v.phase === 'finished'}>
|
||||
<LeftPieces view={v} players={players} />
|
||||
</AfterMotion>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -869,7 +880,7 @@ function ColorChip({ v, i }: { v: GembloView; i: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPlayerView; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
|
||||
function PlayerRow({ v, shown, p, players, deadline, me }: { v: GembloView; shown: GembloView; p: GembloPlayerView; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
|
||||
const u = players[p.id] ?? { id: p.id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
|
||||
const active = v.phase !== 'finished' && v.turnPlayer === p.id;
|
||||
const now = useServerNow(500);
|
||||
@@ -886,7 +897,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl
|
||||
} else if (active && (tc.kind === 'perMove' || v.phase !== 'playing')) {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={v.phase === 'playing' ? tc.perMoveSec * 1000 : 60_000} mine={p.id === me} size={40} />;
|
||||
}
|
||||
const left = p.colors.reduce((n, i) => n + v.colors[i]!.leftCells, 0);
|
||||
const left = p.colors.reduce((n, i) => n + shown.colors[i]!.leftCells, 0);
|
||||
const teamColors = p.team !== null && v.teams ? ` · ${p.team + 1}팀` : '';
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? GEM[v.colors[v.turn]!.color].fill : 'transparent'}`, opacity: p.out ? 0.6 : 1 }}>
|
||||
@@ -907,7 +918,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl
|
||||
</div>
|
||||
<div className="gm-chips" style={{ marginTop: 6 }}>
|
||||
{p.colors.map((i) => (
|
||||
<ColorChip key={i} v={v} i={i} />
|
||||
<ColorChip key={i} v={shown} i={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -922,10 +933,15 @@ function GembloSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const incoming = live && u && u.by !== me && !u.accepted.includes(me!) ? u : null;
|
||||
const waiting = live && u && (u.by === me || u.accepted.includes(me!));
|
||||
const order = mine ? [...v.players.filter((p) => p.id !== me), mine] : v.players;
|
||||
// Cells left / 끝 per color change once the block has landed on the board.
|
||||
const shownMoves = useAfterMotionValue(v.history.length);
|
||||
const shownRef = useRef(v);
|
||||
if (shownMoves === v.history.length) shownRef.current = v;
|
||||
const shown = shownRef.current.colors.length === v.colors.length ? shownRef.current : v;
|
||||
return (
|
||||
<>
|
||||
{order.map((p) => (
|
||||
<PlayerRow key={p.id} v={v} p={p} players={players} deadline={deadline} me={me} />
|
||||
<PlayerRow key={p.id} v={v} shown={shown} p={p} players={players} deadline={deadline} me={me} />
|
||||
))}
|
||||
{live && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: v.undo.allowed ? '1fr 1fr' : '1fr', gap: 8 }}>
|
||||
|
||||
@@ -11,7 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string | null | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : '');
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
@@ -238,18 +238,21 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
|
||||
function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) {
|
||||
const s = seat.score;
|
||||
const items: [string, boolean][] = [
|
||||
const now: [string, boolean][] = [
|
||||
[`광 ${s.gwang}장`, s.gwang >= 3],
|
||||
[`열끗 ${s.yeol}/5`, s.yeol >= 5],
|
||||
[`띠 ${s.tti}/5`, s.tti >= 5],
|
||||
[`피 ${s.pi}/10`, s.pi >= 10],
|
||||
];
|
||||
if (s.godori) items.push([`고도리 ${s.godori}/3`, s.godori === 3]);
|
||||
if (s.hong) items.push([`홍단 ${s.hong}/3`, s.hong === 3]);
|
||||
if (s.cheong) items.push([`청단 ${s.cheong}/3`, s.cheong === 3]);
|
||||
if (s.cho) items.push([`초단 ${s.cho}/3`, s.cho === 3]);
|
||||
if (s.godori) now.push([`고도리 ${s.godori}/3`, s.godori === 3]);
|
||||
if (s.hong) now.push([`홍단 ${s.hong}/3`, s.hong === 3]);
|
||||
if (s.cheong) now.push([`청단 ${s.cheong}/3`, s.cheong === 3]);
|
||||
if (s.cho) now.push([`초단 ${s.cho}/3`, s.cho === 3]);
|
||||
// Progress changes once the taken cards have flown into the pile.
|
||||
const [total, ...rest] = useAfterMotionValue([String(s.total), ...now.map(([t, d]) => `${d ? 1 : 0}${t}`)].join('|')).split('|');
|
||||
const items = rest.map((x): [string, boolean] => [x.slice(1), x[0] === '1']);
|
||||
return (
|
||||
<div className="gs-prog" aria-label={`족보 진행: ${items.map((x) => x[0]).join(', ')}. 지금 ${s.total}점, 기준 ${winScore}점`}>
|
||||
<div className="gs-prog" aria-label={`족보 진행: ${items.map((x) => x[0]).join(', ')}. 지금 ${total}점, 기준 ${winScore}점`}>
|
||||
{items.map(([t, done]) => (
|
||||
<span key={t} className={done ? 'done' : undefined}>
|
||||
{t}
|
||||
@@ -260,9 +263,11 @@ function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) {
|
||||
}
|
||||
|
||||
function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) {
|
||||
// The score changes once the taken cards have flown into the pile.
|
||||
const score = useAfterMotionValue(seat.score.total);
|
||||
return (
|
||||
<div className="gs-badges">
|
||||
{seat.participant && <span className="gs-badge score" title="이번 판 지금 점수">지금 {seat.score.total}점</span>}
|
||||
{seat.participant && <span className="gs-badge score" title="이번 판 지금 점수">지금 {score}점</span>}
|
||||
{seat.goCount > 0 && <span className="gs-badge go">{seat.goCount}고</span>}
|
||||
{seat.shakes > 0 && <span className="gs-badge">흔듦 {seat.shakes}</span>}
|
||||
{seat.bombs > 0 && <span className="gs-badge">폭탄 {seat.bombs}</span>}
|
||||
@@ -279,8 +284,10 @@ function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) {
|
||||
function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: GostopView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const active = actorOf(v) === seat.id;
|
||||
// Room points change once the round's payments have flown.
|
||||
const total = useAfterMotionValue(seat.total);
|
||||
return (
|
||||
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<div className="gs-head">
|
||||
<Avatar user={u} size={26} />
|
||||
<span className="nm">
|
||||
@@ -289,7 +296,7 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop
|
||||
</span>
|
||||
{seat.isDealer && <span className="gs-badge dealer">선</span>}
|
||||
<span style={{ fontVariantNumeric: 'tabular-nums' }} title="방 점수 합계">
|
||||
합계 <strong>{signed(seat.total)}</strong>
|
||||
합계 <strong>{signed(total)}</strong>
|
||||
</span>
|
||||
{(seat.participant || v.step === 'sell') && (
|
||||
<span className="gs-backs" aria-label={`손패 ${seat.handCount}장`}>
|
||||
@@ -405,7 +412,12 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
}
|
||||
|
||||
function LastTurn({ v, players }: { v: GostopView; players: Record<string, PublicUser> }) {
|
||||
const t = v.lastTurn;
|
||||
// A new turn (what was flipped and taken) shows once its cards have landed; until then the previous one stays.
|
||||
const key = `${v.roundNo}-${v.lastTurn?.seq ?? 0}`;
|
||||
const shownKey = useAfterMotionValue(key);
|
||||
const kept = useRef(v.lastTurn);
|
||||
if (shownKey === key) kept.current = v.lastTurn;
|
||||
const t = kept.current;
|
||||
if (!t) return <div className="gs-last" aria-hidden />;
|
||||
const tags = t.tags.map((x) => TAG_KO[x]).filter(Boolean);
|
||||
const stolen = t.stolen.reduce((a, s) => a + s.cards.length, 0);
|
||||
@@ -459,7 +471,7 @@ type Ask = { kind: 'target' | 'shake' | 'bomb'; h: HandCardView } | null;
|
||||
function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; onFocusCard: (h: HandCardView | null) => void }) {
|
||||
const [lifted, setLifted] = useState<number | null>(null);
|
||||
const [ask, setAsk] = useState<Ask>(null);
|
||||
const canPlay = v.step === 'play' && v.turn === v.me && !pending;
|
||||
const canPlay = v.phase === 'playing' && v.step === 'play' && v.turn === v.me && !pending;
|
||||
const hints = v.rules.hints;
|
||||
const cw = useCardW();
|
||||
useEffect(() => {
|
||||
@@ -578,12 +590,13 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
);
|
||||
}
|
||||
|
||||
function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView | null) => void }) {
|
||||
const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard } = props;
|
||||
function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView | null) => void; holdOpen: boolean }) {
|
||||
const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard, holdOpen } = props;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!seat || !me) return null;
|
||||
const active = actorOf(v) === me;
|
||||
if (v.phase !== 'playing') return null;
|
||||
// After the round ends my area stays until the result panel shows, so the last cards can still fly into my pile.
|
||||
if (v.phase !== 'playing' && !(v.outcome && holdOpen)) return null;
|
||||
return (
|
||||
<div className={`gs-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
<div className="gs-head">
|
||||
@@ -644,7 +657,13 @@ function SellPanel({ v, me, players, act, pending }: { v: GostopView; me: string
|
||||
|
||||
// ---------------------------------------------------------------- decisions (sheets)
|
||||
|
||||
function Decisions({ view: v, me, players, act, pending }: BoardProps<GostopView>) {
|
||||
/** A decision sheet (고·스톱, 뒤집은 패, 총통, 국진) opens once the cards that led to it have landed. */
|
||||
function Decisions(props: BoardProps<GostopView>) {
|
||||
const sheet = DecisionSheet(props);
|
||||
return sheet && <AfterMotion key={props.view.step}>{sheet}</AfterMotion>;
|
||||
}
|
||||
|
||||
function DecisionSheet({ view: v, me, players, act, pending }: BoardProps<GostopView>): React.ReactElement | null {
|
||||
if (!me || v.phase !== 'playing') return null;
|
||||
const nop = () => {};
|
||||
if (v.step === 'goStop' && v.goStop && v.turn === me) {
|
||||
@@ -744,11 +763,14 @@ function outcomeTitle(o: OutcomeView, players: Record<string, PublicUser>, me: s
|
||||
|
||||
function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopView>) {
|
||||
const o = v.outcome;
|
||||
// The panel waits (invisible, so the payment chips can still fly to it) until the last cards, the 스톱! banner and
|
||||
// the chips have played.
|
||||
const shown = useMotionSettled(!!o && v.phase !== 'playing');
|
||||
if (!o || v.phase === 'playing') return null;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||
return (
|
||||
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
||||
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite" aria-hidden={!shown || undefined} style={shown ? undefined : { visibility: 'hidden' }}>
|
||||
<h2 style={{ margin: 0 }}>
|
||||
{v.roundNo}판 결과 · {outcomeTitle(o, players, me)}
|
||||
</h2>
|
||||
@@ -1190,11 +1212,12 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
}
|
||||
prevMine.current = mine;
|
||||
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const resultShown = useMotionSettled(!!v.outcome && v.phase !== 'playing');
|
||||
useEffect(() => {
|
||||
if (v.outcome && v.phase !== 'playing') {
|
||||
if (resultShown && v.outcome && v.phase !== 'playing') {
|
||||
setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`);
|
||||
}
|
||||
}, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [v.roundNo, v.phase, resultShown]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
useGostopFx(v, me, players, showBanner);
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
@@ -1212,7 +1235,7 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
</ul>
|
||||
<Floor v={v} glow={glow} narrow={narrow} players={players} />
|
||||
<RoundResult {...props} />
|
||||
<MyArea {...props} onFocusCard={setFocus} />
|
||||
<MyArea {...props} onFocusCard={setFocus} holdOpen={!resultShown} />
|
||||
<Decisions {...props} />
|
||||
{banner}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -1226,8 +1249,14 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>) {
|
||||
const ranked = [...v.seats].sort((a, b) => b.total - a.total);
|
||||
const mySeat = v.seats.find((s) => s.id === me);
|
||||
// Points change once the cards / payment chips that caused them have landed.
|
||||
const shownTotals = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.total}`).join(','));
|
||||
const totalOf = new Map(shownTotals.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const));
|
||||
const total = (s: SeatView) => totalOf.get(s.id) ?? s.total;
|
||||
const ranked = [...v.seats].sort((a, b) => total(b) - total(a));
|
||||
const myScore = mySeat ? `${mySeat.score.total}\n${mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')}` : '';
|
||||
const [myTotal, myItems] = useAfterMotionValue(myScore).split('\n');
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -1253,7 +1282,7 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
{s.isDealer ? ' · 선' : ''}
|
||||
{s.left ? ' · 나감' : s.autoPilot ? ' · 자동' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{signed(s.total)}</strong>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{signed(total(s))}</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -1261,10 +1290,10 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
{mySeat?.participant && v.phase === 'playing' && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>
|
||||
내 점수 {mySeat.score.total}점 / 기준 {v.rules.winScore}점
|
||||
내 점수 {myTotal}점 / 기준 {v.rules.winScore}점
|
||||
</strong>
|
||||
{mySeat.score.items.length > 0 ? (
|
||||
<span className="small">{mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')}</span>
|
||||
{myItems ? (
|
||||
<span className="small">{myItems}</span>
|
||||
) : (
|
||||
<span className="small muted">아직 점수 족보가 없어요.</span>
|
||||
)}
|
||||
@@ -1285,19 +1314,21 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
</details>
|
||||
)}
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)})
|
||||
</span>
|
||||
))}
|
||||
{v.stats.bestRound && (
|
||||
<span className="small muted">
|
||||
가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)})
|
||||
</span>
|
||||
))}
|
||||
{v.stats.bestRound && (
|
||||
<span className="small muted">
|
||||
가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
<details className="card" style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보표</summary>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { socket, useRoom } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs } from '../../lib/motion';
|
||||
import { useWide } from '../../lib/media';
|
||||
|
||||
const FRUITS: Fruit[] = ['strawberry', 'banana', 'lime', 'plum'];
|
||||
@@ -975,21 +975,24 @@ function HalliGalliSide({ view: v, me, players }: BoardProps<HalliGalliView>) {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong}
|
||||
{/* The ranking waits for the last bell's slap and card flights. */}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
@@ -1221,6 +1224,7 @@ const ui: GameUI<HalliGalliView, HalliGalliOptions> = {
|
||||
Board: HalliGalliBoard,
|
||||
Side: HalliGalliSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -20,6 +20,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { MascotIcon, RaceCard } from './art';
|
||||
import { helpNow } from './help';
|
||||
@@ -708,8 +709,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps<HotStreakView>
|
||||
}
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const lastRes = v.results.at(-1);
|
||||
const showPayout = v.phase === 'payout' && lastRes && !replay.busy;
|
||||
const answered = v.phase === 'payout' && lastRes && !replay.busy ? lastRes.side.yes : null;
|
||||
// The payout and the side answer wait until the race has played to the end (its last 1등!/실격! floats included).
|
||||
const showPayout = useMotionSettled(v.phase === 'payout' && !!lastRes && !replay.busy);
|
||||
const answered = showPayout && lastRes ? lastRes.side.yes : null;
|
||||
const r = v.race;
|
||||
const house = HOUSE(v);
|
||||
const shownLog = r && line ? r.log.filter((l) => l.n <= line.n) : [];
|
||||
@@ -726,12 +728,14 @@ function Board({ view: v, me, players, act, pending }: BoardProps<HotStreakView>
|
||||
))}
|
||||
{v.phase !== 'finished' && <SideCard v={v} answered={answered} />}
|
||||
</div>
|
||||
{v.result && <FinalPanel v={v} me={me} players={players} />}
|
||||
<AfterMotion when={!!v.result}>
|
||||
<FinalPanel v={v} me={me} players={players} />
|
||||
</AfterMotion>
|
||||
{v.phase === 'draft' && v.mode === 'tickets' && v.draft && <DraftPanel v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'double' && <DoublePanel v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'draft' && v.mode === 'pots' && <PotPanel v={v} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'submit' && <SubmitPanel v={v} me={me} act={act} pending={pending} />}
|
||||
{showPayout && <PayoutPanel v={v} me={me} players={players} act={act} pending={pending} res={lastRes} />}
|
||||
{showPayout && lastRes && <PayoutPanel v={v} me={me} players={players} act={act} pending={pending} res={lastRes} />}
|
||||
<RaceArea v={v} me={me} act={act} pending={pending} replay={replay} compact={compact} />
|
||||
{v.faceUp.length > 0 && (v.phase === 'draft' || v.phase === 'double' || v.phase === 'submit') && <DeckList v={v} />}
|
||||
{shownLog.length > 0 && (
|
||||
@@ -779,6 +783,9 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<HotStr
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const playing = v.phase !== 'finished';
|
||||
const timed = v.phase === 'draft' || v.phase === 'double' || v.phase === 'submit';
|
||||
// Money changes at the payout: the new amounts show once the race has finished playing on the board.
|
||||
const moneyKey = useAfterMotionValue(v.seats.map((p) => v.money[p] ?? 0).join(','));
|
||||
const money = Object.fromEntries(v.seats.map((p, i) => [p, Number(moneyKey.split(',')[i] ?? v.money[p] ?? 0)]));
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 12, gap: 8 }} aria-label="참가자">
|
||||
@@ -797,8 +804,8 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<HotStr
|
||||
</div>
|
||||
<div className="small muted">{statusOf(v, p)}</div>
|
||||
</div>
|
||||
<strong style={{ fontSize: '1.15rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} ${v.money[p]}달러`}>
|
||||
{$(v.money[p]!)}
|
||||
<strong style={{ fontSize: '1.15rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} ${money[p]}달러`}>
|
||||
{$(money[p]!)}
|
||||
</strong>
|
||||
{on && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={34} />}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useEffect, useRef, useState, type ReactElement } from 'react';
|
||||
import type { HsRaceView, RaceLine, Racer } from '@bg/games/hot-streak';
|
||||
import { MASCOTS, MASCOT_IDS, josa, type MascotId } from '@bg/games/hot-streak/cards';
|
||||
import { noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionHold } from '../../lib/motion';
|
||||
import { MascotFace } from './art';
|
||||
|
||||
export const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
@@ -210,6 +210,8 @@ export function useReplay(r: HsRaceView | null) {
|
||||
q.current.push(...fresh);
|
||||
if (!s.playing) pump();
|
||||
}, [r?.no, r?.log.at(-1)?.n]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The lines play with timers (gaps between hops are not animations): results wait until the last line has played.
|
||||
useMotionHold(busy);
|
||||
|
||||
return { shown, floats, busy };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { addedPieces, janggiCues, janggiMotion } from './fx';
|
||||
import { helpNow } from './help';
|
||||
import { nopeSound, pickSound, playJanggi, setupSound } from './sound';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const SIDE_KO: Record<Side, string> = { cho: '초', han: '한' };
|
||||
const INK: Record<Side, string> = { cho: '#1d4ed8', han: '#c0262d' };
|
||||
@@ -207,6 +207,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
const [kbd, setKbd] = useState(false);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [bubble, setBubble] = useState<Bubble | null>(null);
|
||||
// 장군!/멍군!/빅장! wait until the piece has landed (and the 장군 pulse has played).
|
||||
const [dueBubble, setDueBubble] = useState<Bubble | null>(null);
|
||||
const bubbleReady = useMotionSettled(dueBubble !== null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prev = useRef({ count: v.moveCount, inCheck: v.inCheck, bikjang: v.bikjang, phase: v.phase });
|
||||
|
||||
@@ -245,8 +248,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
// Sounds, bubbles and announcements when the position changes.
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
const show = (text: string, color: string) => setBubble({ text, color, id: Date.now() });
|
||||
playJanggi(janggiCues(p, v), landSec * 1000);
|
||||
const show = (text: string, color: string) => setDueBubble({ text, color, id: Date.now() });
|
||||
// The slide plays at the game speed, so the landing sounds wait the scaled time.
|
||||
playJanggi(janggiCues(p, v), fxMs(landSec * 1000));
|
||||
if (v.moveCount > p.count) {
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
if (m.kind === 'move') {
|
||||
@@ -269,6 +273,12 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
setPreview(null);
|
||||
}, [v.moveCount, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubbleReady || !dueBubble) return;
|
||||
setBubble(dueBubble);
|
||||
setDueBubble(null);
|
||||
}, [bubbleReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubble) return;
|
||||
const t = setTimeout(() => setBubble(null), fxMs(1600));
|
||||
@@ -361,6 +371,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
const ghostTo = selected !== null ? (preview ?? (hover !== null && legal.get(selected)?.some((m) => m.to === hover) ? hover : null)) : null;
|
||||
const vias = new Set<number>();
|
||||
for (const t of targets) if (t.via !== null && (ghostTo === null || t.to === ghostTo)) vias.add(t.via);
|
||||
// The 장군 / 빅장 notes under the board show once the move that caused them has landed.
|
||||
const checkShown = useAfterMotionValue(v.inCheck);
|
||||
const bikjangShown = useAfterMotionValue(v.bikjang?.calledBy ?? null);
|
||||
const kingInCheck = v.inCheck ? v.board.findIndex((p) => p?.kind === 'king' && p.side === v.inCheck) : -1;
|
||||
const last = v.lastMove;
|
||||
const pad = 0.95;
|
||||
@@ -531,18 +544,18 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
{announce}
|
||||
</p>
|
||||
<div className="stack jg-rows" style={{ gap: 10 }}>
|
||||
{v.phase === 'playing' && v.inCheck && (
|
||||
{v.phase === 'playing' && checkShown && (
|
||||
<div className="card" role="alert" style={{ padding: '8px 12px', background: 'var(--danger-soft)', color: 'var(--danger)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.inCheck === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[v.inCheck]} 장군!`}
|
||||
{checkShown === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[checkShown]} 장군!`}
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'playing' && v.bikjang && (
|
||||
{v.phase === 'playing' && bikjangShown && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.bikjang.calledBy === v.mySide
|
||||
{bikjangShown === v.mySide
|
||||
? '빅장을 불렀어요. 상대가 막지 못하면 점수로 판정해요.'
|
||||
: v.mySide
|
||||
? '빅장이에요! 궁 사이를 막거나 궁을 옆으로 옮기지 않으면 점수로 판정해요.'
|
||||
: `${SIDE_KO[v.bikjang.calledBy]} 빅장!`}
|
||||
: `${SIDE_KO[bikjangShown]} 빅장!`}
|
||||
</div>
|
||||
)}
|
||||
{myTurn && v.repeatWarning && (
|
||||
@@ -764,7 +777,8 @@ function JanggiSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
}
|
||||
|
||||
function ScoreBar({ view: v }: { view: JanggiView }) {
|
||||
const { cho, han } = v.scores;
|
||||
// A capture changes the score once the capturing piece has landed.
|
||||
const [cho, han] = useAfterMotionValue(`${v.scores.cho}|${v.scores.han}`).split('|').map(Number) as [number, number];
|
||||
const pct = (cho / (cho + han)) * 100;
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px' }} aria-label={`점수 초 ${fmtScore(cho)}, 한 ${fmtScore(han)}`}>
|
||||
@@ -826,7 +840,10 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView;
|
||||
const id = v.players[side];
|
||||
const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
|
||||
const active = (v.phase === 'playing' && v.turn === side) || (v.phase === 'setup' && v.setup.waitingFor.includes(side));
|
||||
const caps = [...v.captured[side]].sort((a, b) => VALUE[b] - VALUE[a]);
|
||||
// Captured pieces and the 장군 mark appear once the move has landed.
|
||||
const capsKey = useAfterMotionValue(v.captured[side].join(','));
|
||||
const inCheck = useAfterMotionValue(v.inCheck);
|
||||
const caps = (capsKey ? (capsKey.split(',') as PieceKind[]) : []).sort((a, b) => VALUE[b] - VALUE[a]);
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? INK[side] : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<div className="row" style={{ gap: 10 }}>
|
||||
@@ -842,7 +859,7 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView;
|
||||
<div className="small" style={{ color: INK[side], fontWeight: 700 }}>
|
||||
{SIDE_KO[side]} {side === 'cho' ? '· 선수' : '· 후수 덤 1.5'}
|
||||
{v.phase === 'playing' && v.turn === side ? ' · 두는 중' : ''}
|
||||
{v.inCheck === side ? ' · 장군!' : ''}
|
||||
{inCheck === side ? ' · 장군!' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<Clock view={v} side={side} deadline={deadline} mine={id === me} />
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const ROLL_MS = 650;
|
||||
const HOUSE = 'house';
|
||||
@@ -309,6 +309,16 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevRoll = useRef(v.rollSeq);
|
||||
const prevView = useRef(v);
|
||||
// The dice tumble (timers + flicking faces): what was rolled shows only after it.
|
||||
useMotionHold(rolling);
|
||||
// A round's banner ("+30점") waits until its settlement has been dealt out on the screen.
|
||||
const [bannerNext, setBannerNext] = useState<{ text: string; sub?: string; key: number } | null>(null);
|
||||
const bannerReady = useMotionSettled(!!bannerNext);
|
||||
useEffect(() => {
|
||||
if (!bannerReady || !bannerNext) return;
|
||||
setBanner(bannerNext);
|
||||
setBannerNext(null);
|
||||
}, [bannerReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// New roll: tumble animation + screen-reader text.
|
||||
useLayoutEffect(() => {
|
||||
@@ -387,11 +397,15 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
settleSound(delay + 150, ties, awards.length, mineAw.length > 0, more);
|
||||
const seated = !!me && v.seats.includes(me) && !v.conceded.includes(me);
|
||||
const got = mineAw.reduce((t, a) => t + (a.note ?? 0), 0);
|
||||
setBanner({
|
||||
text: more ? `${rr.round}라운드 정산` : '최종 정산',
|
||||
sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined,
|
||||
key: v.roundResults.length,
|
||||
});
|
||||
// The last one only announces the final settlement right away (the room's result window waits for it); the
|
||||
// amounts are in the final table that follows.
|
||||
if (more) {
|
||||
setBannerNext({
|
||||
text: `${rr.round}라운드 정산`,
|
||||
sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined,
|
||||
key: v.roundResults.length,
|
||||
});
|
||||
} else setBanner({ text: '최종 정산', key: v.roundResults.length });
|
||||
if (more) setDealt(v.round);
|
||||
haptic([50, 30, 50]);
|
||||
}
|
||||
@@ -467,7 +481,9 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
)}
|
||||
{v.result && lastRR && (
|
||||
<div className="lv-lower">
|
||||
<FinalTable v={v} me={me} players={players} />
|
||||
<AfterMotion>
|
||||
<FinalTable v={v} me={me} players={players} />
|
||||
</AfterMotion>
|
||||
<Settlement round={lastRR.round} payouts={lastRR.payouts} v={v} me={me} players={players} />
|
||||
</div>
|
||||
)}
|
||||
@@ -759,6 +775,8 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
const [ask, setAsk] = useState(false);
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const mine = me ? v.money[me] : undefined;
|
||||
const myCount = useAfterMotionValue(mine?.count ?? 0);
|
||||
const myTotal = useAfterMotionValue(mine?.total ?? 0);
|
||||
const playing = v.phase !== 'finished';
|
||||
return (
|
||||
<>
|
||||
@@ -792,17 +810,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
{out ? '기권' : v.away.includes(p) ? '자리 비움' : playing ? `주사위 ${h.own}${v.neutralPer ? ` · 흰 ${h.neutral}` : ''}` : '끝'}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}
|
||||
aria-label={`${nick(players, p)} 지폐 ${m.count}장${m.total !== null ? `, ${m.total}점` : ''}`}
|
||||
>
|
||||
<strong style={{ fontSize: '1.2rem' }}>
|
||||
<Bump value={m.total}>{m.total !== null ? `${m.total}점` : '?'}</Bump>
|
||||
</strong>
|
||||
<div className="small muted">
|
||||
<Bump value={m.count}>{m.count}장</Bump>
|
||||
</div>
|
||||
</span>
|
||||
<Money name={nick(players, p)} total={m.total} count={m.count} />
|
||||
{turn && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={40} />}
|
||||
</div>
|
||||
);
|
||||
@@ -813,7 +821,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
<div className="row small" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>내 지폐</strong>
|
||||
<span>
|
||||
{mine.count}장 · {mine.total ?? 0}점
|
||||
{myCount}장 · {myTotal}점
|
||||
</span>
|
||||
</div>
|
||||
<MyBills notes={mine.notes ?? []} />
|
||||
@@ -843,6 +851,22 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
);
|
||||
}
|
||||
|
||||
/** A seat's money; changes once the settlement has been dealt out on the board. */
|
||||
function Money({ name, total: totalNow, count: countNow }: { name: string; total: number | null; count: number }) {
|
||||
const total = useAfterMotionValue(totalNow);
|
||||
const count = useAfterMotionValue(countNow);
|
||||
return (
|
||||
<span style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }} aria-label={`${name} 지폐 ${count}장${total !== null ? `, ${total}점` : ''}`}>
|
||||
<strong style={{ fontSize: '1.2rem' }}>
|
||||
<Bump value={total}>{total !== null ? `${total}점` : '?'}</Bump>
|
||||
</strong>
|
||||
<div className="small muted">
|
||||
<Bump value={count}>{count}장</Bump>
|
||||
</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** My bills; the ones just received fly in (my own amounts are always visible to me). */
|
||||
function MyBills({ notes }: { notes: number[] }) {
|
||||
const sig = notes.join(',');
|
||||
|
||||
@@ -21,7 +21,7 @@ import { BotActivity } from '../../components/BotActivity';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
type Kind = LiarView['phase']['kind'];
|
||||
|
||||
@@ -69,6 +69,15 @@ function josa(word: string, pair: [string, string]): string {
|
||||
return `${word}${c >= 0 && c < 11172 && c % 28 !== 0 ? pair[0] : pair[1]}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last event number as of the last still screen, and whether a newer announcement (vote result, accused, the
|
||||
* liar's answer, the end) is still playing out: what it reveals waits until its vote rows, spotlight and banners are done.
|
||||
*/
|
||||
function useShownEvents(v: LiarView): { shownN: number; settling: boolean } {
|
||||
const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0);
|
||||
return { shownN, settling: v.events.some((e) => e.n > shownN && e.t !== 'phase' && e.t !== 'left') };
|
||||
}
|
||||
|
||||
function phaseTitle(v: LiarView): string {
|
||||
const ph = v.phase;
|
||||
if (ph.kind === 'describe') return v.rounds > 1 ? `${ph.round}바퀴째 설명` : PHASE_KO.describe;
|
||||
@@ -296,9 +305,10 @@ function latestNews(events: PublicEvent[]): PublicEvent[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
function News({ v, players }: { v: LiarView; players: Record<string, PublicUser> }) {
|
||||
const news = latestNews(v.events);
|
||||
if (!news.length || v.final) return null;
|
||||
function News({ v, players, shownN, finalShown }: { v: LiarView; players: Record<string, PublicUser>; shownN: number; finalShown: boolean }) {
|
||||
// The vote rows are the animation itself; what comes after them (accused, the answer) waits for it.
|
||||
const news = latestNews(v.events).filter((e) => e.t === 'vote' || e.n <= shownN);
|
||||
if (!news.length || finalShown) return null;
|
||||
const title = news.some((e) => e.t === 'accused') ? '투표 결과' : news.some((e) => e.t === 'vote') ? '투표 결과' : '알림';
|
||||
return (
|
||||
<section className="lg-news" key={news[0]!.n} aria-label={title} role="status">
|
||||
@@ -356,7 +366,9 @@ type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void
|
||||
|
||||
function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; spot: string | null }) {
|
||||
const ph = v.phase;
|
||||
const accused = v.final?.accused ?? ph.liar;
|
||||
// Who was accused / who is the liar shows only after the result has played out.
|
||||
const accused = useAfterMotionValue(v.final?.accused ?? ph.liar ?? '') || null;
|
||||
const liars = useAfterMotionValue(v.players.filter((p) => p.liar === true).map((p) => p.id).join(',')).split(',');
|
||||
return (
|
||||
<section className="lg-box" aria-label="사람들과 말하는 순서">
|
||||
<h2>
|
||||
@@ -381,7 +393,7 @@ function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players
|
||||
</span>
|
||||
{speaking && <span className="lg-tag say">말하는 중</span>}
|
||||
{ph.kind === 'vote' && p.voted && <span className="lg-tag ok anim-pop">투표함</span>}
|
||||
{p.liar === true && <span className="lg-tag liar anim-pop">🤥 라이어</span>}
|
||||
{liars.includes(id) && <span className="lg-tag liar anim-pop">🤥 라이어</span>}
|
||||
{p.left && <span className="lg-tag">나감</span>}
|
||||
</>
|
||||
);
|
||||
@@ -389,7 +401,7 @@ function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players
|
||||
`${i + 1}번째, ${u.nickname}${id === me ? '(나)' : ''}`,
|
||||
speaking ? '지금 설명하는 사람' : '',
|
||||
ph.kind === 'vote' && p.voted ? '투표함' : '',
|
||||
p.liar === true ? '라이어' : '',
|
||||
liars.includes(id) ? '라이어' : '',
|
||||
p.left ? '나감' : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
@@ -452,12 +464,12 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record<string,
|
||||
type Line = ({ k: 'chat'; text: string; from: string; key: string } | { k: 'sys'; e: PublicEvent }) & { at: number };
|
||||
const runKey = (l: Line | undefined) => l && { from: l.k === 'chat' ? l.from : null, at: l.at };
|
||||
|
||||
function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void }) {
|
||||
function ChatBox({ v, players, me, act, shownN }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; shownN: number }) {
|
||||
const [text, setText] = useState('');
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const send = (t: string) => act({ type: 'chat', text: t });
|
||||
const lines: Line[] = [
|
||||
...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })),
|
||||
...v.events.filter((e) => e.n <= shownN && (e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess')).map((e) => ({ k: 'sys' as const, e, at: e.at })),
|
||||
...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })),
|
||||
// Stable sort: same moment keeps the event order, announcements before chat.
|
||||
].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1));
|
||||
@@ -578,12 +590,15 @@ function GuessForm({ v, act, pending }: { v: LiarView; act: (a: unknown) => void
|
||||
);
|
||||
}
|
||||
|
||||
function Actions({ v, players, me, act, pending }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean }) {
|
||||
function Actions({ v, players, me, act, pending, settling }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean; settling: boolean }) {
|
||||
const my = v.my;
|
||||
const ph = v.phase;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
let body: ReactNode = null;
|
||||
if (!my) {
|
||||
if (settling) {
|
||||
// The next step (guess, re-vote, the end) gives the result away: it shows once the result has played out.
|
||||
body = <p className="lg-prompt">결과를 공개하는 중이에요…</p>;
|
||||
} else if (!my) {
|
||||
body = <p className="lg-prompt">관전 중이에요. 주제는 {v.topicKo}이고, 제시어는 게임이 끝나면 공개돼요.</p>;
|
||||
} else if (ph.kind === 'ended') {
|
||||
body = <p className="lg-prompt">게임이 끝났어요. 라이어와 제시어가 공개됐어요.</p>;
|
||||
@@ -666,7 +681,7 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor
|
||||
}
|
||||
return (
|
||||
<section className="lg-box" aria-label="할 일">
|
||||
<h2>{ph.kind === 'ended' ? '🏁 결과' : '🎯 할 일'}</h2>
|
||||
<h2>{ph.kind === 'ended' && !settling ? '🏁 결과' : '🎯 할 일'}</h2>
|
||||
{body}
|
||||
</section>
|
||||
);
|
||||
@@ -742,6 +757,9 @@ function useLiarFx(v: LiarView, me: string | null, players: Record<string, Publi
|
||||
const prev = useRef(v);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
useEffect(() => () => timers.current.forEach(clearTimeout), []);
|
||||
// The result plays with timers (quiet gaps between the vote rows, spotlight and banners): results wait for it all.
|
||||
const [staging, setStaging] = useState(false);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
@@ -803,6 +821,8 @@ function useLiarFx(v: LiarView, me: string | null, players: Record<string, Publi
|
||||
later(t, () => showBanner(e.winner === 'liar' ? '라이어 승리!' : '시민 승리!', e.winner === 'liar' ? 'red' : 'blue', liar ? `라이어는 ${nick(players, liar)}님` : undefined));
|
||||
}
|
||||
}
|
||||
setStaging(true);
|
||||
later(t, () => setStaging(false));
|
||||
return;
|
||||
}
|
||||
if (fresh.some((e) => e.t === 'left')) return sfx.whoosh();
|
||||
@@ -814,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;
|
||||
@@ -836,41 +856,47 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
const [banner, showBanner] = useBanner();
|
||||
const [spot, setSpot] = useState<Spot | null>(null);
|
||||
useLiarFx(v, me, players, showBanner, setSpot);
|
||||
const { shownN, settling } = useShownEvents(v);
|
||||
const finalShown = useMotionSettled(!!v.final && !settling);
|
||||
|
||||
const pick: Pick = my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null;
|
||||
const hot = ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe);
|
||||
const sub =
|
||||
const pick: Pick = !settling && my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null;
|
||||
const hot = !settling && (ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe));
|
||||
const sub = useAfterMotionValue(
|
||||
ph.kind === 'describe' && ph.speaker
|
||||
? `${nick(players, ph.speaker)}님 차례 · 주제: ${v.topicKo}`
|
||||
: ph.kind === 'ended'
|
||||
? (v.final?.summary ?? '')
|
||||
: `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`;
|
||||
: `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`,
|
||||
);
|
||||
// The phase title (라이어 맞히기, 게임 끝) would give the result away: it changes once the screen is still.
|
||||
const title = useAfterMotionValue(phaseTitle(v));
|
||||
return (
|
||||
<div className="lg">
|
||||
<style>{CSS}</style>
|
||||
<section className="lg-banner" data-time={ph.kind === 'ended' ? 'end' : 'play'} data-hot={hot} aria-label="진행 상황">
|
||||
<section className="lg-banner" data-time={finalShown ? 'end' : 'play'} data-hot={hot} aria-label="진행 상황">
|
||||
<span className="lg-ph">
|
||||
<span className="d">🤥 라이어 게임</span>
|
||||
<strong key={phaseKey} className="anim-slide-up">
|
||||
{phaseTitle(v)}
|
||||
<strong key={title} className="anim-slide-up">
|
||||
{title}
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <WordCard v={v} always={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} />
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<News v={v} players={players} shownN={shownN} finalShown={finalShown} />
|
||||
{finalShown && <FinalReveal v={v} players={players} />}
|
||||
<div className="lg-grid">
|
||||
<div className="lg-col lg-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} spot={spot?.id ?? null} />
|
||||
</div>
|
||||
<div className="lg-col lg-talk">
|
||||
<Descriptions v={v} players={players} me={me} />
|
||||
<ChatBox v={v} players={players} me={me} act={act} />
|
||||
<ChatBox v={v} players={players} me={me} act={act} shownN={shownN} />
|
||||
</div>
|
||||
<div className="lg-col lg-actions">
|
||||
<Actions v={v} players={players} me={me} act={act} pending={pending} />
|
||||
<Actions v={v} players={players} me={me} act={act} pending={pending} settling={settling} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -885,11 +911,14 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function LiarSide({ view: v, players }: BoardProps<LiarView>) {
|
||||
const log = v.events.filter((e) => e.t !== 'phase');
|
||||
// Announcements join the log once the board has played them out.
|
||||
const { shownN } = useShownEvents(v);
|
||||
const log = v.events.filter((e) => e.t !== 'phase' && e.n <= shownN);
|
||||
const title = useAfterMotionValue(phaseTitle(v));
|
||||
return (
|
||||
<>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>라이어 게임 · {phaseTitle(v)}</strong>
|
||||
<strong>라이어 게임 · {title}</strong>
|
||||
<span className="small">주제: {v.topicKo}</span>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* While the game runs the room chat panel and quick reactions are closed (`ownChat`), so night talk
|
||||
* cannot leak through the room chat; after the game the room chat opens again.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import type { Channel, ChatView, MafiaOptions, MafiaView, PlayerView, PrivateResult, PublicEvent, Role, Team } from '@bg/games/mafia';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
@@ -19,7 +19,7 @@ import { keepFocus, useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- names (original names only, docs §12)
|
||||
|
||||
@@ -392,15 +392,18 @@ type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void
|
||||
/** Tiles animating right now: who just left the game (turns over and greys out), who was spared. */
|
||||
type TileFx = { dying: string[]; saved: string[] };
|
||||
|
||||
function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null }) {
|
||||
function Players({ v, players, me, pick, pending, fx, hiddenDead, hideRoles }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null; hiddenDead: string[]; hideRoles: boolean }) {
|
||||
const mafiaChoice = v.my?.night?.action === 'mafiaTarget' ? v.my.night.choice : null;
|
||||
// Deaths whose turn-over has not played yet still look alive (the sun is still coming up).
|
||||
const aliveCount = v.aliveCount + hiddenDead.length;
|
||||
return (
|
||||
<section className="mf-box" aria-label={`사람들. 살아 있는 사람 ${v.aliveCount}명`}>
|
||||
<section className="mf-box" aria-label={`사람들. 살아 있는 사람 ${aliveCount}명`}>
|
||||
<h2>
|
||||
사람들 <span className="small muted">살아 있는 사람 {v.aliveCount}명</span>
|
||||
사람들 <span className="small muted">살아 있는 사람 {aliveCount}명</span>
|
||||
</h2>
|
||||
<div className="mf-tiles">
|
||||
{v.players.map((p) => {
|
||||
{v.players.map((q) => {
|
||||
const p = hiddenDead.includes(q.id) ? { ...q, alive: true, role: q.id === me || v.my?.mates.includes(q.id) ? q.role : null, team: null } : q;
|
||||
const u = userOf(players, p.id);
|
||||
const cls = `mf-tile${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}${p.id === v.phase.accused ? ' accused' : ''}${fx?.dying.includes(p.id) ? ' dying' : fx?.saved.includes(p.id) ? ' saved' : ''}`;
|
||||
const can = pick?.ids.includes(p.id) ?? false;
|
||||
@@ -411,7 +414,7 @@ function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players:
|
||||
{u.nickname}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleTag p={p} meId={me} />
|
||||
{!hideRoles && <RoleTag p={p} meId={me} />}
|
||||
{!p.alive && <span className="mf-tag">탈락 · {p.diedDay}일차</span>}
|
||||
{p.id === v.phase.accused && <span className="mf-tag mark">지목됨</span>}
|
||||
{mafiaChoice === p.id && !pick && <span className="mf-tag mark">🎯 오늘 밤 대상</span>}
|
||||
@@ -585,6 +588,9 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
const my = v.my;
|
||||
const ph = v.phase;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
// A night's investigation result shows once the morning has come up on screen.
|
||||
const resultCount = useAfterMotionValue(my?.results.length ?? 0);
|
||||
const results = my ? my.results.slice(0, resultCount) : [];
|
||||
let body: ReactNode = null;
|
||||
if (!my) {
|
||||
body = <p className="mf-prompt">관전 중이에요. 낮 채팅과 발표만 볼 수 있어요.</p>;
|
||||
@@ -720,11 +726,11 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
<h2>{ph.kind === 'night' ? '🌙 오늘 밤' : ph.kind === 'ended' ? '🏁 결과' : '☀️ 할 일'}</h2>
|
||||
{body}
|
||||
{my?.idleWarning && ph.kind !== 'ended' && <strong style={{ color: 'var(--danger)' }}>오늘도 아무것도 하지 않으면 자리 비움으로 탈락해요.</strong>}
|
||||
{my && my.results.length > 0 && (
|
||||
{my && results.length > 0 && (
|
||||
<>
|
||||
<strong className="small">{my.role === 'medium' ? '영매 결과 (나만 봐요)' : '조사 결과 (나만 봐요)'}</strong>
|
||||
<ul className="mf-results">
|
||||
{my.results.map((r) => (
|
||||
{results.map((r) => (
|
||||
<li key={r.id}>{resultText(r, players)}</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -792,11 +798,16 @@ type ShowBanner = (text: string, tone?: BannerTone, sub?: string) => void;
|
||||
* Sounds and motion for what anyone did: announcements (votes, deaths, saves, the end), choices, the done count.
|
||||
* Banners come one after another (a morning death, then the winning side); a new announcement cancels queued ones.
|
||||
*/
|
||||
function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): void {
|
||||
function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): string[] {
|
||||
const prev = useRef(v);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
// The banners / tile motion still to come (timers): results wait for them. Deaths whose tile has not turned over yet.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const [hiddenDead, setHiddenDead] = useState<string[]>([]);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => timers.current.forEach(clearTimeout), []);
|
||||
useEffect(() => {
|
||||
// Layout effect: a new death must not show on its tile for even one frame before its turn.
|
||||
useLayoutEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
@@ -828,11 +839,18 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
|
||||
timers.current = [];
|
||||
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f());
|
||||
const start = isNight(p) && !isNight(v) ? 900 : 0;
|
||||
setHiddenDead(dying);
|
||||
if (dying.length || saved.length) {
|
||||
later(start, () => setTileFx({ dying, saved }));
|
||||
later(start, () => {
|
||||
setHiddenDead([]);
|
||||
setTileFx({ dying, saved });
|
||||
});
|
||||
later(start + 1200, () => setTileFx(null));
|
||||
}
|
||||
banners.forEach(([text, tone, sub], i) => later(start + i * 1500, () => showBanner(text, tone, sub)));
|
||||
const end = Math.max(dying.length || saved.length ? start + 1200 : 0, banners.length ? start + (banners.length - 1) * 1500 : 0);
|
||||
setStaging(end > 0);
|
||||
later(end, () => setStaging(false));
|
||||
}
|
||||
let played = false;
|
||||
const play = (f: () => void) => {
|
||||
@@ -856,9 +874,16 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
|
||||
if (my && pm && (my.vote !== pm.vote || my.ballot !== pm.ballot || my.night?.choice !== pm.night?.choice)) return play(sfx.select);
|
||||
if (v.phase.readyCount > p.phase.readyCount && v.phase.kind === p.phase.kind) play(sfx.chip);
|
||||
}, [v]);
|
||||
return hiddenDead;
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView>) {
|
||||
/** `v.events` up to the last one whose banners / motion have finished playing. */
|
||||
function useShownEvents(v: MafiaView): PublicEvent[] {
|
||||
const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0);
|
||||
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, 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;
|
||||
@@ -880,7 +905,14 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
const [tileFx, setTileFx] = useState<TileFx | null>(null);
|
||||
useMafiaFx(v, players, showBanner, setTileFx);
|
||||
const hiddenDead = useMafiaFx(v, players, showBanner, setTileFx);
|
||||
// Announcements (news, chat lines) and the final reveal show once the banners and the sky have played.
|
||||
const shownEvents = useShownEvents(v);
|
||||
const shownV = shownEvents === v.events ? v : { ...v, events: shownEvents };
|
||||
const endShown = useMotionSettled(ph.kind === 'ended');
|
||||
// My own death shows (role card, 탈락 panel) when my tile turns over, like everyone else's.
|
||||
const meHidden = !!me && !!my && hiddenDead.includes(me);
|
||||
const actV = meHidden ? { ...v, my: { ...my!, alive: true } } : v;
|
||||
// Night falls / morning comes (for everyone, whoever's button press moved the phase on).
|
||||
const [sky, setSky] = useState<{ kind: 'night' | 'day'; key: string } | null>(null);
|
||||
const wasNight = useRef(isNight(v));
|
||||
@@ -907,7 +939,9 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
: ph.kind === 'discussion' && ph.adjustedBy.length
|
||||
? `시간 바꾼 사람: ${ph.adjustedBy.map((id) => nick(players, id)).join(', ')}`
|
||||
: ph.kind === 'ended'
|
||||
? v.final?.summary
|
||||
? endShown
|
||||
? v.final?.summary
|
||||
: ''
|
||||
: `살아 있는 사람 ${v.aliveCount}명`;
|
||||
return (
|
||||
<div className="mf">
|
||||
@@ -922,20 +956,23 @@ 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'} />
|
||||
{my && <RoleCard role={my.role} mates={my.mates} players={players} always={!!v.winner || !my.alive} />}
|
||||
{/* 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={v} players={players} />
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<News v={shownV} players={players} />
|
||||
<AfterMotion when={!!v.final}>
|
||||
<FinalReveal v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<div className="mf-grid">
|
||||
<div className="mf-col mf-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} fx={tileFx} />
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} fx={tileFx} hiddenDead={hiddenDead} hideRoles={ph.kind === 'ended' && !endShown} />
|
||||
</div>
|
||||
<div className="mf-col mf-chatwrap">
|
||||
<ChatBox v={v} players={players} me={me} act={act} />
|
||||
<ChatBox v={shownV} players={players} me={me} act={act} />
|
||||
</div>
|
||||
<div className="mf-col mf-actions">
|
||||
<Actions v={v} players={players} me={me} act={act} pending={pending} />
|
||||
<Actions v={actV} players={players} me={me} act={act} pending={pending} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -960,6 +997,7 @@ function composition(setup: MafiaView['setup']): string {
|
||||
}
|
||||
|
||||
function MafiaSide({ view: v, players }: BoardProps<MafiaView>) {
|
||||
const events = useShownEvents(v);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -970,11 +1008,11 @@ function MafiaSide({ view: v, players }: BoardProps<MafiaView>) {
|
||||
<span className="small">이번 판 직업: {composition(v.setup)}</span>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
</div>
|
||||
{v.events.length > 0 && (
|
||||
{events.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>발표 기록</summary>
|
||||
<ol className="mf-log">
|
||||
{[...v.events]
|
||||
{[...events]
|
||||
.reverse()
|
||||
.filter((e) => e.t !== 'phase')
|
||||
.map((e) => (
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { itemsOf, type Item } from './replay';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4'];
|
||||
|
||||
@@ -692,6 +692,10 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) {
|
||||
pump();
|
||||
}, [r?.no, lastN]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The drawing replays the race step by step with timers: results (scores, the next race, 결과) wait for it.
|
||||
const w = d.current;
|
||||
useMotionHold(!!w.timer || w.q.length > 0 || !!w.walk || !!w.die?.rolling);
|
||||
|
||||
return { d: d.current, floats, confetti, banner };
|
||||
}
|
||||
|
||||
@@ -1019,7 +1023,13 @@ const STEP_TITLE: Record<MaPrompt['step'], string> = {
|
||||
};
|
||||
|
||||
function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; rolling: boolean }) {
|
||||
const pr = v.prompt;
|
||||
// A new choice (it can tell the roll: "다시 굴릴까요?", "4칸 가기") shows once the die and the runners have stopped;
|
||||
// until then the previous one stays, greyed out.
|
||||
const key = v.prompt ? `${v.prompt.owner}|${v.prompt.step}|${v.prompt.racer ?? ''}|${v.prompt.options.map((o) => o.key).join(',')}` : '';
|
||||
const settling = useAfterMotionValue(key) !== key;
|
||||
const kept = useRef(v.prompt);
|
||||
if (!settling) kept.current = v.prompt;
|
||||
const pr = kept.current;
|
||||
if (v.phase !== 'race') return null;
|
||||
const mine = !!pr && pr.owner === me;
|
||||
return (
|
||||
@@ -1033,7 +1043,7 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet
|
||||
</h3>
|
||||
<div className={`ma-opts${pr.options.length > 2 ? ' many' : ''}`} role="group" aria-label={STEP_TITLE[pr.step]}>
|
||||
{pr.options.map((o, i) => (
|
||||
<button key={o.key} type="button" className={`btn ${i === 0 ? 'btn-primary' : 'btn-secondary'} btn-block`} disabled={pending || rolling} onClick={() => act(actionFor(pr, o.key))}>
|
||||
<button key={o.key} type="button" className={`btn ${i === 0 ? 'btn-primary' : 'btn-secondary'} btn-block`} disabled={pending || rolling || settling} onClick={() => act(actionFor(pr, o.key))}>
|
||||
{pr.step === 'roll' && o.key === 'roll' ? `🎲 ${o.label}` : o.label}
|
||||
</button>
|
||||
))}
|
||||
@@ -1059,7 +1069,8 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet
|
||||
}
|
||||
|
||||
function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const r = v.race!;
|
||||
// Positions, falls and places as of the last still screen (the board replays the race behind the view).
|
||||
const r = JSON.parse(useAfterMotionValue(JSON.stringify({ cur: v.race!.cur, racers: v.race!.racers }))) as { cur: RacerId | null; racers: MaRacerView[] };
|
||||
return (
|
||||
<section className="card ma-panel" aria-label="이번 경주 선수">
|
||||
<h3>이번 경주 선수</h3>
|
||||
@@ -1155,7 +1166,9 @@ function Select({ v, me, players, act, pending }: { v: MagicalAthleteView; me: s
|
||||
}
|
||||
|
||||
function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
if (!v.results.length) return null;
|
||||
// A race's result row shows once its finish has been drawn.
|
||||
const results = v.results.slice(0, useAfterMotionValue(v.results.length));
|
||||
if (!results.length) return null;
|
||||
const cell = (id: RacerId | null, rr: RaceResult) => {
|
||||
if (!id) return '—';
|
||||
const o = rr.field.find((x) => x.id === id)!.owner;
|
||||
@@ -1178,7 +1191,7 @@ function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null;
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.results.map((rr) => (
|
||||
{results.map((rr) => (
|
||||
<tr key={rr.no}>
|
||||
<td>
|
||||
{rr.no}
|
||||
@@ -1243,6 +1256,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
const prevLog = useRef<number>(v.race?.log.at(-1)?.n ?? 0);
|
||||
const prevRace = useRef<number>(v.race?.no ?? 0);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
// The race log lists new lines once the board has drawn them.
|
||||
const [logRace, logN] = useAfterMotionValue(`${v.race?.no ?? 0}:${v.race?.log.at(-1)?.n ?? 0}`).split(':').map(Number);
|
||||
const logShown = { race: logRace!, n: logN! };
|
||||
|
||||
// New log lines → screen-reader announcement (the board draws and sounds them).
|
||||
useEffect(() => {
|
||||
@@ -1282,22 +1298,29 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const r = v.race;
|
||||
// A race's end (the next race's selection, the final table, the header) shows once the board has finished
|
||||
// replaying it; until then the screen stays on the race.
|
||||
const stage = `${v.phase}:${v.raceNo}`;
|
||||
const shownStage = useAfterMotionValue(stage);
|
||||
const ready = shownStage === stage;
|
||||
const [phase, raceNo] = ready ? [v.phase, v.raceNo] : [shownStage.slice(0, shownStage.indexOf(':')), Number(shownStage.slice(shownStage.indexOf(':') + 1))];
|
||||
const medal = v.medals[Math.min(raceNo, v.races) - 1] ?? v.medals[0]!;
|
||||
return (
|
||||
<div className="ma-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="card ma-head">
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? '선수 뽑기' : `${v.raceNo} / ${v.races} 경주`}</strong>
|
||||
{r && v.phase === 'race' && <span className={`ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>}
|
||||
<strong>{phase === 'finished' ? '게임 끝' : phase === 'draft' ? '선수 뽑기' : `${raceNo} / ${v.races} 경주`}</strong>
|
||||
{r && phase === 'race' && <span className={`ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>}
|
||||
<span className="small muted">
|
||||
{v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.gold}점 · 2등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.silver}점
|
||||
{v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {medal.gold}점 · 2등 {medal.silver}점
|
||||
</span>
|
||||
</div>
|
||||
{v.result && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.result && ready && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft && <Draft v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'select' && <Select v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'select' && ready && <Select v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{r && (
|
||||
<>
|
||||
{v.phase !== 'race' && (
|
||||
{v.phase !== 'race' && ready && (
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
{r.no}번째 경주가 끝났을 때 모습이에요.
|
||||
</p>
|
||||
@@ -1307,7 +1330,7 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
<section className="card ma-panel" aria-label="경주 기록">
|
||||
<h3>경주 기록</h3>
|
||||
<ul className="ma-log" tabIndex={0} aria-label="경주 기록 (최신이 위)">
|
||||
{[...r.log].reverse().map((l) => (
|
||||
{[...r.log.filter((l) => logShown.race === r.no && l.n <= logShown.n)].reverse().map((l) => (
|
||||
<li key={l.n} className={l.kind}>
|
||||
{ICON[l.kind]} {l.text}
|
||||
</li>
|
||||
@@ -1332,11 +1355,15 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<Magica
|
||||
const [ask, setAsk] = useState(false);
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const playing = v.phase !== 'finished';
|
||||
// Points change once the finish / star that gave them has been drawn.
|
||||
const scoreKey = v.seats.map((p) => [v.scores[p]!.gold, v.scores[p]!.silver, v.scores[p]!.bonus, v.scores[p]!.total].join(',')).join('|');
|
||||
const shownScores = useAfterMotionValue(scoreKey).split('|');
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 12, gap: 8 }} aria-label="참가자">
|
||||
{v.seats.map((p) => {
|
||||
const sc = v.scores[p]!;
|
||||
{v.seats.map((p, i) => {
|
||||
const [gold, silver, bonus, tot] = (shownScores[i] ?? '').split(',').map(Number);
|
||||
const sc = shownScores.length === v.seats.length ? { gold: gold!, silver: silver!, bonus: bonus!, total: tot! } : v.scores[p]!;
|
||||
const on = active.includes(p);
|
||||
return (
|
||||
<div key={p} style={{ padding: '4px 6px', borderRadius: 10, border: `3px solid ${on ? 'var(--focus)' : 'transparent'}` }}>
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MAHJONG_TILE_CREDIT, Tile, tileName, tileOrder, tileShort } from './Tile';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const WIND = ['동', '남', '서', '북'];
|
||||
const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽'];
|
||||
@@ -141,8 +141,9 @@ function useSeen(v: MahjongView): Seen | null {
|
||||
return s.hand === handId(v) ? s : null;
|
||||
}
|
||||
|
||||
/** A number that pops when it changes (not on the first render). */
|
||||
function Bump({ value, children }: { value: number; children?: ReactNode }) {
|
||||
/** A number that pops when it changes (not on the first render), once the move that changed it has played. */
|
||||
function Bump({ value: live, children }: { value: number; children?: ReactNode }) {
|
||||
const value = useAfterMotionValue(live);
|
||||
const prev = useRef(value);
|
||||
const moved = useRef(false);
|
||||
if (prev.current !== value) {
|
||||
@@ -737,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);
|
||||
@@ -779,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 && (
|
||||
@@ -1155,7 +1156,10 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const wide = width >= 900;
|
||||
const reserve = v.my ? 300 : 20;
|
||||
const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560)) : width || 360;
|
||||
const showTable = v.phase === 'playing' || (v.phase === 'handResult' && !wide);
|
||||
// The hand's result (and the final ranking) shows once the 론·쯔모·유국 banner and the last tiles have finished.
|
||||
const resultShown = useMotionSettled(v.phase === 'handResult' && !!v.result);
|
||||
const finalShown = useMotionSettled(v.phase === 'finished');
|
||||
const showTable = v.phase === 'playing' || (v.phase === 'handResult' && (!wide || !resultShown));
|
||||
return (
|
||||
<div className={`mj${wide ? ' wide' : ''}`} ref={ref}>
|
||||
<style>{CSS}</style>
|
||||
@@ -1165,8 +1169,8 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
))}
|
||||
</ul>
|
||||
<div className="mj-main" style={wide ? { width: tableWidth, maxHeight: mainH > 0 ? mainH - 12 : undefined } : undefined}>
|
||||
{v.phase === 'handResult' && v.result && <ResultPanel v={v} players={players} me={me} act={act} pending={pending} deadline={deadline} />}
|
||||
{v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||||
{resultShown && v.phase === 'handResult' && v.result && <ResultPanel v={v} players={players} me={me} act={act} pending={pending} deadline={deadline} />}
|
||||
{finalShown && v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||||
{showTable && (
|
||||
<div className="mj-table-wrap">
|
||||
<Table v={v} players={players} width={tableWidth} callout={callout ? <span key={callout.seq} className={`mj-callout c-${callout.call}`}>{callout.text}</span> : null} seen={seen} />
|
||||
@@ -1217,6 +1221,8 @@ function Toggles({ v, act, pending }: { v: MahjongView; act: (a: unknown) => voi
|
||||
}
|
||||
|
||||
function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProps<MahjongView>) {
|
||||
// A hand's score change is listed once its result has played on the board.
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const turnSeat = v.phase === 'playing' && v.stage !== 'claim' ? v.turn : null;
|
||||
return (
|
||||
<>
|
||||
@@ -1257,11 +1263,11 @@ function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProp
|
||||
</ol>
|
||||
</div>
|
||||
<Toggles v={v} act={act} pending={pending} />
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<details className="card" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>국별 점수 변화</summary>
|
||||
<ol className="mj-hist">
|
||||
{[...v.history].reverse().map((h, i) => (
|
||||
{[...history].reverse().map((h, i) => (
|
||||
<li key={i}>
|
||||
<strong>{h.label}</strong> {h.kind === 'agari' ? '화료' : h.kind === 'exhaustive' ? '유국' : '도중유국'} ·{' '}
|
||||
{v.seats.map((s) => `${nick(players, s.id)} ${signed(h.deltas[s.seat]!)}`).join(' / ')}
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { newEvents, toSegments, type Seg } from './events';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
type GameEvent = MarbleView['log'][number];
|
||||
|
||||
@@ -514,10 +514,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
for (;;) {
|
||||
const seg = w.q[0];
|
||||
if (!seg) {
|
||||
if (w.cur) {
|
||||
w.cur = null;
|
||||
rerender((x) => x + 1);
|
||||
}
|
||||
// Always re-render at the end of the queue: the motion hold below is read from the walker while rendering.
|
||||
w.cur = null;
|
||||
rerender((x) => x + 1);
|
||||
return;
|
||||
}
|
||||
const wait = w.hold - Date.now();
|
||||
@@ -626,19 +625,28 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
seen.current.current = v.current;
|
||||
}, [v.current]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The dice and the walking tokens are played with timers: results (and the room's result window) wait for them.
|
||||
const walking = rolling !== null || !!walker.current.cur || walker.current.q.length > 0;
|
||||
useMotionHold(walking);
|
||||
// What the view says now shows once the board has caught up (the prompt, new owners). `v.owned` / `v.log` come
|
||||
// straight from the view state, so their identity only changes with a new view.
|
||||
const owned = useAfterMotionValue(v.owned);
|
||||
const stepKey = [v.phase, v.current, v.lastRoll?.seq ?? 0, JSON.stringify(v.log[v.log.length - 1] ?? null)].join('|');
|
||||
const settled = useAfterMotionValue(stepKey) === stepKey;
|
||||
|
||||
// Newly bought land / new building: pop in once (not on the first render).
|
||||
const ownSeen = useRef(new Map(v.owned.map((o) => [o.pos, o])));
|
||||
const ownSeen = useRef(new Map(owned.map((o) => [o.pos, o])));
|
||||
const [fresh, setFresh] = useState<Record<number, { claim?: string; level?: number }>>({});
|
||||
useLayoutEffect(() => {
|
||||
const upd: Record<number, { claim?: string; level?: number }> = {};
|
||||
for (const o of v.owned) {
|
||||
for (const o of owned) {
|
||||
const was = ownSeen.current.get(o.pos);
|
||||
if (!was || was.owner !== o.owner) upd[o.pos] = { claim: o.owner };
|
||||
else if (o.level > was.level) upd[o.pos] = { level: o.level };
|
||||
}
|
||||
ownSeen.current = new Map(v.owned.map((o) => [o.pos, o]));
|
||||
ownSeen.current = new Map(owned.map((o) => [o.pos, o]));
|
||||
if (Object.keys(upd).length) setFresh((f) => ({ ...f, ...upd }));
|
||||
}, [v.owned]);
|
||||
}, [owned]);
|
||||
|
||||
const moveCell = (to: number) => {
|
||||
const n = (to + 40) % 40;
|
||||
@@ -664,9 +672,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
|
||||
const ownedAt = useMemo(() => {
|
||||
const m = new Map<number, MarbleOwnedView>();
|
||||
for (const o of v.owned) m.set(o.pos, o);
|
||||
for (const o of owned) m.set(o.pos, o);
|
||||
return m;
|
||||
}, [v.owned]);
|
||||
}, [owned]);
|
||||
const seatOf = (id: string) => v.players.find((p) => p.id === id)?.seat ?? 0;
|
||||
const walk = walker.current.cur;
|
||||
const trail = walk && walk.seg.walk ? new Set(walk.seg.path.slice(1, walk.i + 1)) : null;
|
||||
@@ -786,7 +794,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
})}
|
||||
</svg>
|
||||
<div className="mb-center">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling !== null} card={card} onCardClose={() => setCard(null)} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling !== null} settled={settled} card={card} onCardClose={() => setCard(null)} />
|
||||
</div>
|
||||
{banner && (
|
||||
<div className="mb-banner-wrap" aria-hidden>
|
||||
@@ -835,6 +843,7 @@ function Center({
|
||||
act,
|
||||
pending,
|
||||
rolling,
|
||||
settled,
|
||||
card,
|
||||
onCardClose,
|
||||
}: {
|
||||
@@ -844,6 +853,8 @@ function Center({
|
||||
act: (a: unknown) => void;
|
||||
pending: boolean;
|
||||
rolling: boolean;
|
||||
/** The dice and tokens have finished showing the latest move: the prompt and the result may show. */
|
||||
settled: boolean;
|
||||
card: { id: CardId; player: string; seq: number } | null;
|
||||
onCardClose: () => void;
|
||||
}) {
|
||||
@@ -894,8 +905,15 @@ function Center({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{v.phase !== 'finished' && <Prompt view={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
{v.phase !== 'finished' &&
|
||||
(settled ? (
|
||||
<Prompt view={v} me={me} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<div className="mb-prompt" role="status">
|
||||
<p>…</p>
|
||||
</div>
|
||||
))}
|
||||
{settled && v.phase === 'finished' && v.result && (
|
||||
<div className="mb-prompt">
|
||||
<h3>{v.result.summary}</h3>
|
||||
</div>
|
||||
@@ -1189,7 +1207,9 @@ function SpaceSheet({
|
||||
|
||||
// ---------------------------------------------------------------- side panel
|
||||
|
||||
function PlayerCard({ p, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
function PlayerCard({ p: live, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
// Points, lands and 파산 / 무인도 change once the token has got there (the view's player object is stable per view).
|
||||
const p = useAfterMotionValue(live);
|
||||
const active = v.phase !== 'finished' && ((v.phase === 'debt' && v.debt?.debtor === p.id) || (v.phase === 'tradeResponse' && v.trade?.to === p.id) || (v.phase !== 'debt' && v.phase !== 'tradeResponse' && v.current === p.id));
|
||||
const prev = useRef(p.cash);
|
||||
const [delta, setDelta] = useState<{ n: number; k: number } | null>(null);
|
||||
@@ -1447,7 +1467,9 @@ function MarbleSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [trade, setTrade] = useState(false);
|
||||
const ref = useRef<HTMLOListElement>(null);
|
||||
const lines = v.log.map((e) => logLine(e, players)).filter((x): x is string => !!x);
|
||||
// A move is written down once the board has played it.
|
||||
const log = useAfterMotionValue(v.log);
|
||||
const lines = log.map((e) => logLine(e, players)).filter((x): x is string => !!x);
|
||||
useEffect(() => {
|
||||
ref.current?.scrollTo({ top: ref.current.scrollHeight });
|
||||
}, [v.turnSeq]);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useSeatRows } from '../../lib/seat-rows';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow, resolvedHandSize } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const MODE_KO: Record<NNOptions['mode'], string> = { 'kr-product': '전용 카드', classic: '트럼프 카드' };
|
||||
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
|
||||
@@ -68,6 +68,42 @@ function useCountUp(target: number): number {
|
||||
return shown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table as of the last still screen: the total, the recent plays, lives / 탈락, the round and the final ranking
|
||||
* change only after the card that caused them has flown to the dial (and its banners have played).
|
||||
*/
|
||||
function useShownTable(v: NinetyNineView) {
|
||||
const total = useAfterMotionValue(v.total);
|
||||
const round = useAfterMotionValue(v.round);
|
||||
const recentKey = useAfterMotionValue(v.recent.map((e) => `${e.seq}-${e.p}`).join(','));
|
||||
const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.lives}:${s.alive ? 1 : 0}`).join(','));
|
||||
const lastKey = v.log.length ? nnLogKey(v.log[v.log.length - 1]!) : '';
|
||||
const shownLastKey = useAfterMotionValue(lastKey);
|
||||
const result = useMotionSettled(!!v.result) ? v.result : null;
|
||||
const seatSnap = new Map(
|
||||
seatKey
|
||||
.split(',')
|
||||
.filter(Boolean)
|
||||
.map((x) => {
|
||||
const [lives, alive] = x.split(':').slice(-2);
|
||||
return [x.split(':').slice(0, -2).join(':'), { lives: Number(lives), alive: alive === '1' }];
|
||||
}),
|
||||
);
|
||||
const recentShown = new Set(recentKey.split(','));
|
||||
const logEnd = v.log.findIndex((e) => nnLogKey(e) === shownLastKey);
|
||||
return {
|
||||
total,
|
||||
round,
|
||||
result,
|
||||
/** The total has not caught up with the last play yet (the card is still in the air). */
|
||||
settling: total !== v.total,
|
||||
recent: v.recent.filter((e) => recentShown.has(`${e.seq}-${e.p}`)),
|
||||
seat: (x: SeatView): SeatView => ({ ...x, ...seatSnap.get(x.id) }),
|
||||
log: logEnd < 0 ? v.log : v.log.slice(0, logEnd + 1),
|
||||
};
|
||||
}
|
||||
type ShownTable = ReturnType<typeof useShownTable>;
|
||||
|
||||
/** Green → yellow → red as the total nears 99. */
|
||||
const gaugeColor = (t: number) => `hsl(${Math.max(0, 130 - (t / 99) * 130)} 78% 46%)`;
|
||||
|
||||
@@ -251,9 +287,9 @@ function seatLabel(s: SeatView, v: NinetyNineView, players: Record<string, Publi
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
function SeatChip({ s, v, players, me, deadline, result }: { s: SeatView; v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; result: NinetyNineView['result'] }) {
|
||||
const u = userOf(players, s.id);
|
||||
const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||
const rank = result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||
return (
|
||||
<li className={`nn-seat${s.isTurn ? ' turn anim-glow' : ''}${s.alive ? '' : ' out'}`} data-fx-seat={s.id} aria-label={seatLabel(s, v, players, me)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
@@ -283,12 +319,13 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineV
|
||||
|
||||
// ---------------------------------------------------------------- table
|
||||
|
||||
function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const shown = useCountUp(v.total);
|
||||
function Table({ v, players, me, deadline, st }: { v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; st: ShownTable }) {
|
||||
const total = st.total;
|
||||
const shown = useCountUp(total);
|
||||
const dial = 'max(clamp(150px, 20vw, 196px), var(--nn-dial, 0px))';
|
||||
const r = 44;
|
||||
const c = 2 * Math.PI * r;
|
||||
const frac = Math.min(1, v.total / 99);
|
||||
const frac = Math.min(1, total / 99);
|
||||
const cur = v.current;
|
||||
return (
|
||||
<div className="nn-table" role="region" aria-label="카드 판" style={{ '--dial': dial } as CSSProperties}>
|
||||
@@ -306,12 +343,12 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
<span className="nn-chip" data-fx="nn-deck" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
||||
더미 {v.drawPileCount}장
|
||||
</span>
|
||||
{v.livesStart > 0 && <span className="nn-chip">{v.round}판째</span>}
|
||||
{v.livesStart > 0 && <span className="nn-chip">{st.round}판째</span>}
|
||||
</div>
|
||||
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
||||
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${total}`}>
|
||||
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden>
|
||||
<circle cx="50" cy="50" r={r} fill="rgba(0,0,0,.28)" stroke="rgba(255,255,255,.18)" strokeWidth="8" />
|
||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(v.total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||
</svg>
|
||||
<span className="nn-total" aria-hidden>
|
||||
{shown}
|
||||
@@ -322,9 +359,9 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
</div>
|
||||
<div className="nn-right">
|
||||
<span className="nn-rule">99를 넘기면 안 돼요!</span>
|
||||
{v.recent.length > 0 ? (
|
||||
{st.recent.length > 0 ? (
|
||||
<ol className="nn-recent" aria-label="최근에 낸 카드">
|
||||
{v.recent.slice(-4).map((e) => (
|
||||
{st.recent.slice(-4).map((e) => (
|
||||
<li key={`${e.seq}-${e.p}`}>
|
||||
<span className="who">{nick(players, e.p)}</span>
|
||||
<Mini face={e.face} kind={e.kind} />
|
||||
@@ -335,7 +372,7 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<span className="nn-chip">{v.round > 1 ? `${v.round}판 시작! 합계 ${v.total}` : v.total > 0 ? `시작 숫자 ${v.total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'}</span>
|
||||
<span className="nn-chip">{st.round > 1 ? `${st.round}판 시작! 합계 ${total}` : total > 0 ? `시작 숫자 ${total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -402,11 +439,12 @@ function JokerDial({ c, total, pending, onPlay }: { c: HandCardView; total: numb
|
||||
);
|
||||
}
|
||||
|
||||
function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function MyHand({ v, act, pending, st }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean; st: ShownTable }) {
|
||||
const my = v.my!;
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [note, setNote] = useState('');
|
||||
const myTurn = my.myTurn;
|
||||
// The previews (→ new total) and legality give the new total away: they show once the last card has landed.
|
||||
const myTurn = my.myTurn && !st.settling;
|
||||
useEffect(() => {
|
||||
setSel(null);
|
||||
setNote('');
|
||||
@@ -425,6 +463,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
};
|
||||
const single = (c: HandCardView) => c.choices.length === 1 && !c.joker;
|
||||
const tap = (c: HandCardView) => {
|
||||
if (st.settling) return;
|
||||
if (!myTurn) {
|
||||
setNote('지금은 내 차례가 아니에요. 카드를 누르면 낼 때 합계를 미리 볼 수 있어요.');
|
||||
setSel(sel === c.id ? null : c.id);
|
||||
@@ -458,7 +497,8 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
};
|
||||
const n = my.hand.length;
|
||||
const cw = `max(${n <= 3 ? 'clamp(84px, 24vw, 104px)' : n === 4 ? 'clamp(72px, 20vw, 96px)' : 'clamp(62px, 16.5vw, 90px)'}, var(--nn-cw, 0px))`;
|
||||
const meSeat = v.seats.find((s) => s.id === v.me);
|
||||
const meSeatNow = v.seats.find((s) => s.id === v.me);
|
||||
const meSeat = meSeatNow && st.seat(meSeatNow);
|
||||
const legalCount = my.hand.filter((c) => c.legal).length;
|
||||
return (
|
||||
<div className="nn-hand-wrap">
|
||||
@@ -487,7 +527,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
onClick={() => tap(c)}
|
||||
>
|
||||
<span className={`nn-prev ${p.cls}`} aria-hidden>
|
||||
{p.text}
|
||||
{st.settling ? '…' : p.text}
|
||||
</span>
|
||||
<Face face={c.face} kind={c.kind} jokerRange={c.joker ?? undefined} />
|
||||
</button>
|
||||
@@ -582,7 +622,9 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||
const meSeat = v.seats.find((s) => s.id === me);
|
||||
const st = useShownTable(v);
|
||||
const meSeatNow = v.seats.find((s) => s.id === me);
|
||||
const meSeat = meSeatNow && st.seat(meSeatNow);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useNinetyNineFx(v, me, players, showBanner);
|
||||
return (
|
||||
@@ -590,11 +632,11 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
<style>{CSS}</style>
|
||||
<ul className="nn-opps" aria-label="다른 사람" ref={opps.ref} style={opps.style}>
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.id} s={s} v={v} players={players} me={me} deadline={deadline} />
|
||||
<SeatChip key={s.id} s={st.seat(s)} v={v} players={players} me={me} deadline={deadline} result={st.result} />
|
||||
))}
|
||||
</ul>
|
||||
<Table v={v} players={players} me={me} deadline={deadline} />
|
||||
{v.my && meSeat?.alive && v.phase === 'playing' && <MyHand v={v} act={act} pending={pending} />}
|
||||
<Table v={v} players={players} me={me} deadline={deadline} st={st} />
|
||||
{v.my && meSeat?.alive && v.phase === 'playing' && <MyHand v={v} act={act} pending={pending} st={st} />}
|
||||
{meSeat && !meSeat.alive && v.phase === 'playing' && (
|
||||
<div className="nn-panel">
|
||||
<strong>{meSeat.left ? '게임에서 나갔어요.' : '탈락했어요. 남은 게임을 지켜봐요.'}</strong>
|
||||
@@ -659,8 +701,10 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<s
|
||||
};
|
||||
useNewEntries(v.log, nnLogKey, (fresh) => {
|
||||
let t = 0;
|
||||
// When the last played card reaches the dial: what it caused (no card, a life, 탈락) shows after that.
|
||||
let landed = 0;
|
||||
for (const e of fresh) {
|
||||
const at = t;
|
||||
const at = e.t === 'play' ? t : Math.max(t, landed);
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
const from = e.p === me ? (myPlayRect ?? fxEl('nn-hand')) : seatEl(e.p);
|
||||
@@ -676,26 +720,32 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<s
|
||||
if (e.kind === 'to99') later(at + 300, () => showBanner('99!', 'red', `${who(e.p)} 바로 99`));
|
||||
// Refill: the player takes one card from the pile (mine flies in from MyHand).
|
||||
if (v.options.refill && e.p !== me) flyGhost(fxEl('nn-deck'), seatEl(e.p), { delay: at + 420, ms: 380 });
|
||||
landed = at + 400;
|
||||
t += 160;
|
||||
break;
|
||||
}
|
||||
case 'noCard':
|
||||
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||
later(at, sfx.bad);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
later(at, () => {
|
||||
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||
sfx.bad();
|
||||
bump(seatEl(e.p), 'shake');
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'life':
|
||||
later(at, nnSfx.heart);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
later(at, () => {
|
||||
nnSfx.heart();
|
||||
bump(seatEl(e.p), 'shake');
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'out':
|
||||
if (e.why === 'noCard') {
|
||||
showBanner('탈락!', 'dark', who(e.p));
|
||||
later(at + 120, sfx.bad);
|
||||
}
|
||||
t += 200;
|
||||
if (e.why === 'noCard')
|
||||
later(at, () => {
|
||||
showBanner('탈락!', 'dark', who(e.p));
|
||||
later(120, sfx.bad);
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'round':
|
||||
if (e.round > 1) {
|
||||
@@ -760,6 +810,7 @@ function rulesLine(o: NNOptions): string {
|
||||
}
|
||||
|
||||
function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
const st = useShownTable(v);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -767,14 +818,14 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
구십구 · {MODE_KO[v.mode]}
|
||||
{v.livesStart > 0 ? ` · ${v.round}판` : ''}
|
||||
{v.phase === 'finished' ? ' · 게임 끝' : ''}
|
||||
{v.livesStart > 0 ? ` · ${st.round}판` : ''}
|
||||
{st.result ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
{v.current && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">{rulesLine(v.options)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.seats.map((s) => (
|
||||
{v.seats.map(st.seat).map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.alive ? 1 : 0.55 }} aria-label={seatLabel(s, v, players, me)}>
|
||||
<span style={{ filter: s.alive ? 'none' : 'grayscale(1)', display: 'inline-flex' }}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
@@ -796,10 +847,10 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{st.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
{st.result.ranking.map((r) => (
|
||||
<span key={r.player}>
|
||||
{r.rank}등 {nick(players, r.player)}
|
||||
<span className="muted small">
|
||||
@@ -808,14 +859,14 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
<span className="small muted">{st.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
{st.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
<ol className="nn-log">
|
||||
{[...v.log].reverse().map((e, i) => (
|
||||
{[...st.log].reverse().map((e, i) => (
|
||||
<li key={`${e.seq}-${e.t}-${i}`} className="small">
|
||||
{logText(e, players)}
|
||||
</li>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import { fanCard, fanLayout, type FanLayout } from './fan';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { fxAnim, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
|
||||
const JOKER = 'X1';
|
||||
@@ -196,7 +196,8 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047,
|
||||
box-shadow: 0 6px 16px rgba(0,0,0,.4), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; will-change: transform, opacity; }
|
||||
.om-ghost::after { content: ''; position: absolute; left: 50%; top: 50%; width: 34%; height: 24%; background: #3b82f6; transform: translate(-50%, -50%) rotate(45deg); border-radius: 2px; }
|
||||
.om-last { display: flex; align-items: center; gap: 12px; background: rgba(0,0,0,.24); border: 1px solid rgba(255,255,255,.1); border-radius: 14px; padding: 8px 14px; width: 100%; max-width: 620px; justify-content: center; }
|
||||
.om-last .cards { display: flex; flex: none; padding: 2px 4px; }
|
||||
.om-thief-joker { animation: om-pop .45s ease-out; }
|
||||
.om-last .cards { display: flex; flex: none; padding: 2px 4px; animation: om-pop .3s ease-out; }
|
||||
.om-last .cards .om-card { --cw: 40px; transform-origin: 50% 100%; filter: drop-shadow(-1px 2px 2px rgba(0,0,0,.3)); }
|
||||
.om-last .cards .om-card:first-child:not(:last-child) { transform: rotate(-7deg); }
|
||||
.om-last .cards .om-card + .om-card { margin-left: -12px; transform: rotate(7deg); }
|
||||
@@ -235,7 +236,7 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047,
|
||||
.om-last .cards .om-card { --cw: 36px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn { animation: none; }
|
||||
.om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn, .om-last .cards, .om-thief-joker { animation: none; }
|
||||
.om-strip { transition: none; }
|
||||
}
|
||||
`;
|
||||
@@ -330,13 +331,14 @@ function seatLabel(v: OldMaidView, id: string, me: string | null, players: Recor
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaidView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null }) {
|
||||
/** `r`: the view as of the last time the table stood still (counts, places, the thief), `v`: the live view (whose turn). */
|
||||
function Seat({ id, v, r, me, players, deadline, bubble }: { id: string; v: OldMaidView; r: OldMaidView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null }) {
|
||||
const u = userOf(players, id);
|
||||
const st = v.status[id];
|
||||
const thief = v.final?.thief === id;
|
||||
const st = r.status[id];
|
||||
const thief = r.final?.thief === id;
|
||||
const cls = ['om-seat', v.turn === id ? 'turn anim-glow' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
|
||||
return (
|
||||
<section className={cls} data-fx-seat={id} aria-label={seatLabel(v, id, me, players)}>
|
||||
<section className={cls} data-fx-seat={id} aria-label={seatLabel(r, id, me, players)}>
|
||||
{bubble && (
|
||||
<span className="om-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -350,7 +352,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
|
||||
<div className="om-badges" aria-hidden>
|
||||
{v.turn === id && <span className="om-badge turn">{v.target === me ? '내 카드 뽑는 중' : '뽑는 중'}</span>}
|
||||
{v.target === id && <span className="om-badge target">{v.turn === me ? '내가 여기서 뽑아요' : '뽑히는 중'}</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {v.places[id]}등</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {r.places[id]}등</span>}
|
||||
{st === 'left' && <span className="om-badge">나감</span>}
|
||||
{thief && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{v.away[id] && <span className="om-badge">자리 비움</span>}
|
||||
@@ -358,15 +360,15 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
|
||||
<div className="om-meta" aria-hidden>
|
||||
{st === 'playing' || thief ? (
|
||||
<>
|
||||
<MiniFan n={v.handCounts[id] ?? 0} />
|
||||
<MiniFan n={r.handCounts[id] ?? 0} />
|
||||
<span>
|
||||
<strong>{v.handCounts[id]}</strong>장
|
||||
<strong>{r.handCounts[id]}</strong>장
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span>{st === 'out' ? '다 털었어요' : '나갔어요'}</span>
|
||||
)}
|
||||
<span>· 짝 {v.pairCounts[id]}</span>
|
||||
<span>· 짝 {r.pairCounts[id]}</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
@@ -515,7 +517,11 @@ function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidV
|
||||
}
|
||||
|
||||
function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const d = v.lastDraw;
|
||||
// A new draw (the card drawn, the pair thrown away) is told only once its card has landed.
|
||||
const shownNo = useAfterMotionValue(v.lastDraw?.no ?? 0);
|
||||
const kept = useRef(v.lastDraw);
|
||||
if ((v.lastDraw?.no ?? 0) === shownNo) kept.current = v.lastDraw;
|
||||
const d = kept.current;
|
||||
if (!d) return null;
|
||||
const mineDraw = d.drawer === me;
|
||||
const text = `${drawerSubj(players, d.drawer, me)} ${whose(players, d.from, me)} ${d.index + 1}번째 카드를 뽑았어요${d.auto ? '(시간 초과)' : ''}`;
|
||||
@@ -524,7 +530,7 @@ function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; playe
|
||||
else if (mineDraw && d.card) tail = d.card === JOKER ? '앗, 조커를 뽑았어요!' : `뽑은 카드 ${cardName(d.card)} · 짝이 없어서 손에 넣었어요`;
|
||||
else tail = '짝이 없어서 손에 넣었어요';
|
||||
return (
|
||||
<div className="om-last" role="status" aria-label={`${text}. ${tail}`}>
|
||||
<div key={d.no} className="om-last" role="status" aria-label={`${text}. ${tail}`}>
|
||||
{(d.pair || (mineDraw && d.card)) && (
|
||||
<span className="cards" aria-hidden>
|
||||
{d.pair ? d.pair.map((c) => <Card key={c} card={c} />) : <Card card={d.card} />}
|
||||
@@ -559,8 +565,17 @@ function Pile({ v }: { v: OldMaidView }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Table(props: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean }) {
|
||||
function Table(props: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean; revealed: boolean }) {
|
||||
const { v, me, players } = props;
|
||||
if (v.phase === 'finished' && !props.revealed) {
|
||||
// The last card is still flying (or the thief banner is up): the thief is unmasked after that.
|
||||
return (
|
||||
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
|
||||
<LastDraw v={v} me={me} players={players} />
|
||||
<Pile v={v} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (v.phase === 'finished') {
|
||||
const f = v.final!;
|
||||
return (
|
||||
@@ -607,7 +622,7 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
|
||||
const HAND_PC = { cw: 72, prefer: 46 };
|
||||
const HAND_PHONE = { cw: 50, prefer: 34 };
|
||||
|
||||
function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
||||
function MyArea({ v, r, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; r: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
||||
const hand = v.myHand ?? [];
|
||||
const st = v.status[me];
|
||||
const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
|
||||
@@ -668,8 +683,8 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
|
||||
</span>
|
||||
)}
|
||||
{v.away[me] && <span className="om-badge">자리 비움</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {v.places[me]}등</span>}
|
||||
{v.final?.thief === me && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{r.status[me] === 'out' && <span className="om-badge win">🎉 {r.places[me]}등</span>}
|
||||
{r.final?.thief === me && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{v.turn === me && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine size={30} />}
|
||||
</div>
|
||||
<div className="om-mine">
|
||||
@@ -715,6 +730,29 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
|
||||
const [banner, showBanner] = useBanner();
|
||||
useOldMaidFx(v, me, players, showBanner);
|
||||
// "조커를 뽑았어요!" tells what the card is: only once it has landed in my hand.
|
||||
const [note, setNote] = useState<{ text: string; buzz: number | number[] } | null>(null);
|
||||
const noteReady = useMotionSettled(!!note);
|
||||
useEffect(() => {
|
||||
if (!noteReady || !note) return;
|
||||
toast(note.text);
|
||||
haptic(note.buzz);
|
||||
setNote(null);
|
||||
}, [noteReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// Places, counts and the thief change on screen once the cards have landed; the end table after the thief banner.
|
||||
const shown = useAfterMotionValue(v);
|
||||
const revealed = useMotionSettled(v.phase === 'finished');
|
||||
const popBubbles = (bub: Record<string, string>) => {
|
||||
setBubbles((b) => ({ ...b, ...bub }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
|
||||
};
|
||||
const [bubQ, setBubQ] = useState<Record<string, string> | null>(null);
|
||||
const bubReady = useMotionSettled(!!bubQ);
|
||||
useEffect(() => {
|
||||
if (!bubReady || !bubQ) return;
|
||||
popBubbles(bubQ);
|
||||
setBubQ(null);
|
||||
}, [bubReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
@@ -735,13 +773,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const hand = v.myHand ?? [];
|
||||
const ld = v.lastDraw;
|
||||
if (amPlayer && ld && added.some((e) => e.t === 'draw')) {
|
||||
if (ld.drawer === me && ld.card === JOKER) {
|
||||
toast('앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.');
|
||||
haptic([40, 30, 40]);
|
||||
} else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) {
|
||||
toast('조커를 넘겼어요! 😆');
|
||||
haptic(40);
|
||||
}
|
||||
if (ld.drawer === me && ld.card === JOKER) setNote({ text: '앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.', buzz: [40, 30, 40] });
|
||||
else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) setNote({ text: '조커를 넘겼어요! 😆', buzz: 40 });
|
||||
setFresh(ld.drawer === me && !ld.pair ? ld.card : null);
|
||||
}
|
||||
if (amPlayer && v.turn === me && p.turn !== me && v.phase === 'playing') {
|
||||
@@ -751,8 +784,9 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
}
|
||||
if (msgs.length) setAnnounce(msgs.join(' '));
|
||||
if (Object.keys(bub).length) {
|
||||
setBubbles((b) => ({ ...b, ...bub }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
|
||||
// "짝!" / "다 털었어요" once the drawn card has landed; "섞었어요" right away (it goes with the riffle).
|
||||
if (added.some((e) => e.t !== 'shuffle')) setBubQ((q) => ({ ...q, ...bub }));
|
||||
else popBubbles(bub);
|
||||
}
|
||||
prev.current = { logCount: v.logCount, hand, turn: v.turn };
|
||||
if (shuffled) {
|
||||
@@ -769,11 +803,11 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
<style>{CSS}</style>
|
||||
<div className="om-seats">
|
||||
{seats.map((p) => (
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} />
|
||||
<Seat key={p} id={p} v={v} r={shown} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} />
|
||||
))}
|
||||
</div>
|
||||
<Table v={v} me={me} players={players} act={act} pending={pending} tapConfirm={tapConfirm} riffle={riffle} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} act={act} pending={pending} deadline={deadline} fresh={fresh} bubble={bubbles[me!] ?? null} />}
|
||||
<Table v={v} me={me} players={players} act={act} pending={pending} tapConfirm={tapConfirm} riffle={riffle} revealed={revealed} />
|
||||
{amPlayer && <MyArea v={v} r={shown} me={me!} players={players} act={act} pending={pending} deadline={deadline} fresh={fresh} bubble={bubbles[me!] ?? null} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -791,11 +825,32 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
const hand = v.myHand ?? [];
|
||||
const prevHand = useRef(hand);
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
// Banners ("1등!", "도둑!") wait until the card that caused them has landed; the screen counts as moving meanwhile,
|
||||
// so the room's result window opens only after the banner.
|
||||
const flightEnd = useRef(0);
|
||||
const bannerTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const [bannerWait, setBannerWait] = useState(false);
|
||||
useMotionHold(bannerWait);
|
||||
useEffect(() => () => clearTimeout(bannerTimer.current), []);
|
||||
const bannerAfterFlight = (...args: Parameters<typeof showBanner>) => {
|
||||
clearTimeout(bannerTimer.current);
|
||||
const wait = flightEnd.current - performance.now();
|
||||
if (wait <= 0) {
|
||||
setBannerWait(false);
|
||||
return showBanner(...args);
|
||||
}
|
||||
setBannerWait(true);
|
||||
bannerTimer.current = setTimeout(() => {
|
||||
setBannerWait(false);
|
||||
showBanner(...args);
|
||||
}, wait);
|
||||
};
|
||||
/** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */
|
||||
const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p));
|
||||
const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i }));
|
||||
useNewEntries(entries, (x) => x.n, (fresh) => {
|
||||
let t = 0;
|
||||
let end = 0; // when the last flying card lands (written ms)
|
||||
const ld = v.lastDraw;
|
||||
const pile = (pairs: [string, string][], from: Element | null, delay: number) => {
|
||||
for (const p of pairs) flyFrom(document.querySelector(`.om-pile [data-pair="${cssEsc(pairKey(p))}"]`), from, { delay, ms: 420, rotate: 14 });
|
||||
@@ -814,6 +869,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.drawer === me) myDrawRect = null;
|
||||
fanSnap = null;
|
||||
const land = lifted ? LIFT_MS - 140 : 300;
|
||||
end = Math.max(end, at + (lifted ? LIFT_MS : 420));
|
||||
later(at, () => {
|
||||
if (e.auto) sfx.tick();
|
||||
sfx.draw();
|
||||
@@ -821,7 +877,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.pair) {
|
||||
pile([e.pair], spot(e.drawer), at + land);
|
||||
later(at + land + 30, omSfx.pair);
|
||||
later(at + land + 30, () => bump(document.querySelector('.om-last .cards'), 'pop'));
|
||||
end = Math.max(end, at + land + 420);
|
||||
t += land + 120;
|
||||
} else t += 160;
|
||||
break;
|
||||
@@ -831,7 +887,8 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
omSfx.out();
|
||||
bump(seatEl(e.player), 'pop');
|
||||
});
|
||||
showBanner(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
|
||||
flightEnd.current = performance.now() + fxMs(end);
|
||||
bannerAfterFlight(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
|
||||
t += 150;
|
||||
break;
|
||||
case 'shuffle':
|
||||
@@ -852,7 +909,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.pairs.length) {
|
||||
pile(e.pairs, seatEl(e.player), at + 350);
|
||||
later(at + 380, omSfx.pair);
|
||||
end = Math.max(end, at + 350 + 420);
|
||||
}
|
||||
end = Math.max(end, at + 480 + 60 * Math.max(0, n - 1));
|
||||
t += 400;
|
||||
break;
|
||||
}
|
||||
@@ -869,6 +928,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
});
|
||||
} else if (had && !has && v.phase === 'playing') later(t + 150, omSfx.jokerGone);
|
||||
}
|
||||
flightEnd.current = performance.now() + fxMs(end);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
prevHand.current = hand;
|
||||
@@ -877,11 +937,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
useChange(v.phase, (now) => {
|
||||
const thief = v.final?.thief;
|
||||
if (now !== 'finished' || !thief) return;
|
||||
showBanner('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
|
||||
setTimeout(() => {
|
||||
bump(seatEl(thief), 'shake');
|
||||
bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop');
|
||||
}, fxMs(200));
|
||||
bannerAfterFlight('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
|
||||
// (The joker on the end table pops by itself when it shows, after the banner.)
|
||||
setTimeout(() => bump(seatEl(thief), 'shake'), Math.max(0, flightEnd.current - performance.now()) + fxMs(200));
|
||||
});
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
@@ -902,7 +960,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function OldMaidSide({ view: v, me, players, deadline }: BoardProps<OldMaidView>) {
|
||||
function OldMaidSide({ view, me, players, deadline }: BoardProps<OldMaidView>) {
|
||||
// The side panel (places, the thief, the log) follows the board once its cards have landed.
|
||||
const v = useAfterMotionValue(view);
|
||||
const running = v.phase === 'playing';
|
||||
const log = v.log.filter((e) => e.t !== 'shuffle').slice(-8).reverse();
|
||||
return (
|
||||
|
||||
@@ -6,11 +6,11 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import { bump, useBanner } from '../card-fx';
|
||||
import { bump, useBanner, type BannerTone } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
type Color = 'black' | 'white';
|
||||
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
||||
@@ -67,16 +67,26 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
}, [refused]);
|
||||
|
||||
// The game is over: "오목!" for five in a row (who won underneath), otherwise just who won.
|
||||
// Shown once the last stone has set down (it waits in `endBanner` until the board is still).
|
||||
const prevPhase = useRef(v.phase);
|
||||
const [endBanner, setEndBanner] = useState<[string, BannerTone, string | undefined] | null>(null);
|
||||
const endReady = useMotionSettled(!!endBanner);
|
||||
useEffect(() => {
|
||||
const before = prevPhase.current;
|
||||
prevPhase.current = v.phase;
|
||||
if (before === v.phase || v.phase !== 'finished' || !v.result) return;
|
||||
const w = v.result.winner;
|
||||
const tone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue';
|
||||
if (v.winLine?.length) showBanner('오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined);
|
||||
else showBanner(w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary);
|
||||
const tone: BannerTone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue';
|
||||
if (v.winLine?.length) setEndBanner(['오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined]);
|
||||
else setEndBanner([w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary]);
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!endReady || !endBanner) return;
|
||||
showBanner(...endBanner);
|
||||
setEndBanner(null);
|
||||
}, [endReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The winning five light up only after the last stone has landed.
|
||||
const winShown = useMotionSettled(!!v.winLine?.length);
|
||||
|
||||
const forbidden = useMemo(() => new Set(v.forbidden.map((p) => p.y * n + p.x)), [v.forbidden, n]);
|
||||
// What the board was before the last change: a new stone sets down, stones taken back by 무르기 fade away.
|
||||
@@ -227,7 +237,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
<circle className={fresh ? 'anim-pop' : undefined} style={{ animationDelay: '0.2s', transformBox: 'fill-box', transformOrigin: 'center' }} cx={v.lastMove.x} cy={v.lastMove.y} r={0.13} fill="#ef4444" />
|
||||
</g>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
{(winShown ? (v.winLine ?? []) : []).map((p, k) => (
|
||||
<circle
|
||||
key={`win${p.x}-${p.y}`}
|
||||
className="bm-win"
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
* 원카드 소리·움직임 (docs/games/one-card.md §9). Everything reacts to new public log lines, so other players' moves
|
||||
* sound and move too, and each change plays once (lines are handled by their `seq`).
|
||||
*/
|
||||
import { useLayoutEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
|
||||
import type { CardFace, LogEntry, OneCardView } from '@bg/games/one-card';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { fxAnim, fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
export interface Banner {
|
||||
key: number;
|
||||
@@ -182,9 +182,31 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
const round = useRef(v.round);
|
||||
const keyRef = useRef(1);
|
||||
const timers = useRef<number[]>([]);
|
||||
// Results (등수, 파산, 의심 결과, 판 끝) wait until the card that caused them has landed.
|
||||
const [late, setLate] = useState<{ banners: Banner[]; sounds: string[] }>({ banners: [], sounds: [] });
|
||||
const lateReady = useMotionSettled(late.banners.length > 0);
|
||||
|
||||
useLayoutEffect(() => () => timers.current.forEach((t) => clearTimeout(t)), []);
|
||||
|
||||
const showBanners = (banners: Banner[], next: Partial<Fx> = {}) => {
|
||||
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
|
||||
for (const b of banners) {
|
||||
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700));
|
||||
timers.current.push(t);
|
||||
}
|
||||
timers.current = timers.current.slice(-20);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!lateReady) return;
|
||||
const q = late;
|
||||
setLate({ banners: [], sounds: [] });
|
||||
if (q.sounds.includes('out')) sfx.fanfare();
|
||||
if (q.sounds.includes('good')) sfx.good();
|
||||
if (q.sounds.includes('bad')) sfx.bad();
|
||||
showBanners(q.banners);
|
||||
}, [lateReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0;
|
||||
const myHand = v.my?.hand ?? [];
|
||||
@@ -197,6 +219,12 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
let drawGap = 0;
|
||||
let myDraw = 0;
|
||||
const banner = (b: Omit<Banner, 'key'>) => banners.push({ ...b, key: keyRef.current++ });
|
||||
const lateBanners: Banner[] = [];
|
||||
const lateSounds: string[] = [];
|
||||
const later = (b: Omit<Banner, 'key'>, sound?: string) => {
|
||||
lateBanners.push({ ...b, key: keyRef.current++ });
|
||||
if (sound) lateSounds.push(sound);
|
||||
};
|
||||
const who = (p: string) => (p === me ? '내가' : `${nick(p)}님이`);
|
||||
const rootEl = root.current;
|
||||
const layerEl = layer.current;
|
||||
@@ -283,19 +311,16 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
next.shuffle = (next.shuffle ?? fx.shuffle) + 1;
|
||||
break;
|
||||
case 'out':
|
||||
if (v.phase !== 'finished') sounds.add('out');
|
||||
banner({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' });
|
||||
later({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' }, v.phase !== 'finished' ? 'out' : undefined);
|
||||
break;
|
||||
case 'bankrupt':
|
||||
sounds.add('bad');
|
||||
banner({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' });
|
||||
later({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' }, 'bad');
|
||||
break;
|
||||
case 'challenge':
|
||||
sounds.add(e.illegal ? 'good' : 'bad');
|
||||
banner({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' });
|
||||
later({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' }, e.illegal ? 'good' : 'bad');
|
||||
break;
|
||||
case 'round':
|
||||
banner({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' });
|
||||
later({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' });
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -335,19 +360,10 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
else if (sounds.has('alarm')) sfx.alarm();
|
||||
if (sounds.has('call')) ocSound.call();
|
||||
if (sounds.has('oneLeft')) ocSound.oneLeft();
|
||||
if (sounds.has('out')) sfx.fanfare();
|
||||
if (sounds.has('good')) sfx.good();
|
||||
if (sounds.has('bad')) sfx.bad();
|
||||
if (myDraw >= 2) haptic([30, 30, 30]);
|
||||
|
||||
if (banners.length || Object.keys(next).length) {
|
||||
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
|
||||
for (const b of banners) {
|
||||
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700));
|
||||
timers.current.push(t);
|
||||
}
|
||||
}
|
||||
timers.current = timers.current.slice(-20);
|
||||
if (banners.length || Object.keys(next).length) showBanners(banners, next);
|
||||
if (lateBanners.length) setLate((q) => ({ banners: [...q.banners, ...lateBanners], sounds: [...q.sounds, ...lateSounds] }));
|
||||
}, [v.log.length ? v.log[v.log.length - 1]!.seq : 0, v.round, v.my?.hand.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return fx;
|
||||
|
||||
@@ -12,7 +12,7 @@ import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard';
|
||||
import { FX_CSS, useOneCardFx, type Fx } from './fx';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const SUITS: Suit[] = ['S', 'H', 'D', 'C'];
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
@@ -173,8 +173,11 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
|
||||
function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const u = userOf(players, s.id);
|
||||
const place = v.result?.players.find((p) => p.player === s.id)?.rank;
|
||||
// 다 냄 / 파산 and points change once the last card has landed.
|
||||
const status = useAfterMotionValue(s.status);
|
||||
const score = useAfterMotionValue(s.score);
|
||||
return (
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${s.status === 'bankrupt' || s.status === 'left' ? ' gone' : ''}`} data-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${status === 'bankrupt' || status === 'left' ? ' gone' : ''}`} data-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={24} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
@@ -190,11 +193,11 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView
|
||||
{s.oneCard === 'declared' ? '원카드!' : '1장!'}
|
||||
</span>
|
||||
)}
|
||||
{s.status === 'out' && <span className="oc-badge" style={{ background: 'var(--success)', color: '#fff' }}>{place ? `${place}등` : '다 냄'}</span>}
|
||||
{s.status === 'bankrupt' && <span className="oc-badge" style={{ background: 'var(--danger)', color: '#fff' }}>파산</span>}
|
||||
{status === 'out' && <span className="oc-badge" style={{ background: 'var(--success)', color: '#fff' }}>{place ? `${place}등` : '다 냄'}</span>}
|
||||
{status === 'bankrupt' && <span className="oc-badge" style={{ background: 'var(--danger)', color: '#fff' }}>파산</span>}
|
||||
{s.status === 'left' && <span className="oc-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
|
||||
{s.away && <span className="oc-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
|
||||
{v.mode === 'uno-style' && v.options.unoTargetScore > 0 && <span className="small muted">{s.score}점</span>}
|
||||
{v.mode === 'uno-style' && v.options.unoTargetScore > 0 && <span className="small muted">{score}점</span>}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -227,6 +230,8 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) {
|
||||
);
|
||||
return () => window.clearInterval(id);
|
||||
}, [n]);
|
||||
// Counting up card by card (timer steps): results wait for the count.
|
||||
useMotionHold(shown < n);
|
||||
if (n <= 0) return null;
|
||||
return (
|
||||
<span key={shown} className="oc-attack grow" aria-live="polite" aria-label={`${uno ? '먹을 카드' : '공격'} ${n}장`} style={{ fontSize: `${1.4 + Math.min(shown, 15) * 0.07}rem` }}>
|
||||
@@ -807,8 +812,12 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
}}
|
||||
/>
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
<AfterMotion when={!!v.reveal}>
|
||||
<RevealPanel v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<AfterMotion when={v.phase === 'roundEnd'}>
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
</AfterMotion>
|
||||
{v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} arrived={fx.arrived} />}
|
||||
{meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
|
||||
<div className="oc-panel">
|
||||
@@ -840,6 +849,12 @@ function rulesLine(v: Pick<OneCardView, 'mode' | 'options' | 'penalty' | 'bankru
|
||||
function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>) {
|
||||
const scoreMode = v.mode === 'uno-style' && v.options.unoTargetScore > 0;
|
||||
const waitingId = v.current;
|
||||
// Seats, the 기록 and the final ranking show what happened only after it has played on the table.
|
||||
const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0;
|
||||
const shownSeq = useAfterMotionValue(lastSeq);
|
||||
const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.status}:${s.score}`).join(','));
|
||||
const seatShown = seatKey.split(',');
|
||||
const showResult = useAfterMotionValue(!!v.result);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -854,25 +869,28 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>
|
||||
</div>
|
||||
<span className="small muted">{rulesLine(v)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.seats.map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'bankrupt' || s.status === 'left' ? 0.55 : 1 }} aria-label={seatLabel(s, players, me, v)}>
|
||||
{v.seats.map((s, i) => {
|
||||
const [status, score] = (seatShown[i] ?? `${s.status}:${s.score}`).split(':') as [SeatView['status'], string];
|
||||
return (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: status === 'bankrupt' || status === 'left' ? 0.55 : 1 }} aria-label={seatLabel(s, players, me, v)}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
|
||||
{s.isTurn ? '▶ ' : ''}
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.status === 'out' ? ' · 다 냄' : s.status === 'bankrupt' ? ' · 파산' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
{status === 'out' ? ' · 다 냄' : status === 'bankrupt' ? ' · 파산' : status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
{scoreMode && <span className="small">{s.score}점</span>}
|
||||
{scoreMode && <span className="small">{score}점</span>}
|
||||
<span className="oc-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{showResult && v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
@@ -892,7 +910,7 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
<ol className="oc-log">
|
||||
{[...v.log].reverse().map((e) => (
|
||||
{v.log.filter((e) => e.seq <= shownSeq).reverse().map((e) => (
|
||||
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
|
||||
{logText(e, players)}
|
||||
</li>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS } from '../board-motion';
|
||||
import { useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import { toast } from '../../store/toast';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
@@ -74,6 +75,16 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
const [anim, setAnim] = useState<Anim | null>(null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
// Pass notices wait until the flips of the move before them have played.
|
||||
const [passMsgs, setPassMsgs] = useState<string[]>([]);
|
||||
const passReady = useMotionSettled(passMsgs.length > 0);
|
||||
useEffect(() => {
|
||||
if (!passReady) return;
|
||||
for (const m of passMsgs) toast(m);
|
||||
setPassMsgs([]);
|
||||
}, [passReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The disc counts change once the discs have finished turning over.
|
||||
const [black, white] = useAfterMotionValue(`${v.discs.black},${v.discs.white}`).split(',').map(Number) as [number, number];
|
||||
|
||||
const legal = useMemo(() => {
|
||||
const m = new Map<number, OthelloLegalMove>();
|
||||
@@ -93,6 +104,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
}
|
||||
const added = v.moves.slice(prev);
|
||||
const texts: string[] = [];
|
||||
const passes: string[] = [];
|
||||
for (const m of added) {
|
||||
if (m.kind === 'place') texts.push(`${COLOR_KO[m.color]}이 ${label(m)}에 두어 ${m.flipped.length}개를 뒤집었어요.`);
|
||||
else {
|
||||
@@ -103,9 +115,10 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
? '상대가 둘 곳이 없어서 내 차례가 한 번 더 와요'
|
||||
: `${COLOR_KO[m.color]}이 둘 곳이 없어서 차례가 넘어갔어요`;
|
||||
texts.push(msg + '.');
|
||||
toast(msg);
|
||||
passes.push(msg);
|
||||
}
|
||||
}
|
||||
if (passes.length) setPassMsgs((q) => [...q, ...passes]);
|
||||
setAnnounce(texts.join(' '));
|
||||
const lm = v.lastMove;
|
||||
if (lm && added.some((m) => m.kind === 'place')) {
|
||||
@@ -188,7 +201,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
const showFlips = !!targetMove && (v.showLegalMoves || !!preview);
|
||||
const flipSet = new Set(showFlips ? targetMove!.flipped : []);
|
||||
const showGhost = !!target && v.myColor && v.board[target.y * N + target.x] === 0 && (!!targetMove || !v.showLegalMoves);
|
||||
const total = v.discs.black + v.discs.white;
|
||||
const total = black + white;
|
||||
const pad = 0.55;
|
||||
|
||||
return (
|
||||
@@ -196,17 +209,17 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
<div className="board-wrap stack oth-fit" style={{ gap: 10, '--oth-rows': tapConfirm ? 'calc(var(--btn-h) + 50px)' : '40px' } as React.CSSProperties}>
|
||||
<style>{BOARD_MOTION_CSS + CSS}</style>
|
||||
<div
|
||||
aria-label={`돌 수: 흑 ${v.discs.black}개, 백 ${v.discs.white}개`}
|
||||
aria-label={`돌 수: 흑 ${black}개, 백 ${white}개`}
|
||||
role="img"
|
||||
style={{ display: 'flex', height: 30, borderRadius: 15, overflow: 'hidden', border: '2px solid var(--border)', fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}
|
||||
>
|
||||
<div style={{ flex: `${v.discs.black} 1 0`, minWidth: 48, background: '#161616', color: '#fff', display: 'flex', alignItems: 'center', paddingLeft: 12, transition: 'flex-grow 0.4s' }}>
|
||||
● {v.discs.black}
|
||||
<div style={{ flex: `${black} 1 0`, minWidth: 48, background: '#161616', color: '#fff', display: 'flex', alignItems: 'center', paddingLeft: 12, transition: 'flex-grow 0.4s' }}>
|
||||
● {black}
|
||||
</div>
|
||||
<div
|
||||
style={{ flex: `${total ? v.discs.white : 1} 1 0`, minWidth: 48, background: '#fafaf7', color: '#161616', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 12, transition: 'flex-grow 0.4s' }}
|
||||
style={{ flex: `${total ? white : 1} 1 0`, minWidth: 48, background: '#fafaf7', color: '#161616', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 12, transition: 'flex-grow 0.4s' }}
|
||||
>
|
||||
{v.discs.white} ○
|
||||
{white} ○
|
||||
</div>
|
||||
</div>
|
||||
<svg
|
||||
@@ -438,7 +451,8 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: OthelloVie
|
||||
} else if (active && tc.kind === 'perMove') {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={id === me} />;
|
||||
}
|
||||
const score = v.result ? v.result.displayScore[color] : v.discs[color];
|
||||
// Shown once the discs of the last move have turned over.
|
||||
const score = useAfterMotionValue(v.result ? v.result.displayScore[color] : v.discs[color]);
|
||||
return (
|
||||
<div className="card row" style={{ padding: '8px 12px', gap: 10, border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<svg width={28} height={28} viewBox="-0.5 -0.5 1 1" aria-hidden>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const MODE_KO: Record<PokerMode, string> = {
|
||||
holdem: '텍사스 홀덤',
|
||||
@@ -123,8 +123,8 @@ function seatBadges(seat: SeatView, v: PokerView): [string, string][] {
|
||||
return b;
|
||||
}
|
||||
|
||||
function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: string | null; k: number }) {
|
||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||
function SeatCards({ seat, v, me, k, endShown }: { seat: SeatView; v: PokerView; me: string | null; k: number; endShown: boolean }) {
|
||||
const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined;
|
||||
const cards: { c: ViewCard; key: string; title?: string }[] = [];
|
||||
if (seat.forehead !== undefined) cards.push({ c: seat.forehead, key: 'f', title: seat.forehead ? undefined : seat.id === me ? '내 이마 카드(나만 못 봐요)' : '이마 카드' });
|
||||
// Hidden cards arrive as null; at showdown the view already reveals them.
|
||||
@@ -149,13 +149,16 @@ function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: strin
|
||||
);
|
||||
}
|
||||
|
||||
function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number; k: number }) {
|
||||
function SeatBox({ seat, v, players, me, deadline, x, y, k, endShown }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number; k: number; endShown: boolean }) {
|
||||
const u = userOf(players, seat.id);
|
||||
// Chips change once the flying chips have landed.
|
||||
const stack = useAfterMotionValue(seat.stack);
|
||||
const badges = seatBadges(seat, v);
|
||||
const waiting = v.waiting.includes(seat.id) && v.handPhase !== 'handEnd';
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const won = v.handPhase === 'handEnd' && v.winners.includes(seat.id);
|
||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||
// Winner, hand names and best cards show once the cards have been turned over (endShown).
|
||||
const won = endShown && v.handPhase === 'handEnd' && v.winners.includes(seat.id);
|
||||
const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined;
|
||||
const marks: [string, string, string][] = [];
|
||||
if (seat.dealer) marks.push(['D', '#facc15', '딜러']);
|
||||
if (seat.sb) marks.push(['SB', '#93c5fd', '스몰 블라인드']);
|
||||
@@ -166,7 +169,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
|
||||
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
|
||||
data-fx-seat={seat.id}
|
||||
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||
aria-label={`${u.nickname} ${formatChips(stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||
>
|
||||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={22} />
|
||||
@@ -182,7 +185,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
{waiting && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={seat.id === me} size={28} />}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6, justifyContent: 'space-between' }}>
|
||||
<Chips n={seat.stack} strong />
|
||||
<Chips n={stack} strong />
|
||||
{seat.roundBet > 0 && <span className="small" title="이번 라운드에 건 칩">+{seat.roundBet.toLocaleString('ko-KR')}</span>}
|
||||
</div>
|
||||
{seat.lastAction && !seat.folded && <span className="small muted">{seat.lastAction}</span>}
|
||||
@@ -196,8 +199,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SeatCards seat={seat} v={v} me={me} k={k} />
|
||||
{!sd && v.foldShown?.id === seat.id && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{v.foldShown.handName}</strong>}
|
||||
<SeatCards seat={seat} v={v} me={me} k={k} endShown={endShown} />
|
||||
{!sd && endShown && v.foldShown?.id === seat.id && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{v.foldShown.handName}</strong>}
|
||||
{sd && (
|
||||
<strong style={{ color: 'var(--primary)', textAlign: 'center' }}>
|
||||
{sd.handName}
|
||||
@@ -211,6 +214,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
function CenterInfo({ v, players, k }: { v: PokerView; players: Record<string, PublicUser>; k: number }) {
|
||||
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
||||
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
|
||||
// The pot changes once the chips have flown in (or out to the winner).
|
||||
const pot = useAfterMotionValue(v.pot);
|
||||
return (
|
||||
<div className="pk-center" data-fx="poker-center">
|
||||
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
|
||||
@@ -221,7 +226,7 @@ function CenterInfo({ v, players, k }: { v: PokerView; players: Record<string, P
|
||||
)}
|
||||
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
||||
<div style={{ fontSize: `${(2.2 * (1 + (k - 1) / 2)).toFixed(2)}rem`, fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
|
||||
{formatChips(v.pot)}
|
||||
{formatChips(pot)}
|
||||
</div>
|
||||
{v.pots.length > 1 && (
|
||||
<div className="small" style={{ opacity: 0.9 }}>
|
||||
@@ -258,6 +263,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const showKey = `${v.handNo}-${v.handPhase}`;
|
||||
const [banner, showBanner] = useBanner();
|
||||
usePokerFx(v, me, players, showBanner);
|
||||
// The hand's outcome (winner, hand names, 이번 판 결과, 다음 판으로) waits until the showdown flips and chips are done.
|
||||
const endShown = useMotionSettled(v.handPhase === 'handEnd');
|
||||
// PC: seats, cards and the pot grow with the table (1 at the old 890×600 table, up to 1.6×).
|
||||
const wide = useWide();
|
||||
const tableRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -287,10 +294,10 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
}, [mine, v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (v.handPhase !== 'handEnd') return;
|
||||
if (!endShown || v.handPhase !== 'handEnd') return;
|
||||
setAnnounce(resultLine(v, players));
|
||||
if (me && v.winners.includes(me)) sounds.win();
|
||||
}, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [showKey, endShown]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return (
|
||||
<MyCardW.Provider value={lgW}>
|
||||
@@ -311,11 +318,11 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const sn = Math.sin(ang);
|
||||
const cx = wide ? Math.sign(c) * Math.abs(c) ** 0.7 : c;
|
||||
const sy = wide ? Math.sign(sn) * Math.abs(sn) ** 0.7 : sn;
|
||||
return <SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * cx} y={50 + ry * sy} k={k} />;
|
||||
return <SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * cx} y={50 + ry * sy} k={k} endShown={endShown} />;
|
||||
})}
|
||||
<CenterInfo v={v} players={players} k={k} />
|
||||
</div>
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} />
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} endShown={endShown} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -663,9 +670,11 @@ interface AreaProps {
|
||||
pending: boolean;
|
||||
}
|
||||
|
||||
function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
function MyArea({ v, me, players, act, pending, endShown }: AreaProps & { endShown: boolean }) {
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!me || !seat) return v.handPhase === 'handEnd' ? <ResultPanel v={v} players={players} /> : null;
|
||||
// My hand's name changes once the new card has flown in.
|
||||
const [handName, lowName] = useAfterMotionValue(`${v.my.handName ?? ''}\n${v.my.lowName ?? ''}`).split('\n');
|
||||
if (!me || !seat) return v.handPhase === 'handEnd' && endShown ? <ResultPanel v={v} players={players} /> : null;
|
||||
const m = v.my;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
@@ -678,10 +687,10 @@ function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
) : (
|
||||
<MyCards v={v} seat={seat} />
|
||||
)}
|
||||
{(m.handName || m.lowName) && (
|
||||
{(handName || lowName) && (
|
||||
<div style={{ textAlign: 'center', fontSize: '1.4rem', fontWeight: 900 }}>
|
||||
지금: {m.handName}
|
||||
{m.lowName && <span className="small" style={{ marginLeft: 8 }}>로우 {m.lowName}</span>}
|
||||
지금: {handName}
|
||||
{lowName && <span className="small" style={{ marginLeft: 8 }}>로우 {lowName}</span>}
|
||||
</div>
|
||||
)}
|
||||
{seat.folded && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>이번 판은 포기했어요. 내 카드는 나만 볼 수 있어요.</p>}
|
||||
@@ -702,13 +711,13 @@ function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
</p>
|
||||
)}
|
||||
{seat.inHand && v.handPhase === 'betting' && !seat.folded && !seat.allIn && <BetBar v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.handPhase === 'handEnd' && <ResultPanel v={v} players={players} />}
|
||||
{m.canReady && (
|
||||
{v.handPhase === 'handEnd' && endShown && <ResultPanel v={v} players={players} />}
|
||||
{m.canReady && endShown && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={pending} onClick={() => act({ type: 'ready' })}>
|
||||
다음 판으로
|
||||
</button>
|
||||
)}
|
||||
{v.handPhase === 'handEnd' && seat.inHand && seat.ready && seat.status !== 'left' && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>다른 사람을 기다리는 중…</p>}
|
||||
{v.handPhase === 'handEnd' && endShown && seat.inHand && seat.ready && seat.status !== 'left' && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>다른 사람을 기다리는 중…</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1049,7 +1058,11 @@ function HandRanks({ mode, o }: { mode: PokerMode; o: Pick<PokerOptions, 'indian
|
||||
|
||||
function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<PokerView>) {
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
|
||||
// Chip counts change once the chips have landed on the table.
|
||||
const shownStacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(','));
|
||||
const stackOf = new Map(shownStacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const));
|
||||
const stack = (s: SeatView) => stackOf.get(s.id) ?? s.stack;
|
||||
const ranked = [...v.seats].sort((a, b) => stack(b) - stack(a));
|
||||
const scoreBy = v.options.endCondition === 'hands' || v.handsPlayed >= 300;
|
||||
return (
|
||||
<>
|
||||
@@ -1074,31 +1087,33 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
{s.rebuys > 0 ? ` · 리바이 ${s.rebuys}` : ''}
|
||||
{s.status === 'eliminated' ? ' · 탈락' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
<Chips n={s.stack} />
|
||||
<Chips n={stack(s)} />
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => {
|
||||
const sc = v.result!.scores[g[0]!] ?? 0;
|
||||
return (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
|
||||
{scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''}
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => {
|
||||
const sc = v.result!.scores[g[0]!] ?? 0;
|
||||
return (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
|
||||
{scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{scoreBy && <span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>}
|
||||
{v.stats.bestHand && (
|
||||
<span className="small">
|
||||
최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판)
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{scoreBy && <span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>}
|
||||
{v.stats.bestHand && (
|
||||
<span className="small">
|
||||
최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판)
|
||||
</span>
|
||||
)}
|
||||
{v.stats.biggestPot && <span className="small">가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)</span>}
|
||||
</div>
|
||||
)}
|
||||
{v.stats.biggestPot && <span className="small">가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)</span>}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보</summary>
|
||||
@@ -1128,20 +1143,22 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
</details>
|
||||
)}
|
||||
{v.my.canRebuy && !confirmQuit && (
|
||||
<Sheet onClose={() => {}} label="칩 다시 받기">
|
||||
<h2>칩을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rebuy', accept: true })}>
|
||||
칩 다시 받기
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ flex: 1 }} disabled={pending} onClick={() => setConfirmQuit(true)}>
|
||||
그만하기
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
<AfterMotion>
|
||||
<Sheet onClose={() => {}} label="칩 다시 받기">
|
||||
<h2>칩을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rebuy', accept: true })}>
|
||||
칩 다시 받기
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ flex: 1 }} disabled={pending} onClick={() => setConfirmQuit(true)}>
|
||||
그만하기
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{confirmQuit && v.my.canRebuy && (
|
||||
<ConfirmSheet
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { JUMP_LAND_MS, qdSound } from './sound';
|
||||
import { useAfterMotionValue } from '../../lib/motion';
|
||||
|
||||
type O = 'h' | 'v';
|
||||
interface Pt {
|
||||
@@ -196,6 +197,8 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const newWall = recent?.kind === 'wall' ? wallKey(recent.wall) : null;
|
||||
const goalSeat = recent?.kind === 'move' && reachedGoal(recent.seat, before?.seats ?? [], v.seats) ? recent.seat : null;
|
||||
const takenBack = before && !forward ? before.walls.filter((w) => !v.walls.some((x) => wallKey(x) === wallKey(w))) : [];
|
||||
// Who has reached their goal, as shown: the winner's ring only once the pawn has landed on the goal row.
|
||||
const arrived = useAfterMotionValue(v.seats.filter((x) => x.status === 'finished').map((x) => x.seat).join(''));
|
||||
|
||||
const legalCells = useMemo(() => {
|
||||
const m = new Set<string>();
|
||||
@@ -562,7 +565,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
return (
|
||||
<g key={x.seat} className={`qd-pawn${moved && jumped ? ' jump' : ''}`} style={{ transform: `translate(${p.x + 0.5}px, ${p.y + 0.5}px)` }} data-pawn={x.seat} data-at={label(x.pos)}>
|
||||
{turn && <circle className="qd-turn-ring" cx={0} cy={0} r={0.45} fill="none" stroke={SEAT_COLOR[x.seat]} strokeWidth={0.06} />}
|
||||
{x.status === 'finished' && <circle className="bm-win" cx={0} cy={0} r={0.47} fill="none" stroke="#fbbf24" strokeWidth={0.07} />}
|
||||
{x.status === 'finished' && arrived.includes(x.seat) && <circle className="bm-win" cx={0} cy={0} r={0.47} fill="none" stroke="#fbbf24" strokeWidth={0.07} />}
|
||||
<g key={`h${v.moveCount}`} className={moved ? (jumped ? 'qd-hop' : 'qd-step') : undefined}>
|
||||
<PawnMark seat={x.seat} cx={0} cy={0} />
|
||||
</g>
|
||||
@@ -645,7 +648,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
)}
|
||||
{me && v.phase === 'playing' && !(myTurn && mode === 'wall') && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{me.status === 'playing'
|
||||
{me.status === 'playing' || (me.status === 'finished' && !arrived.includes(me.seat))
|
||||
? `내 말은 ${COLOR_KO[me.seat]}(${SEAT_KO[me.seat]})이에요. ${myGoal} 줄(${COLOR_KO[me.seat]} 띠)에 먼저 닿으면 이겨요.`
|
||||
: me.status === 'finished'
|
||||
? '목표에 도착했어요! 남은 사람들의 순위가 정해질 때까지 지켜봐요.'
|
||||
@@ -691,7 +694,7 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid
|
||||
} else if (active && tc.kind === 'perMove') {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={x.playerId === me} size={40} />;
|
||||
}
|
||||
const state =
|
||||
const stateNow =
|
||||
x.status === 'finished'
|
||||
? `${x.finishOrder}등 도착`
|
||||
: x.status === 'resigned'
|
||||
@@ -699,6 +702,8 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid
|
||||
: x.status === 'timedOut'
|
||||
? '시간패'
|
||||
: `남은 길 ${x.distance}칸${x.autoMoveStreak > 0 ? ` · 자리 비움 ${x.autoMoveStreak}번` : ''}`;
|
||||
// "1등 도착" and the path length change once the move has played on the board.
|
||||
const state = useAfterMotionValue(stateNow);
|
||||
return (
|
||||
<div
|
||||
className="card row"
|
||||
|
||||
@@ -34,7 +34,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useNewEntries
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
@@ -351,8 +351,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const movedFrom = useRef<Map<string, DOMRect> | null>(null);
|
||||
/** Who had the turn on the previous render: tiles that newly show up on the table come from that seat. */
|
||||
const prevCurrent = useRef(v.current);
|
||||
const winTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(winTimer.current), []);
|
||||
// The round / match end banners are staged with timers (after the last tiles have landed): results wait for them.
|
||||
const endTimers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
const [ending, setEnding] = useState(false);
|
||||
useMotionHold(ending);
|
||||
useEffect(() => () => endTimers.current.forEach(clearTimeout), []);
|
||||
const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record<string, boolean>; table: Set<string> } | null>(null);
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
const boardRef = useRef<HTMLDivElement>(null);
|
||||
@@ -485,23 +488,42 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
// Somebody else is moving tiles around in their turn.
|
||||
snd.shuffleQuiet();
|
||||
}
|
||||
const endSteps: (() => void)[] = [];
|
||||
// The round is over: "루미큐브!" when somebody emptied the rack (the match result sound itself is played by the room page).
|
||||
if (prev.phase === 'playing' && v.phase !== 'playing' && v.round) {
|
||||
const w = v.round.winners;
|
||||
const who = w.includes(me ?? '') ? '내가' : `${w.map((p) => nick(players, p)).join(', ')}님이`;
|
||||
if (v.round.endReason === 'rackEmpty') {
|
||||
showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`);
|
||||
for (const p of w) bump(seatEl(p));
|
||||
if (v.phase === 'roundEnd') sfx.fanfare();
|
||||
} else if (v.round.endReason === 'stalemate') showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요');
|
||||
const roundEnd = v.phase === 'roundEnd';
|
||||
if (v.round.endReason === 'rackEmpty')
|
||||
endSteps.push(() => {
|
||||
showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`);
|
||||
for (const p of w) bump(seatEl(p));
|
||||
if (roundEnd) sfx.fanfare();
|
||||
});
|
||||
else if (v.round.endReason === 'stalemate') endSteps.push(() => showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요'));
|
||||
}
|
||||
// The match is over: who won (after the round banner, if there was one).
|
||||
if (prev.phase !== 'finished' && v.phase === 'finished' && v.result?.reason === 'normal') {
|
||||
const top = v.result.ranking[0] ?? [];
|
||||
const iWon = top.includes(me ?? '');
|
||||
const text = iWon ? '승리!' : top.length ? `${top.map((p) => nick(players, p)).join(', ')}님 승리` : '게임 끝';
|
||||
clearTimeout(winTimer.current);
|
||||
winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? fxMs(1500) : 0);
|
||||
const sub = v.match.total > 1 ? `${v.match.total}판 합계` : undefined;
|
||||
endSteps.push(() => showBanner(text, iWon ? 'gold' : 'blue', sub));
|
||||
}
|
||||
if (endSteps.length) {
|
||||
// The last tiles put down (new on the screen: they fly in from the seat, see below) land first, then the banners
|
||||
// one by one. `prevCells` (declared below) still holds the previous render's board here.
|
||||
const before = prevCells.current;
|
||||
const landed = before ? cells.filter((x) => !before.has(x.id)).length : 0;
|
||||
const lead = prev.phase === 'playing' && landed ? fxMs(380 + Math.min(landed, 20) * 60) : 0;
|
||||
endTimers.current.forEach(clearTimeout);
|
||||
setEnding(true);
|
||||
endTimers.current = endSteps.map((f, i) =>
|
||||
setTimeout(() => {
|
||||
f();
|
||||
if (i === endSteps.length - 1) setEnding(false);
|
||||
}, lead + i * fxMs(1500)),
|
||||
);
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -1004,7 +1026,9 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
</>
|
||||
)}
|
||||
|
||||
{v.phase !== 'playing' && v.round && <RoundPanel v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} />}
|
||||
<AfterMotion when={v.phase !== 'playing' && !!v.round}>
|
||||
<RoundPanel v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} />
|
||||
</AfterMotion>
|
||||
|
||||
{my && v.phase === 'playing' && (
|
||||
<div className="rk-rackwrap">
|
||||
@@ -1210,14 +1234,24 @@ function logText(e: LogEntry, players: Record<string, PublicUser>, me: string |
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function RummikubSide({ view: v, me, players }: BoardProps<RummikubView>) {
|
||||
const order = [...v.seats].sort((a, b) => b.wins - a.wins || b.total - a.total);
|
||||
// Wins / points (and 게임 끝) change when a round ends: they show once the board has played the end of the round.
|
||||
const scoreKey = useAfterMotionValue(`${v.phase === 'finished' ? 'f' : ''}|${v.seats.map((s) => `${s.id}:${s.wins}:${s.total}`).join(',')}`);
|
||||
const [shownEnd, shownScores] = scoreKey.split('|') as [string, string];
|
||||
const score = new Map(
|
||||
shownScores.split(',').map((x) => {
|
||||
const [id, w, t] = x.split(':');
|
||||
return [id!, { wins: Number(w), total: Number(t) }];
|
||||
}),
|
||||
);
|
||||
const sc = (s: RummikubView['seats'][number]) => score.get(s.id) ?? { wins: s.wins, total: s.total };
|
||||
const order = [...v.seats].sort((a, b) => sc(b).wins - sc(a).wins || sc(b).total - sc(a).total);
|
||||
const lastRound = v.opening.length ? Math.max(...v.opening.map((o) => o.round)) : 0;
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'}</strong>
|
||||
<strong>{shownEnd ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'}</strong>
|
||||
<span className="small muted">남은 타일 {v.poolCount}장</span>
|
||||
</div>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
@@ -1231,8 +1265,8 @@ function RummikubSide({ view: v, me, players }: BoardProps<RummikubView>) {
|
||||
<span className="small">{s.tiles}장</span>
|
||||
{v.match.total > 1 && (
|
||||
<span className="small muted">
|
||||
{s.wins}승 · {s.total > 0 ? '+' : ''}
|
||||
{s.total}점
|
||||
{sc(s).wins}승 · {sc(s).total > 0 ? '+' : ''}
|
||||
{sc(s).total}점
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { HWATU_RATIO, HwatuBack, HwatuCard } from '../../components/cards/HwatuC
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import type { BoardProps } from '../types';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import { JokboBoard } from './jokbo';
|
||||
|
||||
export const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
||||
@@ -319,6 +319,10 @@ function ActBubble({ seat }: { seat: SeotdaSeatView }) {
|
||||
interface SeatProps {
|
||||
seat: SeotdaSeatView;
|
||||
view: SeotdaView;
|
||||
/** The cards have finished turning over: 족보 seals may show. */
|
||||
revealed: boolean;
|
||||
/** The payout has finished: the hand's +/- may show. */
|
||||
settled: boolean;
|
||||
players: Record<string, PublicUser>;
|
||||
me: string | null;
|
||||
deadline: number | null;
|
||||
@@ -328,8 +332,10 @@ interface SeatProps {
|
||||
setRef: (id: string, el: HTMLElement | null) => void;
|
||||
}
|
||||
|
||||
function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) {
|
||||
function Seat({ seat, view: v, revealed, settled, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) {
|
||||
const u = userOf(players, seat.id);
|
||||
// The money changes once the coins have flown (bets to the 판돈, the 판돈 to the winner).
|
||||
const stack = useAfterMotionValue(seat.stack);
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const tags: [string, string][] = [];
|
||||
if (seat.left) tags.push(['나감', '#b91c1c']);
|
||||
@@ -367,7 +373,7 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef
|
||||
</div>
|
||||
<div className="row" style={{ justifyContent: 'space-between', gap: 4, flexWrap: 'nowrap' }}>
|
||||
<span className="sd-money" title="보유 금액">
|
||||
{formatWonShort(seat.stack)}원
|
||||
{formatWonShort(stack)}원
|
||||
</span>
|
||||
{seat.matchBet > 0 && (
|
||||
<span className="small sub" style={{ whiteSpace: 'nowrap' }} title="이번 판에 건 돈">
|
||||
@@ -375,8 +381,8 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{seat.handName && <div className={`sd-seal${isBig(seat.handName) ? ' big' : ''} anim-pop`}>{seat.handName}</div>}
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
{revealed && seat.handName && <div className={`sd-seal${isBig(seat.handName) ? ' big' : ''} anim-pop`}>{seat.handName}</div>}
|
||||
{settled && seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
<div className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</div>
|
||||
)}
|
||||
{tags.length > 0 && (
|
||||
@@ -449,6 +455,14 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
const [banner, setBanner] = useState<{ text: string; key: number } | null>(null);
|
||||
const seen = useRef<{ match: string; log: number; cards: number; phase: string | null } | null>(null);
|
||||
const flyId = useRef(0);
|
||||
const match = `${v.handNo}-${v.rematchNo}`;
|
||||
// Bet coins still to fly (staged with timers): results wait for them.
|
||||
const [queued, setQueued] = useState(0);
|
||||
useMotionHold(queued > 0);
|
||||
// The hand's result waits until the cards have turned over; `revealedAt` = the (re)match whose payout has started.
|
||||
const [payout, setPayout] = useState<{ winners: Set<string>; banner: string | null } | null>(null);
|
||||
const cardsTurned = useMotionSettled(!!payout);
|
||||
const [revealedAt, setRevealedAt] = useState<string | null>(() => (v.handPhase === 'handEnd' ? match : null));
|
||||
|
||||
const center = (el: HTMLElement | null | undefined) => {
|
||||
const t = tableRef.current?.getBoundingClientRect();
|
||||
@@ -467,7 +481,6 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const match = `${v.handNo}-${v.rematchNo}`;
|
||||
const cards = v.seats.reduce((a, s) => a + s.cards.length, 0);
|
||||
const prev = seen.current;
|
||||
seen.current = { match, log: v.betLog.length, cards, phase: v.handPhase };
|
||||
@@ -481,8 +494,10 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
}
|
||||
// Bets since last time (anyone's): coins fly from the seat to the 판돈.
|
||||
const fresh: BetLogEntry[] = sameMatch ? v.betLog.slice(prev.log) : v.betLog;
|
||||
if (fresh.length) setQueued((q) => q + fresh.length);
|
||||
fresh.forEach((e, i) => {
|
||||
setTimeout(() => {
|
||||
setQueued((q) => q - 1);
|
||||
if (e.t === 'die') sfx.whoosh();
|
||||
else if (e.amount <= 0) sfx.tick();
|
||||
else {
|
||||
@@ -492,36 +507,41 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
}
|
||||
}, fxMs(i * 220));
|
||||
});
|
||||
// Result: reveal, payout, banner.
|
||||
// Result: the cards turn over, then (once they have) the payout and the banner.
|
||||
if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') {
|
||||
if (v.showdown || v.foldWin?.shown) sfx.cardFlip();
|
||||
const winners = new Set<string>();
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
const b = bannerOf(v);
|
||||
setTimeout(() => {
|
||||
for (const w of winners) launch('pot', w, 5);
|
||||
if (winners.size) sfx.collect();
|
||||
if (b) {
|
||||
setBanner({ text: b, key: Date.now() });
|
||||
if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare();
|
||||
else sfx.pop();
|
||||
}
|
||||
if (me && winners.has(me)) {
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
|
||||
}, fxMs(v.showdown ? 450 : 150));
|
||||
setPayout({ winners, banner: bannerOf(v) });
|
||||
}
|
||||
}); // every render: cheap comparisons against the refs
|
||||
|
||||
useEffect(() => {
|
||||
if (!cardsTurned || !payout) return;
|
||||
const { winners, banner: b } = payout;
|
||||
setPayout(null);
|
||||
setRevealedAt(match);
|
||||
for (const w of winners) launch('pot', w, 5);
|
||||
if (winners.size) sfx.collect();
|
||||
if (b) {
|
||||
setBanner({ text: b, key: Date.now() });
|
||||
if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare();
|
||||
else sfx.pop();
|
||||
}
|
||||
if (me && winners.has(me)) {
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
|
||||
}, [cardsTurned]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!banner) return undefined;
|
||||
const t = setTimeout(() => setBanner(null), fxMs(1700));
|
||||
return () => clearTimeout(t);
|
||||
}, [banner]);
|
||||
|
||||
return { flies, banner };
|
||||
return { flies, banner, revealed: v.handPhase === 'handEnd' && revealedAt === match && !payout };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- bottom bar (한게임 섯다처럼: 족보 · 내 얼굴 · 내 패 · 베팅 버튼)
|
||||
@@ -657,6 +677,8 @@ interface DockProps {
|
||||
pending: boolean;
|
||||
deadline: number | null;
|
||||
winner: boolean;
|
||||
revealed: boolean;
|
||||
settled: boolean;
|
||||
setRef: SeatProps['setRef'];
|
||||
phone: boolean;
|
||||
/** My card size factor (PC: grows with the table width). */
|
||||
@@ -668,7 +690,7 @@ interface DockProps {
|
||||
* them, then the number-key bet buttons. In 3장 섯다 the cards themselves are clicked to pick the open card / the two
|
||||
* cards to use, and the bet buttons make room for that step's button.
|
||||
*/
|
||||
function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, phone, scale }: DockProps) {
|
||||
function Dock({ view: v, seat, players, act, pending, deadline, winner, revealed, settled, setRef, phone, scale }: DockProps) {
|
||||
const [pick, setPick] = useState<number[]>([]);
|
||||
useEffect(() => setPick([]), [v.handNo, v.rematchNo, v.handPhase]);
|
||||
const [hover, setHover] = useState<BetType | null>(null);
|
||||
@@ -679,7 +701,11 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
const myKeys = (seat?.cards ?? []).filter(isCard).map((c) => c.key);
|
||||
if (myKeys.length && first.current?.tag !== matchTag) first.current = { tag: matchTag, keys: new Set(myKeys) };
|
||||
const squeezing = (key: string) => !!first.current && first.current.tag === matchTag && !first.current.keys.has(key) && !peeked.has(key) && !seat?.handName;
|
||||
const peeking = myKeys.some(squeezing);
|
||||
// Cards still being dealt in: the 족보 they make shows once they have landed.
|
||||
const cardKey = myKeys.join(',');
|
||||
const dealing = useAfterMotionValue(cardKey) !== cardKey;
|
||||
const peeking = myKeys.some(squeezing) || dealing;
|
||||
const stack = useAfterMotionValue(seat?.stack ?? 0);
|
||||
const u = seat ? userOf(players, seat.id) : null;
|
||||
const cards = seat?.cards ?? [];
|
||||
const opening = !!seat && v.handPhase === 'open' && seat.opening === false;
|
||||
@@ -702,7 +728,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
|
||||
// Under my cards: the 족보 (or, with 3 cards, every pair's 족보 like 한게임; clickable while choosing).
|
||||
let under: ReactNode = null;
|
||||
if (seat?.handName) under = <span className={`sd-seal anim-pop${isBig(seat.handName) ? ' big' : ''}`}>{seat.handName}</span>;
|
||||
if (seat?.handName && revealed) under = <span className={`sd-seal anim-pop${isBig(seat.handName) ? ' big' : ''}`}>{seat.handName}</span>;
|
||||
else if (seat?.folded) under = <span className="sd-seal die">다이</span>;
|
||||
else if (playing && hints && v.myCombos && !v.myChosen && !peeking)
|
||||
under = (
|
||||
@@ -766,7 +792,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
else if (v.handPhase === 'handEnd')
|
||||
actions = (
|
||||
<>
|
||||
<ResultPanel view={v} players={players} />
|
||||
{settled ? <ResultPanel view={v} players={players} /> : <p>결과를 확인하는 중이에요…</p>}
|
||||
{seat && seat.status === 'playing' && !seat.left && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={seat.ready || pending} onClick={() => act({ type: 'ready' })}>
|
||||
{seat.ready ? '다른 사람을 기다리는 중…' : v.next === 'rematch' ? '재경기 시작' : '다음 판으로'}
|
||||
@@ -798,7 +824,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
<ActBubble seat={seat} />
|
||||
<Avatar user={u} size={phone ? 34 : 52} />
|
||||
<strong className="nm">{u.nickname} (나)</strong>
|
||||
<span className="sd-money">{formatWonShort(seat.stack)}원</span>
|
||||
<span className="sd-money">{formatWonShort(stack)}원</span>
|
||||
<span className="row" style={{ gap: 4, justifyContent: 'center', minHeight: 30 }}>
|
||||
{seat.isDealer && (
|
||||
<span className="sd-tag" style={{ background: '#facc15', color: '#422006' }} title="선(먼저 받고 먼저 거는 사람)">
|
||||
@@ -807,7 +833,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
)}
|
||||
{timed && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine size={30} />}
|
||||
</span>
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && <span className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</span>}
|
||||
{settled && seat.handDelta !== null && seat.handDelta !== 0 && <span className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</span>}
|
||||
</div>
|
||||
)}
|
||||
<div className="sd-play" role={group ? 'group' : undefined} aria-label={group}>
|
||||
@@ -838,7 +864,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
)}
|
||||
</div>
|
||||
{under && <div className="under">{under}</div>}
|
||||
{playing && h && hints && !seat.handName && <span className="hint">{h.hint}</span>}
|
||||
{playing && h && hints && !(seat.handName && revealed) && <span className="hint">{h.hint}</span>}
|
||||
{seat.folded && !seat.handName && <span className="hint">다이했어요. 내 패는 나만 볼 수 있어요.</span>}
|
||||
</div>
|
||||
)}
|
||||
@@ -923,7 +949,9 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
if (el) seatEls.current.set(id, el);
|
||||
else seatEls.current.delete(id);
|
||||
};
|
||||
const { flies, banner } = useTableEffects(v, me, tableRef, seatEls, potEl);
|
||||
const { flies, banner, revealed } = useTableEffects(v, me, tableRef, seatEls, potEl);
|
||||
// Result panel, winners' glow and +/- wait for the payout coins and the banner.
|
||||
const settled = useMotionSettled(revealed);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevToAct = useRef(v.toAct);
|
||||
useLayoutEffect(() => {
|
||||
@@ -937,7 +965,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
prevToAct.current = v.toAct;
|
||||
}, [v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const winners = new Set<string>();
|
||||
if (v.handPhase === 'handEnd') {
|
||||
if (v.handPhase === 'handEnd' && settled) {
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
}
|
||||
@@ -966,6 +994,8 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
key={s.id}
|
||||
seat={s}
|
||||
view={v}
|
||||
revealed={revealed}
|
||||
settled={settled}
|
||||
players={players}
|
||||
me={me}
|
||||
deadline={deadline}
|
||||
@@ -996,7 +1026,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Dock view={v} seat={mySeat} players={players} act={act} pending={pending} deadline={deadline} winner={!!mySeat && winners.has(mySeat.id)} setRef={setRef} phone={phone} scale={dockScale} />
|
||||
<Dock view={v} seat={mySeat} players={players} act={act} pending={pending} deadline={deadline} winner={!!mySeat && winners.has(mySeat.id)} revealed={revealed} settled={settled} setRef={setRef} phone={phone} scale={dockScale} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/mone
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import { HWATU_CREDIT } from '../../components/cards/HwatuCard';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { BET_KO, SeotdaBoard, nick, resultLine, totalMsOf, userOf } from './board';
|
||||
@@ -21,7 +22,14 @@ const PLAY_MONEY_NOTICE = '여기 나오는 원과 판돈은 이 방 안에서
|
||||
|
||||
function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps<SeotdaView>) {
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
|
||||
// Money, 판 기록 and the popups below change only after the table has finished animating (coins, cards).
|
||||
const stacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(','));
|
||||
const stackOf = new Map(stacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))]));
|
||||
const ranked = v.seats.map((s) => ({ ...s, stack: stackOf.get(s.id) ?? s.stack })).sort((a, b) => b.stack - a.stack);
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const showResult = useMotionSettled(!!v.result);
|
||||
const showRejoin = useMotionSettled(!!v.rejoin?.mine);
|
||||
const showRebuy = useMotionSettled(!!v.rebuy?.mine);
|
||||
const log = v.betLog;
|
||||
return (
|
||||
<>
|
||||
@@ -55,7 +63,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{showResult && v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
@@ -80,11 +88,11 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<details className="card" style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>판 기록</summary>
|
||||
<ol style={{ listStyle: 'none', margin: '8px 0 0', padding: 0, display: 'grid', gap: 2, maxHeight: 180, overflow: 'auto' }}>
|
||||
{[...v.history].reverse().map((r, i) => (
|
||||
{[...history].reverse().map((r, i) => (
|
||||
<li key={i} className="small">
|
||||
<span className="muted">
|
||||
{r.handNo}판{r.rematchNo ? `(재${r.rematchNo})` : ''}
|
||||
@@ -97,7 +105,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
{v.rejoin?.mine && (
|
||||
{showRejoin && v.rejoin?.mine && (
|
||||
<Sheet onClose={() => {}} label="재경기 참가">
|
||||
<h2>구사 재경기에 다시 들어갈까요?</h2>
|
||||
<p className="muted">판돈에 {formatWon(v.rejoin.cost)}을 더 내면 재경기에 참가할 수 있어요. 시간이 지나면 참가하지 않아요.</p>
|
||||
@@ -111,7 +119,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</div>
|
||||
</Sheet>
|
||||
)}
|
||||
{v.rebuy?.mine && !confirmQuit && (
|
||||
{showRebuy && v.rebuy?.mine && !confirmQuit && (
|
||||
<Sheet onClose={() => {}} label="시작 금액 다시 받기">
|
||||
<h2>가진 원을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -137,6 +137,26 @@ function usePlayback(v: SixNimmtView): Playback {
|
||||
return { rows: st.rows, marker: st.marker, step: st, waiting, busy: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scores as of the last still screen: totals, this round's bulls and the round columns change only after the replay
|
||||
* has shown the take that caused them.
|
||||
*/
|
||||
function useShownScores(v: SixNimmtView): (p: string) => { total: number; roundBulls: number; roundScores: number[] } {
|
||||
const now = (p: string) => ({ total: v.players[p]!.total, roundBulls: v.players[p]!.roundBulls, roundScores: v.roundScores[p] ?? [] });
|
||||
const key = v.seats.map((p) => `${p}|${now(p).total}|${now(p).roundBulls}|${now(p).roundScores.join('.')}`).join(',');
|
||||
const shown = useAfterMotionValue(key);
|
||||
const map = new Map(
|
||||
shown
|
||||
.split(',')
|
||||
.filter(Boolean)
|
||||
.map((x) => {
|
||||
const [id, total, roundBulls, rs] = x.split('|') as [string, string, string, string];
|
||||
return [id, { total: Number(total), roundBulls: Number(roundBulls), roundScores: rs ? rs.split('.').map(Number) : [] }];
|
||||
}),
|
||||
);
|
||||
return (p) => map.get(p) ?? now(p);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rows
|
||||
|
||||
function Rows({ v, pb, me, players, act, pending, overlay }: { v: SixNimmtView; pb: Playback; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; overlay?: ReactNode }) {
|
||||
@@ -223,10 +243,11 @@ function recommendRow(v: SixNimmtView): number {
|
||||
|
||||
function Strip({ v, me, players, active, deadline }: { v: SixNimmtView; me: string | null; players: Record<string, PublicUser>; active: string[]; deadline: number | null }) {
|
||||
const playing = v.phase !== 'finished';
|
||||
const score = useShownScores(v);
|
||||
return (
|
||||
<section className="sx-strip" aria-label="참가자">
|
||||
{v.seats.map((p) => {
|
||||
const pv = v.players[p]!;
|
||||
const pv = { ...v.players[p]!, ...score(p) };
|
||||
const on = playing && active.includes(p);
|
||||
const state = pv.left ? '나감' : pv.away ? '자리 비움' : v.phase === 'select' ? (pv.picked ? '골랐어요' : '고르는 중') : v.phase === 'choose' && v.pending?.player === p ? '줄 고르는 중' : v.phase === 'draft' && v.draft?.at === p ? '카드 가져가는 중' : '';
|
||||
return (
|
||||
@@ -286,7 +307,7 @@ function previewText(p: Preview | undefined): string {
|
||||
return `${p.row + 1}번 줄 ${p.side === 'L' ? '왼쪽' : `${p.pos}번째`}${'tie' in p && p.tie ? '(고름)' : ''}`;
|
||||
}
|
||||
|
||||
function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function Hand({ v, act, pending, replaying }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean; replaying: boolean }) {
|
||||
const my = v.my!;
|
||||
const [pick, setPick] = useState<Card | null>(null);
|
||||
const [flip, setFlip] = useState(false);
|
||||
@@ -324,7 +345,8 @@ function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void;
|
||||
<div className="sx-hand" role="group" aria-label="손패">
|
||||
{my.hand.map((h) => {
|
||||
const up = chosen === h.n;
|
||||
const pv = flip && h.flipped ? h.flipped.preview : h.preview;
|
||||
// The previews use the rows after the turn still being replayed: they show once it has played.
|
||||
const pv = replaying ? undefined : flip && h.flipped ? h.flipped.preview : h.preview;
|
||||
return (
|
||||
<button
|
||||
key={h.n}
|
||||
@@ -471,14 +493,18 @@ function FinalTable({ v, me, players }: { v: SixNimmtView; me: string | null; pl
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function Board({ view: v, me, players, act, pending, active, deadline }: BoardProps<SixNimmtView>) {
|
||||
const pb = usePlayback(v);
|
||||
const replay = usePlayback(v);
|
||||
// The replay steps are timers: results wait for it, then for the last card to finish landing.
|
||||
useMotionHold(replay.busy);
|
||||
const still = useMotionSettled(!replay.busy);
|
||||
const pb: Playback = { ...replay, busy: !still };
|
||||
const [roundShown, setRoundShown] = useState<number>(v.lastRound?.round ?? 0);
|
||||
const [roundOpen, setRoundOpen] = useState(false);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
const prevPicked = useRef(0);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
|
||||
// Round result window: once the replay of the last turn is done, for 5 seconds (closable).
|
||||
// Round result window: once the replay of the last turn is done and the screen is still, for 5 seconds (closable).
|
||||
useEffect(() => {
|
||||
if (!v.lastRound || v.lastRound.round === roundShown || pb.busy) return;
|
||||
setRoundShown(v.lastRound.round);
|
||||
@@ -517,11 +543,12 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
|
||||
const seated = !!me && v.seats.includes(me) && !v.players[me]!.left;
|
||||
const pd = v.pending;
|
||||
const head = useAfterMotionValue(v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? `${v.round}라운드 · 카드 골라 가기` : `${v.round}라운드 · ${v.turn}/10번째 카드`);
|
||||
return (
|
||||
<div className="sx-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="card sx-head">
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? `${v.round}라운드 · 카드 골라 가기` : `${v.round}라운드 · ${v.turn}/10번째 카드`}</strong>
|
||||
<strong>{head}</strong>
|
||||
<span className="small muted">
|
||||
{v.options.endMode === 'score' ? `${v.options.endScore}점이 넘으면 끝` : `${v.options.rounds}라운드까지`}
|
||||
{v.options.fanCard !== 'none' ? ` · ${FAN_KO[v.options.fanCard]}` : ''}
|
||||
@@ -529,8 +556,8 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
</span>
|
||||
</div>
|
||||
<Strip v={v} me={me} players={players} active={active} deadline={deadline} />
|
||||
{v.result && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft ? (
|
||||
{v.result && !pb.busy && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft && !pb.busy ? (
|
||||
<Draft v={v} me={me} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<>
|
||||
@@ -545,7 +572,7 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
</div>
|
||||
)}
|
||||
<Rows v={v} pb={pb} me={me} players={players} act={act} pending={pending} overlay={roundOpen && v.lastRound && !(v.phase === 'choose' && pd?.player === me) ? <RoundResult v={v} me={me} players={players} onClose={() => setRoundOpen(false)} /> : null} />
|
||||
{seated && v.my && v.phase !== 'finished' && <Hand v={v} act={act} pending={pending} />}
|
||||
{seated && v.my && v.phase !== 'finished' && <Hand v={v} act={act} pending={pending} replaying={pb.busy} />}
|
||||
</>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -606,7 +633,11 @@ function Tracker({ v, me, players }: { v: SixNimmtView; me: string | null; playe
|
||||
|
||||
function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
const rounds = Math.max(0, ...v.seats.map((p) => v.roundScores[p]!.length));
|
||||
const score = useShownScores(v);
|
||||
// Takes join the log once the board has replayed them.
|
||||
const shownLog = useAfterMotionValue(v.log.at(-1)?.n ?? 0);
|
||||
const log = v.log.filter((e) => e.n <= shownLog);
|
||||
const rounds = Math.max(0, ...v.seats.map((p) => score(p).roundScores.length));
|
||||
const playing = v.phase !== 'finished';
|
||||
return (
|
||||
<>
|
||||
@@ -629,11 +660,11 @@ function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
<tr key={p}>
|
||||
<td className="sx-td-name">{who(players, me, p)}</td>
|
||||
{Array.from({ length: rounds }, (_, i) => (
|
||||
<td key={i}>{v.roundScores[p]![i] ?? ''}</td>
|
||||
<td key={i}>{score(p).roundScores[i] ?? ''}</td>
|
||||
))}
|
||||
{playing && <td>{v.players[p]!.roundBulls ? `+${v.players[p]!.roundBulls}` : ''}</td>}
|
||||
{playing && <td>{score(p).roundBulls ? `+${score(p).roundBulls}` : ''}</td>}
|
||||
<td>
|
||||
<b>{v.players[p]!.total}</b>
|
||||
<b>{score(p).total}</b>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -642,11 +673,11 @@ function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
</div>
|
||||
</section>
|
||||
<Tracker v={v} me={me} players={players} />
|
||||
{v.log.length > 0 && (
|
||||
{log.length > 0 && (
|
||||
<section className="card sx-logbox" aria-label="기록">
|
||||
<h3>기록</h3>
|
||||
<ul className="sx-log" tabIndex={0} aria-label="기록 (최신이 위)">
|
||||
{[...v.log]
|
||||
{[...log]
|
||||
.reverse()
|
||||
.slice(0, 30)
|
||||
.map((e) => (
|
||||
|
||||
@@ -22,7 +22,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntr
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// Type-only imports above keep the rules module out of the bundle; the few constants live here.
|
||||
const COLORS: Color[] = ['W', 'U', 'G', 'R', 'K'];
|
||||
@@ -54,6 +54,18 @@ const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.n
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 });
|
||||
const sum = (t: Partial<Record<TokenColor, number>>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0);
|
||||
|
||||
/** Everyone's points as they were when the board last stood still: a new score shows once the card / noble has landed. */
|
||||
function useShownPoints(v: SplendorView): Record<string, number> {
|
||||
const key = useAfterMotionValue(v.order.map((p) => `${p}:${v.players[p]?.points ?? 0}`).join(','));
|
||||
const out: Record<string, number> = {};
|
||||
for (const p of v.order) out[p] = v.players[p]?.points ?? 0;
|
||||
for (const x of key ? key.split(',') : []) {
|
||||
const [p, n] = x.split(':');
|
||||
if (p! in out) out[p!] = Number(n);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const costText = (cost: Partial<Record<TokenColor, number>>) =>
|
||||
TOKEN_COLORS.filter((c) => cost[c])
|
||||
.map((c) => `${SHORT[c]} ${cost[c]}`)
|
||||
@@ -426,6 +438,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
const prevLog = useRef(v.log.at(-1)?.n ?? 0);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useSplendorFx(v, me, players, showBanner);
|
||||
const pts = useShownPoints(v);
|
||||
|
||||
// Reset local choices whenever the turn or phase moves on.
|
||||
useEffect(() => {
|
||||
@@ -609,12 +622,12 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
className={`sp-chip${v.current === p ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}`}
|
||||
data-fx-seat={p}
|
||||
aria-expanded={openOpp === p}
|
||||
aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||
aria-label={`${nick(players, p)} ${pts[p]}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||
onClick={() => setOpenOpp(openOpp === p ? null : p)}
|
||||
>
|
||||
<Avatar user={userOf(players, p)} size={24} />
|
||||
<span style={{ maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 700 }}>{nick(players, p)}</span>
|
||||
<span className="pt">{pv.points}점</span>
|
||||
<span className="pt">{pts[p]}점</span>
|
||||
<span className="muted small">
|
||||
💎{pv.tokenCount} 🃏{pv.cards.length}
|
||||
{pv.reservedCount ? ` 📌${pv.reservedCount}` : ''}
|
||||
@@ -966,7 +979,22 @@ function gemSpot(p: string, c: TokenColor, me: string | null): Element | null {
|
||||
* previous view). Nothing on the first render (join, reload, replay jump).
|
||||
*/
|
||||
function useSplendorFx(v: SplendorView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
// Staged steps (banners, bumps) wait in timers: results wait for them too (the gaps are not animations).
|
||||
const [staged, setStaged] = useState(0);
|
||||
useMotionHold(staged > 0);
|
||||
const wait = (realMs: number, f: () => void) => {
|
||||
setStaged((n) => n + 1);
|
||||
setTimeout(() => {
|
||||
setStaged((n) => n - 1);
|
||||
f();
|
||||
}, realMs);
|
||||
};
|
||||
const later = (ms: number, f: () => void) => (ms ? wait(fxMs(ms), f) : f());
|
||||
// When the flights started by the last view end (performance.now() ms): the game-end banner comes after them.
|
||||
const flightsEnd = useRef(0);
|
||||
const till = (ms: number) => {
|
||||
flightsEnd.current = Math.max(flightsEnd.current, performance.now() + fxMs(ms));
|
||||
};
|
||||
// Board of the previous view (slot key → card id) to know where a bought / reserved card was.
|
||||
const prevBoard = useRef<Record<string, string | null> | null>(null);
|
||||
// Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still
|
||||
@@ -990,6 +1018,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
const bank = fxEl(`sp-bank-${c}`);
|
||||
const spot = gemSpot(p, c, me);
|
||||
flyGhost(toBank ? spot : bank, toBank ? bank : spot, { kind: 'chip', count: n, gap: 80, delay: at + i * 80, ms: 420, label: SHORT[c], className: `sp-fx-gem sp-fx-${c}` });
|
||||
till(at + (i + n - 1) * 80 + 420);
|
||||
for (let k = 0; k < n; k++) (toBank ? spSfx.clack : spSfx.clink)(at + (i + k) * 80 + (toBank ? 380 : 120), i + k);
|
||||
i += n;
|
||||
}
|
||||
@@ -1024,6 +1053,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
? (snap.current.rects.get(`r:${e.cardId}`) ?? fxEl('sp-reserved'))
|
||||
: seatOf(e.p, me);
|
||||
flyGhost(from, to, { kind: 'card', delay: at, ms: 520, className: `sp-fx-card sp-fx-b-${bonus}` });
|
||||
till(at + 520);
|
||||
later(at + 480, () => bump(to));
|
||||
spSfx.buy(at);
|
||||
const paid = sum(e.paid);
|
||||
@@ -1040,6 +1070,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (newCard && isShown(newCard)) flyFrom(newCard, from, { delay: at, ms: 460, rotate: -8 });
|
||||
else flyGhost(from, e.p === me ? fxEl('sp-reserved') : seatOf(e.p, me), { kind: 'card', delay: at, ms: 500, className: `sp-fx-card ${look}` });
|
||||
spSfx.reserve(at);
|
||||
till(at + (e.gold ? 600 : 500));
|
||||
if (e.gold) {
|
||||
flyGhost(fxEl('sp-bank-gold'), gemSpot(e.p, 'gold', me), { kind: 'chip', delay: at + 180, ms: 420, label: SHORT.gold, className: 'sp-fx-gem sp-fx-gold' });
|
||||
spSfx.gold(at + 520);
|
||||
@@ -1051,6 +1082,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
const from = snap.current.rects.get(`n:${e.nobleId}`) ?? fxEl('sp-nobles');
|
||||
const at2 = at + 150;
|
||||
flyGhost(from, seatOf(e.p, me), { kind: 'card', delay: at2, ms: 560, label: '👑', className: 'sp-fx-noble' });
|
||||
till(at2 + 560);
|
||||
later(at2, () => showBanner('👑 귀족 방문!', 'gold', `${NOBLE_NAME[e.nobleId] ?? '귀족'} → ${e.p === me ? '나' : `${nick(players, e.p)}님`} (+3점)`));
|
||||
spSfx.noble(at2);
|
||||
later(at2 + 560, () => bump(seatOf(e.p, me)));
|
||||
@@ -1094,6 +1126,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (!c || before[k] === c.id || before[k] === undefined) return;
|
||||
const delay = 260 + n * 120;
|
||||
flyFrom(fxEl(`sp-slot-${k}`), fxEl(`sp-deck-${t}`), { delay, ms: 420, rotate: 8, scale: 0.7 });
|
||||
till(delay + 420);
|
||||
spSfx.flip(delay + 380);
|
||||
n++;
|
||||
});
|
||||
@@ -1104,7 +1137,8 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (now !== 'finished' || !v.result) return;
|
||||
const w = v.result.winners;
|
||||
const sub = w.length ? (w.includes(me ?? '') && w.length === 1 ? '내가 이겼어요!' : `${w.map((p) => nick(players, p)).join(', ')}님 승리`) : undefined;
|
||||
later(700, () => showBanner('게임 끝', 'gold', sub));
|
||||
// After the last move's flights (cards, gems, a noble) have landed.
|
||||
wait(Math.max(fxMs(700), flightsEnd.current - performance.now() + fxMs(100)), () => showBanner('게임 끝', 'gold', sub));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1128,11 +1162,12 @@ function MyArea({
|
||||
flag: (key: string) => React.ReactNode;
|
||||
}) {
|
||||
const turn = v.current === me;
|
||||
const pts = useShownPoints(v);
|
||||
return (
|
||||
<section className={`sp-mine${turn && v.phase !== 'finished' ? ' anim-glow' : ''}`} aria-label="내 자리" data-fx="sp-mine" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||
<div className="sp-mine-head">
|
||||
<strong>
|
||||
나 · <span style={{ fontSize: '1.2rem' }}>{pv.points}점</span>
|
||||
나 · <span style={{ fontSize: '1.2rem' }}>{pts[me] ?? pv.points}점</span>
|
||||
<span className="muted small"> / {v.options.targetPoints}점</span>
|
||||
</strong>
|
||||
<span className="small">
|
||||
@@ -1239,13 +1274,14 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
const [ask, setAsk] = useState(false);
|
||||
const mine = me ? v.players[me] : undefined;
|
||||
const log = useMemo(() => [...v.log].reverse(), [v.log]);
|
||||
const pts = useShownPoints(v);
|
||||
// 마지막 라운드 / 게임 끝 show once the move that caused them has played on the board.
|
||||
const head = useAfterMotionValue(v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`);
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 10, gap: 6 }} aria-label="참가자">
|
||||
<div className="row small" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
{v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`}
|
||||
</strong>
|
||||
<strong>{head}</strong>
|
||||
</div>
|
||||
{v.order.map((p, i) => {
|
||||
const pv = v.players[p]!;
|
||||
@@ -1266,8 +1302,8 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
{pv.conceded ? '기권' : pv.away ? '자리 비움' : `보석 ${pv.tokenCount} · 카드 ${pv.cards.length} · 예약 ${pv.reservedCount}`}
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontWeight: 900, fontSize: '1.3rem' }} aria-label={`${nick(players, p)} ${pv.points}점`}>
|
||||
{pv.points}
|
||||
<span style={{ fontWeight: 900, fontSize: '1.3rem' }} aria-label={`${nick(players, p)} ${pts[p]}점`}>
|
||||
{pts[p]}
|
||||
</span>
|
||||
{turn && v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.turnMs || 60_000} mine={p === me} size={36} />}
|
||||
</div>
|
||||
@@ -1276,21 +1312,23 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
{v.result && (
|
||||
<section className="card stack" style={{ padding: 10, gap: 4 }} aria-label="최종 순위">
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<div key={r.player} className="row small" style={{ gap: 6 }}>
|
||||
<strong style={{ width: 32 }}>{r.rank}위</strong>
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{nick(players, r.player)}</span>
|
||||
<span>
|
||||
{r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<section className="card stack" style={{ padding: 10, gap: 4 }} aria-label="최종 순위">
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<div key={r.player} className="row small" style={{ gap: 6 }}>
|
||||
<strong style={{ width: 32 }}>{r.rank}위</strong>
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{nick(players, r.player)}</span>
|
||||
<span>
|
||||
{r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{log.length > 0 && (
|
||||
<details className="card" open style={{ padding: 10 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { bump, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
|
||||
import { fxAnim } from '../../lib/motion';
|
||||
import { fxAnim, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { CardFace, TCard } from './cards';
|
||||
import { helpNow } from './help';
|
||||
@@ -767,10 +767,13 @@ function RoundEndPanel({ v, players, me, act, pending }: { v: TichuView; players
|
||||
|
||||
function Standings({ v, players, me }: { v: TichuView; players: Players; me: string | null }) {
|
||||
const target = v.mode === 'threechu' ? null : v.options.targetScore;
|
||||
const max = Math.max(target ?? 1, ...v.scores.map((x) => Math.abs(x)), 1);
|
||||
// New round scores show once the last trick has flown to its winner (and the 원투! banner has played).
|
||||
const scoreKey = useAfterMotionValue(v.scores.join(','));
|
||||
const scores = scoreKey.split(',').length === v.scores.length ? scoreKey.split(',').map(Number) : v.scores;
|
||||
const max = Math.max(target ?? 1, ...scores.map((x) => Math.abs(x)), 1);
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }} aria-label="점수">
|
||||
{v.scores.map((sc, i) => {
|
||||
{scores.map((sc, i) => {
|
||||
const owners = v.scoreOwners[i]!;
|
||||
const team = v.scoreOwners.length === 2;
|
||||
const label = team ? `${teamName(i)} ${owners.map((p) => (p === me ? '나' : short(nick(players, p)))).join('·')}` : owners[0] === me ? '나' : nick(players, owners[0]!);
|
||||
@@ -866,6 +869,16 @@ function Tip() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The round / game result waits until the board has stopped moving (the last trick flying to its winner, 원투!).
|
||||
* Meanwhile an empty table stays in its place, so the flight still has its start point (`tc-center`).
|
||||
*/
|
||||
function AfterTable({ when, children }: { when: boolean; children: ReactNode }) {
|
||||
const shown = useMotionSettled(when);
|
||||
if (!when) return null;
|
||||
return shown ? children : <div className="tc-table" data-fx="tc-center" aria-hidden />;
|
||||
}
|
||||
|
||||
function useTichuFx(v: TichuView, me: string | null, players: Players, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const seatFx = (seat: number) => seatEl(`seat-${seat}`) ?? (v.seats[seat]?.owner === me ? fxEl('tc-hand') : null);
|
||||
useNewEntries(
|
||||
@@ -968,15 +981,17 @@ function TichuBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{playingish && <TableArea v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'grand' && <GrandPanel v={v} act={act} pending={pending} />}
|
||||
{v.phase === 'exchange' && <ExchangePanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'roundEnd' && <RoundEndPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
<AfterTable when={v.phase === 'roundEnd'}>
|
||||
<RoundEndPanel v={v} players={players} me={me} act={act} pending={pending} />
|
||||
</AfterTable>
|
||||
<AfterTable when={v.phase === 'finished' && !!v.result}>
|
||||
<div className="tc-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result.summary}</span>
|
||||
<span>{v.result?.summary}</span>
|
||||
{v.lastRound && <RoundTable v={v} r={v.lastRound} players={players} me={me} />}
|
||||
<Standings v={v} players={players} me={me} />
|
||||
</div>
|
||||
)}
|
||||
</AfterTable>
|
||||
</div>
|
||||
</div>
|
||||
{v.mySeat !== null && v.seats[v.mySeat] && (playingish || v.phase === 'roundEnd') && (
|
||||
@@ -1037,7 +1052,9 @@ function PlayedTable({ cards }: { cards: string[] }) {
|
||||
}
|
||||
|
||||
function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
const phaseKo = { grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase];
|
||||
// 라운드 결과 / 게임 끝 and the new history row show once the end of the round has played on the board.
|
||||
const phaseKo = useAfterMotionValue({ grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase]);
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const [showLast, setShowLast] = useState(false);
|
||||
return (
|
||||
<>
|
||||
@@ -1052,7 +1069,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
<Standings v={v} players={players} me={me} />
|
||||
</div>
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<div className="card" style={{ padding: 12, overflowX: 'auto', flex: 'none' }}>
|
||||
<strong>라운드 기록</strong>
|
||||
<table className="tc-tbl small" style={{ marginTop: 6 }}>
|
||||
@@ -1067,7 +1084,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.history.map((h) => (
|
||||
{history.map((h) => (
|
||||
<tr key={h.round}>
|
||||
<td>
|
||||
{h.round}
|
||||
|
||||
@@ -37,6 +37,11 @@ export interface GameUI<V = any, O = any> {
|
||||
Options: ComponentType<OptionsProps<O>>;
|
||||
optionsSummary(options: O): string;
|
||||
Rules: ComponentType<{ options?: O }>;
|
||||
/**
|
||||
* Real-time games (할리갈리, 도블, 사과 게임, 그림 맞히기): the turn status changes the moment the state does. Other games show
|
||||
* a new status only after the board has finished animating the move that caused it (lib/motion `useAfterMotionValue`).
|
||||
*/
|
||||
liveStatus?: boolean;
|
||||
/** The board has its own chat channels; the room chat panel is hidden while the game runs (마피아). */
|
||||
ownChat?: boolean;
|
||||
/** The board's chat box shows who is typing in it ("입력 중…"); the status row then shows only the computers thinking (라이어 게임). */
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue } from '../../lib/motion';
|
||||
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
|
||||
@@ -193,6 +193,11 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
/** A score that changes only once the round's last card (and the points flying to the winner) has landed. */
|
||||
function Score({ n, className }: { n: number; className?: string }) {
|
||||
return <span className={className}>{useAfterMotionValue(n)}점</span>;
|
||||
}
|
||||
|
||||
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
|
||||
const u = userOf(players, s.id);
|
||||
return (
|
||||
@@ -215,7 +220,7 @@ function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoVi
|
||||
{s.left && <span className="un-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
|
||||
{s.away && <span className="un-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
|
||||
{!s.isTurn && next && <span className="small muted">다음</span>}
|
||||
{v.options.scoring === 'to500' && <span className="small muted">{s.score}점</span>}
|
||||
{v.options.scoring === 'to500' && <Score n={s.score} className="small muted" />}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -705,8 +710,13 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
|
||||
/>
|
||||
<StartColorPanel v={v} act={act} pending={pending} />
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
{/* Results show once the card that led to them has landed. */}
|
||||
<AfterMotion when={!!v.reveal}>
|
||||
<RevealPanel v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<AfterMotion when={v.phase === 'roundEnd'}>
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
</AfterMotion>
|
||||
{v.my && meSeat && !meSeat.left && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} />}
|
||||
{meSeat?.left && v.phase !== 'finished' && (
|
||||
<div className="un-panel">
|
||||
@@ -853,7 +863,7 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
{multi && <span className="small">{s.score}점</span>}
|
||||
{multi && <Score n={s.score} className="small" />}
|
||||
<span className="un-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
@@ -862,21 +872,23 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
<span key={p.player}>
|
||||
{p.rank}등 {nick(players, p.player)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
<span key={p.player}>
|
||||
{p.rank}등 {nick(players, p.player)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// The client draws from the view only; names and hints live here so the rules module isn't bundled.
|
||||
const NAME: Record<Category, string> = {
|
||||
@@ -202,6 +202,8 @@ function DiceRow({ dice, size }: { dice: number[]; size?: number }) {
|
||||
interface RollAnim {
|
||||
key: number;
|
||||
mask: boolean[];
|
||||
/** All five the same: the 요트! flash waits until the dice have landed. */
|
||||
yacht?: { sub?: string };
|
||||
}
|
||||
|
||||
function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardProps<YachtView>) {
|
||||
@@ -225,6 +227,12 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
if (!pending) setHeld(v.held);
|
||||
}, [v.held, v.turnSeq, v.rollSeq, pending]);
|
||||
|
||||
const yachtFlash = (sub: string | undefined, key: number) => {
|
||||
setFlash({ text: '요트!', sub, key });
|
||||
sfx.fanfare();
|
||||
haptic([80, 40, 80]);
|
||||
};
|
||||
|
||||
// Roll animation, sound, yacht flash and screen-reader text when a new roll arrives (anyone's roll).
|
||||
useLayoutEffect(() => {
|
||||
if (v.rollSeq <= prevRoll.current || !v.dice) {
|
||||
@@ -237,12 +245,9 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
|
||||
const animated = !reducedMotion();
|
||||
rollSound(mask.filter(Boolean).length, animated);
|
||||
if (v.dice.every((d) => d === v.dice![0])) {
|
||||
setFlash({ text: '요트!', sub: v.current === me ? undefined : nick(players, v.current ?? ''), key: v.rollSeq });
|
||||
sfx.fanfare();
|
||||
haptic([80, 40, 80]);
|
||||
}
|
||||
if (animated) setAnim({ key: v.rollSeq, mask });
|
||||
const yacht = v.dice.every((d) => d === v.dice![0]) ? { sub: v.current === me ? undefined : nick(players, v.current ?? '') } : undefined;
|
||||
if (animated) setAnim({ key: v.rollSeq, mask, yacht });
|
||||
else if (yacht) yachtFlash(yacht.sub, v.rollSeq);
|
||||
}, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Someone else (re)holding dice: the same knock I hear on my own taps.
|
||||
@@ -261,12 +266,15 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const end = setTimeout(() => {
|
||||
setAnim(null);
|
||||
setFlick(null);
|
||||
if (anim.yacht) yachtFlash(anim.yacht.sub, anim.key);
|
||||
}, fxMs(ROLL_MS));
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
clearTimeout(end);
|
||||
};
|
||||
}, [anim]);
|
||||
}, [anim]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The tumble is staged with timers (flicking faces): results wait for it.
|
||||
useMotionHold(!!anim);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
@@ -382,7 +390,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
{myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 && <p className="muted small" style={{ textAlign: 'center' }}>남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.</p>}
|
||||
{v.lastScore && <LastScore key={`${v.lastScore.player}:${v.lastScore.category}`} entry={v.lastScore} view={v} me={me} players={players} />}
|
||||
</section>
|
||||
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} onScore={score} pointer={pointer} />
|
||||
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} rolling={!!anim} onScore={score} pointer={pointer} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -429,6 +437,7 @@ function ScoreSheet({
|
||||
players,
|
||||
myTurn,
|
||||
pending,
|
||||
rolling,
|
||||
onScore,
|
||||
pointer,
|
||||
}: {
|
||||
@@ -437,6 +446,8 @@ function ScoreSheet({
|
||||
players: Record<string, PublicUser>;
|
||||
myTurn: boolean;
|
||||
pending: boolean;
|
||||
/** Dice still tumbling: the points they make are not shown (or pickable) until they land. */
|
||||
rolling: boolean;
|
||||
onScore: (c: Category, points: number, viaMouse: boolean) => void;
|
||||
pointer: React.MutableRefObject<string>;
|
||||
}) {
|
||||
@@ -461,12 +472,12 @@ function ScoreSheet({
|
||||
const prev = v.current === p ? v.preview?.[c] : undefined;
|
||||
if (p === me && myTurn && v.rollsUsed > 0 && prev !== undefined) {
|
||||
const allowed = v.allowed.includes(c);
|
||||
const show = v.options.showPreview;
|
||||
const show = v.options.showPreview && !rolling;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`yt-cell${show && prev > 0 ? ' good' : ''}${show && prev === 0 ? ' zero' : ''}`}
|
||||
disabled={!allowed || pending}
|
||||
disabled={!allowed || pending || rolling}
|
||||
aria-label={`${catName(c, v.options.scoring)}에 ${show ? `${prev}점 ` : ''}기록하기${allowed ? '' : ' (지금은 넣을 수 없어요)'}`}
|
||||
onPointerDown={(e) => (pointer.current = e.pointerType)}
|
||||
onClick={(e) => {
|
||||
@@ -475,11 +486,11 @@ function ScoreSheet({
|
||||
onScore(c, prev, viaMouse);
|
||||
}}
|
||||
>
|
||||
{show ? prev : '기록'}
|
||||
{show ? prev : rolling ? '' : '기록'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
if (prev !== undefined && v.options.showPreview) return <span className="yt-ghost">{prev}</span>;
|
||||
if (prev !== undefined && v.options.showPreview && !rolling) return <span className="yt-ghost">{prev}</span>;
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/** 증강 윷놀이 방 설정 (docs/games/yut-augmented.md): 혼돈 모드, 고르는 라운드, 후보 수, 나오게 할 증강 목록. */
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { YutOptions } from '@bg/games/yut';
|
||||
import { Sheet } from '../../components/ui';
|
||||
import { AugIcon } from './aug-icons';
|
||||
import { AUGS, AUG_IDS, AUG_ROUNDS, KIND_KO, TIER_KO, selectionTier, type AugId, type AugRoundsKey, type AugTier } from '@bg/games/yut/augments';
|
||||
|
||||
@@ -20,10 +22,23 @@ const AUG_CSS = `
|
||||
.yut-aug-cat { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 10px; border: 1px dashed var(--border); border-radius: 12px; min-width: 0; }
|
||||
.yut-aug-cat-head { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; }
|
||||
.yut-aug-cat-head strong { margin-right: auto; }
|
||||
.yut-aug-row { display: flex; gap: 10px; align-items: flex-start; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; }
|
||||
.yut-aug-row.off { opacity: .6; }
|
||||
.yut-aug-row input { flex: none; width: 22px; height: 22px; margin: 1px 0 0; accent-color: var(--primary); }
|
||||
.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; overflow-wrap: anywhere; }
|
||||
.yut-aug-row { display: flex; gap: 10px; align-items: center; min-height: 56px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; }
|
||||
.yut-aug-row.off { background: var(--surface-2, var(--surface)); }
|
||||
.yut-aug-row.off .yut-aug-body, .yut-aug-row.off .aug-icon { opacity: .55; }
|
||||
.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; overflow-wrap: anywhere; }
|
||||
.yut-aug-switch { flex: none; position: relative; width: 50px; height: 30px; margin: 0; appearance: none; -webkit-appearance: none; border-radius: 999px;
|
||||
background: var(--border); cursor: pointer; transition: background .15s; }
|
||||
.yut-aug-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 24px; height: 24px; border-radius: 50%; background: #fff;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, .3); transition: transform .15s; }
|
||||
.yut-aug-switch:checked { background: var(--primary); }
|
||||
.yut-aug-switch:checked::after { transform: translateX(20px); }
|
||||
.yut-aug-switch:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; }
|
||||
.yut-aug-switch:disabled { cursor: default; }
|
||||
.yut-aug-open { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 48px; }
|
||||
.sheet:has(.yut-aug-sheet) { width: min(100%, 640px); }
|
||||
.yut-aug-sheet { display: flex; flex-direction: column; gap: 10px; }
|
||||
.yut-aug-sheet-head { display: flex; flex-direction: column; gap: 8px; }
|
||||
.yut-aug-sheet-foot { position: sticky; bottom: calc(-20px - env(safe-area-inset-bottom)); background: var(--surface); padding: 8px 0 4px; border-top: 1px solid var(--border); }
|
||||
.yut-aug-name { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; font-weight: 700; }
|
||||
.yut-aug-badge { border-radius: 999px; padding: 0 7px; font-size: .75rem; font-weight: 700; background: var(--primary-soft); color: var(--text); white-space: nowrap; }
|
||||
.yut-aug-badge.win { background: var(--warning-soft, var(--primary-soft)); }
|
||||
@@ -54,7 +69,10 @@ function Field({ label, hint, children }: { label: string; hint?: string; childr
|
||||
|
||||
export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange: (patch: Partial<YutOptions>) => void }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [open, setOpen] = useState<Record<string, boolean>>({});
|
||||
const [listOpen, setListOpen] = useState(false);
|
||||
// Inside the room's read-only settings view (not the host) the list can be read but not changed.
|
||||
const openBtn = useRef<HTMLButtonElement>(null);
|
||||
const [readOnly, setReadOnly] = useState(false);
|
||||
const off = new Set<AugId>(o.augOff ?? []);
|
||||
/** Keep `augOff` in AUG_IDS order so the value is stable. */
|
||||
const setOff = (next: Set<AugId>) => onChange({ augOff: AUG_IDS.filter((id) => next.has(id)) });
|
||||
@@ -97,84 +115,156 @@ export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange
|
||||
<Field label="후보 수" hint="한 번 고를 때 보여 주는 증강 수예요.">
|
||||
<Seg value={o.augOffers ?? 3} options={[[2, '2개'], [3, '3개'], [4, '4개']]} onChange={(augOffers) => onChange({ augOffers })} />
|
||||
</Field>
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
<strong>
|
||||
나오게 할 증강 <span className="yut-rules-count">켜진 증강 {onCount}/{AUG_IDS.length}</span>
|
||||
</strong>
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<strong>나오게 할 증강</strong>
|
||||
<button
|
||||
ref={openBtn}
|
||||
type="button"
|
||||
className="btn btn-secondary yut-aug-open"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={listOpen}
|
||||
onClick={() => {
|
||||
setReadOnly(!!openBtn.current?.closest('.options-view'));
|
||||
setListOpen(true);
|
||||
}}
|
||||
>
|
||||
<span>📋 증강 목록 열기 (켜고 끄기)</span>
|
||||
<span className="yut-rules-count">
|
||||
켜짐 {onCount}/{AUG_IDS.length}
|
||||
</span>
|
||||
</button>
|
||||
<span className="small muted">끈 증강은 후보에 나오지 않아요. 이 사이트에서 만든 추가 증강 {CUSTOM_IDS.length}개는 처음에 꺼져 있어요.</span>
|
||||
<input className="input" type="search" placeholder="증강 이름이나 설명으로 찾기" aria-label="증강 찾기" value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
<div className="yut-aug-tools">
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setOff(new Set())} disabled={off.size === 0}>
|
||||
전체 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(WIN_IDS, false)}>
|
||||
승리 조건 증강 끄기
|
||||
</button>
|
||||
{CUSTOM_IDS.every((id) => off.has(id)) ? (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, true)}>
|
||||
추가 증강 켜기
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, false)}>
|
||||
추가 증강 끄기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{warnings.map((w) => (
|
||||
<span key={w} className="small yut-aug-warn" role="status">
|
||||
⚠ {w}
|
||||
</span>
|
||||
))}
|
||||
{CATS.map((cat) => {
|
||||
const shown = cat.ids.filter(match);
|
||||
if (!shown.length) return null;
|
||||
const on = cat.ids.filter((id) => !off.has(id)).length;
|
||||
const showRows = !!q || !!open[cat.key];
|
||||
return (
|
||||
<section key={cat.key} className="yut-aug-cat" aria-label={cat.title}>
|
||||
<div className="yut-aug-cat-head">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-sm"
|
||||
style={{ marginRight: 'auto', fontWeight: 800 }}
|
||||
aria-expanded={showRows}
|
||||
onClick={() => setOpen((o) => ({ ...o, [cat.key]: !o[cat.key] }))}
|
||||
>
|
||||
{showRows ? '▲' : '▼'} {cat.title} <span className="small muted" style={{ marginLeft: 6 }}>켜짐 {on}/{cat.ids.length}</span>
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, true)} disabled={on === cat.ids.length}>
|
||||
모두 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, false)} disabled={on === 0}>
|
||||
모두 끄기
|
||||
</button>
|
||||
</div>
|
||||
{listOpen &&
|
||||
createPortal(
|
||||
<AugListSheet readOnly={readOnly} onClose={() => setListOpen(false)}>
|
||||
<div className="yut-aug-sheet">
|
||||
<div className="yut-aug-sheet-head">
|
||||
<h2 style={{ margin: 0 }}>
|
||||
나오게 할 증강 <span className="yut-rules-count">켜짐 {onCount}/{AUG_IDS.length}</span>
|
||||
</h2>
|
||||
{readOnly ? (
|
||||
<span className="small muted">👑 방장만 바꿀 수 있어요. 여기서는 볼 수만 있어요.</span>
|
||||
) : (
|
||||
<span className="small muted">오른쪽 스위치로 켜고 꺼요. 끈 증강은 후보에 나오지 않아요.</span>
|
||||
)}
|
||||
<input className="input" type="search" placeholder="증강 이름이나 설명으로 찾기" aria-label="증강 찾기" value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
{!readOnly && (
|
||||
<div className="yut-aug-tools">
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setOff(new Set())} disabled={off.size === 0}>
|
||||
전체 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(WIN_IDS, false)}>
|
||||
승리 조건 증강 끄기
|
||||
</button>
|
||||
{CUSTOM_IDS.every((id) => off.has(id)) ? (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, true)}>
|
||||
추가 증강 켜기
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, false)}>
|
||||
추가 증강 끄기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{warnings.map((w) => (
|
||||
<span key={w} className="small yut-aug-warn" role="status">
|
||||
⚠ {w}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{showRows && shown.map((id) => {
|
||||
const a = AUGS[id];
|
||||
const enabled = !off.has(id);
|
||||
{CATS.map((cat) => {
|
||||
const shown = cat.ids.filter(match);
|
||||
if (!shown.length) return null;
|
||||
const on = cat.ids.filter((id) => !off.has(id)).length;
|
||||
return (
|
||||
<label key={id} className={`yut-aug-row${enabled ? '' : ' off'}`} title={a.note}>
|
||||
<input type="checkbox" checked={enabled} onChange={() => toggle(id)} />
|
||||
<AugIcon id={id} size={36} />
|
||||
<span className="yut-aug-body">
|
||||
<span className="yut-aug-name">
|
||||
{a.name}
|
||||
{cat.key === 'custom' && a.tier !== 'any' && <span className="yut-aug-badge">{TIER_KO[a.tier]}</span>}
|
||||
<span className={`yut-aug-badge${a.kind === 'win' ? ' win' : ''}`}>{KIND_KO[a.kind]}</span>
|
||||
{a.once && <span className="yut-aug-badge">1회</span>}
|
||||
{a.win && a.kind !== 'win' && <span className="yut-aug-badge win">승리 조건</span>}
|
||||
</span>
|
||||
<span className="small muted">{a.text}</span>
|
||||
{a.note && <span className="small muted" style={{ fontSize: '.8rem' }}>{a.note}</span>}
|
||||
</span>
|
||||
</label>
|
||||
<section key={cat.key} className="yut-aug-cat" aria-label={cat.title}>
|
||||
<div className="yut-aug-cat-head">
|
||||
<strong>
|
||||
{cat.title} <span className="small muted">켜짐 {on}/{cat.ids.length}</span>
|
||||
</strong>
|
||||
{!readOnly && (
|
||||
<>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, true)} disabled={on === cat.ids.length}>
|
||||
모두 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, false)} disabled={on === 0}>
|
||||
모두 끄기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{shown.map((id) => {
|
||||
const a = AUGS[id];
|
||||
const enabled = !off.has(id);
|
||||
return (
|
||||
<label key={id} className={`yut-aug-row${enabled ? '' : ' off'}`}>
|
||||
<AugIcon id={id} size={40} />
|
||||
<span className="yut-aug-body">
|
||||
<span className="yut-aug-name">
|
||||
{a.name}
|
||||
{cat.key === 'custom' && a.tier !== 'any' && <span className="yut-aug-badge">{TIER_KO[a.tier]}</span>}
|
||||
<span className={`yut-aug-badge${a.kind === 'win' ? ' win' : ''}`}>{KIND_KO[a.kind]}</span>
|
||||
{a.once && <span className="yut-aug-badge">1회</span>}
|
||||
{a.win && a.kind !== 'win' && <span className="yut-aug-badge win">승리 조건</span>}
|
||||
</span>
|
||||
<span className="small muted">{a.text}</span>
|
||||
{a.note && <span className="small muted" style={{ fontSize: '.8rem' }}>{a.note}</span>}
|
||||
</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
className="yut-aug-switch"
|
||||
checked={enabled}
|
||||
disabled={readOnly}
|
||||
aria-label={`${a.name} ${enabled ? '켜짐' : '꺼짐'}`}
|
||||
onChange={() => toggle(id)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
{q && CATS.every((c) => !c.ids.some(match)) && <span className="small muted">'{query.trim()}'에 맞는 증강이 없어요.</span>}
|
||||
</div>
|
||||
{q && CATS.every((c) => !c.ids.some(match)) && <span className="small muted">'{query.trim()}'에 맞는 증강이 없어요.</span>}
|
||||
<div className="yut-aug-sheet-foot">
|
||||
<button type="button" className="btn btn-primary btn-block" onClick={() => setListOpen(false)}>
|
||||
다 골랐어요 (켜짐 {onCount}/{AUG_IDS.length})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</AugListSheet>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The augment list popup. It is opened from the room settings, which on phones are already a popup: Esc closes only
|
||||
* this one (the settings popup underneath stays open).
|
||||
*/
|
||||
function AugListSheet({ onClose, readOnly, children }: { onClose: () => void; readOnly: boolean; children: React.ReactNode }) {
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => {
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
e.stopPropagation();
|
||||
close.current();
|
||||
};
|
||||
document.addEventListener('keydown', key, true);
|
||||
return () => document.removeEventListener('keydown', key, true);
|
||||
}, []);
|
||||
return (
|
||||
<Sheet onClose={onClose} label={readOnly ? '나오게 할 증강 (보기)' : '나오게 할 증강 고르기'}>
|
||||
{children}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { NODE_NAMES, NODE_POS } from '@bg/games/yut/board';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Sheet } from '../../components/ui';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
import { AugIcon } from './aug-icons';
|
||||
|
||||
type Act = (a: unknown) => void;
|
||||
@@ -64,6 +64,19 @@ export const AUG_CSS = `
|
||||
.aug-board-wrap { position: relative; }
|
||||
.aug-aim { touch-action: none; cursor: crosshair; }
|
||||
.sheet:has(.aug-cards) { width: min(100%, 780px); }
|
||||
.aug-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.aug-list.scroll { max-height: min(52vh, 460px); overflow: auto; padding: 2px; }
|
||||
.aug-row { display: flex; gap: 10px; align-items: flex-start; width: 100%; text-align: left; border: 2px solid var(--border); border-radius: 12px; background: var(--surface);
|
||||
color: var(--text); padding: 8px 10px; font: inherit; min-height: 56px; flex: none; }
|
||||
button.aug-row { cursor: pointer; }
|
||||
.aug-row[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); }
|
||||
.aug-row.win { border-color: #f59e0b; }
|
||||
.aug-row.win[aria-pressed='true'] { border-color: var(--primary); }
|
||||
.aug-row-body { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; overflow-wrap: anywhere; }
|
||||
.aug-row-body strong { font-size: 1rem; }
|
||||
.aug-row-body p { margin: 0; font-size: .88rem; }
|
||||
.aug-row-who { font-size: .8rem; font-weight: 800; color: var(--text-sub); }
|
||||
.aug-row-check { flex: none; align-self: center; font-size: 1.2rem; font-weight: 900; color: var(--primary); width: 22px; text-align: center; }
|
||||
.aug-pop { position: fixed; z-index: 1000; width: max-content; max-width: min(300px, calc(100vw - 16px)); pointer-events: none; text-align: left;
|
||||
border: 3px solid var(--border); border-radius: 14px; background: var(--surface); color: var(--text); padding: 10px 12px;
|
||||
display: flex; flex-direction: column; gap: 6px; box-shadow: 0 10px 28px rgba(0, 0, 0, .28); animation: aug-pop .12s ease both; }
|
||||
@@ -259,6 +272,46 @@ export function AugSlots({ v, side }: { v: YutView; side: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- augment list rows (icon + full description)
|
||||
|
||||
export function AugTags({ id }: { id: AugId }) {
|
||||
const m = AUGS[id];
|
||||
return (
|
||||
<span className="aug-tags">
|
||||
<span className="aug-tag">{TIER_KO[m.tier]}</span>
|
||||
<span className="aug-tag">{KIND_KO[m.kind]}</span>
|
||||
{m.once && <span className="aug-tag">1회</span>}
|
||||
{m.win && m.kind !== 'win' && <span className="aug-tag win">승리 조건</span>}
|
||||
{m.custom && <span className="aug-tag custom">추가</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** One augment in a list: icon, name, tags, the whole description; a button when `onPick` is given. */
|
||||
export function AugRow({ id, who, picked, onPick }: { id: AugId; who?: string; picked?: boolean; onPick?: () => void }) {
|
||||
const m = AUGS[id];
|
||||
const body = (
|
||||
<>
|
||||
<AugIcon id={id} size={44} />
|
||||
<span className="aug-row-body">
|
||||
{who && <span className="aug-row-who">{who}</span>}
|
||||
<strong>{m.name}</strong>
|
||||
<AugTags id={id} />
|
||||
<p>{m.text}</p>
|
||||
{m.note && <p className="small muted">{m.note}</p>}
|
||||
</span>
|
||||
{onPick && <span className="aug-row-check" aria-hidden>{picked ? '✓' : ''}</span>}
|
||||
</>
|
||||
);
|
||||
return onPick ? (
|
||||
<button type="button" className={`aug-row${m.win ? ' win' : ''}`} aria-pressed={!!picked} onClick={onPick}>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<div className={`aug-row${m.win ? ' win' : ''}`}>{body}</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- selection
|
||||
|
||||
function AugCard({ id, picked, onPick, disabled }: { id: AugId; picked: boolean; onPick: () => void; disabled?: boolean }) {
|
||||
@@ -269,31 +322,42 @@ function AugCard({ id, picked, onPick, disabled }: { id: AugId; picked: boolean;
|
||||
<AugIcon id={id} size={56} />
|
||||
<h3>{m.name}</h3>
|
||||
</span>
|
||||
<span className="aug-tags">
|
||||
<span className="aug-tag">{TIER_KO[m.tier]}</span>
|
||||
<span className="aug-tag">{KIND_KO[m.kind]}</span>
|
||||
{m.once && <span className="aug-tag">1회</span>}
|
||||
{m.win && m.kind !== 'win' && <span className="aug-tag win">승리 조건</span>}
|
||||
{m.custom && <span className="aug-tag custom">추가</span>}
|
||||
</span>
|
||||
<AugTags id={id} />
|
||||
<p>{m.text}</p>
|
||||
{m.note && <p className="small muted">{m.note}</p>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
export function AugSelect({ v, act, pending, players, blocked = false }: { v: YutView; act: Act; pending: boolean; players: Record<string, PublicUser>; blocked?: boolean }) {
|
||||
const sel = v.aug!.select!;
|
||||
const [choice, setChoice] = useState<AugId | null>(null);
|
||||
const [target, setTarget] = useState<AugId | ''>('');
|
||||
const [open, setOpen] = useState(true);
|
||||
const mine = sel.offers.length > 0 && sel.picksLeft > 0;
|
||||
const key = sel.offers.join(',');
|
||||
// One key per set of offers to pick from. Picking (or the turn to pick coming back) starts a new one, so an
|
||||
// 이의있음! redo that happens to deal the very same offers still counts as new.
|
||||
const epoch = useRef({ mine, n: 0 });
|
||||
if (mine && !epoch.current.mine) epoch.current.n += 1;
|
||||
epoch.current.mine = mine;
|
||||
const key = `${epoch.current.n}|${sel.offers.join(',')}`;
|
||||
// The window belongs to one key; it never shows while the 이의있음! call is up (`blocked`).
|
||||
const [openKey, setOpenKey] = useState<string | null>(null);
|
||||
const open = mine && openKey === key && !blocked;
|
||||
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, so nothing pops up over an animation.
|
||||
const [autoKey, setAutoKey] = useState<string | null>(mine ? key : null);
|
||||
const ready = useMotionSettled(mine && autoKey === key && !blocked && !pending);
|
||||
useEffect(() => {
|
||||
setChoice(sel.forced);
|
||||
setTarget('');
|
||||
if (mine) setOpen(true);
|
||||
setAutoKey(mine ? key : null);
|
||||
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
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);
|
||||
@@ -310,6 +374,9 @@ export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act;
|
||||
if (!choice || (needTarget && !target)) return;
|
||||
act({ type: 'AUG_PICK', aug: choice, ...(needTarget ? { target } : {}) });
|
||||
haptic(30);
|
||||
// Whatever comes next (my second pick, an 이의있음! redo, even with the same offers) opens as a new window.
|
||||
epoch.current.n += 1;
|
||||
setOpenKey(null);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
@@ -334,17 +401,17 @@ export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act;
|
||||
))}
|
||||
</div>
|
||||
{needTarget && (
|
||||
<label className="stack" style={{ gap: 6 }}>
|
||||
<strong>{choice === 'detective' ? '무효로 만들 증강' : '다음에 받을 증강'}</strong>
|
||||
<select className="input" value={target} onChange={(e) => setTarget(e.target.value as AugId)}>
|
||||
<option value="">골라 주세요</option>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>
|
||||
{choice === 'detective' ? '무효로 만들 증강' : '다음에 받을 증강'}
|
||||
{target ? ` · ${AUGS[target].name}` : ' · 골라 주세요'}
|
||||
</strong>
|
||||
<div className="aug-list scroll" role="group" aria-label={choice === 'detective' ? '무효로 만들 증강' : '다음에 받을 증강'}>
|
||||
{targets.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{AUGS[t].name} ({TIER_KO[AUGS[t].tier]})
|
||||
</option>
|
||||
<AugRow key={t} id={t} picked={target === t} onPick={() => setTarget(t)} />
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="row" style={{ flexWrap: 'nowrap' }}>
|
||||
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setOpen(false)} aria-label="판 보기(후보 창 잠깐 닫기)">
|
||||
@@ -390,6 +457,9 @@ export function AugPrompt({ v, act, pending, players }: { v: YutView; act: Act;
|
||||
);
|
||||
}
|
||||
const send = (choice: number | number[]) => act({ type: 'AUG_ANSWER', choice });
|
||||
if (pr.kind === 'thief' || pr.kind === 'copycat' || pr.kind === 'illusion') {
|
||||
return <AugTargetPrompt key={`${pr.kind}:${pr.choices.map((c) => c.value).join(',')}`} v={v} kind={pr.kind} choices={pr.choices} send={send} pending={pending} players={players} />;
|
||||
}
|
||||
if (pr.kind === 'plan') {
|
||||
const all = pr.choices;
|
||||
return (
|
||||
@@ -441,12 +511,87 @@ export function AugPrompt({ v, act, pending, players }: { v: YutView; act: Act;
|
||||
);
|
||||
}
|
||||
|
||||
const TARGET_VERB = { thief: '빼앗기', copycat: '따라 하기', illusion: '고양이로 바꾸기' } as const;
|
||||
|
||||
/** 손버릇 / 따라쟁이 / 언제부터 착각한 거지?: the augments to choose from, each with its icon and whole description, in a popup. */
|
||||
function AugTargetPrompt({
|
||||
v,
|
||||
kind,
|
||||
choices,
|
||||
send,
|
||||
pending,
|
||||
players,
|
||||
}: {
|
||||
v: YutView;
|
||||
kind: keyof typeof TARGET_VERB;
|
||||
choices: { value: number; label: string }[];
|
||||
send: (choice: number) => void;
|
||||
pending: boolean;
|
||||
players: Record<string, PublicUser>;
|
||||
}) {
|
||||
const [pick, setPick] = useState<number | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
// Opens by itself once the board has stopped moving.
|
||||
const [autoOpen, setAutoOpen] = useState(true);
|
||||
const ready = useMotionSettled(autoOpen);
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
setOpen(true);
|
||||
setAutoOpen(false);
|
||||
}, [ready]);
|
||||
const owner = new Map<number, { side: number; id: AugId }>();
|
||||
for (const x of v.aug!.sides) for (const o of x.augs) owner.set(o.uid, { side: x.id, id: o.id });
|
||||
const picked = pick !== null ? owner.get(pick) : undefined;
|
||||
const title = PROMPT_TITLE[kind];
|
||||
return (
|
||||
<>
|
||||
<div className="card" style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
<strong>{title}</strong>
|
||||
<button type="button" className="btn btn-primary" onClick={() => setOpen(true)} aria-haspopup="dialog">
|
||||
고를 증강 보기
|
||||
</button>
|
||||
</div>
|
||||
{open && (
|
||||
<Sheet onClose={() => setOpen(false)} label={title}>
|
||||
<h2 style={{ margin: 0, textAlign: 'center' }}>{title}</h2>
|
||||
<div className="aug-list scroll" role="group" aria-label="고를 수 있는 증강">
|
||||
{choices.map((c) => {
|
||||
const o = owner.get(c.value);
|
||||
return o ? (
|
||||
<AugRow key={c.value} id={o.id} who={`${who(v, players, o.side)}의 증강`} picked={pick === c.value} onPick={() => setPick(c.value)} />
|
||||
) : (
|
||||
<button key={c.value} type="button" className="aug-row" aria-pressed={pick === c.value} onClick={() => setPick(c.value)}>
|
||||
{c.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="row" style={{ flexWrap: 'nowrap' }}>
|
||||
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setOpen(false)} aria-label="판 보기(창 잠깐 닫기)">
|
||||
👁 판 보기
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 2 }} disabled={pick === null || pending} onClick={() => pick !== null && send(pick)}>
|
||||
{picked ? `${AUGS[picked.id].name} ${TARGET_VERB[kind]}` : pick !== null ? `${TARGET_VERB[kind]}` : '증강을 고른 뒤 확인하세요'}
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- popups & toasts
|
||||
|
||||
/** Shows each new effect once: a dialog for victories / going out, a short toast for the rest. */
|
||||
export function AugFxLayer({ v, players, me }: { v: YutView; players: Record<string, PublicUser>; me: string | null }) {
|
||||
/**
|
||||
* Shows each new effect once: a dialog for victories / going out, a short toast for the rest, 이의있음! full screen.
|
||||
* New effects wait until the board has stopped moving (a piece still hopping to the square that caused them).
|
||||
* `onBlocking` is true while an 이의있음! call is waiting or on screen, so the new selection opens after it.
|
||||
*/
|
||||
export function AugFxLayer({ v, players, me, onBlocking }: { v: YutView; players: Record<string, PublicUser>; me: string | null; onBlocking?: (on: boolean) => void }) {
|
||||
const fx = v.aug?.fx ?? [];
|
||||
const seen = useRef(fx.reduce((m, f) => Math.max(m, f.no), 0));
|
||||
const [queue, setQueue] = useState<AugFx[]>([]);
|
||||
const ready = useMotionSettled(queue.length > 0);
|
||||
const [popup, setPopup] = useState<AugFx | null>(null);
|
||||
const [toast, setToast] = useState<{ key: number; text: string } | null>(null);
|
||||
const [objection, setObjection] = useState<AugFx | null>(null);
|
||||
@@ -454,7 +599,13 @@ export function AugFxLayer({ v, players, me }: { v: YutView; players: Record<str
|
||||
const fresh = fx.filter((f) => f.no > seen.current);
|
||||
if (!fresh.length) return;
|
||||
seen.current = Math.max(...fresh.map((f) => f.no));
|
||||
// 이의있음!: a big full-screen call, then the (already open) new selection shows underneath
|
||||
setQueue((q) => [...q, ...fresh]);
|
||||
}, [fx.map((f) => f.no).join(',')]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!ready) return;
|
||||
const fresh = queue;
|
||||
setQueue([]);
|
||||
// 이의있음!: a big full-screen call, then the new selection opens underneath
|
||||
const obj = fresh.find((f) => f.kind === 'objection');
|
||||
if (obj) {
|
||||
setObjection(obj);
|
||||
@@ -471,7 +622,9 @@ export function AugFxLayer({ v, players, me }: { v: YutView; players: Record<str
|
||||
}
|
||||
const small = fresh.filter((f) => f !== big && f !== obj && f.kind !== 'flick');
|
||||
if (small.length) setToast({ key: small[small.length - 1]!.no, text: small.map((f) => f.text).join(' · ') });
|
||||
}, [fx.map((f) => f.no).join(',')]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [ready]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const blocking = !!objection || queue.some((f) => f.kind === 'objection');
|
||||
useEffect(() => onBlocking?.(blocking), [blocking]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const t = setTimeout(() => setToast(null), fxMs(3200));
|
||||
|
||||
@@ -32,7 +32,7 @@ import { helpNow } from './help';
|
||||
import { houseRules, optionsSummary } from './house-rules';
|
||||
import { quickStart } from './quick';
|
||||
import { HOP_MS, moveSound, throwSound } from './sound';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
import { AugIcon } from './aug-icons';
|
||||
|
||||
type From = number | 'home';
|
||||
@@ -241,6 +241,7 @@ function Sticks({ view: v, players }: { view: YutView; players: Record<string, P
|
||||
const t = setTimeout(() => setTossing(false), fxMs(820));
|
||||
return () => clearTimeout(t);
|
||||
}, [lt?.no]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useMotionHold(tossing);
|
||||
const sticks = lt?.sticks ?? (v.aug ? Array.from({ length: v.aug.sides.find((x) => x.id === v.mySide)?.sticks ?? 4 }, (_, i) => i % 2 === 1) : [false, true, false, true]);
|
||||
const vbW = Math.max(120, 14 + sticks.length * 27);
|
||||
const label = !lt ? '' : tossing ? '…' : lt.result === 'nak' ? '낙!' : lt.results ? `${lt.results.map((r) => THROW_KO[r]).join('·')}!` : `${THROW_KO[lt.result]}!`;
|
||||
@@ -299,6 +300,8 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
const [landing, setLanding] = useState<{ no: number; at: [number, number]; delayMs: number; goal: boolean; victims: { side: number; count: number }[] } | null>(null);
|
||||
const aug = v.aug ?? null;
|
||||
const [aim, setAim] = useState<AimState | null>(null);
|
||||
// An 이의있음! call is waiting or on screen: the new selection opens after it.
|
||||
const [fxBlock, setFxBlock] = useState(false);
|
||||
const [targetUid, setTargetUid] = useState<number | null>(null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
useEffect(() => {
|
||||
@@ -306,6 +309,14 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
setTargetUid(null);
|
||||
}, [v.turnSeq]);
|
||||
const openUses = aug && targetUid !== null ? aug.uses.filter((u) => u.uid === targetUid) : [];
|
||||
// Pieces hopping square by square (timers) and their landing effects: results wait for them.
|
||||
useMotionHold(!!anim || !!landing);
|
||||
// A new throw shows up in 모아 둔 결과 (and the move buttons) only once the sticks have landed; a used result
|
||||
// stays (greyed) until the piece has finished moving.
|
||||
const pendingKey = v.pending.join(',');
|
||||
const shownPendingKey = useAfterMotionValue(pendingKey);
|
||||
const settling = shownPendingKey !== pendingKey;
|
||||
const shownPending = settling ? (shownPendingKey ? (shownPendingKey.split(',') as Throw[]) : []) : v.pending;
|
||||
const lastMoveNo = useRef(v.lastMove?.no ?? 0);
|
||||
const lastThrowNo = useRef(v.lastThrow?.no ?? 0);
|
||||
const prevCurrent = useRef(v.current);
|
||||
@@ -448,7 +459,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
<style>{CSS}</style>
|
||||
{aug && <style>{AUG_CSS}</style>}
|
||||
<div className="yut-board-box aug-board-wrap">
|
||||
{aug && <AugFxLayer v={v} players={players} me={me} />}
|
||||
{aug && <AugFxLayer v={v} players={players} me={me} onBlocking={setFxBlock} />}
|
||||
<svg ref={svgRef} className="yut-board" viewBox="0 0 100 100" role="group" aria-label={`윷판. 말은 오른쪽 아래 1번(출발)에서 출발해 시계 반대 방향으로 돌아요.${chosen ? ` 고른 말은 ${nodeName(chosen.to)}로 가요.` : ''}`} style={{ background: 'var(--wood)' }}>
|
||||
<rect x={1.5} y={1.5} width={97} height={97} rx={6} fill="none" stroke="var(--wood-line)" strokeWidth={0.6} opacity={0.6} />
|
||||
{LINES.map(([a, b]) => (
|
||||
@@ -583,7 +594,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
|
||||
<div className="yut-ctrl">
|
||||
{aug && <AugRoundBar v={v} />}
|
||||
{aug && v.phase === 'aug' && aug.select && <AugSelect v={v} act={act} pending={pending} players={players} />}
|
||||
{aug && v.phase === 'aug' && aug.select && <AugSelect v={v} act={act} pending={pending} players={players} blocked={fxBlock} />}
|
||||
{aug && v.phase === 'prompt' && aug.prompt && <AugPrompt v={v} act={act} pending={pending} players={players} />}
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap' }}>
|
||||
<Sticks view={v} players={players} />
|
||||
@@ -592,11 +603,11 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong className="small">모아 둔 결과{v.current !== me && v.phase !== 'finished' ? ` · ${nick(players, v.current)}님` : ''}</strong>
|
||||
{v.pending.length === 0 ? (
|
||||
<span className="muted small">{v.phase === 'throw' ? '윷을 던지면 여기에 모여요.' : '없음'}</span>
|
||||
{shownPending.length === 0 ? (
|
||||
<span className="muted small">{v.phase === 'throw' || settling ? '윷을 던지면 여기에 모여요.' : '없음'}</span>
|
||||
) : (
|
||||
<div className="yut-chips" role="group" aria-label="모아 둔 윷 결과">
|
||||
{v.pending.map((t, i) => {
|
||||
{shownPending.map((t, i) => {
|
||||
const usable = moves.some((m) => m.throw === t) && (!ordered || i === 0);
|
||||
return (
|
||||
<button
|
||||
@@ -605,7 +616,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
className={`yut-chip${t === 'backdo' ? ' back' : ''}`}
|
||||
aria-pressed={selIdx === i}
|
||||
aria-label={`${THROW_KO[t]}, ${t === 'backdo' ? '뒤로 1칸' : `앞으로 ${STEPS[t]}칸`}`}
|
||||
disabled={!myTurn || v.phase !== 'move' || !usable || pending}
|
||||
disabled={settling || !myTurn || v.phase !== 'move' || !usable || pending}
|
||||
onClick={() => {
|
||||
setSelIdx(i);
|
||||
pickSource(null);
|
||||
@@ -622,7 +633,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
)}
|
||||
</div>
|
||||
|
||||
{myTurn && v.phase === 'throw' && !aim && (aug?.pickThrow ? (
|
||||
{myTurn && v.phase === 'throw' && !aim && !settling && (aug?.pickThrow ? (
|
||||
<div className="row" style={{ flexWrap: 'nowrap' }} aria-label="개돼지: 도나 개를 골라서 내요">
|
||||
<button className="btn btn-primary yut-throw" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'THROW', pick: 'do' })}>
|
||||
🐷 도 내기
|
||||
@@ -641,7 +652,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
<AugUses v={v} act={act} pending={pending} aim={aim} setAim={setAim} targetUid={targetUid} setTargetUid={setTargetUid} />
|
||||
)}
|
||||
|
||||
{myTurn && v.phase === 'move' && (
|
||||
{myTurn && v.phase === 'move' && !settling && (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
{chosen && roadChoice && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Timers that stage effects (how long a banner stays, the next step of a sequence, removing a flying copy): `fxMs`.
|
||||
* Real-time things (turn timers, `[role="timer"]` bars, the drawing stream) and the chat are not scaled.
|
||||
*/
|
||||
import { useEffect, type RefObject } from 'react';
|
||||
import { useEffect, useState, type ReactNode, type RefObject } from 'react';
|
||||
import { clampGameSpeed, GAME_SPEED_DEFAULT } from '@bg/shared/lite';
|
||||
|
||||
/** At speed ×1 everything takes this much longer than the durations written in the code (2026-10-14: a bit slower). */
|
||||
@@ -77,3 +77,100 @@ export function useMotionScope(ref: RefObject<Element | null>): void {
|
||||
};
|
||||
}, [ref]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- results wait for the motion (2026-11-08)
|
||||
/*
|
||||
* "애니메이션을 다 보고 나서 결과": result windows, round results and other "what happened" screens appear only once
|
||||
* the game screen has stopped moving. Moving means: a finite CSS / Web Animation still running anywhere on the page
|
||||
* (flying copies on <body> included; endless loops, the chat, turn timers and site toasts don't count), or a
|
||||
* game holding the screen with `useMotionHold` while it plays a sequence step by step with timers.
|
||||
*/
|
||||
|
||||
/** Never moving: endless decorations aside, these are not part of the game's story. */
|
||||
const NOT_GAME = `${SKIP}, .toasts, .toast, [data-motion-free]`;
|
||||
const holds = new Set<symbol>();
|
||||
|
||||
/** Is something in the game still moving (or held)? */
|
||||
export function motionBusy(): boolean {
|
||||
if (holds.size) return true;
|
||||
if (typeof document === 'undefined' || typeof document.getAnimations !== 'function') return false;
|
||||
for (const a of document.getAnimations()) {
|
||||
if (a.playState !== 'running' && !a.pending) continue;
|
||||
const timing = a.effect?.getComputedTiming();
|
||||
if (!timing || timing.endTime === Infinity || timing.iterations === Infinity) continue;
|
||||
const t = targetOf(a);
|
||||
if (t && t.closest(NOT_GAME)) continue;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* While `on`, results wait (a sequence played with timers: a piece hopping square by square, cards dealt one by one,
|
||||
* dice still to settle). Turn it off when the last step has been shown.
|
||||
*/
|
||||
export function useMotionHold(on: boolean): void {
|
||||
useEffect(() => {
|
||||
if (!on) return;
|
||||
const id = Symbol('hold');
|
||||
holds.add(id);
|
||||
return () => {
|
||||
holds.delete(id);
|
||||
};
|
||||
}, [on]);
|
||||
}
|
||||
|
||||
/** The screen must stay still this long (real ms) before results show: bridges the gap between two staged steps. */
|
||||
export const SETTLE_MS = 220;
|
||||
/**
|
||||
* False while `when` is false; once `when` turns true, becomes true after the game screen has been still for
|
||||
* `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);
|
||||
useEffect(() => {
|
||||
if (!when) {
|
||||
setSettled(false);
|
||||
return;
|
||||
}
|
||||
if (typeof requestAnimationFrame !== 'function') {
|
||||
setSettled(true);
|
||||
return;
|
||||
}
|
||||
const start = performance.now();
|
||||
const limit = maxMs ?? Infinity;
|
||||
let stillSince: number | null = null;
|
||||
let raf = 0;
|
||||
const tick = (now: number) => {
|
||||
if (motionBusy()) stillSince = null;
|
||||
else stillSince ??= now;
|
||||
if ((stillSince !== null && now - stillSince >= SETTLE_MS) || now - start >= limit) {
|
||||
setSettled(true);
|
||||
return;
|
||||
}
|
||||
raf = requestAnimationFrame(tick);
|
||||
};
|
||||
raf = requestAnimationFrame(tick);
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [when, maxMs]);
|
||||
return when && settled;
|
||||
}
|
||||
|
||||
/**
|
||||
* `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`: see useMotionSettled.
|
||||
*/
|
||||
export function useAfterMotionValue<T>(value: T, maxMs?: number): T {
|
||||
const [shown, setShown] = useState(value);
|
||||
const settled = useMotionSettled(!Object.is(shown, value), maxMs);
|
||||
useEffect(() => {
|
||||
if (settled) setShown(value);
|
||||
}, [settled, value]);
|
||||
return settled ? value : shown;
|
||||
}
|
||||
|
||||
/** Renders `children` only after the game screen has stopped moving (see `useMotionSettled`). */
|
||||
export function AfterMotion({ when = true, children }: { when?: boolean; children: ReactNode }): ReactNode {
|
||||
return useMotionSettled(when) ? children : null;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,12 @@ export interface ChatLine {
|
||||
|
||||
export interface GameState {
|
||||
seq: number;
|
||||
/**
|
||||
* The room's game number this view belongs to. The server sends the new room before a new game's first state,
|
||||
* so this is read from the room when the state arrives. The room page remounts the board when it changes, so
|
||||
* nothing a board remembers (the last effect / move it showed) leaks into the next game.
|
||||
*/
|
||||
gameNo: number;
|
||||
view: unknown;
|
||||
active: string[];
|
||||
deadline: number | null;
|
||||
@@ -294,7 +300,7 @@ class GameSocket {
|
||||
case 'state': {
|
||||
if (st.game && m.seq < st.game.seq) break; // stale
|
||||
const patch: Partial<RoomStore> = {
|
||||
game: { seq: m.seq, view: m.view, active: m.active, deadline: m.deadline, events: m.events },
|
||||
game: { seq: m.seq, gameNo: st.room?.gameNo ?? 0, view: m.view, active: m.active, deadline: m.deadline, events: m.events },
|
||||
};
|
||||
if (m.cs !== undefined && m.cs === st.pending) {
|
||||
patch.pending = null;
|
||||
@@ -303,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');
|
||||
|
||||
@@ -21,7 +21,7 @@ import { useWide } from '../lib/media';
|
||||
import { usePlayArea } from '../lib/play-area';
|
||||
import { GameHelp } from '../components/GameHelp';
|
||||
import { PlayerName } from '../components/PlayerCard';
|
||||
import { useMotionScope } from '../lib/motion';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionScope } from '../lib/motion';
|
||||
|
||||
export default function RoomPage() {
|
||||
const { code = '' } = useParams();
|
||||
@@ -239,11 +239,17 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
|
||||
</div>
|
||||
</nav>
|
||||
{inGame && game ? (
|
||||
<GameView room={room} ui={ui} me={me} players={players} pending={pending !== null} slow={slow} />
|
||||
<GameView key={game.gameNo} room={room} ui={ui} me={me} players={players} pending={pending !== null} slow={slow} />
|
||||
) : (
|
||||
<Lobby room={room} ui={ui} me={me} />
|
||||
)}
|
||||
{room.status === 'finished' && result && game && !backInLobby && <ResultPanel room={room} me={me} players={players} onLeave={doLeave} onAgain={toLobby} />}
|
||||
{/* The result window waits until the last move's animation has played out, then once more for anything the board
|
||||
itself held back until that moment (a "1등!" banner shown after the last card landed). */}
|
||||
<AfterMotion when={room.status === 'finished' && !!result && !!game && !backInLobby}>
|
||||
<AfterMotion>
|
||||
<ResultPanel room={room} me={me} players={players} onLeave={doLeave} onAgain={toLobby} />
|
||||
</AfterMotion>
|
||||
</AfterMotion>
|
||||
<EmoteBubbles room={room} />
|
||||
{chatOpen && !roomChatClosed && !wide && (
|
||||
<Sheet onClose={() => setChatOpen(false)} label="채팅">
|
||||
@@ -670,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,
|
||||
@@ -680,6 +692,11 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
|
||||
active: game.active,
|
||||
tapConfirm,
|
||||
};
|
||||
// A status that tells what happened ("윷! 한 번 더", "○○ 1등!") waits for the board to finish showing it. Only right
|
||||
// after my own move (my turn is over and the game goes on) it changes at once, so it never keeps saying "내 차례예요".
|
||||
const statusNow = ui.statusText(game.view, me.id, players);
|
||||
const lagged = useAfterMotionValue(`${myTurn ? 1 : 0}${statusNow}`);
|
||||
const statusShown = lagged[0] === '1' && !myTurn && room.status !== 'finished' ? statusNow : lagged.slice(1);
|
||||
const status = (
|
||||
<div
|
||||
className="card turn-status"
|
||||
@@ -694,7 +711,7 @@ function GameView({ room, ui, me, players, pending, slow }: { room: RoomView; ui
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
{room.status === 'paused' ? '오류로 게임이 멈췄어요. 방장이 끝낼 수 있어요.' : ui.statusText(game.view, me.id, players)}
|
||||
{room.status === 'paused' ? '오류로 게임이 멈췄어요. 방장이 끝낼 수 있어요.' : ui.liveStatus ? statusNow : statusShown}
|
||||
{slow && <span className="small"> · 연결 확인 중…</span>}
|
||||
{!isPlayer && (
|
||||
<span className="badge" style={{ marginLeft: 8 }}>
|
||||
|
||||
@@ -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` | 반응 |
|
||||
|
||||
@@ -9,6 +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`/`<AfterMotion>`(0.22초 동안 멈춰 있으면 보여 줌, 움직임이 아무리 길어도 기다림), `useAfterMotionValue`(멈춘 뒤에 값을 바꿈)를 쓴다. 타이머로 한 단계씩 보여 주는 연출은 `useMotionHold`로 잡아 둔다. 실시간 게임(할리갈리·도블·사과 게임·그림 맞히기)은 상태 줄을 바로 바꾼다(`liveStatus`). 연출 뒤에 나오는 선택 창도 제한 시간을 다 쓸 수 있게, 각자의 화면이 움직임을 다 보여 주면 서버에 `settled`를 보내고 그 사람의 제한 시간은 그때부터 흐른다(03 §3.1, 실시간 게임 제외).
|
||||
8. **한눈에 들어오게 (2026-10-09, "한 화면에 정보가 너무 많다" 피드백).** 참고: NN/g 점진적 공개(자주 쓰는 것만 첫 단계, 나머지는 이름이 분명한 두 번째 단계, 최대 2단계), 토스 "한 화면 한 가지", Board Game Arena 화면 지침(판이 가운데, 정보는 묶어서, 드문 정보는 버튼·접기 뒤로), Hick의 법칙(고를 것이 많으면 묶음 탭으로 나눈다).
|
||||
- 같은 정보를 두 곳에 두지 않는다(방 안에서는 사이트 메뉴를 숨기고 방 막대 한 줄만, 대기실의 규칙 전문은 [📖 규칙]으로).
|
||||
- 목록 카드는 이름 + 한 줄 정보만. 설명·난이도는 들어간 다음 화면에서.
|
||||
|
||||
@@ -42,6 +42,7 @@ export interface GameDefinition<S, A, V, O> {
|
||||
deadline?(state: S): number | null;
|
||||
timeoutPlayers?(state: S): PlayerId[]; // 마감이 적용되는 사람(기본: activePlayers)
|
||||
timeoutNotBefore?(state: S): number | null; // 자리 비움이어도 이 시각 전에는 시간 초과 처리 안 함(실시간 게임)
|
||||
publicDeadline?(state: S, effective: number | null): number | null; // 화면에 보내는 마감(기본: 실제 마감). 누가 기다려지는지가 비밀일 때(아발론 암살자) 유예 시간으로 당겨진 마감을 숨김
|
||||
disconnectGraceMs?(state: S): number | null; // 연결 끊긴 마감 대상의 유예 시간(ms), null이면 방의 graceSec
|
||||
isStreamAction?(action: A): boolean; // 그림 획처럼 잦은 행동: 이벤트만 'stream' 메시지로 중계, 저장은 묶어서
|
||||
syncView?(state: S, viewer: PlayerId | null): V; // (재)접속·sync 때 보내는 전체 view(기본: view)
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
- 이의있음!: 고른 것은 다른 것처럼 비밀이고, 혼돈 모드라도 그 사람의 선택은 거기서 끝난다. 모두 고르면 공개 대신 화면 전체에 "이의있음!"이 크게 뜨고(누가 냈는지 함께), 이번에 모두가 고른 증강은 하나도 받지 않은 채 살아 있는 모두가 새 후보로 같은 선택을 처음부터 다시 한다. 다시 고를 때는 이의있음!이 후보에 없어서 한 선택에 한 번만 일어난다. 배달로 주문해 둔 증강은 다시 고를 때도 후보에 나온다. 가진 증강으로 남지 않는다.
|
||||
- 고를 것이 없으면(후보 0개) 그 사람은 건너뛴다. 시간 제한은 max(30초, 행동 시간×2), 넘기면 첫 후보(이의있음 제외, 대상은 첫 항목).
|
||||
- **질문(prompt)**: 효과에 선택이 필요한 증강(거머리·접기·돌림판·착각·계획·승부·손버릇은 주인, 나 누구게?는 다른 모두, 내려는 모두)은 공개 직후 차례로 묻는다. 시간 초과는 첫 선택지.
|
||||
- **증강을 고르는 목록**: 명탐정·배달의 대상, 손버릇·따라쟁이·착각의 대상은 아이콘과 설명 전체가 보이는 목록에서 고른다(손버릇·따라쟁이·착각은 판이 멈춘 뒤 팝업으로 열림). 방 설정의 "나오게 할 증강"은 [증강 목록 열기] 팝업에서 증강마다 스위치로 켜고 끈다.
|
||||
- **순위**: 말을 모두 내거나 특수 승리 조건을 이루면 그 즉시 비어 있는 가장 높은 순위(공동 순위는 같은 숫자, 다음은 +1)를 받고 빠진다. 탈락하면 판 위 말이 빠지고 꼴찌 쪽(늦게 탈락할수록 위). `ranking=first`면 첫 승자가 나오면 끝(동메달은 '승자'가 아님), `all`이면 한 명 남을 때까지. 끝날 때 남은 사람은 난 말 수·남은 거리로 순위를 매긴다.
|
||||
- 거머리·네크로맨서로 이어진 사람은 상대가 이기면 같은 순위를 받는다(거머리는 탈락도 같이).
|
||||
|
||||
|
||||
@@ -244,7 +244,9 @@ async function gostopStep(p: Page, state: { go: number; stop: number; picks: num
|
||||
const target = (await card.count()) ? card : any;
|
||||
if (!(await target.count())) {
|
||||
const dummy = p.getByRole('button', { name: /^빈패 내기/ });
|
||||
if (await dummy.isEnabled().catch(() => false)) {
|
||||
// The status line now changes only after the move's animation, so "내 차례예요" can still show for a moment after
|
||||
// my play while the hand is already disabled: don't wait 30 s for a 빈패 button that isn't there.
|
||||
if ((await dummy.count()) && (await dummy.isEnabled().catch(() => false))) {
|
||||
await dummy.click({ timeout: 1500 });
|
||||
state.plays++;
|
||||
return 'dummy';
|
||||
@@ -1409,7 +1411,8 @@ const PLANS: Record<string, Plan> = {
|
||||
await host.getByRole('tab', { name: '단서' }).waitFor();
|
||||
const captain = async () => {
|
||||
for (let t = 0; t < 100; t++) {
|
||||
for (const p of pages) if ((await status(p)).includes('내가 반장이에요')) return p;
|
||||
// (the status line changes only after the board stops moving, so also look for the captain's buttons)
|
||||
for (const p of pages) if ((await status(p)).includes('내가 반장이에요') && (await p.getByRole('button', { name: '고르기' }).count())) return p;
|
||||
await host.waitForTimeout(100);
|
||||
}
|
||||
throw new Error('nobody is captain');
|
||||
@@ -1606,12 +1609,17 @@ const PLANS: Record<string, Plan> = {
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('button', { name: '증강 윷놀이', exact: true }).first().click();
|
||||
await host.getByRole('tab', { name: '증강 윷놀이' }).click();
|
||||
await host.getByText(/켜진 증강/).first().waitFor();
|
||||
await host.getByText(/켜짐 71\/101/).first().waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'yut-aug-options-pc.png'), fullPage: true });
|
||||
// this site's augments start off; switch them on so the game shows them too
|
||||
await host.getByText(/켜진 증강 71\/101/).first().waitFor();
|
||||
await host.getByRole('button', { name: '추가 증강 켜기' }).click();
|
||||
await host.getByText(/켜진 증강 101\/101/).first().waitFor();
|
||||
// the augment list is a popup with a switch per augment; this site's augments start off, so switch them on
|
||||
await host.getByRole('button', { name: /증강 목록 열기/ }).click();
|
||||
const list = host.getByRole('dialog', { name: '나오게 할 증강 고르기' });
|
||||
await list.getByRole('switch').first().waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'yut-aug-list-pc.png') });
|
||||
await list.getByRole('button', { name: '추가 증강 켜기' }).click();
|
||||
await list.getByText(/켜짐 101\/101/).first().waitFor();
|
||||
await list.getByRole('button', { name: /^다 골랐어요/ }).click();
|
||||
await host.getByText(/켜짐 101\/101/).first().waitFor();
|
||||
await host.getByRole('tab', { name: '윷놀이 설정' }).click();
|
||||
await host.getByRole('button', { name: '3개', exact: true }).click();
|
||||
// 증강을 자주 고르도록 1·3·5·7·9라운드, 후보 4개
|
||||
@@ -1624,8 +1632,17 @@ const PLANS: Record<string, Plan> = {
|
||||
await guest.getByRole('button', { name: '설정 보기' }).click();
|
||||
const sheet = guest.getByRole('dialog', { name: '게임 설정' });
|
||||
await sheet.getByRole('tab', { name: '증강 윷놀이' }).click();
|
||||
await sheet.getByText(/켜진 증강/).first().waitFor();
|
||||
await sheet.getByText(/켜짐 101\/101/).first().waitFor();
|
||||
await guest.screenshot({ path: join(SHOTS, 'yut-aug-options-phone.png') });
|
||||
// not the host: the list opens read-only, and Esc closes only the list
|
||||
await sheet.getByRole('button', { name: /증강 목록 열기/ }).click();
|
||||
const view = guest.getByRole('dialog', { name: '나오게 할 증강 (보기)' });
|
||||
await view.getByRole('switch').first().waitFor();
|
||||
if (await view.getByRole('switch').first().isEnabled()) throw new Error('guest can switch augments');
|
||||
await guest.screenshot({ path: join(SHOTS, 'yut-aug-list-phone.png') });
|
||||
await guest.keyboard.press('Escape');
|
||||
await view.waitFor({ state: 'detached' });
|
||||
await sheet.waitFor();
|
||||
await guest.setViewportSize({ width: 320, height: 640 });
|
||||
await guest.emulateMedia({ colorScheme: 'dark' });
|
||||
await guest.screenshot({ path: join(SHOTS, 'yut-aug-options-phone-320-dark.png') });
|
||||
@@ -1666,12 +1683,27 @@ const PLANS: Record<string, Plan> = {
|
||||
if (await cards.count()) {
|
||||
await shotOnce(p, 'select');
|
||||
await cards.nth(stats.picks % (await cards.count())).click();
|
||||
const sel = dialog.locator('select');
|
||||
if (await sel.count()) await sel.selectOption({ index: 1 });
|
||||
// 명탐정·배달: the target is picked from a list with icons and descriptions
|
||||
const target = dialog.locator('.aug-list .aug-row');
|
||||
if (await target.count()) await target.first().click();
|
||||
await dialog.getByRole('button', { name: /고르기$/ }).click();
|
||||
stats.picks++;
|
||||
return true;
|
||||
}
|
||||
// 손버릇·따라쟁이·착각: a popup list of augments with icons and descriptions
|
||||
const rows = dialog.locator('.aug-list .aug-row');
|
||||
if (await rows.count()) {
|
||||
await shotOnce(p, 'target');
|
||||
await rows.first().click();
|
||||
await dialog.getByRole('button', { name: /(빼앗기|따라 하기|고양이로 바꾸기)$/ }).click();
|
||||
stats.prompts++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const reopen = p.getByRole('button', { name: '고를 증강 보기' });
|
||||
if ((await reopen.count()) && !(await dialog.count())) {
|
||||
await reopen.click();
|
||||
return true;
|
||||
}
|
||||
const open = p.getByRole('button', { name: '증강 후보 보기' });
|
||||
if ((await open.count()) && !(await dialog.count())) {
|
||||
@@ -1748,7 +1780,9 @@ const PLANS: Record<string, Plan> = {
|
||||
await host.locator('.yut-board').screenshot({ path: join(SHOTS, 'yut-aug-objs-board.png') });
|
||||
}
|
||||
// 증강 칩 설명은 브라우저 title 대신 팝업 카드: PC는 마우스를 올리면, 휴대폰은 칩을 누르면 뜬다(남의 증강도)
|
||||
if (!seen.has('chip-pop') && !(await host.getByRole('dialog').count()) && (await host.locator('.aug-chip').count()) >= 2) {
|
||||
// (not while a selection / question is up: its popup now opens a moment later, once the board is still)
|
||||
const popupDue = async (p: Page) => (await p.getByRole('dialog').count()) + (await p.getByRole('button', { name: /^(증강 후보 보기|고를 증강 보기)$/ }).count()) > 0;
|
||||
if (!seen.has('chip-pop') && !(await popupDue(host)) && !(await popupDue(guest)) && (await host.locator('.aug-chip').count()) >= 2) {
|
||||
seen.add('chip-pop');
|
||||
const pop = (p: Page) => p.locator('.aug-pop[role="tooltip"]');
|
||||
for (const p of [host, guest]) {
|
||||
@@ -2872,12 +2906,15 @@ const PLANS: Record<string, Plan> = {
|
||||
let jumps = 0;
|
||||
let steps = 0;
|
||||
let shot = false;
|
||||
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
|
||||
// The result window waits for the last move's animation: also stop as soon as the status says who won.
|
||||
const over = async () => (await host.getByRole('dialog', { name: '게임 결과' }).count()) || /승리/.test(await host.locator('.turn-status').innerText());
|
||||
const first = new Set<Page>();
|
||||
for (let turn = 0; turn < 40 && !(await over()); turn++) {
|
||||
const mover = turn % 2 === 0 ? north : south;
|
||||
const useKeys = mover === host && !first.has(mover);
|
||||
first.add(mover);
|
||||
await mover.waitForFunction(() => /내 차례예요|승리/.test(document.querySelector('.turn-status')?.textContent ?? ''), null, { timeout: 15_000 });
|
||||
if (await over()) break;
|
||||
if (await qdStep(mover, useKeys)) jumps++;
|
||||
steps++;
|
||||
if (steps === 6 && !shot) {
|
||||
@@ -3675,7 +3712,8 @@ const PLANS: Record<string, Plan> = {
|
||||
let power = false;
|
||||
let wild = false;
|
||||
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
|
||||
const until = Date.now() + 420_000;
|
||||
// (every roll and move plays out before the next choice shows, so a whole game takes a while)
|
||||
const until = Date.now() + 900_000;
|
||||
while (Date.now() < until && !(await over())) {
|
||||
if (!shots.has('draft') && (await host.locator('section[aria-label="선수 뽑기"]').count()) && st.picks >= 3) {
|
||||
shots.add('draft');
|
||||
|
||||
273
e2e/motion.e2e.ts
Normal file
273
e2e/motion.e2e.ts
Normal file
@@ -0,0 +1,273 @@
|
||||
/**
|
||||
* 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<void>) => {
|
||||
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<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();
|
||||
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();
|
||||
}
|
||||
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:'))!;
|
||||
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<number> {
|
||||
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<string, string[]>).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' }];
|
||||
// The redo deals me the very same offers again (the window must still wait for the call to go away).
|
||||
const send = room.broadcastState.bind(room);
|
||||
room.broadcastState = (...args: unknown[]) => {
|
||||
if (st().aug.select?.redo) st().aug.select.offers[mine] = ['shield', 'tiger', 'fog'];
|
||||
return send(...args);
|
||||
};
|
||||
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 });
|
||||
if (st().aug.select.offers[mine].join() !== 'shield,tiger,fog') throw new Error('the redo did not deal the same offers');
|
||||
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');
|
||||
// The clock on my screen is the server's (moved) deadline, not the one sent with the state.
|
||||
await Bun.sleep(500);
|
||||
const label = (await p.locator('[role="timer"]').first().getAttribute('aria-label')) ?? '';
|
||||
const shown = Number(label.match(/(\d+)초/)?.[1] ?? NaN);
|
||||
const left = (room.effectiveDeadline() - Date.now()) / 1000;
|
||||
if (!(Math.abs(shown - left) <= 1.5)) throw new Error(`screen timer says ${shown}s, server has ${left.toFixed(1)}s left`);
|
||||
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 (timer ${shown}s, server ${left.toFixed(1)}s), stopped 3 s later without a timeout`);
|
||||
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?.();
|
||||
}
|
||||
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -86,6 +86,17 @@ export interface GameDefinition<S, A, V, O> {
|
||||
* pulls forward to the end of the grace period). Real-time games use it to keep a minimum pace.
|
||||
*/
|
||||
timeoutNotBefore?(state: S): number | null;
|
||||
/**
|
||||
* Deadline shown to clients (`state.deadline`), given the room's effective one (the phase clock, pulled forward to
|
||||
* the end of the grace period of an away timed player). Default: the effective one. Games where *who* is timed is a
|
||||
* 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;
|
||||
|
||||
@@ -289,6 +289,7 @@ type Def = GameDefinition<S, A, AppleView, AppleOptions>;
|
||||
export const apple: Def = {
|
||||
id: 'apple',
|
||||
nameKo: '사과 게임',
|
||||
realtime: true,
|
||||
minPlayers: 1,
|
||||
maxPlayers: MAX_PLAYERS,
|
||||
stateVersion: 1,
|
||||
|
||||
@@ -547,6 +547,7 @@ function buildView(s: S, viewer: PlayerId | null, withCanvas: boolean): Catchmin
|
||||
export const catchmind: GameDefinition<S, A, CatchmindView, CatchmindOptions> = {
|
||||
id: 'catchmind',
|
||||
nameKo: '그림 맞히기',
|
||||
realtime: true,
|
||||
minPlayers: 2,
|
||||
maxPlayers: 10,
|
||||
stateVersion: 1,
|
||||
|
||||
@@ -652,6 +652,7 @@ const SCORE_TEXT: Record<MiniGame, (r: RankRow) => string> = {
|
||||
export const dobble: Def = {
|
||||
id: 'dobble',
|
||||
nameKo: '도블',
|
||||
realtime: true,
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
stateVersion: 1,
|
||||
|
||||
@@ -389,6 +389,7 @@ const LATE_FLIP = '늦었어요! 그 사이에 카드가 바뀌었어요.';
|
||||
export const halliGalli: GameDefinition<S, A, HalliGalliView, HalliGalliOptions> = {
|
||||
id: 'halli-galli',
|
||||
nameKo: '할리갈리',
|
||||
realtime: true,
|
||||
minPlayers: 2,
|
||||
maxPlayers: 6,
|
||||
stateVersion: 1,
|
||||
|
||||
@@ -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<typeof ClientMessage>;
|
||||
|
||||
@@ -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 }
|
||||
|
||||
Reference in New Issue
Block a user