Compare commits
14 Commits
0cbda8f551
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2aaff5762 | ||
|
|
9f9d20a641 | ||
|
|
1b9acb9fc1 | ||
|
|
35f2310f8d | ||
|
|
892f64db0e | ||
|
|
943e4be3fd | ||
|
|
122cf5ed1f | ||
|
|
fffb860282 | ||
|
|
f793391b79 | ||
|
|
bc8cb7ae8c | ||
|
|
fa53175f51 | ||
|
|
4e0eb4d52c | ||
|
|
f18909c44f | ||
|
|
72f4f06e21 |
@@ -5,13 +5,14 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (40개)
|
||||
## 게임 (46개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
@@ -19,7 +20,7 @@
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
|
||||
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
|
||||
|
||||
120
apps/server/src/rooms/minesweeper.room.test.ts
Normal file
120
apps/server/src/rooms/minesweeper.room.test.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
/** 지뢰찾기 through a real Room: a practice race against a computer, mines never reach my screen, away players (docs/games/minesweeper.md §8.5). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { MinesweeperState, MinesweeperView } from '@bg/games/minesweeper';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as MinesweeperView;
|
||||
|
||||
describe('지뢰찾기 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 안전한 칸을 하나씩 열고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 내 화면에는 지뢰 위치가 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'minesweeper') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
const s = () => room.game!.state as MinesweeperState;
|
||||
for (let i = 0; i < 4 * 900 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
if (v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing') expect(v.board.cells).not.toMatch(/[*!x]/);
|
||||
// The person opens the first closed cell next to an opened 0-region every 2 s… or gives up after 60 s.
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const k = [...v.board.cells].findIndex((ch, j) => ch === '#' && s().puzzle.field[j] !== '*');
|
||||
if (k >= 0) room.act('A', ++cs, { type: 'open', i: k });
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(['solved', 'failed']).toContain(s().status[bot]!);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'minesweeper', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { level: 'beginner', timeLimitSec: 180 } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as MinesweeperState;
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'minesweeper', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { level: 'beginner', timeLimitSec: null } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as MinesweeperState;
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
118
apps/server/src/rooms/nonogram.room.test.ts
Normal file
118
apps/server/src/rooms/nonogram.room.test.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
/** 네모네모 로직 through a real Room: a practice race against a computer, the answer never reaches my screen, away players (docs/games/nonogram.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { NonogramState, NonogramView } from '@bg/games/nonogram';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as NonogramView;
|
||||
|
||||
function twoPlayerRoom(h: ReturnType<typeof harness>, timeLimitSec: number | null) {
|
||||
const r = h.manager.create('A', 'nonogram', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { size: 5, hints: true, timeLimitSec } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { room, a, b, s: () => room.game!.state as NonogramState };
|
||||
}
|
||||
|
||||
describe('nonogram · 네모네모 로직 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 한 줄씩 칠하고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 끝내기 전 내 화면에는 답이 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'nonogram') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let row = 0;
|
||||
const s = () => room.game!.state as NonogramState;
|
||||
for (let i = 0; i < 4 * 1500 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const mine = v.seats.find((x) => x.id === 'A')!;
|
||||
if (v.board && mine.status === 'playing') {
|
||||
expect(v.board.answer).toBeNull();
|
||||
expect(JSON.stringify(v)).not.toContain(s().puzzle.solution);
|
||||
}
|
||||
// The person fills one row of the answer every 20 s.
|
||||
if (i % 80 === 0 && v.phase === 'playing' && v.board && mine.status === 'playing' && row < v.board.size) {
|
||||
const n = v.board.size;
|
||||
const cells = Array.from({ length: n }, (_, c) => row * n + c).filter((k) => s().puzzle.solution[k] === '#');
|
||||
room.act('A', ++cs, { type: 'paint', cells, value: 1 });
|
||||
row++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().status.A).toBe('solved');
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
const v = lastView(a);
|
||||
expect(v.result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
expect(v.board!.answer!.name).toBe(s().puzzle.name);
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayerRoom(h, 300);
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayerRoom(h, null);
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
115
apps/server/src/rooms/shisen.room.test.ts
Normal file
115
apps/server/src/rooms/shisen.room.test.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/** 사천성 through a real Room: a practice race against a computer to the end, away players (docs/games/shisen.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { findPair, type ShisenState, type ShisenView } from '@bg/games/shisen';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as ShisenView;
|
||||
|
||||
function twoPlayers(timeLimitSec: number | null) {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'shisen', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { size: 'small', hints: true, timeLimitSec } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { h, room, a, b, s: () => room.game!.state as ShisenState };
|
||||
}
|
||||
|
||||
describe('사천성 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 2초마다 한 쌍씩 없애다 1분 뒤 포기하고, 컴퓨터는 자기 판을 끝까지 풀어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'shisen') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let removed = 0;
|
||||
const s = () => room.game!.state as ShisenState;
|
||||
for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const p = findPair(v.board.cells, v.board.rows, v.board.cols);
|
||||
if (p) {
|
||||
room.act('A', ++cs, { type: 'pair', a: p[0], b: p[1] });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().boards.A!.removed).toBe(removed);
|
||||
expect(removed).toBeGreaterThan(20);
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id)).toEqual([bot, 'A']);
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const { h, room, b, s } = twoPlayers(300);
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const { h, room, b, s } = twoPlayers(null);
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.ranking.map((r) => r.status)).toEqual(['done', 'done']);
|
||||
});
|
||||
});
|
||||
121
apps/server/src/rooms/solitaire.room.test.ts
Normal file
121
apps/server/src/rooms/solitaire.room.test.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
/** 솔리테어 through a real Room: a practice race against a computer, hidden cards never reach my screen, away players (docs/games/solitaire.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { legalOn, type SolitaireState, type SolitaireView } from '@bg/games/solitaire';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as SolitaireView;
|
||||
|
||||
function twoPlayers(h: ReturnType<typeof harness>, options: Record<string, unknown>) {
|
||||
const r = h.manager.create('A', 'solitaire', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { room, a, b, s: () => room.game!.state as SolitaireState };
|
||||
}
|
||||
|
||||
describe('solitaire · 솔리테어 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 2초마다 한 수, 1분 뒤 포기하고 컴퓨터는 끝까지 가요. 내 화면에는 뒤집힌 카드와 더미가 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'solitaire') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let moves = 0;
|
||||
const s = () => room.game!.state as SolitaireState;
|
||||
for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
|
||||
if (playing) {
|
||||
const b = s().boards.A!;
|
||||
const json = JSON.stringify(v);
|
||||
for (const c of [...b.stock, ...b.t.flatMap((col, k) => col.slice(0, b.down[k]))]) expect(json).not.toContain(`"${c}"`);
|
||||
}
|
||||
if (i % 8 === 0 && playing) {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const legal = legalOn(v.board!).filter((m) => m.type !== 'undo' && m.type !== 'auto');
|
||||
const m = legal.find((x) => x.type === 'move' && x.to === 'f') ?? legal.find((x) => x.type === 'draw') ?? legal[0];
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
moves++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(moves).toBeGreaterThan(10);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().boards[bot]!.hist.length).toBeGreaterThan(0);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayers(h, { mode: 'spider', draw: 1, suits: 2, timeLimitSec: 600 });
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayers(h, { mode: 'freecell', draw: 1, suits: 1, timeLimitSec: null });
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
126
apps/server/src/rooms/sudoku.room.test.ts
Normal file
126
apps/server/src/rooms/sudoku.room.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/** 스도쿠 through a real Room: a practice race against a computer, the solution never reaches my screen, away players (docs/games/sudoku.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { SudokuState, SudokuView } from '@bg/games/sudoku';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as SudokuView;
|
||||
|
||||
describe('sudoku room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 맞는 숫자를 하나씩 넣고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 다 풀기 전 내 화면에는 정답이 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'sudoku') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
for (let i = 0; i < 4 * 1900 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
|
||||
if (playing) {
|
||||
expect(v.board!.solution).toBeUndefined();
|
||||
expect(JSON.stringify(v)).not.toContain(s().puzzle.solution);
|
||||
}
|
||||
// The person fills the first empty cell with the right number every 2 s.
|
||||
if (i % 8 === 0 && playing) {
|
||||
const k = v.board!.values.indexOf('0');
|
||||
if (k >= 0) room.act('A', ++cs, { type: 'set', i: k, n: Number(s().puzzle.solution[k]) });
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().status.A).toBe('solved');
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
expect(lastView(a).board!.solution).toBe(s().puzzle.solution);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'sudoku', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { difficulty: 'easy', hints: true, timeLimitSec: 600 } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'sudoku', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { difficulty: 'normal', hints: false, timeLimitSec: null } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
h.clock.advance(60_000);
|
||||
room.onTimer();
|
||||
expect(s().status.A).toBe('playing');
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
159
apps/server/src/rooms/typing.room.test.ts
Normal file
159
apps/server/src/rooms/typing.room.test.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
/** 타자 대결 through a real Room: progress streams, a practice game against a computer, away players (docs/games/typing.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { TypingState, TypingView } from '@bg/games/typing';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as TypingView;
|
||||
|
||||
function twoPlayers(options: Record<string, unknown>) {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'typing', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, ...options } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { h, room, a, b, s: () => room.game!.state as TypingState };
|
||||
}
|
||||
|
||||
describe('타자 대결 room flow', () => {
|
||||
test('연습: 먼저 다 친 사람이 방을 나가도 남은 사람은 끝까지 쳐요', () => {
|
||||
const { h, room, b, s } = twoPlayers({ mode: 'practice', category: 'word' });
|
||||
const typeAll = (who: string) => {
|
||||
const n = s().items.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
h.clock.advance(3000);
|
||||
room.act(who, 100 + i, { type: 'submit', item: i, text: s().items[i]! });
|
||||
}
|
||||
};
|
||||
typeAll('A');
|
||||
expect(s().rs.A!.finishedAt).not.toBeNull();
|
||||
room.leave('A');
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(lastView(b).upcoming[0]!.idx).toBe(0);
|
||||
typeAll('B');
|
||||
expect(b.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(s().phase).toBe('ended');
|
||||
expect(s().final!.ranking[0]).toMatchObject({ id: 'B', left: false });
|
||||
});
|
||||
|
||||
test('진행은 stream으로만 가고(보기 다시 계산 없음), 먼저 정확하게 친 사람이 점수를 얻어요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ rounds: 1 });
|
||||
const v = lastView(b);
|
||||
expect(v.phase).toBe('playing');
|
||||
const item = v.upcoming[0]!;
|
||||
// A paste the moment the text appears is refused.
|
||||
room.act('B', 1, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect((b.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string }).reason).toContain('너무 빨라요');
|
||||
const states = b.msgs.filter((m) => m.t === 'state').length;
|
||||
h.clock.advance(1500);
|
||||
room.act('A', 1, { type: 'progress', item: item.idx, text: item.text.slice(0, 2) });
|
||||
const stream = b.msgs.filter((m) => m.t === 'stream').at(-1) as Extract<ServerMessage, { t: 'stream' }>;
|
||||
expect(stream.events).toEqual([expect.objectContaining({ type: 'progress', player: 'A', item: item.idx })]);
|
||||
expect(b.msgs.filter((m) => m.t === 'state').length).toBe(states);
|
||||
h.clock.advance(3000);
|
||||
room.act('A', 2, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect(a.msgs.filter((m) => m.t === 'reject').map((m) => JSON.stringify(m))).toEqual([]);
|
||||
expect(s().totals.A!.points).toBe(1);
|
||||
expect(lastView(b).last).toMatchObject({ winner: 'A', text: item.text });
|
||||
// The next item opens after the gap, from the server clock.
|
||||
expect(lastView(b).upcoming).toEqual([]);
|
||||
h.clock.advance(1500);
|
||||
room.onTimer();
|
||||
expect(lastView(b).upcoming[0]!.idx).toBe(1);
|
||||
});
|
||||
|
||||
test('컴퓨터와 연습(타수 비교): 사람도 컴퓨터도 끝까지 치고, 거절 없이 끝나요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'typing') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, mode: 'speed', rounds: 1 } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
for (let i = 0; i < 4 * 400 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
// The person sends a line every 6 seconds, read from their own screen.
|
||||
const v = lastView(a);
|
||||
const me = v.seats.find((x) => x.id === 'A')!;
|
||||
if (i % 24 === 23 && v.phase === 'playing' && !me.finished && v.upcoming[0]) room.act('A', ++cs, { type: 'submit', item: v.upcoming[0].idx, text: v.upcoming[0].text });
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as TypingState;
|
||||
expect(s.totals.A!.keys).toBeGreaterThan(0);
|
||||
expect(s.totals[bot]!.keys).toBeGreaterThan(0);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('서바이벌 문장별(무제한은 자동 시간으로): 끊긴 사람을 기다리지 않고, 먼저 친 사람이 남아 이겨요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ mode: 'survival', elimination: 'sentence', timeLimit: null, rounds: 1 });
|
||||
// 서바이벌 always has a clock (무제한 plays as 자동).
|
||||
expect(s().curEndsAt).not.toBeNull();
|
||||
room.disconnect(b);
|
||||
const item = lastView(a).upcoming[0]!;
|
||||
h.clock.advance(4000);
|
||||
room.act('A', 1, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().rs.B!.outReason).toBe('slowest');
|
||||
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
|
||||
});
|
||||
|
||||
test('타수 비교 무제한: 끊긴 사람은 유예 뒤 친 데까지로 멈추고, 다음 타이머는 없어요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ mode: 'speed', timeLimit: null, rounds: 1 });
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
expect(d).toBeGreaterThan(h.clock.now());
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().rs.B!.finishedAt).not.toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
let cs = 0;
|
||||
while (!room.game!.finished) {
|
||||
const v = lastView(a);
|
||||
h.clock.advance(5000);
|
||||
room.act('A', ++cs, { type: 'submit', item: v.upcoming[0]!.idx, text: v.upcoming[0]!.text });
|
||||
}
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(40);
|
||||
expect(IDS).toHaveLength(46);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -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]);
|
||||
|
||||
60
apps/web/src/games/minesweeper/art.tsx
Normal file
60
apps/web/src/games/minesweeper/art.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 지뢰찾기 cell pictures (SVG, no image files). */
|
||||
|
||||
/** SVG units per cell. */
|
||||
export const S = 32;
|
||||
const NUM_COLOR = ['', '#1d4ed8', '#15803d', '#dc2626', '#1e3a8a', '#7f1d1d', '#0f766e', '#111827', '#6b7280'];
|
||||
|
||||
function Flag({ x, y, wrong }: { x: number; y: number; wrong?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M12 7 V25" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<path d="M12 7 L24 11.5 L12 16 Z" fill="#dc2626" />
|
||||
<path d="M8 25 H18" stroke="#111827" strokeWidth={2.4} strokeLinecap="round" />
|
||||
{wrong && <path d="M5 5 L27 27 M27 5 L5 27" stroke="#111827" strokeWidth={2.6} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Mine({ x, y }: { x: number; y: number }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M16 6 V26 M6 16 H26 M9 9 L23 23 M23 9 L9 23" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<circle cx={16} cy={16} r={7.5} fill="#111827" />
|
||||
<circle cx={13.5} cy={13.5} r={2} fill="#fff" opacity={0.8} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small stand-alone pictures for rules and help cards. */
|
||||
export function MiniCell({ ch, size = 30 }: { ch: string; size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 32 32" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
|
||||
<CellArt ch={ch} x={0} y={0} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CellArt({ ch, x, y, cls, i }: { ch: string; x: number; y: number; cls?: string; i?: number }) {
|
||||
const closed = ch === '#' || ch === 'F' || ch === 'x';
|
||||
return (
|
||||
<g className={cls} data-i={i} data-ch={i === undefined ? undefined : ch}>
|
||||
{closed ? (
|
||||
<>
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={4} fill="#e5e7eb" />
|
||||
<path d={`M${x + 2} ${y + S - 3} V${y + 3} Q${x + 2} ${y + 2} ${x + 3} ${y + 2} H${x + S - 3}`} stroke="#fff" strokeWidth={2} fill="none" />
|
||||
<path d={`M${x + 3} ${y + S - 2} H${x + S - 3} Q${x + S - 2} ${y + S - 2} ${x + S - 2} ${y + S - 3} V${y + 3}`} stroke="#9ca3af" strokeWidth={2} fill="none" />
|
||||
</>
|
||||
) : (
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={3} fill={ch === '!' ? '#ef4444' : '#f8fafc'} />
|
||||
)}
|
||||
{(ch === 'F' || ch === 'x') && <Flag x={x} y={y} wrong={ch === 'x'} />}
|
||||
{(ch === '*' || ch === '!') && <Mine x={x} y={y} />}
|
||||
{ch >= '1' && ch <= '8' && (
|
||||
<text x={x + S / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={900} fill={NUM_COLOR[Number(ch)]} pointerEvents="none">
|
||||
{ch}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
17
apps/web/src/games/minesweeper/help.ts
Normal file
17
apps/web/src/games/minesweeper/help.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** 지뢰찾기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'연 칸의 숫자는 그 칸을 둘러싼 8칸에 있는 지뢰 수예요. 지뢰가 없는 칸을 모두 열면 다 푼 거예요.',
|
||||
'지뢰가 확실한 칸에는 깃발을 꽂아요(PC 오른쪽 클릭, 휴대폰 길게 누르기). 깃발 수가 숫자와 같아진 숫자 칸을 누르면 주변을 한꺼번에 열어요.',
|
||||
'지뢰를 밟으면 그 판은 끝이에요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 열기, F로 깃발이에요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '지뢰를 밟았어요.');
|
||||
if (v.board && v.phase === 'playing') return `${lines}\n남은 지뢰(전체 지뢰 − 내 깃발)는 ${v.board.mines - v.board.flags}개예요.`;
|
||||
return lines;
|
||||
}
|
||||
321
apps/web/src/games/minesweeper/index.tsx
Normal file
321
apps/web/src/games/minesweeper/index.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
/** 지뢰찾기 화면 (docs/games/minesweeper.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { LEVELS, type Level, type MinesweeperOptions, type MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { CellArt, MiniCell, S } from './art';
|
||||
|
||||
const FAIL = '지뢰를 밟았어요!';
|
||||
const LONG_PRESS_MS = 420;
|
||||
|
||||
type Cell = [number, number];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ms-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation;
|
||||
border-radius: 10px; background: #9ca3af; box-shadow: var(--shadow); outline: none; cursor: pointer; }
|
||||
.ms-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ms-board[data-off='true'] { cursor: default; }
|
||||
.ms-new { animation: ms-in .28s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ms-boom { animation: ms-boom .6s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
@keyframes ms-in { from { opacity: 0; transform: scale(.6); } }
|
||||
@keyframes ms-boom { 0% { transform: scale(.4); } 40% { transform: scale(1.3); } 100% { transform: scale(1); } }
|
||||
@media (prefers-reduced-motion: reduce) { .ms-new, .ms-boom { animation: none; } }
|
||||
`;
|
||||
|
||||
const describeCh = (ch: string) =>
|
||||
ch === '#' ? '닫힌 칸' : ch === 'F' ? '깃발' : ch === '0' ? '빈 칸' : ch === '*' ? '지뢰' : ch === '!' ? '터진 지뢰' : ch === 'x' ? '잘못 꽂은 깃발' : `숫자 ${ch}`;
|
||||
|
||||
function MinesBoard({ view: v, me, players, act }: BoardProps<MinesweeperView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [flagMode, setFlagMode] = useState(false);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const press = useRef<{ i: number; x: number; y: number; timer: ReturnType<typeof setTimeout> | null; long: boolean; button: number } | null>(null);
|
||||
const prev = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
// Newly opened cells pop in; sounds for what changed.
|
||||
useEffect(() => {
|
||||
const cur = b?.cells ?? null;
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!cur || !was || was.length !== cur.length) return;
|
||||
const added = new Set<number>();
|
||||
let flagged = 0;
|
||||
for (let i = 0; i < cur.length; i++) {
|
||||
if (was[i] === '#' && cur[i]! >= '0' && cur[i]! <= '8') added.add(i);
|
||||
if (was[i] !== cur[i] && (cur[i] === 'F' || was[i] === 'F') && cur[i] !== '*') flagged++;
|
||||
}
|
||||
if (cur.includes('!') && !was.includes('!')) {
|
||||
noise(500, 0.2, 0, 'lowpass', 400, 0.7);
|
||||
haptic([30, 40, 60]);
|
||||
} else if (added.size > 8) sfx.whoosh();
|
||||
else if (added.size) tone(900, 40, 'triangle', 0.1);
|
||||
else if (flagged === 1) tone(640, 50, 'square', 0.05);
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(320));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.cells]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자를 보고 지뢰를 피해 모든 칸을 열어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const turn = phone && b.cols > b.rows;
|
||||
const dR = turn ? b.cols : b.rows;
|
||||
const dC = turn ? b.rows : b.cols;
|
||||
const toDisp = (i: number): Cell => {
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
return turn ? [c, b.rows - 1 - r] : [r, c];
|
||||
};
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (b.rows - 1 - dc) * b.cols + dr : dr * b.cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }) => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1);
|
||||
const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1);
|
||||
return toIndex(dr, dc);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${describeCh(b.cells[i]!)}`;
|
||||
};
|
||||
/** Primary action on a cell: open a closed one, open around a number, or flag (깃발 mode / right click / long press). */
|
||||
const hit = (i: number, flag: boolean) => {
|
||||
if (!playing) return;
|
||||
const ch = b.cells[i]!;
|
||||
if (flag) {
|
||||
if (ch === '#' || ch === 'F') {
|
||||
act({ type: 'flag', i });
|
||||
haptic(10);
|
||||
setAnnounce(ch === 'F' ? '깃발을 치웠어요.' : '깃발을 꽂았어요.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ch === '#') act({ type: 'open', i });
|
||||
else if (ch >= '1' && ch <= '8') {
|
||||
// A number opens the cells around it once its flags match.
|
||||
let flags = 0;
|
||||
let closed = 0;
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
for (let y = r - 1; y <= r + 1; y++)
|
||||
for (let x = c - 1; x <= c + 1; x++) {
|
||||
if (y < 0 || x < 0 || y >= b.rows || x >= b.cols || (y === r && x === c)) continue;
|
||||
const k = b.cells[y * b.cols + x];
|
||||
if (k === 'F') flags++;
|
||||
else if (k === '#') closed++;
|
||||
}
|
||||
if (closed && flags === Number(ch)) act({ type: 'chord', i });
|
||||
else if (closed) setAnnounce(`주변 깃발이 ${flags}개예요. ${ch}개를 꽂아야 한꺼번에 열 수 있어요.`);
|
||||
} else if (ch === 'F') setAnnounce('깃발을 꽂은 칸이에요. 깃발 모드나 오른쪽 클릭으로 치워요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing) return;
|
||||
const i = cellAt(e);
|
||||
setCursor(i);
|
||||
const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType<typeof setTimeout> | null, long: false, button: e.button };
|
||||
if (e.pointerType !== 'mouse')
|
||||
p.timer = setTimeout(() => {
|
||||
p.long = true;
|
||||
hit(p.i, !flagMode);
|
||||
}, LONG_PRESS_MS);
|
||||
press.current = p;
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > 10) {
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
press.current = null; // scrolling, not a tap
|
||||
}
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (!p) return;
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
if (p.long) return;
|
||||
if (cellAt(e) !== p.i) return;
|
||||
hit(p.i, p.button === 2 || flagMode);
|
||||
};
|
||||
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, Cell> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const [dr, dc] = toDisp(cursor);
|
||||
const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) hit(cursor, flagMode);
|
||||
} else if (e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') {
|
||||
e.preventDefault();
|
||||
hit(cursor, true);
|
||||
}
|
||||
};
|
||||
|
||||
const [cr, cc] = toDisp(cursor);
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${dC * 56}px, calc((var(--play-h, 100vh) - 170px) * ${dC / dR}))`, minWidth: Math.min(280, dC * 22) };
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 지뢰 ${b.mines - b.flags}개`}>
|
||||
💣 <b>{b.mines - b.flags}</b>
|
||||
</span>
|
||||
{mine && v.phase === 'playing' && (
|
||||
<button type="button" className="rc-pill" aria-pressed={flagMode} onClick={() => setFlagMode((f) => !f)} aria-label="깃발 모드">
|
||||
{flagMode ? '🚩 깃발 꽂기' : '⛏ 칸 열기'}
|
||||
</button>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ms-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${dC * S} ${dR * S}`}
|
||||
role="application"
|
||||
aria-roledescription="지뢰 판"
|
||||
aria-label={playing ? `지뢰 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 열기, F로 깃발. 지금 ${describe(cursor)}` : '지뢰 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => {
|
||||
if (press.current?.timer) clearTimeout(press.current.timer);
|
||||
press.current = null;
|
||||
}}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.cells, (ch, i) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return <CellArt key={i} i={i} ch={ch} x={dc * S} y={dr * S} cls={ch === '!' ? 'ms-boom' : fresh.has(i) ? 'ms-new' : undefined} />;
|
||||
})}
|
||||
{focused && playing && <rect x={cc * S + 1.5} y={cr * S + 1.5} width={S - 3} height={S - 3} rx={5} fill="none" stroke="#f59e0b" strokeWidth={3} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`;
|
||||
|
||||
function MinesSide(props: BoardProps<MinesweeperView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="지뢰찾기" info={levelInfo(props.view.options.level)} />;
|
||||
}
|
||||
|
||||
function statusText(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<MinesweeperOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.level}
|
||||
options={(Object.keys(LEVELS) as Level[]).map((l) => [l, LEVELS[l].name])}
|
||||
onChange={(level) => onChange({ ...o, level })}
|
||||
/>
|
||||
<span className="small muted">{levelInfo(o.level)}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[180, 300, 600, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: MinesweeperOptions): string {
|
||||
return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: MinesweeperOptions }) {
|
||||
const level = options?.level ?? 'beginner';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 <strong>모두 열면</strong> 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<MiniCell ch="1" />
|
||||
<MiniCell ch="2" />
|
||||
<MiniCell ch="3" />
|
||||
<span>연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수</span>
|
||||
</div>
|
||||
<p>
|
||||
시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 <MiniCell ch="F" size={22} /> 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이
|
||||
한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요).
|
||||
</p>
|
||||
<p>
|
||||
<strong>지뢰를 밟으면</strong> 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '}
|
||||
{limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<MinesweeperView, MinesweeperOptions> = {
|
||||
Board: MinesBoard,
|
||||
Side: MinesSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/** 지뢰찾기 30초 규칙 요약 (docs/07 §5). Small boards drawn with the game's own cells. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniCell } from './art';
|
||||
|
||||
function Grid({ rows }: { rows: string[] }) {
|
||||
return (
|
||||
<svg viewBox={`0 0 ${rows[0]!.length * 32} ${rows.length * 32}`} width={rows[0]!.length * 30} height={rows.length * 30} aria-hidden>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => (
|
||||
<svg key={`${r}-${c}`} x={c * 32} y={r * 32} width={32} height={32} viewBox="0 0 32 32">
|
||||
<MiniCell ch={ch} size={32} />
|
||||
</svg>
|
||||
)),
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <Grid rows={['1##', '1#1', '110']} />,
|
||||
alt: '닫힌 칸 사이에 숫자 1이 적힌 연 칸들이 있어요',
|
||||
title: '숫자 = 주변 지뢰 수',
|
||||
text: '연 칸의 숫자는 둘러싼 8칸에 있는 지뢰 수예요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F#', '1#1', '110']} />,
|
||||
alt: '지뢰가 확실한 칸에 빨간 깃발을 꽂은 모습이에요',
|
||||
title: '지뢰에는 깃발',
|
||||
text: '지뢰가 확실한 칸에 깃발을 꽂아요(오른쪽 클릭, 휴대폰은 길게 누르기). 지뢰를 밟으면 끝이에요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F1', '111', '110']} />,
|
||||
alt: '지뢰 칸만 남기고 모든 칸이 열렸어요',
|
||||
title: '모든 칸을 열면 승리',
|
||||
text: '지뢰 없는 칸을 모두 열면 다 푼 거예요. 여럿이면 가장 먼저 다 연 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -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>
|
||||
|
||||
53
apps/web/src/games/nonogram/art.tsx
Normal file
53
apps/web/src/games/nonogram/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 네모네모 로직 small pictures for the rules and the 30-second cards (SVG, no image files). */
|
||||
|
||||
/** Run lengths of the '#' cells; an empty line is [0]. */
|
||||
export function runsOf(line: string): number[] {
|
||||
const out = line.split(/[^#]+/).filter(Boolean).map((s) => s.length);
|
||||
return out.length ? out : [0];
|
||||
}
|
||||
|
||||
/**
|
||||
* A small puzzle: clues from `answer`, cells from `marks` ('#' filled, 'x' X, '.' empty; default = the answer).
|
||||
* `color` paints the filled cells (a solved picture).
|
||||
*/
|
||||
export function MiniNono({ answer, marks = answer, color, cell = 22 }: { answer: string[]; marks?: string[]; color?: string; cell?: number }) {
|
||||
const n = answer.length;
|
||||
const S = 20;
|
||||
const rows = answer.map(runsOf);
|
||||
const cols = Array.from({ length: n }, (_, c) => runsOf(answer.map((r) => r[c]).join('')));
|
||||
const left = Math.max(...rows.map((r) => r.length)) * 12 + 6;
|
||||
const top = Math.max(...cols.map((c) => c.length)) * 13 + 4;
|
||||
const w = left + n * S;
|
||||
const h = top + n * S;
|
||||
return (
|
||||
<svg viewBox={`0 0 ${w} ${h}`} width={(w * cell) / S} height={(h * cell) / S} aria-hidden style={{ maxWidth: '100%', height: 'auto' }}>
|
||||
{cols.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} x={left + c * S + S / 2} y={top - 4 - (clue.length - 1 - j) * 13} textAnchor="middle" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rows.map((clue, r) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`r${r}-${j}`} x={left - 6 - (clue.length - 1 - j) * 12} y={top + r * S + 14.5} textAnchor="end" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{marks.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const x = left + c * S;
|
||||
const y = top + r * S;
|
||||
return (
|
||||
<g key={`${r}-${c}`}>
|
||||
<rect x={x} y={y} width={S} height={S} fill={ch === '#' ? (color ?? 'var(--text)') : 'var(--surface)'} stroke="var(--border)" strokeWidth={1} />
|
||||
{ch === 'x' && <path d={`M${x + 6} ${y + 6} L${x + S - 6} ${y + S - 6} M${x + S - 6} ${y + 6} L${x + 6} ${y + S - 6}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
<rect x={left} y={top} width={n * S} height={n * S} fill="none" stroke="var(--text-sub)" strokeWidth={1.5} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
18
apps/web/src/games/nonogram/help.ts
Normal file
18
apps/web/src/games/nonogram/help.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** 네모네모 로직 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'줄 옆의 숫자는 그 줄에서 이어서 칠할 칸 수예요. 숫자가 여러 개면 그 순서대로, 덩어리 사이는 한 칸 이상 띄어요.',
|
||||
'모든 가로줄과 세로줄이 숫자와 맞게 칠하면 그림이 나오고 다 푼 거예요. 칠한 칸이 맞는지는 알려 주지 않아요.',
|
||||
'비어야 할 칸에는 ✕를 해 두면 헷갈리지 않아요(PC 오른쪽 클릭, 휴대폰은 [✕ 표시]로 바꿔서). 끌면 한 줄을 한 번에 칠해요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 칠하기, X로 ✕ 표시예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
if (v.board && v.phase === 'playing' && v.options.hints && v.seats.some((s) => s.id === me && s.status === 'playing'))
|
||||
return `${lines}\n막히면 [💡 힌트]로 틀렸거나 모르는 칸 하나를 바르게 고칠 수 있어요(쓴 횟수는 결과에 나와요). 지금까지 ${v.board.hints}번 썼어요.`;
|
||||
return lines;
|
||||
}
|
||||
412
apps/web/src/games/nonogram/index.tsx
Normal file
412
apps/web/src/games/nonogram/index.tsx
Normal file
@@ -0,0 +1,412 @@
|
||||
/** 네모네모 로직 화면 (docs/games/nonogram.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import type { MarkValue, NonogramOptions, NonogramSize, NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniNono, runsOf } from './art';
|
||||
|
||||
/** SVG units per cell. */
|
||||
const S = 20;
|
||||
const SIZE_NAME: Record<NonogramSize, string> = { 5: '쉬움', 10: '보통', 15: '어려움' };
|
||||
const sizeInfo = (n: NonogramSize) => `${n}×${n} ${SIZE_NAME[n]}`;
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const MARK_WORD: Record<string, string> = { '0': '빈 칸', '1': '칠한 칸', '2': '✕ 표시' };
|
||||
|
||||
const CSS = `
|
||||
.ng-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none;
|
||||
border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); outline: none; cursor: crosshair; }
|
||||
.ng-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ng-board[data-off='true'] { cursor: default; }
|
||||
.ng-clue { font-weight: 800; fill: var(--text); transition: opacity .3s; }
|
||||
.ng-clue[data-ok='true'] { opacity: .3; }
|
||||
.ng-new { animation: ng-in .22s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-color { animation: ng-color .7s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-hint { animation: ng-hint 1.2s ease-out 2 both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-title { font-weight: 900; font-size: 1.15rem; color: var(--success); margin: 0; text-align: center; }
|
||||
.ng-title.ans { color: var(--text-sub); font-size: 1rem; }
|
||||
@keyframes ng-in { from { transform: scale(.4); } }
|
||||
@keyframes ng-color { 0% { fill: var(--text); transform: scale(1); } 40% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes ng-hint { 0% { opacity: 1; stroke-width: 4; } 100% { opacity: .2; stroke-width: 2; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ng-new, .ng-color, .ng-hint { animation: none; } .ng-clue { transition: none; } }
|
||||
`;
|
||||
|
||||
interface Drag {
|
||||
start: number;
|
||||
end: number;
|
||||
axis: 'row' | 'col' | null;
|
||||
/** The mark the first cell had: the drag only changes cells that have it too. */
|
||||
from: string;
|
||||
value: MarkValue;
|
||||
}
|
||||
|
||||
function NonoBoard({ view: v, me, players, act }: BoardProps<NonogramView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [mode, setMode] = useState<1 | 2>(1);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [drag, setDrag] = useState<Drag | null>(null);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prev = useRef<{ marks: string; ok: number; hint: number | null } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const n = b?.size ?? 10;
|
||||
const rowClues = (b?.rows ?? []).map((c) => (c.length ? c : [0]));
|
||||
const colClues = (b?.cols ?? []).map((c) => (c.length ? c : [0]));
|
||||
const lineOf = (line: number) => (line < n ? Array.from({ length: n }, (_, c) => line * n + c) : Array.from({ length: n }, (_, r) => r * n + line - n));
|
||||
const okLines = b ? [...rowClues, ...colClues].map((clue, line) => runsOf(lineOf(line).map((i) => (b.marks[i] === '1' ? '#' : '.')).join('')).join() === clue.join()) : [];
|
||||
const okCount = okLines.filter(Boolean).length;
|
||||
|
||||
// Sounds and the pop of newly marked cells; say when a line comes right.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const was = prev.current;
|
||||
prev.current = { marks: b.marks, ok: okCount, hint: b.lastHint };
|
||||
if (!was || was.marks.length !== b.marks.length) return;
|
||||
const changed = new Set<number>();
|
||||
let filled = 0;
|
||||
let crossed = 0;
|
||||
for (let i = 0; i < b.marks.length; i++) {
|
||||
if (was.marks[i] === b.marks[i]) continue;
|
||||
changed.add(i);
|
||||
if (b.marks[i] === '1') filled++;
|
||||
else if (b.marks[i] === '2') crossed++;
|
||||
}
|
||||
if (b.lastHint !== was.hint && b.hints) sfx.pop();
|
||||
else if (okCount > was.ok) tone(1175, 90, 'triangle', 0.09);
|
||||
else if (filled) tone(820, 40, 'triangle', 0.1);
|
||||
else if (crossed) tone(520, 40, 'square', 0.04);
|
||||
else if (changed.size) tone(400, 40, 'sine', 0.06);
|
||||
if (okCount !== was.ok) setAnnounce(`맞는 줄 ${okCount}/${2 * n}`);
|
||||
if (changed.size) {
|
||||
setFresh(changed);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(260));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.marks, b?.lastHint]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자대로 칸을 칠해 그림을 완성해요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Layout in SVG units: row clues on the left, column clues on top, then the grid.
|
||||
const numW = (x: number) => (x >= 10 ? 0.95 : 0.62) * S;
|
||||
const L = Math.max(...rowClues.map((c) => c.reduce((a, x) => a + numW(x), 0))) + 0.4 * S;
|
||||
const T = Math.max(...colClues.map((c) => c.length)) * 0.72 * S + 0.35 * S;
|
||||
const W = L + n * S;
|
||||
const H = T + n * S;
|
||||
const answer = b.answer;
|
||||
|
||||
const cellAt = (e: { clientX: number; clientY: number }, inside: boolean): number | null => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const k = W / box.width;
|
||||
const c = Math.floor(((e.clientX - box.left) * k - L) / S);
|
||||
const r = Math.floor(((e.clientY - box.top) * k - T) / S);
|
||||
if (inside && (c < 0 || r < 0 || c >= n || r >= n)) return null;
|
||||
return clamp(r, 0, n - 1) * n + clamp(c, 0, n - 1);
|
||||
};
|
||||
const dragCells = (d: Drag): number[] => {
|
||||
const r0 = Math.floor(d.start / n);
|
||||
const c0 = d.start % n;
|
||||
const out: number[] = [];
|
||||
if (d.axis === 'row') {
|
||||
const c1 = d.end % n;
|
||||
for (let c = c0; ; c += Math.sign(c1 - c0)) {
|
||||
out.push(r0 * n + c);
|
||||
if (c === c1) break;
|
||||
}
|
||||
} else if (d.axis === 'col') {
|
||||
const r1 = Math.floor(d.end / n);
|
||||
for (let r = r0; ; r += Math.sign(r1 - r0)) {
|
||||
out.push(r * n + c0);
|
||||
if (r === r1) break;
|
||||
}
|
||||
} else out.push(d.start);
|
||||
return out.filter((i) => b.marks[i] === d.from);
|
||||
};
|
||||
const valueFor = (i: number, m: 1 | 2): MarkValue => (b.marks[i] === String(m) ? 0 : m);
|
||||
const paint = (cells: number[], value: MarkValue) => {
|
||||
if (!playing || !cells.length) return;
|
||||
act({ type: 'paint', cells, value });
|
||||
haptic(8);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 2)) return;
|
||||
const i = cellAt(e, true);
|
||||
if (i === null) return;
|
||||
e.preventDefault();
|
||||
svgRef.current!.setPointerCapture?.(e.pointerId);
|
||||
setCursor(i);
|
||||
setDrag({ start: i, end: i, axis: null, from: b.marks[i]!, value: valueFor(i, e.button === 2 ? 2 : mode) });
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!drag) return;
|
||||
const i = cellAt(e, false)!;
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
const r0 = Math.floor(drag.start / n);
|
||||
const c0 = drag.start % n;
|
||||
if (i === drag.start && !drag.axis) return;
|
||||
// The first step away from the start cell decides the row or column; then the line follows the pointer along it.
|
||||
const axis = drag.axis ?? (r === r0 ? 'row' : c === c0 ? 'col' : Math.abs(c - c0) >= Math.abs(r - r0) ? 'row' : 'col');
|
||||
const end = axis === 'row' ? r0 * n + c : r * n + c0;
|
||||
if (end !== drag.end || axis !== drag.axis) setDrag({ ...drag, axis, end });
|
||||
};
|
||||
const onUp = () => {
|
||||
if (!drag) return;
|
||||
setDrag(null);
|
||||
paint(dragCells(drag), drag.value);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
return `${r + 1}줄 ${c + 1}칸, ${MARK_WORD[b.marks[i]!]}. 가로 숫자 ${rowClues[r]!.join(' ')}, 세로 숫자 ${colClues[c]!.join(' ')}`;
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const next = clamp(Math.floor(cursor / n) + m[0], 0, n - 1) * n + clamp((cursor % n) + m[1], 0, n - 1);
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 1));
|
||||
} else if (e.key === 'x' || e.key === 'X' || e.key === 'ㅌ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 2));
|
||||
}
|
||||
};
|
||||
|
||||
const preview = new Map<number, MarkValue>();
|
||||
if (drag) for (const i of dragCells(drag)) preview.set(i, drag.value);
|
||||
const cr = Math.floor(cursor / n);
|
||||
const cc = cursor % n;
|
||||
const showCursor = focused && playing;
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${Math.round((W / S) * 40)}px, calc((var(--play-h, 100vh) - 230px) * ${(W / H).toFixed(3)}))`, minWidth: Math.min(320, (W / S) * 24) };
|
||||
const fill = (i: number) => {
|
||||
if (answer) return answer.solution[i] === '#' ? answer.color : 'var(--surface)';
|
||||
const m = preview.get(i) ?? Number(b.marks[i]);
|
||||
return m === 1 ? 'var(--text)' : 'var(--surface)';
|
||||
};
|
||||
const xMark = (i: number) => !answer && (preview.get(i) ?? Number(b.marks[i])) === 2;
|
||||
const solvedByMe = mine?.status === 'solved';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`맞는 줄 ${okCount}개, 전체 ${2 * n}줄`}>
|
||||
✔ <b>{okCount}/{2 * n}</b>
|
||||
</span>
|
||||
{mine && playing && (
|
||||
<>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 1} onClick={() => setMode(1)}>
|
||||
■ 채우기
|
||||
</button>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 2} onClick={() => setMode(2)}>
|
||||
✕ 표시
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="rc-pill" onClick={() => act({ type: 'hint' })} aria-label={`힌트 쓰기, 지금까지 ${b.hints}번`}>
|
||||
💡 힌트{b.hints ? ` ${b.hints}` : ''}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
{answer && (
|
||||
<p className={`ng-title${solvedByMe ? '' : ' ans'}`} role="status">
|
||||
{solvedByMe ? `다 풀었어요! ${answer.name}` : `정답 그림: ${answer.name}`}
|
||||
</p>
|
||||
)}
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ng-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
role="application"
|
||||
aria-roledescription="네모네모 로직 판"
|
||||
aria-label={playing ? `네모네모 로직 ${n}×${n}. 화살표로 옮기고 스페이스로 칠하기, X로 ✕ 표시. 지금 ${describe(cursor)}` : '네모네모 로직 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => setDrag(null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<rect x={0} y={0} width={L} height={H} fill="var(--surface-2)" />
|
||||
<rect x={L} y={0} width={n * S} height={T} fill="var(--surface-2)" />
|
||||
{showCursor && (
|
||||
<>
|
||||
<rect x={0} y={T + cr * S} width={L} height={S} fill="var(--primary-soft)" />
|
||||
<rect x={L + cc * S} y={0} width={S} height={T} fill="var(--primary-soft)" />
|
||||
</>
|
||||
)}
|
||||
{colClues.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} className="ng-clue" data-ok={okLines[n + c]} data-line={n + c} data-k={j} x={L + c * S + S / 2} y={T - 0.3 * S - (clue.length - 1 - j) * 0.72 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rowClues.map((clue, r) => {
|
||||
let x = L - 0.25 * S;
|
||||
return [...clue].reverse().map((num, j) => {
|
||||
const at = x - numW(num) / 2;
|
||||
x -= numW(num);
|
||||
return (
|
||||
<text key={`r${r}-${j}`} className="ng-clue" data-ok={okLines[r]} data-line={r} data-k={clue.length - 1 - j} x={at} y={T + r * S + 0.71 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{num}
|
||||
</text>
|
||||
);
|
||||
});
|
||||
})}
|
||||
{Array.from(b.marks, (ch, i) => {
|
||||
const x = L + (i % n) * S;
|
||||
const y = T + Math.floor(i / n) * S;
|
||||
const colored = !!answer && answer.solution[i] === '#';
|
||||
return (
|
||||
<g key={i} data-i={i} data-m={ch} className={!answer && fresh.has(i) ? 'ng-new' : undefined}>
|
||||
<rect
|
||||
x={x}
|
||||
y={y}
|
||||
width={S}
|
||||
height={S}
|
||||
fill={fill(i)}
|
||||
opacity={preview.has(i) ? 0.6 : 1}
|
||||
className={colored ? 'ng-color' : undefined}
|
||||
style={colored ? { animationDelay: `${fxMs(((i % n) + Math.floor(i / n)) * 18)}ms` } : undefined}
|
||||
/>
|
||||
{xMark(i) && <path d={`M${x + 5.5} ${y + 5.5} L${x + S - 5.5} ${y + S - 5.5} M${x + S - 5.5} ${y + 5.5} L${x + 5.5} ${y + S - 5.5}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" opacity={preview.has(i) ? 0.6 : 1} />}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{Array.from({ length: n + 1 }, (_, k) => {
|
||||
const thick = k % 5 === 0 || k === n;
|
||||
const style = { stroke: thick ? 'var(--text-sub)' : 'var(--border)', strokeWidth: thick ? 1.4 : 0.6 };
|
||||
return (
|
||||
<g key={`l${k}`} pointerEvents="none">
|
||||
<line x1={L + k * S} y1={thick ? 0 : T} x2={L + k * S} y2={H} {...style} />
|
||||
<line x1={thick ? 0 : L} y1={T + k * S} x2={W} y2={T + k * S} {...style} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{!answer && b.lastHint !== null && (
|
||||
<rect key={`h${b.hints}`} className="ng-hint" x={L + (b.lastHint % n) * S + 1.5} y={T + Math.floor(b.lastHint / n) * S + 1.5} width={S - 3} height={S - 3} rx={3} fill="none" stroke="#f59e0b" strokeWidth={2} pointerEvents="none" />
|
||||
)}
|
||||
{showCursor && <rect x={L + cc * S + 1} y={T + cr * S + 1} width={S - 2} height={S - 2} rx={3} fill="none" stroke="var(--focus)" strokeWidth={2.4} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 오른쪽 클릭·끌기: ✕ 표시 · 키보드: 화살표 + 스페이스 칠하기, X ✕ 표시</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 한 줄로 끌면 한 번에 · 칠한 칸을 다시 누르면 지워요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NonoSide(props: BoardProps<NonogramView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="네모네모 로직" info={`${sizeInfo(props.view.options.size)} · 힌트 ${props.view.options.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자대로 칸을 칠해 그림을 완성해요', playing: '줄마다 숫자 = 이어서 칠할 칸 수 · 모든 줄을 숫자와 맞게 칠해요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<NonogramOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>크기</strong>
|
||||
<Seg label="크기" value={o.size} options={([5, 10, 15] as NonogramSize[]).map((s) => [s, sizeInfo(s)])} onChange={(size) => onChange({ ...o, size })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg label="힌트" value={o.hints} options={[[true, '켬'], [false, '끔']]} onChange={(hints) => onChange({ ...o, hints })} />
|
||||
<span className="small muted">{o.hints ? '막히면 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 1200, 1800]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as NonogramOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: NonogramOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: NonogramOptions }) {
|
||||
const size = options?.size ?? 10;
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
줄마다 적힌 숫자대로 칸을 칠하면 <strong>그림</strong>이 나와요. 모두 <strong>똑같은 그림</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center' }}>
|
||||
<MiniNono answer={['.#.#.', '#####', '#####', '.###.', '..#..']} marks={['x#x#x', '#####', '.....', '.....', '.....']} cell={18} />
|
||||
<span>숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"은 한 칸, 한 칸 이상 띄고, 또 한 칸이에요. 숫자 순서대로 놓여요.</span>
|
||||
</div>
|
||||
<p>
|
||||
확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 두면 좋아요(✕는 답에 상관없어요). 칠한 칸이 맞는지는 알려 주지 않아요. 숫자와 맞게 칠해진 줄은 숫자가 흐려져요. 칠한 칸이 그림과
|
||||
똑같아지면 다 푼 거예요.
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 <strong>숫자와 맞는 줄</strong>이 많은 사람이 이겨요. 힌트를 켜면 막힐 때 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요(쓴 횟수는
|
||||
결과에 나와요). 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1200)}이고, 지금 크기는 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭·끌기 칠하기, 오른쪽 클릭·끌기 ✕. 휴대폰: 누르거나 끌어서 칠하고, 위의 [✕ 표시]로 바꾸면 ✕를 해요. 칠한 칸을 다시 누르면 지워요. 키보드: 화살표, 스페이스 칠하기, X로 ✕.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<NonogramView, NonogramOptions> = {
|
||||
Board: NonoBoard,
|
||||
Side: NonoSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
26
apps/web/src/games/nonogram/quick.tsx
Normal file
26
apps/web/src/games/nonogram/quick.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
/** 네모네모 로직 30초 규칙 요약 (docs/07 §5). Small puzzles drawn with ./art. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniNono } from './art';
|
||||
|
||||
const HEART = ['.#.#.', '#####', '#####', '.###.', '..#..'];
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['.....', '.....', '.....', '.....', '.....']} />,
|
||||
alt: '5×5 빈 칸 위와 왼쪽에 줄마다 숫자가 적혀 있어요',
|
||||
title: '숫자 = 칠할 칸 덩어리',
|
||||
text: '줄 옆 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"이면 한 칸, 띄고, 한 칸이에요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['x#x#x', '#####', '#####', '.....', '.....']} />,
|
||||
alt: '위 세 줄은 칠한 칸과 ✕ 표시로 채워져 있어요',
|
||||
title: '칠하기와 ✕ 표시',
|
||||
text: '확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 둬요. 끌면 한 줄을 한 번에 칠해요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} color="#ef4444" />,
|
||||
alt: '다 칠한 칸이 빨간 하트 그림이 됐어요',
|
||||
title: '다 칠하면 그림이 나와요',
|
||||
text: '모든 줄이 숫자와 맞으면 그림이 나와요. 모두 같은 그림이라 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -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"
|
||||
|
||||
289
apps/web/src/games/race/kit.tsx
Normal file
289
apps/web/src/games/race/kit.tsx
Normal file
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Shared screen parts for the race games (docs/games/race.md §4): the clock row, everyone's progress chips, the side
|
||||
* ranking, the countdown and finished notes, 포기, the time limit option and the shared status / help lines.
|
||||
* Each game draws its own board in between.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { sfx, tone } from '../../lib/feedback';
|
||||
import { AfterMotion } from '../../lib/motion';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export { STATUS_WORD, limitLabel, mySeat, nick, raceHelp, raceIsMyTurn, raceStatusText } from './text';
|
||||
import { STATUS_WORD, limitLabel, mySeat, nick } from './text';
|
||||
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const clock = (ms: number) => {
|
||||
const s = Math.ceil(Math.max(0, ms) / 1000);
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
};
|
||||
/** Stopwatch: "1:05.4". */
|
||||
const watch = (ms: number) => {
|
||||
const t = Math.floor(Math.max(0, ms) / 100);
|
||||
return `${Math.floor(t / 600)}:${String(Math.floor((t % 600) / 10)).padStart(2, '0')}.${t % 10}`;
|
||||
};
|
||||
|
||||
export function canPlay(v: V, me: string | null, now: number): boolean {
|
||||
const s = mySeat(v, me);
|
||||
return !!s && s.status === 'playing' && v.phase === 'playing' && !!v.board && (v.endsAt === null || now < v.endsAt);
|
||||
}
|
||||
|
||||
export const RACE_CSS = `
|
||||
.rc { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
|
||||
.rc-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.rc-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; font-size: 1rem; white-space: nowrap; border: 0; color: inherit; }
|
||||
.rc-pill b { font-size: 1.1rem; }
|
||||
.rc-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
button.rc-pill { cursor: pointer; min-height: 36px; }
|
||||
button.rc-pill[aria-pressed='true'] { background: var(--primary); color: #fff; }
|
||||
.rc-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
|
||||
.rc-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; }
|
||||
.rc-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rc-others li b { font-variant-numeric: tabular-nums; margin-left: 2px; }
|
||||
.rc-others li[data-me='true'] { background: var(--primary-soft); }
|
||||
.rc-others li[data-out='true'] { opacity: .55; }
|
||||
.rc-wrap { position: relative; max-width: 100%; }
|
||||
.rc-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
|
||||
border-radius: 12px; text-align: center; padding: 12px; z-index: 4; }
|
||||
.rc-over.count { background: rgba(0,0,0,.4); color: #fff; font-size: 4.5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); min-height: 180px; }
|
||||
.rc-over.count small { font-size: 1.05rem; font-weight: 800; }
|
||||
.rc-over.count b { display: block; animation: rc-count .9s ease-out both; }
|
||||
.rc-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
|
||||
.rc-over.note.win { color: var(--success); border: 3px solid var(--success); }
|
||||
.rc-acts { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
|
||||
.rc-acts .btn { min-height: 40px; }
|
||||
.rc-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
|
||||
.rc-wait { min-height: 220px; width: min(100%, 520px); border-radius: 12px; background: var(--surface-2); }
|
||||
@keyframes rc-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
|
||||
@media (prefers-reduced-motion: reduce) { .rc-over.count b { animation: none; } }
|
||||
`;
|
||||
|
||||
/** Clock values for the board: time left (time limit) or my stopwatch (무제한), the 3·2·1 countdown. */
|
||||
export function useRaceClock(v: V, me: string | null) {
|
||||
const now = useServerNow(v.endsAt === null ? 100 : 200);
|
||||
const mine = mySeat(v, me);
|
||||
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
|
||||
const elapsed = mine?.timeMs ?? (v.phase === 'playing' && (!mine || mine.status === 'playing') ? Math.max(0, now - v.countdownEndsAt) : null);
|
||||
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
// Sounds that follow the clock: 3·2·1, start, the last 10 seconds, finishing.
|
||||
const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0;
|
||||
const heard = useRef({ countdown: 0, lastSec: 0, status: mine?.status ?? null });
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) tone(660, 90, 'triangle', 0.12);
|
||||
else if (was.countdown > 0 && v.phase === 'playing') {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
}
|
||||
}
|
||||
if (lastSec && lastSec !== was.lastSec) sfx.tick();
|
||||
const st = mine?.status ?? null;
|
||||
if (st !== was.status && was.status === 'playing') {
|
||||
if (st === 'solved') sfx.fanfare();
|
||||
else if (st === 'failed') sfx.bad();
|
||||
}
|
||||
heard.current = { countdown, lastSec, status: st };
|
||||
});
|
||||
return { now, left, elapsed, countdown, mine };
|
||||
}
|
||||
|
||||
/** Top row: the clock first, then the game's own pills. */
|
||||
export function RaceTop({ v, left, elapsed, children }: { v: V; left: number | null; elapsed: number | null; children?: ReactNode }) {
|
||||
return (
|
||||
<div className="rc-top">
|
||||
{left === null ? (
|
||||
<span className="rc-pill" aria-label={elapsed === null ? '제한 시간 없음' : `걸린 시간 ${formatElapsed(elapsed)}`}>
|
||||
⏱ {elapsed === null ? '무제한' : <b style={{ fontSize: '1rem' }}>{watch(elapsed)}</b>}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`rc-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
|
||||
⏱ {clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everyone's progress (live), ranked; only with more than one player. */
|
||||
export function RaceSeats({ v, me, players }: { v: V; me: string | null; players: Record<string, PublicUser> }) {
|
||||
if (v.seats.length < 2) return null;
|
||||
return (
|
||||
<ol className="rc-others" aria-label="진행 상황">
|
||||
{rankSeats(v.seats).map((s) => (
|
||||
<li
|
||||
key={s.id}
|
||||
data-me={s.id === me}
|
||||
data-out={s.status === 'left'}
|
||||
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, ${s.status === 'solved' ? `다 풀었어요 ${formatElapsed(s.timeMs ?? 0)}` : s.progressText}${s.status !== 'playing' && s.status !== 'solved' ? `, ${STATUS_WORD[s.status]}` : ''}`}
|
||||
>
|
||||
<Avatar user={userOf(players, s.id)} size={20} />
|
||||
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<b key={s.progress} className={s.progress ? 'anim-bump' : undefined}>
|
||||
{s.status === 'solved' ? `✔ ${formatElapsed(s.timeMs ?? 0)}` : s.progressText.replace(/^[^\d]*/, '')}
|
||||
</b>
|
||||
{s.status !== 'playing' && s.status !== 'solved' && <span aria-hidden>· {STATUS_WORD[s.status]}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
/** Countdown over the (still hidden) board. */
|
||||
export function RaceCountdown({ countdown, text }: { countdown: number; text: string }) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<div className="rc-over count" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>{text}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Notes over the board once I am finished, left, or watching. */
|
||||
export function RaceNotes({ v, mine, failText }: { v: V; mine: RaceSeat | null; failText: string }) {
|
||||
const playing = v.phase === 'playing';
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
return (
|
||||
<>
|
||||
<AfterMotion when={!!mine && mine.status === 'solved' && playing}>
|
||||
<div className="rc-over note win" role="status">
|
||||
다 풀었어요! {formatElapsed(mine?.timeMs ?? 0)}
|
||||
{mine?.extra}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
<AfterMotion when={!!mine && mine.status === 'failed' && playing}>
|
||||
<div className="rc-over note" role="status">
|
||||
{failText} {mine?.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
{mine?.status === 'done' && playing && (
|
||||
<div className="rc-over note" role="status">
|
||||
포기했어요. {mine.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
)}
|
||||
{mine?.status === 'left' && v.phase !== 'ended' && <div className="rc-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="rc-over note">관전 중이에요 · 위에서 진행 상황을 볼 수 있어요</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 포기: press twice (the first press only asks). */
|
||||
export function GiveUp({ act }: { act: (a: unknown) => void }) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!ask) return;
|
||||
const t = setTimeout(() => setAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [ask]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${ask ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => {
|
||||
if (!ask) return setAsk(true);
|
||||
setAsk(false);
|
||||
act({ type: 'stop' });
|
||||
}}
|
||||
>
|
||||
{ask ? '한 번 더 누르면 포기해요' : '포기할래요'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Right panel: the live ranking, then the final one. */
|
||||
export function RaceSide({ v, me, players, title, info }: { v: V; me: string | null; players: Record<string, PublicUser>; title: string; info: string }) {
|
||||
return (
|
||||
<>
|
||||
<style>{RACE_CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>
|
||||
{title}
|
||||
{v.phase === 'ended' ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
<span className="small muted">
|
||||
{info} · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rankSeats(v.seats).map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}>
|
||||
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
|
||||
{s.rank}등
|
||||
</span>
|
||||
<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 }}>
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{STATUS_WORD[s.status] ? ` · ${STATUS_WORD[s.status]}` : ''}
|
||||
</span>
|
||||
<strong className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.status === 'solved' ? formatElapsed(s.timeMs ?? 0) : s.progressText}
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
<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.text}</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Time limit choice for the room settings. */
|
||||
export function TimeLimitOption({ value, choices, onChange }: { value: number | null; choices: number[]; onChange: (v: number | null) => void }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>제한 시간</strong>
|
||||
<Seg label="제한 시간" value={value} options={[...choices.map((c) => [c, limitLabel(c)] as [number, string]), [null, '무제한']]} onChange={onChange} />
|
||||
<span className="small muted">
|
||||
{value === null ? '시간 제한 없이 각자 다 풀거나 포기할 때까지 해요. 스톱워치로 걸린 시간을 재요.' : '시간이 끝나면 다 못 푼 사람은 푼 만큼으로 순위를 매겨요.'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Narrow screens (phones). */
|
||||
export function useNarrow(): boolean {
|
||||
const q = '(max-width: 640px)';
|
||||
const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia(q);
|
||||
const on = () => setM(mq.matches);
|
||||
mq.addEventListener('change', on);
|
||||
return () => mq.removeEventListener('change', on);
|
||||
}, []);
|
||||
return m;
|
||||
}
|
||||
55
apps/web/src/games/race/text.ts
Normal file
55
apps/web/src/games/race/text.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/** Pure text helpers for the race games (status line, [?] help); no DOM, so help tests can import them. */
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
export const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
|
||||
export const STATUS_WORD: Record<RaceSeat['status'], string> = { playing: '', solved: '다 풂', failed: '실패', done: '포기', left: '나감' };
|
||||
|
||||
export function mySeat(v: V, me: string | null): RaceSeat | null {
|
||||
return v.seats.find((s) => s.id === me) ?? null;
|
||||
}
|
||||
|
||||
/** I can make moves now. */
|
||||
export function raceIsMyTurn(v: V, me: string | null): boolean {
|
||||
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
|
||||
}
|
||||
|
||||
/** Status line; `playing` is the game's line while I am still solving. */
|
||||
export function raceStatusText(v: V, me: string | null, players: Record<string, PublicUser>, texts: { countdown: string; playing: string; failed: string }): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return texts.countdown;
|
||||
const mine = mySeat(v, me);
|
||||
if (!mine) {
|
||||
const top = rankSeats(v.seats)[0];
|
||||
return top && top.status === 'solved' ? `${nick(players, top.id)}님이 가장 먼저 다 풀었어요` : '모두 같은 판을 풀고 있어요';
|
||||
}
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
if (mine.status === 'left') return '게임에서 나갔어요';
|
||||
if (mine.status === 'solved') return `다 풀었어요! ${formatElapsed(mine.timeMs ?? 0)}${mine.extra}${wait}`;
|
||||
if (mine.status === 'failed') return `${texts.failed} ${mine.progressText}${wait}`;
|
||||
if (mine.status === 'done') return `포기했어요 · ${mine.progressText}${wait}`;
|
||||
return texts.playing;
|
||||
}
|
||||
|
||||
/** [?] lines every race game shares: phase, my state, who leads. `how` explains the game's moves. */
|
||||
export function raceHelp(v: V, me: string | null, players: Record<string, PublicUser>, how: string[], failed: string): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 걸린 시간과 푼 만큼을 볼 수 있어요.';
|
||||
const secs = v.options.timeLimitSec;
|
||||
const limitLine = secs === null ? '제한 시간은 없어요. 다 풀거나 포기할 때까지 해요.' : `제한 시간은 ${limitLabel(secs)}이에요.`;
|
||||
const winLine = v.seats.length > 1 ? '가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 푼 사람이 이겨요.' : '';
|
||||
if (v.phase === 'countdown') return [`곧 시작해요. 모두 똑같은 판을 각자 풀어요. ${limitLine}`, ...how].join('\n');
|
||||
const mine = mySeat(v, me);
|
||||
const solved = rankSeats(v.seats).filter((s) => s.status === 'solved');
|
||||
const lead = v.seats.length > 1 && solved.length ? `지금까지 ${solved.map((s) => (s.id === me ? '나' : `${nick(players, s.id)}님`)).join(', ')}이(가) 다 풀었어요.` : '';
|
||||
if (!mine) return [`모두 똑같은 판을 각자 풀고 있어요. ${winLine}`, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
const waitLine = v.seats.length > 1 ? '모두 끝나면 순위가 나와요.' : '';
|
||||
if (mine.status === 'solved') return [`다 풀었어요! 걸린 시간은 ${formatElapsed(mine.timeMs ?? 0)}이에요.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'failed') return [`${failed} ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'done') return [`포기했어요. ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
return [...how, `지금 ${mine.progressText}.`, limitLine, winLine, lead, '그만하고 싶으면 [포기할래요]를 두 번 눌러요.'].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
'cockroach-poker': () => import('./cockroach-poker'),
|
||||
'ninety-nine': () => import('./ninety-nine'),
|
||||
'connect-four': () => import('./connect-four'),
|
||||
typing: () => import('./typing'),
|
||||
minesweeper: () => import('./minesweeper'),
|
||||
shisen: () => import('./shisen'),
|
||||
solitaire: () => import('./solitaire'),
|
||||
sudoku: () => import('./sudoku'),
|
||||
nonogram: () => import('./nonogram'),
|
||||
'old-maid': () => import('./old-maid'),
|
||||
dobble: () => import('./dobble'),
|
||||
catchmind: () => import('./catchmind'),
|
||||
|
||||
@@ -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">
|
||||
|
||||
41
apps/web/src/games/shisen/art.tsx
Normal file
41
apps/web/src/games/shisen/art.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 사천성 board geometry and small pictures for the rules and help cards (tiles: ../mahjong/Tile). */
|
||||
import { Tile } from '../mahjong/Tile';
|
||||
|
||||
/** Felt behind the tiles (the same in light and dark mode). */
|
||||
export const FELT = '#2f6b4f';
|
||||
export const LINE = '#fbbf24';
|
||||
|
||||
/**
|
||||
* Where things sit on a board of `dR`×`dC` tiles `tw` px wide: tiles are 3:4, with a half-tile margin all round that
|
||||
* connecting lines may run through. Margin rows/columns (-1 and dR/dC) map to the middle of that strip.
|
||||
*/
|
||||
export function geom(tw: number, dR: number, dC: number) {
|
||||
const th = Math.round((tw * 4) / 3);
|
||||
const m = Math.round(tw / 2);
|
||||
const x = (c: number) => (c < 0 ? m / 2 : c >= dC ? m + dC * tw + m / 2 : m + (c + 0.5) * tw);
|
||||
const y = (r: number) => (r < 0 ? m / 2 : r >= dR ? m + dR * th + m / 2 : m + (r + 0.5) * th);
|
||||
return { tw, th, m, w: dC * tw + 2 * m, h: dR * th + 2 * m, x, y, left: (c: number) => m + c * tw, top: (r: number) => m + r * th };
|
||||
}
|
||||
|
||||
/** A tiny board (rows of kind codes, '' = empty) with an optional line through [row, col] points. */
|
||||
export function MiniBoard({ rows, path, tw = 26, dim = [] }: { rows: string[][]; path?: [number, number][]; tw?: number; dim?: string[] }) {
|
||||
const g = geom(tw, rows.length, rows[0]!.length);
|
||||
return (
|
||||
<div aria-hidden style={{ position: 'relative', width: g.w, height: g.h, background: FELT, borderRadius: 8, flex: 'none' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
row.map((k, c) =>
|
||||
k ? (
|
||||
<div key={`${r}-${c}`} style={{ position: 'absolute', left: g.left(c), top: g.top(r), opacity: dim.includes(k) ? 0.35 : 1 }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
) : null,
|
||||
),
|
||||
)}
|
||||
{path && (
|
||||
<svg width={g.w} height={g.h} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
|
||||
<polyline points={path.map(([r, c]) => `${g.x(c)},${g.y(r)}`).join(' ')} fill="none" stroke={LINE} strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
apps/web/src/games/shisen/help.ts
Normal file
19
apps/web/src/games/shisen/help.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/** 사천성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { ShisenView } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'같은 그림의 패 두 장을 차례로 누르면 없어져요. 두 패 사이를 빈 칸으로만 지나는 선이 두 번 이하로 꺾여야 해요(판 바깥 테두리로 돌아가도 돼요).',
|
||||
'고른 패를 다시 누르면 취소돼요. 이을 수 있는 쌍이 하나도 없으면 남은 패가 저절로 섞여요.',
|
||||
'키보드: 화살표로 옮기고 스페이스(또는 Enter)로 골라요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!v.board || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const left = v.board.cells.filter((k) => k !== null).length;
|
||||
const hint = !v.options.hints ? '이 방은 힌트를 쓰지 않아요.' : v.board.hint ? '빛나는 두 장이 힌트예요.' : '막히면 [💡 힌트]로 이을 수 있는 쌍 하나를 볼 수 있어요.';
|
||||
return `${lines}\n남은 패는 ${left}장이에요. ${hint}`;
|
||||
}
|
||||
445
apps/web/src/games/shisen/index.tsx
Normal file
445
apps/web/src/games/shisen/index.tsx
Normal file
@@ -0,0 +1,445 @@
|
||||
/** 사천성 화면 (docs/games/shisen.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { SIZES, findPath, type Point, type ShisenOptions, type ShisenView, type Size } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { MAHJONG_TILE_CREDIT, Tile, tileName } from '../mahjong/Tile';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { FELT, LINE, MiniBoard, geom } from './art';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const NOT_SAME = '같은 패가 아니에요';
|
||||
const TOO_MANY_TURNS = '두 번 넘게 꺾여야 이어져요';
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ss-fit { width: 100%; display: flex; justify-content: center; }
|
||||
.ss-board { position: relative; border-radius: 12px; background: ${FELT}; box-shadow: var(--shadow), inset 0 0 0 2px rgba(0,0,0,.18);
|
||||
touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; outline: none; cursor: pointer; }
|
||||
.ss-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ss-board[data-off='true'] { cursor: default; }
|
||||
.ss-cell { position: absolute; transition: transform .12s ease; pointer-events: none; }
|
||||
.ss-cell .mj-tile { filter: drop-shadow(0 1.5px 1px rgba(0,0,0,.4)); }
|
||||
.ss-cell::after { content: ''; position: absolute; inset: -1px; border-radius: 7px; pointer-events: none; }
|
||||
.ss-cell.sel { transform: translateY(-4px); z-index: 2; }
|
||||
.ss-cell.sel::after { box-shadow: 0 0 0 3px #f59e0b, 0 0 12px 3px rgba(245,158,11,.75); }
|
||||
.ss-cell.hint { transform: translateY(-2px); z-index: 2; }
|
||||
.ss-cell.hint::after { box-shadow: 0 0 0 4px #0ea5e9, 0 0 16px 5px rgba(14,165,233,.95); animation: ss-pulse .8s ease-in-out infinite alternate; }
|
||||
.ss-cell.cur::after { outline: 3px dashed #fff; outline-offset: 1px; }
|
||||
.ss-shake { animation: ss-shake .35s ease both; }
|
||||
.ss-gone { z-index: 3; animation: ss-gone var(--ss-ms) ease-in forwards; }
|
||||
.ss-line { position: absolute; inset: 0; pointer-events: none; z-index: 4; overflow: visible; }
|
||||
.ss-line polyline { animation: ss-fade var(--ss-ms) ease-in forwards; }
|
||||
.ss-toast { position: absolute; top: 6px; left: 50%; transform: translateX(-50%); z-index: 5; padding: 6px 14px; border-radius: 999px; background: var(--surface);
|
||||
color: var(--text); font-weight: 800; box-shadow: var(--shadow); pointer-events: none; white-space: nowrap; animation: ss-pop .25s ease-out both; }
|
||||
.ss-toast.bad { color: var(--danger); }
|
||||
.ss-probe-box { position: relative; width: 0; height: 0; overflow: hidden; flex: none; }
|
||||
.ss-probe { position: absolute; top: 0; left: 0; width: 1px; height: var(--play-h, 100vh); visibility: hidden; }
|
||||
@keyframes ss-shake { 20% { transform: translateX(-5px); } 40% { transform: translateX(5px); } 60% { transform: translateX(-3px); } 80% { transform: translateX(2px); } }
|
||||
@keyframes ss-gone { to { opacity: 0; transform: scale(.7); } }
|
||||
@keyframes ss-fade { 0%, 55% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@keyframes ss-pop { from { opacity: 0; transform: translate(-50%, -6px); } }
|
||||
@keyframes ss-pulse { from { opacity: .6; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ss-shake, .ss-toast, .ss-cell.hint::after, .ss-line polyline { animation: none; }
|
||||
.ss-cell { transition: none; }
|
||||
.ss-gone { animation: none; opacity: 0; }
|
||||
}
|
||||
`;
|
||||
|
||||
const sizeInfo = (s: Size) => `${SIZES[s].name} ${SIZES[s].cols}×${SIZES[s].rows} · ${SIZES[s].rows * SIZES[s].cols}패`;
|
||||
|
||||
interface Flash {
|
||||
key: number;
|
||||
pts: Point[];
|
||||
a: number;
|
||||
b: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
function ShisenBoard({ view: v, me, players, act }: BoardProps<ShisenView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
// The keyboard cursor shows only while playing by keyboard (not after a click or tap).
|
||||
const [keyCursor, setKeyCursor] = useState(false);
|
||||
const [flash, setFlash] = useState<Flash | null>(null);
|
||||
const [shake, setShake] = useState<{ key: number; ids: number[] } | null>(null);
|
||||
const [toast, setToast] = useState<{ key: number; text: string; bad: boolean } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [tw, setTw] = useState(40);
|
||||
const fitRef = useRef<HTMLDivElement>(null);
|
||||
const probeRef = useRef<HTMLDivElement>(null);
|
||||
const boardRef = useRef<HTMLDivElement>(null);
|
||||
const press = useRef<number | null>(null);
|
||||
const seenShuffles = useRef<number | null>(null);
|
||||
const seenHint = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const rows = b?.rows ?? SIZES[v.options.size].rows;
|
||||
const cols = b?.cols ?? SIZES[v.options.size].cols;
|
||||
// Phones: a wide board is turned so it is taller than wide.
|
||||
const turn = phone && cols > rows;
|
||||
const dR = turn ? cols : rows;
|
||||
const dC = turn ? rows : cols;
|
||||
|
||||
// Tile width: fit the column width and the visible height. PC: the play area (--play-h, measured by a probe) minus
|
||||
// the rows above and below the board. Phone: the first screen from the board's top down, minus the buttons below.
|
||||
useLayoutEffect(() => {
|
||||
const fit = fitRef.current;
|
||||
const probe = probeRef.current;
|
||||
if (!fit || !probe) return;
|
||||
const update = () => {
|
||||
const availH = phone ? window.innerHeight - (fit.getBoundingClientRect().top + window.scrollY) - 96 : probe.offsetHeight - 175;
|
||||
const w = Math.floor(Math.min(fit.clientWidth / (dC + 1), availH / ((dR * 4) / 3 + 1), 64));
|
||||
setTw(Math.max(phone ? 34 : 28, w)); // phones: at least a finger-sized tile, scrolling if needed
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(fit);
|
||||
ro.observe(probe);
|
||||
ro.observe(document.body); // rows above the board change height (status text)
|
||||
window.addEventListener('resize', update);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, [dC, dR, phone, !!b]);
|
||||
|
||||
// Auto-reshuffle: say so for a moment.
|
||||
useEffect(() => {
|
||||
const n = b?.shuffles ?? null;
|
||||
const was = seenShuffles.current;
|
||||
seenShuffles.current = n;
|
||||
if (n === null || was === null || n <= was) return;
|
||||
setSel(null);
|
||||
setToast({ key: Date.now(), text: '섞었어요!', bad: false });
|
||||
sfx.shuffle();
|
||||
setAnnounce('이을 수 있는 쌍이 없어서 남은 패를 섞었어요.');
|
||||
}, [b?.shuffles]);
|
||||
|
||||
// A new hint: announce the pair.
|
||||
useEffect(() => {
|
||||
const h = b?.hint ? `${b.hint[0]}-${b.hint[1]}` : null;
|
||||
if (h && h !== seenHint.current && b?.hint) {
|
||||
sfx.pop();
|
||||
setAnnounce(`힌트: 빛나는 ${tileName(b.cells[b.hint[0]]!)} 두 장을 이을 수 있어요.`);
|
||||
}
|
||||
seenHint.current = h;
|
||||
}, [b?.hint?.[0], b?.hint?.[1]]);
|
||||
|
||||
// The selected tile went away (removed, reshuffled): drop the selection.
|
||||
useEffect(() => {
|
||||
if (sel !== null && b && b.cells[sel] == null) setSel(null);
|
||||
}, [b?.cells, sel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), fxMs(350));
|
||||
return () => clearTimeout(t);
|
||||
}, [flash?.key]);
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(null), fxMs(400));
|
||||
return () => clearTimeout(t);
|
||||
}, [shake?.key]);
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const t = setTimeout(() => setToast(null), fxMs(1200));
|
||||
return () => clearTimeout(t);
|
||||
}, [toast?.key]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="같은 패 두 장을 두 번 이하로 꺾인 선으로 이어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const g = geom(tw, dR, dC);
|
||||
const toDisp = (r: number, c: number): Point => (turn ? [c, rows - 1 - r] : [r, c]);
|
||||
const dispOf = (i: number) => toDisp(Math.floor(i / cols), i % cols);
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (rows - 1 - dc) * cols + dr : dr * cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }): number | null => {
|
||||
const box = boardRef.current!.getBoundingClientRect();
|
||||
const dc = Math.floor((e.clientX - box.left - g.m) / g.tw);
|
||||
const dr = Math.floor((e.clientY - box.top - g.m) / g.th);
|
||||
return dr < 0 || dc < 0 || dr >= dR || dc >= dC ? null : toIndex(dr, dc);
|
||||
};
|
||||
const tilesLeft = b.cells.filter((k) => k !== null).length;
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
const k = b.cells[i];
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${k ? tileName(k) : '빈 칸'}${i === sel ? '(고름)' : ''}`;
|
||||
};
|
||||
|
||||
const tap = (i: number) => {
|
||||
if (!playing) return;
|
||||
setCursor(i);
|
||||
const k = b.cells[i];
|
||||
if (k == null) return;
|
||||
if (sel === null || b.cells[sel] == null) {
|
||||
setSel(i);
|
||||
sfx.select();
|
||||
setAnnounce(`골랐어요: ${describe(i)}. 같은 패를 하나 더 골라요.`);
|
||||
return;
|
||||
}
|
||||
if (sel === i) {
|
||||
setSel(null);
|
||||
sfx.click();
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
return;
|
||||
}
|
||||
const pts = b.cells[sel] === k ? findPath(b.cells, b.rows, b.cols, sel, i) : null;
|
||||
if (!pts) {
|
||||
// Not a pair: shake both, say why, and start again from the tile just picked.
|
||||
const why = b.cells[sel] === k ? TOO_MANY_TURNS : NOT_SAME;
|
||||
setShake({ key: Date.now(), ids: [sel, i] });
|
||||
setToast({ key: Date.now(), text: why, bad: true });
|
||||
setSel(i);
|
||||
tone(220, 120, 'square', 0.05);
|
||||
haptic(30);
|
||||
setAnnounce(`${why}. 새로 고른 패: ${describe(i)}.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'pair', a: sel, b: i });
|
||||
setFlash({ key: Date.now(), pts, a: sel, b: i, kind: k });
|
||||
setSel(null);
|
||||
tone(880, 60, 'triangle', 0.12);
|
||||
tone(1320, 110, 'triangle', 0.1, 60);
|
||||
haptic(12);
|
||||
setAnnounce(`${tileName(k)} 한 쌍을 없앴어요. 남은 패 ${tilesLeft - 2}장.`);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0)) return;
|
||||
setKeyCursor(false);
|
||||
press.current = cellAt(e);
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (p !== null && cellAt(e) === p) tap(p);
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, Point> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
const [dr, dc] = dispOf(cursor);
|
||||
const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
} else if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
if (!e.repeat) tap(cursor);
|
||||
} else if (e.key === 'Escape' && sel !== null) {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
}
|
||||
};
|
||||
|
||||
const hint: number[] = b.hint ?? [];
|
||||
const msVar = { '--ss-ms': `${fxMs(350)}ms` } as CSSProperties;
|
||||
const showHint = !!mine && v.phase === 'playing' && v.options.hints;
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 패 ${tilesLeft}장`}>
|
||||
🀄 <b>{tilesLeft}</b>
|
||||
</span>
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
<div className="rc-wrap" style={{ width: g.w }}>
|
||||
<div
|
||||
ref={boardRef}
|
||||
className="ss-board"
|
||||
data-off={!playing}
|
||||
data-rows={rows}
|
||||
data-cols={cols}
|
||||
style={{ width: g.w, height: g.h, ...msVar }}
|
||||
role="application"
|
||||
aria-roledescription="사천성 판"
|
||||
aria-label={playing ? `사천성 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 패 고르기. 지금 ${describe(cursor)}` : '사천성 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => (press.current = null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={(e) => setKeyCursor(e.currentTarget.matches(':focus-visible'))}
|
||||
onBlur={() => setKeyCursor(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{b.cells.map((k, i) => {
|
||||
if (k == null || (flash && (i === flash.a || i === flash.b))) return null;
|
||||
const [dr, dc] = dispOf(i);
|
||||
const cls = ['ss-cell', i === sel && 'sel', hint.includes(i) && 'hint', keyCursor && playing && i === cursor && 'cur', shake?.ids.includes(i) && 'ss-shake'].filter(Boolean).join(' ');
|
||||
return (
|
||||
<div key={i} className={cls} data-i={i} data-k={k} style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{keyCursor && playing && b.cells[cursor] == null && (
|
||||
<div className="ss-cell cur" style={{ left: g.left(dispOf(cursor)[1]), top: g.top(dispOf(cursor)[0]), width: g.tw, height: g.th }} />
|
||||
)}
|
||||
{flash &&
|
||||
[flash.a, flash.b].map((i) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
return (
|
||||
<div key={`g${flash.key}-${i}`} className="ss-cell ss-gone" style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={flash.kind} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{flash && (
|
||||
<svg key={flash.key} className="ss-line" width={g.w} height={g.h} aria-hidden>
|
||||
<polyline
|
||||
points={flash.pts.map(([r, c]) => toDisp(r, c)).map(([dr, dc]) => `${g.x(dc)},${g.y(dr)}`).join(' ')}
|
||||
fill="none"
|
||||
stroke={LINE}
|
||||
strokeWidth={Math.max(3, tw / 10)}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
{toast && (
|
||||
<div key={toast.key} className={`ss-toast${toast.bad ? ' bad' : ''}`} aria-hidden>
|
||||
{toast.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
{showHint && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!!b.hint} onClick={() => act({ type: 'hint' })}>
|
||||
💡 힌트{b.hints ? ` (${b.hints}번 씀)` : ''}
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">같은 패 두 장을 차례로 클릭 · 고른 패를 다시 누르면 취소 · 키보드: 화살표 + 스페이스, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">같은 패 두 장을 차례로 눌러요 · 고른 패를 다시 누르면 취소</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ShisenSide(props: BoardProps<ShisenView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="사천성" info={`${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 같은 패 두 장을 이어서 없애요', playing: '같은 패 두 장을 두 번 이하로 꺾인 선으로 이으면 없어져요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<ShisenOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>판 크기</strong>
|
||||
<Seg label="판 크기" value={o.size} options={(Object.keys(SIZES) as Size[]).map((s) => [s, SIZES[s].name])} onChange={(size) => onChange({ ...o, size })} />
|
||||
<span className="small muted">{sizeInfo(o.size)}</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '쓰기'],
|
||||
[false, '안 쓰기'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]를 누르면 이을 수 있는 쌍 하나를 보여 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 900, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as ShisenOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: ShisenOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: ShisenOptions }) {
|
||||
const size = options?.size ?? 'normal';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
마작패가 깔린 판에서 <strong>같은 그림의 패 두 장</strong>을 골라 없애요. 패를 모두 없애면 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
<span>두 패를 잇는 선이 빈 칸으로만 지나고 두 번까지만 꺾이면 돼요. 판 바깥 테두리로 돌아가도 돼요.</span>
|
||||
</div>
|
||||
<p>
|
||||
이을 수 있는 쌍이 하나도 없으면 남은 패가 같은 자리에서 저절로 섞여요(언제나 다 풀 수 있게). 판은 처음부터 끝까지 풀 수 있게 만들어져요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못
|
||||
풀면 없앤 쌍이 많은 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 900)}이고, 지금 판은 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 패를 차례로 클릭. 휴대폰: 패를 차례로 눌러요(넓은 판은 세로로 돌려 보여 줘요). 키보드: 화살표로 옮기고 스페이스로 골라요. 힌트를 쓰는 방이면 [💡 힌트]로 한 쌍을 볼 수 있어요.</p>
|
||||
<p className="small muted">{MAHJONG_TILE_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<ShisenView, ShisenOptions> = {
|
||||
Board: ShisenBoard,
|
||||
Side: ShisenSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
60
apps/web/src/games/shisen/quick.tsx
Normal file
60
apps/web/src/games/shisen/quick.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 사천성 30초 규칙 요약 (docs/07 §5). Small boards drawn with the mahjong tiles. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniBoard } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['3p', '', '3p'],
|
||||
['1z', '5s', '2m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '같은 통수 3 두 장이 빈 칸을 지나는 곧은 선으로 이어져 있어요',
|
||||
title: '같은 패 두 장을 이어요',
|
||||
text: '같은 그림의 패 두 장을 차례로 누르면 없어져요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '가운데가 막힌 중 두 장이 판 바깥을 돌아 두 번 꺾인 선으로 이어져 있어요',
|
||||
title: '두 번까지 꺾여도 돼요',
|
||||
text: '빈 칸으로만 지나는 선이 두 번 이하로 꺾이면 이어져요. 판 바깥 테두리로 돌아가도 돼요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['', '5z', ''],
|
||||
['', '', '5z'],
|
||||
]}
|
||||
path={[
|
||||
[0, 1],
|
||||
[1, 1],
|
||||
[1, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '판에 백 두 장만 남아 한 번 꺾인 선으로 이어져 있어요',
|
||||
title: '모두 없애면 승리',
|
||||
text: '패를 모두 없애면 다 푼 거예요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 이을 쌍이 없으면 저절로 섞여요.',
|
||||
},
|
||||
];
|
||||
@@ -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) => (
|
||||
|
||||
29
apps/web/src/games/solitaire/help.ts
Normal file
29
apps/web/src/games/solitaire/help.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/** 솔리테어 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { Mode, SolitaireView } from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW: Record<Mode, string[]> = {
|
||||
klondike: [
|
||||
'클론다이크: 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 줄에는 K만 놓아요. 카드를 옮기면 아래 뒤집힌 카드가 열려요.',
|
||||
'더미를 누르면 카드를 넘겨요. 더미가 비면 버린 카드를 다시 뒤집어 써요. A부터 무늬별로 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
freecell: [
|
||||
'프리셀: 모든 카드가 앞면이에요. 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 칸 4개에는 카드를 한 장씩 잠깐 둘 수 있어요.',
|
||||
'여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요. 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
spider: [
|
||||
'스파이더: 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요.',
|
||||
'K부터 A까지 같은 무늬 한 줄이 되면 저절로 빠져요. 8줄을 모두 빼면 다 푼 거예요. 더미를 누르면 열 줄에 한 장씩 나눠요(빈 줄이 있으면 못 나눠요).',
|
||||
],
|
||||
};
|
||||
const COMMON = ['카드를 눌러 고르고 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [되돌리기]로 한 수씩 되돌릴 수 있어요(횟수가 결과에 적혀요).'];
|
||||
|
||||
export function helpNow(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, [...HOW[v.options.mode], ...COMMON], '실패했어요.');
|
||||
const b = v.board;
|
||||
if (!b || v.phase !== 'playing') return lines;
|
||||
if (b.mode === 'spider') return `${lines}\n더미에서 ${b.stock / 10}번 더 나눌 수 있어요.`;
|
||||
if (b.mode === 'klondike') return `${lines}\n더미에 ${b.stock}장, 버린 카드 ${b.waste.length}장이 있어요.`;
|
||||
return `${lines}\n빈 칸 ${b.cells.filter((c) => !c).length}개가 비어 있어요.`;
|
||||
}
|
||||
510
apps/web/src/games/solitaire/index.tsx
Normal file
510
apps/web/src/games/solitaire/index.tsx
Normal file
@@ -0,0 +1,510 @@
|
||||
/** 솔리테어 화면 (docs/games/solitaire.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import {
|
||||
MODE_NAME,
|
||||
TIME_CHOICES,
|
||||
canAuto,
|
||||
freecellCapacity,
|
||||
isRun,
|
||||
moveProblem,
|
||||
rankOf,
|
||||
type Mode,
|
||||
type SolitaireBoardView,
|
||||
type SolitaireMove,
|
||||
type SolitaireOptions,
|
||||
type SolitaireView,
|
||||
} from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT, PlayingCard, cardAria } from '../../components/cards/PlayingCard';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const FAIL = '실패했어요.';
|
||||
const DOUBLE_TAP_MS = 380;
|
||||
|
||||
const CSS = `
|
||||
.sl-felt { width: 100%; border-radius: 14px; background: var(--felt); box-shadow: inset 0 0 40px rgba(0,0,0,.25), var(--shadow); color: #fff;
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; }
|
||||
.sl-row { display: grid; justify-content: center; align-items: start; }
|
||||
.sl-pile { position: relative; }
|
||||
.sl-slot { display: flex; align-items: center; justify-content: center; border-radius: 8%/6%; border: 2px dashed rgba(255,255,255,.45); background: rgba(0,0,0,.12);
|
||||
color: rgba(255,255,255,.7); font-weight: 900; padding: 0; cursor: pointer; font-family: inherit; }
|
||||
.sl-slot[data-hint='true'] { border-color: #fbbf24; border-style: solid; background: rgba(251,191,36,.18); }
|
||||
.sl-slot:disabled { cursor: default; }
|
||||
.sl-card { position: absolute; left: 0; padding: 0; border: 0; background: none; cursor: pointer; display: block; border-radius: 9%/6%; }
|
||||
.sl-card:disabled, span.sl-card { cursor: default; }
|
||||
.sl-card:focus-visible, .sl-slot:focus-visible, .sl-stock:focus-visible { outline: 3px solid #fbbf24; outline-offset: 2px; z-index: 50; }
|
||||
.sl-stock { position: relative; padding: 0; border: 0; background: none; cursor: pointer; display: block; }
|
||||
.sl-stock:disabled { cursor: default; }
|
||||
.sl-badge { position: absolute; right: -4px; bottom: -6px; min-width: 22px; padding: 1px 5px; border-radius: 999px; background: #111827; color: #fff; font-size: .72rem;
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; box-shadow: 0 1px 3px rgba(0,0,0,.4); pointer-events: none; }
|
||||
.sl-in { animation: sl-in .26s ease-out both; }
|
||||
.sl-shake { animation: sl-shake .3s ease-in-out; }
|
||||
@keyframes sl-in { from { transform: translateY(-14px) scale(1.06); opacity: .5; } }
|
||||
@keyframes sl-shake { 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } }
|
||||
@media (prefers-reduced-motion: reduce) { .sl-in, .sl-shake { animation: none; } }
|
||||
`;
|
||||
|
||||
interface Sel {
|
||||
from: string;
|
||||
n: number;
|
||||
}
|
||||
|
||||
const colsOf = (mode: Mode) => (mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10);
|
||||
const fTotal = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0);
|
||||
const pileName = (id: string) =>
|
||||
id === 'w' ? '버린 카드' : id === 'f' ? '파운데이션' : id[0] === 't' ? `${Number(id.slice(1)) + 1}번째 줄` : id[0] === 'c' ? `빈 칸 ${Number(id.slice(1)) + 1}` : `파운데이션 ${Number(id.slice(1)) + 1}`;
|
||||
|
||||
/** Every visible card on its pile ("t3:4" → "KS"), to spot cards that just arrived. */
|
||||
function cardSpots(b: SolitaireBoardView): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
b.t.forEach((c, i) => c.forEach((x, k) => out.set(`t${i}:${k}`, x ?? '')));
|
||||
b.waste.forEach((x, k) => out.set(`w:${k}`, x));
|
||||
b.cells.forEach((x, i) => x && out.set(`c${i}:0`, x));
|
||||
b.f.forEach((x, i) => x && out.set(`f${i}:0`, x));
|
||||
return out;
|
||||
}
|
||||
|
||||
function SolBoard({ view: v, me, players, act }: BoardProps<SolitaireView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [fresh, setFresh] = useState<Set<string>>(new Set());
|
||||
const [shake, setShake] = useState(0);
|
||||
const [box, setBox] = useState({ w: 0, h: 800 });
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const lastTap = useRef<{ key: string; at: number } | null>(null);
|
||||
const prev = useRef<SolitaireBoardView | null>(null);
|
||||
const bKey = b ? JSON.stringify(b) : '';
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = wrapRef.current;
|
||||
if (!el) return;
|
||||
const update = () => {
|
||||
const playH = parseFloat(getComputedStyle(el).getPropertyValue('--play-h'));
|
||||
setBox({ w: el.clientWidth, h: Number.isFinite(playH) && playH > 0 ? playH : window.innerHeight });
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [!!b]);
|
||||
|
||||
// Cards that just arrived slide in; sounds for what changed. Any change ends the current selection.
|
||||
useEffect(() => {
|
||||
const was = prev.current;
|
||||
prev.current = b;
|
||||
setSel(null);
|
||||
if (!b || !was) return;
|
||||
const before = cardSpots(was);
|
||||
const added = new Set<string>();
|
||||
for (const [k, c] of cardSpots(b)) if (c && before.get(k) !== c) added.add(k);
|
||||
const up = fTotal(b.f) - fTotal(was.f);
|
||||
if (b.done.length > was.done.length) {
|
||||
sfx.good();
|
||||
haptic([20, 30, 20]);
|
||||
setAnnounce(`K부터 A까지 한 줄을 완성해서 뺐어요. 완성 ${b.done.length}/8줄`);
|
||||
} else if (up > 0) {
|
||||
[1046, 1318].forEach((f, i) => tone(f, 70, 'triangle', 0.1, i * 60));
|
||||
setAnnounce(`파운데이션에 올렸어요. 올린 카드 ${fTotal(b.f)}/52`);
|
||||
} else if (b.stock < was.stock && b.mode === 'spider') sfx.deal(10, 35);
|
||||
else if (b.stock !== was.stock || b.waste.length !== was.waste.length) sfx.cardFlip();
|
||||
else if (added.size) sfx.cardPlay();
|
||||
if (b.undos > was.undos) setAnnounce('한 수 되돌렸어요.');
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(300));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [bKey]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text={`${MODE_NAME[v.options.mode]} · 모두 같은 패예요!`} />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Card size: the columns fill the width (phones: 7–8 columns ≈ 47 px, 10 columns ≈ 34 px).
|
||||
const N = colsOf(b.mode);
|
||||
const gap = phone ? (N >= 10 ? 2 : 4) : N >= 10 ? 8 : 12;
|
||||
const pad = phone ? 4 : 14;
|
||||
const w = Math.max(24, Math.min(N >= 10 ? 78 : 96, Math.floor((box.w - 2 * pad - gap * (N - 1)) / N)));
|
||||
const h = Math.round(w * 1.4);
|
||||
const colMax = phone ? Infinity : Math.max(h * 3, box.h - h - 230);
|
||||
const offsets = (col: (string | null)[]) => {
|
||||
const downs = col.filter((x) => x === null).length;
|
||||
const ups = col.length - downs;
|
||||
let dOff = Math.round(h * 0.11);
|
||||
let uOff = Math.round(h * (phone ? 0.3 : 0.38));
|
||||
if (h + downs * dOff + Math.max(0, ups - 1) * uOff > colMax) {
|
||||
dOff = Math.max(3, Math.round(h * 0.05));
|
||||
uOff = Math.max(Math.round(h * 0.24), Math.floor((colMax - h - downs * dOff) / Math.max(1, ups - 1)));
|
||||
}
|
||||
let y = 0;
|
||||
return col.map((x) => {
|
||||
const top = y;
|
||||
y += x === null ? dOff : uOff;
|
||||
return top;
|
||||
});
|
||||
};
|
||||
const grid: CSSProperties = { gridTemplateColumns: `repeat(${N}, ${w}px)`, gap, padding: `${pad}px ${pad}px 0` };
|
||||
|
||||
const tops = (pile: string): number => {
|
||||
if (pile === 'w') return b.waste.length - 1;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]!.length - 1;
|
||||
return 0;
|
||||
};
|
||||
const cardAt = (pile: string, i: number): string | null => {
|
||||
if (pile === 'w') return b.waste[i] ?? null;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]![i] ?? null;
|
||||
if (pile[0] === 'c') return b.cells[Number(pile.slice(1))] || null;
|
||||
return b.f[Number(pile.slice(1))] || null;
|
||||
};
|
||||
const nope = (why: string) => {
|
||||
setAnnounce(why);
|
||||
setShake((x) => x + 1);
|
||||
tone(220, 110, 'sine', 0.07);
|
||||
haptic(15);
|
||||
};
|
||||
const send = (m: SolitaireMove) => {
|
||||
const why = moveProblem(b, m);
|
||||
if (why) return nope(why);
|
||||
act(m);
|
||||
};
|
||||
const dropOn = (pile: string) => {
|
||||
if (!sel) return;
|
||||
setSel(null);
|
||||
const m: SolitaireMove = { type: 'move', from: sel.from, n: sel.n, to: pile };
|
||||
// A foundation tap means "up there": use the slot that fits when the tapped one does not.
|
||||
if (pile[0] === 'f' && moveProblem(b, m)) m.to = 'f';
|
||||
send(m);
|
||||
};
|
||||
const toFoundation = (pile: string) => {
|
||||
const m: SolitaireMove = { type: 'move', from: pile, n: 1, to: 'f' };
|
||||
setSel(null);
|
||||
send(m);
|
||||
};
|
||||
|
||||
const tapCard = (pile: string, i: number) => {
|
||||
if (!playing) return;
|
||||
const t = performance.now();
|
||||
const key = `${pile}:${i}`;
|
||||
const dbl = lastTap.current?.key === key && t - lastTap.current.at < DOUBLE_TAP_MS;
|
||||
lastTap.current = dbl ? null : { key, at: t };
|
||||
const card = cardAt(pile, i);
|
||||
if (dbl && pile[0] !== 'f' && i === tops(pile) && !moveProblem(b, { type: 'move', from: pile, n: 1, to: 'f' })) return toFoundation(pile);
|
||||
if (sel && sel.from !== pile && pile !== 'w') return dropOn(pile);
|
||||
if (!card) return;
|
||||
const n = pile[0] === 't' ? b.t[Number(pile.slice(1))]!.length - i : 1;
|
||||
if (sel && sel.n === n) {
|
||||
setSel(null);
|
||||
setAnnounce('고른 카드를 내려놓았어요.');
|
||||
return;
|
||||
}
|
||||
if (pile[0] === 'f' && b.mode !== 'klondike') return nope('올린 카드는 내릴 수 없어요.');
|
||||
if (pile[0] === 't' && !isRun(b.mode, b.t[Number(pile.slice(1))]!.slice(i)))
|
||||
return nope(b.mode === 'spider' ? '같은 무늬로 이어진 카드만 함께 옮길 수 있어요.' : '색이 번갈아 하나씩 작아지게 이어진 카드만 함께 옮길 수 있어요.');
|
||||
setSel({ from: pile, n });
|
||||
sfx.select();
|
||||
setAnnounce(`${cardAria(card)}${n > 1 ? `부터 ${n}장` : ''}을 골랐어요. 놓을 곳을 눌러요.`);
|
||||
};
|
||||
const onCardKey = (pile: string, i: number) => (e: ReactKeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 그만뒀어요.');
|
||||
} else if ((e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') && i === tops(pile) && pile[0] !== 'f') {
|
||||
e.preventDefault();
|
||||
if (playing) toFoundation(pile);
|
||||
}
|
||||
};
|
||||
const tapStock = () => {
|
||||
if (!playing) return;
|
||||
setSel(null);
|
||||
send(b.mode === 'spider' ? { type: 'deal' } : { type: 'draw' });
|
||||
};
|
||||
|
||||
/** Piles the selected cards may go to (a soft glow helps beginners). */
|
||||
const fits = (to: string) => !!sel && sel.from !== to && moveProblem(b, { type: 'move', from: sel.from, n: sel.n, to }) === null;
|
||||
const isSel = (pile: string, i: number) => !!sel && sel.from === pile && i >= tops(pile) - sel.n + 1;
|
||||
|
||||
const cardButton = (pile: string, i: number, card: string, style: CSSProperties, label: string) => (
|
||||
<button
|
||||
key={`${pile}-${i}`}
|
||||
type="button"
|
||||
className={`sl-card${fresh.has(`${pile}:${i}`) ? ' sl-in' : ''}`}
|
||||
style={{ ...style, zIndex: i + 1 }}
|
||||
data-card={card}
|
||||
aria-label={label}
|
||||
aria-pressed={isSel(pile, i)}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
onClick={() => tapCard(pile, i)}
|
||||
onKeyDown={onCardKey(pile, i)}
|
||||
>
|
||||
<PlayingCard card={card} width={w} selected={isSel(pile, i)} highlight={i === tops(pile) && fits(pile)} />
|
||||
</button>
|
||||
);
|
||||
const slot = (pile: string, text: string, label: string, onClick?: () => void) => (
|
||||
<button
|
||||
key={`${pile}-slot`}
|
||||
type="button"
|
||||
className="sl-slot"
|
||||
style={{ width: w, height: h, fontSize: Math.max(11, w * 0.32) }}
|
||||
data-hint={fits(pile)}
|
||||
aria-label={label}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
disabled={!playing}
|
||||
onClick={onClick ?? (() => dropOn(pile))}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Top row: stock / waste / foundations (Klondike), free cells / foundations (FreeCell), stock / completed runs (Spider).
|
||||
const stockLeft = b.mode === 'spider' ? b.stock / 10 : b.stock;
|
||||
const stock = (
|
||||
<div className="sl-pile" data-pile="s" data-count={b.stock} style={{ gridColumn: 1 }}>
|
||||
{b.stock > 0 || b.mode === 'spider' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="sl-stock"
|
||||
disabled={!playing || b.stock === 0}
|
||||
onClick={tapStock}
|
||||
aria-label={b.mode === 'spider' ? (b.stock ? `카드 나누기, ${stockLeft}번 남음` : '나눌 카드가 없어요') : `더미에서 카드 넘기기, ${b.stock}장 남음`}
|
||||
style={{ width: w, height: h }}
|
||||
>
|
||||
{b.stock > 0 ? (
|
||||
Array.from({ length: Math.min(b.mode === 'spider' ? stockLeft : 3, 5) }, (_, k) => (
|
||||
<span key={k} style={{ position: 'absolute', left: k * Math.max(2, w * 0.06), top: 0 }}>
|
||||
<PlayingCard card={null} width={w} />
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />
|
||||
)}
|
||||
{b.stock > 0 && <span className="sl-badge">{b.mode === 'spider' ? `${stockLeft}번` : b.stock}</span>}
|
||||
</button>
|
||||
) : (
|
||||
slot('s', b.waste.length ? '↻' : '', b.waste.length ? '버린 카드를 다시 더미로 뒤집기' : '더미가 비었어요', tapStock)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
const fan = b.draw === 3 ? Math.round(w * 0.32) : 0;
|
||||
const shownWaste = b.waste.slice(-(b.draw === 3 ? 3 : 2));
|
||||
const waste = (
|
||||
<div className="sl-pile" data-pile="w" style={{ gridColumn: 2, width: w, height: h }}>
|
||||
{!b.waste.length && <span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />}
|
||||
{shownWaste.map((c, k) => {
|
||||
const i = b.waste.length - shownWaste.length + k;
|
||||
const x = b.draw === 3 ? k * fan : 0;
|
||||
return i === b.waste.length - 1 ? (
|
||||
cardButton('w', i, c, { left: x, top: 0 }, `버린 카드 맨 위 ${cardAria(c)}. 두 번 누르면 파운데이션으로`)
|
||||
) : (
|
||||
<span key={`w-${i}`} className="sl-card" style={{ left: x, top: 0, zIndex: k }} aria-hidden>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
const foundations = b.f.map((c, i) => (
|
||||
<div key={`f${i}`} className="sl-pile" data-pile={`f${i}`} data-top={c} style={{ gridColumn: N - 3 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`f${i}`, 0, c, { top: 0 }, `파운데이션 ${i + 1}, 맨 위 ${cardAria(c)}`) : slot(`f${i}`, 'A', `파운데이션 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const cells = b.cells.map((c, i) => (
|
||||
<div key={`c${i}`} className="sl-pile" data-pile={`c${i}`} style={{ gridColumn: 1 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`c${i}`, 0, c, { top: 0 }, `빈 칸 ${i + 1}의 ${cardAria(c)}`) : slot(`c${i}`, '', `빈 칸 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const done = Array.from({ length: 8 }, (_, i) => (
|
||||
<div key={`d${i}`} className="sl-pile" style={{ gridColumn: 3 + i, width: w, height: h }} aria-hidden>
|
||||
{b.done[i] ? <span className="sl-done-card"><PlayingCard card={`K${b.done[i]}`} width={w} /></span> : <span className="sl-slot" style={{ width: w, height: h, cursor: 'default', opacity: 0.6 }} />}
|
||||
</div>
|
||||
));
|
||||
|
||||
const columns = b.t.map((col, i) => {
|
||||
const pile = `t${i}`;
|
||||
const ys = offsets(col);
|
||||
const height = (ys.at(-1) ?? 0) + h;
|
||||
return (
|
||||
<div key={pile} className="sl-pile" data-pile={pile} role="group" aria-label={`${i + 1}번째 줄, ${col.length}장`} style={{ width: w, height: height + Math.round(w * 0.25) }}>
|
||||
{!col.length && slot(pile, b.mode === 'klondike' ? 'K' : '', `${i + 1}번째 줄, 비었어요${b.mode === 'klondike' ? '. K만 놓을 수 있어요' : ''}`)}
|
||||
{col.map((c, k) =>
|
||||
c === null ? (
|
||||
<span key={`${pile}-${k}`} className="sl-card" style={{ top: ys[k], zIndex: k + 1 }} data-card="">
|
||||
<PlayingCard card={null} width={w} title="뒤집힌 카드" />
|
||||
</span>
|
||||
) : (
|
||||
cardButton(pile, k, c, { top: ys[k] }, `${i + 1}번째 줄 ${k + 1}번째 ${cardAria(c)}${k === col.length - 1 ? ', 맨 위' : ''}`)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const autoOk = b.mode !== 'spider' && canAuto(b);
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill">{MODE_NAME[b.mode]}</span>
|
||||
<span className="rc-pill" aria-label={b.mode === 'spider' ? `완성 ${b.done.length}/8줄` : `올린 카드 ${fTotal(b.f)}/52`}>
|
||||
{b.mode === 'spider' ? '🂮' : '🂡'} <b>{b.mode === 'spider' ? `${b.done.length}/8` : `${fTotal(b.f)}/52`}</b>
|
||||
</span>
|
||||
{b.mode === 'freecell' && (
|
||||
<span className="rc-pill" aria-label={`한 번에 ${freecellCapacity(b, false)}장까지 옮길 수 있어요`}>
|
||||
⇅ <b>{freecellCapacity(b, false)}장</b>
|
||||
</span>
|
||||
)}
|
||||
{b.undos > 0 && <span className="rc-pill" aria-label={`되돌리기 ${b.undos}번`}>↶ {b.undos}</span>}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={{ width: '100%' }} ref={wrapRef}>
|
||||
<div key={shake} className={`sl-felt${shake ? ' sl-shake' : ''}`} data-mode={b.mode} style={{ paddingBottom: pad }}>
|
||||
<div className="sl-row" style={grid} role="group" aria-label={b.mode === 'freecell' ? '빈 칸과 파운데이션' : b.mode === 'spider' ? '더미와 완성한 줄' : '더미, 버린 카드, 파운데이션'}>
|
||||
{b.mode === 'klondike' && [stock, waste, ...foundations]}
|
||||
{b.mode === 'freecell' && [...cells, ...foundations]}
|
||||
{b.mode === 'spider' && [stock, ...done]}
|
||||
</div>
|
||||
<div className="sl-row" style={{ ...grid, paddingTop: Math.max(8, Math.round(h * 0.18)) }}>
|
||||
{columns}
|
||||
</div>
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<button type="button" className="btn btn-secondary" disabled={!b.canUndo} onClick={() => send({ type: 'undo' })}>
|
||||
↶ 되돌리기
|
||||
</button>
|
||||
{b.mode !== 'spider' && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!autoOk} onClick={() => send({ type: 'auto' })}>
|
||||
자동 정리
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로 · 키보드: Tab으로 옮기고 Enter로 고르기·놓기, F 파운데이션, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const modeInfo = (o: SolitaireOptions) =>
|
||||
o.mode === 'klondike' ? `클론다이크 · ${o.draw}장씩 넘기기` : o.mode === 'spider' ? `스파이더 · 무늬 ${o.suits}가지` : '프리셀 · 빈 칸 4개';
|
||||
|
||||
function SolSide(props: BoardProps<SolitaireView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="솔리테어" info={modeInfo(props.view.options)} />;
|
||||
}
|
||||
|
||||
const PLAYING_LINE: Record<Mode, string> = {
|
||||
klondike: '색을 번갈아 하나씩 작게 쌓고, A부터 무늬별로 파운데이션에 올려요',
|
||||
freecell: '빈 칸 4개를 잘 써서 모든 카드를 A부터 무늬별로 올려요',
|
||||
spider: '하나 작은 수 위에 쌓아 K부터 A까지 같은 무늬 한 줄을 만들어요',
|
||||
};
|
||||
|
||||
function statusText(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: `곧 시작해요! ${MODE_NAME[v.options.mode]} · 모두 같은 패예요`, playing: PLAYING_LINE[v.options.mode], failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SolitaireOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>종류</strong>
|
||||
<Seg label="종류" value={o.mode} options={(Object.keys(MODE_NAME) as Mode[]).map((m) => [m, MODE_NAME[m]])} onChange={(mode) => onChange({ ...o, mode })} />
|
||||
<span className="small muted">
|
||||
{o.mode === 'klondike'
|
||||
? '일곱 줄, 더미에서 카드를 넘겨 가며 풀어요.'
|
||||
: o.mode === 'freecell'
|
||||
? '모든 카드가 앞면으로 여덟 줄. 빈 칸 4개를 잠깐 쓸 수 있어요.'
|
||||
: '카드 두 벌로 열 줄. K부터 A까지 같은 무늬 한 줄을 만들면 빠져요.'}
|
||||
</span>
|
||||
</div>
|
||||
{o.mode === 'klondike' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>한 번에 넘기는 카드</strong>
|
||||
<Seg label="한 번에 넘기는 카드" value={o.draw} options={[[1, '1장(쉬움)'], [3, '3장(어려움)']]} onChange={(draw) => onChange({ ...o, draw })} />
|
||||
</div>
|
||||
)}
|
||||
{o.mode === 'spider' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>무늬 수</strong>
|
||||
<Seg label="무늬 수" value={o.suits} options={[[1, '1가지(쉬움)'], [2, '2가지(보통)'], [4, '4가지(어려움)']]} onChange={(suits) => onChange({ ...o, suits })} />
|
||||
</div>
|
||||
)}
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[...TIME_CHOICES]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SolitaireOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SolitaireOptions): string {
|
||||
return `${modeInfo(o)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SolitaireOptions }) {
|
||||
const o = options ?? { mode: 'klondike', draw: 1, suits: 1, timeLimitSec: 900 };
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
윈도우에 있던 그 카드놀이예요. 모두 <strong>똑같은 패</strong>를 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. 지금은 {modeInfo(o)}, 제한 시간 {limitLabel(o.timeLimitSec)}이에요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<PlayingCard card="8S" width={40} />
|
||||
<PlayingCard card="7H" width={40} style={{ marginLeft: -22, marginTop: 14 }} />
|
||||
<PlayingCard card="6C" width={40} style={{ marginLeft: -22, marginTop: 28 }} />
|
||||
<span style={{ marginLeft: 8 }}>줄에는 색을 번갈아 하나씩 작은 수를 쌓아요(스파이더는 색 상관없이).</span>
|
||||
</div>
|
||||
<p>
|
||||
<strong>클론다이크</strong>: 일곱 줄 가운데 맨 위만 앞면이에요. 아래 카드를 옮기면 뒤집힌 카드가 저절로 열려요. 빈 줄에는 K만 놓을 수 있어요. 더미를 누르면 카드를 1장(또는 3장)씩 넘기고,
|
||||
더미가 비면 버린 카드를 다시 뒤집어 써요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>프리셀</strong>: 모든 카드가 앞면이에요. 빈 칸 4개에 카드를 한 장씩 잠깐 둘 수 있고, 빈 줄에는 아무 카드나 놓아요. 여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>스파이더</strong>: 카드 두 벌로 열 줄이에요. 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요. K부터 A까지 같은 무늬 한 줄이 되면 저절로
|
||||
빠져요. 더미를 누르면 열 줄에 한 장씩 나눠 주는데, 빈 줄이 있으면 나눌 수 없어요.
|
||||
</p>
|
||||
<p>
|
||||
카드를 눌러 고르고(위에 얹힌 카드까지 함께) 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [자동 정리]는 올릴 수 있는 카드를 모두 올려요. [되돌리기]는 몇 번이든 쓸 수 있지만 결과에 횟수가
|
||||
적혀요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 올린(스파이더는 많이 완성한) 사람이 이겨요. 클론다이크는 가끔 풀 수 없는 패도 나와요.
|
||||
</p>
|
||||
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SolitaireView, SolitaireOptions> = {
|
||||
Board: SolBoard,
|
||||
Side: SolSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
63
apps/web/src/games/solitaire/quick.tsx
Normal file
63
apps/web/src/games/solitaire/quick.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
/** 솔리테어 30초 규칙 요약 (docs/07 §5). Small tables drawn with the real playing cards. */
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** A fanned column: face-down cards (null) then face-up ones. */
|
||||
function Fan({ cards, w = 34 }: { cards: (string | null)[]; w?: number }) {
|
||||
const h = Math.round(w * 1.4);
|
||||
let y = 0;
|
||||
const ys = cards.map((c) => {
|
||||
const top = y;
|
||||
y += c === null ? h * 0.12 : h * 0.3;
|
||||
return top;
|
||||
});
|
||||
return (
|
||||
<span style={{ position: 'relative', display: 'inline-block', width: w, height: (ys.at(-1) ?? 0) + h }}>
|
||||
{cards.map((c, i) => (
|
||||
<span key={i} style={{ position: 'absolute', left: 0, top: ys[i] }}>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const row = { display: 'inline-flex', gap: 6, alignItems: 'flex-start' } as const;
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, null, 'KS', 'QH', 'JC']} />
|
||||
<Fan cards={[null, '8D', '7S', '6H']} />
|
||||
</span>
|
||||
),
|
||||
alt: '두 줄에 카드가 색을 번갈아 하나씩 작은 수로 쌓여 있어요',
|
||||
title: '색을 번갈아 내려 쌓기',
|
||||
text: '줄에는 색을 번갈아 하나씩 작은 수를 쌓아요. 모두 똑같은 패를 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<PlayingCard card="AH" width={34} />
|
||||
<PlayingCard card="2H" width={34} />
|
||||
<PlayingCard card="3H" width={34} />
|
||||
</span>
|
||||
),
|
||||
alt: '하트 A, 2, 3이 차례로 놓여 있어요',
|
||||
title: 'A부터 무늬별로 올리기',
|
||||
text: '파운데이션에 A부터 같은 무늬로 차례대로 올려요. 두 번 누르면 바로 올라가요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, 'KS', 'QS', 'JS', 'TS']} w={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
</span>
|
||||
),
|
||||
alt: '스페이드가 K부터 차례로 이어진 줄과 완성한 줄이에요',
|
||||
title: '세 가지 솔리테어',
|
||||
text: '클론다이크·프리셀은 52장을 다 올리면, 스파이더는 K→A 같은 무늬 8줄을 빼면 다 풀어요.',
|
||||
},
|
||||
];
|
||||
@@ -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>
|
||||
|
||||
53
apps/web/src/games/sudoku/art.tsx
Normal file
53
apps/web/src/games/sudoku/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 스도쿠 small pictures for the rules and the summary cards (SVG, no image files). */
|
||||
|
||||
const U = 32;
|
||||
|
||||
/**
|
||||
* A few rows of cells. Per char: '1'..'9' given (bold), 'a'..'i' my number 1..9 (blue), '.' empty, '*' the selected
|
||||
* empty cell. `bad` cells are red (a digit twice), `notes` puts small pencil marks in empty cells, `box` draws thick
|
||||
* lines every 3 cells.
|
||||
*/
|
||||
export function MiniSudoku({ rows, bad = [], notes = {}, box = true, size = 28 }: { rows: string[]; bad?: number[]; notes?: Record<number, string>; box?: boolean; size?: number }) {
|
||||
const cols = rows[0]!.length;
|
||||
const w = cols * U;
|
||||
const h = rows.length * U;
|
||||
return (
|
||||
<svg viewBox={`-2 -2 ${w + 4} ${h + 4}`} width={cols * size} height={rows.length * size} aria-hidden style={{ verticalAlign: 'middle', maxWidth: '100%' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const i = r * cols + c;
|
||||
const x = c * U;
|
||||
const y = r * U;
|
||||
const mine = ch >= 'a' && ch <= 'i';
|
||||
const d = mine ? String(ch.charCodeAt(0) - 96) : ch >= '1' && ch <= '9' ? ch : '';
|
||||
const red = bad.includes(i);
|
||||
return (
|
||||
<g key={i}>
|
||||
<rect x={x} y={y} width={U} height={U} fill={red ? '#fee2e2' : ch === '*' ? '#dbe7ff' : '#ffffff'} stroke="#cbd5e1" strokeWidth={1} />
|
||||
{ch === '*' && <rect x={x + 2} y={y + 2} width={U - 4} height={U - 4} fill="none" stroke="#2563eb" strokeWidth={3} />}
|
||||
{d && (
|
||||
<text x={x + U / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={mine ? 600 : 900} fill={red ? '#dc2626' : mine ? '#2563eb' : '#111827'}>
|
||||
{d}
|
||||
</text>
|
||||
)}
|
||||
{!d &&
|
||||
[...(notes[i] ?? '')].map((n) => {
|
||||
const k = Number(n) - 1;
|
||||
return (
|
||||
<text key={n} x={x + 6 + (k % 3) * 10} y={y + 10 + Math.floor(k / 3) * 10} textAnchor="middle" fontSize={8.5} fontWeight={700} fill="#64748b">
|
||||
{n}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(cols / 3) + 1 }, (_, k) => <line key={`v${k}`} x1={k * 3 * U} y1={0} x2={k * 3 * U} y2={h} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(rows.length / 3) + 1 }, (_, k) => <line key={`h${k}`} x1={0} y1={k * 3 * U} x2={w} y2={k * 3 * U} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{!box && <rect x={0} y={0} width={w} height={h} fill="none" stroke="#111827" strokeWidth={2.5} />}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
41
apps/web/src/games/sudoku/help.ts
Normal file
41
apps/web/src/games/sudoku/help.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 스도쿠 [?] "지금 할 수 있는 것" (docs/07 §5) and the conflict check the board uses. Pure: only reads the client view. */
|
||||
import type { SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
/** Cells whose digit shows up twice in a row, column or box (visible numbers only, no answer). */
|
||||
export function conflicts(values: string): Set<number> {
|
||||
const out = new Set<number>();
|
||||
const units: number[][] = [];
|
||||
for (let k = 0; k < 9; k++) {
|
||||
units.push(Array.from({ length: 9 }, (_, c) => k * 9 + c));
|
||||
units.push(Array.from({ length: 9 }, (_, r) => r * 9 + k));
|
||||
units.push(Array.from({ length: 9 }, (_, j) => (Math.floor(k / 3) * 3 + Math.floor(j / 3)) * 9 + (k % 3) * 3 + (j % 3)));
|
||||
}
|
||||
for (const u of units) {
|
||||
const seen = new Map<string, number[]>();
|
||||
for (const i of u) if (values[i] !== '0') seen.set(values[i]!, [...(seen.get(values[i]!) ?? []), i]);
|
||||
for (const cells of seen.values()) if (cells.length > 1) for (const i of cells) out.add(i);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const HOW = [
|
||||
'가로줄·세로줄·굵은 선 3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 다 맞게 채우면 다 푼 거예요.',
|
||||
'칸을 고르고 아래 숫자를 누르거나 키보드로 숫자를 쳐요. 맞는지는 알려 주지 않아요(종이처럼). 같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요.',
|
||||
'[메모]를 켜면 숫자가 작은 후보 메모로 들어가요. 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는 지워져요.',
|
||||
'키보드: 화살표로 칸을 옮기고 1~9 넣기, Backspace·Delete·0 지우기, N이나 스페이스로 메모 켜고 끄기예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const b = v.board;
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!b || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const extra: string[] = [];
|
||||
const bad = conflicts(b.values).size;
|
||||
if (bad) extra.push(`지금 숫자가 겹친 빨간 칸이 ${bad}개 있어요. 둘 중 하나는 틀렸어요.`);
|
||||
if (v.options.hints) extra.push(`막히면 [💡 힌트]를 눌러요. 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(지금까지 ${b.hints}번, 결과에 남아요).`);
|
||||
else extra.push('이 방은 힌트를 쓸 수 없어요.');
|
||||
return [lines, ...extra].join('\n');
|
||||
}
|
||||
428
apps/web/src/games/sudoku/index.tsx
Normal file
428
apps/web/src/games/sudoku/index.tsx
Normal file
@@ -0,0 +1,428 @@
|
||||
/** 스도쿠 화면 (docs/games/sudoku.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { DIFFICULTIES, type Difficulty, type SudokuOptions, type SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { conflicts, helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const rowOf = (i: number) => Math.floor(i / 9);
|
||||
const colOf = (i: number) => i % 9;
|
||||
const boxOf = (i: number) => Math.floor(rowOf(i) / 3) * 3 + Math.floor(colOf(i) / 3);
|
||||
|
||||
const CSS = `
|
||||
.sd-main { display: flex; gap: 18px; align-items: flex-start; justify-content: center; width: 100%; }
|
||||
.sd-main.phone { flex-direction: column; align-items: stretch; gap: 10px; }
|
||||
.sd-grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(9, 1fr); aspect-ratio: 1; width: 100%;
|
||||
background: var(--surface); border: 3px solid var(--text); border-radius: 8px; overflow: hidden; box-shadow: var(--shadow);
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; outline: none; cursor: pointer; }
|
||||
.sd-grid:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.sd-grid[data-off='true'] { cursor: default; }
|
||||
.sd-cell { position: relative; display: flex; align-items: center; justify-content: center; min-width: 0; min-height: 0;
|
||||
border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums;
|
||||
font-size: clamp(1.15rem, 6vw, 2rem); line-height: 1; transition: background-color .12s; }
|
||||
.sd-cell[data-c='2'], .sd-cell[data-c='5'] { border-right: 2px solid var(--text); }
|
||||
.sd-cell[data-c='8'] { border-right: 0; }
|
||||
.sd-cell[data-r='2'], .sd-cell[data-r='5'] { border-bottom: 2px solid var(--text); }
|
||||
.sd-cell[data-r='8'] { border-bottom: 0; }
|
||||
.sd-cell.peer { background: var(--surface-2); }
|
||||
.sd-cell.same { background: var(--primary-soft); }
|
||||
.sd-cell.hint { background: var(--warning-soft); }
|
||||
.sd-cell.sel { background: var(--primary-soft); box-shadow: inset 0 0 0 3px var(--primary); }
|
||||
.sd-cell .d { font-weight: 600; color: var(--primary); }
|
||||
.sd-cell[data-given='true'] .d { font-weight: 900; color: var(--text); }
|
||||
.sd-cell.same .d { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; }
|
||||
.sd-cell.bad { background: var(--danger-soft); }
|
||||
.sd-cell.bad .d { color: var(--danger); }
|
||||
.sd-cell.sol .d { color: var(--success); font-weight: 600; opacity: .85; }
|
||||
.sd-cell.wrong { background: var(--danger-soft); }
|
||||
.sd-cell.wrong .d { color: var(--success); }
|
||||
.sd-notes { position: absolute; inset: 2px; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr);
|
||||
font-size: clamp(.55rem, 2.6vw, .78rem); font-weight: 700; color: var(--text-sub); line-height: 1; }
|
||||
.sd-notes span { display: flex; align-items: center; justify-content: center; }
|
||||
.sd-notes span.on { color: var(--primary); }
|
||||
.sd-pop .d { animation: sd-pop .3s ease-out both; }
|
||||
.sd-glow { animation: sd-glow .9s ease-out both; }
|
||||
@keyframes sd-pop { from { transform: scale(.4); opacity: .3; } 60% { transform: scale(1.18); } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes sd-glow { 0% { box-shadow: inset 0 0 0 0 var(--warning); } 40% { box-shadow: inset 0 0 0 5px var(--warning); } 100% { box-shadow: inset 0 0 0 0 var(--warning); } }
|
||||
.sd-pad { display: flex; flex-direction: column; gap: 8px; width: 216px; flex: none; }
|
||||
.sd-digits { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||||
.sd-tools { display: grid; grid-template-columns: 1fr; gap: 6px; }
|
||||
.sd-main.phone .sd-pad { width: 100%; }
|
||||
.sd-main.phone .sd-digits { grid-template-columns: repeat(9, 1fr); gap: 4px; }
|
||||
.sd-main.phone .sd-tools { grid-template-columns: repeat(3, 1fr); }
|
||||
.sd-key { position: relative; border: 0; border-radius: 10px; background: var(--surface); color: var(--primary); box-shadow: var(--shadow); cursor: pointer;
|
||||
font-size: 1.7rem; font-weight: 800; min-height: 64px; padding: 0; font-variant-numeric: tabular-nums; touch-action: manipulation; }
|
||||
.sd-main.phone .sd-key { min-height: 54px; font-size: 1.45rem; border-radius: 8px; }
|
||||
.sd-key small { position: absolute; right: 6px; bottom: 4px; font-size: .7rem; font-weight: 700; color: var(--text-sub); }
|
||||
.sd-main.phone .sd-key small { right: 0; left: 0; bottom: 2px; text-align: center; font-size: .62rem; }
|
||||
.sd-key[data-done='true'] { opacity: .35; }
|
||||
.sd-key[data-memo='true'] { color: var(--text-sub); font-size: 1.15rem; }
|
||||
.sd-key:active { transform: scale(.95); }
|
||||
.sd-key:disabled { cursor: default; }
|
||||
.sd-tool { min-height: 44px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-weight: 800; font-size: .98rem; cursor: pointer; padding: 0 8px; touch-action: manipulation; }
|
||||
.sd-tool[aria-pressed='true'] { background: var(--primary); color: var(--primary-text); }
|
||||
.sd-tool:disabled { opacity: .5; cursor: default; }
|
||||
@media (prefers-reduced-motion: reduce) { .sd-pop .d, .sd-glow { animation: none; } .sd-key:active { transform: none; } }
|
||||
`;
|
||||
|
||||
const notesOf = (mask: number) => DIGITS.filter((n) => mask & (1 << n));
|
||||
|
||||
function SudokuBoardView({ view: v, me, players, act }: BoardProps<SudokuView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState(40);
|
||||
const [memo, setMemo] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [glow, setGlow] = useState<number | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const prev = useRef<{ values: string; notes: string; hints: number; bad: number } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
const bad = b ? conflicts(b.values) : new Set<number>();
|
||||
|
||||
// Pop-in for new numbers, a glow on the hinted cell, sounds for what changed.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const cur = { values: b.values, notes: b.notes.join(','), hints: b.hints, bad: bad.size };
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!was || was.values.length !== cur.values.length) return;
|
||||
const added = new Set<number>();
|
||||
let cleared = 0;
|
||||
for (let i = 0; i < 81; i++) {
|
||||
if (was.values[i] === cur.values[i]) continue;
|
||||
if (cur.values[i] === '0') cleared++;
|
||||
else added.add(i);
|
||||
}
|
||||
if (cur.hints > was.hints) {
|
||||
sfx.good();
|
||||
setGlow(b.hintAt);
|
||||
} else if (cur.bad > was.bad) {
|
||||
tone(240, 120, 'square', 0.05);
|
||||
haptic([20, 30, 20]);
|
||||
} else if (added.size) tone(880 + Number(b.values[[...added][0]!]) * 40, 60, 'triangle', 0.1);
|
||||
else if (cleared) tone(420, 50, 'triangle', 0.07);
|
||||
else if (cur.notes !== was.notes) tone(1300, 25, 'triangle', 0.05);
|
||||
const timers: ReturnType<typeof setTimeout>[] = [];
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
timers.push(setTimeout(() => setFresh(new Set()), fxMs(320)));
|
||||
}
|
||||
if (cur.hints > was.hints) timers.push(setTimeout(() => setGlow(null), fxMs(900)));
|
||||
return () => timers.forEach(clearTimeout);
|
||||
}, [b?.values, b?.notes.join(','), b?.hints]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="가로·세로·상자에 1~9를 한 번씩!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const given = (i: number) => b.givens[i] === '1';
|
||||
const reveal = b.solution;
|
||||
const counts = DIGITS.map((n) => [...b.values].filter((ch) => ch === String(n)).length);
|
||||
const describe = (i: number) => {
|
||||
const where = `${rowOf(i) + 1}줄 ${colOf(i) + 1}칸`;
|
||||
const ch = b.values[i]!;
|
||||
if (given(i)) return `${where}, 처음 숫자 ${ch}`;
|
||||
if (ch !== '0') return `${where}, 내 숫자 ${ch}${bad.has(i) ? ', 겹침' : ''}`;
|
||||
const ns = notesOf(b.notes[i]!);
|
||||
return `${where}, 빈칸${ns.length ? `, 메모 ${ns.join(' ')}` : ''}`;
|
||||
};
|
||||
|
||||
const select = (i: number, speak: boolean) => {
|
||||
setSel(i);
|
||||
if (speak) setAnnounce(describe(i));
|
||||
};
|
||||
const enter = (n: number) => {
|
||||
if (!playing) return;
|
||||
const ch = b.values[sel]!;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 바꿀 수 없어요.');
|
||||
if (memo) {
|
||||
if (ch !== '0') return setAnnounce('숫자가 있는 칸에는 메모할 수 없어요. 먼저 지워 주세요.');
|
||||
act({ type: 'note', i: sel, n });
|
||||
setAnnounce(b.notes[sel]! & (1 << n) ? `메모 ${n}을(를) 지웠어요.` : `메모 ${n}을(를) 적었어요.`);
|
||||
return;
|
||||
}
|
||||
haptic(8);
|
||||
if (ch === String(n)) {
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce(`${n}을(를) 지웠어요.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'set', i: sel, n });
|
||||
const dup = [...b.values].some((c, j) => j !== sel && c === String(n) && (rowOf(j) === rowOf(sel) || colOf(j) === colOf(sel) || boxOf(j) === boxOf(sel)));
|
||||
setAnnounce(`${n}을(를) 넣었어요.${dup ? ' 같은 줄·칸·상자에 이미 있는 숫자예요.' : ''}`);
|
||||
};
|
||||
const erase = () => {
|
||||
if (!playing) return;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 지울 수 없어요.');
|
||||
if (b.values[sel] === '0' && !b.notes[sel]) return setAnnounce('지울 것이 없어요.');
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce('지웠어요.');
|
||||
};
|
||||
const toggleMemo = () => {
|
||||
setMemo((m) => !m);
|
||||
setAnnounce(memo ? '메모 모드를 껐어요. 숫자를 넣어요.' : '메모 모드를 켰어요. 숫자가 작은 메모로 들어가요.');
|
||||
};
|
||||
const hint = () => {
|
||||
if (!playing || !v.options.hints) return;
|
||||
act({ type: 'hint' });
|
||||
setAnnounce('힌트로 한 칸을 맞는 숫자로 채웠어요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const box = gridRef.current!.getBoundingClientRect();
|
||||
const c = clamp(Math.floor(((e.clientX - box.left) / box.width) * 9), 0, 8);
|
||||
const r = clamp(Math.floor(((e.clientY - box.top) / box.height) * 9), 0, 8);
|
||||
select(r * 9 + c, false);
|
||||
if (e.pointerType === 'mouse') gridRef.current!.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
const onButton = (e.target as HTMLElement).tagName === 'BUTTON';
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
select(clamp(rowOf(sel) + m[0], 0, 8) * 9 + clamp(colOf(sel) + m[1], 0, 8), true);
|
||||
return;
|
||||
}
|
||||
const num = /^(Digit|Numpad)([0-9])$/.exec(e.code)?.[2] ?? (/^[0-9]$/.test(e.key) ? e.key : null);
|
||||
if (num !== null) {
|
||||
e.preventDefault();
|
||||
if (num === '0') erase();
|
||||
else enter(Number(num));
|
||||
} else if (e.key === 'Backspace' || e.key === 'Delete') {
|
||||
e.preventDefault();
|
||||
erase();
|
||||
} else if ((e.key === ' ' && !onButton) || e.key === 'n' || e.key === 'N' || e.key === 'ㅜ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) toggleMemo();
|
||||
}
|
||||
};
|
||||
|
||||
const wrapStyle: CSSProperties = phone ? { width: '100%' } : { width: 'min(100%, 600px, calc(var(--play-h, 100vh) - 150px))', minWidth: 300, flex: '0 1 auto' };
|
||||
const showPad = !!mine && mine.status === 'playing' && v.phase === 'playing';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
{mine && (
|
||||
<span className="rc-pill" aria-label={mine.progressText}>
|
||||
✏️ <b>{mine.progressText.replace(/^[^\d]*/, '')}</b>
|
||||
</span>
|
||||
)}
|
||||
{b.hints > 0 && (
|
||||
<span className="rc-pill" aria-label={`힌트 ${b.hints}번`}>
|
||||
💡 <b>{b.hints}</b>
|
||||
</span>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className={`sd-main${phone ? ' phone' : ''}`} onKeyDown={onKey}>
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<div
|
||||
ref={gridRef}
|
||||
className="sd-grid"
|
||||
data-off={!playing}
|
||||
role="application"
|
||||
aria-roledescription="스도쿠 판"
|
||||
aria-label={playing ? `스도쿠 판. 화살표로 옮기고 1~9로 넣기, Backspace로 지우기, N으로 메모. 지금 ${describe(sel)}` : '스도쿠 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.values, (ch, i) => {
|
||||
const r = rowOf(i);
|
||||
const c = colOf(i);
|
||||
// Selection shading only while I can still play.
|
||||
const s = playing ? b.values[sel]! : '0';
|
||||
const cls = ['sd-cell'];
|
||||
const sol = reveal && ch !== reveal[i] ? reveal[i]! : null;
|
||||
if (sol) cls.push(ch === '0' ? 'sol' : 'wrong');
|
||||
else if (bad.has(i)) cls.push('bad');
|
||||
if (playing && i === sel) cls.push('sel');
|
||||
else if (s !== '0' && ch === s) cls.push('same');
|
||||
else if (glow === i || (b.hintAt === i && playing)) cls.push('hint');
|
||||
else if (playing && (r === rowOf(sel) || c === colOf(sel) || boxOf(i) === boxOf(sel))) cls.push('peer');
|
||||
if (fresh.has(i)) cls.push('sd-pop');
|
||||
if (glow === i) cls.push('sd-glow');
|
||||
const shown = sol ?? (ch !== '0' ? ch : null);
|
||||
return (
|
||||
<div key={i} className={cls.join(' ')} data-i={i} data-v={ch} data-r={r} data-c={c} data-given={given(i)} data-bad={bad.has(i)} aria-hidden>
|
||||
{shown ? (
|
||||
<span className="d">{shown}</span>
|
||||
) : b.notes[i] ? (
|
||||
<span className="sd-notes">
|
||||
{DIGITS.map((n) => (
|
||||
<span key={n} className={s !== '0' && String(n) === s ? 'on' : undefined}>
|
||||
{b.notes[i]! & (1 << n) ? n : ''}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{showPad && (
|
||||
<div className="sd-pad" role="group" aria-label="숫자 패드">
|
||||
<div className="sd-digits">
|
||||
{DIGITS.map((n, k) => {
|
||||
const rest = 9 - counts[k]!;
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className="sd-key"
|
||||
data-n={n}
|
||||
data-done={rest <= 0}
|
||||
data-memo={memo}
|
||||
disabled={!playing}
|
||||
aria-label={`${memo ? '메모 ' : ''}${n}, ${Math.max(0, rest)}개 남음`}
|
||||
onClick={() => enter(n)}
|
||||
>
|
||||
{n}
|
||||
<small aria-hidden>{Math.max(0, rest)}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="sd-tools">
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={erase}>
|
||||
⌫ 지우기
|
||||
</button>
|
||||
<button type="button" className="sd-tool" aria-pressed={memo} onClick={toggleMemo}>
|
||||
✏️ 메모 {memo ? '켬' : '끔'}
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={hint}>
|
||||
💡 힌트
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && showPad && <p className="rc-keys">칸 클릭 또는 화살표로 고르고 1~9 넣기 · Backspace·Delete·0 지우기 · N·스페이스 메모 켜고 끄기 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{phone && showPad && <p className="rc-keys">칸을 누르고 아래 숫자를 눌러요 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{reveal && v.phase === 'ended' && <p className="rc-keys">초록 숫자 = 정답(빈칸이었거나 틀린 칸)</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const diffInfo = (d: Difficulty) => `${DIFFICULTIES[d].name} · ${DIFFICULTIES[d].givens}`;
|
||||
|
||||
function SudokuSide(props: BoardProps<SudokuView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="스도쿠" info={`${diffInfo(o.difficulty)} · 힌트 ${o.hints ? '있음' : '없음'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 가로·세로·상자에 1~9를 한 번씩 넣어요', playing: '가로·세로·3×3 상자마다 1~9가 한 번씩 · 빈칸을 모두 맞게 채워요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SudokuOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.difficulty}
|
||||
options={(Object.keys(DIFFICULTIES) as Difficulty[]).map((d) => [d, DIFFICULTIES[d].name])}
|
||||
onChange={(difficulty) => onChange({ ...o, difficulty })}
|
||||
/>
|
||||
<span className="small muted">
|
||||
처음부터 있는 {DIFFICULTIES[o.difficulty].givens}
|
||||
{o.difficulty === 'easy' ? ' · 차근차근 하나씩 찾으면 풀려요' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '있음'],
|
||||
[false, '없음'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]로 한 칸씩 맞는 숫자를 받을 수 있어요. 쓴 횟수는 결과에 남아요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[600, 1200, 1800, 3600]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SudokuOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SudokuOptions): string {
|
||||
return `${DIFFICULTIES[o.difficulty].name} · 힌트 ${o.hints ? '있음' : '없음'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SudokuOptions }) {
|
||||
const d = options?.difficulty ?? 'easy';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
9×9 판의 <strong>가로줄·세로줄·굵은 선 3×3 상자</strong>마다 1부터 9까지가 <strong>한 번씩</strong> 들어가게 빈칸을 채워요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요. 답은 딱 하나뿐인 판만 나와요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={26} />
|
||||
<span>굵은 숫자는 처음부터 있던 것, 파란 숫자는 내가 넣은 것, 작은 숫자는 메모예요.</span>
|
||||
</div>
|
||||
<p>
|
||||
칸을 고르고 숫자를 넣어요. 맞는지는 알려 주지 않지만(종이처럼), 같은 줄·칸·상자에 같은 숫자가 겹치면 빨갛게 보여요. [메모]를 켜면 후보 숫자를 작게 적어 둘 수 있고, 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는
|
||||
저절로 지워져요. {options?.hints === false ? '이 방은 힌트가 없어요.' : '[💡 힌트]를 누르면 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(쓴 횟수는 결과에 남아요).'}
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 <strong>가장 먼저 다 맞게 채운 사람</strong>이 이기고, 아무도 못 풀면 많이 채운 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1800)}이고, 지금 난이도는 {diffInfo(d)}예요.
|
||||
</p>
|
||||
<p>PC: 칸을 클릭하거나 화살표로 고르고 1~9, Backspace로 지우기, N이나 스페이스로 메모. 휴대폰: 칸을 누르고 아래 숫자 버튼을 눌러요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SudokuView, SudokuOptions> = {
|
||||
Board: SudokuBoardView,
|
||||
Side: SudokuSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
24
apps/web/src/games/sudoku/quick.tsx
Normal file
24
apps/web/src/games/sudoku/quick.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 스도쿠 30초 규칙 요약 (docs/07 §5). Small grids drawn with the game's own look. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6.9', '.87']} size={30} />,
|
||||
alt: '굵은 선 3×3 상자 하나에 숫자 몇 개가 처음부터 들어 있어요',
|
||||
title: '1~9를 한 번씩',
|
||||
text: '가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={30} />,
|
||||
alt: '고른 칸이 파랗게 표시되고, 내가 넣은 숫자는 파란색, 빈칸에는 작은 메모가 있어요',
|
||||
title: '칸을 고르고 숫자',
|
||||
text: '칸을 누르고 아래 숫자를 눌러요. [메모]를 켜면 작은 후보 숫자로 적어 둘 수 있어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6i9', '.87']} bad={[4, 5]} size={30} />,
|
||||
alt: '같은 줄에 9가 두 번 들어가 두 칸이 빨갛게 보여요',
|
||||
title: '겹치면 빨강',
|
||||
text: '같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요. 다 맞게 채우면 끝! 여럿이면 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -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 (라이어 게임). */
|
||||
|
||||
57
apps/web/src/games/typing/help.test.ts
Normal file
57
apps/web/src/games/typing/help.test.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { marks } from './marks';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const def = GAMES.typing!;
|
||||
const view = (s: unknown, who: string | null) => def.view(s, who) as any;
|
||||
const tick = (s: any, now: number) => def.apply(s, 'A', { type: 'tick' }, { rng: { next: () => 0, int: () => 0, shuffle: (a: unknown[]) => [...a] } as any, now }).state as any;
|
||||
|
||||
test('타자 대결: 카운트다운 / 치는 중 / 관전 / 1등', () => {
|
||||
const { state: s0, now } = setupGame('typing', 3);
|
||||
expect(helpNow(view(s0, 'A'), 'A', users)).toContain('곧 시작해요');
|
||||
const s = tick(s0, now + 3000);
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('Enter');
|
||||
expect(t).toContain('가장 먼저 정확하게');
|
||||
expect(t).toContain('한/영');
|
||||
expect(helpNow(view(s, null), null, users)).toContain('관전 중');
|
||||
s.totals.B.points = 2;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(2점)');
|
||||
});
|
||||
|
||||
test('타자 대결: 서바이벌 목숨 / 탈락 / 끝', () => {
|
||||
const { state: s0, now } = setupGame('typing', 3, { mode: 'survival', lives: 2 });
|
||||
const s = tick(s0, now + 3000);
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('목숨은 2개');
|
||||
s.rs.B.alive = false;
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('탈락했어요');
|
||||
s.phase = 'ended';
|
||||
s.final = { ranking: [], summary: '라운드 점수가 가장 높은 사람이 이겼어요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('라운드 점수가 가장 높은');
|
||||
});
|
||||
|
||||
test('글자 표시: 맞음·틀림·조합 중인 글자', () => {
|
||||
expect(marks('강아지', '강').marks).toEqual(['ok', '', '']);
|
||||
expect(marks('강아지', '가').marks).toEqual(['comp', '', '']);
|
||||
// 도깨비불: "가나" 쪽으로 가는 "간"은 아직 조합 중이에요.
|
||||
expect(marks('가나', '간').marks).toEqual(['comp', '']);
|
||||
expect(marks('강아지', '강오').marks).toEqual(['ok', 'bad', '']);
|
||||
expect(marks('강아지', '강앚').marks).toEqual(['ok', 'comp', '']);
|
||||
expect(marks('강아지', '강오지').marks).toEqual(['ok', 'bad', 'ok']);
|
||||
expect(marks('abc', 'abcd')).toEqual({ marks: ['ok', 'ok', 'ok'], extra: 1 });
|
||||
});
|
||||
|
||||
test('타자 대결: 연습은 라운드·점수 없이 평균·최고 타수', () => {
|
||||
const { state: s0, now } = setupGame('typing', 1, { mode: 'practice' });
|
||||
const s = tick(s0, now + 3000);
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('연습.');
|
||||
expect(t).not.toContain('라운드');
|
||||
expect(t).toContain('최고 0타');
|
||||
s.phase = 'ended';
|
||||
s.final = { ranking: [], summary: '연습 끝! 타수와 정확도를 확인해요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('연습이 끝났어요');
|
||||
});
|
||||
51
apps/web/src/games/typing/help.ts
Normal file
51
apps/web/src/games/typing/help.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/** 타자 대결 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import { ELIM_KO, MODE_KO, type TypingView } from '@bg/games/typing';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const HOW = '위에 나온 글을 입력 칸에 그대로 치고 Enter를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 안 돼요.';
|
||||
|
||||
const MODE_LINE: Record<TypingView['options']['mode'], string> = {
|
||||
first: '가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 빨간 글자를 고쳐서 다시 Enter를 눌러요.',
|
||||
survival: '탈락 조건에 걸리지 않게 끝까지 버티면 라운드 1점이에요. 문제마다 제한 시간이 조금씩 줄어요.',
|
||||
speed: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 라운드 타수(1분에 친 타 수, 틀린 만큼은 빼요)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 정확도가 가장 높은 사람이 1점이에요(같으면 타수).',
|
||||
timeAttack: '시간이 끝날 때까지 나오는 글을 계속 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '제한 시간과 점수 없이 한 줄씩 제 속도로 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
|
||||
function leader(v: TypingView, players: Record<string, PublicUser>, me: string | null): string {
|
||||
const live = v.seats.filter((s) => !s.left);
|
||||
if (live.length < 2) return '';
|
||||
const best = Math.max(...live.map((s) => s.points));
|
||||
if (best === 0) return '아직 아무도 점수가 없어요.';
|
||||
const top = live.filter((s) => s.points === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
|
||||
return `지금 1등은 ${top.join(', ')}(${best}${v.options.mode === 'first' ? '점' : '승'})예요.`;
|
||||
}
|
||||
|
||||
export function helpNow(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended')
|
||||
return v.options.mode === 'practice'
|
||||
? `연습이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n평균·최고 타수와 정확도를 확인하고, [한 판 더]로 한 번 더 연습할 수 있어요.'
|
||||
: `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자의 점수, 평균 타수와 정확도를 볼 수 있어요.';
|
||||
const mode = v.options.mode;
|
||||
const surv = mode === 'survival' ? ` 탈락 조건은 "${ELIM_KO[v.options.elimination]}"${v.options.elimination === 'wrong' ? `, 목숨은 ${v.options.lives}개` : ''}예요.` : '';
|
||||
const head = mode === 'practice' ? `${MODE_KO[mode]}.` : `${MODE_KO[mode]} · 라운드 ${v.round}/${v.options.rounds}.${surv}`;
|
||||
const lead = leader(v, players, me);
|
||||
if (v.phase === 'countdown') return `${head}\n곧 시작해요. ${HOW}\n${MODE_LINE[mode]}`;
|
||||
if (v.phase === 'roundEnd') return `${head}\n라운드가 끝났어요. ${v.rounds.at(-1)?.summary ?? ''}. 잠시 뒤 다음 라운드가 시작해요.${lead ? `\n${lead}` : ''}`;
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
if (!mine) return `${head}\n관전 중이에요. 아래 막대로 각자 얼마나 쳤는지 볼 수 있어요.${lead ? `\n${lead}` : ''}`;
|
||||
if (mine.left) return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
if (!mine.alive) return `${head}\n이번 라운드에서 탈락했어요. 다음 라운드에 다시 참가해요.${lead ? `\n${lead}` : ''}`;
|
||||
const lines = [head];
|
||||
if (v.flow === 'shared' && v.upcoming.length === 0) lines.push('다음 문제가 곧 나와요. 나오자마자 쳐요!');
|
||||
else if (v.flow === 'shared' && mine.solved) lines.push('이번 문제를 쳤어요. 다른 사람이 끝내기를 기다려요.');
|
||||
else if (v.flow === 'lane' && mine.finished) lines.push('이번 라운드를 다 쳤어요. 다른 사람이 끝내기를 기다려요.');
|
||||
else lines.push(HOW);
|
||||
lines.push(MODE_LINE[mode]);
|
||||
lines.push(`${mode === 'practice' ? `지금까지: 평균 ${mine.roundKpm}타, 최고 ${mine.bestKpm}타` : `이번 라운드: ${mine.roundKpm}타`}, 정확도 ${mine.roundTried ? `${mine.roundAcc}%` : '아직 없음'}${mine.wrong ? `, 틀린 Enter ${mine.wrong}번` : ''}.`);
|
||||
if (mode === 'survival' && v.options.elimination === 'wrong') lines.push(`남은 목숨 ${mine.lives}개.`);
|
||||
if (lead) lines.push(lead);
|
||||
lines.push(v.options.lang === 'ko' ? '영어가 쳐지면 한/영 키를 눌러 한글로 바꿔요.' : '한글이 쳐지면 한/영 키를 눌러 영어로 바꿔요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
875
apps/web/src/games/typing/index.tsx
Normal file
875
apps/web/src/games/typing/index.tsx
Normal file
@@ -0,0 +1,875 @@
|
||||
/** 타자 대결 화면 (docs/games/typing.md §9). */
|
||||
import { useEffect, useRef, useState, type FormEvent, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import {
|
||||
CATEGORY_KO,
|
||||
ELIM_KO,
|
||||
LANG_KO,
|
||||
MODE_KO,
|
||||
TOPIC_BY_ID,
|
||||
correctKeys,
|
||||
keyCount,
|
||||
kpm,
|
||||
normalize,
|
||||
topicsFor,
|
||||
type Category,
|
||||
type Elim,
|
||||
type Mode,
|
||||
type RoundResult,
|
||||
type SeatView,
|
||||
type TypingOptions,
|
||||
type TypingView,
|
||||
} from '@bg/games/typing';
|
||||
import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { marks } from './marks';
|
||||
import { AfterMotion } 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' };
|
||||
const secs = (ms: number) => Math.max(0, Math.ceil(ms / 1000));
|
||||
const clock = (ms: number) => {
|
||||
const s = secs(ms);
|
||||
return s >= 60 ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` : `${s}초`;
|
||||
};
|
||||
/** Progress is sent at most this often while typing. */
|
||||
const PROGRESS_MS = 300;
|
||||
|
||||
const tySound = {
|
||||
key: () => tone(1800, 12, 'square', 0.025),
|
||||
right: () => {
|
||||
tone(880, 70, 'triangle', 0.13);
|
||||
tone(1320, 110, 'triangle', 0.11, 60);
|
||||
},
|
||||
wrong: () => sounds.buzz(),
|
||||
first: () => sfx.fanfare(),
|
||||
out: () => [440, 330, 247].forEach((f, i) => tone(f, 160, 'sine', 0.13, i * 130)),
|
||||
count: () => tone(660, 90, 'triangle', 0.12),
|
||||
go: () => {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
},
|
||||
};
|
||||
|
||||
const OUT_KO: Record<string, string> = { lives: '목숨을 다 썼어요', slowest: '가장 늦게 쳤어요', least: '가장 적게 쳤어요', time: '시간 안에 못 쳤어요', left: '나갔어요' };
|
||||
|
||||
const CSS = `
|
||||
.ty { width: 100%; max-width: 860px; margin: 0 auto; display: flex; flex-direction: column; gap: 10px; }
|
||||
.ty-top { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.ty-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.ty-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
.ty-card { position: relative; background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 16px; display: flex; flex-direction: column; gap: 12px; min-height: 180px; }
|
||||
.ty-topic { color: var(--text-sub); font-weight: 700; font-size: .9rem; text-align: center; }
|
||||
.ty-target { font-size: clamp(1.25rem, 4.2vw, 1.9rem); font-weight: 800; line-height: 1.5; text-align: center; word-break: keep-all; overflow-wrap: anywhere; letter-spacing: .01em; }
|
||||
.ty-target span { border-radius: 3px; }
|
||||
.ty-target .ok { color: var(--success); }
|
||||
.ty-target .bad { color: #fff; background: var(--danger); }
|
||||
.ty-target .comp { color: var(--primary); text-decoration: underline; }
|
||||
.ty-target .cur { box-shadow: inset 0 -3px 0 var(--primary); }
|
||||
.ty-target .extra { color: #fff; background: var(--danger); margin-left: 2px; }
|
||||
.ty-next { color: var(--text-sub); font-size: 1.05rem; font-weight: 600; text-align: center; opacity: .8; word-break: keep-all; }
|
||||
.ty-passage { max-height: 210px; overflow: auto; border-radius: 10px; background: var(--surface-2); padding: 8px 12px; margin: 0; list-style: none; display: grid; gap: 2px; }
|
||||
.ty-passage li { font-size: .98rem; line-height: 1.5; color: var(--text-sub); }
|
||||
.ty-passage li[data-s='done'] { color: var(--success); }
|
||||
.ty-passage li[data-s='cur'] { color: var(--text); font-weight: 800; }
|
||||
.ty-form { display: flex; gap: 8px; }
|
||||
.ty-input { flex: 1; min-width: 0; font-size: 1.25rem !important; padding: 12px 14px !important; border-radius: 12px; font-weight: 700; }
|
||||
.ty-input[data-shake='true'] { animation: ty-shake .35s; border-color: var(--danger) !important; }
|
||||
.ty-stats { display: flex; flex-wrap: wrap; gap: 4px 14px; justify-content: center; color: var(--text-sub); font-weight: 700; font-size: .92rem; font-variant-numeric: tabular-nums; }
|
||||
.ty-warn { color: var(--danger); font-weight: 800; text-align: center; }
|
||||
.ty-banner { text-align: center; font-weight: 900; font-size: 1.15rem; padding: 8px 12px; border-radius: 12px; background: var(--primary-soft); animation: ty-pop .35s ease-out; }
|
||||
.ty-banner.bad { background: var(--danger-soft); color: var(--danger); }
|
||||
.ty-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; border-radius: 16px;
|
||||
background: rgba(0,0,0,.45); color: #fff; text-align: center; padding: 12px; z-index: 2; }
|
||||
.ty-over b { font-size: 4.5rem; font-weight: 900; line-height: 1; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
|
||||
.ty-over small { font-size: 1.05rem; font-weight: 800; }
|
||||
.ty-seats { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
|
||||
.ty-seat { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 4px 8px; align-items: center; background: var(--surface); border-radius: 12px; padding: 6px 10px; box-shadow: var(--shadow); }
|
||||
.ty-seat[data-me='true'] { outline: 2px solid var(--primary); }
|
||||
.ty-seat[data-out='true'] { background: var(--surface-2); }
|
||||
.ty-seat .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
|
||||
.ty-seat .sc { font-weight: 900; font-variant-numeric: tabular-nums; }
|
||||
.ty-bar { grid-column: 1 / -1; height: 8px; border-radius: 99px; background: var(--surface-2); overflow: hidden; }
|
||||
.ty-bar i { display: block; height: 100%; border-radius: 99px; background: var(--primary); transition: width .25s ease-out; }
|
||||
.ty-bar i[data-s='done'] { background: var(--success); }
|
||||
.ty-bar i[data-s='out'] { background: var(--border); }
|
||||
.ty-hearts { color: var(--danger); letter-spacing: 1px; }
|
||||
.ty-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
||||
.ty-table th, .ty-table td { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border); font-size: .92rem; }
|
||||
.ty-table td.n { text-align: right; }
|
||||
@keyframes ty-shake { 0%,100% { transform: translateX(0); } 25% { transform: translateX(-6px); } 75% { transform: translateX(6px); } }
|
||||
@keyframes ty-pop { from { transform: scale(.9); opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ty-input[data-shake='true'], .ty-banner { animation: none; } .ty-bar i { transition: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- text marks
|
||||
|
||||
function Target({ text, typed }: { text: string; typed: string }) {
|
||||
const { marks: m, extra } = marks(text, typed);
|
||||
const at = Math.min([...typed.replace(/^\s+/, '')].length, m.length);
|
||||
return (
|
||||
<div className="ty-target" aria-hidden>
|
||||
{[...text].map((ch, i) => (
|
||||
<span key={i} className={`${m[i]}${i === at ? ' cur' : ''}`}>
|
||||
{ch === ' ' && m[i] === 'bad' ? '␣' : ch}
|
||||
</span>
|
||||
))}
|
||||
{extra > 0 && <span className="extra">+{extra}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Typed in the wrong keyboard language (한/영). */
|
||||
const wrongLang = (lang: 'ko' | 'en', typed: string) => (lang === 'ko' ? /[a-zA-Z]{2,}/.test(typed) : /[ㄱ-ㅎㅏ-ㅣ가-힣]/.test(typed));
|
||||
|
||||
// ---------------------------------------------------------------- live progress (streamed)
|
||||
|
||||
type Live = Record<string, { round: number; item: number; n: number; of: number }>;
|
||||
|
||||
function useLiveProgress(round: number): Live {
|
||||
const [live, setLive] = useState<Live>({});
|
||||
useEffect(() => setLive({}), [round]);
|
||||
useEffect(
|
||||
() =>
|
||||
socket.subscribe((m: ServerMessage) => {
|
||||
if (m.t !== 'stream') return;
|
||||
const evs = (m.events as { type?: string; player?: string; item?: number; n?: number; of?: number }[]).filter((e) => e.type === 'progress' && e.player);
|
||||
if (!evs.length) return;
|
||||
setLive((cur) => {
|
||||
const next = { ...cur };
|
||||
for (const e of evs) next[e.player!] = { round, item: e.item ?? 0, n: e.n ?? 0, of: e.of ?? 1 };
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
[round],
|
||||
);
|
||||
return live;
|
||||
}
|
||||
|
||||
/** A seat's progress on its current item, 0..1: the latest streamed value when it is about the same item. */
|
||||
function progOf(s: SeatView, v: TypingView, live: Live): number {
|
||||
if (v.flow === 'shared' ? s.solved : s.finished) return 1;
|
||||
const l = live[s.id];
|
||||
const idx = v.flow === 'shared' ? v.cur : s.idx;
|
||||
if (l && l.round === v.round && l.item === idx) return Math.min(1, l.n / Math.max(1, l.of));
|
||||
return s.prog;
|
||||
}
|
||||
|
||||
/** Whole-round bar for lanes with a fixed number of items; the current item otherwise. */
|
||||
function barOf(s: SeatView, v: TypingView, live: Live): number {
|
||||
const p = progOf(s, v, live);
|
||||
if (v.flow === 'lane' && v.total) return s.finished ? 1 : Math.min(1, (s.done + p) / v.total);
|
||||
return p;
|
||||
}
|
||||
|
||||
function Hearts({ n, max }: { n: number; max: number }) {
|
||||
return (
|
||||
<span className="ty-hearts" aria-label={`목숨 ${n}개`}>
|
||||
{'♥'.repeat(Math.max(0, n))}
|
||||
<span style={{ opacity: 0.25 }}>{'♥'.repeat(Math.max(0, max - n))}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Seats({ v, me, players, live }: { v: TypingView; me: string | null; players: Record<string, PublicUser>; live: Live }) {
|
||||
const surv = v.options.mode === 'survival';
|
||||
const lives = surv && v.options.elimination === 'wrong';
|
||||
const unit = v.options.mode === 'first' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<ul className="ty-seats" aria-label="참가자">
|
||||
{v.seats.map((s) => {
|
||||
const out = !s.alive && v.phase === 'playing';
|
||||
const bar = barOf(s, v, live);
|
||||
const state = out ? 'out' : (v.flow === 'shared' ? s.solved : s.finished) ? 'done' : '';
|
||||
const tag = s.left ? '나감' : out ? `탈락 · ${OUT_KO[s.outReason ?? ''] ?? ''}` : v.flow === 'shared' && s.solved ? '✓ 쳤어요' : s.finished && v.phase === 'playing' ? '✓ 다 쳤어요' : '';
|
||||
return (
|
||||
<li key={s.id} className="ty-seat" data-me={s.id === me} data-out={out || s.left}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span className="nm">
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{tag && <span className="small muted"> · {tag}</span>}
|
||||
</span>
|
||||
<span className="sc">
|
||||
{lives && s.alive && <Hearts n={s.lives} max={v.options.lives} />} {practice ? `${s.roundKpm}타` : `${s.points}${unit}`}
|
||||
</span>
|
||||
<span className="ty-bar" role="progressbar" aria-label={`${nick(players, s.id)} 진행`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(bar * 100)}>
|
||||
<i data-s={state} style={{ width: `${Math.round(bar * 100)}%` }} />
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function RoundTable({ r, players, mode }: { r: RoundResult; players: Record<string, PublicUser>; mode: Mode }) {
|
||||
return (
|
||||
<table className="ty-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>순위</th>
|
||||
<th>이름</th>
|
||||
<th className="n">{mode === 'first' ? '먼저 친 문제' : mode === 'survival' ? '친 문제' : '친 줄'}</th>
|
||||
<th className="n">타수</th>
|
||||
<th className="n">정확도</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{r.rows.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td>
|
||||
{row.rank}등{r.winners.includes(row.id) ? ' 🏆' : ''}
|
||||
</td>
|
||||
<td>
|
||||
{nick(players, row.id)}
|
||||
{row.out && row.out !== 'left' ? <span className="small muted"> · 탈락</span> : row.out === 'left' ? <span className="small muted"> · 나감</span> : null}
|
||||
</td>
|
||||
<td className="n">{row.done}</td>
|
||||
<td className="n">{row.kpm}타</td>
|
||||
<td className="n">{row.acc}%</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
const now = useServerNow(200);
|
||||
const live = useLiveProgress(v.round);
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const shared = v.flow === 'shared';
|
||||
const [typed, setTyped] = useState('');
|
||||
const [shake, setShake] = useState(false);
|
||||
const [note, setNote] = useState<{ key: number; text: string; bad: boolean } | null>(null);
|
||||
// Lanes: the line I have sent but the server has not confirmed yet (so the next line shows at once).
|
||||
const [sent, setSent] = useState<{ round: number; idx: number } | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const composing = useRef(false);
|
||||
const enterAfterCompose = useRef(false);
|
||||
const lastSubmit = useRef(0);
|
||||
const lastProgress = useRef({ at: 0, text: '' });
|
||||
const seq = useRef(0);
|
||||
const passageRef = useRef<HTMLOListElement>(null);
|
||||
|
||||
const serverIdx = mine ? (shared ? v.cur : mine.idx) : 0;
|
||||
const myIdx = !shared && sent && sent.round === v.round && sent.idx >= serverIdx ? sent.idx + 1 : serverIdx;
|
||||
const item = v.upcoming.find((u) => u.idx === myIdx) ?? null;
|
||||
const following = shared ? [] : v.upcoming.filter((u) => u.idx > myIdx).slice(0, 2);
|
||||
const laneDone = !shared && v.total !== null && myIdx >= v.total;
|
||||
const canType = !!mine && mine.alive && !mine.left && v.phase === 'playing' && !!item && !(shared && mine.solved) && !(!shared && (mine.finished || laneDone));
|
||||
const itemKey = `${v.round}:${myIdx}`;
|
||||
const practice = v.options.mode === 'practice';
|
||||
// When the current item's clock started (연습: at its first key, 0 = not yet).
|
||||
const startedAt = useRef<{ key: string; at: number }>({ key: '', at: 0 });
|
||||
if (startedAt.current.key !== itemKey && item) startedAt.current = { key: itemKey, at: practice ? 0 : shared ? Math.max(v.curAt, now) : now };
|
||||
|
||||
// A new item: empty box, focus on it.
|
||||
useEffect(() => {
|
||||
setTyped('');
|
||||
lastProgress.current = { at: 0, text: '' };
|
||||
if (canType) inputRef.current?.focus({ preventScroll: true });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [itemKey, canType]);
|
||||
useEffect(() => setSent(null), [v.round]);
|
||||
// Long texts: keep the line I am on in the middle of the passage box.
|
||||
useEffect(() => {
|
||||
const ol = passageRef.current;
|
||||
const li = ol?.querySelector<HTMLElement>('li[data-s="cur"]');
|
||||
if (ol && li) ol.scrollTop = Math.max(0, li.offsetTop - ol.offsetTop - ol.clientHeight / 2 + li.clientHeight / 2);
|
||||
}, [myIdx, v.passage]);
|
||||
// A refused line (too fast, time over): back to what the server has.
|
||||
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setSent(null)), []);
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(false), 400);
|
||||
return () => clearTimeout(t);
|
||||
}, [shake]);
|
||||
useEffect(() => {
|
||||
if (!note) return;
|
||||
const t = setTimeout(() => setNote(null), 1600);
|
||||
return () => clearTimeout(t);
|
||||
}, [note]);
|
||||
|
||||
// What happened: first typist, wrong answers, people knocked out, my lines.
|
||||
const lastKey = v.last ? `${v.round}:${v.cur}:${v.last.winner}:${v.last.out.join(',')}` : '';
|
||||
const heardLast = useRef(lastKey);
|
||||
useEffect(() => {
|
||||
if (!v.last || heardLast.current === lastKey) return;
|
||||
heardLast.current = lastKey;
|
||||
if (v.last.winner === me) tySound.first();
|
||||
else if (me && v.last.out.includes(me)) tySound.out();
|
||||
else if (v.last.winner) tySound.wrong();
|
||||
}, [lastKey, v.last, me]);
|
||||
|
||||
const sendProgress = (text: string, force = false) => {
|
||||
if (!item) return;
|
||||
const t = Date.now();
|
||||
if (!force && t - lastProgress.current.at < PROGRESS_MS) return;
|
||||
if (text === lastProgress.current.text) return;
|
||||
lastProgress.current = { at: t, text };
|
||||
act({ type: 'progress', item: item.idx, text: text.slice(0, 400) });
|
||||
};
|
||||
// Throttled progress also goes out when typing pauses.
|
||||
useEffect(() => {
|
||||
if (!canType || !typed) return;
|
||||
const t = setTimeout(() => sendProgress(typed, true), PROGRESS_MS);
|
||||
return () => clearTimeout(t);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [typed, canType]);
|
||||
|
||||
const submit = (raw: string) => {
|
||||
if (!canType || !item) return;
|
||||
const t = Date.now();
|
||||
if (t - lastSubmit.current < 150) return; // Enter that the IME reported twice
|
||||
const text = raw.slice(0, 400);
|
||||
if (!normalize(text)) return;
|
||||
lastSubmit.current = t;
|
||||
const right = normalize(text) === normalize(item.text);
|
||||
act({ type: 'submit', item: item.idx, text });
|
||||
if (shared) {
|
||||
if (right) {
|
||||
tySound.right();
|
||||
haptic(15);
|
||||
setTyped('');
|
||||
} else {
|
||||
tySound.wrong();
|
||||
haptic([40, 30, 40]);
|
||||
setShake(true);
|
||||
++seq.current;
|
||||
const surv = v.options.mode === 'survival' && v.options.elimination === 'wrong';
|
||||
setNote({ key: seq.current, text: surv ? '틀렸어요! 목숨 하나를 잃었어요' : '틀린 곳이 있어요. 빨간 글자를 고쳐요', bad: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Lane: the line goes in as typed; the next one shows right away.
|
||||
if (right) tySound.right();
|
||||
else tySound.wrong();
|
||||
setSent({ round: v.round, idx: item.idx });
|
||||
setTyped('');
|
||||
};
|
||||
|
||||
const onKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
// Enter while a syllable is being composed: the IME finishes it first, then the line goes.
|
||||
if (e.nativeEvent.isComposing || composing.current || e.keyCode === 229) {
|
||||
enterAfterCompose.current = true;
|
||||
return;
|
||||
}
|
||||
submit(e.currentTarget.value);
|
||||
};
|
||||
const onSubmitForm = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!composing.current) submit(inputRef.current?.value ?? typed);
|
||||
};
|
||||
|
||||
// Clocks.
|
||||
const countdown = v.phase === 'countdown' && v.phaseEndsAt ? Math.max(1, Math.ceil((v.phaseEndsAt - now) / 1000)) : 0;
|
||||
const gap = shared && v.phase === 'playing' && !item && now < v.curAt;
|
||||
const clockEnd = v.phase !== 'playing' ? null : shared ? (item ? v.curEndsAt : null) : v.options.mode === 'survival' ? v.nextCutAt : v.roundEndsAt;
|
||||
const left = clockEnd === null ? null : clockEnd - now;
|
||||
const heard = useRef({ countdown: 0, warn: 0 });
|
||||
const warnSec = left !== null && left > 0 && left <= 5000 ? secs(left) : 0;
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) tySound.count();
|
||||
else if (was.countdown > 0) tySound.go();
|
||||
}
|
||||
if (warnSec && warnSec !== was.warn && canType) sfx.tick();
|
||||
heard.current = { countdown, warn: warnSec };
|
||||
});
|
||||
|
||||
const ck = item ? correctKeys(item.text, typed) : 0;
|
||||
const elapsed = item && startedAt.current.at ? Math.max(0, now - startedAt.current.at) : 0;
|
||||
const curKpm = typed && elapsed > 500 ? kpm(ck, elapsed) : 0;
|
||||
const langWarn = typed.length >= 2 && wrongLang(v.options.lang, typed);
|
||||
const surv = v.options.mode === 'survival';
|
||||
const roundLabel = practice ? null : `라운드 ${v.round}/${v.options.rounds}`;
|
||||
// 연습: how long I have been at it (like 한컴 타자연습's 경과 시간).
|
||||
const spent = practice && v.phase === 'playing' && mine && !mine.finished && !laneDone ? Math.max(0, now - v.roundStartedAt) : null;
|
||||
const progressPct = v.total ? Math.round((Math.min(myIdx, v.total) / v.total) * 100) : 0;
|
||||
const itemLabel = shared ? (v.total ? `${Math.min(v.cur + 1, v.total)}/${v.total}번째` : `${v.cur + 1}번째`) : v.total ? `${Math.min(myIdx + 1, v.total)}/${v.total}줄` : `${myIdx + 1}번째 줄`;
|
||||
const lastRound = v.rounds.at(-1);
|
||||
const alive = v.seats.filter((s) => s.alive).length;
|
||||
|
||||
let banner: { text: string; bad: boolean } | null = null;
|
||||
if (v.phase === 'playing' && shared && !item && v.last) {
|
||||
const w = v.last.winner;
|
||||
const outs = v.last.out.map((p) => (p === me ? '나' : `${nick(players, p)}님`));
|
||||
if (w) banner = { text: `${w === me ? '내가' : `${nick(players, w)}님이`} 먼저 쳤어요! ${v.last.kpm}타`, bad: false };
|
||||
else if (outs.length) banner = { text: `${outs.join(', ')} 탈락!`, bad: true };
|
||||
else banner = { text: v.options.mode === 'first' ? '시간 끝! 아무도 못 쳤어요' : '다음 문제!', bad: v.options.mode === 'first' };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ty">
|
||||
<style>{CSS}</style>
|
||||
<div className="ty-top">
|
||||
{roundLabel && <span className="ty-pill">{roundLabel}</span>}
|
||||
<span className="ty-pill">{MODE_KO[v.options.mode]}</span>
|
||||
{v.phase === 'playing' && <span className="ty-pill">{itemLabel}</span>}
|
||||
{surv && v.phase === 'playing' && <span className="ty-pill">남은 사람 {alive}명</span>}
|
||||
{left !== null && (
|
||||
<span className={`ty-pill ${left <= 5000 ? 'warn' : ''}`} aria-label={`남은 시간 ${secs(left)}초`}>
|
||||
⏱ {surv && !shared ? `탈락까지 ${clock(left)}` : clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{spent !== null && (
|
||||
<span className="ty-pill" aria-label={`걸린 시간 ${clock(spent)}`}>
|
||||
⏱ {clock(spent)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ty-card">
|
||||
{v.passage && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
<div className="ty-topic">
|
||||
{v.passageTitle}
|
||||
{v.passageBy ? ` · ${v.passageBy}` : ''}
|
||||
</div>
|
||||
<ol className="ty-passage" aria-label="긴글 전체" ref={passageRef}>
|
||||
{v.passage.map((l, i) => (
|
||||
<li key={i} data-s={i < myIdx ? 'done' : i === myIdx ? 'cur' : ''}>
|
||||
{l}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
{item && !v.passage && <div className="ty-topic">{TOPIC_BY_ID[item.topic]?.name ?? ''}</div>}
|
||||
{item ? (
|
||||
<>
|
||||
<p className="sr-only">칠 글: {item.text}</p>
|
||||
<Target text={item.text} typed={canType ? typed : ''} />
|
||||
</>
|
||||
) : (
|
||||
<div className="ty-target" style={{ color: 'var(--text-sub)', fontSize: '1.15rem' }}>
|
||||
{v.phase === 'ended'
|
||||
? practice
|
||||
? '연습 끝!'
|
||||
: '게임 끝!'
|
||||
: v.phase === 'countdown'
|
||||
? '곧 시작해요!'
|
||||
: gap
|
||||
? '다음 문제가 곧 나와요…'
|
||||
: v.phase === 'roundEnd'
|
||||
? '라운드 끝!'
|
||||
: !mine
|
||||
? '관전 중이에요 · 아래에서 진행을 볼 수 있어요'
|
||||
: mine.left
|
||||
? '게임에서 나갔어요'
|
||||
: !mine.alive
|
||||
? '탈락했어요. 다음 라운드를 기다려요'
|
||||
: laneDone || mine.finished
|
||||
? '다 쳤어요! 다른 사람을 기다려요'
|
||||
: ''}
|
||||
</div>
|
||||
)}
|
||||
{following.map((u) => (
|
||||
<div key={u.idx} className="ty-next" aria-hidden>
|
||||
{u.text}
|
||||
</div>
|
||||
))}
|
||||
{banner && (
|
||||
<div key={lastKey} className={`ty-banner ${banner.bad ? 'bad' : ''}`} role="status">
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
{mine && !mine.left && v.phase !== 'ended' && (
|
||||
<form className="ty-form" onSubmit={onSubmitForm} autoComplete="off">
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="input ty-input"
|
||||
data-shake={shake}
|
||||
value={typed}
|
||||
disabled={!canType}
|
||||
lang={v.options.lang === 'ko' ? 'ko' : 'en'}
|
||||
inputMode="text"
|
||||
enterKeyHint="send"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
maxLength={400}
|
||||
aria-label={item ? `여기에 쳐요: ${item.text}` : '입력 칸'}
|
||||
placeholder={canType ? '위의 글을 그대로 치고 Enter' : ''}
|
||||
onChange={(e) => {
|
||||
const t = e.target.value;
|
||||
if (t.length > typed.length && !composing.current) tySound.key();
|
||||
if (practice && !startedAt.current.at && normalize(t)) startedAt.current.at = socket.now();
|
||||
setTyped(t);
|
||||
sendProgress(t);
|
||||
}}
|
||||
onCompositionStart={() => {
|
||||
composing.current = true;
|
||||
}}
|
||||
onCompositionEnd={(e) => {
|
||||
composing.current = false;
|
||||
const el = e.currentTarget;
|
||||
if (enterAfterCompose.current) {
|
||||
enterAfterCompose.current = false;
|
||||
setTimeout(() => submit(el.value), 0);
|
||||
}
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
onPaste={(e) => e.preventDefault()}
|
||||
onDrop={(e) => e.preventDefault()}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={!canType} onPointerDown={(e) => e.preventDefault()} onMouseDown={(e) => e.preventDefault()}>
|
||||
입력
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{langWarn && <div className="ty-warn">{v.options.lang === 'ko' ? '한/영 키를 눌러 한글로 바꿔 주세요' : 'Press the 한/영 key to type in English (영어로 바꿔 주세요)'}</div>}
|
||||
{note && (
|
||||
<div key={note.key} className={`ty-banner ${note.bad ? 'bad' : ''}`} role="alert">
|
||||
{note.text}
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>진행 {progressPct}%</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'ended' && practice && (
|
||||
<div className="ty-stats" role="status" style={{ fontSize: '1.05rem' }}>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>
|
||||
{mine.done}줄 중 틀린 줄 {mine.wrong}개
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && !practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>이번 라운드 {mine.roundKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
{mine.wrong > 0 && <span>틀림 {mine.wrong}번</span>}
|
||||
{item && <span>{keyCount(item.text)}타짜리</span>}
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="ty-over" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>
|
||||
{v.round > 1 && !practice ? `라운드 ${v.round} · ` : ''}
|
||||
{CATEGORY_KO[v.options.category]} · {MODE_KO[v.options.mode]}
|
||||
</small>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{v.phase === 'roundEnd' && lastRound && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }} role="status">
|
||||
<strong>
|
||||
라운드 {lastRound.round} 결과 · {lastRound.summary}
|
||||
</strong>
|
||||
<RoundTable r={lastRound} players={players} mode={v.options.mode} />
|
||||
{v.phaseEndsAt && <span className="small muted">{secs(v.phaseEndsAt - now)}초 뒤 다음 라운드</span>}
|
||||
</div>
|
||||
)}
|
||||
<Seats v={v} me={me} players={players} live={live} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function TypingSide({ view: v, players }: BoardProps<TypingView>) {
|
||||
const rows = [...v.seats].sort((a, b) => Number(a.left) - Number(b.left) || b.points - a.points || b.kpm - a.kpm);
|
||||
const unit = v.options.mode === 'first' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>타자 대결{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rows.map((s, i) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.left ? 0.6 : 1 }}>
|
||||
<span style={{ width: 22, fontWeight: 800 }}>{i + 1}</span>
|
||||
<Avatar user={userOf(players, s.id)} size={22} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 600 }}>
|
||||
{nick(players, s.id)}
|
||||
{s.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
<span className="small muted" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.kpm}타 · {s.tried ? `${s.acc}%` : '-'}
|
||||
</span>
|
||||
{!practice && (
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.points}
|
||||
{unit}
|
||||
</strong>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.rounds.length > 0 && (
|
||||
<details className="card" style={{ padding: 12 }} open={v.phase === 'ended'}>
|
||||
<summary style={{ fontWeight: 800, cursor: 'pointer' }}>라운드 기록 ({v.rounds.length})</summary>
|
||||
<div className="stack" style={{ gap: 10, marginTop: 8 }}>
|
||||
{v.rounds.map((r) => (
|
||||
<div key={r.round} className="stack" style={{ gap: 4 }}>
|
||||
<span className="small" style={{ fontWeight: 700 }}>
|
||||
{practice ? '연습 기록' : `라운드 ${r.round} · ${r.winners.length ? r.winners.map((w) => nick(players, w)).join(', ') : '승자 없음'}`}
|
||||
</span>
|
||||
<RoundTable r={r} players={players} mode={v.options.mode} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
<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">
|
||||
{' '}
|
||||
· {practice ? '' : `${r.points}${unit} · `}평균 {r.kpm}타 · 정확도 {r.acc}%{r.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: TypingView, me: string | null): boolean {
|
||||
const s = v.seats.find((x) => x.id === me);
|
||||
if (!s || v.phase !== 'playing' || !s.alive) return false;
|
||||
return v.flow === 'shared' ? v.upcoming.length > 0 && !s.solved : !s.finished;
|
||||
}
|
||||
|
||||
function statusText(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return `${v.options.mode === 'practice' ? '연습' : `라운드 ${v.round}`} 곧 시작! 나오는 글을 그대로 쳐요`;
|
||||
if (v.phase === 'roundEnd') return v.rounds.at(-1)?.summary ?? '라운드 끝';
|
||||
const s = v.seats.find((x) => x.id === me);
|
||||
if (!s) return v.options.mode === 'practice' ? MODE_KO.practice : `${MODE_KO[v.options.mode]} · 라운드 ${v.round}/${v.options.rounds}`;
|
||||
if (s.left) return '게임에서 나갔어요';
|
||||
if (!s.alive) return '탈락했어요 · 다음 라운드를 기다려요';
|
||||
if (v.flow === 'shared') {
|
||||
if (!v.upcoming.length) return v.last?.winner ? `${v.last.winner === me ? '내가' : `${nick(players, v.last.winner)}님이`} 먼저 쳤어요!` : '다음 문제가 곧 나와요';
|
||||
if (s.solved) return '쳤어요! 다른 사람을 기다려요';
|
||||
return v.options.mode === 'first' ? '가장 먼저 정확하게 치면 1점!' : '제한 시간 안에 정확하게 쳐요!';
|
||||
}
|
||||
if (s.finished) return '다 쳤어요! 다른 사람을 기다려요';
|
||||
return v.options.mode === 'timeAttack' ? '시간 안에 최대한 많이 쳐요!' : v.options.mode === 'practice' ? '한 줄씩 치고 Enter! 천천히 정확하게 연습해요' : '한 줄씩 치고 Enter!';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label} style={{ flexWrap: 'wrap' }}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MODE_HELP: Record<Mode, string> = {
|
||||
first: '모두에게 같은 글이 나오고, 가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 고쳐서 다시 쳐요.',
|
||||
survival: '같은 글을 모두 함께 치고, 탈락 조건에 걸리면 빠져요. 끝까지 남은 사람이 라운드 1점. 문제마다 제한 시간이 조금씩 줄어요.',
|
||||
speed: '각자 자기 속도로 글을 치고, 라운드의 타수(1분에 친 타 수, 오타는 빼고)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 글을 치고, 정확도가 가장 높은 사람이 1점이에요. 정확도가 같으면 타수가 높은 사람이 이겨요.',
|
||||
timeAttack: '정해진 시간 동안 끝없이 나오는 글을 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '한컴 타자연습처럼 혼자(또는 함께) 제 속도로 연습해요. 제한 시간과 점수 없이 짧은글은 10문장, 단어는 20개, 긴글은 한 편을 처음부터 끝까지 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
const ELIM_HELP: Record<Elim, string> = {
|
||||
wrong: '틀린 채로 Enter를 누르거나 시간 안에 못 치면 목숨이 하나 줄고, 목숨을 다 쓰면 탈락해요.',
|
||||
sentence: '문장마다 가장 늦게 친 한 사람이 탈락해요.',
|
||||
interval: '모두 각자 치다가, 정해진 시간마다 그때까지 가장 적게 친 사람이 탈락해요.',
|
||||
deadline: '문장마다 제한 시간 안에 못 친 사람은 모두 탈락해요.',
|
||||
};
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
|
||||
const set = (p: Partial<TypingOptions>) => onChange({ ...o, ...p });
|
||||
const topics = topicsFor(o.lang, o.category);
|
||||
const picked = o.topics.filter((t) => topics.some((x) => x.id === t));
|
||||
const toggle = (id: string) => {
|
||||
const others = o.topics.filter((t) => !topics.some((x) => x.id === t));
|
||||
const next = picked.includes(id) ? picked.filter((t) => t !== id) : [...picked, id];
|
||||
set({ topics: [...others, ...next] });
|
||||
};
|
||||
const timeLabel = o.mode === 'speed' || o.mode === 'accuracy' ? '라운드 제한 시간' : '한 문제 제한 시간';
|
||||
const practice = o.mode === 'practice';
|
||||
const showTime = o.mode !== 'timeAttack' && !practice && !(o.mode === 'survival' && o.elimination === 'interval');
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>언어</strong>
|
||||
<Seg label="언어" value={o.lang} options={[['ko', LANG_KO.ko], ['en', LANG_KO.en]]} onChange={(lang) => set({ lang })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>대결 방식</strong>
|
||||
<Seg label="대결 방식" value={o.mode} options={(Object.keys(MODE_KO) as Mode[]).map((m) => [m, MODE_KO[m]])} onChange={(mode) => set({ mode })} />
|
||||
<span className="small muted">{MODE_HELP[o.mode]}</span>
|
||||
</div>
|
||||
{o.mode === 'survival' && (
|
||||
<div className="stack" style={{ gap: 6, paddingLeft: 10, borderLeft: '3px solid var(--border)' }}>
|
||||
<strong>탈락 조건</strong>
|
||||
<Seg label="탈락 조건" value={o.elimination} options={(Object.keys(ELIM_KO) as Elim[]).map((m) => [m, ELIM_KO[m].replace(/\(.*\)/, '')])} onChange={(elimination) => set({ elimination })} />
|
||||
<span className="small muted">{ELIM_HELP[o.elimination]}</span>
|
||||
{o.elimination === 'wrong' && (
|
||||
<>
|
||||
<strong>목숨</strong>
|
||||
<Seg label="목숨" value={o.lives} options={[1, 2, 3, 4, 5].map((n) => [n, `${n}개`] as [number, string])} onChange={(lives) => set({ lives })} />
|
||||
</>
|
||||
)}
|
||||
{o.elimination === 'interval' && (
|
||||
<>
|
||||
<strong>탈락 간격</strong>
|
||||
<Seg label="탈락 간격" value={o.intervalSec} options={([10, 15, 20, 30] as const).map((n) => [n, `${n}초`] as [typeof n, string])} onChange={(intervalSec) => set({ intervalSec })} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{practice ? '연습 종목' : '대결 종목'}</strong>
|
||||
<Seg label={practice ? '연습 종목' : '대결 종목'} value={o.category} options={(['word', 'short', 'long'] as Category[]).map((c) => [c, CATEGORY_KO[c]])} onChange={(category) => set({ category })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>주제 (여러 개 고를 수 있어요)</strong>
|
||||
<div className="segmented" role="group" aria-label="주제" style={{ flexWrap: 'wrap' }}>
|
||||
<button type="button" aria-pressed={picked.length === 0} onClick={() => set({ topics: o.topics.filter((t) => !topics.some((x) => x.id === t)) })}>
|
||||
전체
|
||||
</button>
|
||||
{topics.map((t) => (
|
||||
<button key={t.id} type="button" aria-pressed={picked.includes(t.id)} onClick={() => toggle(t.id)}>
|
||||
{t.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="small muted">
|
||||
{picked.length === 0 ? `전체 ${topics.length}개 주제에서 골고루 나와요.` : `${picked.map((id) => topics.find((t) => t.id === id)?.name).join(', ')}에서 나와요.`}
|
||||
{o.category === 'long' ? (practice ? ' 연습은 그중 한 편을 처음부터 끝까지 쳐요.' : ' 긴글은 라운드마다 한 단락(8줄 안팎)씩 이어서 쳐요.') : ''}
|
||||
</span>
|
||||
</div>
|
||||
{!practice && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>라운드</strong>
|
||||
<Seg label="라운드" value={o.rounds} options={Array.from({ length: 10 }, (_, i) => [i + 1, `${i + 1}`] as [number, string])} onChange={(rounds) => set({ rounds })} />
|
||||
</div>
|
||||
)}
|
||||
{showTime && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{timeLabel}</strong>
|
||||
<select
|
||||
className="input"
|
||||
aria-label={timeLabel}
|
||||
style={{ maxWidth: 260 }}
|
||||
value={o.timeLimit === null ? 'null' : String(o.timeLimit)}
|
||||
onChange={(e) => set({ timeLimit: (e.target.value === 'null' ? null : Number(e.target.value)) as TypingOptions['timeLimit'] })}
|
||||
>
|
||||
<option value="0">자동(글 길이에 맞게)</option>
|
||||
{[10, 20, 30, 60, 120, 180, 300].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n < 60 ? `${n}초` : `${n / 60}분`}
|
||||
</option>
|
||||
))}
|
||||
<option value="null">{o.mode === 'survival' ? '무제한(서바이벌은 자동으로 해요)' : '무제한'}</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{o.mode === 'timeAttack' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>타임어택 시간</strong>
|
||||
<Seg label="타임어택 시간" value={o.attackSec} options={([30, 60, 90, 120] as const).map((n) => [n, n < 60 ? `${n}초` : n === 90 ? '1분 30초' : `${n / 60}분`] as [typeof n, string])} onChange={(attackSec) => set({ attackSec })} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: TypingOptions): string {
|
||||
const topics = topicsFor(o.lang, o.category);
|
||||
const picked = topics.filter((t) => o.topics.includes(t.id)).map((t) => t.name);
|
||||
const sub = o.mode === 'survival' ? `(${ELIM_KO[o.elimination].replace(/\(.*\)/, '')}${o.elimination === 'wrong' ? ` · 목숨 ${o.lives}` : ''})` : '';
|
||||
return `${LANG_KO[o.lang]} · ${MODE_KO[o.mode]}${sub} · ${CATEGORY_KO[o.category]}(${picked.length ? picked.join(', ') : '전체 주제'})${o.mode === 'practice' ? '' : ` · ${o.rounds}라운드`}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules({ options: o }: { options?: TypingOptions }) {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
모두에게 <strong>같은 글</strong>이 나와요. 입력 칸에 그대로 치고 <strong>Enter</strong>를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 쓸 수 없어요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>타수</strong>는 1분 동안 친 자판 수예요(두벌식: "강" = ㄱ·ㅏ·ㅇ 3타, "과" = ㄱ·ㅗ·ㅏ 3타). 틀린 만큼은 빼고 세요. <strong>정확도</strong>는 글과 얼마나 똑같이 쳤는지예요.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>가장 먼저 입력</strong>: 같은 글을 동시에 치고, 가장 먼저 정확하게 친 사람이 1점. 단어는 한 라운드에 10개, 짧은글은 5문장, 긴글은 한 단락을 한 줄씩 겨뤄요.
|
||||
</li>
|
||||
<li>
|
||||
<strong>서바이벌</strong>: 탈락 조건 — 틀렸을 때(목숨, 기본 3개), 문장별(가장 늦게 친 사람), 시간별(정해진 시간마다 가장 적게 친 사람), 시간 초과(제한 시간 안에 못 친 사람). 끝까지 남으면 1점. 문제마다 제한 시간이 조금씩 줄어요. 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않아요.
|
||||
</li>
|
||||
<li>
|
||||
<strong>타수 비교</strong>: 각자 자기 속도로 치고, 라운드 타수가 가장 높은 사람이 1점.
|
||||
</li>
|
||||
<li>
|
||||
<strong>정확도 대결</strong>: 정확도가 가장 높은 사람이 1점(같으면 타수).
|
||||
</li>
|
||||
<li>
|
||||
<strong>타임어택</strong>: 정해진 시간 동안 끝없이 나오는 글을 쳐서, 정확하게 친 타 수가 가장 많은 사람이 1점.
|
||||
</li>
|
||||
<li>
|
||||
<strong>연습</strong>: 한컴 타자연습처럼 제한 시간·점수 없이 제 속도로 쳐요. 짧은글 10문장, 단어 20개, 긴글은 한 편 전체. 지금·평균·최고 타수, 정확도, 진행률과 걸린 시간을 보여 줘요.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
라운드는 1~10번(기본 3번)이에요. 모두 끝나면 점수가 가장 높은 사람이 이기고, 같으면 평균 타수가 높은 사람이 앞서요. 한국어·영어, 단어·짧은글·긴글과 주제(여러 개)를 방 설정에서 골라요. 혼자서도, 컴퓨터와도 할 수
|
||||
있어요.
|
||||
</p>
|
||||
{o && <p className="small muted">이 방: {optionsSummary(o)}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<TypingView, TypingOptions> = {
|
||||
Board: TypingBoard,
|
||||
Side: TypingSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
17
apps/web/src/games/typing/marks.ts
Normal file
17
apps/web/src/games/typing/marks.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** 타자 대결: how each letter of the text looks against what is typed (pure, for the screen and its tests). */
|
||||
import { toKeys } from '@bg/games/typing';
|
||||
|
||||
export type Mark = 'ok' | 'bad' | 'comp' | '';
|
||||
|
||||
/** How each letter of the target looks against what is typed: right, wrong, or the syllable still being composed. */
|
||||
export function marks(target: string, typed: string): { marks: Mark[]; extra: number } {
|
||||
const t = [...target];
|
||||
const y = [...typed.replace(/^\s+/, '')];
|
||||
const out: Mark[] = t.map(() => '');
|
||||
for (let i = 0; i < y.length && i < t.length; i++) {
|
||||
if (y[i] === t[i]) out[i] = 'ok';
|
||||
else if (i === y.length - 1 && toKeys(t.slice(i).join('')).startsWith(toKeys(y[i]!))) out[i] = 'comp';
|
||||
else out[i] = 'bad';
|
||||
}
|
||||
return { marks: out, extra: Math.max(0, y.length - t.length) };
|
||||
}
|
||||
99
apps/web/src/games/typing/quick.tsx
Normal file
99
apps/web/src/games/typing/quick.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
/** 타자 대결 30초 규칙 요약 (docs/07 §5). Simple redraws of the typing card. */
|
||||
import type { ReactNode } from 'react';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
function Frame({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<svg viewBox="0 0 240 150" width={240} height={150} aria-hidden>
|
||||
<rect x={0} y={0} width={240} height={150} rx={14} fill="#eef2ff" />
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** A text line where the first `ok` letters are green and letter `bad` (if any) is red. */
|
||||
function Line({ y, text, ok, bad = -1, size = 20 }: { y: number; text: string; ok: number; bad?: number; size?: number }) {
|
||||
const chars = [...text];
|
||||
const w = size * 0.95;
|
||||
const x0 = 120 - (chars.length * w) / 2;
|
||||
return (
|
||||
<>
|
||||
{chars.map((c, i) => (
|
||||
<g key={i}>
|
||||
{i === bad && <rect x={x0 + i * w - 1} y={y - size + 2} width={w} height={size + 4} rx={3} fill="#dc2626" />}
|
||||
<text x={x0 + i * w + w / 2} y={y} textAnchor="middle" fontSize={size} fontWeight={800} fill={i === bad ? '#fff' : i < ok ? '#16a34a' : '#1f2937'}>
|
||||
{c}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Box({ y, text }: { y: number; text: string }) {
|
||||
return (
|
||||
<>
|
||||
<rect x={20} y={y} width={200} height={32} rx={8} fill="#fff" stroke="#6366f1" strokeWidth={2} />
|
||||
<text x={30} y={y + 22} fontSize={15} fontWeight={700} fill="#1f2937">
|
||||
{text}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Bar({ y, name, frac, color }: { y: number; name: string; frac: number; color: string }) {
|
||||
return (
|
||||
<>
|
||||
<text x={20} y={y + 9} fontSize={12} fontWeight={700} fill="#374151">
|
||||
{name}
|
||||
</text>
|
||||
<rect x={70} y={y} width={150} height={10} rx={5} fill="#e5e7eb" />
|
||||
<rect x={70} y={y} width={150 * frac} height={10} rx={5} fill={color} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Line y={52} text="티끌 모아 태산." ok={4} />
|
||||
<Box y={80} text="티끌 모|" />
|
||||
</Frame>
|
||||
),
|
||||
alt: '위에 "티끌 모아 태산."이 있고, 아래 입력 칸에 "티끌 모"까지 쳤어요. 친 글자는 초록이에요',
|
||||
title: '나온 글을 그대로',
|
||||
text: '모두에게 같은 글이 나와요. 입력 칸에 그대로 치고 Enter! 맞은 글자는 초록, 틀린 글자는 빨강이에요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Bar y={34} name="호랑이" frac={1} color="#16a34a" />
|
||||
<Bar y={64} name="나" frac={0.7} color="#6366f1" />
|
||||
<Bar y={94} name="토끼" frac={0.4} color="#6366f1" />
|
||||
<text x={120} y={135} textAnchor="middle" fontSize={15} fontWeight={900} fill="#15803d">
|
||||
호랑이님이 먼저 쳤어요! 352타
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '세 사람의 진행 막대예요. 호랑이가 먼저 다 쳤어요',
|
||||
title: '빠르고 정확하게',
|
||||
text: '가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택 중에서 골라요. 다른 사람이 친 만큼 막대로 보여요. 혼자 연습하려면 연습!',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Line y={52} text="천 리 길도" ok={2} bad={2} size={22} />
|
||||
<text x={120} y={92} textAnchor="middle" fontSize={22} fill="#dc2626">
|
||||
♥♥♡
|
||||
</text>
|
||||
<text x={120} y={128} textAnchor="middle" fontSize={14} fontWeight={800} fill="#374151">
|
||||
라운드 1/3 · 평균 280타 · 정확도 97%
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '틀린 글자가 빨갛게 보이고, 목숨 하트 3개 중 1개가 비었어요',
|
||||
title: '라운드 점수로 승부',
|
||||
text: '서바이벌은 틀리면 목숨이 줄어요. 1~10라운드(기본 3) 점수를 모아 1등을 가려요. 혼자서도 OK!',
|
||||
},
|
||||
];
|
||||
@@ -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 }}>
|
||||
|
||||
@@ -35,6 +35,12 @@ export const GAME_ICON: Record<string, string> = {
|
||||
blackjack: '🂡',
|
||||
'six-nimmt': '🐮',
|
||||
gemblo: '💠',
|
||||
typing: '⌨️',
|
||||
minesweeper: '💣',
|
||||
shisen: '🀄',
|
||||
solitaire: '♥️',
|
||||
sudoku: '🧮',
|
||||
nonogram: '🧩',
|
||||
'hot-streak': '🏁',
|
||||
tichu: '🐉',
|
||||
'case-file': '🔍',
|
||||
@@ -48,5 +54,6 @@ export const UPCOMING: string[] = [];
|
||||
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo', 'castles-of-burgundy'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt', 'tichu'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'hot-streak', 'case-file'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'typing', 'hot-streak', 'case-file'] },
|
||||
{ key: 'solo', label: '혼자·퍼즐', ids: ['minesweeper', 'shisen', 'solitaire', 'sudoku', 'nonogram', 'apple', 'typing', 'yacht', 'blackjack', 'case-file', 'castles-of-burgundy'] },
|
||||
];
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -53,6 +53,12 @@
|
||||
| `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 |
|
||||
| `case-file` | 사건 파일 | 1~5 | 2026-10 새 게임 |
|
||||
| `castles-of-burgundy` | 버건디의 성 | 1~4 | 2026-10 새 게임 |
|
||||
| `typing` | 타자 대결 | 1~8 | 2026-11 새 게임 |
|
||||
| `minesweeper` | 지뢰찾기(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 |
|
||||
| `shisen` | 사천성(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 |
|
||||
| `solitaire` | 솔리테어(클론다이크·프리셀·스파이더, 같은 판 경주) | 1~8 | 2026-11 새 게임 |
|
||||
| `sudoku` | 스도쿠(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 |
|
||||
| `nonogram` | 네모네모 로직(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
67
docs/games/minesweeper.md
Normal file
67
docs/games/minesweeper.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# 지뢰찾기 (`minesweeper`)
|
||||
|
||||
> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 1~10분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 윈도우에 들어 있던 그 지뢰찾기. 숫자(주변 8칸의 지뢰 수)를 보고 지뢰가 없는 칸을 모두 연다.
|
||||
- 원작은 혼자 하는 기록 도전이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 판을 각자 풀고 가장 먼저 다 연 사람이 이긴다. 혼자서도 한다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `level` | 난이도 | 초급 9×9 지뢰 10 / 중급 16×16 지뢰 40 / 고급 16×30 지뢰 99 (윈도우와 같음) | 초급 |
|
||||
| `timeLimitSec` | 제한 시간 | 3분 / 5분 / 10분 / 20분 / 무제한 | 10분 |
|
||||
|
||||
## 3~4. 구성과 준비
|
||||
- 시드로 **시작 칸** 하나를 고르고, 그 칸과 둘레 8칸을 뺀 곳에 지뢰를 고르게 놓는다. 시작 칸은 0이라 둘레가 열린다.
|
||||
- 원작의 "첫 클릭에는 지뢰가 없게"를 같은 판 경주에 맞춘 것: 첫 클릭이 사람마다 다르면 판이 달라지므로, 대신 **모두에게 같은 곳이 열린 채로** 시작한다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 열기(`open`): 닫힌 칸, 깃발이 없을 때. 지뢰면 실패(`failed`), 0이면 이어진 0 영역과 그 둘레까지 연다.
|
||||
- 깃발(`flag`): 닫힌 칸에 꽂기/치우기. 깃발 칸은 열 수 없다.
|
||||
- 한꺼번에 열기(`chord`): 연 숫자 칸의 둘레 깃발 수 = 숫자이고 닫힌 칸이 남았을 때, 깃발 없는 둘레를 모두 연다. 깃발이 틀렸으면 지뢰가 터진다(원작과 같음).
|
||||
- 지뢰 없는 칸을 모두 열면 다 풂(`solved`). 깃발은 다 꽂지 않아도 된다.
|
||||
- 1초에 15번까지.
|
||||
|
||||
## 6. 승패
|
||||
- `race.md` §2. 진행도 = 연 칸 수, 진행 문구 `연 칸 N/전체 안전한 칸`. 지뢰를 밟은 사람도 그때까지 연 칸으로 순위에 든다(결과 ` · 지뢰를 밟았어요`).
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 없음. "추측 없이 풀리는 판"은 만들지 않았다(원작처럼 가끔 찍어야 할 때가 있다). 모두 같은 판이라 운은 공평하다.
|
||||
|
||||
## 8. 엔진 설계
|
||||
```ts
|
||||
puzzle: { rows, cols, mines, field: string /* '*' 또는 '0'..'8' */, start: number }
|
||||
board: { open: string /* '1' 연 칸 */, flags: string, opened: number, boom: number | null }
|
||||
view.board: { rows, cols, mines, cells: string, flags }
|
||||
// cells: '#' 닫힘, 'F' 깃발, '0'..'8' 연 칸, '!' 내가 밟은 지뢰; 게임이 끝나면(다 풀었으면 바로) '*' 지뢰, 'x' 잘못 꽂은 깃발
|
||||
```
|
||||
| type | payload | 검증 |
|
||||
|---|---|---|
|
||||
| `open` | `i`(칸 번호) | 닫힘, 깃발 아님 |
|
||||
| `flag` | `i` | 닫힘 |
|
||||
| `chord` | `i` | 연 숫자 칸, 둘레 깃발 = 숫자, 닫힌 둘레 있음 |
|
||||
| `stop`·`tick`·`leave` | — | 공통 틀 |
|
||||
- 랜덤: `setup`의 시작 칸·지뢰 배치만. 숨길 것: 끝나기 전에는 내 view에 지뢰 위치가 없다(테스트).
|
||||
|
||||
## 9. UI/UX
|
||||
- SVG 판(이미지 파일 없음). 닫힌 칸은 볼록한 회색, 연 칸은 흰색에 원작 색 숫자(1 파랑, 2 초록, 3 빨강…). 새로 열린 칸은 살짝 커지며 나타나고, 터진 지뢰는 빨간 칸.
|
||||
- PC: 왼쪽 클릭 열기(숫자 칸은 한꺼번에 열기), 오른쪽 클릭 깃발. 칸 최대 56px, 화면 높이에 맞춤.
|
||||
- 휴대폰: 누르기 = 열기, 길게 누르기(0.42초) = 깃발, 위의 [⛏ 칸 열기 / 🚩 깃발 꽂기] 버튼으로 바꿈. 고급(16×30)은 판을 세로로 돌려 16칸 폭으로 보여 주고 아래로 스크롤(드래그가 없어 `touch-action: manipulation`).
|
||||
- 키보드: 화살표, 스페이스/Enter 열기, F 깃발. 스크린리더는 칸 위치와 내용을 읽어 준다.
|
||||
- 위에 남은 지뢰(전체 − 내 깃발).
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 판: 난이도별 크기·지뢰 수, 시작 칸 둘레에 지뢰 없음, 숫자 = 둘레 지뢰 수, 같은 시드 = 같은 판, 모두 같은 시작
|
||||
- [x] 열기·0 이어 열기·깃발·한꺼번에 열기(틀린 깃발이면 터짐), 지뢰 → 실패·내 화면에만 지뢰 공개
|
||||
- [x] 다 풂 → 혼자면 끝, 순위(다 푼 사람 > 연 칸 많은 순, 같은 칸 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김, 속도 제한
|
||||
- [x] 무작위 대국(1·2·5·8명, 세 난이도), 컴퓨터(거절 0, 어려움이 쉬움보다 자주 풂), 방 통합(연습·끊김·무제한)
|
||||
- [x] E2E: PC 클릭·오른쪽 클릭, 휴대폰 탭·길게 누르기·깃발 모드, 같은 시작 판, 상대 진행 표시, 포기 → 결과
|
||||
|
||||
## 11. 참고
|
||||
- Microsoft Minesweeper(초급 9×9/10, 중급 16×16/40, 고급 30×16/99).
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 확실한 수 먼저: 둘레 깃발 = 숫자면 한꺼번에 열기, 닫힌 칸 수 = 남은 지뢰 수면 깃발. 강할수록 두 숫자를 비교하는 규칙(부분집합)도 자주 쓴다.
|
||||
- 확실한 수가 없으면 찍는다: 강하면 지뢰일 가능성이 가장 낮아 보이는 칸, 약하면 아무 칸이나.
|
||||
- 한 수에 레벨 1 약 3초 → 레벨 60 약 0.8초(찍을 때는 더 오래). 초급 20판에서 어려움 컴퓨터가 대부분 풀고 쉬움보다 자주 푼다(테스트).
|
||||
71
docs/games/nonogram.md
Normal file
71
docs/games/nonogram.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# 네모네모 로직 (`nonogram`)
|
||||
|
||||
> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 3~20분 · 난이도: 보통
|
||||
|
||||
## 1. 개요
|
||||
- 노노그램(Nonogram, 일본 이름 그림 로직). 줄마다 적힌 숫자대로 칸을 칠하면 그림이 나온다.
|
||||
- 원작은 혼자 푸는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 그림을 각자 풀고 가장 먼저 다 푼 사람이 이긴다. 혼자서도 한다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `size` | 크기 | 5×5 쉬움 / 10×10 보통 / 15×15 어려움 | 10×10 |
|
||||
| `hints` | 힌트 쓰기 | 켬 / 끔 | 켬 |
|
||||
| `timeLimitSec` | 제한 시간 | 5분 / 10분 / 20분 / 30분 / 무제한 | 20분 |
|
||||
|
||||
## 3~4. 구성과 준비
|
||||
- 그림은 손으로 그린 픽셀 그림(`packages/games/src/nonogram/bank.ts`, `#` 칠함 · `.` 빔): 5×5 11장, 10×10 15장, 15×15 11장. 하트·집·나무·우산·별·음표·컵·버섯·고양이·사과·물고기·오리·자동차·로켓·꽃 …
|
||||
- 모든 그림은 **답이 하나**이고 **줄 논리만으로** 끝까지 풀린다(아래 §8 줄 풀이를 모든 줄에 되풀이해 다 정해짐, 테스트). 빈 줄(숫자 0)은 없다.
|
||||
- 시드로 크기에 맞는 그림 하나를 고른다. 모두 빈 판으로 시작.
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 칠하기(`paint`): 한 줄(가로 또는 세로)에 있는 1~15칸을 한꺼번에 `0` 비움 / `1` 칠함 / `2` ✕로 바꾼다. 화면에서 끌기 한 번 = 한 수.
|
||||
- 맞았는지 틀렸는지는 알려 주지 않는다(원작과 같음). ✕는 표시일 뿐 답에 상관없다.
|
||||
- 힌트(`hint`, 켠 방만): 틀렸거나 아직 안 정한 칸 하나를 골라(시드 랜덤) 바른 상태로 바꾼다(칠할 칸은 칠함, 빈 칸은 ✕). 쓴 횟수가 결과에 ` · 힌트 N번`으로 붙는다.
|
||||
- 칠한 칸이 답과 똑같아지면 다 풂(`solved`). 1초에 12번까지.
|
||||
|
||||
## 6. 승패
|
||||
- `race.md` §2. 진행도 = **지금 칠한 칸이 숫자와 맞는 줄 수**(가로 + 세로), 진행 문구 `맞는 줄 N/전체`. 숫자만 보고 누구나 셀 수 있는 값이라 답을 알려 주지 않는다. 실패는 없다.
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 힌트(끌 수 있음). 원작에는 없지만 처음 하는 사람이 막히지 않게 넣었다. 대신 결과에 횟수를 남긴다.
|
||||
|
||||
## 8. 엔진 설계
|
||||
```ts
|
||||
puzzle: { size, name, color, solution: string /* '#' | '.' */, rows: number[][], cols: number[][] }
|
||||
board: { marks: string /* '0' | '1' | '2' */, hints: number, lastHint: number | null }
|
||||
view.board: { size, rows, cols, marks, hints, lastHint, answer: { solution, name, color } | null /* 내가 끝났거나 게임이 끝나면 */ }
|
||||
```
|
||||
| type | payload | 검증 |
|
||||
|---|---|---|
|
||||
| `paint` | `cells`(1~15칸), `value` 0/1/2 | 판 안, 겹치지 않음, 모두 한 가로줄 또는 한 세로줄, 바뀌는 칸이 있음 |
|
||||
| `hint` | — | 힌트를 켠 방 |
|
||||
| `stop`·`tick`·`leave` | — | 공통 틀 |
|
||||
- 줄 풀이(`solver.ts`): 한 줄의 숫자와 아는 칸으로 앞·뒤에서 DP를 돌려, 어떤 배치에서도 칠해지는 칸과 어떤 배치에서도 비는 칸을 정한다. `solveGrid`는 이것을 바뀐 줄마다 다시 돌려 더 정할 칸이 없을 때까지.
|
||||
- 랜덤: `setup`의 그림 고르기, 힌트 칸 고르기. 숨길 것: 끝내기 전에는 내 view·관전 view에 답 문자열과 그림 이름이 없다(테스트).
|
||||
|
||||
## 9. UI/UX
|
||||
- SVG 한 장: 위에 세로줄 숫자, 왼쪽에 가로줄 숫자, 그 안에 판(5칸마다 굵은 선). 숫자와 맞는 줄은 숫자가 흐려진다. 위 알약에 맞는 줄 수.
|
||||
- 끌기: 첫 칸에서 한 칸 움직인 방향의 가로줄/세로줄로 고정되고, 첫 칸의 상태로 값이 정해진다(빈 칸이면 칠하기, 칠한 칸이면 지우기). 첫 칸과 같은 상태인 칸만 바뀐다. 끄는 동안 미리 보이고, 손을 떼면 한 수로 보낸다.
|
||||
- [■ 채우기] / [✕ 표시] 버튼으로 바꾼다. PC는 오른쪽 클릭·끌기가 늘 ✕. 휴대폰은 판에 `touch-action: none`(끌기가 스크롤이 되지 않게).
|
||||
- 키보드: 화살표, 스페이스/Enter 칠하기·지우기, X ✕. 스크린리더는 칸 위치·상태와 그 줄의 숫자를 읽어 주고, 맞는 줄 수가 바뀌면 알려 준다.
|
||||
- [💡 힌트]: 고친 칸에 노란 테두리가 깜박인다.
|
||||
- 다 풀면 그림이 왼쪽 위부터 색으로 물들고 이름이 나온다(`다 풀었어요! 고양이`). 시간이 끝나거나 포기하면 `정답 그림: …`과 그림.
|
||||
- 휴대폰 390px에서 15×15가 숫자까지 들어간다(칸 약 19px), 320px에서도 칠할 수 있다. 소리: 칠하기·✕·지우기, 줄이 맞을 때, 힌트.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 그림 은행: 크기별 수, 빈 줄 없음, 모든 그림이 줄 논리만으로 하나의 답으로 풀림; 줄 풀이 단위 테스트
|
||||
- [x] 같은 시드 = 같은 그림, 모두 같은 빈 판, 카운트다운에는 판 없음, 기본 옵션
|
||||
- [x] 칠하기·✕·지우기, 거절(판 밖·겹침·한 줄 아님·바뀌는 칸 없음·형식), 힌트(바른 상태·횟수·끈 방 거절·힌트만으로도 풀림)
|
||||
- [x] 다 풂(✕ 상관없음, 칠한 칸이 하나 더 많으면 아직), 진행도 = 맞는 줄, 순위·같은 순위·나간 사람, 제한 시간, 무제한 끊김, 속도 제한
|
||||
- [x] 끝내기 전 내 화면·관전 화면에 답·이름 없음, 무작위 대국(1·2·5·8명, 세 크기)
|
||||
- [x] 컴퓨터(거절 0, 끝까지, 50ms 안, 강한 컴퓨터가 기본 시간 안에 10×10을 풀고 더 빠름), 방 통합(연습·끊김·무제한)
|
||||
- [x] E2E: PC 마우스 끌기·오른쪽 클릭·키보드, 휴대폰 터치 끌기·✕ 모드, 같은 시작 판, 상대 진행 표시, 다 풀기 → 그림 이름, 결과
|
||||
|
||||
## 11. 참고
|
||||
- Nonogram(Non Ishida, 1987). 한국에서는 "네모네모 로직"(잡지·게임 이름)으로 널리 알려졌다.
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 자기 화면(숫자와 자기 표시)만 보고 §8의 줄 풀이로 정해지는 칸을 찾는다. 한 수 = 한 줄에서 새로 정해진 연속 칸 한 덩어리(칠하기 또는 ✕).
|
||||
- 강할수록 가장 긴 칠하기 덩어리를 먼저 고르고, 약하면 아무 덩어리나. 약한 컴퓨터는 가끔 모르는 칸을 잘못 칠했다가 몇 수 뒤 지운다(그동안 그 칸은 모르는 칸으로 생각).
|
||||
- 한 수에 레벨 1 약 6초 → 레벨 60 약 1.2초(5×5는 조금 짧게, 15×15는 조금 길게). 10×10을 레벨 60은 약 1분, 레벨 1은 약 6분에 푼다.
|
||||
38
docs/games/race.md
Normal file
38
docs/games/race.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# 같은 판 경주 공통 틀 (`race`)
|
||||
|
||||
지뢰찾기·사천성·솔리테어·스도쿠·네모네모 로직이 함께 쓰는 틀. 원래 혼자 하는 퍼즐을 **모두 같은 판(같은 시드)** 으로 각자 동시에 풀게 해서, 혼자 하면 기록 도전, 여럿이면 "누가 먼저 푸나" 경주가 된다. 사과 게임(`apple.md`)의 방식을 퍼즐 게임용으로 일반화했다.
|
||||
|
||||
코드: `packages/games/src/race/index.ts`(엔진 `makeRaceGame`), `race/bot.ts`(컴퓨터 `raceBot`), `apps/web/src/games/race/kit.tsx`(화면 부품), `race/text.ts`(상태 줄·도움말 글).
|
||||
|
||||
## 1. 진행
|
||||
- 인원 1~8명. `setup`에서 시드로 퍼즐 하나를 만들어 모두에게 같은 시작 판을 준다(`puzzle` + 각자 `boards`).
|
||||
- 3초 카운트다운 동안에는 판을 보내지 않는다(`view.board = null`, `secretsOf` = 퍼즐의 숨은 부분).
|
||||
- 턴이 없다. 시작 뒤 누구나 언제든 자기 판에 수를 둔다(게임마다 1초에 정해진 횟수까지, 기본 12번).
|
||||
- 상태: `playing` → `solved`(다 풂) / `failed`(지뢰를 밟는 것처럼 판이 끝나는 실수) / `done`(포기) / `left`(나감).
|
||||
- `stop` = [포기할래요](두 번 눌러야 함). 제한 시간이 있어도 없어도 쓸 수 있다.
|
||||
- 제한 시간: 게임마다 고르는 값 + 무제한. 마감 `tick`으로 끝난다. 마감 뒤 수는 `시간이 다 됐어요.`로 거절.
|
||||
- 끝: 모두 `playing`이 아니면(다 풂·실패·포기·나감) 끝, 또는 마감. 한 사람이 나가도 남은 사람은 끝까지 푼다.
|
||||
|
||||
## 2. 순위와 점수
|
||||
- 다 푼 사람이 먼저, **걸린 시간이 짧은 순**. 그다음 다 못 푼 사람(시간 끝·실패·포기)은 **푼 만큼(progress)이 많은 순**. 나간 사람은 맨 아래.
|
||||
- 같은 시간 / 같은 진행도는 같은 순위.
|
||||
- 걸린 시간 = 카운트다운이 끝난 때부터 다 풀었을 때(실패·포기한 때)까지, 서버 시계.
|
||||
- 결과 문구(`scoreText`): `다 풀었어요 · 3분 05.4초`(+ 힌트 횟수 등), 다 못 풀면 게임의 진행 문구(`연 칸 40/71`) + ` · 지뢰를 밟았어요`/` · 포기`.
|
||||
- 요약: 혼자 `다 풀었어요! 걸린 시간 …` / `시간이 다 됐어요. …` / `포기했어요. …`. 여럿 `가장 먼저 다 푼 사람이 이겼어요`, 아무도 못 풀면 `아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요`(+ `공동 1등 N명`).
|
||||
- `GameResult.scores` = 진행도.
|
||||
|
||||
## 3. 보기(view)·타이머
|
||||
- 내 view: 내 판(게임이 정한 모양, 내가 다 풀었거나 게임이 끝나면 정답까지 보여 줌 `reveal`. 실패·포기한 사람에게는 게임이 끝날 때까지 정답을 보내지 않는다 — 보조 참가자가 포기해 정답을 받아 다른 사람에게 알려 주는 것을 막기 위해) + 모두의 상태·진행도·진행 문구·걸린 시간. 다른 사람 판은 보내지 않는다. 관전자는 판 없이 진행 상황만.
|
||||
- 같은 판을 푸는 게임이라 "남의 비밀"은 없고, 숨길 것은 **아직 열지 않은 정답**(지뢰 위치, 뒤집힌 카드, 스도쿠·노노그램 답)뿐이다. 그래서 엔진 공통 검사(`checkNoLeak`)는 카운트다운만 보고, 각 게임 테스트가 "끝나기 전 내 view에 정답이 없다"를 따로 확인한다.
|
||||
- `deadline`: 카운트다운 끝 / 마감. `timeoutNotBefore` = 같은 값이라 연결이 끊긴 사람이 일찍 시간 초과되지 않는다. 무제한이면 진행 중 마감이 없고, 끊긴 채 유예 시간이 지난 사람만 `tick`으로 포기(`done`) 처리.
|
||||
- 컴퓨터 연습방이 사람 없이도 끝나도록 게임마다 **기본 제한 시간이 있다**(무제한은 고를 때만).
|
||||
|
||||
## 4. 화면 부품 (`race/kit.tsx`)
|
||||
- 위: 남은 시간(마지막 10초 빨강) 또는 무제한 스톱워치(0.1초) + 게임 알약들. 그 아래 여러 명이면 모두의 진행 칩(순위순, 실시간).
|
||||
- 판 위에 카운트다운(3·2·1), 끝나면 `다 풀었어요! …`/실패/포기 안내, 관전 안내.
|
||||
- [포기할래요] 두 번 누르기. 오른쪽 패널에 순위표와 최종 순위.
|
||||
- 소리: 3·2·1, 시작, 마지막 10초 째깍, 다 풀면 팡파르, 실패하면 낮은 소리.
|
||||
|
||||
## 5. 컴퓨터 (`raceBot`)
|
||||
- live 전략: 서버가 컴퓨터마다 자기 타이머로 계속 묻고, 컴퓨터는 자기 view만 본다. 남의 판을 방해할 수 없어서 실시간 게임이지만 컴퓨터를 넣었다.
|
||||
- 게임이 "다음 수 + 사람이 그 수를 찾는 데 걸릴 시간"을 정하면 그만큼 기다렸다 둔다. 레벨(1~60)이 시간과 실수를, 컴퓨터마다 빠르기(`pace`)가 시간을 조금 바꾼다.
|
||||
67
docs/games/shisen.md
Normal file
67
docs/games/shisen.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# 사천성 (`shisen`)
|
||||
|
||||
> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~15분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 마작패로 하는 짝 맞추기 퍼즐(Shisen-Sho, 四川省). 같은 그림의 패 두 장을 **두 번 이하로 꺾인 선**으로 이어 없애고, 판을 모두 비우면 이긴다.
|
||||
- 원작은 혼자 하는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 판을 각자 풀고 가장 먼저 다 비운 사람이 이긴다. 혼자서도 한다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `size` | 판 크기 | 작게 12×6(72패, 18종) / 보통 14×8(112패, 28종) / 크게 17×8(136패, 34종 전부) | 보통 |
|
||||
| `hints` | 힌트 쓰기 | 쓰기 / 안 쓰기 | 쓰기 |
|
||||
| `timeLimitSec` | 제한 시간 | 5분 / 10분 / 15분 / 20분 / 무제한 | 15분 |
|
||||
|
||||
## 3~4. 구성과 준비
|
||||
- 패 종류: 만수·통수·삭수 1~9, 자패 동·남·서·북·백·발·중 = 34종(`'1m'..'9m'`, `'1p'..'9p'`, `'1s'..'9s'`, `'1z'..'7z'`), 종류마다 4장. 작게·보통은 쓸 종류를 시드로 고른다.
|
||||
- **언제나 풀리는 판**: 판을 거꾸로 만든다. 채울 칸 전체에서 "지금 이어지는 두 칸"(나머지 칸은 다 차 있다고 보고)을 하나씩 골라 비워 가며 쌍을 정하고, 다 비운 뒤 쌍마다 종류를 붙인다. 이것은 빈 판에 이어지는 두 칸씩 쌍을 놓아 가는 역방향 구성과 같고, 비운 순서가 곧 풀이다. 두 열의 맨 위 패(열이 하나면 맨 위 두 장)는 언제나 위 테두리로 이어지므로 막히는 일이 없다(재시도가 필요 없음). 크게도 1ms 안팎.
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 잇기(`pair`): 서로 다른 두 칸, 둘 다 패, 같은 종류, 그리고 둘을 잇는 가로·세로 선(최대 3토막 = 꺾임 2번)이 **빈 칸만** 지나야 한다. 선은 판 바로 바깥 한 칸 테두리를 지나도 된다. 맞으면 두 장이 없어진다.
|
||||
- 없앤 뒤 패가 남았는데 이어지는 쌍이 하나도 없으면 **남은 패를 그 자리들에 저절로 섞는다**(위와 같은 방식이라 다시 풀림, 섞기 횟수 `shuffles`). 원작의 막힘 = 실패 대신, 경주가 끝까지 가게 했다.
|
||||
- 힌트(`hint`): 힌트를 쓰는 방에서, 힌트가 안 보일 때만. 이어지는 쌍 하나를 보여 주고 횟수를 센다. 그 두 장 중 하나가 없어지거나 판이 섞이면 사라진다.
|
||||
- 판이 비면 다 풂(`solved`). 실패는 없다. 1초에 12번까지.
|
||||
|
||||
## 6. 승패
|
||||
- `race.md` §2. 진행도 = 없앤 쌍 수, 진행 문구 `없앤 쌍 N/전체 쌍`(보통이면 `/56`). 결과 문구에 ` · 섞기 N번`, ` · 힌트 N번`이 붙는다.
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 막히면 저절로 섞기(원작은 막히면 끝이거나 직접 섞기). 패를 쌓지 않는 한 층 판(원작의 기본형).
|
||||
|
||||
## 8. 엔진 설계
|
||||
```ts
|
||||
puzzle: { rows, cols, cells: (string | null)[] /* 칸마다 종류 코드 */ }
|
||||
board: { cells, removed: number, hint: [a, b] | null, hints: number, shuffles: number }
|
||||
view.board: { rows, cols, cells, hint, shuffles, hints }
|
||||
findPath(cells, rows, cols, a, b): [row, col][] | null // [a, 꺾인 곳…, b], 테두리는 -1 / rows / cols
|
||||
```
|
||||
| type | payload | 검증 |
|
||||
|---|---|---|
|
||||
| `pair` | `a`, `b`(칸 번호) | 판 안, 서로 다름, 둘 다 패, 같은 종류, 꺾임 2번 이하 길 |
|
||||
| `hint` | — | 힌트 쓰는 방, 지금 힌트 없음 |
|
||||
| `stop`·`tick`·`leave` | — | 공통 틀 |
|
||||
- 랜덤: `setup`의 종류 고르기·배치, 저절로 섞기(`ctx.rng`). 숨길 것: 판 전체가 보이는 게임이라 카운트다운 동안만 판을 숨긴다(테스트).
|
||||
|
||||
## 9. UI/UX
|
||||
- 마작 화면의 패 그림(`mahjong/Tile`)을 녹색 판 위에 놓고, 둘레에 반 칸 테두리(선이 지나는 곳). 패 크기는 칸 폭과 보이는 높이에 맞춘다(최대 64px).
|
||||
- 누르기(클릭·탭): 첫 패는 떠오르며 노란 테두리, 같은 패를 다시 누르면 취소. 두 번째 패가 이어지면 노란 선(테두리로 도는 것까지)을 0.35초 그리고 두 장이 작아지며 사라진다. 안 되면 두 장이 흔들리고 `같은 패가 아니에요` / `두 번 넘게 꺾여야 이어져요`를 보여 주고, 방금 누른 패가 새로 골라진다.
|
||||
- [💡 힌트]: 이어지는 두 장이 파랗게 빛난다. 저절로 섞이면 `섞었어요!`.
|
||||
- 휴대폰: 판이 가로로 길면(열 > 줄) 세로로 돌려 보여 주고, 작게·보통은 스크롤 없이 화면에 들어온다(크게는 조금 내려야 할 수 있음).
|
||||
- 키보드: 화살표로 칸 옮기기, 스페이스/Enter 고르기, Esc 취소. 스크린리더는 칸 위치와 패 이름을 읽어 준다(`aria-live`).
|
||||
- 위에 남은 패 수. 규칙 화면에 패 그림 출처(`MAHJONG_TILE_CREDIT`).
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 판: 크기별 칸·종류·종류마다 4장, 같은 시드 = 같은 판, 모두 같은 판, 크기마다 200판이 풀이 순서대로 모두 없어짐(100ms 안), 카운트다운에는 판 없음
|
||||
- [x] 길 찾기: 곧게·한 번·두 번 꺾기·테두리로 돌기·세 번이면 안 됨, `reachable`과 `findPath`가 같은 답
|
||||
- [x] 잇기·거절(다른 패, 같은 칸, 꺾임, 판 밖), 힌트(횟수·중복 금지·사라짐·끈 방), 막히면 저절로 섞기(같은 칸·같은 패·다시 풀림), 다 비우면 다 풂
|
||||
- [x] 순위(다 푼 사람 > 없앤 쌍 많은 순, 같으면 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김(한 번만 포기), 속도 제한
|
||||
- [x] 무작위 대국(1·2·5·8명, 세 크기), 컴퓨터(거절 0, 다 풂, 강할수록 빠름), 방 통합(연습·끊김·무제한)
|
||||
- [x] E2E: PC 클릭·키보드, 휴대폰 탭, 같은 시작 판, 상대 진행 표시, 포기 → 결과
|
||||
|
||||
## 11. 참고
|
||||
- Shisen-Sho(四川省, 1989 Activision, KShisen 등): 같은 패 두 장을 꺾임 2번 이하로 잇는 규칙, 판 바깥 테두리 통과.
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 자기 판에서 지금 이어지는 쌍을 찾는다(`findPath`). 약한 컴퓨터는 주로 곧게 이어지거나 가까운(꺾임 1번, 4칸 안) 쌍만 눈에 띄고, 먼 쌍만 남으면 더 오래 찾는다. 강할수록 어떤 쌍이든 본다.
|
||||
- 한 쌍에 레벨 1 약 7초 → 레벨 60 약 1.5초. 작게 10판에서 강한 컴퓨터가 약한 컴퓨터보다 거의 늘 먼저 다 푼다(테스트).
|
||||
91
docs/games/solitaire.md
Normal file
91
docs/games/solitaire.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# 솔리테어 (`solitaire`)
|
||||
|
||||
> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~15분 · 난이도: 쉬움
|
||||
|
||||
## 1. 개요
|
||||
- 윈도우에 들어 있던 카드놀이 세 가지: 클론다이크(그냥 "솔리테어"), 프리셀, 스파이더.
|
||||
- 원작은 혼자 하는 놀이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 패를 각자 풀고 가장 먼저 다 푼 사람이 이긴다. 혼자서도 한다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `mode` | 종류 | 클론다이크 / 프리셀 / 스파이더 | 클론다이크 |
|
||||
| `draw` | 한 번에 넘기는 카드(클론다이크만) | 1장 / 3장 | 1장 |
|
||||
| `suits` | 무늬 수(스파이더만) | 1가지(스페이드) / 2가지(스페이드·하트) / 4가지 | 1가지 |
|
||||
| `timeLimitSec` | 제한 시간 | 10분 / 15분 / 20분 / 30분 / 무제한 | 15분 |
|
||||
|
||||
## 3~4. 구성과 준비
|
||||
- 카드 id는 `PlayingCard`와 같다: 숫자 `A23456789TJQK` + 무늬 `SHDC`("AS", "TD").
|
||||
- 클론다이크: 52장. 일곱 줄에 1~7장(맨 위만 앞면), 나머지 24장은 더미. 파운데이션 4자리.
|
||||
- 프리셀: 52장. 여덟 줄에 7·7·7·7·6·6·6·6장 모두 앞면. 빈 칸 4개, 파운데이션 4자리.
|
||||
- 스파이더: 두 벌 104장(1가지면 모두 스페이드, 2가지면 스페이드·하트 반씩). 열 줄에 앞 네 줄 6장, 나머지 5장(맨 위만 앞면), 더미 50장(10장씩 5번).
|
||||
- 시드로 섞은 한 벌을 모두에게 똑같이 돌린다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 옮기기(`move {from, n, to}`): 자리 id는 줄 `t0`~`t9`, 버린 카드 `w`, 빈 칸 `c0`~`c3`, 파운데이션 `f0`~`f3`(`to: 'f'` = 맞는 파운데이션 아무 곳). 줄에서는 맨 위 `n`장, 나머지 자리에서는 한 장.
|
||||
- 줄 쌓기: 클론다이크·프리셀은 색을 번갈아 하나씩 작게, 스파이더는 무늬 상관없이 하나 작게. 빈 줄에는 클론다이크는 K만, 나머지는 아무 카드나.
|
||||
- 한꺼번에 옮기기: 클론다이크·프리셀은 색이 번갈아 이어진 카드, 스파이더는 **같은 무늬로** 이어진 카드만. 프리셀은 (빈 칸 + 1) × 2^(빈 줄)장까지(빈 줄로 옮길 때 그 줄은 빼고 셈).
|
||||
- 파운데이션: A부터 같은 무늬로 차례대로. 클론다이크는 올린 카드를 줄로 다시 내릴 수 있다(윈도우와 같음), 프리셀은 못 내린다.
|
||||
- 뒤집힌 카드 위의 카드를 다 옮기면 저절로 앞면이 된다.
|
||||
- 넘기기(`draw`, 클론다이크): 더미에서 1장(3장)을 버린 카드 위로. 더미가 비면 버린 카드를 다시 뒤집어 더미로(횟수 제한 없음).
|
||||
- 나누기(`deal`, 스파이더): 열 줄에 한 장씩. 빈 줄이 있으면 못 나눈다(원작 규칙). 단 줄 위의 카드가 10장보다 적으면 빈 줄이 있어도 나눌 수 있다(채울 카드가 모자라 막히는 것을 피함).
|
||||
- 스파이더: K부터 A까지 같은 무늬 13장이 앞면으로 이어지면 저절로 빠진다.
|
||||
- 자동 정리(`auto`, 클론다이크·프리셀): 파운데이션에 올릴 수 있는 카드를 더 없을 때까지 모두 올린다.
|
||||
- 되돌리기(`undo`): 바로 앞 판으로. 판마다 최근 50번까지 저장, 몇 번이든 쓸 수 있지만 결과에 ` · 되돌리기 N번`이 붙는다. 뒤집혔던 카드가 되돌리기로 다시 뒤집혀도 괜찮다(윈도우와 같음).
|
||||
- 다 풂: 클론다이크·프리셀은 52장을 모두 올림, 스파이더는 8줄을 모두 뺌. 1초에 12번까지.
|
||||
|
||||
## 6. 승패
|
||||
- `race.md` §2. 진행도 = 클론다이크·프리셀 올린 카드 수(0~52, 문구 `올린 카드 N/52`), 스파이더 뺀 카드 수(0~104, 문구 `완성 N/8줄`).
|
||||
- 실패(`failed`)는 없다. 막히면 포기하거나 시간이 끝날 때까지 푼 만큼으로 순위.
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 클론다이크는 원작처럼 가끔 풀 수 없는 패가 나온다. 모두 같은 패라 공평하고, 그때는 진행도 순위가 된다.
|
||||
- 점수(윈도우의 표준/라스베이거스 점수)는 쓰지 않는다. 경주라서 시간과 올린 카드만 본다.
|
||||
- 스파이더 나누기의 "카드가 10장보다 적으면 빈 줄이 있어도 됨"(§5).
|
||||
- 끝나도 뒤집힌 카드는 공개하지 않는다(정답이 따로 없는 놀이라서).
|
||||
|
||||
## 8. 엔진 설계
|
||||
```ts
|
||||
puzzle: { mode, deck: string /* 섞은 카드, 2글자씩 */ }
|
||||
board: { t: string[][], down: number[] /* 줄마다 아래 뒤집힌 수 */, stock: string[], waste: string[],
|
||||
cells: string[] /* '' 빈 칸 */, f: string[] /* 파운데이션 맨 위 */, done: string /* 스파이더 뺀 줄의 무늬 */,
|
||||
hist: string[] /* 되돌리기용 이전 판(짧은 글자열), 최대 50 */, undos: number }
|
||||
view.board: { mode, draw, t: (string | null)[][] /* 뒤집힌 카드 null */, stock: number /* 장수만 */, waste, cells, f, done, canUndo, undos }
|
||||
```
|
||||
| type | payload | 검증 |
|
||||
|---|---|---|
|
||||
| `move` | `from`, `n`(1~13), `to` | 자리가 그 모드에 있음, 같은 자리 아님, 집을 카드가 앞면·이어짐, 놓을 곳 규칙(§5), 프리셀 장수 |
|
||||
| `draw` | — | 클론다이크, 더미나 버린 카드가 있음 |
|
||||
| `deal` | — | 스파이더, 더미 있음, 빈 줄 없음(§5 예외) |
|
||||
| `auto` | — | 클론다이크·프리셀, 올릴 카드 있음 |
|
||||
| `undo` | — | 이전 판이 있음 |
|
||||
| `stop`·`tick`·`leave` | — | 공통 틀 |
|
||||
- 규칙 검사(`moveProblem`)는 보이는 판(`Table` = view 모양)에서 한다. 서버·화면·컴퓨터가 같은 함수를 쓴다.
|
||||
- 랜덤: `setup`의 섞기만. 숨길 것: 끝나기 전 내 view에 뒤집힌 카드와 더미 내용이 없다(테스트, 클론다이크는 카드가 모두 달라 글자로도 확인).
|
||||
|
||||
## 9. UI/UX
|
||||
- 카드는 `PlayingCard`(SVG, 그림카드는 CC0 그림, 규칙에 `PLAYING_CARD_CREDIT`). 초록 펠트 위에 위 줄(더미·버린 카드·파운데이션 / 빈 칸·파운데이션 / 더미·완성한 줄)과 줄들. 줄은 부채꼴로, 뒤집힌 카드는 더 촘촘히 겹친다. PC에서 줄이 길면 화면 높이에 맞게 간격을 줄인다.
|
||||
- 카드를 누르면 그 카드와 위에 얹힌 카드가 함께 들리며 골라지고, 놓을 수 있는 곳이 노랗게 빛난다. 놓을 곳을 누르면 옮긴다. 두 번 누르면(더블 클릭/더블 탭) 파운데이션으로. 안 되는 수는 판이 살짝 흔들리고 이유를 읽어 준다.
|
||||
- 더미를 누르면 넘기기/나누기, 비었으면 ↻(다시 뒤집기). 아래 [↶ 되돌리기] [자동 정리] [포기할래요].
|
||||
- 새로 놓인 카드는 살짝 내려앉는 움직임(`prefers-reduced-motion`이면 없음). 소리: 고르기, 놓기, 넘기기, 나누기, 파운데이션(높은 두 음), 한 줄 완성.
|
||||
- 휴대폰 390px: 7·8줄은 카드 약 47px, 스파이더 10줄은 약 34px(320px에서는 약 27px). 세로로는 페이지가 스크롤된다.
|
||||
- 키보드: Tab으로 카드·자리를 옮기고 Enter/스페이스로 고르기·놓기, F 파운데이션, Esc 취소. 스크린리더는 줄·카드 이름을 읽고, 고른 것·올린 것·거절 이유를 알려 준다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 패: 모드별 모양(1~7장·뒤집힘, 7·7·7·7·6·6·6·6, 6×4·5×6), 스파이더 무늬 구성, 같은 시드 = 같은 패, 모두 같은 시작, 카운트다운에 판 없음
|
||||
- [x] 클론다이크: 1장/3장 넘기기·다시 뒤집기, 쌓기·K만 빈 줄·뒤집힌 카드 못 옮김·저절로 뒤집힘, 파운데이션(`f`·`f0`)·다시 내리기, 자동 정리, 다 풂
|
||||
- [x] 프리셀: 빈 칸, 아무 카드 빈 줄, 장수 공식(빈 줄로 옮길 때 포함), 올린 카드 못 내림, 스크립트 풀이로 실제 다 풂
|
||||
- [x] 스파이더: 무늬 상관없이 쌓기, 같은 무늬만 함께, 빈 줄이면 못 나눔, 나누기 10장, 한 줄 완성·저절로 뒤집힘, 8줄 → 다 풂
|
||||
- [x] 되돌리기(50번 한도, 횟수 문구), 순위·제한 시간·무제한 끊김·속도 제한, 무작위 대국(1·2·5·8명, 모든 모드) 중 뒤집힌 카드·더미가 내 view에 없음
|
||||
- [x] 컴퓨터(거절 0, 끝없이 돌지 않음, 강할수록 평균 진행도가 높음), 방 통합(연습·끊김·무제한)
|
||||
- [x] E2E: PC 마우스(클릭·더블 클릭·더미·되돌리기), 휴대폰 탭·더블 탭, 같은 시작 패, 상대 진행 표시, 포기 → 결과; 스파이더·프리셀 화면
|
||||
|
||||
## 11. 참고
|
||||
- Microsoft Solitaire(Windows XP/7): 클론다이크 1장/3장, 프리셀(빈 칸 4개, 여러 장 옮기기 공식), 스파이더(1·2·4가지 무늬, 빈 줄이면 나눌 수 없음).
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 자기 화면만 본다(앞면 카드, 더미 장수). 모든 수에 점수를 매겨 고른다: 파운데이션 > 뒤집힌 카드 열기(뒤집힌 수가 많은 줄 먼저) > 줄 비우기(클론다이크는 놓을 K가 있을 때만) > 파운데이션에 갈 카드 드러내기 > 쌓기(스파이더는 같은 무늬 위를 크게). 이미 잘 이어진 카드를 떼어 내는 수는 하지 않는다.
|
||||
- 강할수록 한 수 앞을 본다(그 수가 열어 주는 다음 수의 절반만큼 더함). 프리셀은 카드가 다 보이니 올릴 카드가 없을 때 짧게 찾아본다(강하면 400판, 약하면 60판까지) — 한 장 더 올리는 길을 찾으면 따라간다.
|
||||
- 할 게 없으면 클론다이크는 넘기기, 스파이더는 나누기(빈 줄이 있으면 먼저 채움).
|
||||
- 끝없이 돌지 않게: 같은 판에서 같은 수는 두 번 하지 않고, 클론다이크는 더미를 두 바퀴 돌도록 판이 그대로면, 할 수가 없으면, 또는 1200수가 넘으면 포기(`stop`).
|
||||
- 한 수에 레벨 1 약 4초 → 레벨 60 약 1초(넘기기·나누기는 절반). 약할수록 가장 좋은 수를 가끔 놓친다. 같은 패 12판에서 강한 컴퓨터가 약한 컴퓨터보다 평균적으로 더 많이 올린다(테스트).
|
||||
70
docs/games/sudoku.md
Normal file
70
docs/games/sudoku.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# 스도쿠 (`sudoku`)
|
||||
|
||||
> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~30분 · 난이도: 보통
|
||||
|
||||
## 1. 개요
|
||||
- 9×9 판의 가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채우는 숫자 퍼즐.
|
||||
- 원작은 혼자 푸는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 퍼즐을 각자 풀고 가장 먼저 다 맞게 채운 사람이 이긴다. 혼자서도 한다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `difficulty` | 난이도 | 쉬움(처음 숫자 38~40개, 싱글만으로 풀림) / 보통(30~32개) / 어려움(26개 안팎) | 쉬움 |
|
||||
| `hints` | 힌트 | 있음 / 없음 | 있음 |
|
||||
| `timeLimitSec` | 제한 시간 | 10분 / 20분 / 30분 / 60분 / 무제한 | 30분 |
|
||||
|
||||
## 3~4. 구성과 준비
|
||||
- 시드로 퍼즐을 만든다(`makePuzzle`). 먼저 무작위 백트래킹으로 9×9를 꽉 채우고, 칸을 무작위 순서로 하나씩 비우면서 **해답이 하나뿐일 때만** 비운 채로 둔다(비트마스크 풀이기가 해답을 2개까지 센다).
|
||||
- 쉬움: 38~40개가 남을 때까지, 그리고 네이키드·히든 싱글(한 칸에 들어갈 수 있는 숫자가 하나 / 줄·상자에서 그 숫자가 갈 곳이 하나)만으로 풀려야 비운다. 보통: 30~32개까지. 어려움: 끝까지 비워 본다(보통 21~26개).
|
||||
- 모두 같은 퍼즐(처음 숫자만 있는 판)로 시작한다. 만드는 데 300ms 안(테스트, 실제로는 수 ms).
|
||||
|
||||
## 5. 진행 규칙
|
||||
- 숫자(`set`): 처음 숫자가 아닌 칸에 1~9. 내가 넣은 숫자는 바꿀 수 있다(같은 숫자는 거절). 그 칸의 메모는 지워지고, 같은 줄·칸·상자 메모에서 그 숫자가 빠진다.
|
||||
- 지우기(`clear`): 내 숫자를 지운다. 숫자가 없으면 그 칸 메모를 지운다.
|
||||
- 메모(`note`): 빈칸에 작은 후보 숫자를 켜고 끈다.
|
||||
- 힌트(`hint`, 힌트 있음일 때): 빈칸이나 틀린 칸 하나(시드 rng로 고름)를 맞는 숫자로 채운다. 쓴 횟수가 결과에 ` · 힌트 N번`으로 남는다.
|
||||
- 종이처럼 **맞는지 알려 주지 않는다**. 틀린 숫자도 넣을 수 있다. 81칸이 모두 정답과 같아지면 다 풂(`solved`). 실패(`failed`)는 없다.
|
||||
- 1초에 12번까지.
|
||||
|
||||
## 6. 승패
|
||||
- `race.md` §2. 진행도 = 채운 칸 수(처음 숫자 제외, 맞든 틀리든), 진행 문구 `채운 칸 N/빈칸 수`. 진행도로 맞고 틀림이 새지 않게 했다.
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 힌트(끌 수 있음), 겹친 숫자 빨간 표시(화면에 보이는 숫자끼리만 비교하므로 정답 정보가 아니다), 같은 숫자를 다시 누르면 지우기(화면).
|
||||
|
||||
## 8. 엔진 설계
|
||||
```ts
|
||||
puzzle: { difficulty, givens: string /* 81자 '0' 빈칸 */, solution: string }
|
||||
board: { values: string /* 처음 숫자 포함 */, notes: number[] /* 칸마다 비트 n = 숫자 n */, hints, hintAt: number | null }
|
||||
view.board: { difficulty, givens: string /* '1' 처음 숫자 */, values, notes, hints, hintAt, solution? /* 내가 끝났거나 게임이 끝났을 때만 */ }
|
||||
```
|
||||
| type | payload | 검증 |
|
||||
|---|---|---|
|
||||
| `set` | `i`, `n`(1~9) | 처음 숫자 칸 아님, 지금 숫자와 다름 |
|
||||
| `clear` | `i` | 처음 숫자 칸 아님, 숫자나 메모가 있음 |
|
||||
| `note` | `i`, `n` | 처음 숫자 칸 아님, 빈칸 |
|
||||
| `hint` | — | 힌트 있음 |
|
||||
| `stop`·`tick`·`leave` | — | 공통 틀 |
|
||||
- 랜덤: `setup`의 퍼즐 만들기, 힌트 칸 고르기. 숨길 것: 끝나기 전에는 내 view에 정답(`solution`)이 없다(테스트). 카운트다운 동안은 퍼즐 전체.
|
||||
|
||||
## 9. UI/UX
|
||||
- HTML 9×9 판(굵은 선 3×3 상자). 고른 칸은 파란 테두리, 같은 줄·칸·상자는 옅은 회색, 같은 숫자는 옅은 파랑+밑줄, 겹친 숫자는 빨강, 메모는 칸 안에 작은 3×3 숫자. 처음 숫자는 굵게, 내 숫자는 파랗게. 넣은 숫자는 톡 튀어나오고, 힌트 칸은 노랗게 빛난다.
|
||||
- 숫자 패드 1~9(남은 개수 = 9 − 판에 있는 개수, 0이면 흐리게) + [⌫ 지우기] + [✏️ 메모] + [💡 힌트]. 같은 숫자를 다시 누르면 지운다.
|
||||
- PC: 판 오른쪽에 3×3 패드. 키보드: 화살표, 1~9(숫자패드도), Backspace·Delete·0 지우기, N·스페이스 메모 켜고 끄기.
|
||||
- 휴대폰: 판은 화면 폭 전체(320px까지), 아래에 1~9 한 줄 + 도구 한 줄 큰 버튼.
|
||||
- 다 풀었거나 게임이 끝나면 빈칸·틀린 칸에 정답을 초록 숫자로 보여 준다. 스크린리더는 칸 위치·숫자·메모를 읽어 준다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 퍼즐: 난이도마다 30판 해답 하나·올바른 스도쿠·숫자 개수·쉬움은 싱글로 풀림·300ms 안·같은 시드 = 같은 판, 모두 같은 시작
|
||||
- [x] 숫자·지우기·메모(같은 줄·칸·상자 메모 지움)·힌트(횟수, 끈 방 거절), 틀린 숫자 허용, 진행도에 맞고 틀림 없음
|
||||
- [x] 다 풂 → 혼자면 끝, 끝난 뒤에만 정답 공개, 순위(다 푼 사람 > 채운 칸 많은 순, 같으면 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김, 속도 제한
|
||||
- [x] 무작위 대국(1·2·5·8명, 세 난이도, 다 풀기 전 내 view에 정답 없음), 컴퓨터(거절 0, 강한 컴퓨터가 30분 안에·약한 컴퓨터보다 빨리), 방 통합(연습·끊김·무제한)
|
||||
- [x] E2E: PC 클릭+키보드·메모·겹침 빨강, 휴대폰 탭+패드·힌트, 같은 시작 판, 상대 진행 표시, PC 다 풂 + 휴대폰 포기 → 결과, 다크 모드·320px 휴대폰 화면
|
||||
|
||||
## 11. 참고
|
||||
- 스도쿠(Number Place). 해답이 하나뿐인 퍼즐, 네이키드/히든 싱글 기법.
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- 자기 화면의 처음 숫자(공개 정보)로 퍼즐을 한 번 풀어 두고, 후보가 가장 적은(가장 쉬운) 빈칸부터 하나씩 채운다. 힌트는 쓰지 않는다.
|
||||
- 한 칸에 쉬움 기준 레벨 1 약 15초 → 레벨 60 약 4초, 보통 ×1.5, 어려움 ×2.2(후보가 많은 칸은 더 오래).
|
||||
- 약한 컴퓨터는 가끔(레벨 1 약 15%) 틀린 숫자를 넣고, 나중에 알아채 고친다(판이 다 차면 반드시).
|
||||
102
docs/games/typing.md
Normal file
102
docs/games/typing.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# 타자 대결 (`typing`)
|
||||
|
||||
> 사이트에서 직접 만든 게임(2026-11-12 사용자 요청). 한컴 타자연습의 타수·정확도 개념에 여러 명 대결 방식을 더했다.
|
||||
|
||||
## 1. 개요
|
||||
- 1~8명(서바이벌은 2명부터), 컴퓨터 상대 가능. 한 판 3~10분.
|
||||
- 모두에게 같은 글이 나오고, 입력 칸에 그대로 친 뒤 Enter. 맞은 글자는 초록, 틀린 글자는 빨강, 조합 중인 글자는 파랑 밑줄.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
| 옵션 | 값 (기본값 굵게) |
|
||||
|---|---|
|
||||
| 언어 | **한국어**, 영어 |
|
||||
| 대결 방식 | **가장 먼저 입력**, 서바이벌, 타수 비교, 정확도 대결, 타임어택, 연습 |
|
||||
| 대결 종목 | 단어, **짧은글**, 긴글 |
|
||||
| 주제 | 여러 개 고르기, 비우면 **전체**(언어·종목에 맞는 주제만 쓰임) |
|
||||
| 라운드 | 1~10 (**3**) |
|
||||
| 서바이벌 탈락 조건 | **틀렸을 때**, 문장별, 시간별, 시간 초과 |
|
||||
| 목숨(틀렸을 때) | 1~5 (**3**) |
|
||||
| 탈락 간격(시간별) | 10·**15**·20·30초 |
|
||||
| 제한 시간 | **자동(글 길이)**, 10초~5분, 무제한 — 가장 먼저 입력·서바이벌은 한 문제, 타수 비교·정확도 대결은 한 라운드 |
|
||||
| 타임어택 시간 | 30초·**1분**·1분 30초·2분 |
|
||||
|
||||
## 3. 구성물 (글 묶음, `packages/games/src/typing/texts.ts`)
|
||||
- 한국어 단어: 과일, 동물, 채소, 나라, 음식, 직업, 스포츠, 사자성어
|
||||
- 한국어 짧은글: 속담, 명언, 잰말놀이, 일상 문장
|
||||
- 한국어 긴글: 애국가, 별 헤는 밤·서시(윤동주), 진달래꽃·산유화(김소월), 님의 침묵(한용운), 훈민정음 서문(현대어 풀이), 흥부와 놀부·해님 달님·토끼와 거북(사이트에서 다시 씀)
|
||||
- 영어 단어: Fruits, Animals, Colors, Countries, Food, Jobs, Sports
|
||||
- 영어 짧은글: Proverbs, Famous quotes, Tongue twisters, Pangrams
|
||||
- 영어 긴글: Gettysburg Address, The Road Not Taken, Sonnet 18, Daffodils, Twinkle Twinkle Little Star, US Constitution Preamble, The Tortoise and the Hare
|
||||
- 시는 위키문헌 원문과 대조해 현대 맞춤법으로 적었다. 일반 자판으로 칠 수 있는 글자만(한자·둥근 따옴표·줄표 없음, 테스트로 확인).
|
||||
|
||||
## 4. 준비
|
||||
- 단어·짧은글: 고른 주제의 항목을 모두 섞은 덱 하나(시드 RNG). 라운드마다 덱에서 차례로 뽑는다(가장 먼저 입력: 단어 10개·짧은글 5문장, 타수 비교·정확도 대결: 단어 15개·짧은글 3문장). 덱을 다 쓰면 다시 섞는다.
|
||||
- 긴글: 주제 순서를 섞고 라운드마다 다음 주제의 다음 단락(8줄 안팎, 남는 2줄 이하는 앞 단락에 붙임)을 친다. 긴 줄은 띄어쓰기에서 나눈다(한국어 34자, 영어 52자).
|
||||
- 서바이벌·타임어택은 글이 끝없이 돈다.
|
||||
- 연습(2026-11-12 사용자 요청, 한컴 타자연습의 짧은글·긴글 연습처럼): 라운드 1번, 제한 시간·점수 없음(라운드·제한 시간 옵션은 안 씀). 단어 20개·짧은글 10문장, 긴글은 고른 주제 중 한 편을 처음부터 끝까지.
|
||||
- 라운드마다 3초 카운트다운. 그동안 첫 글은 숨긴다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
- **함께 치기**(가장 먼저 입력, 서바이벌 중 시간별 아닌 것): 모두 같은 문제를 동시에 친다. 문제가 정해지면 1.5초 쉬고 다음 문제가 열린다.
|
||||
- 가장 먼저 입력: 먼저 정확하게 친 사람 1점. 틀리면 고쳐서 다시. 시간이 끝나면 아무도 점수 없음.
|
||||
- 서바이벌 틀렸을 때: 틀린 Enter·시간 초과마다 목숨 −1, 0이면 탈락. 살아 있는 사람이 모두 치면 다음 문제.
|
||||
- 서바이벌 문장별: 남은 사람 중 마지막 한 사람이 남으면 그 사람 탈락. 시간 안에 못 친 사람도 탈락.
|
||||
- 서바이벌 시간 초과: 시간 안에 못 친 사람 모두 탈락.
|
||||
- **각자 치기**(타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습): 각자 한 줄 치고 Enter → 다음 줄. 틀린 채로 넘어가도 되고 그만큼 정확도·타수가 깎인다.
|
||||
- 서바이벌 시간별: 정해진 간격마다 그때까지 친 타 수(지금 줄 포함)가 가장 적은 사람(같으면 함께) 탈락.
|
||||
- 연습: 줄마다 첫 타(첫 진행)부터 시간을 잰다(줄 사이에 쉬어도 타수가 안 떨어짐). 첫 타의 시간 몫으로 0.15초 앞당겨 시작하고, 그래서 붙여 넣기 막기도 다른 방식과 같다. 줄마다 타수의 최고값(`best`)을 둔다. 모두 다 치면 끝(여럿이면 각자 속도로).
|
||||
- 서바이벌은 문제마다 제한 시간이 0.9배씩 줄고(무제한은 자동으로 친다), 아주 빠른 사람(900타)이 치는 시간 + 1초 아래로는 줄지 않는다. 그래서 라운드가 반드시 끝난다.
|
||||
- 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않는다(목숨은 1개로).
|
||||
- 붙여 넣기 막기: 화면에서 붙여 넣기·끌어 놓기를 막고, 서버는 2,400타/분 + 0.15초보다 빠른 Enter를 거절하며 진행 막대도 그 속도 이상 앞서지 않는다.
|
||||
|
||||
## 6. 승패와 점수 계산
|
||||
- 타수 = 1분에 친 자판 수(두벌식: 겹모음·겹받침 2타, 쌍자음 1타, 영어는 글자 수). 각자 치기는 줄의 타 수 × 정확도, 함께 치기는 맞게 친 문제(못 친 문제는 맞게 친 데까지).
|
||||
- 정확도 = 1 − 편집 거리 / 긴 쪽 글자 수.
|
||||
- 라운드 점수: 가장 먼저 입력은 문제마다 1점, 나머지는 라운드 1등(같으면 모두) 1점 — 타수 비교는 타수, 정확도 대결은 정확도(같으면 타수), 타임어택은 친 타 수, 서바이벌은 끝까지 남은 사람.
|
||||
- 최종: 점수 → 평균 타수 → 평균 정확도 순. 나간 사람은 맨 뒤.
|
||||
- 연습: 점수 없음, 순위는 평균 타수 → 정확도. `scoreText` = "평균 N타 · 정확도 N%".
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 없음(위 옵션으로 조절).
|
||||
|
||||
## 8. 엔진 설계
|
||||
### 8.1 상태
|
||||
`phase`(countdown·playing·roundEnd·ended), `round`, `items`·`itemTopic`·`cycle`, 함께 치기의 `cur`·`curAt`·`curOpen`·`curEndsAt`·`last`, 시간별 `nextCutAt`, 각자의 라운드 기록 `rs`(idx·prog·done·keys·ms·정확도 합·wrong·lives·alive·place), 누적 `totals`, 라운드 결과 `rounds`, 덱 `deck`·`deckAt`, 긴글 `longOrder`·`longAt`.
|
||||
### 8.2 액션
|
||||
`progress { item, text }`(stream: 서버는 이벤트만 전달, 보기를 다시 보내지 않음), `submit { item, text }`, 시스템 `tick`·`leave`. 초당 15번 제한.
|
||||
### 8.3 공개/비공개 정보
|
||||
다른 사람이 친 글은 보내지 않고 진행 비율만. 카운트다운과 문제 사이 쉬는 동안 다음 글은 숨김.
|
||||
### 8.4 랜덤 요소
|
||||
덱 섞기, 긴글 주제 순서.
|
||||
### 8.5 타이머·연결 끊김
|
||||
`realtime`. 시계가 있는 단계(카운트다운, 쉬는 시간, 문제·라운드 시간, 시간별 간격)는 그 시각에만 끝나고 끊긴 사람 때문에 당겨지지 않는다. 시계가 없는 단계(무제한)는 기다리는 사람만 시간 초과 대상이라, 끊긴 사람은 방의 유예 시간 뒤 한 번만 처리된다(각자 치기: 친 데까지로 멈춤).
|
||||
### 8.6 종료와 결과
|
||||
마지막 라운드가 끝나거나 한 명만 남으면(나머지가 나감) 끝. 연습은 남은 사람이 다 칠 때까지 계속하고, 모두 나가야 끝. `scoreText` = "N문제/N승 · 평균 N타 · 정확도 N%".
|
||||
|
||||
## 9. UI/UX
|
||||
- 위: 라운드·방식·몇 번째·남은 사람·시계. 가운데 카드: 주제, 칠 글(글자별 색, 커서 밑줄), 긴글은 단락 전체와 지금 줄, 각자 치기는 다음 두 줄 미리 보기, 입력 칸 + [입력].
|
||||
- 한글 조합 중 Enter는 조합이 끝난 뒤 보낸다(IME가 Enter를 두 번 보내는 것도 거름). 붙여 넣기·끌어 놓기 막음, 자동 완성·맞춤법 끔.
|
||||
- 한/영이 반대로 쳐지면 경고. 지금 타수·라운드 타수·정확도·틀린 횟수 표시.
|
||||
- 아래: 모두의 진행 막대(stream으로 실시간), 목숨 하트, 탈락·다 침 표시. 문제가 정해지면 "OO님이 먼저 쳤어요! 352타"/"OO님 탈락!" 띠. 라운드 끝 표(순위·친 문제·타수·정확도), 6초 뒤 다음 라운드.
|
||||
- 연습: 라운드 표시 대신 걸린 시간(⏱), 아래에 지금·평균·최고 타수, 정확도, 진행 %. 끝나면 평균·최고 타수, 정확도, 틀린 줄. 참가자 막대 옆은 점수 대신 타수.
|
||||
- 소리: 자판 딸깍, 맞음, 틀림 삐, 먼저 침 팡파르, 탈락, 3·2·1, 마지막 5초.
|
||||
### 9.1 설정 화면
|
||||
언어·방식(서바이벌이면 탈락 조건·목숨·간격)·종목·주제(전체 또는 여러 개)·라운드 1~10·제한 시간/타임어택 시간. 방식마다 한 줄 설명.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- keys.test: 두벌식 타 수, 조합 중 글자, 정확도·편집 거리, 글 묶음 글자 검사·줄 나누기.
|
||||
- typing.test: 옵션·주제, 가장 먼저 입력(쉬는 시간, 늦은 답, 붙여 넣기, 시간 초과, 라운드·최종), 서바이벌 4가지와 모두 탈락 방지·줄어드는 시계, 타수 비교·정확도 대결·타임어택·무제한, 나가기, 무작위 대국 10가지 설정(누출 없음).
|
||||
- typing.test 연습: 10문장·시계 없음·점수 없음, 첫 타부터 시간·최고 타수·붙여 넣기 막기, 긴글 한 편 전체, 여럿이 각자.
|
||||
- e2e typingPractice(짧은글, 3초 쉬어도 타수 유지)·typingPracticeLong(애국가 16줄 전체).
|
||||
- bot.test: 10가지 설정(연습은 컴퓨터끼리만) × (사람 1 + 컴퓨터 / 컴퓨터만) 거절 0, 레벨별 타수.
|
||||
- typing.room.test: 진행 stream, 연습 방, 끊긴 사람.
|
||||
- 웹 help.test: 도움말, 글자 표시.
|
||||
|
||||
## 11. 참고 자료
|
||||
- 한컴 타자연습(타수·정확도 개념), 위키문헌(애국가·윤동주·김소월·한용운 원문).
|
||||
|
||||
## 12. 메모
|
||||
- 시·노래는 저작권이 끝난 것만(저자 사후 70년 경과, 애국가). 동화는 직접 다시 썼다.
|
||||
|
||||
## 13. 컴퓨터 상대
|
||||
- `LIVE_BOT_STRATEGIES.typing`: 자기 화면만 보고 자기 시계로 친다. 레벨 1~60에 따라 한국어 120~620타(영어 100~500), 읽는 시간 0.9~0.35초, 오타 확률(글이 길수록 높음). 함께 치기에서는 틀린 Enter 뒤 고쳐서 다시, 각자 치기에서는 오타를 둔 채 넘어간다. 진행은 0.35~0.65초마다 보낸다.
|
||||
@@ -15,6 +15,7 @@
|
||||
- 이의있음!: 고른 것은 다른 것처럼 비밀이고, 혼돈 모드라도 그 사람의 선택은 거기서 끝난다. 모두 고르면 공개 대신 화면 전체에 "이의있음!"이 크게 뜨고(누가 냈는지 함께), 이번에 모두가 고른 증강은 하나도 받지 않은 채 살아 있는 모두가 새 후보로 같은 선택을 처음부터 다시 한다. 다시 고를 때는 이의있음!이 후보에 없어서 한 선택에 한 번만 일어난다. 배달로 주문해 둔 증강은 다시 고를 때도 후보에 나온다. 가진 증강으로 남지 않는다.
|
||||
- 고를 것이 없으면(후보 0개) 그 사람은 건너뛴다. 시간 제한은 max(30초, 행동 시간×2), 넘기면 첫 후보(이의있음 제외, 대상은 첫 항목).
|
||||
- **질문(prompt)**: 효과에 선택이 필요한 증강(거머리·접기·돌림판·착각·계획·승부·손버릇은 주인, 나 누구게?는 다른 모두, 내려는 모두)은 공개 직후 차례로 묻는다. 시간 초과는 첫 선택지.
|
||||
- **증강을 고르는 목록**: 명탐정·배달의 대상, 손버릇·따라쟁이·착각의 대상은 아이콘과 설명 전체가 보이는 목록에서 고른다(손버릇·따라쟁이·착각은 판이 멈춘 뒤 팝업으로 열림). 방 설정의 "나오게 할 증강"은 [증강 목록 열기] 팝업에서 증강마다 스위치로 켜고 끈다.
|
||||
- **순위**: 말을 모두 내거나 특수 승리 조건을 이루면 그 즉시 비어 있는 가장 높은 순위(공동 순위는 같은 숫자, 다음은 +1)를 받고 빠진다. 탈락하면 판 위 말이 빠지고 꼴찌 쪽(늦게 탈락할수록 위). `ranking=first`면 첫 승자가 나오면 끝(동메달은 '승자'가 아님), `all`이면 한 명 남을 때까지. 끝날 때 남은 사람은 난 말 수·남은 거리로 순위를 매긴다.
|
||||
- 거머리·네크로맨서로 이어진 사람은 상대가 이기면 같은 순위를 받는다(거머리는 탈락도 같이).
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user