Compare commits
65 Commits
42e8d7650b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2aaff5762 | ||
|
|
9f9d20a641 | ||
|
|
1b9acb9fc1 | ||
|
|
35f2310f8d | ||
|
|
892f64db0e | ||
|
|
943e4be3fd | ||
|
|
122cf5ed1f | ||
|
|
fffb860282 | ||
|
|
f793391b79 | ||
|
|
bc8cb7ae8c | ||
|
|
fa53175f51 | ||
|
|
4e0eb4d52c | ||
|
|
f18909c44f | ||
|
|
72f4f06e21 | ||
|
|
0cbda8f551 | ||
|
|
c2ce1979b2 | ||
|
|
7084a20e59 | ||
|
|
0e8ba529c0 | ||
|
|
2403b6747f | ||
|
|
f4fb796dfe | ||
|
|
f9ed734db4 | ||
|
|
daac1982fa | ||
|
|
5666b227e7 | ||
|
|
9ba93e9576 | ||
|
|
049d910dc6 | ||
|
|
28ef4ed947 | ||
|
|
d40ba1e121 | ||
|
|
1bd69200fd | ||
|
|
5a878ba991 | ||
|
|
17df65bccf | ||
|
|
19fd1fabf2 | ||
|
|
fdf54bd554 | ||
|
|
9f16bf833a | ||
|
|
03e0e8ed84 | ||
|
|
fcc79f05bc | ||
|
|
e9bc366305 | ||
|
|
ca8baf5cc8 | ||
|
|
adc3b5337a | ||
|
|
0335a09eef | ||
|
|
02c2a8508c | ||
|
|
c10fac8e82 | ||
|
|
9ec756bf38 | ||
|
|
81b257df74 | ||
|
|
3125008895 | ||
|
|
8e549a72c3 | ||
|
|
a81f73ef6d | ||
|
|
f1f1104abd | ||
|
|
e34745fe50 | ||
|
|
ce6f662a86 | ||
|
|
3769b20ac3 | ||
|
|
c9f4b782e8 | ||
|
|
609cd8b410 | ||
|
|
bdb415aff6 | ||
|
|
74f37131ea | ||
|
|
3b8a717888 | ||
|
|
8f59a99d7d | ||
|
|
4f69f19bf9 | ||
|
|
efa7adc0c2 | ||
|
|
8aad123222 | ||
|
|
97969a87bd | ||
|
|
b02c9870cf | ||
|
|
88db031d0a | ||
|
|
8620c82ca8 | ||
|
|
57351fd9d6 | ||
|
|
b61be627c9 |
13
README.md
13
README.md
@@ -5,13 +5,14 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (34개)
|
||||
## 게임 (46개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루 |
|
||||
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임 |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
@@ -19,10 +20,10 @@
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)을 뺀 31개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
|
||||
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
|
||||
|
||||
## 개발
|
||||
```bash
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, TEST_SUPERADMINS, api, boot, guest, sleep } from './test-utils';
|
||||
import { GUEST_IDLE_MS } from './server';
|
||||
import { TOPICS, bankTopics, liarBankRef, setLiarBank, setLiarBankResolver, type LiarState } from '@bg/games/liar';
|
||||
import type { Conn, Room } from './rooms/room';
|
||||
|
||||
const [SUPER, SUPER2] = TEST_SUPERADMINS;
|
||||
type Booted = ReturnType<typeof boot>;
|
||||
@@ -11,6 +13,9 @@ const clients: Client[] = [];
|
||||
afterEach(async () => {
|
||||
for (const c of clients.splice(0)) c.close();
|
||||
for (const s of running.splice(0)) await s.stop();
|
||||
// The 라이어 word bank is process-wide (the game module holds it): back to the code's for the next test.
|
||||
setLiarBank(TOPICS, null);
|
||||
setLiarBankResolver(null);
|
||||
});
|
||||
|
||||
function start(): Booted {
|
||||
@@ -142,6 +147,109 @@ describe('game settings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('라이어 게임 제시어 (§4.1)', () => {
|
||||
const topic = {
|
||||
ko: '우리 반',
|
||||
generic: ['교실에 있어요', '매일 봐요'],
|
||||
words: [
|
||||
{ word: '칠판', hints: ['앞에 걸려 있어요', '분필로 써요'], aliases: ['흑판'], group: '앞' },
|
||||
{ word: '교탁', hints: ['선생님 자리예요'], group: '앞' },
|
||||
{ word: '사물함', hints: ['뒤에 있어요', '자물쇠를 달아요'], group: '뒤' },
|
||||
{ word: '청소함', hints: ['빗자루가 들어 있어요'], group: '뒤' },
|
||||
],
|
||||
};
|
||||
const send = (s: Booted, cookie: string, method: string, path: string, body?: unknown) =>
|
||||
api(s.base, `/api/admin/liar${path}`, { method, cookie, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
||||
|
||||
test('추가·수정·삭제·되돌리기, 잘못된 단어는 이유와 함께 거절, 일반 사용자는 403, 모두 기록', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const plain = await discordLogin(s, '111111111111111111');
|
||||
expect((await send(s, plain.cookie, 'GET', '/topics')).res.status).toBe(403);
|
||||
expect((await send(s, plain.cookie, 'POST', '/topics', topic)).res.status).toBe(403);
|
||||
|
||||
const list = await send(s, sup.cookie, 'GET', '/topics');
|
||||
expect(list.body.topics.map((t: any) => t.id)).toEqual(TOPICS.map((t) => t.id));
|
||||
expect(list.body.topics[0]).toMatchObject({ id: 'fruit', builtin: true, modified: false, deleted: false });
|
||||
expect(list.body.topics[0].words[0].group).toBeTruthy();
|
||||
|
||||
// Problems come back in Korean: the word inside its own hint, and one word inside another.
|
||||
const bad = await send(s, sup.cookie, 'POST', '/topics', { ...topic, words: [...topic.words, { word: '큰칠판', hints: ['큰 칠판이에요'] }] });
|
||||
expect(bad.res.status).toBe(400);
|
||||
expect(bad.body.error).toContain("'큰칠판'의 설명");
|
||||
expect(bad.body.error).toContain("'칠판'가 '큰칠판' 안에");
|
||||
|
||||
const made = await send(s, sup.cookie, 'POST', '/topics', topic);
|
||||
expect(made.res.status).toBe(200);
|
||||
const id = made.body.topic.id as string;
|
||||
expect(id).toMatch(/^c_[a-z0-9]+$/);
|
||||
expect(made.body.topic).toMatchObject({ ko: '우리 반', builtin: false, deleted: false });
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.at(-1)).toEqual({ id, ko: '우리 반', words: 4 });
|
||||
|
||||
// Edit a built-in topic (drop 수박), then reset it.
|
||||
const fruit = list.body.topics[0];
|
||||
const edited = await send(s, sup.cookie, 'PUT', '/topics/fruit', { ko: fruit.ko, generic: fruit.generic, words: fruit.words.filter((w: any) => w.word !== '수박') });
|
||||
expect(edited.res.status).toBe(200);
|
||||
expect(edited.body.topic).toMatchObject({ builtin: true, modified: true });
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(false);
|
||||
expect((await send(s, sup.cookie, 'POST', '/topics/fruit/reset')).body.topic.modified).toBe(false);
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === 'fruit')!.words.some((w) => w.word === '수박')).toBe(true);
|
||||
|
||||
// Delete: a built-in topic is hidden (and can come back), an admin's own is gone.
|
||||
expect((await send(s, sup.cookie, 'DELETE', '/topics/person')).res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(false);
|
||||
expect((await send(s, sup.cookie, 'GET', '/topics')).body.topics.find((t: any) => t.id === 'person')).toMatchObject({ deleted: true });
|
||||
await send(s, sup.cookie, 'POST', '/topics/person/reset');
|
||||
expect((await api(s.base, '/api/liar/topics')).body.topics.some((t: any) => t.id === 'person')).toBe(true);
|
||||
expect((await send(s, sup.cookie, 'DELETE', `/topics/${id}`)).res.status).toBe(200);
|
||||
expect((await send(s, sup.cookie, 'PUT', `/topics/${id}`, topic)).res.status).toBe(404);
|
||||
expect(liarBankRef()).toBeNull();
|
||||
|
||||
const audit = await api(s.base, '/api/admin/audit', { cookie: sup.cookie });
|
||||
expect(audit.body.entries.map((e: any) => e.action)).toEqual(['liar.topic.delete', 'liar.topic.reset', 'liar.topic.delete', 'liar.topic.reset', 'liar.topic.update', 'liar.topic.create']);
|
||||
});
|
||||
|
||||
test('새 판은 고친 은행을 쓰고 그 판본을 옵션에 남겨요. 은행을 또 고쳐도 지난 판본은 남고, 서버를 다시 켜도 그대로', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const id = (await send(s, sup.cookie, 'POST', '/topics', topic)).body.topic.id as string;
|
||||
const ref = liarBankRef()!;
|
||||
expect(ref).toBeTruthy();
|
||||
const host = await guest(s.base, '방장');
|
||||
const room = s.rooms.createPractice(host.id, 'liar') as Room;
|
||||
const conn: Conn = { userId: host.id, send: () => {}, close: () => {} };
|
||||
room.join(conn, 'player');
|
||||
expect(room.configure(host.id, { options: { ...(room.config.options as object), topic: id, foolMode: true } })).toBeNull();
|
||||
expect(room.start(host.id)).toBeNull();
|
||||
for (let i = 0; i < 200 && !room.game; i++) await sleep(10);
|
||||
const st = room.game!.state as LiarState;
|
||||
expect(st.topic).toBe(id);
|
||||
expect(st.options.bank).toBe(ref);
|
||||
expect(st.words).toEqual(['칠판', '교탁', '사물함', '청소함']);
|
||||
// 바보 모드: the liar's word is from the same group.
|
||||
const group = (w: string) => topic.words.find((x) => x.word === w)!.group;
|
||||
expect(group(st.liarWord!)).toBe(group(st.word));
|
||||
const stored = s.db.query<{ options_json: string }, []>("SELECT options_json FROM games WHERE game_id = 'liar'").get()!;
|
||||
expect(JSON.parse(stored.options_json).bank).toBe(ref);
|
||||
|
||||
// Another change: a new version; the old one is still found (replays).
|
||||
await send(s, sup.cookie, 'PUT', `/topics/${id}`, { ...topic, words: topic.words.slice(0, 2) });
|
||||
expect(liarBankRef()).not.toBe(ref);
|
||||
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
|
||||
expect(bankTopics(liarBankRef()).find((t) => t.id === id)!.words).toHaveLength(2);
|
||||
|
||||
// Restart on the same database: same bank, same version name.
|
||||
const now = liarBankRef();
|
||||
await s.stop();
|
||||
running.splice(running.indexOf(s), 1);
|
||||
setLiarBank(TOPICS, null);
|
||||
const again = boot(s.dbPath);
|
||||
running.push(again);
|
||||
expect(liarBankRef()).toBe(now);
|
||||
expect(bankTopics(ref).find((t) => t.id === id)!.words).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin-only options (threat guides)', () => {
|
||||
test('off by default; the host cannot turn them on; the admin default always wins and is not shown as a lock', async () => {
|
||||
const s = start();
|
||||
@@ -223,6 +331,32 @@ describe('site settings, rooms, users', () => {
|
||||
expect((await next).room.gameSpeed).toBe(2);
|
||||
});
|
||||
|
||||
test('chat sound: 0~200% (default 80), shown in /api/config and open rooms, out of range rejected', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site;
|
||||
expect(site.chatSound).toBe(80);
|
||||
expect((await api(s.base, '/api/config')).body.chatSound).toBe(80);
|
||||
for (const bad of [-1, 201, 50.5]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: bad }) });
|
||||
expect(r.res.status).toBe(400);
|
||||
}
|
||||
for (const ok of [0, 200, 120]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: ok }) });
|
||||
expect(r.res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/config')).body.chatSound).toBe(ok);
|
||||
}
|
||||
const g = await guest(s.base, '방장님');
|
||||
const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) });
|
||||
const c = await new Client(s.base, g.cookie, g.id).connect();
|
||||
clients.push(c);
|
||||
c.send({ t: 'join', code: room.body.code, as: 'player' });
|
||||
expect((await c.next('room')).room.chatSound).toBe(120);
|
||||
const next = c.next('room');
|
||||
await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: 30 }) });
|
||||
expect((await next).room.chatSound).toBe(30);
|
||||
});
|
||||
|
||||
test('admin closes a room: everyone is told and disconnected from it', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
|
||||
153
apps/server/src/admin/liar-bank.ts
Normal file
153
apps/server/src/admin/liar-bank.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics.
|
||||
* The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name
|
||||
* (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay
|
||||
* (or a game restored after a restart) sets up from the bank it started with.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { z } from 'zod';
|
||||
import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
|
||||
const line = (max: number) => z.string().trim().min(1).max(max);
|
||||
export const LiarTopicInputSchema = z.object({
|
||||
ko: line(20),
|
||||
generic: z.array(line(80)).max(20),
|
||||
words: z
|
||||
.array(
|
||||
z.object({
|
||||
word: line(20),
|
||||
aliases: z.array(line(20)).max(10).optional(),
|
||||
hints: z.array(line(80)).max(10),
|
||||
group: z.string().trim().max(20).optional(),
|
||||
}),
|
||||
)
|
||||
.max(300),
|
||||
});
|
||||
export type LiarTopicInput = z.infer<typeof LiarTopicInputSchema>;
|
||||
|
||||
/** Most topics an admin may add. */
|
||||
export const CUSTOM_TOPICS_MAX = 100;
|
||||
|
||||
export interface AdminLiarTopic extends Omit<LiarTopic, 'groups'> {
|
||||
builtin: boolean;
|
||||
/** Built-in topic changed by an admin (can be reset). */
|
||||
modified: boolean;
|
||||
/** Built-in topic an admin deleted (can be restored). */
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
/** Drops empty optional fields so the stored JSON stays small and stable. */
|
||||
function clean(t: LiarTopicInput): NonNullable<TopicOverride['topic']> {
|
||||
return {
|
||||
ko: t.ko,
|
||||
generic: t.generic,
|
||||
words: t.words.map((x) => ({
|
||||
word: x.word,
|
||||
hints: x.hints,
|
||||
...(x.aliases?.length ? { aliases: x.aliases } : {}),
|
||||
...(x.group ? { group: x.group } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export class LiarBankStore {
|
||||
private rows: TopicOverride[] = [];
|
||||
private versions = new Map<string, readonly LiarTopic[]>();
|
||||
|
||||
constructor(private db: Database) {
|
||||
this.load();
|
||||
setLiarBankResolver((ref) => this.version(ref));
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
this.rows = this.db
|
||||
.query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id')
|
||||
.all()
|
||||
.map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit<TopicOverride, 'id'>) }));
|
||||
const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null;
|
||||
const topics = mergeBank(this.rows);
|
||||
if (ref) {
|
||||
this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now());
|
||||
this.versions.set(ref, topics);
|
||||
}
|
||||
setLiarBank(topics, ref);
|
||||
}
|
||||
|
||||
/** A stored bank version (null if unknown: the game falls back to the bank in the code). */
|
||||
private version(ref: string): readonly LiarTopic[] | null {
|
||||
const hit = this.versions.get(ref);
|
||||
if (hit) return hit;
|
||||
const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref);
|
||||
if (!row) return null;
|
||||
const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]);
|
||||
if (this.versions.size > 50) this.versions.clear();
|
||||
this.versions.set(ref, topics);
|
||||
return topics;
|
||||
}
|
||||
|
||||
/** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */
|
||||
list(): AdminLiarTopic[] {
|
||||
const by = new Map(this.rows.map((r) => [r.id, r]));
|
||||
const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => {
|
||||
const builtin = TOPICS.some((b) => b.id === t.id);
|
||||
return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false };
|
||||
});
|
||||
for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true });
|
||||
return out;
|
||||
}
|
||||
|
||||
get(id: string): AdminLiarTopic | null {
|
||||
return this.list().find((t) => t.id === id) ?? null;
|
||||
}
|
||||
|
||||
/** Problems (Korean) with a topic as typed, or none. */
|
||||
problems(t: LiarTopicInput): string[] {
|
||||
return topicProblems(clean(t));
|
||||
}
|
||||
|
||||
private write(id: string, value: Omit<TopicOverride, 'id'>, by: string, now: number): void {
|
||||
this.db
|
||||
.query(
|
||||
'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at',
|
||||
)
|
||||
.run(id, JSON.stringify(value), now, by, now);
|
||||
this.load();
|
||||
}
|
||||
|
||||
private remove(id: string): void {
|
||||
this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id);
|
||||
this.load();
|
||||
}
|
||||
|
||||
/** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */
|
||||
save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void {
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
}
|
||||
|
||||
/** Adds a topic of the admins' own; returns its id, or null when there are too many. */
|
||||
create(t: LiarTopicInput, by: string, now = Date.now()): string | null {
|
||||
if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null;
|
||||
let id: string;
|
||||
do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`;
|
||||
while (this.rows.some((r) => r.id === id));
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */
|
||||
delete(id: string, by: string, now = Date.now()): void {
|
||||
if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now);
|
||||
else this.remove(id);
|
||||
}
|
||||
|
||||
/** A built-in topic back to the code's words (undoes a change or a delete). */
|
||||
reset(id: string): void {
|
||||
this.remove(id);
|
||||
}
|
||||
|
||||
/** Topics new rooms can pick, for the lobby. */
|
||||
static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] {
|
||||
return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length }));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { z } from 'zod';
|
||||
import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { CATALOG, GAME_SPEED_DEFAULT, GAME_SPEED_MAX, GAME_SPEED_MIN, type CatalogEntry } from '@bg/shared';
|
||||
import { CATALOG, CHAT_SOUND_DEFAULT, CHAT_SOUND_MAX, CHAT_SOUND_MIN, GAME_SPEED_DEFAULT, GAME_SPEED_MAX, GAME_SPEED_MIN, type CatalogEntry } from '@bg/shared';
|
||||
|
||||
export const SiteSettingsSchema = z.object({
|
||||
siteName: z.string().trim().min(1).max(40).default('같이 놀자 보드게임'),
|
||||
@@ -21,6 +21,8 @@ export const SiteSettingsSchema = z.object({
|
||||
chatFloodGuard: z.boolean().default(false),
|
||||
/** Animations and the computers' thinking time are divided by this (applies at once, also to running games). */
|
||||
gameSpeed: z.number().min(GAME_SPEED_MIN).max(GAME_SPEED_MAX).default(GAME_SPEED_DEFAULT),
|
||||
/** Chat sound in % of a game sound (0 = silent, applies at once, also to open rooms). */
|
||||
chatSound: z.number().int().min(CHAT_SOUND_MIN).max(CHAT_SOUND_MAX).default(CHAT_SOUND_DEFAULT),
|
||||
});
|
||||
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;
|
||||
|
||||
|
||||
5
apps/server/src/db/migrations/004_liar_bank.sql
Normal file
5
apps/server/src/db/migrations/004_liar_bank.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
-- 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1).
|
||||
-- One row per changed topic: a built-in topic replaced ({"topic":…}) or deleted ({"deleted":true}), or an admin's own topic (id c_…).
|
||||
CREATE TABLE liar_topics (id TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL, updated_by TEXT, updated_at INTEGER NOT NULL);
|
||||
-- Every set of changes games were started with (options.bank = ref), so replays set up from the same bank.
|
||||
CREATE TABLE liar_bank_versions (ref TEXT PRIMARY KEY, json TEXT NOT NULL, created_at INTEGER NOT NULL);
|
||||
@@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { botProfile, nicknameError, normalizeNickname } from '@bg/shared';
|
||||
import type { Audit, Role, Roles } from '../admin/roles';
|
||||
import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
||||
import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank';
|
||||
import type { Sessions } from '../auth/sessions';
|
||||
import { toPublicUser, type Users } from '../auth/users';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
@@ -19,6 +20,7 @@ export interface AdminDeps {
|
||||
audit: Audit;
|
||||
settings: SettingsStore;
|
||||
games: Record<string, AnyGameDefinition>;
|
||||
liarBank: LiarBankStore;
|
||||
disconnectUser: (userId: string) => void;
|
||||
/** When an idle guest will be deleted; null for members and for guests still online or seated. */
|
||||
guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null;
|
||||
@@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) {
|
||||
return c.json({ effective: d.settings.game(id), raw: {} });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1)
|
||||
app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() }));
|
||||
|
||||
/** Parses and checks a topic as typed; the error response, or the topic. */
|
||||
const liarInput = async (c: Context<Env>) => {
|
||||
const parsed = LiarTopicInputSchema.safeParse(await body(c));
|
||||
if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) };
|
||||
const problems = d.liarBank.problems(parsed.data);
|
||||
if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) };
|
||||
return { topic: parsed.data };
|
||||
};
|
||||
|
||||
app.post('/liar/topics', async (c) => {
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
const id = d.liarBank.create(r.topic, actor(c));
|
||||
if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400);
|
||||
d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.put('/liar/topics/:id', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
d.liarBank.save(id, r.topic, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.delete('/liar/topics/:id', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400);
|
||||
d.liarBank.delete(id, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.delete', id, before, null);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post('/liar/topics/:id/reset', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400);
|
||||
d.liarBank.reset(id);
|
||||
d.audit.log(actor(c), 'liar.topic.reset', id, before, null);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ site
|
||||
app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
|
||||
app.put('/site', async (c) => {
|
||||
@@ -93,8 +146,8 @@ export function createAdminApp(d: AdminDeps) {
|
||||
const before = d.settings.getSite();
|
||||
d.settings.setSite(parsed.data, actor(c));
|
||||
d.audit.log(actor(c), 'site.update', null, before, parsed.data);
|
||||
// The game speed applies at once: open rooms get it with a fresh room view (their animations follow it).
|
||||
if (before.gameSpeed !== parsed.data.gameSpeed) for (const r of d.rooms.all()) r.broadcastRoom();
|
||||
// The game speed and chat sound apply at once: open rooms get them with a fresh room view.
|
||||
if (before.gameSpeed !== parsed.data.gameSpeed || before.chatSound !== parsed.data.chatSound) for (const r of d.rooms.all()) r.broadcastRoom();
|
||||
return c.json({ site: parsed.data });
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { z } from 'zod';
|
||||
import { bankTopics, liarBankRef } from '@bg/games/liar';
|
||||
import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared';
|
||||
import type { Config } from '../config';
|
||||
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
|
||||
@@ -98,9 +99,13 @@ export function createHttpApp(d: HttpDeps) {
|
||||
announcement: site.announcement,
|
||||
maintenance: site.maintenance,
|
||||
gameSpeed: site.gameSpeed,
|
||||
chatSound: site.chatSound,
|
||||
});
|
||||
});
|
||||
|
||||
// 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices.
|
||||
app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) }));
|
||||
|
||||
app.post('/api/auth/guest', async (c) => {
|
||||
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));
|
||||
|
||||
@@ -226,8 +226,9 @@ export class BotDriver {
|
||||
if (!def.validate(g.state, bot, decision.action, { now }).ok) continue; // the moment passed (phase changed); look again later
|
||||
const brain = this.room.brain;
|
||||
const say = decision.action as { type?: string; channel?: string; text?: string };
|
||||
if (brain && say.type === 'chat' && brain.enabled()) {
|
||||
this.typeLive(brain, bot, say as { type: 'chat'; channel: string; text: string }, decision.hint ?? null, names, g);
|
||||
// 라이어 게임's description is typed like a chat line too ("입력 중…" before it appears).
|
||||
if (brain && (say.type === 'chat' || say.type === 'describe') && brain.enabled()) {
|
||||
this.typeLive(brain, bot, say as { type: 'chat' | 'describe'; channel: string; text: string }, decision.hint ?? null, names, g);
|
||||
continue;
|
||||
}
|
||||
const err = this.room.run(bot, decision.action);
|
||||
@@ -240,7 +241,7 @@ export class BotDriver {
|
||||
* Live chat like a person: the model may say the planned line in the computer's own words, then "입력 중…" for the
|
||||
* typing time, then it is sent (if it still may be: the phase can end meanwhile).
|
||||
*/
|
||||
private typeLive(brain: BotBrain, bot: string, chat: { type: 'chat'; channel: string; text: string }, hint: string | null, names: Record<string, string>, g: unknown): void {
|
||||
private typeLive(brain: BotBrain, bot: string, chat: { type: 'chat' | 'describe'; channel: string; text: string }, hint: string | null, names: Record<string, string>, g: unknown): void {
|
||||
this.liveBusy.add(bot);
|
||||
const view = this.room.def.view(this.room.game!.state, bot) as { chat?: { channel: string; from: string; text: string }[] };
|
||||
const recent = (view.chat ?? []).filter((m) => m.channel === chat.channel).slice(-8).map((m) => ({ from: names[m.from] ?? '누군가', text: m.text }));
|
||||
|
||||
89
apps/server/src/rooms/case-file.room.test.ts
Normal file
89
apps/server/src/rooms/case-file.room.test.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/** 사건 파일 through a real Room: briefing clock, captain passes, report clock, race clock, and views that keep unread texts on the server (docs/games/case-file.md §8.5). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ServerMessage } from '@bg/shared';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { CASES, type CaseFileOptions, type CaseFileState } from '@bg/games/case-file';
|
||||
import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
function harness(players: string[], opts: Partial<CaseFileOptions> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, set: (t: number) => (now = t), advance: (ms: number) => (now += ms) };
|
||||
const games = { 'case-file': GAMES['case-file']! };
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = { gameId: 'case-file', options: games['case-file'].optionsSchema.parse(opts), maxPlayers: players.length, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60 };
|
||||
const room = new Room('room1', '482913', config, players[0]!, deps);
|
||||
store.insertRoom({ id: 'room1', code: '482913', hostId: players[0]!, gameId: 'case-file', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
|
||||
const conns: Record<string, Conn & { msgs: ServerMessage[] }> = {};
|
||||
for (const p of players) {
|
||||
const msgs: ServerMessage[] = [];
|
||||
conns[p] = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(conns[p], 'player');
|
||||
}
|
||||
expect(room.start(players[0]!)).toBeNull();
|
||||
room.clearTimer();
|
||||
const state = () => room.game!.state as CaseFileState;
|
||||
/** Jumps to the current deadline and lets the room fire it. */
|
||||
const expire = () => {
|
||||
clock.set(Math.max(clock.now(), room.effectiveDeadline()!));
|
||||
room.onTimer();
|
||||
room.clearTimer();
|
||||
};
|
||||
let cs = 0;
|
||||
/** Sends an action like the client and fails on a reject. */
|
||||
const act = (p: string, a: unknown) => {
|
||||
const before = conns[p]!.msgs.length;
|
||||
room.act(p, ++cs, a);
|
||||
room.clearTimer();
|
||||
const rej = conns[p]!.msgs.slice(before).find((m) => m.t === 'reject');
|
||||
if (rej) throw new Error(`${p} ${JSON.stringify(a)} rejected: ${JSON.stringify(rej)}`);
|
||||
};
|
||||
return { room, clock, conns, state, expire, act };
|
||||
}
|
||||
|
||||
const allText = (msgs: ServerMessage[]) => JSON.stringify(msgs);
|
||||
|
||||
describe('사건 파일 room flow', () => {
|
||||
test('의뢰 60초 → 수사, 반장 시간 초과는 넘기기만, 보고서 시간 초과 → 채점', () => {
|
||||
const { room, state, expire, conns, act } = harness(['A', 'B'], { turnSeconds: 60, reportSeconds: 180 });
|
||||
expect(state().phase).toBe('briefing');
|
||||
expire();
|
||||
expect(state().phase).toBe('investigate');
|
||||
const cap = state().players[state().decider]!.id;
|
||||
expire();
|
||||
expect(state().players[state().decider]!.id).not.toBe(cap);
|
||||
expect(state().investigations.team!.visited).toHaveLength(0);
|
||||
const now = state().players[state().decider]!.id;
|
||||
act(now, { type: 'pick', lead: 'c1-03' });
|
||||
// The read text went out; texts nobody read did not.
|
||||
const c = CASES.c1;
|
||||
expect(allText(conns.A!.msgs)).toContain(JSON.stringify(c.leads[2]!.text).slice(1, 40));
|
||||
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.leads[10]!.text).slice(1, 40));
|
||||
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.solution).slice(1, 40));
|
||||
const next = state().players[state().decider]!.id;
|
||||
act(next, { type: 'report' });
|
||||
expect(state().phase).toBe('report');
|
||||
act('A', { type: 'answer', q: 'q1', choice: 0 });
|
||||
expire();
|
||||
expire();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.lastResult!.summary).toContain('범인은 강민재였어요');
|
||||
});
|
||||
|
||||
test('따로 겨루기: 전체 시간이 끝나면 모두 보고서, 끝나면 순위', () => {
|
||||
const { room, state, expire, act } = harness(['A', 'B'], { mode: 'race', raceMinutes: 30, reportSeconds: 180 });
|
||||
expire();
|
||||
expect(state().raceEndsAt).not.toBeNull();
|
||||
act('A', { type: 'pick', lead: 'c1-01' });
|
||||
expire();
|
||||
expect(state().phase).toBe('report');
|
||||
act('B', { type: 'answer', q: 'q1', choice: 0 });
|
||||
act('B', { type: 'submit' });
|
||||
expire();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.lastResult!.ranking).toEqual([['B'], ['A']]);
|
||||
});
|
||||
});
|
||||
91
apps/server/src/rooms/castles-of-burgundy.room.test.ts
Normal file
91
apps/server/src/rooms/castles-of-burgundy.room.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/** 버건디의 성 through a real Room: a practice game against a computer, played from the person's own screen, with turn clocks (docs/games/castles-of-burgundy.md §8.5). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { CobAction, CobState, CobView } from '@bg/games/castles-of-burgundy';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Room, Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
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 { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as CobView | null;
|
||||
|
||||
/** What the person presses, read only from their own screen: place > take > anything but ending the turn early. */
|
||||
function personMove(v: CobView): CobAction | null {
|
||||
const my = v.my;
|
||||
if (!my || !my.moves.length) return null;
|
||||
const rank = (a: CobAction) =>
|
||||
a.type === 'useDie' ? (a.act.kind === 'place' ? 0 : a.act.kind === 'take' ? 1 : 3) : a.type === 'endTurn' ? 9 : a.type === 'buy' ? 8 : 2;
|
||||
let best = my.moves.map((a, i) => ({ a, i })).sort((x, y) => rank(x.a) - rank(y.a) || (my.costs[x.i] ?? 0) - (my.costs[y.i] ?? 0) || x.i - y.i)[0]!.a;
|
||||
if (my.needDiscard) {
|
||||
if ((best.type === 'useDie' || best.type === 'bonus') && best.act.kind === 'take') best = { ...best, act: { ...best.act, discard: 0 } };
|
||||
else if ((best.type === 'buy' || best.type === 'depotTake' || best.type === 'soloTrade') && 'tile' in best) best = { ...best, discard: 0 } as CobAction;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
describe('버건디의 성 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 자기 화면만 보고 두고, 가끔 시간을 넘겨도 끝까지 가요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'castles-of-burgundy') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots.length).toBeGreaterThan(0);
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
let lastTurn = -1;
|
||||
let skipTurn = false;
|
||||
for (let i = 0; i < 60_000 && !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 || !v.my) continue;
|
||||
if (v.turnSeq !== lastTurn) {
|
||||
lastTurn = v.turnSeq;
|
||||
skipTurn = v.turnSeq % 7 === 3; // now and then the person lets the clock run out
|
||||
}
|
||||
if (skipTurn) continue;
|
||||
const m = personMove(v);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as CobState;
|
||||
expect(s.stage).toBe('finished');
|
||||
expect(s.log.some((e) => e.t === 'end')).toBe(true);
|
||||
expect(mine).toBeGreaterThan(40);
|
||||
const last = lastView(a)!;
|
||||
expect(last.final!.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
}, 60_000);
|
||||
});
|
||||
113
apps/server/src/rooms/gemblo.room.test.ts
Normal file
113
apps/server/src/rooms/gemblo.room.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/** 젬블로 through a real Room: practice against computers from the person's own screen, and the turn clock (docs/games/gemblo.md §8.5, §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { GembloAction, GembloState, GembloView } from '@bg/games/gemblo';
|
||||
import { legalPlacements, obstaclePlacements } from '@bg/games/gemblo/board';
|
||||
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 db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
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 { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as GembloView | null;
|
||||
|
||||
/** What the person does, read only from their own screen: tap the first link point, take the first way it offers. */
|
||||
function personMove(v: GembloView, me: string): GembloAction | null {
|
||||
if (v.turnPlayer !== me || v.phase === 'finished') return null;
|
||||
if (v.phase === 'obstacleDraft') return { type: 'pickObstacle', pieceId: v.obstacle!.pool[0]! };
|
||||
if (v.phase === 'obstaclePlace') {
|
||||
const p = obstaclePlacements(v, v.obstacle!.hands[me]!, v.obstacle!.sectorCount, undefined, 1)[0]!;
|
||||
return { type: 'placeObstacle', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
|
||||
}
|
||||
if (!v.legal) return null;
|
||||
const c = v.colors[v.turn]!;
|
||||
// A link point may be one no block left can cover (only the 1-cell block would fit): try the next point.
|
||||
for (const point of v.legal.bridgePoints) {
|
||||
const p = legalPlacements(v, c, v.allowFlip, { points: [point] })[0];
|
||||
if (p) return { type: 'place', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
|
||||
}
|
||||
throw new Error('my turn without a placement');
|
||||
}
|
||||
|
||||
function drive(h: ReturnType<typeof harness>, room: Room, a: ReturnType<ReturnType<typeof harness>['conn']>, play: boolean) {
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
for (let i = 0; i < 20_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(500);
|
||||
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 m = play && v ? personMove(v, 'A') : null;
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
return mine;
|
||||
}
|
||||
|
||||
describe('젬블로 room flow', () => {
|
||||
test('컴퓨터 1명과 연습: 사람은 자기 화면(이음점 → 놓는 방법)만 보고 끝까지', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'gemblo') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const mine = drive(h, room, a, true);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as GembloState;
|
||||
expect(s.colors).toHaveLength(4); // 2명 = 2색씩
|
||||
expect(s.placements.filter((p) => p.auto)).toEqual([]);
|
||||
expect(mine).toBeGreaterThan(10);
|
||||
const v = lastView(a)!;
|
||||
expect(v.result!.ranking.flat().sort()).toEqual(['A', ...s.players.filter(isBotId)].sort());
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('5명(장애물 직접 고르기) + 시간 초과만 하는 사람: 자동 배치 두 번 뒤 그 사람 색은 끝나고 게임은 끝까지', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'gemblo', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
for (let i = 0; i < 4; i++) expect(room.addBot('A')).toBeNull();
|
||||
expect(room.configure('A', { options: { ...GAMES.gemblo!.defaultOptions, fivePlayerObstacles: 'draft' } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect((room.game!.state as GembloState).phase).toBe('obstacleDraft');
|
||||
drive(h, room, a, false);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const s = room.game!.state as GembloState;
|
||||
expect(s.placements.filter((p) => p.kind === 'obstacle').length).toBeGreaterThanOrEqual(13);
|
||||
const auto = s.placements.filter((p) => p.auto && p.kind === 'play' && s.colors.find((c) => c.color === p.color)?.owner === 'A');
|
||||
expect(auto).toHaveLength(2);
|
||||
expect(s.out).toEqual([expect.objectContaining({ playerId: 'A', reason: 'timeLoss' })]);
|
||||
expect(lastView(a)!.result!.ranking.at(-1)).toEqual(['A']);
|
||||
});
|
||||
});
|
||||
150
apps/server/src/rooms/hot-streak.room.test.ts
Normal file
150
apps/server/src/rooms/hot-streak.room.test.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
/** 핫스트릭 through a real Room: races flip on the server clock only, 빨리 보기 needs everyone, practice games finish (docs/games/hot-streak.md §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { HotStreakAction, HotStreakState, HotStreakView } from '@bg/games/hot-streak';
|
||||
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 db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
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 { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as HotStreakView);
|
||||
|
||||
/** What the person presses, read only from their own screen. */
|
||||
function personMove(v: HotStreakView, n: number): HotStreakAction | null {
|
||||
const l = v.legal;
|
||||
if (l.draft) {
|
||||
const o = l.draft[n % l.draft.length]!;
|
||||
return { type: 'DRAFT', stack: o.stack, side: n % 3 === 0 ? 'risky' : 'safe' };
|
||||
}
|
||||
if (l.double) return { type: 'DOUBLE', index: 0 };
|
||||
if (l.submit) return { type: 'SUBMIT', cards: l.submit.cards.slice(0, l.submit.count) };
|
||||
if (l.pot) return { type: 'POT_BET', mascot: 'D', last: false, side: 'NO', doubled: l.pot.doubleRequired ? 'mascot' : null };
|
||||
if (l.ready) return { type: 'READY' };
|
||||
return null;
|
||||
}
|
||||
|
||||
function tick(h: ReturnType<typeof harness>, room: Room, ms = 250) {
|
||||
h.clock.advance(ms);
|
||||
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();
|
||||
}
|
||||
|
||||
describe('핫스트릭 room flow', () => {
|
||||
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 남이 넣은 카드는 안 보여요', (nBots) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'hot-streak') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'hot-streak', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
let seen = 0;
|
||||
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
|
||||
tick(h, room);
|
||||
const vs = views(a);
|
||||
for (const v of vs.slice(seen)) {
|
||||
expect(v.me).toBe('A');
|
||||
const st = room.game!.state as HotStreakState;
|
||||
for (const b of bots) for (const c of st.hands[b] ?? []) expect(JSON.stringify(v)).not.toContain(c);
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, mine);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as HotStreakState;
|
||||
expect(s.results).toHaveLength(3);
|
||||
expect(s.timeouts.A).toBe(0);
|
||||
expect(mine).toBeGreaterThan(6);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('경주는 서버 시계로만 넘어가요: 끊긴 사람이 있어도 2초마다 한 장, 모두 [빨리 보기]면 바로 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'hot-streak', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
const c = h.conn('C');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.join(c, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
let cs = 0;
|
||||
const st = () => room.game!.state as HotStreakState;
|
||||
// Everyone plays the betting steps from their own view.
|
||||
for (let i = 0; i < 400 && st().phase !== 'race'; i++) {
|
||||
for (const [p, cn] of [['A', a], ['B', b], ['C', c]] as const) {
|
||||
const v = views(cn).at(-1);
|
||||
const m = v && personMove(v, i);
|
||||
if (m) room.act(p, ++cs, m);
|
||||
}
|
||||
tick(h, room, 100);
|
||||
}
|
||||
expect(st().phase).toBe('race');
|
||||
// C drops: nothing speeds up (the driver's grace is 0 but cards wait for their time).
|
||||
room.disconnect(c);
|
||||
const flipAt = st().race!.nextFlipAt;
|
||||
expect(room.effectiveDeadline()).toBe(flipAt);
|
||||
const before = st().race!.processed;
|
||||
h.clock.advance(flipAt - h.clock.now() - 10);
|
||||
room.onTimer();
|
||||
expect(st().race!.processed).toBe(before);
|
||||
h.clock.advance(10);
|
||||
room.onTimer();
|
||||
expect(st().race!.processed).toBe(before + 1);
|
||||
// Next card two seconds later.
|
||||
expect(room.effectiveDeadline()).toBe(h.clock.now() + 2000);
|
||||
// 빨리 보기: A and B agree, C (offline) has not — still running.
|
||||
room.act('A', ++cs, { type: 'HURRY' });
|
||||
room.act('B', ++cs, { type: 'HURRY' });
|
||||
if (st().phase === 'race') {
|
||||
expect(st().race!.hurry.sort()).toEqual(['A', 'B']);
|
||||
room.join(c, 'player');
|
||||
room.act('C', ++cs, { type: 'HURRY' });
|
||||
}
|
||||
expect(st().phase).toBe('payout');
|
||||
expect(st().race!.over).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -74,7 +74,7 @@ describe('라이어 게임 room flow with computers', () => {
|
||||
const speaker = () => GAMES.liar!.view(state(), null).phase.speaker;
|
||||
while (state().phase.kind === 'describe') {
|
||||
if (speaker() === 'A') {
|
||||
room.act('A', cs++, { type: 'chat', text: iAmLiar ? '저는 좋아하는 편이에요' : '음 다들 아실 거예요' });
|
||||
room.act('A', cs++, { type: 'describe', text: iAmLiar ? '저는 좋아하는 편이에요' : '음 다들 아실 거예요' });
|
||||
described++;
|
||||
}
|
||||
run(() => state().phase.kind !== 'describe' || speaker() === 'A');
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { ulid } from 'ulid';
|
||||
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
|
||||
import { botChatRequired, clampGameSpeed, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { botChatRequired, clampChatSound, clampGameSpeed, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { botPersona } from '@bg/games/bots';
|
||||
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
@@ -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;
|
||||
@@ -440,6 +454,7 @@ export class Room {
|
||||
// Levels are revealed only once the game is over (fairness check).
|
||||
...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}),
|
||||
gameSpeed: this.gameSpeed(),
|
||||
chatSound: clampChatSound(this.deps.settings?.getSite().chatSound),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -461,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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -473,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;
|
||||
@@ -903,7 +922,8 @@ export class Room {
|
||||
if (countErr) return countErr;
|
||||
const eff = this.deps.settings?.game(def.id);
|
||||
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
|
||||
return { options: parsed.data };
|
||||
// Data the server decides (e.g. the admin-edited 라이어 word-bank version) goes with the options, so replays match.
|
||||
return { options: def.prepareOptions ? def.prepareOptions(parsed.data) : parsed.data };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1126,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;
|
||||
@@ -1137,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;
|
||||
@@ -1181,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']);
|
||||
});
|
||||
});
|
||||
129
apps/server/src/rooms/six-nimmt.room.test.ts
Normal file
129
apps/server/src/rooms/six-nimmt.room.test.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 젝스님트 through a real Room (docs/games/six-nimmt.md §10): practice games against computers played to the end from
|
||||
* the person's own screen, with the simultaneous secret pick, the row choice, the pro draft and timeouts on the clock.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { SixNimmtAction, SixNimmtState, SixNimmtView } from '@bg/games/six-nimmt';
|
||||
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 db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
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 { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as SixNimmtView);
|
||||
|
||||
/** What the person presses, read only from their own screen (the safest-looking card, or the fewest-bulls row). */
|
||||
function personMove(v: SixNimmtView, me: string, n: number): SixNimmtAction | null {
|
||||
if (v.phase === 'draft') return v.draft!.at === me ? { type: 'DRAFT', card: v.draft!.pool[n % v.draft!.pool.length]! } : null;
|
||||
if (v.phase === 'select') {
|
||||
if (v.players[me]!.picked || !v.my) return null;
|
||||
const hand = [...v.my.hand].sort((a, b) => (a.preview?.takes ?? 0) - (b.preview?.takes ?? 0));
|
||||
return { type: 'SELECT', card: hand[n % 2 === 0 ? 0 : hand.length - 1]!.n };
|
||||
}
|
||||
const pd = v.pending;
|
||||
if (v.phase !== 'choose' || !pd || pd.player !== me) return null;
|
||||
if (pd.kind === 'place') return { type: 'PLACE', row: pd.choices[0]!.row, side: pd.choices[0]!.side };
|
||||
const best = v.rows.reduce((b, r, i) => (r.bulls < v.rows[b]!.bulls ? i : b), 0);
|
||||
return { type: 'TAKE_ROW', row: best };
|
||||
}
|
||||
|
||||
describe('젝스님트 room flow', () => {
|
||||
test.each([
|
||||
[1, {}],
|
||||
[3, { deck: 'pro', endMode: 'rounds', rounds: 2 }],
|
||||
[4, { placement: 'both', lowCard: 'choose', endMode: 'rounds', rounds: 2 }],
|
||||
] as const)('컴퓨터 %i명과 연습 %j: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 카드는 공개 전까지 안 보여요', (nBots, options) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'six-nimmt') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'six-nimmt', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
expect(room.configure('A', { options: { ...GAMES['six-nimmt']!.defaultOptions, ...options } })).toBeNull();
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let seen = 0;
|
||||
let mine = 0;
|
||||
let chose = 0;
|
||||
for (let i = 0; i < 60_000 && !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 vs = views(a);
|
||||
for (const v of vs.slice(seen)) {
|
||||
// A computer's secret pick never reaches my screen before the reveal.
|
||||
for (const b of bots) expect(JSON.stringify(v)).not.toContain(`six-sel:${b}`);
|
||||
expect(v.me).toBe('A');
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, 'A', mine);
|
||||
if (m) {
|
||||
if (m.type === 'TAKE_ROW' || m.type === 'PLACE') chose++;
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as SixNimmtState;
|
||||
expect(s.timeouts.A).toBe(0); // every step of the person was a real press
|
||||
const last = views(a).at(-1)!;
|
||||
expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
expect(last.result!.ranking[0]!.total).toBe(Math.min(...s.seats.map((p) => s.totals[p]!)));
|
||||
expect(mine).toBeGreaterThanOrEqual(10);
|
||||
if (nBots === 1) expect(chose + mine).toBeGreaterThan(10);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('시간 초과: 사람이 아무것도 안 하면 제한 시간마다 자동으로 내고 3번이면 자리 비움', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'six-nimmt') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
for (let i = 0; i < 2000; i++) {
|
||||
h.clock.advance(500);
|
||||
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();
|
||||
if ((room.game!.state as SixNimmtState).timeouts.A! >= 3) break;
|
||||
}
|
||||
const s = room.game!.state as SixNimmtState;
|
||||
expect(s.timeouts.A).toBeGreaterThanOrEqual(3);
|
||||
expect(views(a).at(-1)!.players.A!.away).toBe(true);
|
||||
});
|
||||
});
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import { Replays } from './rooms/replay';
|
||||
import { Gateway, type WsData } from './ws/gateway';
|
||||
import { Audit, Roles } from './admin/roles';
|
||||
import { SettingsStore } from './admin/settings';
|
||||
import { LiarBankStore } from './admin/liar-bank';
|
||||
|
||||
/** A guest who closed the site and stayed away this long is deleted. */
|
||||
export const GUEST_IDLE_MS = 24 * 3600_000;
|
||||
@@ -57,6 +58,8 @@ export function startServer(opts: StartOptions) {
|
||||
return u ? toPublicUser(u) : null;
|
||||
};
|
||||
const settings = new SettingsStore(db, GAMES);
|
||||
// 라이어 게임 words the admins changed: loaded before rooms are restored (their games may use an edited bank).
|
||||
const liarBank = new LiarBankStore(db);
|
||||
const roles = new Roles(db, config.superadminDiscordIds);
|
||||
const audit = new Audit(db);
|
||||
const startedAt = Date.now();
|
||||
@@ -131,6 +134,7 @@ export function startServer(opts: StartOptions) {
|
||||
admin: {
|
||||
audit,
|
||||
games: GAMES,
|
||||
liarBank,
|
||||
disconnectUser: (id) => gateway.disconnectUser(id),
|
||||
guestDeleteAt: (u) => (u.kind !== 'guest' || guestKept(u.id) ? null : u.last_seen_at + GUEST_IDLE_MS),
|
||||
stats: () => {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
36
apps/web/scripts/aug-icon-sheet.tsx
Normal file
36
apps/web/scripts/aug-icon-sheet.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Dev tool: renders every 증강 icon (big and small, light and dark background) to a PNG contact sheet.
|
||||
* cd apps/web && bun scripts/aug-icon-sheet.tsx [out.png] [ids,comma,separated]
|
||||
*/
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { chromium } from 'playwright-core';
|
||||
import { AUGS, AUG_IDS, type AugId } from '@bg/games/yut/augments';
|
||||
import { AugIcon, GLYPHS } from '../src/games/yut/aug-icons';
|
||||
|
||||
const out = process.argv[2] ?? `${process.env.HOME}/.tmp/aug-icons.png`;
|
||||
const only = process.argv[3]?.split(',').filter(Boolean) as AugId[] | undefined;
|
||||
const ids = only?.length ? only : [...AUG_IDS];
|
||||
const cell = (id: AugId) => (
|
||||
<div className="cell">
|
||||
<AugIcon id={id} size={72} />
|
||||
<div className="row">
|
||||
<div className="light"><AugIcon id={id} size={20} /></div>
|
||||
<div className="dark"><AugIcon id={id} size={20} /></div>
|
||||
</div>
|
||||
<div className={`name${GLYPHS[id] ? '' : ' missing'}`}>{AUGS[id].name}</div>
|
||||
<div className="id">{id}</div>
|
||||
</div>
|
||||
);
|
||||
const html = `<!doctype html><meta charset="utf-8"><style>
|
||||
body{margin:0;padding:12px;font-family:sans-serif;background:#f3f4f6}
|
||||
.grid{display:grid;grid-template-columns:repeat(10,112px);gap:8px}
|
||||
.cell{display:flex;flex-direction:column;align-items:center;gap:4px;background:#fff;border-radius:8px;padding:6px}
|
||||
.row{display:flex;gap:4px}.light{background:#fff;padding:3px;border:1px solid #ddd}.dark{background:#111827;padding:3px}
|
||||
.name{font-size:11px;font-weight:700;text-align:center}.missing{color:#dc2626}.id{font-size:10px;color:#6b7280}
|
||||
</style><div class="grid">${renderToStaticMarkup(<>{ids.map((id) => <div key={id}>{cell(id)}</div>)}</>)}</div>`;
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
||||
const page = await browser.newPage({ viewport: { width: 1240, height: 400 }, deviceScaleFactor: 1 });
|
||||
await page.setContent(html);
|
||||
await page.screenshot({ path: out, fullPage: true });
|
||||
await browser.close();
|
||||
console.log(out, ids.length, 'icons,', ids.filter((id) => !GLYPHS[id]).length, 'missing');
|
||||
43
apps/web/src/components/BotActivity.test.tsx
Normal file
43
apps/web/src/components/BotActivity.test.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
/** "입력 중…" in 라이어 게임's chat box: `hideBots` leaves out a computer typing its description, never a person typing in the chat. */
|
||||
import { afterEach, expect, mock, test } from 'bun:test';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { RoomView } from '@bg/shared/lite';
|
||||
|
||||
// The real socket module needs a browser (document, WebSocket); BotActivity only reads `me` and `typing` from it.
|
||||
// A plain selector over a test-owned state (a zustand store renders its initial state on the server).
|
||||
type St = { me: { id: string } | null; typing: Record<string, { ch: 'room' | 'game'; until: number }> };
|
||||
let st: St = { me: null, typing: {} };
|
||||
mock.module('../net/socket', () => ({ useRoom: <T,>(sel: (s: St) => T) => sel(st) }));
|
||||
const { BotActivity } = await import('./BotActivity');
|
||||
|
||||
const room = (botActivity: RoomView['botActivity']) =>
|
||||
({
|
||||
seats: [
|
||||
{ user: { id: 'speaker', nickname: '말하는사람' } },
|
||||
{ user: { id: 'bot:1', nickname: '컴퓨터 1' } },
|
||||
],
|
||||
spectators: [],
|
||||
botActivity,
|
||||
}) as unknown as RoomView;
|
||||
const typingAs = (id: string) => (st = { me: { id: 'me' }, typing: { [id]: { ch: 'game', until: Date.now() + 5000 } } });
|
||||
|
||||
afterEach(() => (st = { me: null, typing: {} }));
|
||||
|
||||
test('설명 차례인 사람이 토론 채팅을 치면 hideBots에 있어도 "입력 중"이 보여요', () => {
|
||||
typingAs('speaker');
|
||||
const html = renderToStaticMarkup(<BotActivity room={room(undefined)} only="typing" ch="game" hideBots={['speaker']} />);
|
||||
expect(html).toContain('말하는사람 입력 중');
|
||||
});
|
||||
|
||||
test('설명 차례인 컴퓨터가 설명을 치는 중이면 채팅 칸에 "입력 중"을 띄우지 않아요', () => {
|
||||
const r = room({ 'bot:1': 'typing' });
|
||||
expect(renderToStaticMarkup(<BotActivity room={r} only="typing" ch="game" />)).toContain('컴퓨터 1 입력 중');
|
||||
expect(renderToStaticMarkup(<BotActivity room={r} only="typing" ch="game" hideBots={['bot:1']} />)).toBe('');
|
||||
});
|
||||
|
||||
test('상태 줄(only="thinking")에는 컴퓨터 "생각 중"만, 입력 중은 없어요', () => {
|
||||
typingAs('speaker');
|
||||
const html = renderToStaticMarkup(<BotActivity room={room({ 'bot:1': 'thinking' })} only="thinking" ch="game" />);
|
||||
expect(html).toContain('컴퓨터 1 생각 중');
|
||||
expect(html).not.toContain('입력 중');
|
||||
});
|
||||
@@ -3,14 +3,15 @@ import { useRoom } from '../net/socket';
|
||||
|
||||
/**
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…", and people
|
||||
* typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat).
|
||||
* typing ("💬 고양이 입력 중…", `ch`: the room chat or the game's own public chat). `hideBots`: computers left out
|
||||
* (라이어 게임: the computer typing its description is not typing in the chat; people's "입력 중" always comes from a chat box).
|
||||
* Not announced to screen readers: the chat line or the move that follows is.
|
||||
*/
|
||||
export function BotActivity({ room, only, ch }: { room: RoomView; only?: 'typing'; ch?: 'room' | 'game' }) {
|
||||
export function BotActivity({ room, only, ch, hideBots }: { room: RoomView; only?: 'typing' | 'thinking'; ch?: 'room' | 'game'; hideBots?: string[] }) {
|
||||
const typing = useRoom((s) => s.typing);
|
||||
const me = useRoom((s) => s.me?.id);
|
||||
const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only);
|
||||
const people = ch ? Object.entries(typing).filter(([id, t]) => t.ch === ch && id !== me) : [];
|
||||
const entries = Object.entries(room.botActivity ?? {}).filter(([id, a]) => (!only || a === only) && !hideBots?.includes(id));
|
||||
const people = ch && only !== 'thinking' ? Object.entries(typing).filter(([id, t]) => t.ch === ch && id !== me) : [];
|
||||
if (!entries.length && !people.length) return null;
|
||||
const name = (id: string, fallback: string) =>
|
||||
room.seats.find((s) => s?.user.id === id)?.user.nickname ?? room.spectators.find((u) => u.id === id)?.nickname ?? fallback;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { create } from 'zustand';
|
||||
import { socket, useRoom } from '../net/socket';
|
||||
import { useTypingSignal } from '../lib/chat-input';
|
||||
import { keepFocus, useTypingSignal } from '../lib/chat-input';
|
||||
import { useStickToBottom } from '../lib/useStickToBottom';
|
||||
import { BotActivity } from './BotActivity';
|
||||
import { ChatMessage, sameRun } from './ChatMessage';
|
||||
@@ -70,6 +70,7 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
@@ -88,7 +89,9 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
aria-label="메시지"
|
||||
enterKeyHint="send"
|
||||
/>
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
<button className="btn btn-primary btn-sm" {...keepFocus}>
|
||||
보내기
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted small">이 방은 채팅을 쓰지 않아요. 반응 버튼은 쓸 수 있어요.</p>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Hwatu card: the real 48-card hwatu artwork from Wikimedia Commons "SVG Hwatu" (Marcus Richert after Louie Mantia Jr.,
|
||||
* CC BY-SA 4.0 — ./hwatu/ATTRIBUTION.txt, docs/games/seotda.md "화투 그림"), bundled from our own origin (no external
|
||||
* URLs). A small month badge stays on top so beginners can read the card at a glance;
|
||||
* URLs). A small month badge stays on top so beginners can read the card at a glance (섯다 instead draws a big outlined
|
||||
* number in the bottom-left corner, which stays visible when cards overlap);
|
||||
* 쌍피 / bonus cards get their value tag (고스톱). The back and the bonus cards are drawn here.
|
||||
*/
|
||||
import type { CSSProperties } from 'react';
|
||||
@@ -70,6 +71,15 @@ function BonusFace({ w, h, value }: { w: number; h: number; value: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Dark outline around white text (8 directions + soft shadow), readable on both the white and black parts of a card. */
|
||||
const cornerOutline = (t: number): string =>
|
||||
[
|
||||
[-t, -t], [0, -t], [t, -t], [-t, 0], [t, 0], [-t, t], [0, t], [t, t],
|
||||
]
|
||||
.map(([x, y]) => `${x}px ${y}px 0 #111827`)
|
||||
.concat('0 1px 3px rgba(0,0,0,0.6)')
|
||||
.join(', ');
|
||||
|
||||
export function HwatuCard({
|
||||
card,
|
||||
size = 'md',
|
||||
@@ -78,7 +88,9 @@ export function HwatuCard({
|
||||
dimmed,
|
||||
highlight,
|
||||
showMonth = true,
|
||||
monthStyle = 'badge',
|
||||
onClick,
|
||||
disabled,
|
||||
className,
|
||||
style,
|
||||
}: {
|
||||
@@ -91,7 +103,11 @@ export function HwatuCard({
|
||||
highlight?: boolean;
|
||||
/** Small month number badge (on by default). */
|
||||
showMonth?: boolean;
|
||||
/** 'badge': small dark circle top-right. 'corner': big white outlined number bottom-left (섯다). */
|
||||
monthStyle?: 'badge' | 'corner';
|
||||
onClick?: () => void;
|
||||
/** Keeps the card a (disabled) button while it can't be clicked, so switching on/off doesn't remount it (no replayed deal animation). */
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}) {
|
||||
@@ -109,7 +125,7 @@ export function HwatuCard({
|
||||
border: 0,
|
||||
borderRadius: radius,
|
||||
background: 'none',
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
cursor: onClick && !disabled ? 'pointer' : 'default',
|
||||
opacity: dimmed ? 0.45 : 1,
|
||||
transform: selected ? `translateY(${-Math.round(w * 0.2)}px)` : undefined,
|
||||
transition: 'transform 0.12s ease',
|
||||
@@ -132,8 +148,9 @@ export function HwatuCard({
|
||||
<Tag
|
||||
style={s}
|
||||
onClick={onClick}
|
||||
disabled={onClick ? disabled : undefined}
|
||||
aria-label={card.name}
|
||||
aria-pressed={onClick ? !!selected : undefined}
|
||||
aria-pressed={onClick && !disabled ? !!selected : undefined}
|
||||
title={card.name}
|
||||
className={className}
|
||||
>
|
||||
@@ -142,7 +159,27 @@ export function HwatuCard({
|
||||
) : (
|
||||
<img src={hwatuSrc(card.id)} alt="" draggable={false} width={w} height={h} decoding="async" style={{ display: 'block', width: w, height: h, borderRadius: radius }} />
|
||||
)}
|
||||
{showMonth && card.month > 0 && (
|
||||
{showMonth && card.month > 0 && monthStyle === 'corner' && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: Math.round(w * 0.08),
|
||||
bottom: Math.round(w * 0.06),
|
||||
color: '#fff',
|
||||
fontSize: Math.max(12, Math.round(8 + w * 0.26)),
|
||||
fontWeight: 900,
|
||||
lineHeight: 1,
|
||||
letterSpacing: '-0.04em',
|
||||
textShadow: cornerOutline(Math.max(1, Math.round(w * 0.025))),
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{card.month}
|
||||
</span>
|
||||
)}
|
||||
{showMonth && card.month > 0 && monthStyle === 'badge' && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface PlayingCardProps {
|
||||
/** e.g. "AS", "TD", "X1" (joker). null = face down. */
|
||||
card: string | null;
|
||||
size?: CardSize;
|
||||
/** Exact width in px (overrides `size`). */
|
||||
width?: number;
|
||||
selected?: boolean;
|
||||
dimmed?: boolean;
|
||||
highlight?: boolean;
|
||||
@@ -44,8 +46,8 @@ export function cardAria(card: string | null): string {
|
||||
return `${SUIT_KO[card[1]!]} ${FACE_KO[r] ?? RANK_LABEL[r] ?? r}`;
|
||||
}
|
||||
|
||||
export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
|
||||
const w = WIDTH[size];
|
||||
export function PlayingCard({ card, size = 'md', width, selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
|
||||
const w = width ?? WIDTH[size];
|
||||
const h = Math.round(w * 1.4);
|
||||
const lift = selected ? -Math.round(w * 0.22) : 0;
|
||||
const common: CSSProperties = {
|
||||
|
||||
@@ -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;
|
||||
@@ -137,6 +137,12 @@ const CSS = `
|
||||
@keyframes ap-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
|
||||
@keyframes ap-pop { 0% { transform: scale(1); opacity: 1; } 40% { transform: scale(1.25); opacity: .9; } 100% { transform: scale(.2) translateY(-30px); opacity: 0; } }
|
||||
@keyframes ap-flash { 0% { opacity: 0; transform: translateX(-50%) scale(.8); } 15% { opacity: 1; transform: translateX(-50%) scale(1.05); } 70% { opacity: 1; } 100% { opacity: 0; } }
|
||||
/* PC: the 17x10 board is the largest that fits the play column after the score rows, buttons and key help (~150px). */
|
||||
@media (min-width: 1100px) {
|
||||
.ap-wrap { width: min(100%, calc((var(--play-h) - 150px) * 1.7)); }
|
||||
.ap-pill { font-size: clamp(1rem, calc(var(--play-h) * .017), 1.2rem); }
|
||||
.ap-others li { font-size: clamp(.85rem, calc(var(--play-h) * .014), 1rem); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .ap-hint { animation: none; } .ap-pop { animation-duration: .01s; } .ap-flash, .ap-in, .ap-burst, .ap-over.count b { animation: none; } .ap-burst { display: none; } }
|
||||
`;
|
||||
|
||||
@@ -547,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>
|
||||
@@ -629,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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -750,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: '백' };
|
||||
@@ -66,6 +66,8 @@ type MarkMode = 'dead' | 'seki';
|
||||
const BADUK_CSS = `
|
||||
.bd-own { transform-box: fill-box; transform-origin: center; animation: bd-own .32s cubic-bezier(.3, 1.5, .5, 1) both; animation-delay: var(--d, 0ms); }
|
||||
@keyframes bd-own { from { opacity: 0; transform: scale(.2); } }
|
||||
/* PC: the board takes the whole play-area height minus the rows that can show under it (--bd-rows). */
|
||||
@media (min-width: 1100px) { .board-wrap.bd-fit { max-width: min(100%, calc(var(--play-h) - var(--bd-rows, 0px))); } }
|
||||
`;
|
||||
|
||||
/**
|
||||
@@ -158,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;
|
||||
@@ -166,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
|
||||
|
||||
@@ -262,7 +280,11 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const lastColor: Color | null = v.lastMove ? (at(v.lastMove) === 1 ? 'black' : 'white') : null;
|
||||
const pad = 0.95;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<div
|
||||
className="board-wrap stack bd-fit"
|
||||
// Room under the board: the illegal-move note, the dead-stone marking card while scoring, touch tap-confirm buttons.
|
||||
style={{ gap: 10, '--bd-rows': `calc(1.5rem + 30px${marking ? ' + 2.7rem + 90px' : ''}${tapConfirm ? ' + var(--btn-h) + 10px' : ''})` } as React.CSSProperties}
|
||||
>
|
||||
<style>{BOARD_MOTION_CSS + BADUK_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
@@ -484,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;
|
||||
@@ -494,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>하면 계가가 끝나요. 처음 표시는 컴퓨터의 추정이라 틀릴 수 있어요.
|
||||
@@ -560,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 }}>
|
||||
@@ -679,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') {
|
||||
@@ -736,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)
|
||||
|
||||
@@ -78,7 +78,7 @@ const faceAria = (f: CardFace) => `${CARD_INFO[f.kind].name}, ${SUIT_KO[f.suit]}
|
||||
// ---------------------------------------------------------------- styles
|
||||
|
||||
const CSS = `
|
||||
.bg { width: 100%; max-width: 1180px; display: flex; flex-direction: column; gap: 12px; align-self: center; }
|
||||
.bg { width: 100%; display: flex; flex-direction: column; gap: 12px; align-self: stretch; }
|
||||
.bg-table { position: relative; width: 100%; aspect-ratio: 16 / 8.2; min-height: 460px; border-radius: 200px; border: 10px solid var(--wood);
|
||||
background: radial-gradient(ellipse at center, rgba(255,255,255,.13), rgba(255,255,255,0) 62%), var(--felt); box-shadow: var(--shadow); }
|
||||
.bg-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); width: var(--sw, 178px); z-index: 1;
|
||||
@@ -160,6 +160,16 @@ button.bg-card:focus-visible { outline: 3px solid var(--focus); outline-offset:
|
||||
.bg-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 300px; overflow: auto; }
|
||||
.bg-rules td, .bg-rules th { padding: 4px 6px; text-align: left; vertical-align: middle; border-bottom: 1px solid var(--border); }
|
||||
.bg-last { font-size: .86rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
||||
/* PC: fill the play column; the table takes the height my area leaves, hand cards grow a little with the screen. */
|
||||
@media (min-width: 1100px) {
|
||||
.bg { flex: 1 1 auto; min-height: 0; }
|
||||
.bg-table { flex: 1 1 auto; aspect-ratio: auto; min-height: 400px; }
|
||||
.bg-me .bg-card:not(.sm) { --cw: clamp(96px, calc(var(--play-h) * .11), 124px); }
|
||||
}
|
||||
/* Very large screens: seats and the centre piles grow with the bigger table (scaled around their own centre). */
|
||||
@media (min-width: 2200px) and (min-height: 1200px) {
|
||||
.bg-seat, .bg-center { transform: translate(-50%, -50%) scale(1.3); }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.bg-table { aspect-ratio: auto; min-height: 0; border-radius: 18px; border-width: 6px; padding: 8px; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
|
||||
.bg-seat { position: static; transform: none; width: auto; padding: 4px 5px; font-size: .76rem; gap: 2px; border-width: 2px; }
|
||||
@@ -285,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) => (
|
||||
@@ -363,6 +374,7 @@ function Seat({
|
||||
mark,
|
||||
onPick,
|
||||
style,
|
||||
shift,
|
||||
}: {
|
||||
p: PlayerView;
|
||||
v: BangView;
|
||||
@@ -371,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">
|
||||
@@ -391,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>
|
||||
@@ -428,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}
|
||||
@@ -436,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>
|
||||
);
|
||||
@@ -457,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">
|
||||
@@ -472,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>
|
||||
);
|
||||
}
|
||||
@@ -614,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('');
|
||||
@@ -682,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} />
|
||||
@@ -697,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
|
||||
@@ -802,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[]>([]);
|
||||
@@ -818,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 && (
|
||||
@@ -1038,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);
|
||||
@@ -1092,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}
|
||||
/>
|
||||
);
|
||||
@@ -1099,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>
|
||||
@@ -1146,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,
|
||||
@@ -1379,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,
|
||||
);
|
||||
@@ -1412,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 (
|
||||
<>
|
||||
@@ -1426,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 }}>
|
||||
|
||||
791
apps/web/src/games/blackjack/board.tsx
Normal file
791
apps/web/src/games/blackjack/board.tsx
Normal file
@@ -0,0 +1,791 @@
|
||||
/**
|
||||
* 블랙잭 판 화면 (docs/games/blackjack.md §9): 큰 반원 테이블 위에 딜러(위)와 카드 슈(오른쪽 위), 아래 호를 따라
|
||||
* 참가자 자리(내 자리는 가운데 앞, 크게), 테이블 아래 흰 조작판(베팅 입력·칩 버튼·휠·슬라이더 / 히트·스탠드… /
|
||||
* 인슈어런스 / 결과). 모든 조작이 판 안에 있다.
|
||||
*
|
||||
* 카드는 한 장씩: 서버가 여러 장을 한꺼번에 보내도(처음 나눠 주기, 딜러 차례) 화면은 나눠 주는 순서대로
|
||||
* BJ_DEAL_STEP_MS 간격으로 슈에서 날아와 놓이고, 합·결과는 카드가 다 놓인 뒤에 보인다.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||
import type { BlackjackView, HandView, SeatView } from '@bg/games/blackjack';
|
||||
import { BJ_DEAL_STEP_MS, baseCard, handValue } from '@bg/games/blackjack';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import { ChipIcon, formatChips } from '../../components/cards/Chips';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps } from '../types';
|
||||
|
||||
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 HAND_KO: Record<HandView['status'], string> = { playing: '', stand: '', bust: '버스트', blackjack: '블랙잭!', charlie: '찰리!', surrender: '서렌더' };
|
||||
const OUTCOME_KO: Record<NonNullable<HandView['outcome']>, string> = { win: '승', lose: '패', push: '푸시', blackjack: '블랙잭', bonus: '보너스' };
|
||||
|
||||
const CSS = `
|
||||
.bj-wrap { width: 100%; display: flex; flex-direction: column; gap: 12px; align-self: stretch; }
|
||||
.bj-table { position: relative; width: 100%; aspect-ratio: 16 / 8.4; min-height: 460px; border: 12px solid var(--wood); border-radius: 48px 48px 50% 50% / 48px 48px 34% 34%;
|
||||
background:
|
||||
radial-gradient(ellipse at 50% 20%, rgba(255,255,255,.14) 0%, rgba(255,255,255,0) 55%),
|
||||
repeating-linear-gradient(45deg, rgba(255,255,255,.03) 0 2px, transparent 2px 16px),
|
||||
repeating-linear-gradient(-45deg, rgba(255,255,255,.03) 0 2px, transparent 2px 16px),
|
||||
var(--felt);
|
||||
box-shadow: inset 0 0 0 2px var(--wood-line), inset 0 0 60px rgba(0,0,0,.3), var(--shadow); color: #fff; overflow: hidden; }
|
||||
.bj-print { position: absolute; left: 50%; top: 47%; transform: translate(-50%, -50%); text-align: center; pointer-events: none; color: rgba(255,255,255,.55); }
|
||||
.bj-print b { display: block; font-size: 1.5rem; letter-spacing: .3em; color: rgba(253,230,138,.75); }
|
||||
.bj-print span { font-size: .8rem; letter-spacing: .08em; }
|
||||
.bj-print::after { content: ''; display: block; width: 420px; height: 120px; margin: -64px auto 0; border: 2px solid rgba(255,255,255,.12); border-top: 0; border-radius: 0 0 50% 50% / 0 0 100% 100%; }
|
||||
.bj-dealer { position: absolute; left: 50%; top: 18px; transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 6px; z-index: 2; }
|
||||
.bj-dealer .who { display: flex; gap: 8px; align-items: center; font-weight: 900; font-size: .9rem; }
|
||||
.bj-shoe { position: absolute; right: 7%; top: 20px; width: 70px; height: 92px; z-index: 1; transform: scale(var(--bjs, 1)); transform-origin: top right; }
|
||||
.bj-shoe i { position: absolute; inset: 0; border-radius: 8px; background: linear-gradient(160deg, #3b82f6, #1e3a8a); border: 2px solid #fff; box-shadow: 0 2px 4px rgba(0,0,0,.35); }
|
||||
.bj-shoe i:nth-child(2) { transform: translate(-4px, 4px); } .bj-shoe i:nth-child(3) { transform: translate(-8px, 8px); }
|
||||
.bj-shoe::after { content: ''; position: absolute; left: -16px; right: -6px; bottom: -12px; height: 34px; border-radius: 8px; background: linear-gradient(180deg, #4b5563, #1f2937); box-shadow: 0 3px 6px rgba(0,0,0,.4); }
|
||||
.bj-shoe small { position: absolute; left: -16px; right: -6px; bottom: -8px; z-index: 1; text-align: center; font-size: .7rem; font-weight: 800; color: #e5e7eb; }
|
||||
.bj-total { display: inline-flex; flex: none; white-space: nowrap; align-items: center; justify-content: center; min-width: 34px; padding: 1px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-weight: 900;
|
||||
font-variant-numeric: tabular-nums; font-size: .95rem; border: 2px solid rgba(255,255,255,.25); }
|
||||
.bj-total.bust { background: #b91c1c; border-color: #fecaca; }
|
||||
.bj-total.bj { background: linear-gradient(160deg, #fde047, #f59e0b); color: #5a2a00; border-color: #fff7c2; }
|
||||
.bj-total.d21 { background: #15803d; }
|
||||
.bj-cards { display: flex; align-items: flex-end; justify-content: center; min-height: 20px; }
|
||||
.bj-cards > * + * { margin-left: calc(var(--cw) * -1 * var(--ov, .42)); }
|
||||
.bj-card-in { animation: bj-in .42s cubic-bezier(.2,.8,.3,1.1) both; }
|
||||
@keyframes bj-in { from { transform: translate(var(--fx, 260px), var(--fy, -260px)) rotate(-24deg) scale(.6); opacity: 0; } 30% { opacity: 1; } to { transform: none; opacity: 1; } }
|
||||
.bj-card-flip { animation: bj-flip .46s ease both; }
|
||||
@keyframes bj-flip { from { transform: perspective(500px) rotateY(90deg); } to { transform: perspective(500px) rotateY(0); } }
|
||||
.bj-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -100%); z-index: 3; display: flex; flex-direction: column; align-items: center; gap: 5px;
|
||||
width: max-content; max-width: var(--mw, 40%); }
|
||||
.bj-name .nm { min-width: 0; }
|
||||
/* Split hands wrap inside the seat's share of the table instead of running into the neighbours. */
|
||||
.bj-seat .hands { display: flex; flex-direction: column; align-items: center; gap: 4px; max-width: 100%; }
|
||||
.bj-seat .hrow { display: flex; gap: 10px; align-items: flex-end; justify-content: center; }
|
||||
.bj-hand { position: relative; display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 6px 6px 4px; border-radius: 14px; border: 2px solid transparent; transition: border-color .2s, background .2s; }
|
||||
.bj-hand.on { border-color: var(--focus); background: rgba(245,158,11,.14); box-shadow: 0 0 18px rgba(245,158,11,.35); }
|
||||
.bj-hand .meta { display: flex; flex-wrap: wrap; justify-content: center; gap: 3px 5px; align-items: center; }
|
||||
.bj-tag { font-weight: 900; font-size: .8rem; border-radius: 6px; padding: 0 7px; color: #fff; white-space: nowrap; }
|
||||
.bj-bet { display: inline-flex; align-items: center; gap: 3px; font-size: .78rem; font-weight: 800; background: rgba(255,255,255,.92); color: #1c1e21; border-radius: 999px; padding: 0 8px 0 3px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.bj-name { display: flex; align-items: center; gap: 6px; max-width: 100% !important; background: var(--surface); color: var(--text); border-radius: 999px; padding: 3px 10px 3px 3px; box-shadow: var(--shadow), 0 3px 10px rgba(0,0,0,.2);
|
||||
font-size: .82rem; font-weight: 800; white-space: nowrap; max-width: 220px; border: 2px solid transparent; }
|
||||
.bj-name .nm { overflow: hidden; text-overflow: ellipsis; }
|
||||
.bj-name .ch { color: var(--warning); font-variant-numeric: tabular-nums; }
|
||||
.bj-seat.turn .bj-name { border-color: var(--focus); }
|
||||
.bj-seat.me .bj-name { border-color: var(--primary); }
|
||||
.bj-seat.out { opacity: .55; }
|
||||
.bj-net { font-weight: 900; font-size: 1rem; text-shadow: 0 1px 3px rgba(0,0,0,.6); }
|
||||
.bj-net.plus { color: #86efac; } .bj-net.minus { color: #fca5a5; } .bj-net.zero { color: #e5e7eb; }
|
||||
.bj-wait { font-size: .8rem; opacity: .85; background: rgba(0,0,0,.25); border-radius: 999px; padding: 1px 10px; }
|
||||
.bj-banner { position: absolute; left: 0; right: 0; top: 42%; z-index: 8; text-align: center; font-size: 3rem; font-weight: 900; color: #fde047; -webkit-text-stroke: 2px #7c2d12;
|
||||
text-shadow: 0 4px 12px rgba(0,0,0,.6); pointer-events: none; white-space: nowrap; }
|
||||
/* 조작판: 사이트의 흰 카드 한 장. */
|
||||
.bj-dock { position: relative; display: flex; gap: 12px; align-items: stretch; padding: 12px; border-radius: var(--radius-lg); background: var(--surface); color: var(--text);
|
||||
border: 2px solid var(--border); box-shadow: var(--shadow); min-height: 132px; }
|
||||
.bj-dock.turn { border-color: var(--primary); box-shadow: 0 0 0 4px var(--primary-soft), var(--shadow); }
|
||||
.bj-dock.turn::before { content: '내 차례'; position: absolute; top: -13px; left: 50%; transform: translateX(-50%); background: var(--primary); color: var(--primary-text); font-weight: 900;
|
||||
font-size: .8rem; padding: 1px 14px; border-radius: 999px; }
|
||||
.bj-me { flex: 0 0 150px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; background: var(--surface-2); border-radius: var(--radius); padding: 8px; text-align: center; }
|
||||
.bj-me .nm { font-weight: 800; font-size: .88rem; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.bj-me .ch { font-weight: 900; font-size: 1.15rem; font-variant-numeric: tabular-nums; }
|
||||
.bj-main { flex: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; gap: 8px; }
|
||||
.bj-main p { margin: 0; }
|
||||
.bj-info { flex: 0 0 170px; display: flex; flex-direction: column; justify-content: center; gap: 2px; font-size: .8rem; color: var(--text-sub); background: var(--surface-2); border-radius: var(--radius); padding: 8px 10px; }
|
||||
.bj-info b { color: var(--text); }
|
||||
.bj-betrow { display: flex; gap: 8px; align-items: stretch; flex-wrap: wrap; }
|
||||
.bj-amount { display: flex; align-items: center; gap: 4px; border: 2px solid var(--primary); border-radius: var(--radius); background: var(--surface); padding: 0 4px; touch-action: none; }
|
||||
.bj-amount input { width: 7.5em; border: 0; background: none; color: var(--text); font: inherit; font-size: 1.5rem; font-weight: 900; text-align: right; font-variant-numeric: tabular-nums; padding: 4px 2px; outline: none; }
|
||||
.bj-amount input::-webkit-outer-spin-button, .bj-amount input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
|
||||
.bj-amount input[type=number] { -moz-appearance: textfield; }
|
||||
.bj-amount .unit { font-weight: 800; color: var(--text-sub); padding-right: 4px; }
|
||||
.bj-step { width: 40px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-size: 1.3rem; font-weight: 900; cursor: pointer; }
|
||||
.bj-step:disabled { opacity: .4; cursor: default; }
|
||||
.bj-chipbtns { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
|
||||
.bj-chip { --c: #2563eb; width: 52px; height: 52px; border-radius: 50%; border: 0; cursor: pointer; color: #fff; font-weight: 900; font-size: .74rem; font-family: inherit; white-space: nowrap; padding: 0;
|
||||
background: radial-gradient(circle, var(--c) 0 52%, #fff 53% 58%, var(--c) 59%); box-shadow: 0 2px 4px rgba(0,0,0,.3), inset 0 0 0 3px rgba(255,255,255,.35); }
|
||||
.bj-chip:hover { transform: translateY(-2px); } .bj-chip:active { transform: translateY(1px); }
|
||||
.bj-chip:disabled { opacity: .35; cursor: default; transform: none; }
|
||||
.bj-quick { border: 1px solid var(--border); background: var(--surface); color: var(--text); border-radius: 999px; padding: 4px 12px; font: inherit; font-weight: 800; font-size: .82rem; cursor: pointer; }
|
||||
.bj-quick:disabled { opacity: .4; cursor: default; }
|
||||
.bj-range { width: 100%; accent-color: var(--primary); }
|
||||
.bj-acts { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 8px; }
|
||||
.bj-act { position: relative; min-height: 56px; border: 2px solid var(--c); border-radius: var(--radius); background: color-mix(in srgb, var(--c) 10%, var(--surface)); color: var(--c);
|
||||
font: inherit; font-weight: 900; font-size: 1.15rem; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.15; }
|
||||
.bj-act small { font-size: .7rem; font-weight: 700; color: var(--text-sub); }
|
||||
.bj-act kbd { position: absolute; left: 7px; top: 6px; font: inherit; font-size: .68rem; font-weight: 900; background: var(--c); color: #fff; border-radius: 5px; padding: 0 5px; }
|
||||
.bj-act:hover { background: color-mix(in srgb, var(--c) 18%, var(--surface)); }
|
||||
.bj-act:active { transform: translateY(1px); }
|
||||
:root[data-theme='dark'] .bj-act { color: color-mix(in srgb, var(--c) 55%, #fff); }
|
||||
.bj-help { margin: 0; text-align: center; min-height: 1.4em; }
|
||||
/* PC: the table takes all the height the dock leaves (cards grow with it, see BlackjackBoard). */
|
||||
@media (min-width: 1100px) {
|
||||
.bj-wrap { flex: 1 1 auto; min-height: 0; justify-content: center; }
|
||||
.bj-table { flex: 1 1 0; aspect-ratio: auto; max-height: calc(var(--play-w) * .62); }
|
||||
.bj-print b { font-size: calc(1.5rem * var(--bjs, 1)); }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.bj-table { aspect-ratio: auto; min-height: 0; border-width: 7px; border-radius: 24px; padding: 12px 8px; display: flex; flex-direction: column; gap: 14px; }
|
||||
.bj-print, .bj-shoe { display: none; }
|
||||
.bj-dealer { position: relative; left: auto; top: auto; transform: none; }
|
||||
.bj-seats { display: flex; flex-wrap: wrap; justify-content: center; gap: 14px 10px; }
|
||||
.bj-seat { position: relative; left: auto; top: auto; transform: none; width: auto; max-width: 100%; }
|
||||
.bj-seat.me { order: 99; flex-basis: 100%; }
|
||||
.bj-dock { flex-direction: column; gap: 10px; padding: 10px; }
|
||||
.bj-me { flex: none; flex-direction: row; justify-content: flex-start; gap: 10px; padding: 6px 10px; }
|
||||
.bj-info { display: none; }
|
||||
.bj-amount input { width: 6em; font-size: 1.3rem; }
|
||||
.bj-banner { position: fixed; top: 40%; font-size: 2.2rem; }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- deal queue (one card at a time)
|
||||
|
||||
const DEALER_GROUP = 1e6;
|
||||
|
||||
/** A key per card slot: real ids are unique per shoe; the face-down hole gets its own key so turning it is a new card. */
|
||||
const holeKey = (v: BlackjackView) => `hole-${v.handsPlayed}`;
|
||||
|
||||
/**
|
||||
* Every card the screen has not shown yet gets a landing time, in dealing order (card 1 of everyone, dealer, card 2 of
|
||||
* everyone, dealer, then hits / dealer draws), BJ_DEAL_STEP_MS apart. Cards render only once they have landed.
|
||||
*/
|
||||
function useDealQueue(v: BlackjackView) {
|
||||
const land = useRef<Map<string, number> | null>(null);
|
||||
const queueEnd = useRef(0);
|
||||
const hand = useRef(v.handsPlayed);
|
||||
const [, setTick] = useState(0);
|
||||
const now = Date.now();
|
||||
if (land.current && hand.current !== v.handsPlayed) {
|
||||
// A new hand: anything still queued from the last one shows at once, so a fast table never falls behind.
|
||||
hand.current = v.handsPlayed;
|
||||
for (const [k, at] of land.current) if (at > now) land.current.set(k, 0);
|
||||
queueEnd.current = now;
|
||||
}
|
||||
const step = Math.min(BJ_DEAL_STEP_MS, fxMs(300));
|
||||
const slots: { key: string; idx: number; group: number }[] = [];
|
||||
const orderIdx = (id: string) => {
|
||||
const i = v.order.indexOf(id);
|
||||
return i < 0 ? v.seats.findIndex((s) => s.id === id) : i;
|
||||
};
|
||||
for (const s of v.seats) s.hands?.forEach((h, hi) => h.cards.forEach((c, ci) => slots.push({ key: c, idx: ci, group: orderIdx(s.id) * 10 + hi })));
|
||||
v.dealer.cards.forEach((c, ci) => slots.push({ key: c ?? holeKey(v), idx: ci, group: DEALER_GROUP }));
|
||||
if (!land.current) {
|
||||
// First render (page load / reconnect): everything already on the table is shown at once.
|
||||
land.current = new Map(slots.map((x) => [x.key, 0]));
|
||||
} else {
|
||||
const fresh = slots.filter((x) => !land.current!.has(x.key)).sort((a, b) => a.idx - b.idx || a.group - b.group);
|
||||
let t = Math.max(now, queueEnd.current);
|
||||
for (const x of fresh) {
|
||||
land.current.set(x.key, t);
|
||||
t += step;
|
||||
}
|
||||
if (fresh.length) queueEnd.current = t;
|
||||
}
|
||||
const map = land.current;
|
||||
const pending = slots.filter((x) => (map.get(x.key) ?? 0) > now);
|
||||
const nextAt = pending.length ? Math.min(...pending.map((x) => map.get(x.key)!)) : 0;
|
||||
useEffect(() => {
|
||||
if (!nextAt) return undefined;
|
||||
const t = setTimeout(() => setTick((n) => n + 1), Math.max(0, nextAt - Date.now()) + 5);
|
||||
return () => clearTimeout(t);
|
||||
}, [nextAt]);
|
||||
return {
|
||||
shown: (key: string) => (map.get(key) ?? 0) <= now,
|
||||
/** Cards that landed just now (play the sound / animation). */
|
||||
landedRecently: (key: string) => {
|
||||
const at = map.get(key) ?? 0;
|
||||
return at > 0 && now - at < 600;
|
||||
},
|
||||
busy: pending.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 } {
|
||||
return cards.length ? handValue(cards as never) : { total: 0, soft: false };
|
||||
}
|
||||
|
||||
function TotalBadge({ cards, status, final }: { cards: string[]; status?: HandView['status']; final: boolean }) {
|
||||
if (!cards.length) return null;
|
||||
const { total, soft } = totalOf(cards);
|
||||
const bust = total > 21;
|
||||
const bj = final && status === 'blackjack';
|
||||
const label = bust ? `${total}` : soft && total < 21 ? `${total - 10}/${total}` : `${total}`;
|
||||
return <span className={`bj-total${bust ? ' bust' : bj ? ' bj' : total === 21 ? ' d21' : ''}`}>{bj ? '블랙잭' : label}</span>;
|
||||
}
|
||||
|
||||
function DealtCard({ id, width, anim }: { id: string | null; width: number; anim: 'in' | 'flip' | null }) {
|
||||
// Fly-in offset from the shoe (top right of the table) to this card, measured before the first paint.
|
||||
const ref = useRef<HTMLSpanElement | null>(null);
|
||||
const [off, setOff] = useState<CSSProperties>({});
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || anim !== 'in') return;
|
||||
const shoe = el.closest('.bj-table')?.querySelector('.bj-shoe')?.getBoundingClientRect();
|
||||
const r = el.getBoundingClientRect();
|
||||
if (shoe && shoe.width) setOff({ ['--fx' as string]: `${Math.round(shoe.left - r.left)}px`, ['--fy' as string]: `${Math.round(shoe.top - r.top)}px` });
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return (
|
||||
<span ref={ref} className={anim === 'in' ? 'bj-card-in' : anim === 'flip' ? 'bj-card-flip' : undefined} style={{ display: 'inline-block', ...off }}>
|
||||
<PlayingCard card={id ? baseCard(id as never) : null} width={width} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 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';
|
||||
return (
|
||||
<div className={`bj-hand${active ? ' on' : ''}${done && h.status === 'bust' ? ' anim-shake' : ''}`}>
|
||||
<div className="bj-cards" style={{ ['--cw' as string]: `${width}px`, ['--ov' as string]: overlapOf(h.cards.length), minHeight: Math.round(width * 1.4) }}>
|
||||
{cards.map((c) => (
|
||||
<DealtCard key={c} id={c} width={width} anim={q.landedRecently(c) ? 'in' : null} />
|
||||
))}
|
||||
</div>
|
||||
<div className="meta">
|
||||
<TotalBadge cards={landed} status={h.status} final={done} />
|
||||
<span className="bj-bet" title="건 칩">
|
||||
<ChipIcon size={14} />
|
||||
{h.bet.toLocaleString('ko-KR')}
|
||||
{h.doubled ? ' ×2' : ''}
|
||||
</span>
|
||||
{tag && (
|
||||
<span className="bj-tag anim-pop" style={{ background: color }}>
|
||||
{tag}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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(chips)}`}>
|
||||
{seat.hands ? (
|
||||
<div className="hands">
|
||||
{Array.from({ length: rows }, (_, r) => (
|
||||
<div key={r} className="hrow">
|
||||
{hands.slice(r * per, r * per + per).map((h, j) => {
|
||||
const i = r * per + j;
|
||||
return <HandBox key={i} h={h} active={isTurn && i === seat.active} width={width} q={q} final={final} />;
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : v.phase === 'betting' && seat.status === 'playing' ? (
|
||||
<span className="bj-wait">{seat.betLocked ? `${seat.bet.toLocaleString('ko-KR')} 칩 걸었어요` : '베팅하는 중…'}</span>
|
||||
) : null}
|
||||
{final && seat.net !== null && seat.hands && (
|
||||
<span className={`bj-net anim-slide-up ${seat.net > 0 ? 'plus' : seat.net < 0 ? 'minus' : 'zero'}`}>{seat.net > 0 ? `+${formatChips(seat.net)}` : seat.net < 0 ? `-${formatChips(-seat.net)}` : '본전'}</span>
|
||||
)}
|
||||
<div className="bj-name">
|
||||
{maxW >= 130 && <Avatar user={u} size={24} />}
|
||||
<span className="nm">
|
||||
{u.nickname}
|
||||
{seat.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<span className="ch">{chips.toLocaleString('ko-KR')}</span>
|
||||
{seat.status === 'out' && <span className="small">칩 소진</span>}
|
||||
{seat.status === 'left' && <span className="small">나감</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** How much each card of a hand hides the one before (more cards → tighter fan). */
|
||||
const overlapOf = (cards: number) => (cards >= 5 ? 0.68 : cards === 4 ? 0.58 : 0.42);
|
||||
|
||||
/** Width a hand needs, in card widths (first card whole, the rest the visible part). */
|
||||
const handUnits = (h: HandView) => 1 + (h.cards.length - 1) * (1 - overlapOf(h.cards.length));
|
||||
|
||||
/**
|
||||
* Card width that fits `hands` (in `rows` rows) into `avail` px: hand padding 16 px, gap 10 px. Never bigger than
|
||||
* `base`, never smaller than 26 px.
|
||||
*/
|
||||
function fitCardWidth(hands: HandView[], avail: number, base: number, rows: number): number {
|
||||
if (!hands.length) return base;
|
||||
const per = Math.ceil(hands.length / rows);
|
||||
let worst = 0;
|
||||
let cnt = 1;
|
||||
for (let r = 0; r < rows; r++) {
|
||||
const row = hands.slice(r * per, r * per + per);
|
||||
const u = row.reduce((a, h) => a + handUnits(h), 0);
|
||||
if (u > worst) {
|
||||
worst = u;
|
||||
cnt = row.length;
|
||||
}
|
||||
}
|
||||
const w = (avail - cnt * 16 - (cnt - 1) * 10) / worst;
|
||||
return Math.max(26, Math.min(base, Math.floor(w)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Seats along the front of the table, left to right, I sit in the middle (dealing goes right → left, first base on
|
||||
* the right). Each seat gets a share of the width by weight — mine and split seats more — so neighbours never run
|
||||
* into each other; the shallow arc puts the middle lowest. `share` is in % of the table width.
|
||||
*/
|
||||
function seatLayout(v: BlackjackView, me: string | null): { id: string; x: number; y: number; share: number }[] {
|
||||
const ids = (v.order.length ? v.order : v.seats.map((s) => s.id)).filter((id) => v.seats.some((s) => s.id === id));
|
||||
for (const s of v.seats) if (!ids.includes(s.id)) ids.push(s.id);
|
||||
let ltr = [...ids].reverse();
|
||||
const n = ltr.length;
|
||||
const mid = Math.floor(n / 2);
|
||||
const mi = me ? ltr.indexOf(me) : -1;
|
||||
if (mi >= 0) ltr = ltr.map((_, i) => ltr[(i + mi - mid + n) % n]!);
|
||||
const handsOf = (id: string) => Math.max(1, v.seats.find((s) => s.id === id)?.hands?.length ?? 1);
|
||||
const weight = (id: string) => (id === me ? Math.min(3.2, Math.max(1.8, 1.1 * Math.ceil(handsOf(id) / (handsOf(id) >= 3 ? 2 : 1)))) : Math.min(2, Math.max(1, 0.8 * handsOf(id))));
|
||||
const ws = ltr.map(weight);
|
||||
const total = ws.reduce((a, b) => a + b, 0);
|
||||
const span = Math.min(90, 18 * total);
|
||||
let acc = 50 - span / 2;
|
||||
return ltr.map((id, i) => {
|
||||
const share = (span * ws[i]!) / total;
|
||||
const x = acc + share / 2;
|
||||
acc += share;
|
||||
const t = (x - 50) / 45;
|
||||
return { id, x, y: 96 - 24 * t * t, share };
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- dock (all my controls)
|
||||
|
||||
const ACT_KEYS: Record<string, string> = { hit: 'H', stand: 'S', double: 'D', split: 'P', surrender: 'R' };
|
||||
|
||||
function BetPanel({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
|
||||
const range = v.betRange!;
|
||||
const clamp = (n: number) => Math.min(range.max, Math.max(range.min, Math.round(n / range.step) * range.step));
|
||||
const last = Number(localStorage.getItem('bj:lastBet') ?? 0) || range.min;
|
||||
const [amount, setAmount] = useState(() => clamp(last));
|
||||
const [text, setText] = useState(String(clamp(last)));
|
||||
const [typing, setTyping] = useState(false);
|
||||
const set = (n: number) => {
|
||||
const c = clamp(n);
|
||||
setAmount(c);
|
||||
setText(String(c));
|
||||
sfx.chip();
|
||||
};
|
||||
const typed = Number(text.replace(/[^\d]/g, ''));
|
||||
const bad = typing && (!Number.isFinite(typed) || typed < range.min || typed > range.max || typed % range.step !== 0);
|
||||
const wheelRef = useRef<HTMLDivElement | null>(null);
|
||||
const amountRef = useRef(amount);
|
||||
amountRef.current = amount;
|
||||
useEffect(() => {
|
||||
// Wheel over the bet panel: up = more, down = less (Shift = ×10). Non-passive so the page does not scroll.
|
||||
const el = wheelRef.current;
|
||||
if (!el) return undefined;
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
e.preventDefault();
|
||||
const k = (e.shiftKey ? 10 : 1) * (e.deltaY < 0 ? 1 : -1);
|
||||
set(amountRef.current + k * range.step);
|
||||
};
|
||||
el.addEventListener('wheel', onWheel, { passive: false });
|
||||
return () => el.removeEventListener('wheel', onWheel);
|
||||
}, [range.step, range.min, range.max]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const confirm = () => {
|
||||
const n = typing ? clamp(typed) : amount;
|
||||
localStorage.setItem('bj:lastBet', String(n));
|
||||
sfx.chips(3);
|
||||
act({ type: 'bet', amount: n });
|
||||
};
|
||||
const chips: [number, string][] = [
|
||||
[1, '#2563eb'],
|
||||
[5, '#dc2626'],
|
||||
[10, '#15803d'],
|
||||
[50, '#111827'],
|
||||
];
|
||||
return (
|
||||
<div className="stack" style={{ gap: 8 }} ref={wheelRef}>
|
||||
<div className="bj-betrow">
|
||||
<div className="bj-amount" title="숫자를 바로 적거나, 마우스 휠·↑↓ 키로 바꿀 수 있어요">
|
||||
<button type="button" className="bj-step" aria-label="베팅 줄이기" disabled={pending || amount <= range.min} onClick={() => set(amount - range.step)}>
|
||||
−
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
aria-label={`걸 칩 (${range.min.toLocaleString('ko-KR')}~${range.max.toLocaleString('ko-KR')}, ${range.step} 칩 단위)`}
|
||||
value={typing ? text : amount.toLocaleString('ko-KR')}
|
||||
onFocus={(e) => {
|
||||
setTyping(true);
|
||||
setText(String(amount));
|
||||
requestAnimationFrame(() => e.target.select());
|
||||
}}
|
||||
onChange={(e) => setText(e.target.value.replace(/[^\d]/g, '').slice(0, 7))}
|
||||
onBlur={() => {
|
||||
setTyping(false);
|
||||
if (text) set(typed);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!pending) confirm();
|
||||
} else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
const base = typing ? clamp(typed) : amount;
|
||||
set(base + (e.key === 'ArrowUp' ? 1 : -1) * (e.shiftKey ? 10 : 1) * range.step);
|
||||
setTyping(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span className="unit">칩</span>
|
||||
<button type="button" className="bj-step" aria-label="베팅 늘리기" disabled={pending || amount >= range.max} onClick={() => set(amount + range.step)}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 1, minWidth: 150, fontSize: '1.1rem' }} disabled={pending || bad} onClick={confirm}>
|
||||
{formatChips(typing && !bad ? clamp(typed) : amount)} 베팅
|
||||
</button>
|
||||
</div>
|
||||
<div className="bj-chipbtns">
|
||||
{chips.map(([k, c]) => (
|
||||
<button key={k} type="button" className="bj-chip" style={{ '--c': c } as CSSProperties} disabled={pending || amount >= range.max} onClick={() => set(amount + k * range.step)} aria-label={`${k * range.step} 칩 더하기`}>
|
||||
+{(k * range.step).toLocaleString('ko-KR')}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.min)}>
|
||||
최소
|
||||
</button>
|
||||
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.max / 2)}>
|
||||
절반
|
||||
</button>
|
||||
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(range.max)}>
|
||||
최대
|
||||
</button>
|
||||
<button type="button" className="bj-quick" disabled={pending} onClick={() => set(last)}>
|
||||
지난 베팅
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
className="bj-range"
|
||||
type="range"
|
||||
aria-label="베팅 칩 조절"
|
||||
min={range.min}
|
||||
max={range.max}
|
||||
step={range.step}
|
||||
value={amount}
|
||||
onChange={(e) => set(Number(e.target.value))}
|
||||
/>
|
||||
{bad && <span className="small" style={{ color: 'var(--danger)' }}>{`${range.min.toLocaleString('ko-KR')}~${range.max.toLocaleString('ko-KR')} 칩, ${range.step} 칩 단위로 적어 주세요. 적은 값에 가장 가까운 금액으로 맞춰 걸어요.`}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Actions({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
|
||||
const my = v.my!;
|
||||
const list: [string, string, boolean, string, string][] = [
|
||||
['hit', '히트', my.canHit, '#2563eb', '한 장 더'],
|
||||
['stand', '스탠드', my.canStand, '#15803d', '여기서 멈춤'],
|
||||
['double', '더블', my.canDouble, '#b45309', '두 배, 한 장만'],
|
||||
['split', '스플릿', my.canSplit, '#7c3aed', '둘로 나누기'],
|
||||
['surrender', '서렌더', my.canSurrender, '#6b7280', '절반 돌려받고 포기'],
|
||||
];
|
||||
const press = (t: string) => {
|
||||
if (pending) return;
|
||||
sfx.click();
|
||||
act({ type: t });
|
||||
};
|
||||
const pressRef = useRef(press);
|
||||
pressRef.current = press;
|
||||
const avail = list.filter((x) => x[2]).map((x) => x[0]);
|
||||
const availRef = useRef(avail);
|
||||
availRef.current = avail;
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
const el = e.target as HTMLElement | null;
|
||||
if (el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable)) return;
|
||||
const t = Object.keys(ACT_KEYS).find((k) => ACT_KEYS[k] === e.key.toUpperCase());
|
||||
if (t && availRef.current.includes(t)) {
|
||||
e.preventDefault();
|
||||
pressRef.current(t);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, []);
|
||||
return (
|
||||
<div className="bj-acts" role="group" aria-label="내 행동">
|
||||
{list
|
||||
.filter((x) => x[2])
|
||||
.map(([t, label, , c, sub]) => (
|
||||
<button key={t} type="button" className="bj-act anim-pop" style={{ '--c': c } as CSSProperties} disabled={pending} onClick={() => press(t)} aria-keyshortcuts={ACT_KEYS[t]} title={`${sub} (${ACT_KEYS[t]} 키)`}>
|
||||
<kbd aria-hidden>{ACT_KEYS[t]}</kbd>
|
||||
{label}
|
||||
<small>{sub}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
if (!seat) main = <p className="muted">구경 중이에요. {v.turn ? `${nick(players, v.turn)}님 차례예요.` : ''}</p>;
|
||||
else if (v.phase === 'betting')
|
||||
main = mine ? (
|
||||
<BetPanel key={v.handsPlayed} v={v} act={act} pending={pending} />
|
||||
) : seat.betLocked ? (
|
||||
<p>
|
||||
<strong>{formatChips(seat.bet)}</strong> 걸었어요. 다른 사람이 걸기를 기다려요.
|
||||
</p>
|
||||
) : (
|
||||
<p className="muted">이번 판은 쉬어요.</p>
|
||||
);
|
||||
else if (v.phase === 'insurance')
|
||||
main = v.insuranceOpen ? (
|
||||
<>
|
||||
<p>
|
||||
<strong>딜러가 A를 보여 줬어요.</strong> 인슈어런스를 걸까요? 딜러가 블랙잭이면 2:1로 돌려받아요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: true })}>
|
||||
걸기 ({formatChips(v.insuranceMax)})
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: false })}>
|
||||
안 함
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="muted">인슈어런스 선택을 기다려요.</p>
|
||||
);
|
||||
else if (v.phase === 'playing')
|
||||
main = mine ? <Actions v={v} act={act} pending={pending} /> : <p className="muted">{v.turn ? `${nick(players, v.turn)}님 차례예요.` : '딜러가 카드를 받고 있어요.'}</p>;
|
||||
else if (v.phase === 'handEnd')
|
||||
main = (
|
||||
<>
|
||||
<p style={{ fontSize: '1.1rem' }}>
|
||||
{!final ? (
|
||||
'딜러가 카드를 펼치는 중이에요…'
|
||||
) : !seat.hands ? (
|
||||
'이번 판은 쉬었어요.'
|
||||
) : (
|
||||
<>
|
||||
이번 판{' '}
|
||||
<strong style={{ color: seat.net && seat.net > 0 ? 'var(--success)' : seat.net && seat.net < 0 ? 'var(--danger)' : undefined }}>
|
||||
{seat.net === null || seat.net === 0 ? '본전이에요' : seat.net > 0 ? `+${formatChips(seat.net)} 땄어요` : `${formatChips(-seat.net)} 잃었어요`}
|
||||
</strong>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
{seat.hands && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={pending || seat.ready || !final} onClick={() => act({ type: 'ready' })}>
|
||||
{seat.ready ? '다음 판을 기다려요…' : '다음 판'}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
else main = <p className="muted">{v.result?.summary ?? '게임이 끝났어요.'}</p>;
|
||||
const turn = !!seat && mine && v.phase !== 'handEnd';
|
||||
return (
|
||||
<div className={`bj-dock${turn ? ' turn' : ''}`}>
|
||||
{seat && u && (
|
||||
<div className="bj-me">
|
||||
<Avatar user={u} size={44} />
|
||||
<span className="nm">{u.nickname} (나)</span>
|
||||
<span className="ch">
|
||||
<ChipIcon size={18} /> {chips(seat.id).toLocaleString('ko-KR')}
|
||||
</span>
|
||||
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={30} />}
|
||||
</div>
|
||||
)}
|
||||
<div className="bj-main">{main}</div>
|
||||
<div className="bj-info" aria-label="판 정보">
|
||||
<span>
|
||||
<b>{v.handLimit ? `${Math.min(v.handsPlayed + 1, v.handLimit)} / ${v.handLimit}판` : `${v.handsPlayed + 1}판째`}</b>
|
||||
</span>
|
||||
<span>
|
||||
블랙잭 {v.options.blackjackPayout} · 딜러 {v.options.dealerSoft17 === 'hit' ? 'H17' : 'S17'}
|
||||
</span>
|
||||
<span>슈에 약 {v.decksLeft}벌 남음</span>
|
||||
<span>
|
||||
키: 히트 H · 스탠드 S · 더블 D{v.options.surrender === 'late' ? ' · 서렌더 R' : ''} · 스플릿 P
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
export function isMyTurn(v: BlackjackView, me: string | null): boolean {
|
||||
if (!me || v.me !== me) return false;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!seat) return false;
|
||||
switch (v.phase) {
|
||||
case 'betting':
|
||||
return !seat.betLocked && !!v.betRange;
|
||||
case 'insurance':
|
||||
return v.insuranceOpen;
|
||||
case 'playing':
|
||||
return v.turn === me && !!v.my;
|
||||
case 'handEnd':
|
||||
return !!seat.hands && !seat.ready;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function BlackjackBoard({ view: v, me, players, act, pending, deadline }: BoardProps<BlackjackView>) {
|
||||
const mine = isMyTurn(v, me);
|
||||
const phone = usePhone();
|
||||
const q = useDealQueue(v);
|
||||
// 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 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);
|
||||
const [[tableW, tableH], setTableSize] = useState([990, 520]);
|
||||
// Cards grow with the table on PC (1 at the old 990×520 table, up to 1.7×).
|
||||
const scale = phone ? 1 : Math.min(1.7, Math.max(1, Math.min(tableW / 990, tableH / 520)));
|
||||
const otherW = phone ? 40 : Math.round(56 * scale);
|
||||
const myW = phone ? 56 : Math.round(76 * scale);
|
||||
const dealerW = phone ? 56 : Math.round(66 * scale);
|
||||
useLayoutEffect(() => {
|
||||
const el = tableRef.current;
|
||||
if (!el) return undefined;
|
||||
const measure = () => setTableSize([el.clientWidth, el.clientHeight]);
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
measure();
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
// Sounds + my result once the cards are down.
|
||||
const sounded = useRef(new Set<string>());
|
||||
const allKeys = [...v.seats.flatMap((s) => s.hands?.flatMap((h) => h.cards) ?? []), ...d.cards.map((c) => c ?? holeKey(v))];
|
||||
useEffect(() => {
|
||||
for (const k of allKeys) {
|
||||
if (!q.shown(k) || sounded.current.has(k)) continue;
|
||||
sounded.current.add(k);
|
||||
if (!q.landedRecently(k)) continue;
|
||||
if (d.cards.indexOf(k) === 1) sfx.cardFlip();
|
||||
else sfx.cardDeal();
|
||||
}
|
||||
});
|
||||
const [banner, setBanner] = useState<{ text: string; key: number } | null>(null);
|
||||
const resultFor = useRef<number>(-1);
|
||||
const mySeat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||
useEffect(() => {
|
||||
if (!final || !mySeat?.hands || resultFor.current === v.handsPlayed) return;
|
||||
resultFor.current = v.handsPlayed;
|
||||
const bj = mySeat.hands.some((h) => h.outcome === 'blackjack');
|
||||
if (bj) setBanner({ text: '블랙잭!', key: Date.now() });
|
||||
else if (d.bust) setBanner({ text: '딜러 버스트!', key: Date.now() });
|
||||
if ((mySeat.net ?? 0) > 0) {
|
||||
sfx.collect();
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if ((mySeat.net ?? 0) < 0) sounds.lose();
|
||||
}, [final, v.handsPlayed]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!banner) return undefined;
|
||||
const t = setTimeout(() => setBanner(null), fxMs(1500));
|
||||
return () => clearTimeout(t);
|
||||
}, [banner]);
|
||||
const prevTurn = useRef(v.turn);
|
||||
useLayoutEffect(() => {
|
||||
if (v.turn && v.turn !== prevTurn.current && v.turn === me) {
|
||||
sounds.myTurn();
|
||||
haptic(40);
|
||||
}
|
||||
prevTurn.current = v.turn;
|
||||
}, [v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
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 ?? [];
|
||||
const rows = hands.length >= 3 ? 2 : 1;
|
||||
const avail = Math.floor(phone ? (id === me ? tableW - 24 : (tableW - 34) / 2) : (tableW * share) / 100 - 8);
|
||||
// Height too (PC): the seat grows upward from its spot and must stay below the dealer's cards
|
||||
// (dealer row ≈ 40 + 1.4 × dealer card; per hand row: 1.4 × card + 50 for padding and the total line; name + result ≈ 64).
|
||||
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} chips={chips(id)} />;
|
||||
});
|
||||
return (
|
||||
<div className="bj-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="bj-table" ref={tableRef} role="region" aria-label="블랙잭 테이블" style={{ ['--bjs' as string]: scale.toFixed(2) }}>
|
||||
<div className="bj-print" aria-hidden>
|
||||
<b>BLACKJACK</b>
|
||||
<span>
|
||||
블랙잭 {v.options.blackjackPayout} · 딜러는 {v.options.dealerSoft17 === 'hit' ? '소프트 17에서 받아요' : '17 이상이면 멈춰요'}
|
||||
{v.options.insurance ? ' · 인슈어런스 2:1' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="bj-shoe" aria-hidden>
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
<small>슈 {v.decksLeft}벌</small>
|
||||
</div>
|
||||
<div className="bj-dealer" aria-label={`딜러 ${d.revealed ? d.total : `${d.total} +?`}`}>
|
||||
<div className="who">
|
||||
<span>딜러</span>
|
||||
{dealerReal.length > 0 && (
|
||||
<TotalBadge cards={d.revealed && dealerDone ? (d.cards as string[]) : dealerReal} status={d.blackjack && dealerDone ? 'blackjack' : undefined} final={d.revealed && dealerDone} />
|
||||
)}
|
||||
{!d.revealed && d.cards.length > 1 && dealerDone && <span className="small" style={{ opacity: 0.8 }}>+ ?</span>}
|
||||
</div>
|
||||
<div className="bj-cards" style={{ ['--cw' as string]: `${dealerW}px`, minHeight: Math.round(dealerW * 1.4) }}>
|
||||
{d.cards.length === 0 && <span className="bj-wait">베팅이 끝나면 카드를 나눠 줘요</span>}
|
||||
{d.cards.map((c, i) => {
|
||||
const k = c ?? holeKey(v);
|
||||
if (!q.shown(k)) return null;
|
||||
return <DealtCard key={k} id={c} width={dealerW} anim={q.landedRecently(k) ? (i === 1 && c ? 'flip' : 'in') : null} />;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{phone ? <div className="bj-seats">{seatEls}</div> : seatEls}
|
||||
{banner && (
|
||||
<div key={banner.key} className="bj-banner anim-banner" aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} chips={chips} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,7 +33,7 @@ export function helpNow(v: BlackjackView, me: string | null, players: Record<str
|
||||
|
||||
if (v.phase === 'betting') {
|
||||
if (!seat.betLocked && v.betRange) {
|
||||
return `베팅할 차례예요. 내 칩은 ${chips(seat.chips)}.\n${chips(v.betRange.min)}부터 ${chips(v.betRange.max)}까지 ${v.betRange.step.toLocaleString('ko-KR')} 칩 단위로 걸고 [베팅]을 눌러요. ${goal}`;
|
||||
return `베팅할 차례예요. 내 칩은 ${chips(seat.chips)}.\n${chips(v.betRange.min)}부터 ${chips(v.betRange.max)}까지 ${v.betRange.step.toLocaleString('ko-KR')} 칩 단위로 걸어요. 아래 판에서 숫자를 바로 적거나, 마우스 휠·↑↓ 키·칩 버튼(+10 등)·막대로 정한 뒤 [베팅](또는 Enter)을 눌러요. ${goal}`;
|
||||
}
|
||||
return `베팅을 걸었어요(${chips(seat.bet)}). 다른 사람이 걸면 카드를 나눠 줘요.`;
|
||||
}
|
||||
@@ -62,7 +62,7 @@ export function helpNow(v: BlackjackView, me: string | null, players: Record<str
|
||||
if (my.canDouble) acts.push('[더블]은 베팅을 두 배로 걸고 딱 한 장만 받아요');
|
||||
if (my.canSplit) acts.push('[스플릿]은 같은 숫자 두 장을 두 손패로 나눠요(베팅 한 번 더)');
|
||||
if (my.canSurrender) acts.push('[서렌더]는 베팅 절반만 잃고 이 판을 포기해요');
|
||||
lines.push(acts.join('. ') + '.');
|
||||
lines.push(acts.join('. ') + '. 키보드로는 H 히트, S 스탠드, D 더블, P 스플릿, R 서렌더예요.');
|
||||
if ((h?.total ?? 0) >= 17 && !h?.soft) lines.push('17 이상이면 보통 멈춰요. 더 받으면 버스트 위험이 커요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
@@ -1,35 +1,16 @@
|
||||
/** 블랙잭 화면 (docs/games/blackjack.md §9). Standard-deck art reuses components/cards/PlayingCard. */
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import type { BlackjackOptions, BlackjackView, HandView, SeatView } from '@bg/games/blackjack';
|
||||
import { baseCard } from '@bg/games/blackjack';
|
||||
/** 블랙잭 화면 (docs/games/blackjack.md §9): 판·조작은 board.tsx, 여기는 옆 패널(칩 순위)·설정·규칙. */
|
||||
import type { ReactNode } from 'react';
|
||||
import type { BlackjackOptions, BlackjackView } from '@bg/games/blackjack';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT, PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
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, useLandedChips } from './board';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
|
||||
function isMyTurn(v: BlackjackView, me: string | null): boolean {
|
||||
if (!me || v.me !== me) return false;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!seat) return false;
|
||||
switch (v.phase) {
|
||||
case 'betting':
|
||||
return !seat.betLocked && !!v.betRange;
|
||||
case 'insurance':
|
||||
return v.insuranceOpen;
|
||||
case 'playing':
|
||||
return v.turn === me && !!v.my;
|
||||
case 'handEnd':
|
||||
return !!seat.hands && !seat.ready;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function statusText(v: BlackjackView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
switch (v.phase) {
|
||||
case 'betting':
|
||||
@@ -45,199 +26,34 @@ function statusText(v: BlackjackView, me: string | null, players: Record<string,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- hand rendering
|
||||
// ---------------------------------------------------------------- side (standings only; every control is on the board)
|
||||
|
||||
const HAND_KO: Record<HandView['status'], string> = {
|
||||
playing: '',
|
||||
stand: '',
|
||||
bust: '버스트',
|
||||
blackjack: '블랙잭!',
|
||||
charlie: '찰리!',
|
||||
surrender: '서렌더',
|
||||
};
|
||||
const OUTCOME_KO: Record<NonNullable<HandView['outcome']>, string> = {
|
||||
win: '승', lose: '패', push: '푸시', blackjack: '블랙잭', bonus: '보너스',
|
||||
};
|
||||
|
||||
function totalLabel(h: HandView): string {
|
||||
if (h.status === 'bust') return `${h.total} 버스트`;
|
||||
return h.soft ? `${h.total - 10}/${h.total}` : `${h.total}`;
|
||||
}
|
||||
|
||||
function CardRow({ cards, size = 'md' }: { cards: (string | null)[]; size?: 'sm' | 'md' }) {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 4 }}>
|
||||
{cards.map((c, i) => (
|
||||
<PlayingCard key={i} card={c ? baseCard(c) : null} size={size} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HandBox({ h, active }: { h: HandView; active: boolean }) {
|
||||
const tag = h.outcome ? OUTCOME_KO[h.outcome] : 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';
|
||||
return (
|
||||
<div style={{ padding: 6, borderRadius: 10, border: active ? '2px solid #f59e0b' : '2px solid transparent', background: active ? 'rgba(245,158,11,0.12)' : 'transparent' }}>
|
||||
<CardRow cards={h.cards} size="sm" />
|
||||
<div className="small" style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }}>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{totalLabel(h)}</strong>
|
||||
<span className="muted">{formatChips(h.bet)}{h.doubled ? ' ×2' : ''}</span>
|
||||
{tag && <strong style={{ color }}>{tag}</strong>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeatHands({ seat, me, players, isTurn }: { seat: SeatView; me: string | null; players: Record<string, PublicUser>; isTurn: boolean }) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<div className="small" style={{ fontWeight: 800, marginBottom: 2 }}>
|
||||
{seat.id === me ? '나' : nick(players, seat.id)}
|
||||
{seat.net !== null && seat.net !== 0 && <span style={{ color: seat.net > 0 ? '#16a34a' : '#dc2626', marginLeft: 6 }}>{seat.net > 0 ? '+' : ''}{formatChips(seat.net)}</span>}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
|
||||
{seat.hands!.map((h, i) => (
|
||||
<HandBox key={i} h={h} active={isTurn && i === seat.active} />
|
||||
))}
|
||||
</div>
|
||||
<div className="small muted">{formatChips(seat.chips)}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function Board({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
const d = v.dealer;
|
||||
const dealerTotal = d.revealed ? (d.bust ? `${d.total} 버스트` : d.blackjack ? '블랙잭' : `${d.total}`) : `${d.total} +?`;
|
||||
const dealt = v.seats.filter((s) => s.hands);
|
||||
return (
|
||||
<div style={{ background: 'radial-gradient(circle at 50% 0%, #0f6b3d, #0a4f2d)', borderRadius: 16, padding: 16, color: '#fff' }}>
|
||||
<div style={{ textAlign: 'center', marginBottom: 12 }}>
|
||||
<div className="small" style={{ fontWeight: 800, opacity: 0.85 }}>딜러 · {dealerTotal}</div>
|
||||
<div style={{ display: 'flex', gap: 4, justifyContent: 'center', marginTop: 4, minHeight: 90 }}>
|
||||
{d.cards.length ? d.cards.map((c, i) => <PlayingCard key={i} card={c ? baseCard(c) : null} size="md" />) : <span className="small" style={{ opacity: 0.7, alignSelf: 'center' }}>베팅을 기다려요</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap' }}>
|
||||
{dealt.length ? (
|
||||
dealt.map((seat) => <SeatHands key={seat.id} seat={seat} me={me} players={players} isTurn={v.phase === 'playing' && v.turn === seat.id} />)
|
||||
) : (
|
||||
<span className="small" style={{ opacity: 0.8 }}>모두 베팅하는 중이에요…</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side (controls)
|
||||
|
||||
function BetControls({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
|
||||
const range = v.betRange!;
|
||||
const [amount, setAmount] = useState(range.min);
|
||||
const amt = Math.min(range.max, Math.max(range.min, Math.round(amount / range.step) * range.step));
|
||||
const step = (d: number) => setAmount((a) => Math.min(range.max, Math.max(range.min, a + d * range.step)));
|
||||
return (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center' }}>
|
||||
<button type="button" className="btn btn-secondary" disabled={pending || amt <= range.min} onClick={() => step(-1)} aria-label="베팅 줄이기">−</button>
|
||||
<strong style={{ minWidth: 90, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>{formatChips(amt)}</strong>
|
||||
<button type="button" className="btn btn-secondary" disabled={pending || amt >= range.max} onClick={() => step(1)} aria-label="베팅 늘리기">+</button>
|
||||
</div>
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={pending} onClick={() => act({ type: 'bet', amount: amt })}>
|
||||
{formatChips(amt)} 베팅
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButtons({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => void; pending: boolean }) {
|
||||
const my = v.my!;
|
||||
const btn = (label: string, type: string, on: boolean, primary = false) =>
|
||||
on ? (
|
||||
<button key={type} type="button" className={`btn ${primary ? 'btn-primary' : 'btn-secondary'}`} style={{ flex: 1, minWidth: 72 }} disabled={pending} onClick={() => act({ type })}>
|
||||
{label}
|
||||
</button>
|
||||
) : null;
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
{btn('히트', 'hit', my.canHit, true)}
|
||||
{btn('스탠드', 'stand', my.canStand)}
|
||||
{btn('더블', 'double', my.canDouble)}
|
||||
{btn('스플릿', 'split', my.canSplit)}
|
||||
{btn('서렌더', 'surrender', my.canSurrender)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Side({ view: v, me, players, act, pending, deadline }: BoardProps<BlackjackView>) {
|
||||
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||
const mine = isMyTurn(v, me);
|
||||
function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
// 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 }}>
|
||||
{seat && (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<Chips n={seat.chips} strong />
|
||||
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={28} />}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{v.phase === 'betting' && seat && (mine ? <BetControls v={v} act={act} pending={pending} /> : seat.betLocked ? <p className="small muted">베팅함: {formatChips(seat.bet)} · 다른 사람을 기다려요</p> : <p className="small muted">이번 판은 쉬어요</p>)}
|
||||
|
||||
{v.phase === 'insurance' && (v.insuranceOpen ? (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<p className="small">딜러가 A를 보여 줬어요. 인슈어런스를 걸까요?</p>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button type="button" className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: true })}>
|
||||
걸기 ({formatChips(v.insuranceMax)})
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'insurance', take: false })}>
|
||||
안 함
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="small muted">인슈어런스 선택을 기다려요</p>
|
||||
))}
|
||||
|
||||
{v.phase === 'playing' && (mine ? <ActionButtons v={v} act={act} pending={pending} /> : <p className="small muted">{v.turn ? `${nick(players, v.turn)}님 차례예요` : '딜러가 카드를 받고 있어요'}</p>)}
|
||||
|
||||
{v.phase === 'handEnd' && seat?.hands && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<p className="small">
|
||||
이번 판 {seat.net === null || seat.net === 0 ? '비겼어요' : seat.net > 0 ? `+${formatChips(seat.net)} 땄어요` : `${formatChips(seat.net)} 잃었어요`}.
|
||||
</p>
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={pending || seat.ready} onClick={() => act({ type: 'ready' })}>
|
||||
{seat.ready ? '다음 판을 기다려요…' : '다음 판'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SeatList v={v} me={me} players={players} />
|
||||
|
||||
{seat && <PlayChipNotice />}
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>칩 순위</strong>
|
||||
<ul className="stack" style={{ gap: 4, listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{ranked.map((s, i) => (
|
||||
<li key={s.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, opacity: s.status === 'out' || s.status === 'left' ? 0.5 : 1 }}>
|
||||
<span className="small" style={{ fontWeight: v.turn === s.id ? 800 : 600 }}>
|
||||
{i + 1}. {s.id === me ? '나' : nick(players, s.id)}
|
||||
{s.status === 'out' && ' (칩 소진)'}
|
||||
{s.status === 'left' && ' (나감)'}
|
||||
</span>
|
||||
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(chips(s.id))}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
{me && v.seats.some((s) => s.id === me) && <PlayChipNotice />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeatList({ v, me, players }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
return (
|
||||
<ul className="stack" style={{ gap: 4, listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{v.seats.map((s) => (
|
||||
<li key={s.id} style={{ display: 'flex', justifyContent: 'space-between', opacity: s.status === 'out' || s.status === 'left' ? 0.5 : 1 }}>
|
||||
<span className="small" style={{ fontWeight: v.turn === s.id ? 800 : 500 }}>
|
||||
{s.id === me ? '나' : nick(players, s.id)}
|
||||
{s.status === 'out' && ' (칩 소진)'}
|
||||
{s.status === 'left' && ' (나감)'}
|
||||
</span>
|
||||
<span className="small muted">{formatChips(s.chips)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options (room settings)
|
||||
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
@@ -375,7 +191,7 @@ function Rules({ options }: { options?: BlackjackOptions }) {
|
||||
}
|
||||
|
||||
const ui: GameUI<BlackjackView, BlackjackOptions> = {
|
||||
Board,
|
||||
Board: BlackjackBoard,
|
||||
Side,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
|
||||
37
apps/web/src/games/case-file/help.ts
Normal file
37
apps/web/src/games/case-file/help.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/** 사건 파일 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view (never the case data). */
|
||||
import type { CaseFileView } from '@bg/games/case-file';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const nm = (players: Record<string, PublicUser>, id: string | null | undefined) => `${(id && players[id]?.nickname) || '다른 사람'}님`;
|
||||
export const clock = (h: number) => `${String(Math.floor(h)).padStart(2, '0')}:00`;
|
||||
|
||||
export function helpNow(v: CaseFileView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const goal = '정해진 날짜와 시간 안에 단서를 골라 읽고, 마지막에 수사 보고서 문제를 풀어 점수를 받아요.';
|
||||
if (v.phase === 'ended') {
|
||||
return `수사가 끝났어요. ${v.final?.summary ?? ''}`.trim() + '\n[결과] 탭에서 정답과 풀이, [놓친 단서 보기]로 못 본 단서를 모두 읽을 수 있어요.';
|
||||
}
|
||||
if (v.phase === 'briefing') {
|
||||
return v.can.ready
|
||||
? `의뢰를 읽고 [수사 시작]을 눌러요. 모두 누르거나 60초가 지나면 수사가 시작돼요.\n${goal}`
|
||||
: `의뢰를 읽는 중이에요. 다른 사람이 [수사 시작]을 누르길 기다려요.\n${goal}`;
|
||||
}
|
||||
const inv = v.inv;
|
||||
const time = inv ? `지금 ${inv.day}일째 ${clock(inv.hour)}, ${inv.placeName}에 있어요(하루는 ${clock(inv.dayEnd)}까지).` : '';
|
||||
if (v.can.answer) {
|
||||
return `보고서를 쓸 차례예요. 문제마다 답을 고르고 [보고서 내기]를 두 번 눌러 확정해요. 낸 뒤에는 고칠 수 없어요.\n[기록]·[자료] 탭에서 읽은 단서를 다시 볼 수 있어요.`;
|
||||
}
|
||||
if (v.phase === 'report' || inv?.reported) return '보고서를 냈어요. 다른 사람이 다 낼 때까지 기다려요. 끝나면 정답과 풀이가 나와요.';
|
||||
if (!me || !v.seats.some((s) => s.id === me)) return `관전 중이에요. ${time}\n${goal}`;
|
||||
const travel = '다른 동네로 가면 이동 시간이 더 들어요. 하루 끝을 넘기면 야근이에요(1시간마다 −1점).';
|
||||
if (v.mode === 'race') return `따로 겨루기예요. 내 속도로 단서를 고르고, 다 됐으면 [보고서 쓰기]를 눌러요. ${time}\n${travel}`;
|
||||
if (v.decision === 'vote') {
|
||||
return v.myVote
|
||||
? `투표했어요. 모두 투표하거나 시간이 끝나면 가장 많이 고른 칸을 해요. ${time}`
|
||||
: `다 같이 투표로 정해요. 단서 카드나 아래 칸에서 [투표]를 눌러요. ${time}\n${travel}`;
|
||||
}
|
||||
if (v.can.control) {
|
||||
const free = v.decision === 'free' ? ' 누르면 [정말 이걸로 해요]로 한 번 더 확인해요. 보고서는 모두 [보고서 쓰자]를 눌러야 써요.' : '';
|
||||
return `${v.decision === 'rotate' ? '내가 반장이에요. ' : ''}다음 단서를 골라요.${free} ${time}\n${travel} 읽은 단서에 🔍가 있으면 돋보기로 깊이 볼 수 있어요.`;
|
||||
}
|
||||
return `지금 반장은 ${nm(players, v.decider)}이에요. 단서 카드의 [추천]을 누르거나 채팅으로 의견을 내요. 단서를 하나 읽으면 반장이 넘어가요. ${time}`;
|
||||
}
|
||||
811
apps/web/src/games/case-file/index.tsx
Normal file
811
apps/web/src/games/case-file/index.tsx
Normal file
@@ -0,0 +1,811 @@
|
||||
/**
|
||||
* 사건 파일 화면 (docs/games/case-file.md §9). Imports only types and labels from the engine: the case texts reach
|
||||
* the browser through the view, one read lead at a time (no-case-text.test.ts checks the built bundle).
|
||||
*/
|
||||
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { CaseFileOptions, CaseFileView, Choice, ChoiceView, LeadCardView, LogEntryView, PlayerScore } from '@bg/games/case-file';
|
||||
import { CASE_LIST } from '@bg/games/case-file/types';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { sfx, sounds } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { clock, helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
type Players = Record<string, PublicUser>;
|
||||
const nick = (players: Players, id: string | null | undefined) => (id && players[id]?.nickname) || '알 수 없음';
|
||||
|
||||
const CSS = `
|
||||
.cf { width: 100%; max-width: 860px; display: flex; flex-direction: column; gap: 12px; align-self: stretch; margin: 0 auto; }
|
||||
@media (min-width: 1100px) { .cf { flex: 1; min-height: 0; overflow-y: auto; padding-right: 4px; } }
|
||||
.cf.ended { padding-bottom: 96px; }
|
||||
.cf-bar { display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; padding: 10px 14px; border-radius: var(--radius-lg); background: var(--surface); box-shadow: var(--shadow); }
|
||||
.cf-bar h2 { font-size: 1.05rem; margin: 0; flex: 1 1 100%; }
|
||||
.cf-bar .cf-clock { font-weight: 800; font-variant-numeric: tabular-nums; }
|
||||
.cf-dots { display: inline-flex; gap: 4px; }
|
||||
.cf-dots i { width: 10px; height: 10px; border-radius: 50%; background: var(--border); display: inline-block; }
|
||||
.cf-dots i.on { background: var(--primary); }
|
||||
.cf-tabs { display: flex; gap: 4px; background: var(--surface-2); padding: 4px; border-radius: var(--radius); position: sticky; top: 0; z-index: 2; }
|
||||
.cf-tabs button { flex: 1; min-height: 44px; border: 0; border-radius: 10px; background: transparent; color: var(--text); font: inherit; font-weight: 700; cursor: pointer; padding: 0 4px; }
|
||||
.cf-tabs button[aria-selected='true'] { background: var(--surface); box-shadow: var(--shadow); color: var(--primary); }
|
||||
.cf-paper { background: #fffaf0; color: #2b2116; border: 1px solid #e7d9bd; border-radius: 6px; padding: 16px; box-shadow: 0 2px 8px rgba(80,60,20,.12); position: relative; }
|
||||
:root[data-theme='dark'] .cf-paper { background: #2a2620; color: #f1eadc; border-color: #4a4130; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .cf-paper { background: #2a2620; color: #f1eadc; border-color: #4a4130; } }
|
||||
.cf-stamp { display: inline-block; font-size: .85rem; font-weight: 800; color: #b91c1c; border: 2px solid currentColor; border-radius: 6px; padding: 1px 8px; transform: rotate(-2deg); margin-bottom: 6px; }
|
||||
.cf-doc { font-size: max(16px, 1.05rem); line-height: 1.75; overflow-wrap: anywhere; }
|
||||
.cf-doc p { margin: 0 0 .7em; }
|
||||
.cf-doc ul { margin: 0 0 .7em; padding-left: 1.2em; }
|
||||
.cf-doc table { border-collapse: collapse; margin: 0 0 .7em; font-size: max(16px, 1rem); }
|
||||
.cf-doc td, .cf-doc th { border: 1px solid #d6c7a6; padding: 4px 10px; text-align: left; }
|
||||
.cf-deep { border-left: 4px solid #2563eb; padding: 8px 12px; margin-top: 8px; background: rgba(37,99,235,.07); border-radius: 4px; }
|
||||
.cf-leads { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 8px; }
|
||||
@media (max-width: 560px) { .cf-leads { grid-template-columns: minmax(0, 1fr); } }
|
||||
.cf-lead { display: flex; flex-direction: column; gap: 6px; padding: 12px; border-radius: var(--radius); border: 2px solid var(--border); background: var(--surface); }
|
||||
.cf-lead.mine { border-color: var(--primary); }
|
||||
.cf-lead.no { opacity: .55; }
|
||||
.cf-lead strong { font-size: max(16px, 1rem); }
|
||||
.cf-cost { font-size: .95rem; color: var(--text-sub); }
|
||||
.cf-tag { display: inline-block; font-size: .8rem; font-weight: 700; padding: 1px 7px; border-radius: 999px; background: var(--surface-2); margin-right: 4px; }
|
||||
.cf-tag.warn { background: var(--warning-soft); color: var(--warning); }
|
||||
.cf-btns { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.cf-btns .btn { flex: 1 1 auto; min-height: 44px; }
|
||||
.cf-place { font-size: .95rem; font-weight: 800; margin: 6px 0 2px; color: var(--text-sub); }
|
||||
.cf-zones { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.cf-zone { padding: 4px 10px; border-radius: 999px; border: 2px solid var(--border); font-size: .95rem; }
|
||||
.cf-zone.here { border-color: var(--primary); background: var(--primary-soft); font-weight: 800; }
|
||||
.cf-log { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.cf-log button.cf-row { width: 100%; text-align: left; min-height: 48px; padding: 8px 12px; border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface); color: var(--text); font: inherit; cursor: pointer; }
|
||||
.cf-person { padding: 10px 12px; border-radius: var(--radius); border: 2px solid var(--border); background: var(--surface); display: flex; gap: 8px; align-items: flex-start; }
|
||||
.cf-person[data-sus='1'] { border-color: #eab308; }
|
||||
.cf-person[data-sus='2'] { border-color: #dc2626; }
|
||||
.cf-q { display: flex; flex-direction: column; gap: 8px; }
|
||||
.cf-q .cf-choices { display: flex; flex-direction: column; gap: 6px; }
|
||||
.cf-q .cf-choices button { text-align: left; justify-content: flex-start; min-height: 48px; font-size: max(16px, 1rem); }
|
||||
.cf-grade { font-size: 2.6rem; font-weight: 900; color: #b91c1c; border: 5px double currentColor; border-radius: 12px; padding: 4px 18px; display: inline-block; transform: rotate(-6deg); animation: cf-stamp .5s ease-out; }
|
||||
.cf-grade.ok { color: #15803d; }
|
||||
@keyframes cf-stamp { from { transform: scale(2.4) rotate(-6deg); opacity: 0; } to { transform: scale(1) rotate(-6deg); opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) { .cf-grade { animation: none; } }
|
||||
.cf-table { width: 100%; border-collapse: collapse; font-size: .95rem; }
|
||||
.cf-table td, .cf-table th { border-bottom: 1px solid var(--border); padding: 6px 4px; text-align: left; vertical-align: top; }
|
||||
.cf-memo { width: 100%; min-height: 220px; font: inherit; font-size: max(16px, 1rem); line-height: 1.6; padding: 10px; border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface); color: var(--text); }
|
||||
.cf-main { display: flex; flex-direction: column; gap: 12px; }
|
||||
/* PC: use the whole play column. Reading (briefing / last clue) sits in a left column of readable width, choices on the right. */
|
||||
@media (min-width: 1100px) {
|
||||
.cf { max-width: none; }
|
||||
.cf-main { flex-direction: row; align-items: flex-start; }
|
||||
.cf-main > * { flex: 1 1 0; min-width: 0; }
|
||||
.cf-main > .cf-read { flex-grow: 1.15; }
|
||||
.cf-brief { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); align-content: start; align-items: start; }
|
||||
.cf-brief > .cf-bar { grid-column: 1 / -1; }
|
||||
.cf-brief > .cf-paper { grid-row: 2 / span 3; }
|
||||
.cf-brief > :not(.cf-bar):not(.cf-paper) { grid-column: 2; }
|
||||
.cf-memo { min-height: max(220px, calc(var(--play-h) - 260px)); }
|
||||
.cf-doc { font-size: clamp(16px, calc(var(--play-h) * .0185), 20px); }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- device-only notes (§9)
|
||||
|
||||
function roomCode(): string {
|
||||
return /\/r\/(\d{6})/.exec(typeof location !== 'undefined' ? location.pathname : '')?.[1] ?? 'replay';
|
||||
}
|
||||
function useStored<T>(kind: string, startedAt: number, init: T): [T, (v: T) => void] {
|
||||
const key = `bg:case-file:${kind}:${roomCode()}:${startedAt}`;
|
||||
const [val, setVal] = useState<T>(() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
return raw === null ? init : (JSON.parse(raw) as T);
|
||||
} catch {
|
||||
return init;
|
||||
}
|
||||
});
|
||||
const set = (v: T) => {
|
||||
setVal(v);
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(v));
|
||||
} catch {
|
||||
/* storage full or blocked: keep it in memory */
|
||||
}
|
||||
};
|
||||
return [val, set];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- text (a small markdown subset of the case doc)
|
||||
|
||||
function Inline({ text, titles }: { text: string; titles: Record<string, string> }) {
|
||||
const parts = text.split(/(\*\*[^*]+\*\*|`c\d-\d\d`)/g);
|
||||
return (
|
||||
<>
|
||||
{parts.map((p, i) => {
|
||||
if (p.startsWith('**') && p.endsWith('**')) return <strong key={i}>{p.slice(2, -2)}</strong>;
|
||||
if (/^`c\d-\d\d`$/.test(p)) return <Fragment key={i}>「{titles[p.slice(1, -1)] ?? p.slice(1, -1)}」</Fragment>;
|
||||
return <Fragment key={i}>{p}</Fragment>;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Doc({ text, titles = {} }: { text: string; titles?: Record<string, string> }) {
|
||||
const blocks = text.split(/\n\s*\n/);
|
||||
return (
|
||||
<div className="cf-doc">
|
||||
{blocks.map((b, i) => {
|
||||
const lines = b.split('\n');
|
||||
if (lines.every((l) => l.startsWith('|'))) {
|
||||
const rows = lines.filter((l) => !/^\|[-| ]+\|$/.test(l)).map((l) => l.slice(1, -1).split('|').map((c) => c.trim()));
|
||||
return (
|
||||
<table key={i}>
|
||||
<tbody>
|
||||
{rows.map((r, ri) => (
|
||||
<tr key={ri}>{r.map((c, ci) => (ri === 0 ? <th key={ci}>{c}</th> : <td key={ci}>{c}</td>))}</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
if (lines.every((l) => l.startsWith('- '))) {
|
||||
return (
|
||||
<ul key={i}>
|
||||
{lines.map((l, li) => (
|
||||
<li key={li}><Inline text={l.slice(2)} titles={titles} /></li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p key={i}>
|
||||
{lines.map((l, li) => (
|
||||
<Fragment key={li}>
|
||||
{li > 0 && <br />}
|
||||
<Inline text={l} titles={titles} />
|
||||
</Fragment>
|
||||
))}
|
||||
</p>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- shared bits
|
||||
|
||||
const actionOf = (ch: Choice): unknown => {
|
||||
switch (ch.type) {
|
||||
case 'lead':
|
||||
return { type: 'pick', lead: ch.lead };
|
||||
case 'deep':
|
||||
return { type: 'deep', lead: ch.lead };
|
||||
default:
|
||||
return { type: ch.type };
|
||||
}
|
||||
};
|
||||
const keyOf = (ch: Choice) => (ch.type === 'lead' || ch.type === 'deep' ? `${ch.type}:${ch.lead}` : ch.type);
|
||||
|
||||
/** Runs a choice: a vote in vote mode, otherwise a direct action that needs a second press to confirm (§5.2 free). */
|
||||
function useChooser(v: CaseFileView, act: (a: unknown) => void) {
|
||||
const [armed, setArmed] = useState<string | null>(null);
|
||||
useEffect(() => setArmed(null), [v.inv?.log.length, v.inv?.day, v.phase, v.decider]);
|
||||
const voting = v.can.vote;
|
||||
const mine = (key: string) => !!v.myVote && v.myVote !== 'pass' && keyOf(v.myVote) === key;
|
||||
const press = (c: ChoiceView) => {
|
||||
if (voting) {
|
||||
sfx.select();
|
||||
act({ type: 'vote', choice: c.choice });
|
||||
return;
|
||||
}
|
||||
if (armed !== c.key) {
|
||||
setArmed(c.key);
|
||||
sfx.click();
|
||||
return;
|
||||
}
|
||||
setArmed(null);
|
||||
if (c.choice.type === 'lead') sfx.cardFlip();
|
||||
act(actionOf(c.choice));
|
||||
};
|
||||
const label = (c: ChoiceView, base: string) => (voting ? (mine(c.key) ? `✓ 투표함: ${base}` : `투표: ${base}`) : armed === c.key ? '정말 이걸로 해요' : base);
|
||||
return { press, label, armed, voting, mine };
|
||||
}
|
||||
|
||||
function CaseBar({ v, players, deadline }: { v: CaseFileView; players: Players; deadline: number | null }) {
|
||||
const inv = v.inv;
|
||||
const mineTurn = v.can.control || (v.can.vote && !v.myVote) || v.can.answer || v.can.ready;
|
||||
return (
|
||||
<header className="cf-bar" aria-label="수사 현황">
|
||||
<h2>🔍 {v.title} <span className="small muted">({v.level})</span></h2>
|
||||
{inv && v.phase === 'investigate' && !inv.reported && (
|
||||
<>
|
||||
<span className="cf-clock">{inv.day}일째 {clock(inv.hour)} / {clock(inv.dayEnd)}까지</span>
|
||||
<span className="cf-dots" aria-label={`${v.days}일 중 ${inv.day}일째`}>
|
||||
{Array.from({ length: v.days }, (_, i) => <i key={i} className={i < inv.day ? 'on' : ''} />)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{inv && (
|
||||
<span className="small">
|
||||
<span title="돋보기">🔍 {inv.magnifiers}</span> · <span title="남은 조언">💡 {inv.hintsLeft}</span> · <span title="피로(야근)">😪 {inv.fatigue}</span>
|
||||
</span>
|
||||
)}
|
||||
{v.phase === 'investigate' && v.mode === 'coop' && v.decision === 'rotate' && <span className="small">지금 반장: <strong>{v.decider === v.me ? '나' : `${nick(players, v.decider)}님`}</strong></span>}
|
||||
{v.phase === 'investigate' && v.mode === 'coop' && v.decision === 'vote' && <span className="small">투표 {v.seats.filter((s) => s.voted).length}/{v.seats.filter((s) => !s.left).length}</span>}
|
||||
{deadline && v.phase !== 'ended' && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={mineTurn} size={44} />}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function ReadCard({ e, v, players, chooser, titles }: { e: LogEntryView; v: CaseFileView; players: Players; chooser?: ReturnType<typeof useChooser>; titles: Record<string, string> }) {
|
||||
const deep = v.choices.find((c) => c.key === `deep:${e.lead}`);
|
||||
return (
|
||||
<article className="cf-paper" aria-label={`단서: ${e.title}`}>
|
||||
<span className="cf-stamp">{e.day}일째 {clock(e.at)} · {e.placeName}</span>
|
||||
<h3 style={{ margin: '0 0 8px', fontSize: '1.1rem' }}>{e.title}</h3>
|
||||
{e.text !== null ? <Doc text={e.text} titles={titles} /> : <p className="cf-doc">📖 {nick(players, e.by)}님이 읽고 있어요. 채팅으로 들려 달라고 해 보세요.</p>}
|
||||
{e.deepUsed && (e.deepText !== null ? (
|
||||
<div className="cf-deep"><strong>🔍 깊이 보기</strong><Doc text={e.deepText} titles={titles} /></div>
|
||||
) : (
|
||||
<p className="small">🔍 {nick(players, e.deepBy)}님이 깊이 봤어요.</p>
|
||||
))}
|
||||
{e.opened.length > 0 && <p className="small" style={{ margin: '6px 0 0' }}>새로 열린 단서: {e.opened.join(', ')}</p>}
|
||||
{e.deepOpened.length > 0 && <p className="small" style={{ margin: '4px 0 0' }}>깊이 보기로 열린 단서: {e.deepOpened.join(', ')}</p>}
|
||||
{deep && chooser && (
|
||||
<div className="cf-btns" style={{ marginTop: 8 }}>
|
||||
<button type="button" className="btn btn-secondary" onClick={() => chooser.press(deep)}>{chooser.label(deep, '🔍 깊이 보기(돋보기 1개)')}</button>
|
||||
</div>
|
||||
)}
|
||||
{!deep && e.hasDeep && !e.deepUsed && v.phase === 'investigate' && <p className="small muted" style={{ margin: '6px 0 0' }}>🔍 이 단서는 깊이 볼 수 있어요{v.inv?.magnifiers ? '' : '(돋보기가 없어요)'}.</p>}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadCard({ l, v, players, chooser, onPin }: { l: LeadCardView; v: CaseFileView; players: Players; chooser: ReturnType<typeof useChooser>; onPin: (lead: string | null) => void }) {
|
||||
const c = v.choices.find((x) => x.key === `lead:${l.id}`);
|
||||
const myPin = v.me ? v.seats.find((s) => s.id === v.me)?.pin === l.id : false;
|
||||
const multi = v.seats.length > 1;
|
||||
return (
|
||||
<div className={`cf-lead${l.ok ? '' : ' no'}${chooser.mine(`lead:${l.id}`) || myPin ? ' mine' : ''}`}>
|
||||
<strong>{l.title}</strong>
|
||||
<span className="cf-cost">
|
||||
{l.travel > 0 ? `이동 ${l.travel} + ` : ''}단서 {l.hours}시간 = {l.total}시간
|
||||
</span>
|
||||
<span>
|
||||
{l.deep && <span className="cf-tag">🔍 깊이 보기 있음</span>}
|
||||
{l.overtime > 0 && <span className="cf-tag warn">야근 {l.overtime}시간</span>}
|
||||
{!l.ok && <span className="cf-tag warn">{l.why}</span>}
|
||||
</span>
|
||||
{l.pins.length > 0 && <span className="small">👍 {l.pins.map((p) => (p === v.me ? '나' : nick(players, p))).join(', ')}</span>}
|
||||
<div className="cf-btns">
|
||||
{c && <button type="button" className={`btn ${chooser.armed === c.key ? 'btn-primary' : 'btn-secondary'}`} onClick={() => chooser.press(c)}>{chooser.label(c, '고르기')}</button>}
|
||||
{v.can.pin && multi && (
|
||||
<button type="button" className="btn btn-ghost" aria-pressed={myPin} onClick={() => (sfx.pop(), onPin(myPin ? null : l.id))}>
|
||||
{myPin ? '추천 취소' : '👍 추천'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadsTab({ v, players, act, titles }: { v: CaseFileView; players: Players; act: (a: unknown) => void; titles: Record<string, string> }) {
|
||||
const inv = v.inv!;
|
||||
const chooser = useChooser(v, act);
|
||||
const onPin = (lead: string | null) => act({ type: 'pin', lead });
|
||||
const last = inv.log.at(-1);
|
||||
const today = inv.news.find((n) => n.day === inv.day);
|
||||
const groups = new Map<string, LeadCardView[]>();
|
||||
for (const l of inv.leads) groups.set(l.placeName, [...(groups.get(l.placeName) ?? []), l]);
|
||||
const extra = v.choices.filter((c) => c.choice.type === 'hint' || c.choice.type === 'endDay' || c.choice.type === 'report');
|
||||
const free = v.mode === 'coop' && v.decision === 'free';
|
||||
const meSeat = v.seats.find((s) => s.id === v.me);
|
||||
const here = v.seats.filter((s) => !s.left && s.idle === 0);
|
||||
return (
|
||||
<div className="cf-main">
|
||||
{((today && inv.hour === 9) || last) && (
|
||||
<div className="stack cf-read" style={{ gap: 12 }}>
|
||||
{today && inv.hour === 9 && (
|
||||
<div className="cf-paper"><span className="cf-stamp">📰 {today.day}일째 아침 소식</span><Doc text={today.text} /></div>
|
||||
)}
|
||||
{last && <ReadCard e={last} v={v} players={players} chooser={chooser} titles={titles} />}
|
||||
</div>
|
||||
)}
|
||||
<div className="stack" style={{ gap: 12 }}>
|
||||
<section aria-label="지도">
|
||||
<div className="small" style={{ marginBottom: 4 }}>📍 지금 위치: <strong>{inv.placeName}</strong> ({inv.zoneName})</div>
|
||||
<div className="cf-zones">
|
||||
{v.zones.map((z) => (
|
||||
<span key={z.id} className={`cf-zone${z.id === inv.zone ? ' here' : ''}`}>
|
||||
{z.name} {z.id === inv.zone ? '🕵️' : `· ${v.travel[inv.zone]?.[z.id] ?? 0}시간`}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section aria-label="고를 수 있는 단서" className="stack" style={{ gap: 4 }}>
|
||||
<h3 style={{ margin: 0, fontSize: '1.05rem' }}>고를 수 있는 단서 {inv.leads.length}개</h3>
|
||||
{!v.can.control && !v.can.vote && v.mode === 'coop' && <p className="small muted" style={{ margin: 0 }}>{v.decision === 'rotate' ? '반장이 골라요. 마음에 드는 단서에 [추천]을 눌러 주세요.' : '지금은 고를 수 없어요.'}</p>}
|
||||
{[...groups].map(([place, list]) => (
|
||||
<div key={place}>
|
||||
<div className="cf-place">{place}</div>
|
||||
<div className="cf-leads">
|
||||
{list.map((l) => <LeadCard key={l.id} l={l} v={v} players={players} chooser={chooser} onPin={onPin} />)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{inv.leads.length === 0 && <p className="muted">더 고를 단서가 없어요. 하루를 마치거나 보고서를 써요.</p>}
|
||||
</section>
|
||||
{extra.length > 0 && (
|
||||
<div className="cf-btns" role="group" aria-label="수사 행동">
|
||||
{extra.map((c) => {
|
||||
const base = c.choice.type === 'hint' ? `💡 ${c.label}(−2점, ${inv.hintsLeft}번 남음)` : c.choice.type === 'endDay' ? (inv.day >= v.days ? '🌙 마지막 날 마치기(보고서로)' : '🌙 하루 마치기') : '📝 보고서 쓰기';
|
||||
if (free && c.choice.type === 'report') {
|
||||
const agreed = !!meSeat?.agree;
|
||||
return (
|
||||
<button key={c.key} type="button" className={`btn ${agreed ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={agreed} onClick={() => act({ type: 'report' })}>
|
||||
📝 보고서 쓰자 ({v.seats.filter((s) => s.agree).length}/{here.length} 동의){agreed ? ' · 취소' : ''}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button key={c.key} type="button" className={`btn ${chooser.armed === c.key ? 'btn-primary' : 'btn-secondary'}`} onClick={() => chooser.press(c)}>
|
||||
{chooser.label(c, base)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{inv.hints.length > 0 && (
|
||||
<div className="cf-paper"><span className="cf-stamp">💡 반장님 조언</span><ol className="cf-doc" style={{ margin: 0, paddingLeft: '1.3em' }}>{inv.hints.map((h, i) => <li key={i}>{h}</li>)}</ol></div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LogTab({ v, players, startedAt, titles }: { v: CaseFileView; players: Players; startedAt: number; titles: Record<string, string> }) {
|
||||
const inv = v.inv;
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const [stars, setStars] = useStored<string[]>('star', startedAt, []);
|
||||
if (!inv || inv.log.length === 0) return <p className="muted">아직 읽은 단서가 없어요.</p>;
|
||||
const e = open === null ? null : inv.log[open - 1];
|
||||
return (
|
||||
<>
|
||||
<ol className="cf-log" aria-label="수사 기록">
|
||||
{inv.log.map((x) => (
|
||||
<li key={x.n} style={{ display: 'flex', gap: 6 }}>
|
||||
<button type="button" className="cf-row" onClick={() => setOpen(x.n)}>
|
||||
<span className="small muted">{x.day}일째 {clock(x.at)} · {x.placeName}</span>
|
||||
<br />
|
||||
<strong>{x.title}</strong>
|
||||
{x.deepUsed && ' 🔍'}
|
||||
{x.text === null && <span className="small muted"> · {nick(players, x.by)}님이 읽음</span>}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost" style={{ minWidth: 48 }} aria-pressed={stars.includes(x.lead)} aria-label={`${x.title} 중요 표시`} onClick={() => setStars(stars.includes(x.lead) ? stars.filter((s) => s !== x.lead) : [...stars, x.lead])}>
|
||||
{stars.includes(x.lead) ? '★' : '☆'}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{e && (
|
||||
<Sheet onClose={() => setOpen(null)} label={e.title}>
|
||||
<ReadCard e={e} v={v} players={players} titles={titles} />
|
||||
<button type="button" className="btn btn-secondary btn-block" onClick={() => setOpen(null)}>닫기</button>
|
||||
</Sheet>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const SUS = ['흰색', '노랑', '빨강'];
|
||||
function PeopleTab({ v, startedAt }: { v: CaseFileView; startedAt: number }) {
|
||||
const inv = v.inv;
|
||||
const [sus, setSus] = useStored<Record<string, number>>('suspect', startedAt, {});
|
||||
return (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<h3 style={{ margin: 0, fontSize: '1.05rem' }}>자료실 · 인물</h3>
|
||||
{(inv?.people ?? []).map((p) => (
|
||||
<div key={p.id} className="cf-person" data-sus={sus[p.id] ?? 0}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<strong>{p.name}</strong>
|
||||
<div className="cf-doc" style={{ lineHeight: 1.5 }}>{p.line}</div>
|
||||
<div className="small muted">{p.fromTitle ? `처음 나온 단서: ${p.fromTitle}` : '의뢰에서'}</div>
|
||||
</div>
|
||||
<button type="button" className="btn btn-ghost btn-sm" aria-label={`${p.name} 의심 정도: ${SUS[sus[p.id] ?? 0]}`} onClick={() => setSus({ ...sus, [p.id]: ((sus[p.id] ?? 0) + 1) % 3 })}>
|
||||
{['⚪', '🟡', '🔴'][sus[p.id] ?? 0]}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<h3 style={{ margin: '8px 0 0', fontSize: '1.05rem' }}>장소</h3>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: '1.2em' }}>
|
||||
{v.zones.map((z) => (
|
||||
<li key={z.id}><strong>{z.name}</strong>: {v.places.filter((p) => p.zone === z.id).map((p) => p.name).join(', ')}</li>
|
||||
))}
|
||||
</ul>
|
||||
{inv && inv.news.length > 0 && (
|
||||
<>
|
||||
<h3 style={{ margin: '8px 0 0', fontSize: '1.05rem' }}>아침 소식</h3>
|
||||
{inv.news.map((n) => <div key={n.day} className="cf-paper"><span className="cf-stamp">{n.day}일째 아침</span><Doc text={n.text} /></div>)}
|
||||
</>
|
||||
)}
|
||||
<details>
|
||||
<summary>의뢰 다시 읽기</summary>
|
||||
<div className="cf-paper" style={{ marginTop: 6 }}><Doc text={v.briefing} /></div>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MemoTab({ startedAt }: { startedAt: number }) {
|
||||
const [memo, setMemo] = useStored<string>('note', startedAt, '');
|
||||
return (
|
||||
<label className="stack" style={{ gap: 6 }}>
|
||||
<span className="small muted">메모는 이 기기에만 남아요.</span>
|
||||
<textarea className="cf-memo" value={memo} onChange={(e) => setMemo(e.target.value)} placeholder="알아낸 것, 시간표, 의심 가는 점을 적어 두세요." />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function ReportTab({ v, players, act }: { v: CaseFileView; players: Players; act: (a: unknown) => void }) {
|
||||
const [armed, setArmed] = useState(false);
|
||||
const qs = v.questions ?? [];
|
||||
const mine = v.myAnswers ?? {};
|
||||
const answered = qs.filter((q) => mine[q.id] !== undefined).length;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 12 }}>
|
||||
<div className="cf-paper">
|
||||
<span className="cf-stamp">수사 보고서</span>
|
||||
<p className="cf-doc" style={{ margin: 0 }}>문제마다 답을 하나씩 골라요. {v.mode === 'coop' ? '모두 내면 많이 고른 답이 팀 답이 돼요.' : '내 답으로 내 점수가 나와요.'} 범인 문제를 맞히고 기준 점수를 넘어야 해결이에요.</p>
|
||||
</div>
|
||||
{qs.map((q, qi) => (
|
||||
<section key={q.id} className="card cf-q" aria-label={`문제 ${qi + 1}`}>
|
||||
<strong className="cf-doc" style={{ lineHeight: 1.5 }}>Q{qi + 1}. {q.text} <span className="small muted">({q.points}점{q.culprit ? ' · 범인' : ''})</span></strong>
|
||||
<div className="cf-choices" role="group" aria-label={q.text}>
|
||||
{q.choices.map((c, i) => (
|
||||
<button key={i} type="button" className={`btn ${mine[q.id] === i ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={mine[q.id] === i} disabled={!v.can.answer} onClick={() => (sfx.select(), act({ type: 'answer', q: q.id, choice: i }))}>
|
||||
{'①②③④⑤⑥'[i]} {c}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
{v.can.answer ? (
|
||||
<button type="button" className={`btn ${armed ? 'btn-danger' : 'btn-primary'} btn-block`} onClick={() => (armed ? (setArmed(false), act({ type: 'submit' })) : setArmed(true))}>
|
||||
{armed ? `정말 낼까요? (${answered}/${qs.length}문제 답함 · 낸 뒤에는 못 고쳐요)` : '📝 보고서 내기'}
|
||||
</button>
|
||||
) : (
|
||||
<p className="muted">보고서를 냈어요. {v.seats.filter((s) => !s.left && !s.submitted).map((s) => `${nick(players, s.id)}님`).join(', ') || '모두'} 기다리는 중…</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const gradeText = (x: PlayerScore) => (x.grade === '미해결' ? '미해결' : `${x.grade} 해결`);
|
||||
function scoreLine(x: PlayerScore, timeBonus: boolean): string {
|
||||
const parts = [`맞힌 문제 ${x.correct}점`];
|
||||
if (x.fatigue) parts.push(`피로 −${x.fatigue}`);
|
||||
if (x.hintsUsed) parts.push(`조언 −${x.hintsUsed * 2}`);
|
||||
if (timeBonus) parts.push(`남은 시간 보너스 +${x.bonus}`);
|
||||
return `${parts.join(' · ')} = ${x.score}점`;
|
||||
}
|
||||
|
||||
function ResultTab({ v, players, titles }: { v: CaseFileView; players: Players; titles: Record<string, string> }) {
|
||||
const f = v.final!;
|
||||
const [missed, setMissed] = useState(false);
|
||||
const qs = v.questions ?? [];
|
||||
const me = v.me;
|
||||
const head = v.mode === 'coop' ? f.teamScore : me ? f.scores[me] : null;
|
||||
const ans = (a: number | null | undefined, q: (typeof qs)[number]) => (a === null || a === undefined ? '—' : `${'①②③④⑤⑥'[a]} ${q.choices[a]}`);
|
||||
const people = v.seats.map((s) => s.id);
|
||||
const unread = f.leads.filter((l) => !l.read);
|
||||
if (f.reason === 'abandoned') return <p className="muted">{f.summary}</p>;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 12 }}>
|
||||
{head && (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<span className={`cf-grade${head.solved ? ' ok' : ''}`} aria-label={`등급 ${gradeText(head)}`}>{head.grade}</span>
|
||||
<p style={{ margin: '10px 0 0', fontWeight: 800 }}>{v.mode === 'coop' ? '팀' : '내'} {head.score}점 · {gradeText(head)}</p>
|
||||
<p className="small muted" style={{ margin: 0 }}>{scoreLine(head, v.timeBonus)}</p>
|
||||
</div>
|
||||
)}
|
||||
<section className="card" aria-label="문제별 답">
|
||||
<table className="cf-table">
|
||||
<thead>
|
||||
<tr><th>문제</th><th>정답</th>{v.mode === 'coop' && <th>팀 답</th>}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{qs.map((q, qi) => (
|
||||
<tr key={q.id}>
|
||||
<td>Q{qi + 1}. {q.text} ({q.points}점)
|
||||
<div className="small muted">{people.map((p) => `${p === me ? '나' : nick(players, p)}: ${f.answers[p]?.[q.id] === undefined ? '—' : '①②③④⑤⑥'[f.answers[p]![q.id]!]}${f.answers[p]?.[q.id] === f.correct[q.id] ? '✓' : ''}`).join(' · ')}</div>
|
||||
</td>
|
||||
<td>{ans(f.correct[q.id], q)}</td>
|
||||
{v.mode === 'coop' && <td>{ans(f.team?.[q.id], q)} {f.team?.[q.id] === f.correct[q.id] ? '✅' : '❌'}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<ul className="small" style={{ margin: '8px 0 0', paddingLeft: '1.2em' }}>
|
||||
{people.map((p) => f.scores[p] && (
|
||||
<li key={p}>{p === me ? '나' : `${nick(players, p)}님`}: {v.mode === 'coop' ? `이 답이었다면 ${f.scores[p]!.score}점(${gradeText(f.scores[p]!)})` : `${f.scores[p]!.score}점 · ${gradeText(f.scores[p]!)} · 남은 시간 ${f.scores[p]!.remaining}시간`}</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
<div className="cf-paper"><span className="cf-stamp">정답과 풀이</span><Doc text={f.solution} titles={titles} /></div>
|
||||
<button type="button" className="btn btn-secondary btn-block" aria-expanded={missed} onClick={() => setMissed(!missed)}>
|
||||
{missed ? '놓친 단서 접기' : `🔎 놓친 단서 보기 (${unread.length}개)`}
|
||||
</button>
|
||||
{missed && unread.map((l) => (
|
||||
<article key={l.id} className="cf-paper">
|
||||
<span className="cf-stamp">{l.placeName} · {l.hours}시간</span>
|
||||
<h3 style={{ margin: '0 0 8px', fontSize: '1.1rem' }}>{l.title}</h3>
|
||||
<Doc text={l.text} titles={titles} />
|
||||
{l.deep && <div className="cf-deep"><strong>🔍 깊이 보기</strong><Doc text={l.deep} /></div>}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
type Tab = 'main' | 'log' | 'people' | 'memo';
|
||||
|
||||
function Board({ view: v, me, players, act, deadline }: BoardProps<CaseFileView>) {
|
||||
const [tab, setTab] = useState<Tab>('main');
|
||||
const [live, setLive] = useState('');
|
||||
const reportOpen = v.questions !== null && v.phase !== 'ended';
|
||||
const stage = v.phase === 'ended' ? 'ended' : reportOpen ? 'report' : v.phase;
|
||||
useEffect(() => setTab('main'), [stage]);
|
||||
const n = v.inv?.log.length ?? 0;
|
||||
const prev = useRef(n);
|
||||
useEffect(() => {
|
||||
if (n > prev.current) {
|
||||
const last = v.inv!.log.at(-1)!;
|
||||
setLive(`${last.title}을(를) 읽었어요.${last.opened.length ? ` 새 단서 ${last.opened.length}개가 열렸어요.` : ''}`);
|
||||
sfx.cardFlip();
|
||||
}
|
||||
prev.current = n;
|
||||
}, [n, v.inv]);
|
||||
useEffect(() => {
|
||||
if (v.phase === 'report') sounds.ding();
|
||||
}, [v.phase]);
|
||||
const titles: Record<string, string> = Object.fromEntries((v.final?.leads ?? v.inv?.log ?? []).map((l) => ['id' in l ? l.id : l.lead, l.title]));
|
||||
if (v.phase === 'briefing') {
|
||||
const ready = v.seats.filter((s) => s.ready).length;
|
||||
return (
|
||||
<div className="cf cf-brief">
|
||||
<style>{CSS}</style>
|
||||
<CaseBar v={v} players={players} deadline={deadline} />
|
||||
<article className="cf-paper" aria-label="의뢰">
|
||||
<span className="cf-stamp">의뢰 · 해오름 탐정사무소</span>
|
||||
<Doc text={v.briefing} />
|
||||
</article>
|
||||
<section aria-label="알고 있는 사람" className="stack" style={{ gap: 6 }}>
|
||||
{v.inv?.people.map((p) => <div key={p.id} className="cf-person"><div><strong>{p.name}</strong><div className="cf-doc" style={{ lineHeight: 1.5 }}>{p.line}</div></div></div>)}
|
||||
</section>
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
{v.days}일 동안 하루 {v.hoursPerDay}시간씩 수사해요{v.overtime ? '(야근 2시간까지)' : ''}. {v.mode === 'race' ? '따로 겨루기: 각자 수사하고 점수로 겨뤄요.' : v.decision === 'rotate' ? '반장이 돌아가며 다음 단서를 골라요.' : v.decision === 'vote' ? '다 같이 투표로 다음 단서를 정해요.' : '누구든 먼저 고르면 그 단서를 따라가요.'}
|
||||
</p>
|
||||
{v.can.ready ? (
|
||||
<button type="button" className="btn btn-primary btn-block" onClick={() => (sfx.select(), act({ type: 'ready' }))}>🕵️ 수사 시작 ({ready}/{v.seats.filter((s) => !s.left).length})</button>
|
||||
) : (
|
||||
me && <p className="muted" style={{ textAlign: 'center' }}>다른 사람을 기다려요… ({ready}/{v.seats.filter((s) => !s.left).length})</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const mainLabel = stage === 'ended' ? '결과' : stage === 'report' ? '보고서' : '단서';
|
||||
const tabs: [Tab, string][] = [['main', mainLabel], ['log', `기록 ${n}`], ['people', '자료'], ['memo', '메모']];
|
||||
return (
|
||||
<div className={`cf${stage === 'ended' ? ' ended' : ''}`}>
|
||||
<style>{CSS}</style>
|
||||
<CaseBar v={v} players={players} deadline={deadline} />
|
||||
<div className="sr-only" aria-live="polite">{live}</div>
|
||||
<div className="cf-tabs" role="tablist" aria-label="수사 화면">
|
||||
{tabs.map(([k, label]) => (
|
||||
<button key={k} type="button" role="tab" aria-selected={tab === k} onClick={() => setTab(k)}>{label}</button>
|
||||
))}
|
||||
</div>
|
||||
<div role="tabpanel" aria-label={tabs.find((t) => t[0] === tab)![1]}>
|
||||
{tab === 'main' && stage === 'investigate' && v.inv && <LeadsTab v={v} players={players} act={act} titles={titles} />}
|
||||
{tab === 'main' && stage === 'investigate' && !v.inv && <p className="muted">따로 겨루기를 관전 중이에요. 오른쪽에서 각자의 진행을 볼 수 있어요.</p>}
|
||||
{tab === 'main' && stage === 'report' && <ReportTab v={v} players={players} act={act} />}
|
||||
{tab === 'main' && stage === 'ended' && v.final && <ResultTab v={v} players={players} titles={titles} />}
|
||||
{tab === 'main' && stage === 'report' && !v.questions && <p className="muted">보고서를 쓰는 중이에요.</p>}
|
||||
{tab === 'log' && <LogTab v={v} players={players} startedAt={v.startedAt} titles={titles} />}
|
||||
{tab === 'people' && <PeopleTab v={v} startedAt={v.startedAt} />}
|
||||
{tab === 'memo' && <MemoTab startedAt={v.startedAt} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function Side({ view: v, me, players }: BoardProps<CaseFileView>) {
|
||||
const status = (s: CaseFileView['seats'][number]): string => {
|
||||
if (s.left) return '나감';
|
||||
if (v.phase === 'briefing') return s.ready ? '준비 ✓' : '읽는 중';
|
||||
if (v.phase === 'ended') return '';
|
||||
if (s.progress) return s.submitted ? '보고서 냄 📝' : s.progress.reported ? '보고서 쓰는 중' : `${s.progress.day}일째 ${clock(s.progress.hour)} · 단서 ${s.progress.read}개`;
|
||||
if (v.phase === 'report') return s.submitted ? '보고서 냄 📝' : '쓰는 중';
|
||||
const tags: string[] = [];
|
||||
if (v.decision === 'rotate' && v.decider === s.id) tags.push('👑 반장');
|
||||
if (v.decision === 'vote') tags.push(s.voted ? '투표함 ✓' : '투표 중');
|
||||
if (v.decision === 'free' && s.agree) tags.push('보고서 쓰자 ✓');
|
||||
if (s.idle >= (v.decision === 'rotate' ? 3 : 1)) tags.push('💤 자리 비움');
|
||||
if (s.pin && v.inv) tags.push(`👍 ${v.inv.leads.find((l) => l.id === s.pin)?.title ?? ''}`);
|
||||
return tags.join(' · ');
|
||||
};
|
||||
return (
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
<section className="card stack" style={{ gap: 6, padding: 12 }} aria-label="탐정들">
|
||||
<strong>{v.mode === 'race' ? '🏁 따로 겨루기' : '🕵️ 해오름 탐정사무소 팀'}</strong>
|
||||
<ul className="stack" style={{ gap: 4, listStyle: 'none', padding: 0, margin: 0 }}>
|
||||
{v.seats.map((s) => (
|
||||
<li key={s.id} style={{ display: 'flex', justifyContent: 'space-between', gap: 8, opacity: s.left ? 0.5 : 1 }}>
|
||||
<span style={{ fontWeight: v.decider === s.id ? 800 : 500 }}>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<span className="small muted" style={{ textAlign: 'right' }}>{status(s)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{v.lastTally && v.phase === 'investigate' && (
|
||||
<p className="small" style={{ margin: 0 }}>
|
||||
지난 투표: {v.lastTally.label ? <strong>{v.lastTally.label}</strong> : '아무도 투표하지 않았어요'}
|
||||
{v.lastTally.counts.length > 0 && ` (${v.lastTally.counts.map((c) => `${c.label} ${c.n}표`).join(', ')})`}
|
||||
</p>
|
||||
)}
|
||||
{v.mode === 'race' && v.phase !== 'ended' && <p className="small muted" style={{ margin: 0 }}>🤫 따로 겨루기에서는 채팅으로 단서를 알려 주지 말아 주세요. 방장이 방 설정에서 채팅을 끌 수 있어요.</p>}
|
||||
{v.mode === 'coop' && v.readMode === 'reader' && v.phase === 'investigate' && v.seats.length > 1 && <p className="small muted" style={{ margin: 0 }}>📖 고른 사람만 단서 글을 봐요. 채팅으로 들려 주세요. 보고서를 쓸 때는 모두에게 열려요.</p>}
|
||||
{v.mode === 'coop' && v.phase === 'investigate' && v.seats.length > 1 && <p className="small muted" style={{ margin: 0 }}>💬 채팅으로 의견을 나눠요.</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status, options, rules
|
||||
|
||||
function isMyTurn(v: CaseFileView, me: string | null): boolean {
|
||||
if (!me || v.me !== me) return false;
|
||||
return v.can.ready || v.can.control || (v.can.vote && !v.myVote) || v.can.answer;
|
||||
}
|
||||
|
||||
function statusText(v: CaseFileView, me: string | null, players: Players): string {
|
||||
switch (v.phase) {
|
||||
case 'briefing':
|
||||
return v.can.ready ? '의뢰를 읽고 [수사 시작]을 눌러요' : '의뢰를 읽는 중이에요';
|
||||
case 'investigate':
|
||||
if (v.can.answer) return '보고서를 써요';
|
||||
if (v.mode === 'race') return v.inv?.reported ? '다른 사람을 기다려요' : '내 속도로 수사해요';
|
||||
if (v.decision === 'rotate') return v.decider === me ? '내가 반장이에요 · 단서를 골라요' : `${nick(players, v.decider)}님이 반장이에요`;
|
||||
if (v.decision === 'vote') return v.can.vote && !v.myVote ? '다음 할 일을 투표해요' : '투표를 기다려요';
|
||||
return '누구든 단서를 골라요';
|
||||
case 'report':
|
||||
return v.can.answer ? '보고서를 써요' : '보고서를 기다려요';
|
||||
case 'ended':
|
||||
return v.final?.summary ?? '수사가 끝났어요';
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{label}</strong>
|
||||
{children}
|
||||
{help && <span className="small muted">{help}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const onOff: [boolean, string][] = [[false, '끄기'], [true, '켜기']];
|
||||
const LEVELS = ['쉬움', '보통', '어려움'] as const;
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<CaseFileOptions>) {
|
||||
const set = (patch: Partial<CaseFileOptions>) => onChange({ ...o, ...patch });
|
||||
const race = o.mode === 'race';
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label={`사건(${CASE_LIST.length}개)`} help={o.caseId === 'random' ? '어떤 사건인지 시작하면 알아요.' : CASE_LIST.find((c) => c.id === o.caseId)?.pitch}>
|
||||
<select className="input" aria-label="사건" value={o.caseId} onChange={(e) => set({ caseId: e.target.value as CaseFileOptions['caseId'] })}>
|
||||
{LEVELS.map((lv) => (
|
||||
<optgroup key={lv} label={lv}>
|
||||
{CASE_LIST.filter((c) => c.level === lv).map((c) => (
|
||||
<option key={c.id} value={c.id}>{c.title}</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
<option value="random">아무거나(시작하면 알아요)</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="함께 풀기 / 따로 겨루기">
|
||||
<Seg label="함께 풀기 / 따로 겨루기" value={o.mode} options={[['coop', '함께 풀기'], ['race', '따로 겨루기']]} onChange={(mode) => set({ mode })} />
|
||||
</Field>
|
||||
{!race && (
|
||||
<Field label="다음 단서를 누가 고르나" help="혼자 할 때는 상관없어요.">
|
||||
<Seg label="다음 단서를 누가 고르나" value={o.decision} options={[['rotate', '반장이 돌아가며'], ['vote', '다 같이 투표'], ['free', '아무나 먼저']]} onChange={(decision) => set({ decision })} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="하루 수사 시간">
|
||||
<Seg label="하루 수사 시간" value={o.timeBudget} options={[['relaxed', '넉넉하게 10시간'], ['normal', '보통 8시간'], ['tight', '빠듯하게 6시간']]} onChange={(timeBudget) => set({ timeBudget })} />
|
||||
</Field>
|
||||
<Field label="야근" help="하루 2시간까지 더 일하고, 1시간마다 피로 1(−1점).">
|
||||
<Seg label="야근" value={o.overtime} options={onOff} onChange={(overtime) => set({ overtime })} />
|
||||
</Field>
|
||||
<Field label="돋보기(깊이 보기) 개수">
|
||||
<Seg label="돋보기 개수" value={o.magnifiers} options={[[0, '없음'], [2, '2개'], [3, '3개'], [5, '5개']]} onChange={(magnifiers) => set({ magnifiers })} />
|
||||
</Field>
|
||||
<Field label="반장님 조언(1번에 −2점)">
|
||||
<Seg label="반장님 조언" value={o.hints} options={[[0, '없음'], [1, '1번'], [3, '3번']]} onChange={(hints) => set({ hints })} />
|
||||
</Field>
|
||||
<Field label="남은 시간 보너스" help="보고서를 쓸 때 남은 2시간마다 +1점(최대 +5점).">
|
||||
<Seg label="남은 시간 보너스" value={o.timeBonus} options={onOff} onChange={(timeBonus) => set({ timeBonus })} />
|
||||
</Field>
|
||||
<Field label="아침 소식">
|
||||
<Seg label="아침 소식" value={o.morningNews} options={onOff} onChange={(morningNews) => set({ morningNews })} />
|
||||
</Field>
|
||||
{!race && (
|
||||
<Field label="단서 글 읽기(2명 이상)" help={o.readMode === 'reader' ? '고른 사람만 글을 보고 채팅으로 전해요. 보고서 때는 모두 볼 수 있어요.' : undefined}>
|
||||
<Seg label="단서 글 읽기" value={o.readMode} options={[['all', '모두 읽기'], ['reader', '고른 사람만 읽기']]} onChange={(readMode) => set({ readMode })} />
|
||||
</Field>
|
||||
)}
|
||||
{!race && (
|
||||
<Field label="다음 단서 고르기 제한 시간">
|
||||
<Seg label="다음 단서 고르기 제한 시간" value={o.turnSeconds} options={[[60, '60초'], [120, '120초'], [180, '180초'], [300, '300초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||||
</Field>
|
||||
)}
|
||||
<Field label="보고서 쓰기 제한 시간">
|
||||
<Seg label="보고서 쓰기 제한 시간" value={o.reportSeconds} options={[[180, '3분'], [300, '5분'], [600, '10분'], [null, '무제한']]} onChange={(reportSeconds) => set({ reportSeconds })} />
|
||||
</Field>
|
||||
{race && (
|
||||
<Field label="따로 겨루기 전체 제한 시간">
|
||||
<Seg label="따로 겨루기 전체 제한 시간" value={o.raceMinutes} options={[[30, '30분'], [45, '45분'], [60, '60분'], [90, '90분'], [null, '무제한']]} onChange={(raceMinutes) => set({ raceMinutes })} />
|
||||
</Field>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: CaseFileOptions): string {
|
||||
const c = CASE_LIST.find((x) => x.id === o.caseId);
|
||||
const parts = [c ? `${c.title}(${c.level})` : '사건 아무거나', o.mode === 'race' ? '따로 겨루기' : { rotate: '반장 돌아가며', vote: '투표', free: '아무나' }[o.decision]];
|
||||
parts.push({ relaxed: '하루 10시간', normal: '하루 8시간', tight: '하루 6시간' }[o.timeBudget]);
|
||||
parts.push(`돋보기 ${o.magnifiers}`, `조언 ${o.hints}`);
|
||||
if (!o.overtime) parts.push('야근 없음');
|
||||
if (o.timeBonus) parts.push('남은 시간 보너스');
|
||||
if (o.mode === 'coop' && o.readMode === 'reader') parts.push('한 사람만 읽기');
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: CaseFileOptions }) {
|
||||
const race = options?.mode === 'race';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>탐정 사무소 팀이 되어 사건 하나를 <strong>함께 푸는 추리 게임</strong>이에요. 정해진 날짜와 시간 안에서 어떤 단서를 따라갈지 고르고, 고른 단서의 글을 읽고, 마지막에 객관식 <strong>수사 보고서</strong>를 내서 점수를 받아요.</p>
|
||||
<p><strong>시간</strong>: 하루는 09:00에 사무소에서 시작해요(하루 6·8·10시간). 단서마다 1~2시간이 들고, 다른 동네로 가면 이동 시간이 더 들어요. 하루 끝을 넘기면 <strong>야근</strong>(하루 2시간까지, 1시간마다 −1점). [하루 마치기]를 누르면 남은 시간을 버리고 다음 날로 가요.</p>
|
||||
<p><strong>단서</strong>: 읽은 단서에서 새 단서가 열려요. 🔍가 있는 단서는 <strong>돋보기</strong>를 하나 써서 숨은 문단을 더 볼 수 있어요(시간 안 듦). <strong>반장님 조언</strong>은 1번에 −2점이에요. 자료실의 인물 카드와 수사 기록은 언제든 공짜로 다시 봐요.</p>
|
||||
{!race && <p><strong>누가 고르나</strong>: 반장이 돌아가며(다른 사람은 [추천]과 채팅), 다 같이 투표, 아무나 먼저 누르기 중 방 설정대로 해요.</p>}
|
||||
<p><strong>보고서</strong>: 수사를 마치면 그때 문제가 나와요. {race ? '각자 낸 답으로 각자 점수를 받아요. 동점이면 남은 시간이 많은 사람이 앞서요.' : '각자 답을 내면 문제마다 가장 많이 고른 답이 팀 답이에요.'}</p>
|
||||
<p><strong>점수</strong> = 맞힌 문제 점수 − 피로 − 조언 × 2 (+ 남은 시간 보너스). 범인 문제를 맞히고 사건의 기준 점수를 넘으면 <strong>해결</strong>(S·A·B 등급)이에요. 끝나면 정답과 풀이, 못 본 단서를 모두 볼 수 있어요.</p>
|
||||
<p className="small muted">사건과 인물은 모두 이 사이트를 위해 새로 지은 이야기예요. 진행 방식은 『디텍티브: 모던 크라임 보드게임』에서 영감을 받았어요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<CaseFileView, CaseFileOptions> = {
|
||||
Board,
|
||||
Side,
|
||||
statusText,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
69
apps/web/src/games/case-file/no-case-text.test.ts
Normal file
69
apps/web/src/games/case-file/no-case-text.test.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 웹 빌드에 사건 글이 없어야 해요 (docs/games/case-file.md §8.3, §10): the case content is server only, so the built
|
||||
* bundle (apps/web/dist, `bunx vite build`) must not contain any lead text, deep look, answer or solution.
|
||||
* Also checks the web sources never import the case data at runtime.
|
||||
*/
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { CASES } from '@bg/games/case-file';
|
||||
|
||||
const DIST = join(import.meta.dir, '../../../dist');
|
||||
const SRC = join(import.meta.dir, '../..');
|
||||
|
||||
function files(dir: string, keep: (f: string) => boolean): string[] {
|
||||
const out: string[] = [];
|
||||
for (const name of readdirSync(dir)) {
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) out.push(...files(p, keep));
|
||||
else if (keep(p)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A distinctive middle piece of a text (skips quotes/markup at the edges). */
|
||||
const piece = (t: string) => {
|
||||
const flat = t.replace(/\s+/g, ' ');
|
||||
const start = Math.floor(flat.length / 3);
|
||||
return flat.slice(start, start + 14);
|
||||
};
|
||||
/** esbuild may write non-ASCII as \uXXXX escapes. */
|
||||
const escaped = (t: string) => [...t].map((ch) => (ch.charCodeAt(0) > 127 ? `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}` : ch)).join('');
|
||||
|
||||
const probes: string[] = [];
|
||||
for (const c of Object.values(CASES)) {
|
||||
for (const l of c.leads) {
|
||||
probes.push(piece(l.text));
|
||||
if (l.deep) probes.push(piece(l.deep));
|
||||
}
|
||||
probes.push(piece(c.solution), ...c.hints.map(piece));
|
||||
for (const q of c.questions) {
|
||||
const a = q.choices[q.answer]!;
|
||||
if (a.length >= 8) probes.push(a);
|
||||
}
|
||||
}
|
||||
|
||||
describe('사건 글은 브라우저로 미리 가지 않아요', () => {
|
||||
test('웹 코드는 사건 데이터를 실행 중에 가져오지 않아요(타입·라벨만)', () => {
|
||||
for (const f of files(SRC, (p) => /\.(ts|tsx)$/.test(p) && !/\.test\.ts$|test-util\.ts$/.test(p))) {
|
||||
const src = readFileSync(f, 'utf8');
|
||||
for (const m of src.matchAll(/^import\s+(?!type\b)[^;]*from\s+'(@bg\/games[^']*)'/gm)) {
|
||||
const mod = m[1]!;
|
||||
expect(mod === '@bg/games/case-file' || mod.includes('case-file/cases'), `${f}: ${mod}`).toBe(false);
|
||||
if (mod === '@bg/games') throw new Error(`${f}: imports every game module at runtime`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test.skipIf(!existsSync(DIST))('빌드 결과물(apps/web/dist)에 단서 본문·깊이 보기·정답·풀이가 없어요', () => {
|
||||
const bundle = files(DIST, (p) => /\.(js|css|html|json|webmanifest)$/.test(p)).map((f) => readFileSync(f, 'utf8')).join('\n');
|
||||
expect(bundle.length).toBeGreaterThan(1000);
|
||||
expect(probes.length).toBeGreaterThan(80);
|
||||
// Sanity: the probes would be found if the data were bundled — the title (an option label) is there on purpose.
|
||||
expect(bundle.includes('달빛제과의 사라진 레시피 노트') || bundle.includes(escaped('달빛제과의 사라진 레시피 노트'))).toBe(true);
|
||||
for (const p of probes) {
|
||||
expect(bundle.includes(p), p).toBe(false);
|
||||
expect(bundle.includes(escaped(p)), p).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
59
apps/web/src/games/case-file/quick.tsx
Normal file
59
apps/web/src/games/case-file/quick.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
/** 사건 파일 30초 규칙 요약 (docs/games/case-file.md §9). */
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
function Lead({ x, y, title, t, dim }: { x: number; y: number; title: string; t: string; dim?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} opacity={dim ? 0.45 : 1}>
|
||||
<rect width={110} height={50} rx={8} fill="#fdf6e3" stroke="#a16207" strokeWidth={2} />
|
||||
<text x={8} y={20} fontSize={12} fontWeight={800} fill="#3f2d0c">{title}</text>
|
||||
<text x={8} y={39} fontSize={11} fill="#6b4f1d">{t}</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 130" width={250} height={130} aria-hidden>
|
||||
<text x={8} y={18} fontSize={13} fontWeight={800} fill="#2563eb">🕘 1일째 09:00 / 17:00까지</text>
|
||||
<Lead x={8} y={30} title="이야기 듣기" t="1시간" />
|
||||
<Lead x={130} y={30} title="CCTV 보기" t="2시간" />
|
||||
<Lead x={8} y={78} title="장부 보기" t="1시간" dim />
|
||||
</svg>
|
||||
),
|
||||
alt: '하루 시간표와 단서 카드 세 장, 단서마다 걸리는 시간',
|
||||
title: '시간 안에 단서를 골라요',
|
||||
text: '단서를 고르면 시계가 가고 글이 열려요. 시간이 모자라 모든 단서를 볼 수는 없어요. 무엇을 볼지 함께 골라요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 110" width={250} height={110} aria-hidden>
|
||||
<rect x={10} y={30} width={80} height={50} rx={10} fill="#dbeafe" stroke="#2563eb" strokeWidth={2} />
|
||||
<text x={50} y={60} textAnchor="middle" fontSize={13} fontWeight={800} fill="#1e3a8a">사무소</text>
|
||||
<rect x={160} y={30} width={80} height={50} rx={10} fill="#dcfce7" stroke="#15803d" strokeWidth={2} />
|
||||
<text x={200} y={60} textAnchor="middle" fontSize={13} fontWeight={800} fill="#14532d">골목</text>
|
||||
<line x1={92} y1={55} x2={158} y2={55} stroke="#6b7280" strokeWidth={3} strokeDasharray="6 4" />
|
||||
<text x={125} y={45} textAnchor="middle" fontSize={12} fontWeight={800} fill="#374151">이동 1시간</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '사무소와 골목 사이 이동 1시간',
|
||||
title: '동네를 옮기면 시간이 들어요',
|
||||
text: '같은 동네 안은 이동 0시간, 다른 동네로 가면 1~2시간이 더 들어요. 하루 끝을 넘기면 야근(1시간마다 −1점).',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<rect x={40} y={8} width={170} height={104} rx={8} fill="#fffef9" stroke="#334155" strokeWidth={2} />
|
||||
<text x={56} y={32} fontSize={13} fontWeight={900} fill="#111827">수사 보고서</text>
|
||||
<text x={56} y={56} fontSize={12} fill="#374151">Q1. 범인은? (10점)</text>
|
||||
<rect x={56} y={66} width={60} height={22} rx={6} fill="#2563eb" />
|
||||
<text x={86} y={81} textAnchor="middle" fontSize={11} fontWeight={800} fill="#fff">①</text>
|
||||
<rect x={124} y={66} width={60} height={22} rx={6} fill="#e5e7eb" />
|
||||
<text x={154} y={81} textAnchor="middle" fontSize={11} fill="#111827">②</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '객관식 수사 보고서 문제',
|
||||
title: '마지막에 보고서를 풀어요',
|
||||
text: '수사가 끝나면 그때 문제가 나와요. 각자 답을 내면 많이 고른 답이 팀 답이 돼요. 범인을 맞히고 기준 점수를 넘으면 해결!',
|
||||
},
|
||||
];
|
||||
59
apps/web/src/games/castles-of-burgundy/help.ts
Normal file
59
apps/web/src/games/castles-of-burgundy/help.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/** 버건디의 성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { CobView } from '@bg/games/castles-of-burgundy';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const PHASE = ['A', 'B', 'C', 'D', 'E'];
|
||||
|
||||
export function helpNow(v: CobView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const name = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`;
|
||||
const pv = me ? v.players[me] : undefined;
|
||||
const where = `페이즈 ${PHASE[v.phase] ?? 'E'}, 라운드 ${Math.min(5, v.round + 1)}/5`;
|
||||
if (v.stage === 'finished') {
|
||||
if (v.solo) return v.endReason === 'soloWin' ? '성공했어요! 공국 37칸을 모두 채웠어요.' : '게임이 끝났어요. 25라운드 안에 공국을 다 채우지 못했어요.';
|
||||
const rows = [...(v.final ?? [])].sort((a, b) => b.total - a.total);
|
||||
const top = rows[0];
|
||||
const mine = me ? rows.find((r) => r.player === me) : undefined;
|
||||
return [`게임이 끝났어요.${top ? ` 1위는 ${name(top.player)}(${top.total}점)이에요.` : ''}`, mine ? `내 점수는 ${mine.total}점이에요(빈칸 ${mine.emptySpaces}칸).` : '', '같은 점수면 공국 빈칸이 더 많은 사람이 이겨요.']
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
const waiting = v.waiting[0];
|
||||
if (!pv || pv.conceded) {
|
||||
const head = pv?.conceded ? '기권해서 구경하는 중이에요. ' : '';
|
||||
return `${head}${where}. ${waiting ? `${name(waiting)} 차례예요.` : '잠시만 기다려 주세요.'}\n공국을 누르면 크게 볼 수 있어요.`;
|
||||
}
|
||||
const status = `내 점수 ${pv.vp}점 · 일꾼 ${pv.workers}개 · 은화 ${pv.silver}개 · 보관 칸 ${pv.storage.length}/3.`;
|
||||
if (v.stage === 'castle') {
|
||||
return v.my ? '시작 성을 놓을 성(진초록) 칸을 눌러 주세요. 첫 타일은 그 성 옆에 놓게 돼요.' : `${waiting ? name(waiting) : '다른 사람'}이 시작 성 칸을 고르는 중이에요.`;
|
||||
}
|
||||
if (!v.my) {
|
||||
return [`${where}. ${waiting ? `${name(waiting)} 차례예요.` : ''} 기다리는 동안 다음 차례를 계획해 보세요.`, `내 주사위: ${pv.dice.join('·')} (모든 눈이 모두에게 보여요).`, status].join('\n');
|
||||
}
|
||||
const top = v.pending[v.pending.length - 1];
|
||||
if (top) {
|
||||
const tips: Record<string, string> = {
|
||||
bonus: '성 보너스예요. 주사위 하나를 원하는 눈으로 쓴 것처럼 가져오기·놓기·팔기·일꾼 받기 중 하나를 해요(일꾼 필요 없음).',
|
||||
ship: '배를 놓았어요. 상품을 모두 가져올 보급소를 골라 주세요. 상품 칸은 3종류까지예요. 차례 트랙에서 한 칸 앞으로 가요.',
|
||||
depotTake: '건물 효과로 번호 보급소에서 정해진 색 타일 1장을 공짜로 가져와요. 빛나는 타일을 누르거나 건너뛰어요.',
|
||||
warehouse: '창고: 가진 상품 한 종류를 주사위 없이 팔아요.',
|
||||
townhall: '시청: 보관 칸 타일 1장을 숫자와 상관없이 놓아요(색과 맞닿음은 지켜요).',
|
||||
crane: '기중기: 아무 건물 효과 하나를 골라요.',
|
||||
geese: '거위: 같은 목초지의 가축 한 종류를 골라 그 점수를 더 받아요.',
|
||||
shieldCopy: '방패 6번: 수도원 효과를 함께 쓸 사람을 골라요.',
|
||||
upkeep: '페이즈 끝 방패 유지비: 남길 방패 1개당 은화 1개예요.',
|
||||
phasePlace: '방패 효과: 타일 1장을 골라 공국에 바로 놓아요(숫자 조건 없음).',
|
||||
soloTrade: '상품 5장을 내고 검은 보급소 타일 1장을 뒷면으로 받을 수 있어요. 뒷면 타일은 아무 색 칸에나 놓아요.',
|
||||
soloBlack: '색을 모두 채운 보상: 검은 보급소 타일 1장을 공국에 바로 놓아요.',
|
||||
};
|
||||
return [tips[top.kind] ?? '위의 안내에 따라 골라 주세요.', status].join('\n');
|
||||
}
|
||||
const left = [pv.used[0] ? null : pv.dice[0], pv.used[1] ? null : pv.dice[1]].filter((x) => x !== null);
|
||||
const lines = [`내 차례예요(${where}). 남은 주사위: ${left.length ? left.join('·') : '없음'}.`];
|
||||
if (left.length) {
|
||||
lines.push('주사위를 누르면 할 수 있는 일이 빛나요: 같은 번호 보급소에서 가져오기, 같은 색·숫자 칸에 놓기, 같은 번호 상품 팔기, 일꾼 2개 받기.');
|
||||
lines.push('일꾼 1개로 눈을 ±1 바꿀 수 있어요(6과 1은 이어져요). 빛나는 칸의 "일꾼 n"이 드는 일꾼 수예요.');
|
||||
} else lines.push('주사위를 다 썼어요. 살 것이 있으면 [🛒 구매], 아니면 [차례 끝]을 눌러요.');
|
||||
if (!pv.bought && pv.silver >= 2) lines.push('은화 2개로 검은 보급소 타일 1장을 살 수 있어요(차례당 1장).');
|
||||
lines.push(status);
|
||||
return lines.join('\n');
|
||||
}
|
||||
158
apps/web/src/games/castles-of-burgundy/hex.tsx
Normal file
158
apps/web/src/games/castles-of-burgundy/hex.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
/** 버건디의 성 drawing helpers: own hex tile art (colour + symbol, no original artwork). */
|
||||
import { ANIMAL_ICON, ANIMAL_KO, BUILDING_KO, COLOR_ICON, COLOR_KO, GOODS_KO, MONASTERIES, TILES, type Color, type Die } from '@bg/games/castles-of-burgundy/data';
|
||||
|
||||
export const FILL: Record<Color | 'inn' | 'any', string> = {
|
||||
castle: '#2f6b3a',
|
||||
mine: '#7c828c',
|
||||
monastery: '#e2b93b',
|
||||
building: '#d6b383',
|
||||
livestock: '#8cc152',
|
||||
ship: '#3f86d1',
|
||||
inn: '#b45309',
|
||||
any: '#4b5563',
|
||||
};
|
||||
export const SPACE: Record<Color, string> = {
|
||||
castle: '#9cc7a3',
|
||||
mine: '#c9ccd1',
|
||||
monastery: '#f4e2a6',
|
||||
building: '#efdfc6',
|
||||
livestock: '#cfe8b4',
|
||||
ship: '#b7d3f1',
|
||||
};
|
||||
export const INK: Record<Color | 'inn' | 'any', string> = {
|
||||
castle: '#ffffff',
|
||||
mine: '#ffffff',
|
||||
monastery: '#3b2a00',
|
||||
building: '#3b2a00',
|
||||
livestock: '#1f3a0a',
|
||||
ship: '#ffffff',
|
||||
inn: '#ffffff',
|
||||
any: '#ffffff',
|
||||
};
|
||||
export const GOODS_FILL: Record<Die, string> = { 1: '#7c3aed', 2: '#ca8a04', 3: '#db2777', 4: '#0891b2', 5: '#ea580c', 6: '#65a30d' };
|
||||
|
||||
const SQ3 = Math.sqrt(3);
|
||||
export function hexPoints(cx: number, cy: number, r: number): string {
|
||||
const pts: string[] = [];
|
||||
for (let k = 0; k < 6; k++) {
|
||||
const a = (Math.PI / 180) * (60 * k - 90);
|
||||
pts.push(`${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`);
|
||||
}
|
||||
return pts.join(' ');
|
||||
}
|
||||
/** Axial (q, r) → pixel centre for pointy-top hexes of radius `size`. */
|
||||
export const axial = (q: number, r: number, size: number): [number, number] => [size * SQ3 * (q + r / 2), size * 1.5 * r];
|
||||
export const HEX_W = (size: number) => size * SQ3;
|
||||
|
||||
export function tileColor(id: string, facedown = false): Color | 'inn' | 'any' {
|
||||
if (facedown) return 'any';
|
||||
return TILES[id]?.color ?? 'any';
|
||||
}
|
||||
|
||||
/** Short text inside a tile. */
|
||||
export function tileShort(id: string, facedown = false): { icon: string; text: string } {
|
||||
if (facedown) return { icon: '■', text: '뒷면' };
|
||||
const t = TILES[id];
|
||||
if (!t) return { icon: '?', text: '' };
|
||||
if (t.color === 'inn') return { icon: '🛏', text: '여관' };
|
||||
if (t.building) return { icon: '🏠', text: BUILDING_KO[t.building] };
|
||||
if (t.animal) return { icon: ANIMAL_ICON[t.animal], text: `×${t.count}` };
|
||||
if (t.monastery) return { icon: '📜', text: String(t.monastery) };
|
||||
return { icon: COLOR_ICON[t.color as Color], text: '' };
|
||||
}
|
||||
|
||||
/** Full Korean name of a tile ("시장(건물)", "양 3마리", "수도원 8 힘센 일꾼"). */
|
||||
export function tileName(id: string, facedown = false): string {
|
||||
if (facedown) return '뒷면 타일(아무 색)';
|
||||
const t = TILES[id];
|
||||
if (!t) return '타일';
|
||||
if (t.color === 'inn') return '여관';
|
||||
if (t.building) return `${BUILDING_KO[t.building]}(건물)`;
|
||||
if (t.animal) return `${ANIMAL_KO[t.animal]} ${t.count}마리`;
|
||||
if (t.monastery) return `수도원 ${t.monastery}번 ${monasteryName(t.monastery, t.craft)}`;
|
||||
return COLOR_KO[t.color as Color];
|
||||
}
|
||||
export function monasteryName(n: number, craft?: string): string {
|
||||
if (craft) return `${BUILDING_KO[craft as 'bank']} 장인`;
|
||||
return MONASTERIES.find((m) => m.n === n)?.name ?? '';
|
||||
}
|
||||
export function monasteryText(n: number, craft?: string): string {
|
||||
if (craft) return `게임 끝: 내 공국의 ${BUILDING_KO[craft as 'bank']} 1개당 4점`;
|
||||
return MONASTERIES.find((m) => m.n === n)?.text ?? '';
|
||||
}
|
||||
|
||||
export const goodsName = (d: Die) => `${d} ${GOODS_KO[d]}`;
|
||||
|
||||
/** One hex tile at (cx, cy). */
|
||||
export function TileHex({ id, cx, cy, r, facedown, dim }: { id: string; cx: number; cy: number; r: number; facedown?: boolean; dim?: boolean }) {
|
||||
const c = tileColor(id, facedown);
|
||||
const { icon, text } = tileShort(id, facedown);
|
||||
return (
|
||||
<g opacity={dim ? 0.45 : 1}>
|
||||
<polygon points={hexPoints(cx, cy, r)} fill={FILL[c]} stroke="rgba(0,0,0,.45)" strokeWidth={Math.max(1, r * 0.06)} />
|
||||
<polygon points={hexPoints(cx, cy, r * 0.8)} fill="none" stroke="rgba(255,255,255,.35)" strokeWidth={Math.max(0.6, r * 0.04)} />
|
||||
<text x={cx} y={text ? cy - r * 0.08 : cy + r * 0.12} textAnchor="middle" fontSize={r * (text ? 0.62 : 0.8)} dominantBaseline="middle">
|
||||
{icon}
|
||||
</text>
|
||||
{text && (
|
||||
<text x={cx} y={cy + r * 0.52} textAnchor="middle" fontSize={r * (text.length > 2 ? 0.34 : 0.42)} fontWeight={800} fill={INK[c]} dominantBaseline="middle">
|
||||
{text}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** A die face with pips (for the dice bar and the duchy spaces). */
|
||||
export function Pips({ n, cx, cy, s, color = '#1c1e21' }: { n: number; cx: number; cy: number; s: number; color?: string }) {
|
||||
const o = s * 0.28;
|
||||
const at: Record<number, [number, number][]> = {
|
||||
1: [[0, 0]],
|
||||
2: [
|
||||
[-o, -o],
|
||||
[o, o],
|
||||
],
|
||||
3: [
|
||||
[-o, -o],
|
||||
[0, 0],
|
||||
[o, o],
|
||||
],
|
||||
4: [
|
||||
[-o, -o],
|
||||
[o, -o],
|
||||
[-o, o],
|
||||
[o, o],
|
||||
],
|
||||
5: [
|
||||
[-o, -o],
|
||||
[o, -o],
|
||||
[0, 0],
|
||||
[-o, o],
|
||||
[o, o],
|
||||
],
|
||||
6: [
|
||||
[-o, -o],
|
||||
[o, -o],
|
||||
[-o, 0],
|
||||
[o, 0],
|
||||
[-o, o],
|
||||
[o, o],
|
||||
],
|
||||
};
|
||||
return (
|
||||
<g>
|
||||
{(at[n] ?? []).map(([dx, dy], i) => (
|
||||
<circle key={i} cx={cx + dx} cy={cy + dy} r={s * 0.09} fill={color} />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
export function DieFace({ n, size = 40, white, used, label }: { n: number; size?: number; white?: boolean; used?: boolean; label?: string }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 40 40" role="img" aria-label={label ?? `주사위 ${n}`} style={{ display: 'block', opacity: used ? 0.35 : 1 }}>
|
||||
<rect x={2} y={2} width={36} height={36} rx={8} fill={white ? '#ffffff' : '#fde68a'} stroke="#1c1e21" strokeWidth={2} />
|
||||
<Pips n={n} cx={20} cy={20} s={36} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
1390
apps/web/src/games/castles-of-burgundy/index.tsx
Normal file
1390
apps/web/src/games/castles-of-burgundy/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
75
apps/web/src/games/castles-of-burgundy/quick.tsx
Normal file
75
apps/web/src/games/castles-of-burgundy/quick.tsx
Normal file
@@ -0,0 +1,75 @@
|
||||
/** 버건디의 성 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
import { DieFace, FILL, SPACE, TileHex, hexPoints } from './hex';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<foreignObject x={10} y={36} width={44} height={44}>
|
||||
<DieFace n={4} size={44} />
|
||||
</foreignObject>
|
||||
<text x={70} y={64} fontSize={22} fontWeight={900}>
|
||||
=
|
||||
</text>
|
||||
<rect x={92} y={30} width={62} height={56} rx={8} fill="#efece4" stroke="#9ca3af" />
|
||||
<text x={123} y={48} textAnchor="middle" fontSize={12} fontWeight={800}>
|
||||
4번 보급소
|
||||
</text>
|
||||
<TileHex id="S-01" cx={123} cy={70} r={14} />
|
||||
<text x={170} y={64} fontSize={22} fontWeight={900}>
|
||||
=
|
||||
</text>
|
||||
<polygon points={hexPoints(215, 58, 24)} fill={SPACE.ship} stroke="#334155" strokeWidth={2} />
|
||||
<text x={215} y={64} textAnchor="middle" fontSize={20} fontWeight={900}>
|
||||
4
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '주사위 4는 4번 보급소와 공국의 숫자 4 칸을 뜻해요',
|
||||
title: '주사위 눈 = 번호',
|
||||
text: '라운드마다 주사위 2개를 하나씩 써요. 눈과 같은 번호 보급소에서 타일을 가져오고, 같은 숫자 칸에 놓아요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<polygon points={hexPoints(70, 60, 26)} fill={FILL.castle} stroke="#1f2937" strokeWidth={2} />
|
||||
<text x={70} y={66} textAnchor="middle" fontSize={20}>
|
||||
🏰
|
||||
</text>
|
||||
<TileHex id="B-market-1" cx={115} cy={34} r={25} />
|
||||
<polygon points={hexPoints(115, 86, 25)} fill={SPACE.ship} stroke="#2563eb" strokeWidth={3} strokeDasharray="4 3" />
|
||||
<text x={115} y={92} textAnchor="middle" fontSize={18} fontWeight={900}>
|
||||
5
|
||||
</text>
|
||||
<text x={150} y={64} fontSize={13} fontWeight={800} fill="#15803d">
|
||||
같은 색·숫자,
|
||||
</text>
|
||||
<text x={150} y={82} fontSize={13} fontWeight={800} fill="#15803d">
|
||||
맞닿게 놓기
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '성 옆에 시장 타일이 있고, 맞닿은 파란 5번 칸이 빛나요',
|
||||
title: '공국에 맞닿게 놓기',
|
||||
text: '보관 칸 타일을 같은 색·같은 숫자 빈칸에, 이미 놓인 타일과 맞닿게 놓아요. 색마다 효과가 달라요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<TileHex id="M-01" cx={40} cy={50} r={24} />
|
||||
<TileHex id="M-02" cx={82} cy={50} r={24} />
|
||||
<TileHex id="M-03" cx={61} cy={86} r={24} />
|
||||
<text x={115} y={58} fontSize={18} fontWeight={900} fill="#15803d">
|
||||
구역 완성!
|
||||
</text>
|
||||
<text x={115} y={84} fontSize={14} fontWeight={800}>
|
||||
3칸 6점 + A 페이즈 10점
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '광산 3칸 구역을 다 채워 점수를 얻어요',
|
||||
title: '구역을 채워 점수',
|
||||
text: '같은 색 구역을 다 채우면 크기 점수와 페이즈 점수(이를수록 큼)를 받아요. 한 색을 전부 채우면 보너스!',
|
||||
},
|
||||
];
|
||||
@@ -5,13 +5,14 @@ import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { nameHue } from '../../components/ChatMessage';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { keepFocus } from '../../lib/chat-input';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useWide } from '../../lib/media';
|
||||
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)
|
||||
|
||||
@@ -89,7 +90,7 @@ const cmSound = {
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.cm { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 8px; align-self: center; }
|
||||
.cm { width: 100%; display: flex; flex-direction: column; gap: 8px; align-self: stretch; }
|
||||
.cm-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; justify-content: space-between; font-weight: 700; }
|
||||
.cm-pill { display: inline-flex; align-items: center; gap: 5px; border-radius: 999px; padding: 3px 10px; background: var(--surface); box-shadow: var(--shadow); font-size: .92rem; font-variant-numeric: tabular-nums; }
|
||||
.cm-hint { display: flex; justify-content: center; align-items: center; gap: 6px; flex-wrap: wrap; min-height: 48px; }
|
||||
@@ -101,8 +102,9 @@ const CSS = `
|
||||
.cm-bar { position: relative; height: 10px; border-radius: 999px; background: var(--surface-2); overflow: hidden; }
|
||||
.cm-bar i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 999px; transition: width .25s linear; }
|
||||
.cm-stage { display: flex; gap: 12px; align-items: flex-start; justify-content: center; }
|
||||
.cm-paper { position: relative; width: min(100%, calc(100vh - 290px)); min-width: 280px; aspect-ratio: 1 / 1; border-radius: 14px; background: #fff; box-shadow: var(--shadow);
|
||||
border: 3px solid var(--border); overflow: hidden; flex: 0 0 auto; }
|
||||
/* Square paper: as tall as the play column allows after the pills, hint and time rows above it (PC). */
|
||||
.cm-paper { position: relative; width: min(100%, var(--play-h, 100vh) - 150px); min-width: 280px; aspect-ratio: 1 / 1; border-radius: 14px; background: #fff; box-shadow: var(--shadow);
|
||||
border: 3px solid var(--border); overflow: hidden; flex: 0 1 auto; }
|
||||
.cm-paper canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: auto; }
|
||||
.cm-paper[data-draw='true'] canvas { touch-action: none; cursor: crosshair; }
|
||||
.cm-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 16px; text-align: center;
|
||||
@@ -166,6 +168,12 @@ const CSS = `
|
||||
.cm-away { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; background: var(--warning-soft); color: var(--text); border-radius: 12px; padding: 8px 12px; }
|
||||
@keyframes cm-pop { 0% { transform: translate(-50%, -50%) scale(.5); opacity: 0; } 70% { transform: translate(-50%, -50%) scale(1.08); opacity: 1; } 100% { transform: translate(-50%, -50%) scale(1); } }
|
||||
@keyframes cm-shake { 0%,100% { transform: none; } 25% { transform: translateX(-4px); } 75% { transform: translateX(4px); } }
|
||||
/* PC: the guess chat in the side panel takes the height left under the scores. */
|
||||
@media (min-width: 1100px) {
|
||||
.cm-side { flex: 1 1 auto; min-height: 0; }
|
||||
.cm-side .cm-chat { flex: 1 1 auto; min-height: 260px; }
|
||||
.cm-side .cm-chat-list { flex: 1 1 auto; max-height: none; }
|
||||
}
|
||||
@media (max-width: 1099px) {
|
||||
.cm-stage { flex-direction: column; align-items: stretch; }
|
||||
.cm-paper { width: 100%; min-width: 0; }
|
||||
@@ -677,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);
|
||||
@@ -699,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}
|
||||
</>
|
||||
);
|
||||
@@ -1005,6 +1030,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
|
||||
if (!t || !enabled) return;
|
||||
act(v.canGuess ? { type: 'guess', text: t.slice(0, max) } : { type: 'chat', text: t.slice(0, max) });
|
||||
setText('');
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
@@ -1020,7 +1046,7 @@ function GuessPanel({ v, me, players, act, pending }: { v: CatchmindView; me: st
|
||||
autoComplete="off"
|
||||
onKeyDown={(e) => e.key === 'Escape' && e.currentTarget.blur()}
|
||||
/>
|
||||
<button className="btn btn-primary" disabled={!enabled || !text.trim() || pending} style={{ minWidth: 72 }}>
|
||||
<button className="btn btn-primary" disabled={!enabled || !text.trim() || pending} style={{ minWidth: 72 }} {...keepFocus}>
|
||||
{v.canGuess && v.role !== 'solver' ? '맞히기' : '보내기'}
|
||||
</button>
|
||||
</form>
|
||||
@@ -1052,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(() => {
|
||||
@@ -1074,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
|
||||
}
|
||||
|
||||
@@ -1349,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';
|
||||
@@ -86,6 +87,8 @@ const CHESS_CSS = `
|
||||
@keyframes ch-fade { from { opacity: 0; } }
|
||||
:root[data-theme='dark'] .ch-icon-dark { filter: drop-shadow(0 0 .6px #e5e7eb) drop-shadow(0 0 .6px #e5e7eb); }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ch-icon-dark { filter: drop-shadow(0 0 .6px #e5e7eb) drop-shadow(0 0 .6px #e5e7eb); } }
|
||||
/* PC: the board takes the whole play-area height minus the row(s) that can show under it (--ch-rows). */
|
||||
@media (min-width: 1100px) { .board-wrap.ch-fit { max-width: min(100%, calc(var(--play-h) - var(--ch-rows, 0px))); } }
|
||||
`;
|
||||
|
||||
function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
@@ -229,7 +232,11 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||||
const cursorSq = squareAt(cursor.x, cursor.y, bottom);
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<div
|
||||
className="board-wrap stack ch-fit"
|
||||
// Room for what can show under the board: the castling hint (2 lines in 960) for players, [판 돌리기] for watchers.
|
||||
style={{ gap: 10, '--ch-rows': v.myColor ? (v.chess960Index === null ? 'calc(1.35rem + 10px)' : 'calc(2.7rem + 10px)') : 'calc(var(--tap) + 10px)' } as React.CSSProperties}
|
||||
>
|
||||
<style>{BOARD_MOTION_CSS + CHESS_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
@@ -536,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="상대의 요청">
|
||||
@@ -655,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',
|
||||
@@ -193,6 +193,26 @@ button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); }
|
||||
.cl-note { grid-template-columns: minmax(0, 1fr); }
|
||||
.cl-card { width: 66px; min-height: 78px; }
|
||||
}
|
||||
/* PC: fill the play column. Wide screens put the map on the left and the actions, my cards and notes on the right;
|
||||
room text, tokens and cards grow with the play area. */
|
||||
@media (min-width: 1100px) {
|
||||
.cl-board { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; }
|
||||
.cl-rname { font-size: clamp(.92rem, calc(var(--play-h) * .017), 1.25rem); }
|
||||
.cl-tok { width: clamp(24px, calc(var(--play-h) * .03), 34px); height: clamp(24px, calc(var(--play-h) * .03), 34px); font-size: clamp(.72rem, calc(var(--play-h) * .013), .95rem); }
|
||||
.cl-weap { font-size: clamp(1rem, calc(var(--play-h) * .024), 1.6rem); }
|
||||
.cl-mid { font-size: clamp(.8rem, calc(var(--play-h) * .014), 1rem); }
|
||||
.cl-card { width: clamp(74px, calc(var(--play-w) * .055), 100px); min-height: clamp(86px, calc(var(--play-w) * .064), 116px); }
|
||||
}
|
||||
@media (min-width: 1700px) {
|
||||
.cl-board { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-rows: auto auto minmax(0, 1fr);
|
||||
grid-template-areas: "map act" "map cards" "map note"; }
|
||||
.cl-top { display: contents; }
|
||||
.cl-map { grid-area: map; grid-template-rows: repeat(4, minmax(84px, 1fr)); }
|
||||
.cl-top > .cl-panel { grid-area: act; }
|
||||
.cl-board > section.cl-sec { grid-area: cards; }
|
||||
.cl-board > details.cl-sec { grid-area: note; }
|
||||
.cl-note li { min-height: clamp(34px, calc((var(--play-h) - 400px) / 11), 48px); }
|
||||
}
|
||||
/* Tokens / weapons on the map are lifted above the rooms while they slide (see slideFrom). */
|
||||
.cl-map [data-tok], .cl-map [data-weap] { position: relative; }
|
||||
.fx-ghost.cl-ghost { display: flex; align-items: center; justify-content: center; border-radius: 8px; background: linear-gradient(160deg, #fffaf0, #f1e6cf);
|
||||
@@ -282,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.
|
||||
@@ -411,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} />}
|
||||
@@ -615,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 (
|
||||
@@ -623,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)]}`} />
|
||||
@@ -654,6 +681,7 @@ function ActionPanel({
|
||||
myTurn,
|
||||
sel,
|
||||
setSel,
|
||||
rolling,
|
||||
}: {
|
||||
view: ClueView;
|
||||
me: string | null;
|
||||
@@ -663,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(() => {
|
||||
@@ -674,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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -719,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: '고발할지 차례를 끝낼지 고르는 중이에요',
|
||||
};
|
||||
@@ -802,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 })}>
|
||||
@@ -965,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 (
|
||||
<>
|
||||
@@ -991,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'];
|
||||
@@ -211,7 +211,7 @@ function BackCard({ size = 'md', fx }: { size?: 'sm' | 'md' | 'lg'; fx?: string
|
||||
// ---------------------------------------------------------------- styles
|
||||
|
||||
const CSS = `
|
||||
.cp-board { width: 100%; max-width: 1120px; display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 370px); gap: 12px; align-items: start; padding: 2px; }
|
||||
.cp-board { width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 370px); gap: 12px; align-items: start; padding: 2px; }
|
||||
.cp-felt { position: relative; border-radius: 26px; border: 8px solid var(--wood); box-shadow: var(--shadow); color: #fff; padding: 12px; display: flex; flex-direction: column; gap: 12px; min-height: 540px;
|
||||
background: radial-gradient(ellipse at 50% 45%, rgba(255,255,255,.14), rgba(255,255,255,0) 60%), var(--felt); }
|
||||
.cp-actions { display: flex; flex-direction: column; gap: 10px; min-width: 0; }
|
||||
@@ -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%; }
|
||||
@@ -347,6 +350,16 @@ ${KINDS.map((k) => `.fx-ghost.cp-face-${k} { background: ${KIND_COLOR[k].bg}; co
|
||||
.cp-say button:disabled { opacity: .45; cursor: not-allowed; }
|
||||
.cp-log { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; font-size: .9rem; }
|
||||
.cp-log li { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
/* PC: the felt fills the play column's height and its cards grow with it. */
|
||||
@media (min-width: 1100px) {
|
||||
.cp-board { flex: 1 1 auto; min-height: 0; align-items: stretch; grid-template-columns: minmax(0, 1fr) clamp(320px, 26%, 400px); }
|
||||
.cp-felt .cp-card.lg { --w: clamp(92px, calc(var(--play-h) * .13), 180px); }
|
||||
.cp-myhand .cp-card { --w: clamp(60px, min(calc(var(--play-h) * .085), calc(var(--play-w) * .06)), 120px); }
|
||||
.cp-chip .cp-mini { --w: clamp(30px, calc(var(--play-h) * .04), 52px); }
|
||||
.cp-seat { flex-basis: 140px; max-width: 340px; }
|
||||
.cp-center { min-height: 0; }
|
||||
.cp-speech { font-size: clamp(1.15rem, calc(var(--play-h) * .022), 1.5rem); max-width: 240px; }
|
||||
}
|
||||
@media (max-width: 899px) {
|
||||
.cp-board { grid-template-columns: minmax(0, 1fr); }
|
||||
.cp-felt { min-height: 0; }
|
||||
@@ -417,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 (
|
||||
@@ -444,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 />
|
||||
@@ -481,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">
|
||||
@@ -491,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} 앞마당으로
|
||||
@@ -510,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="테이블">
|
||||
@@ -554,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>
|
||||
);
|
||||
}
|
||||
@@ -750,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">
|
||||
@@ -783,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}
|
||||
@@ -828,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>
|
||||
@@ -846,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,
|
||||
@@ -877,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(() => {
|
||||
@@ -894,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!;
|
||||
@@ -930,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 (
|
||||
@@ -940,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 ? (
|
||||
@@ -952,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">
|
||||
@@ -992,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>
|
||||
@@ -1008,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';
|
||||
@@ -33,6 +34,9 @@ const CSS = `
|
||||
:root[data-theme='dark'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; } }
|
||||
@media (prefers-reduced-motion: reduce) { .c4-drop, .c4-win { animation: none; } }
|
||||
.board-wrap.c4-fit { max-width: min(100%, calc((100vh - var(--site-h, 56px) - 180px) * var(--c4-ar))); }
|
||||
/* PC: the board takes the whole play-area height minus the row that can show under it (--c4-rows). */
|
||||
@media (min-width: 1100px) { .board-wrap.c4-fit { max-width: min(100%, calc((var(--play-h) - var(--c4-rows, 0px)) * var(--c4-ar))); } }
|
||||
`;
|
||||
|
||||
function Disc({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
|
||||
@@ -129,12 +133,19 @@ 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);
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: `min(100%, calc((100vh - var(--site-h, 56px) - 180px) * ${(cols + 2 * pad) / (rows + 1.6)}))` }}>
|
||||
<div
|
||||
className="board-wrap stack c4-fit"
|
||||
// --c4-ar: board width per height of the svg below; touch tap-confirm also shows [두기][취소] under it.
|
||||
style={{ gap: 10, '--c4-ar': (cols + 2 * pad) / (rows + 1.7), '--c4-rows': tapConfirm ? 'calc(var(--btn-h) + 10px)' : '0px' } as React.CSSProperties}
|
||||
>
|
||||
<style>{CSS}</style>
|
||||
<svg
|
||||
className="c4-svg"
|
||||
@@ -189,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). */
|
||||
@@ -181,6 +181,21 @@ const CSS = `
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.dm *, .dm-seat, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; }
|
||||
}
|
||||
/* PC: fill the play column. The felt takes the spare height; seats, trick cards and the hand grow with the play area. */
|
||||
@media (min-width: 1100px) {
|
||||
.dm { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; justify-content: center; gap: 12px; }
|
||||
.dm-seats { flex-wrap: nowrap; gap: 8px; }
|
||||
.dm-seat { flex: 0 1 220px; min-width: 0; padding: 8px 12px; font-size: clamp(.88rem, calc(var(--play-h) / 64), 1.08rem); }
|
||||
.dm-seat .ttl, .dm-badge, .dm-bubble { font-size: .88em; }
|
||||
.dm-order { font-size: .86rem; }
|
||||
.dm-table { flex: 1 1 auto; padding: 20px; font-size: clamp(1rem, calc(var(--play-h) / 62), 1.2rem); }
|
||||
.dm-now { font-size: 1.6em; } .dm-now small { font-size: .6em; }
|
||||
.dm-table .dm-card { --w: clamp(60px, calc(var(--play-h) * .11), 150px); }
|
||||
/* The previous sets carry an inline 30px width; scale them too. */
|
||||
.dm-table .dm-prev .dm-card { --w: clamp(30px, calc(var(--play-h) * .05), 60px) !important; }
|
||||
.dm-hand { justify-content: center; }
|
||||
.dm-hand .dm-card { --w: clamp(60px, min(var(--play-h) * .09, (var(--play-w) - 40px) / 13 - 22px), 130px); }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.dm { gap: 8px; }
|
||||
.dm-seat { flex: 1 1 30%; min-width: 0; padding: 4px 6px; font-size: .82rem; }
|
||||
@@ -737,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);
|
||||
@@ -753,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}
|
||||
@@ -773,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.
|
||||
@@ -787,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) {
|
||||
@@ -848,7 +910,7 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
if (started.current) return;
|
||||
@@ -861,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
|
||||
@@ -881,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>
|
||||
@@ -906,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 />
|
||||
@@ -932,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)}
|
||||
@@ -941,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: '흰색' };
|
||||
@@ -105,7 +105,11 @@ const CSS = `
|
||||
.dv-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center;
|
||||
padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900;
|
||||
background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid #050505; box-shadow: 0 4px 0 rgba(0,0,0,.45), 0 12px 30px rgba(0,0,0,.35); }
|
||||
.dv-board { width: 100%; max-width: 980px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; }
|
||||
.dv-board { width: 100%; max-height: 100%; overflow: auto; display: flex; flex-direction: column; justify-content: center; gap: 12px; padding: 2px;
|
||||
flex: 1 1 auto; min-height: 0;
|
||||
/* Tile width grows with the play area: 13 tiles must fit a row, and all rows (--rows) + the middle panel the height. */
|
||||
--tw: clamp(46px, min(var(--play-w) / 19, (var(--play-h) - 420px - var(--rows, 2) * 90px) / (var(--rows, 2) * 2.2)), 112px); }
|
||||
.dv-board > * { flex: none; }
|
||||
.dv-opps { display: grid; gap: 10px; }
|
||||
.dv-player { background: var(--surface); border-radius: var(--radius-lg); padding: 10px 12px; box-shadow: var(--shadow); border: 3px solid transparent; }
|
||||
.dv-player.turn { border-color: var(--focus); }
|
||||
@@ -116,11 +120,11 @@ const CSS = `
|
||||
.dv-badge.turn { background: var(--focus); color: #1c1e21; }
|
||||
.dv-badge.out { background: var(--danger-soft); color: var(--danger); }
|
||||
.dv-badge.ok { background: var(--success-soft); color: var(--success); }
|
||||
.dv-row { --lift: 34px; display: flex; flex-wrap: wrap; gap: 6px; align-items: flex-end; padding-top: calc(8px + var(--lift)); }
|
||||
.dv-me .dv-row { --lift: 40px; }
|
||||
.dv-row { --lift: calc(var(--tw, 46px) * .74); display: flex; flex-wrap: wrap; justify-content: center; gap: 6px; align-items: flex-end; padding-top: calc(8px + var(--lift)); }
|
||||
.dv-me .dv-row { --lift: calc(var(--tw, 46px) * .87); }
|
||||
.dv-slot { display: flex; flex-direction: column; align-items: center; gap: 2px; }
|
||||
.dv-pos { font-size: .75rem; color: var(--text-sub); font-variant-numeric: tabular-nums; line-height: 1; }
|
||||
.dv-tile { --w: 46px; width: var(--w); height: calc(var(--w) * 1.42); border-radius: 8px; display: flex; align-items: center; justify-content: center;
|
||||
.dv-tile { --w: var(--tw, 46px); width: var(--w); height: calc(var(--w) * 1.42); border-radius: 8px; display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 900; font-size: calc(var(--w) * .56); line-height: 1; position: relative; user-select: none; font-variant-numeric: tabular-nums;
|
||||
box-shadow: 0 3px 0 rgba(0,0,0,.35); transition: transform .15s ease; }
|
||||
.dv-tile.black { background: linear-gradient(160deg, #42454d, #141519); color: #fff; border: 2px solid color-mix(in srgb, var(--text) 30%, #050505); }
|
||||
@@ -131,8 +135,8 @@ const CSS = `
|
||||
.dv-slot.open > .dv-pick { position: relative; top: calc(-1 * var(--lift)); }
|
||||
.dv-slot.open > .dv-pick::after { content: ''; position: absolute; left: 12%; right: 12%; bottom: -7px; height: 5px; border-radius: 3px; background: #f59e0b; }
|
||||
.dv-tile.secret { outline: 3px dashed var(--primary); outline-offset: 2px; }
|
||||
.dv-tile.sm { --w: 30px; }
|
||||
.dv-tile.lg { --w: 54px; }
|
||||
.dv-tile.sm { --w: calc(var(--tw, 46px) * .65); }
|
||||
.dv-tile.lg { --w: calc(var(--tw, 46px) * 1.17); }
|
||||
.dv-tile.hit { animation: dv-flip .5s ease-out both, dv-hit 1.2s ease-out both; }
|
||||
.dv-tile.miss { animation: dv-flip .5s ease-out both, dv-miss 1.2s ease-out both; animation-delay: var(--anim-delay, 0ms); }
|
||||
.dv-tile.new { animation: dv-drop .38s ease-out both; animation-delay: var(--anim-delay, 0ms); }
|
||||
@@ -153,7 +157,7 @@ const CSS = `
|
||||
.dv-gap { align-self: stretch; min-width: 28px; min-height: 48px; border: 2px dashed var(--primary); background: var(--primary-soft); color: var(--text);
|
||||
border-radius: 8px; font-weight: 800; cursor: pointer; padding: 0 2px; font-size: .8rem; }
|
||||
.dv-gap:focus-visible { outline: 3px solid var(--focus); }
|
||||
.dv-mid { display: grid; grid-template-columns: minmax(0, 260px) minmax(0, 1fr); gap: 12px; align-items: start; }
|
||||
.dv-mid { display: grid; grid-template-columns: minmax(0, clamp(260px, 24%, 360px)) minmax(0, 1fr); gap: 12px; align-items: start; }
|
||||
.dv-center { background: var(--felt); color: #fff; border-radius: var(--radius-lg); padding: 12px; display: flex; flex-direction: column; gap: 10px; align-items: center; }
|
||||
.dv-piles { display: flex; gap: 12px; justify-content: center; }
|
||||
.dv-pile { display: flex; flex-direction: column; align-items: center; gap: 4px; background: rgba(0,0,0,.18); border: 2px solid transparent; border-radius: 12px;
|
||||
@@ -161,7 +165,7 @@ const CSS = `
|
||||
.dv-pile:disabled { cursor: default; opacity: .8; }
|
||||
.dv-pile.can { border-color: #fde047; background: rgba(253,224,71,.15); }
|
||||
.dv-pile:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
|
||||
.dv-stack { position: relative; width: 44px; height: 50px; }
|
||||
.dv-stack { position: relative; width: calc(var(--tw, 46px) * .96); height: calc(var(--tw, 46px) * 1.09); }
|
||||
.dv-stack .dv-tile { position: absolute; left: 0; }
|
||||
.dv-pending { display: flex; align-items: center; gap: 10px; font-size: .9rem; }
|
||||
.dv-panel { background: var(--surface); border-radius: var(--radius-lg); box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 10px; }
|
||||
@@ -247,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'}`);
|
||||
|
||||
@@ -321,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') {
|
||||
@@ -365,7 +385,7 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="dv-board" role="region" aria-label="다빈치 코드 판">
|
||||
<div className="dv-board" role="region" aria-label="다빈치 코드 판" style={{ '--rows': v.seats.length } as CSSProperties}>
|
||||
<style>{CSS}</style>
|
||||
<div className="dv-opps">
|
||||
{opponentsOf(v, me).map((p) => (
|
||||
@@ -373,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">
|
||||
@@ -391,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 (
|
||||
@@ -404,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>개 ·{' '}
|
||||
</>
|
||||
@@ -554,6 +576,7 @@ function Center({
|
||||
pending,
|
||||
myTurn,
|
||||
pendFx,
|
||||
lastNo,
|
||||
}: {
|
||||
view: DavinciView;
|
||||
me: string | null;
|
||||
@@ -562,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 ? (
|
||||
@@ -639,6 +664,7 @@ function ActionPanel({
|
||||
act,
|
||||
pending,
|
||||
myTurn,
|
||||
settling,
|
||||
sel,
|
||||
val,
|
||||
setVal,
|
||||
@@ -650,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">
|
||||
@@ -882,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;
|
||||
@@ -39,7 +39,9 @@ const dbSound = {
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.db { width: 100%; max-width: 1060px; display: flex; flex-direction: column; gap: 10px; align-self: center; --cd: min(440px, 50vh, calc(50% - 14px)); }
|
||||
/* Fills the play column: the two cards are as big as the column allows (width split in two, height minus the rows around the table). */
|
||||
.db { width: 100%; display: flex; flex-direction: column; gap: 10px; align-self: stretch; flex: 1 1 auto; min-height: 0;
|
||||
--cd: clamp(200px, min(calc((var(--play-w) - 76px) / 2), calc(var(--play-h) - 250px)), 960px); }
|
||||
.db-top { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; justify-content: space-between; font-weight: 700; }
|
||||
.db-top .grp { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.db-pill { display: inline-flex; align-items: center; gap: 5px; border-radius: 999px; padding: 3px 10px; background: var(--surface); box-shadow: var(--shadow); font-size: .9rem; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
@@ -58,7 +60,7 @@ button.db-seat { cursor: pointer; }
|
||||
.db-tag { border-radius: 999px; padding: 0 6px; font-size: .72rem; font-weight: 800; line-height: 1.6; white-space: nowrap; color: #fff; background: #6b7280; }
|
||||
.db-tag.ok { background: #15803d; }
|
||||
.db-tag.warn { background: #f59e0b; color: #111827; }
|
||||
.db-table { position: relative; display: flex; gap: 24px; justify-content: center; align-items: flex-start; padding: 14px; border-radius: 26px; background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt); border: 6px solid var(--wood); box-shadow: var(--shadow); touch-action: manipulation; }
|
||||
.db-table { position: relative; flex: 1 1 auto; display: flex; gap: 24px; justify-content: center; align-items: center; padding: 14px; border-radius: 26px; background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt); border: 6px solid var(--wood); box-shadow: var(--shadow); touch-action: manipulation; }
|
||||
.db-slot { display: flex; flex-direction: column; align-items: center; gap: 6px; width: var(--cd); }
|
||||
.db-slot .cap { color: #fff; font-weight: 800; font-size: .95rem; text-shadow: 0 1px 2px rgba(0,0,0,.4); display: flex; gap: 6px; align-items: center; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
||||
.db-card { position: relative; width: 100%; aspect-ratio: 1; border-radius: 50%; background: #fffdf6; border: 4px solid #d6c7a1; box-shadow: 0 6px 0 rgba(0,0,0,.18), 0 10px 22px rgba(0,0,0,.28); }
|
||||
@@ -281,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 });
|
||||
|
||||
@@ -378,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');
|
||||
@@ -390,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));
|
||||
@@ -552,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>
|
||||
@@ -901,6 +913,7 @@ const ui: GameUI<DobbleView, DobbleOptions> = {
|
||||
Board: DobbleBoard,
|
||||
Side: DobbleSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
133
apps/web/src/games/gemblo/draw.tsx
Normal file
133
apps/web/src/games/gemblo/draw.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
/** 젬블로 그림 도우미: 납작한 육각형 칸, 보석 색과 무늬(색약 배려), 작은 블록 그림. */
|
||||
import type { BlockColor, PieceId } from '@bg/games/gemblo';
|
||||
import { pieceOffsets } from '@bg/games/gemblo/board';
|
||||
|
||||
export const SQ3 = Math.sqrt(3);
|
||||
/** Screen centre of (q, r) with hex radius 1. */
|
||||
export const hx = (q: number, r: number): [number, number] => [1.5 * q, SQ3 * (r + q / 2)];
|
||||
|
||||
const CORNERS = Array.from({ length: 6 }, (_, k) => [Math.cos((Math.PI / 3) * k), Math.sin((Math.PI / 3) * k)] as const);
|
||||
/** Polygon points of a flat-top hex. */
|
||||
export function hexPoints(cx: number, cy: number, s = 1): string {
|
||||
return CORNERS.map(([a, b]) => `${(cx + a * s).toFixed(3)},${(cy + b * s).toFixed(3)}`).join(' ');
|
||||
}
|
||||
|
||||
export const GEM: Record<BlockColor, { fill: string; edge: string; light: string }> = {
|
||||
red: { fill: '#e11d48', edge: '#9f1239', light: '#fda4af' },
|
||||
yellow: { fill: '#eab308', edge: '#a16207', light: '#fef08a' },
|
||||
green: { fill: '#16a34a', edge: '#166534', light: '#86efac' },
|
||||
blue: { fill: '#2563eb', edge: '#1e3a8a', light: '#93c5fd' },
|
||||
purple: { fill: '#9333ea', edge: '#581c87', light: '#d8b4fe' },
|
||||
orange: { fill: '#ea580c', edge: '#9a3412', light: '#fdba74' },
|
||||
gold: { fill: '#a8842c', edge: '#6b5313', light: '#f3dc8f' },
|
||||
};
|
||||
|
||||
/** A different mark per colour so colours can be told apart without seeing colour. */
|
||||
export function Glyph({ color, cx, cy, s = 0.3 }: { color: BlockColor; cx: number; cy: number; s?: number }) {
|
||||
const f = 'rgba(255,255,255,0.78)';
|
||||
switch (color) {
|
||||
case 'red':
|
||||
return <circle cx={cx} cy={cy} r={s * 0.8} fill={f} />;
|
||||
case 'yellow':
|
||||
return <polygon points={`${cx},${cy - s} ${cx + s * 0.95},${cy + s * 0.7} ${cx - s * 0.95},${cy + s * 0.7}`} fill="rgba(80,50,0,0.55)" />;
|
||||
case 'green':
|
||||
return <rect x={cx - s * 0.7} y={cy - s * 0.7} width={s * 1.4} height={s * 1.4} fill={f} />;
|
||||
case 'blue':
|
||||
return <polygon points={`${cx},${cy - s} ${cx + s},${cy} ${cx},${cy + s} ${cx - s},${cy}`} fill={f} />;
|
||||
case 'purple': {
|
||||
const pts = Array.from({ length: 10 }, (_, k) => {
|
||||
const a = -Math.PI / 2 + (Math.PI / 5) * k;
|
||||
const rr = k % 2 ? s * 0.45 : s * 1.05;
|
||||
return `${(cx + Math.cos(a) * rr).toFixed(3)},${(cy + Math.sin(a) * rr).toFixed(3)}`;
|
||||
}).join(' ');
|
||||
return <polygon points={pts} fill={f} />;
|
||||
}
|
||||
case 'orange':
|
||||
return <path d={`M${cx - s} ${cy}H${cx + s}M${cx} ${cy - s}V${cy + s}`} stroke={f} strokeWidth={s * 0.5} strokeLinecap="round" />;
|
||||
case 'gold':
|
||||
return <path d={`M${cx - s * 0.8} ${cy + s * 0.8}L${cx + s * 0.8} ${cy - s * 0.8}`} stroke="rgba(60,40,0,0.5)" strokeWidth={s * 0.35} strokeLinecap="round" />;
|
||||
}
|
||||
}
|
||||
|
||||
/** One gem cell (board and pictures share it). */
|
||||
export function GemCell({ color, cx, cy, s = 0.94, ghost, bad }: { color: BlockColor; cx: number; cy: number; s?: number; ghost?: boolean; bad?: boolean }) {
|
||||
const g = GEM[color];
|
||||
if (bad) return <polygon points={hexPoints(cx, cy, s)} fill="rgba(220,38,38,0.55)" stroke="#7f1d1d" strokeWidth={0.1} strokeDasharray="0.25 0.15" />;
|
||||
return (
|
||||
<g opacity={ghost ? 0.6 : 1}>
|
||||
<polygon points={hexPoints(cx, cy, s)} fill={g.fill} stroke={g.edge} strokeWidth={0.1} />
|
||||
<polygon points={hexPoints(cx - 0.12, cy - 0.14, s * 0.42)} fill={g.light} opacity={0.55} />
|
||||
<Glyph color={color} cx={cx} cy={cy + 0.05} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Cells of a piece in orientation o, as (q, r) offsets moved so the picture starts at (0, 0). */
|
||||
export function pieceShape(id: PieceId, o: number): [number, number][] {
|
||||
return pieceOffsets(id, o);
|
||||
}
|
||||
|
||||
/** Small picture of a block (tray, rules, results). `size` = pixel height of the box. */
|
||||
export function PieceIcon({ id, orient = 0, color, size = 44, dim, title }: { id: PieceId; orient?: number; color: BlockColor; size?: number; dim?: boolean; title?: string }) {
|
||||
const cells = pieceShape(id, orient).map(([q, r]) => hx(q, r));
|
||||
const xs = cells.map((c) => c[0]);
|
||||
const ys = cells.map((c) => c[1]);
|
||||
const minX = Math.min(...xs) - 1.05;
|
||||
const maxX = Math.max(...xs) + 1.05;
|
||||
const minY = Math.min(...ys) - 0.95;
|
||||
const maxY = Math.max(...ys) + 0.95;
|
||||
// Square box so every block in the tray has the same footprint (at least 4.6 units: a 5-cell line fits).
|
||||
const side = Math.max(maxX - minX, maxY - minY, 4.6);
|
||||
const cx = (minX + maxX) / 2;
|
||||
const cy = (minY + maxY) / 2;
|
||||
return (
|
||||
<svg viewBox={`${cx - side / 2} ${cy - side / 2} ${side} ${side}`} width={size} height={size} aria-hidden={title ? undefined : true} role={title ? 'img' : undefined} aria-label={title} style={{ opacity: dim ? 0.35 : 1, display: 'block' }}>
|
||||
{cells.map(([x, y], i) => (
|
||||
<GemCell key={i} color={color} cx={x} cy={y} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Mini board picture for the rules / 30초 요약: hexes in a small patch with coloured cells. */
|
||||
export interface MiniCell {
|
||||
q: number;
|
||||
r: number;
|
||||
color?: BlockColor;
|
||||
mark?: 'start' | 'link' | 'bad' | 'ghost';
|
||||
}
|
||||
export function MiniHex({ radius = 3, cells, lines = [], crosses = [], width = 170 }: { radius?: number; cells: MiniCell[]; lines?: [number, number, number, number][]; crosses?: [number, number][]; width?: number }) {
|
||||
const all: [number, number][] = [];
|
||||
for (let q = -radius; q <= radius; q++) for (let r = -radius; r <= radius; r++) if (Math.abs(q + r) <= radius) all.push([q, r]);
|
||||
const w = 3 * radius + 2.2;
|
||||
const h = SQ3 * (2 * radius + 1) + 0.4;
|
||||
const byKey = new Map(cells.map((c) => [`${c.q},${c.r}`, c]));
|
||||
return (
|
||||
<svg viewBox={`${-w / 2} ${-h / 2} ${w} ${h}`} width={width} height={(width * h) / w} aria-hidden style={{ display: 'block', margin: '0 auto' }}>
|
||||
<rect x={-w / 2} y={-h / 2} width={w} height={h} rx={0.8} fill="var(--wood)" />
|
||||
{all.map(([q, r]) => {
|
||||
const [x, y] = hx(q, r);
|
||||
const c = byKey.get(`${q},${r}`);
|
||||
if (c?.color && c.mark !== 'ghost' && c.mark !== 'bad') return <GemCell key={`${q},${r}`} color={c.color} cx={x} cy={y} />;
|
||||
return (
|
||||
<g key={`${q},${r}`}>
|
||||
<polygon points={hexPoints(x, y, 0.94)} fill="rgba(255,255,255,0.5)" />
|
||||
{c?.mark === 'ghost' && c.color && <GemCell color={c.color} cx={x} cy={y} ghost />}
|
||||
{c?.mark === 'bad' && <GemCell color="red" cx={x} cy={y} bad />}
|
||||
{c?.mark === 'start' && <polygon points={hexPoints(x, y, 0.7)} fill="none" stroke={GEM[c.color ?? 'red'].fill} strokeWidth={0.18} />}
|
||||
{c?.mark === 'link' && <circle cx={x} cy={y} r={0.26} fill={GEM[c.color ?? 'red'].fill} stroke="#fff" strokeWidth={0.08} />}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{lines.map(([q1, r1, q2, r2], i) => {
|
||||
const [x1, y1] = hx(q1, r1);
|
||||
const [x2, y2] = hx(q2, r2);
|
||||
return <line key={`l${i}`} x1={x1 + (x2 - x1) * 0.3} y1={y1 + (y2 - y1) * 0.3} x2={x1 + (x2 - x1) * 0.7} y2={y1 + (y2 - y1) * 0.7} stroke="#111827" strokeWidth={0.16} strokeLinecap="round" />;
|
||||
})}
|
||||
{crosses.map(([q, r], i) => {
|
||||
const [x, y] = hx(q, r);
|
||||
return <path key={`x${i}`} d={`M${x - 0.35} ${y - 0.35}L${x + 0.35} ${y + 0.35}M${x + 0.35} ${y - 0.35}L${x - 0.35} ${y + 0.35}`} stroke="#dc2626" strokeWidth={0.2} strokeLinecap="round" />;
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
27
apps/web/src/games/gemblo/help.test.ts
Normal file
27
apps/web/src/games/gemblo/help.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C', 'D', 'E']);
|
||||
const view = (s: unknown, who: string | null) => GAMES.gemblo!.view(s, who) as any;
|
||||
|
||||
test('젬블로: 내 차례(첫 블록) / 남의 차례 / 관전', () => {
|
||||
const { state } = setupGame('gemblo', 2, { seatOrder: 'joinOrder' }); // A: 빨강·초록, B: 노랑·파랑
|
||||
const mine = helpNow(view(state, 'A'), 'A', users);
|
||||
expect(mine).toContain('내 차례예요. 빨강 블록을 하나 놓아요(남은 72칸)');
|
||||
expect(mine).toContain('시작점을 덮어야');
|
||||
expect(mine).toContain('이음점');
|
||||
expect(helpNow(view(state, 'B'), 'B', users)).toContain('호랑이님(빨강) 차례예요. 기다려 주세요');
|
||||
expect(helpNow(view(state, null), null, users)).toContain('구경하고 있어요');
|
||||
});
|
||||
|
||||
test('젬블로: 두 번째 블록부터는 이음점 안내, 무르기 요청, 5명 장애물 고르기', () => {
|
||||
let { state } = setupGame('gemblo', 2, { seatOrder: 'joinOrder', undo: '1' });
|
||||
state = applyAction('gemblo', state, 'A', { type: 'place', pieceId: 'i5', orient: 0, q: -9, r: -3 });
|
||||
state = applyAction('gemblo', state, 'A', { type: 'requestUndo' });
|
||||
expect(helpNow(view(state, 'B'), 'B', users)).toContain('무르기를 부탁했어요');
|
||||
const five = setupGame('gemblo', 5, { seatOrder: 'joinOrder', fivePlayerObstacles: 'draft' }).state;
|
||||
expect(helpNow(view(five, 'A'), 'A', users)).toContain('장애물로 놓을 블록을 하나 골라요');
|
||||
expect(helpNow(view(five, 'B'), 'B', users)).toContain('호랑이님이 장애물 블록을 고르고 있어요');
|
||||
});
|
||||
57
apps/web/src/games/gemblo/help.ts
Normal file
57
apps/web/src/games/gemblo/help.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
/** 젬블로 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { GembloView } from '@bg/games/gemblo';
|
||||
import { COLOR_KO } from '@bg/games/gemblo/board';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
export function helpNow(v: GembloView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const nick = (id: string | null) => (id ? `${players[id]?.nickname ?? '다른 사람'}님` : '다른 사람');
|
||||
const mine = v.players.find((p) => p.id === me) ?? null;
|
||||
const myColors = mine ? mine.colors.map((i) => v.colors[i]!) : [];
|
||||
const myText = myColors.length ? `내 색은 ${myColors.map((c) => `${COLOR_KO[c.color]}(남은 ${c.leftCells}칸${c.done ? ', 끝' : ''})`).join(', ')}이에요.` : '';
|
||||
const goal = '같은 색끼리는 변이 닿으면 안 되고, 내 블록 꼭짓점에서 선을 따라 한 칸 떨어진 곳(이음점)에 이어 놓아요. 끝날 때 남은 칸이 적을수록 이겨요.';
|
||||
|
||||
if (v.phase === 'finished') {
|
||||
const r = v.result;
|
||||
if (!r) return '게임이 끝났어요.';
|
||||
const place = mine ? r.ranking.findIndex((g) => g.includes(mine.id)) : -1;
|
||||
const tail = place === 0 ? ' 내가 1등이에요!' : place > 0 ? ` 나는 ${place + 1}등이에요.` : '';
|
||||
return `게임이 끝났어요. ${r.summary}.${tail} 판 아래에 색마다 남은 블록이 보여요.`;
|
||||
}
|
||||
|
||||
if (!mine) {
|
||||
const turn = v.phase === 'playing' ? `${nick(v.turnPlayer)}(${COLOR_KO[v.colors[v.turn]!.color]}) 차례예요.` : `${nick(v.turnPlayer)}이 장애물을 ${v.phase === 'obstacleDraft' ? '고르는' : '놓는'} 중이에요.`;
|
||||
return `구경하고 있어요. ${turn}\n${goal}`;
|
||||
}
|
||||
if (mine.out) return `게임에서 빠졌어요(${mine.out === 'resign' ? '기권' : '시간패'}). 남은 사람들이 끝낼 때까지 지켜볼 수 있어요.\n${myText}`;
|
||||
|
||||
const u = v.undo.pending;
|
||||
if (u && u.by !== mine.id && !u.accepted.includes(mine.id)) {
|
||||
return `${nick(u.by)}이 무르기를 부탁했어요. [수락]하면 방금 놓은 블록 하나가 되돌려지고, [거절]하면 그대로 계속해요.`;
|
||||
}
|
||||
|
||||
if (v.phase === 'obstacleDraft') {
|
||||
if (v.turnPlayer === mine.id) return '5명 게임 준비예요. 남는 색 블록 15개를 장애물로 써요. 아래 목록에서 장애물로 놓을 블록을 하나 골라요(한 사람이 3개씩).';
|
||||
return `5명 게임 준비 중이에요. ${nick(v.turnPlayer)}이 장애물 블록을 고르고 있어요. 다 고르면 차례로 하나씩 판에 놓아요.`;
|
||||
}
|
||||
if (v.phase === 'obstaclePlace') {
|
||||
if (v.turnPlayer === mine.id)
|
||||
return '내가 고른 장애물을 판에 놓을 차례예요. 맨 바깥 줄에는 못 놓고, 바깥에서 두 번째 줄 칸을 하나 이상 덮으면서 판 가운데 쪽으로 뻗어야 해요. 두 시작점 사이마다 장애물은 3개까지예요.';
|
||||
return `${nick(v.turnPlayer)}이 장애물을 놓고 있어요. 장애물을 마지막에 놓은 사람부터 게임을 시작해요.`;
|
||||
}
|
||||
|
||||
const c = v.colors[v.turn]!;
|
||||
if (v.turnPlayer !== mine.id) {
|
||||
const wait = u && (u.by === mine.id || u.accepted.includes(mine.id)) ? '\n무르기 요청에 다른 사람이 답하기를 기다리는 중이에요.' : '';
|
||||
return `${nick(v.turnPlayer)}(${COLOR_KO[c.color]}) 차례예요. 기다려 주세요.\n${myText}${wait}`;
|
||||
}
|
||||
const lines = [`내 차례예요. ${COLOR_KO[c.color]} 블록을 하나 놓아요(남은 ${c.leftCells}칸).`];
|
||||
if (c.placed === 0) lines.push('첫 블록은 판에 테두리로 표시된 내 시작점을 덮어야 해요.');
|
||||
else lines.push(goal);
|
||||
lines.push('아래에서 블록을 고르고 판의 칸을 눌러 미리 본 뒤 [놓기]를 눌러요. ⟲ ⟳로 돌리고' + (v.allowFlip ? ' ↔로 뒤집어요.' : '요(이 방은 뒤집기 금지).'));
|
||||
if (v.showHints && v.legal) lines.push(`판의 내 색 점 ${v.legal.bridgePoints.length}개가 이음점이에요. 점을 누르면 그 점을 덮는 방법이 바로 나오고, 다시 누르면 다음 방법이에요.`);
|
||||
if (v.legal) {
|
||||
const locked = c.left.length - v.legal.placeable.length;
|
||||
if (locked > 0) lines.push(`🔒 표시 블록 ${locked}개는 지금 놓을 곳이 없어요.`);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
1225
apps/web/src/games/gemblo/index.tsx
Normal file
1225
apps/web/src/games/gemblo/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/web/src/games/gemblo/quick.tsx
Normal file
24
apps/web/src/games/gemblo/quick.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 젬블로 30초 규칙 요약 (docs/07 §5). Small hex patches drawn inline. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniHex } from './draw';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniHex cells={[{ q: 0, r: 0, color: 'red' }, { q: 0, r: 1, color: 'red' }, { q: 2, r: -1, mark: 'link', color: 'red' }, { q: 1, r: 2, mark: 'link', color: 'red' }, { q: -1, r: -1, mark: 'link', color: 'red' }]} lines={[[0, 0, 2, -1], [0, 1, 1, 2], [0, 0, -1, -1]]} />,
|
||||
alt: '빨간 블록의 꼭짓점에서 선을 따라 한 칸 떨어진 곳에 빨간 점이 찍혀 있어요',
|
||||
title: '선으로 한 칸 떨어져 이어요',
|
||||
text: '첫 블록은 내 시작점을 덮고, 그다음부터는 내 블록 꼭짓점에서 선을 따라 한 칸 떨어진 곳(내 색 점)에 이어 놓아요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniHex cells={[{ q: 0, r: 0, color: 'red' }, { q: 0, r: 1, mark: 'bad' }, { q: 1, r: 0, color: 'blue' }, { q: 1, r: 1, color: 'blue' }]} />,
|
||||
alt: '빨간 블록 바로 옆 칸은 빨갛게 막혀 있고, 파란 블록은 빨간 블록 옆에 붙어 있어요',
|
||||
title: '같은 색끼리는 닿으면 안 돼요',
|
||||
text: '같은 색 블록끼리는 변이 닿으면 안 돼요. 다른 색과는 붙어도 괜찮아요. 서로 다른 두 블록 사이의 틈은 지나갈 수 있어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniHex radius={2} cells={[{ q: -1, r: 0, color: 'green' }, { q: -1, r: 1, color: 'green' }, { q: 0, r: 0, color: 'yellow' }, { q: 1, r: -1, color: 'red' }, { q: 1, r: 0, color: 'red' }, { q: 0, r: 1, color: 'blue' }, { q: 0, r: -1, color: 'purple' }]} />,
|
||||
alt: '여러 색 보석 블록이 판을 채우고 있어요',
|
||||
title: '남은 칸이 적으면 승리',
|
||||
text: '놓을 곳이 없으면 그 색은 끝나요. 모두 끝나면 못 놓은 블록의 칸 수가 가장 적은 사람이 이겨요. 큰 블록부터 쓰세요!',
|
||||
},
|
||||
];
|
||||
24
apps/web/src/games/gemblo/sound.ts
Normal file
24
apps/web/src/games/gemblo/sound.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 젬블로 소리: 보석 블록 "딸깍". Short and soft; the site volume is applied by feedback.ts. */
|
||||
import { noise, tone } from '../../lib/feedback';
|
||||
|
||||
export const gmSound = {
|
||||
/** A block set down: a glassy click with a little shimmer. */
|
||||
place: () => {
|
||||
noise(28, 0.12, 0, 'bandpass', 3400, 2.2);
|
||||
tone(1760, 70, 'triangle', 0.07, 4);
|
||||
tone(2640, 90, 'sine', 0.035, 24);
|
||||
},
|
||||
/** A spot where the block can't go (small and low). */
|
||||
refuse: () => tone(190, 120, 'triangle', 0.08, 0, { slideTo: 140 }),
|
||||
/** A colour has nowhere left to go: a short falling pair. */
|
||||
out: () => {
|
||||
tone(523, 110, 'triangle', 0.06);
|
||||
tone(392, 160, 'triangle', 0.06, 110);
|
||||
},
|
||||
/** All 18 blocks of a colour placed: a quick sparkle. */
|
||||
allPlaced: () => [1319, 1568, 1976, 2637].forEach((f, i) => tone(f, 110, 'sine', 0.05, 60 + i * 55)),
|
||||
/** Rotating / flipping the block in hand. */
|
||||
turn: () => tone(1100, 30, 'triangle', 0.05),
|
||||
/** Moves taken back (무르기). */
|
||||
undo: () => tone(700, 160, 'sine', 0.06, 0, { slideTo: 420 }),
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 고스톱 / 맞고 화면 (docs/games/gostop.md §9). Points are room-only play points. */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { BakKind, CardView, GostopOptions, GostopView, HandCardView, OutcomeView, SeatView, TurnTag } from '@bg/games/gostop';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, Sheet } from '../../components/ui';
|
||||
@@ -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' };
|
||||
@@ -49,6 +49,15 @@ function useNarrow(): boolean {
|
||||
return narrow;
|
||||
}
|
||||
|
||||
/** Card size factor for the board (PC: grows with the play area, see GostopBoard). */
|
||||
const CardScale = createContext(1);
|
||||
const HW = { sm: 40, md: 60, lg: 84 } as const;
|
||||
/** Card width in px for a HwatuCard size, scaled for the play area. */
|
||||
function useCardW(): (size: keyof typeof HW) => number {
|
||||
const k = useContext(CardScale);
|
||||
return (size) => Math.round(HW[size] * k);
|
||||
}
|
||||
|
||||
function totalMsOf(v: GostopView): number {
|
||||
if (v.phase === 'roundResult') return 10_000;
|
||||
const who = v.step === 'sell' ? v.sell?.current : v.turn;
|
||||
@@ -93,7 +102,7 @@ function statusText(v: GostopView, me: string | null, players: Record<string, Pu
|
||||
}
|
||||
|
||||
const CSS = `
|
||||
.gs { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 8px; align-self: center; margin: auto 0; }
|
||||
.gs { width: 100%; display: flex; flex-direction: column; gap: 8px; align-self: center; margin: auto 0; }
|
||||
.gs-opps { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 8px; list-style: none; margin: 0; padding: 0; }
|
||||
.gs-seat { background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 10px; border: 3px solid transparent;
|
||||
box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
@@ -116,20 +125,20 @@ const CSS = `
|
||||
.gs-pile { display: flex; flex-direction: column; gap: 1px; min-width: 40px; }
|
||||
.gs-pile b { font-size: .78rem; font-weight: 800; color: var(--text-sub); white-space: nowrap; }
|
||||
.gs-pile-cards { display: flex; }
|
||||
.gs-pile-cards > * + * { margin-left: var(--ov, -30px); }
|
||||
.gs-pile-cards > * + * { margin-left: calc(var(--ov, -30px) * var(--gk, 1)); }
|
||||
.gs-cap[aria-expanded='true'] .gs-pile-cards > * + * { --ov: -14px; }
|
||||
.gs-table { border-radius: 20px; border: 8px solid var(--wood); box-shadow: var(--shadow); color: #fff; padding: 10px;
|
||||
background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt);
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) 210px; gap: 10px; align-items: stretch; }
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) calc(210px * var(--gk, 1)); gap: 10px; align-items: stretch; }
|
||||
.gs-floor { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 6px; list-style: none; margin: 0; padding: 0; }
|
||||
.gs-slot { min-height: 104px; border-radius: 10px; border: 2px dashed rgba(255,255,255,.16); display: flex; align-items: center; justify-content: center; position: relative; }
|
||||
.gs-slot { min-height: calc(104px * var(--gk, 1)); border-radius: 10px; border: 2px dashed rgba(255,255,255,.16); display: flex; align-items: center; justify-content: center; position: relative; }
|
||||
.gs-slot .m { position: absolute; top: 1px; left: 6px; font-size: .72rem; font-weight: 700; color: rgba(255,255,255,.55); }
|
||||
.gs-slot.has { border-style: solid; border-color: rgba(255,255,255,.28); }
|
||||
.gs-slot.ppeok { border: 3px solid #f87171; background: rgba(239,68,68,.18); }
|
||||
.gs-slot.ppeok::after { content: '뻑'; position: absolute; right: 4px; top: 2px; font-size: .75rem; font-weight: 900; color: #fecaca; }
|
||||
.gs-slot.natural::after { content: '3장'; }
|
||||
.gs-slot-cards { display: flex; }
|
||||
.gs-slot-cards > * + * { margin-left: var(--sov, -40px); }
|
||||
.gs-slot-cards > * + * { margin-left: var(--sov, calc(-40px * var(--gk, 1))); }
|
||||
.gs-glow { animation: gs-blink .9s ease-in-out infinite; border-radius: 8px; }
|
||||
@keyframes gs-blink { 0%, 100% { filter: drop-shadow(0 0 2px #fde047); } 50% { filter: drop-shadow(0 0 10px #fde047) brightness(1.08); } }
|
||||
.gs-side { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
@@ -166,6 +175,11 @@ const CSS = `
|
||||
.gs-res td { padding: 3px 4px; border-bottom: 1px solid var(--border); }
|
||||
.gs-res td.n { text-align: right; font-variant-numeric: tabular-nums; font-weight: 700; white-space: nowrap; }
|
||||
.gs-notice { background: var(--surface-2); border-radius: 10px; padding: 8px 12px; margin: 0; }
|
||||
/* PC: fill the play column; the floor takes the height the seats leave (cards grow with the area, see GostopBoard). */
|
||||
@media (min-width: 1100px) {
|
||||
.gs { align-self: stretch; flex: 1 1 auto; min-height: 0; margin: 0; }
|
||||
.gs-table { flex: 1 1 auto; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.gs-opps { grid-template-columns: 1fr; }
|
||||
.gs-table { grid-template-columns: 1fr; border-width: 5px; padding: 8px; }
|
||||
@@ -182,18 +196,20 @@ const CSS = `
|
||||
|
||||
function Card({ c, size = 'sm', className, style }: { c: CardView | null; size?: 'sm' | 'md' | 'lg'; className?: string; style?: React.CSSProperties }) {
|
||||
const card = c as HwatuInfo | null;
|
||||
const cw = useCardW();
|
||||
return className ? (
|
||||
<span className={className} style={{ display: 'inline-flex', ...style }}>
|
||||
<HwatuCard card={card} size={size} />
|
||||
<HwatuCard card={card} width={cw(size)} />
|
||||
</span>
|
||||
) : (
|
||||
<HwatuCard card={card} size={size} style={style} />
|
||||
<HwatuCard card={card} width={cw(size)} style={style} />
|
||||
);
|
||||
}
|
||||
|
||||
function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const groups = (['gwang', 'yeol', 'tti', 'pi'] as const).filter((k) => seat.captured[k].length > 0);
|
||||
const cw = useCardW();
|
||||
if (groups.length === 0)
|
||||
return (
|
||||
<span className="small muted" data-fx-cap={seat.id}>
|
||||
@@ -210,7 +226,7 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
<span className="gs-pile-cards">
|
||||
{seat.captured[k].map((c) => (
|
||||
<span key={c.key} data-gs-cap={c.key} style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={c as HwatuInfo} size="sm" />
|
||||
<HwatuCard card={c as HwatuInfo} width={cw('sm')} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
@@ -222,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}
|
||||
@@ -244,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>}
|
||||
@@ -263,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">
|
||||
@@ -273,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}장`}>
|
||||
@@ -310,9 +333,28 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop
|
||||
function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>; narrow: boolean; players: Record<string, PublicUser> }) {
|
||||
const months = Array.from({ length: 12 }, (_, i) => i + 1);
|
||||
const pf = v.pendingFlip;
|
||||
const cw = useCardW();
|
||||
// PC: floor cards fill their month slot (3 overlapping cards across, one card high), never smaller than the base size.
|
||||
const floorRef = useRef<HTMLUListElement | null>(null);
|
||||
const [fit, setFit] = useState(0);
|
||||
useLayoutEffect(() => {
|
||||
const el = floorRef.current;
|
||||
if (!el) return undefined;
|
||||
const measure = () => {
|
||||
if (window.innerWidth < 1100) return setFit(0);
|
||||
const slotW = (el.clientWidth - 5 * 6) / 6;
|
||||
const slotH = (el.clientHeight - 6) / 2;
|
||||
setFit(Math.floor(Math.min(150, (slotW - 10) / 1.66, (slotH - 24) / 1.63)));
|
||||
};
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
measure();
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
const fw = narrow ? 40 : Math.max(cw('md'), fit);
|
||||
return (
|
||||
<div className="gs-table" role="region" aria-label="바닥">
|
||||
<ul className="gs-floor" data-fx="gs-floor" aria-label="바닥 패(월별)">
|
||||
<ul className="gs-floor" ref={floorRef} data-fx="gs-floor" aria-label="바닥 패(월별)" style={fit ? ({ '--sov': `${-Math.round(fw * 0.67)}px` } as React.CSSProperties) : undefined}>
|
||||
{months.map((m) => {
|
||||
const g = v.floor.find((x) => x.month === m);
|
||||
const cls = `gs-slot${g ? ' has' : ''}${g && g.cards.length === 3 ? (g.natural ? ' ppeok natural' : ' ppeok') : ''}`;
|
||||
@@ -328,7 +370,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
<span className="gs-slot-cards">
|
||||
{g.cards.map((c) => (
|
||||
<span key={c.key} className={glow.has(c.id) ? 'gs-glow' : undefined} data-gs-floor={c.key} style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={c as HwatuInfo} size={narrow ? 'sm' : 'md'} />
|
||||
<HwatuCard card={c as HwatuInfo} width={fw} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
@@ -340,7 +382,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
<div className="gs-side">
|
||||
<div className="gs-deck">
|
||||
<div data-fx="gs-deck" aria-label={`더미 ${v.deckCount}장`} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
|
||||
<HwatuCard card={null} size={narrow ? 'sm' : 'md'} />
|
||||
<HwatuCard card={null} width={narrow ? 40 : cw('md')} />
|
||||
<strong>{v.deckCount}장</strong>
|
||||
</div>
|
||||
<div className="gs-info">
|
||||
@@ -358,7 +400,7 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
<div aria-label={`뒤집은 패 ${pf.flipped.name}`} style={{ textAlign: 'center' }}>
|
||||
<div className="small">뒤집은 패</div>
|
||||
<span className="gs-glow" data-fx="gs-pflip" style={{ display: 'inline-flex' }}>
|
||||
<HwatuCard card={pf.flipped as HwatuInfo} size="sm" />
|
||||
<HwatuCard card={pf.flipped as HwatuInfo} width={cw('sm')} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
@@ -370,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);
|
||||
@@ -424,8 +471,9 @@ 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(() => {
|
||||
setLifted(null);
|
||||
setAsk(null);
|
||||
@@ -476,7 +524,7 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
onFocus={() => onFocusCard(h)}
|
||||
onBlur={() => onFocusCard(null)}
|
||||
>
|
||||
<HwatuCard card={h.card as HwatuInfo} size="md" />
|
||||
<HwatuCard card={h.card as HwatuInfo} width={cw('md')} />
|
||||
{tag && <span className={`tag${h.canShake ? ' shake' : ''}`}>{tag}</span>}
|
||||
</button>
|
||||
);
|
||||
@@ -542,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">
|
||||
@@ -608,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) {
|
||||
@@ -708,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>
|
||||
@@ -1115,6 +1173,23 @@ function useGostopFx(v: GostopView, me: string | null, players: Record<string, P
|
||||
function GostopBoard(props: BoardProps<GostopView>) {
|
||||
const { view: v, me, players } = props;
|
||||
const narrow = useNarrow();
|
||||
// PC: cards grow with the play area (1 at the old 1100 px column, up to 1.7×; the height check keeps it on screen).
|
||||
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [k, setK] = useState(1);
|
||||
useLayoutEffect(() => {
|
||||
const el = rootRef.current;
|
||||
if (!el) return undefined;
|
||||
const wide = matchMedia('(min-width: 1100px)');
|
||||
const measure = () => setK(wide.matches ? Math.min(1.7, Math.max(1, Math.min(el.clientWidth / 1100, el.clientHeight / 640))) : 1);
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
wide.addEventListener('change', measure);
|
||||
measure();
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
wide.removeEventListener('change', measure);
|
||||
};
|
||||
}, []);
|
||||
const [focus, setFocus] = useState<HandCardView | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const mine = isMyTurn(v, me);
|
||||
@@ -1137,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);
|
||||
@@ -1149,30 +1225,38 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
const glow = new Set<number>(v.rules.hints && focus ? focus.matches : []);
|
||||
if (v.pendingFlip) for (const c of v.pendingFlip.options) glow.add(c.id);
|
||||
return (
|
||||
<div className="gs">
|
||||
<style>{CSS}</style>
|
||||
<ul className="gs-opps" aria-label={me ? '다른 사람' : '플레이어'}>
|
||||
{others.map((s) => (
|
||||
<SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={props.deadline} />
|
||||
))}
|
||||
</ul>
|
||||
<Floor v={v} glow={glow} narrow={narrow} players={players} />
|
||||
<RoundResult {...props} />
|
||||
<MyArea {...props} onFocusCard={setFocus} />
|
||||
<Decisions {...props} />
|
||||
{banner}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
<CardScale.Provider value={k}>
|
||||
<div className="gs" ref={rootRef} style={{ '--gk': k.toFixed(2) } as React.CSSProperties}>
|
||||
<style>{CSS}</style>
|
||||
<ul className="gs-opps" aria-label={me ? '다른 사람' : '플레이어'}>
|
||||
{others.map((s) => (
|
||||
<SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={props.deadline} />
|
||||
))}
|
||||
</ul>
|
||||
<Floor v={v} glow={glow} narrow={narrow} players={players} />
|
||||
<RoundResult {...props} />
|
||||
<MyArea {...props} onFocusCard={setFocus} holdOpen={!resultShown} />
|
||||
<Decisions {...props} />
|
||||
{banner}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
</CardScale.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 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>
|
||||
@@ -1198,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>
|
||||
@@ -1206,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>
|
||||
)}
|
||||
@@ -1230,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,8 @@ 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'];
|
||||
const FRUIT_KO: Record<Fruit, string> = { strawberry: '딸기', banana: '바나나', lime: '라임', plum: '자두' };
|
||||
@@ -36,7 +37,8 @@ const hgSound = {
|
||||
};
|
||||
|
||||
const CSS = `
|
||||
.hg { width: 100%; max-width: 1100px; display: flex; flex-direction: column; gap: 10px; align-self: center; }
|
||||
/* Fills the play column; on PC the table takes all the height the top row and my deck row leave. */
|
||||
.hg { width: 100%; display: flex; flex-direction: column; gap: 10px; align-self: stretch; flex: 1 1 auto; min-height: 0; }
|
||||
.hg-top { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; justify-content: space-between; font-weight: 700; }
|
||||
.hg-top .grp { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
|
||||
.hg-pill { display: inline-flex; align-items: center; gap: 5px; border-radius: 999px; padding: 3px 10px; background: var(--surface); box-shadow: var(--shadow); font-size: .92rem; font-variant-numeric: tabular-nums; }
|
||||
@@ -144,6 +146,12 @@ const CSS = `
|
||||
@keyframes hg-pop { 0% { transform: translateX(-50%) scale(.6); opacity: 0; } 70% { transform: translateX(-50%) scale(1.06); opacity: 1; } 100% { transform: translateX(-50%) scale(1); } }
|
||||
@keyframes hg-ring { 0%,100% { transform: rotate(0); } 20% { transform: rotate(-14deg); } 40% { transform: rotate(12deg); } 60% { transform: rotate(-8deg); } 80% { transform: rotate(5deg); } }
|
||||
@keyframes hg-fly { from { left: var(--fx); top: var(--fy); opacity: 1; } 85% { opacity: .9; } to { left: var(--tx); top: var(--ty); opacity: 0; transform: translate(-50%, -50%) scale(.6); } }
|
||||
@media (min-width: 720px) {
|
||||
.hg-table { flex: 1 1 auto; height: auto; min-height: clamp(440px, 64vh, 600px); }
|
||||
}
|
||||
@media (min-width: 1100px) {
|
||||
.hg-table { min-height: 440px; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.hg-table { height: 450px; border-width: 6px; border-radius: 22px; }
|
||||
.hg-seat { padding: 3px 3px 4px; gap: 2px; }
|
||||
@@ -331,7 +339,7 @@ const CENTER: Pos = { left: '50%', top: '50%' };
|
||||
* "half the table minus half a seat", so seats always stay inside the felt whatever its size.
|
||||
* `tall` (narrow phone table): seats that are not level with the bell move further up/down so they clear it.
|
||||
*/
|
||||
function seatPositions(n: number, seat: { w: number; h: number }, maxRx: number, tall: boolean): Pos[] {
|
||||
function seatPositions(n: number, seat: { w: string; h: string }, maxRx: string, tall: boolean): Pos[] {
|
||||
const f = (x: number) => (Math.abs(x) < 1e-9 ? 0 : Number(x.toFixed(4)));
|
||||
return Array.from({ length: n }, (_, k) => {
|
||||
const t = (2 * Math.PI * k) / n;
|
||||
@@ -339,8 +347,8 @@ function seatPositions(n: number, seat: { w: number; h: number }, maxRx: number,
|
||||
const y = tall && c !== 0 ? Math.sign(c) * Math.max(Math.abs(c), 0.75) : c;
|
||||
const sn = f(Math.sin(t));
|
||||
return {
|
||||
left: `calc(50% - ${sn} * min(50% - ${seat.w / 2 + 6}px, ${maxRx}px))`,
|
||||
top: `calc(50% + ${y} * (50% - ${seat.h / 2 + 6}px))`,
|
||||
left: `calc(50% - ${sn} * min(50% - ${seat.w} / 2 - 6px, ${maxRx}))`,
|
||||
top: `calc(50% + ${y} * (50% - ${seat.h} / 2 - 6px))`,
|
||||
side: sn > 0.2 ? 'left' : sn < -0.2 ? 'right' : 'mid',
|
||||
dir: [-sn, y],
|
||||
};
|
||||
@@ -546,6 +554,7 @@ function bellText(v: HalliGalliView, players: Record<string, PublicUser>): Bubbl
|
||||
function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<HalliGalliView>) {
|
||||
const now = useServerNow(100);
|
||||
const phone = usePhone();
|
||||
const wide = useWide();
|
||||
const rtt = useRoom((s) => s.rttMs);
|
||||
const [bubble, setBubble] = useState<Bubble | null>(null);
|
||||
const [ghosts, setGhosts] = useState<Ghost[]>([]);
|
||||
@@ -563,9 +572,16 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
const rot = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx), ...v.seats.slice(0, myIdx)];
|
||||
const many = rot.length >= 5;
|
||||
const cw = phone ? (many ? 40 : 50) : many ? 64 : 80;
|
||||
const sw = Math.round(cw * 1.72 + 6 + 12);
|
||||
const pos = seatPositions(rot.length, { w: sw, h: cw * 1.4 + (phone ? 50 : 58) + 8 }, phone ? 400 : 400, phone);
|
||||
// Card width: fixed on phones/tablets; on PC it grows with the play area (CSS length, so seats and fly-ins follow live resizes).
|
||||
const cwPx = phone ? (many ? 40 : 50) : many ? 64 : 80;
|
||||
const cw = !wide
|
||||
? `${cwPx}px`
|
||||
: many
|
||||
? 'clamp(64px, min(var(--play-w) * .056, var(--play-h) * .088), 128px)'
|
||||
: 'clamp(80px, min(var(--play-w) * .07, var(--play-h) * .11), 160px)';
|
||||
const sw = wide ? 'calc(var(--cw) * 1.72 + 18px)' : `${Math.round(cwPx * 1.72 + 18)}px`;
|
||||
const seatH = wide ? 'calc(var(--cw) * 1.4 + 66px)' : `${cwPx * 1.4 + (phone ? 50 : 58) + 8}px`;
|
||||
const pos = seatPositions(rot.length, { w: sw, h: seatH }, wide ? 'max(400px, var(--bell) * 2.4)' : '400px', phone);
|
||||
const posOf = (id: string) => pos[rot.findIndex((s) => s.id === id)] ?? CENTER;
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const playing = v.phase === 'playing';
|
||||
@@ -709,7 +725,14 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
|
||||
return () => clearTimeout(t);
|
||||
}, [bubble]);
|
||||
|
||||
const bellSize = phone ? (rot.length >= 5 ? 128 : 'min(40vw, 156px)') : 'clamp(140px, 20vh, 190px)';
|
||||
// PC: the bell (and its dashed ring, 1.55x) grows too, but stays clear of the top and bottom seats (table ≈ play height - 130px).
|
||||
const bellSize = phone
|
||||
? rot.length >= 5
|
||||
? 128
|
||||
: 'min(40vw, 156px)'
|
||||
: wide
|
||||
? 'clamp(140px, min(var(--play-h) * .26, var(--play-w) * .2, (var(--play-h) - 142px - 2 * (var(--cw) * 1.4 + 66px)) / 1.55), 320px)'
|
||||
: 'clamp(140px, 20vh, 190px)';
|
||||
const countdown = v.phase === 'countdown' ? Math.max(0, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
const totals = FRUITS.map((f) => ({ f, n: v.seats.reduce((a, s) => a + (s.top && s.top.fruit === f ? s.top.count : 0), 0) }));
|
||||
const timeLeft = v.endsAt !== null ? Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt)) : null;
|
||||
@@ -755,7 +778,7 @@ function HalliGalliBoard({ view: v, me, players, act, pending }: BoardProps<Hall
|
||||
className="hg-table"
|
||||
role="region"
|
||||
aria-label="카드 테이블"
|
||||
style={{ '--bell': typeof bellSize === 'number' ? `${bellSize}px` : bellSize, '--cw': `${cw}px`, '--sw': `${sw}px` } as CSSProperties}
|
||||
style={{ '--bell': typeof bellSize === 'number' ? `${bellSize}px` : bellSize, '--cw': cw, '--sw': sw } as CSSProperties}
|
||||
>
|
||||
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }} aria-label="사람들의 펼친 카드">
|
||||
{rot.map((s, i) => (
|
||||
@@ -952,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>
|
||||
@@ -1198,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(34);
|
||||
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,/);
|
||||
|
||||
156
apps/web/src/games/hot-streak/art.tsx
Normal file
156
apps/web/src/games/hot-streak/art.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* 핫스트릭 그림: 우리가 새로 그린 탈 인형 마스코트 4명(곰·핫도그·아귀·여왕)과 경주 카드 (docs/games/hot-streak.md §9, §12).
|
||||
* Simple inline SVG only — no original artwork.
|
||||
*/
|
||||
import { MASCOTS, cardInfo, type CardBase, type MascotId } from '@bg/games/hot-streak/cards';
|
||||
|
||||
/** A mascot face drawn in a 100×100 box (centre 50,50). */
|
||||
export function MascotFace({ id }: { id: MascotId }) {
|
||||
const m = MASCOTS[id];
|
||||
const eyes = (y = 46, dx = 13) => (
|
||||
<>
|
||||
<circle cx={50 - dx} cy={y} r={6.5} fill="#fff" />
|
||||
<circle cx={50 + dx} cy={y} r={6.5} fill="#fff" />
|
||||
<circle cx={51 - dx} cy={y + 1} r={3.2} fill="#111827" />
|
||||
<circle cx={51 + dx} cy={y + 1} r={3.2} fill="#111827" />
|
||||
</>
|
||||
);
|
||||
switch (id) {
|
||||
case 'G':
|
||||
return (
|
||||
<g>
|
||||
<circle cx={24} cy={24} r={13} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
|
||||
<circle cx={76} cy={24} r={13} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
|
||||
<circle cx={24} cy={24} r={6} fill="#fed7aa" />
|
||||
<circle cx={76} cy={24} r={6} fill="#fed7aa" />
|
||||
<circle cx={50} cy={52} r={36} fill={m.color} stroke="#7c2d12" strokeWidth={3} />
|
||||
<ellipse cx={50} cy={66} rx={17} ry={13} fill="#fed7aa" />
|
||||
<ellipse cx={50} cy={60} rx={6} ry={4.5} fill="#3f1d0b" />
|
||||
<path d="M44 70 Q50 75 56 70" stroke="#3f1d0b" strokeWidth={3} fill="none" strokeLinecap="round" />
|
||||
{eyes(44)}
|
||||
<rect x={22} y={82} width={56} height={12} rx={6} fill={m.color2} />
|
||||
</g>
|
||||
);
|
||||
case 'H':
|
||||
return (
|
||||
<g>
|
||||
<rect x={14} y={30} width={72} height={52} rx={26} fill="#f6c27a" stroke="#92400e" strokeWidth={3} />
|
||||
<rect x={20} y={18} width={60} height={64} rx={30} fill={m.color} stroke="#7f1d1d" strokeWidth={3} />
|
||||
<path d="M28 30 l8 6 l8 -6 l8 6 l8 -6 l8 6" stroke="#facc15" strokeWidth={4} fill="none" strokeLinejoin="round" strokeLinecap="round" />
|
||||
{eyes(52, 12)}
|
||||
<path d="M40 66 Q50 74 60 66" stroke="#7f1d1d" strokeWidth={3.5} fill="none" strokeLinecap="round" />
|
||||
<rect x={10} y={76} width={80} height={14} rx={7} fill="#f6c27a" stroke="#92400e" strokeWidth={3} />
|
||||
</g>
|
||||
);
|
||||
case 'D':
|
||||
return (
|
||||
<g>
|
||||
<path d="M52 20 Q58 2 74 6" stroke="#1e3a8a" strokeWidth={3.5} fill="none" strokeLinecap="round" />
|
||||
<circle cx={76} cy={7} r={6.5} fill="#fde047" stroke="#a16207" strokeWidth={2} />
|
||||
<ellipse cx={50} cy={56} rx={38} ry={33} fill={m.color} stroke="#1e3a8a" strokeWidth={3} />
|
||||
<path d="M12 56 L2 44 L4 68 Z" fill={m.color2} stroke="#1e3a8a" strokeWidth={2.5} strokeLinejoin="round" />
|
||||
{eyes(42, 14)}
|
||||
<path d="M24 66 Q50 86 76 66 Z" fill="#1e1b4b" />
|
||||
<path d="M28 67 l5 7 l5 -6 l5 7 l5 -7 l5 7 l5 -7 l5 6 l5 -6" stroke="#fff" strokeWidth={2.5} fill="none" strokeLinejoin="round" />
|
||||
</g>
|
||||
);
|
||||
case 'M':
|
||||
return (
|
||||
<g>
|
||||
<path d="M22 34 L26 10 L38 24 L50 6 L62 24 L74 10 L78 34 Z" fill={m.color} stroke="#854d0e" strokeWidth={3} strokeLinejoin="round" />
|
||||
<circle cx={50} cy={20} r={4} fill={m.color2} />
|
||||
<circle cx={50} cy={58} r={30} fill="#fde68a" stroke="#854d0e" strokeWidth={3} />
|
||||
<path d="M20 50 Q14 76 30 88 M80 50 Q86 76 70 88" stroke={m.color2} strokeWidth={7} fill="none" strokeLinecap="round" />
|
||||
{eyes(54, 11)}
|
||||
<circle cx={34} cy={68} r={5} fill="#fda4af" opacity={0.8} />
|
||||
<circle cx={66} cy={68} r={5} fill="#fda4af" opacity={0.8} />
|
||||
<path d="M43 72 Q50 77 57 72" stroke="#9f1239" strokeWidth={3} fill="none" strokeLinecap="round" />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Mascot icon as its own <svg> (lists, buttons). */
|
||||
export function MascotIcon({ id, size = 28, title }: { id: MascotId; size?: number; title?: string }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 100" width={size} height={size} aria-hidden={title ? undefined : true} role={title ? 'img' : undefined} aria-label={title} style={{ flex: 'none', overflow: 'visible' }}>
|
||||
<MascotFace id={id} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small glyph of what a card does (arrow, star, fall …). */
|
||||
function EffectGlyph({ base }: { base: CardBase }) {
|
||||
const e = cardInfo(base).effect;
|
||||
const stroke = { stroke: '#111827', strokeWidth: 5, fill: 'none', strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const };
|
||||
switch (e.kind) {
|
||||
case 'star':
|
||||
return <path d="M50 18 L58 40 L82 40 L62 54 L70 78 L50 63 L30 78 L38 54 L18 40 L42 40 Z" fill="#facc15" stroke="#a16207" strokeWidth={3} />;
|
||||
case 'fall':
|
||||
return (
|
||||
<g {...stroke}>
|
||||
<path d="M22 70 L78 70" />
|
||||
<path d="M40 44 L62 60" strokeWidth={9} />
|
||||
<circle cx={34} cy={38} r={7} fill="#111827" />
|
||||
</g>
|
||||
);
|
||||
case 'turn':
|
||||
return <path d="M30 60 Q30 30 55 30 Q76 30 76 52 M68 44 L76 54 L84 44" {...stroke} />;
|
||||
case 'weave':
|
||||
return <path d="M20 66 L56 66 Q72 66 72 50 L72 30 M64 38 L72 28 L80 38" {...stroke} />;
|
||||
case 'rise':
|
||||
return (
|
||||
<g {...stroke}>
|
||||
<path d="M50 76 L50 30 M38 42 L50 28 L62 42" />
|
||||
<path d="M30 80 L70 80" />
|
||||
</g>
|
||||
);
|
||||
default:
|
||||
return e.n < 0 ? <path d="M78 50 L24 50 M38 36 L22 50 L38 64" {...stroke} /> : <path d="M22 50 L76 50 M62 36 L78 50 L62 64" {...stroke} />;
|
||||
}
|
||||
}
|
||||
|
||||
const BIG: Record<string, string> = { move: '', rise: '↑', star: '★', fall: '', turn: '', weave: '' };
|
||||
|
||||
/** A race card face. `size` = width in px (height 1.4×). */
|
||||
export function RaceCard({ base, size = 64, faceDown = false, className = '' }: { base?: CardBase | null; size?: number; faceDown?: boolean; className?: string }) {
|
||||
const w = size;
|
||||
const h = Math.round(size * 1.4);
|
||||
if (faceDown || !base) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 140" width={w} height={h} className={`hs-card ${className}`} aria-hidden>
|
||||
<rect x={3} y={3} width={94} height={134} rx={12} fill="#1f2937" stroke="#f97316" strokeWidth={4} />
|
||||
<path d="M20 40 L50 20 L80 40 M20 70 L50 50 L80 70 M20 100 L50 80 L80 100 M20 130 L50 110 L80 130" stroke="#f97316" strokeWidth={6} fill="none" opacity={0.6} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
const c = cardInfo(base);
|
||||
const m = c.who === 'all' ? null : MASCOTS[c.who];
|
||||
const e = c.effect;
|
||||
const num = e.kind === 'move' || e.kind === 'rise' || e.kind === 'weave' ? `${e.n < 0 ? '−' : ''}${Math.abs(e.n)}` : BIG[e.kind] ?? '';
|
||||
return (
|
||||
<svg viewBox="0 0 100 140" width={w} height={h} className={`hs-card ${className}`} role="img" aria-label={c.who === 'all' ? c.label : `${m!.name} ${c.label}`}>
|
||||
<rect x={3} y={3} width={94} height={134} rx={12} fill={m ? '#fffdf7' : '#dcfce7'} stroke={c.starter ? '#111827' : m ? m.color : '#16a34a'} strokeWidth={c.starter ? 7 : 5} />
|
||||
<rect x={3} y={3} width={94} height={30} rx={12} fill={m ? m.color : '#16a34a'} />
|
||||
<rect x={3} y={22} width={94} height={11} fill={m ? m.color : '#16a34a'} />
|
||||
{m ? (
|
||||
<g transform="translate(6 4) scale(0.27)">
|
||||
<MascotFace id={m.id} />
|
||||
</g>
|
||||
) : (
|
||||
<text x={12} y={25} fontSize={18} fontWeight={900} fill="#fff">
|
||||
모두
|
||||
</text>
|
||||
)}
|
||||
<text x={90} y={26} fontSize={22} fontWeight={900} fill="#fff" textAnchor="end">
|
||||
{num}
|
||||
</text>
|
||||
<g transform="translate(14 36) scale(0.72)">
|
||||
<EffectGlyph base={base} />
|
||||
</g>
|
||||
<text x={50} y={124} fontSize={c.label.length > 6 ? 12 : 15} fontWeight={800} fill="#111827" textAnchor="middle">
|
||||
{c.who === 'all' ? c.label.replace('모두 ', '') : c.label}
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
30
apps/web/src/games/hot-streak/help.test.ts
Normal file
30
apps/web/src/games/hot-streak/help.test.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const ID = 'hot-streak';
|
||||
const users = usersOf(['A', 'B', 'C', 'D']);
|
||||
const view = (s: unknown, who: string | null) => GAMES[ID]!.view(s, who) as any;
|
||||
const picker = (s: any): string => s.seats[s.draftOrder[s.draftAt]];
|
||||
|
||||
test('핫스트릭: 티켓 뽑기 차례 / 기다리기 / 관전', () => {
|
||||
const { state } = setupGame(ID, 4);
|
||||
const p = picker(state);
|
||||
const other = state.seats.find((x: string) => x !== p)!;
|
||||
expect(helpNow(view(state, p), p, users)).toContain('티켓을 가져올 차례');
|
||||
expect(helpNow(view(state, other), other, users)).toContain(`${users[p]!.nickname}님이 티켓을 고르는 중`);
|
||||
expect(helpNow(view(state, null), null, users)).toContain('1번째 경주');
|
||||
});
|
||||
|
||||
test('핫스트릭: 카드 넣기와 경주', () => {
|
||||
let { state } = setupGame(ID, 4);
|
||||
while (state.phase === 'draft') {
|
||||
const p = picker(state);
|
||||
state = applyAction(ID, state, p, GAMES[ID]!.legalActions!(state, p)[0]);
|
||||
}
|
||||
expect(helpNow(view(state, 'A'), 'A', users)).toContain('[몰래 넣기]');
|
||||
for (const p of ['A', 'B', 'C', 'D']) state = applyAction(ID, state, p, { type: 'SUBMIT', cards: [state.hands[p][0]] });
|
||||
expect(state.phase).toBe('race');
|
||||
expect(helpNow(view(state, 'A'), 'A', users)).toContain('[빨리 보기]');
|
||||
});
|
||||
59
apps/web/src/games/hot-streak/help.ts
Normal file
59
apps/web/src/games/hot-streak/help.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/** 핫스트릭 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { HotStreakView } from '@bg/games/hot-streak';
|
||||
import { MASCOTS, cardHelp, isMascot } from '@bg/games/hot-streak/cards';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
export function helpNow(v: HotStreakView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const name = (p: string) => `${players[p]?.nickname ?? '다른 사람'}님`;
|
||||
const seated = !!me && v.seats.includes(me);
|
||||
const money = seated ? `지금 내 돈은 $${v.money[me!]}이에요.` : '';
|
||||
const goal = `경주를 ${v.races}번 하고 돈이 가장 많은 사람이 이겨요(놀이용 가상 돈).`;
|
||||
|
||||
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
|
||||
if (seated && v.left.includes(me!)) return '나는 그만해서 구경만 할 수 있어요. 내 차례는 자동으로 진행돼요.';
|
||||
const head = `${v.raceNo}번째 경주예요. 이번 사이드 질문: ${v.side.text}`;
|
||||
|
||||
if (v.phase === 'draft' && v.mode === 'tickets') {
|
||||
const d = v.draft!;
|
||||
if (v.legal.draft) {
|
||||
return [
|
||||
head,
|
||||
'지금 내가 티켓을 가져올 차례예요. 마스코트 더미나 YES·NO 더미를 눌러 맨 위 티켓을 안전 면이나 위험 면으로 가져와요.',
|
||||
'안전 면은 2·3등이어도 꽤 받고, 위험 면은 1등일 때 크게 받아요. 사이드 위험 면은 틀리면 $5를 내요.',
|
||||
v.faceUp.length ? '아래 "경주 덱 앞면"을 보고 카드가 많은 마스코트를 노려 보세요.' : '',
|
||||
money,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
return `${head}\n지금은 ${name(d.picker)}이 티켓을 고르는 중이에요. 뱀 순서로 돌아가며 한 장씩 가져와요.\n${goal}\n${money}`.trim();
|
||||
}
|
||||
if (v.phase === 'double') {
|
||||
if (v.legal.double) return `${head}\n마지막 경주예요! 내 티켓 중 하나를 골라 두 배로 해요. 틀리면 마이너스도 두 배예요.\n${money}`.trim();
|
||||
return `${head}\n${name(v.doubleFor ?? '')}이 두 배로 할 티켓을 고르는 중이에요.\n${money}`.trim();
|
||||
}
|
||||
if (v.phase === 'draft') {
|
||||
if (v.legal.pot) return `${head}\n마스코트 하나와 사이드 질문 YES/NO를 몰래 적어요. 18장 덱이 모두 앞면으로 보여요. 모두 적으면 함께 공개돼요.\n${goal}`;
|
||||
return `${head}\n모두 몰래 적는 중이에요. 다 적으면 경주가 시작돼요.\n${goal}`;
|
||||
}
|
||||
if (v.phase === 'submit') {
|
||||
if (v.legal.submit) {
|
||||
const tip = v.hand?.[0] ? `예: ${cardHelp(v.hand[0].base)}` : '';
|
||||
return `${head}\n손패에서 ${v.legal.submit.count}장을 눌러 고른 뒤 [몰래 넣기]를 눌러요. 내가 건 마스코트를 밀어 주거나 1등 후보를 넘어뜨리는 카드가 좋아요.\n${tip}\n${money}`.trim();
|
||||
}
|
||||
return `${head}\n다른 사람이 카드를 넣는 중이에요. 누가 무엇을 넣었는지는 끝까지 비밀이에요.\n${money}`.trim();
|
||||
}
|
||||
if (v.phase === 'race') {
|
||||
const mine = seated ? v.tickets[me!] ?? [] : [];
|
||||
const bet = mine.filter((t) => isMascot(t.stack)).map((t) => MASCOTS[t.stack as keyof typeof MASCOTS].name);
|
||||
return [
|
||||
`${head}\n경주 중이에요! 카드가 몇 초마다 한 장씩 넘어가요. 지금은 고를 것이 없어요. 구경하며 응원해요.`,
|
||||
bet.length ? `내가 건 마스코트: ${[...new Set(bet)].join(', ')}.` : '',
|
||||
seated ? '모두 [빨리 보기]를 누르면 끝까지 바로 처리해요.' : '',
|
||||
money,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
return `${head}\n이번 경주 정산이에요. 티켓마다 받은 돈이 표에 나와요. [다음 경주로]를 누르거나 잠시 기다리면 넘어가요.\n${money}`.trim();
|
||||
}
|
||||
1073
apps/web/src/games/hot-streak/index.tsx
Normal file
1073
apps/web/src/games/hot-streak/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
112
apps/web/src/games/hot-streak/quick.tsx
Normal file
112
apps/web/src/games/hot-streak/quick.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
/** 핫스트릭 30초 규칙 요약 (docs/07 §5). */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MascotFace, RaceCard } from './art';
|
||||
|
||||
function Ticket({ x, y, color, title, a, b, picked = false }: { x: number; y: number; color: string; title: string; a: string; b: string; picked?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`}>
|
||||
<rect width={78} height={66} rx={8} fill={picked ? '#dbeafe' : '#fff'} stroke={picked ? '#2563eb' : '#6b7280'} strokeWidth={picked ? 3.5 : 2} />
|
||||
<rect width={78} height={18} rx={8} fill={color} />
|
||||
<text x={39} y={13} textAnchor="middle" fontSize={11} fontWeight={900} fill="#fff">
|
||||
{title}
|
||||
</text>
|
||||
<text x={39} y={38} textAnchor="middle" fontSize={11} fontWeight={800} fill="#111827">
|
||||
{a}
|
||||
</text>
|
||||
<text x={39} y={56} textAnchor="middle" fontSize={11} fontWeight={800} fill="#dc2626">
|
||||
{b}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function BetPic() {
|
||||
return (
|
||||
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
|
||||
<Ticket x={6} y={10} color="#2563eb" title="댕글 1단" a="안전 10/7/5" b="위험 15/5/2" picked />
|
||||
<Ticket x={92} y={10} color="#f97316" title="고블러 1단" a="안전 10/7/5" b="위험 15/5/2" />
|
||||
<Ticket x={178} y={10} color="#16a34a" title="YES 1단" a="맞히면 +10" b="+15 / −5" />
|
||||
<text x={130} y={106} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
|
||||
뱀 순서로 한 장씩, 안전 또는 위험
|
||||
</text>
|
||||
<text x={130} y={130} textAnchor="middle" fontSize={12} fill="#374151">
|
||||
사이드 질문: "실격이 나올까요?"
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function SecretPic() {
|
||||
return (
|
||||
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
|
||||
<g transform="translate(20 14)">
|
||||
<RaceCard base="D-F3" size={50} />
|
||||
</g>
|
||||
<g transform="translate(80 14)">
|
||||
<RaceCard base="G-FD" size={50} />
|
||||
</g>
|
||||
<path d="M140 50 Q170 30 196 54" stroke="#2563eb" strokeWidth={3} fill="none" strokeDasharray="5 4" />
|
||||
<g transform="translate(196 18)">
|
||||
<RaceCard faceDown size={50} />
|
||||
</g>
|
||||
<text x={130} y={118} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
|
||||
🤫 손패 1장을 경주 덱에 몰래
|
||||
</text>
|
||||
<text x={130} y={140} textAnchor="middle" fontSize={12} fill="#374151">
|
||||
누가 넣었는지는 끝까지 비밀
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function RacePic() {
|
||||
const cells = Array.from({ length: 6 }, (_, i) => i);
|
||||
return (
|
||||
<svg viewBox="0 0 260 150" width={250} height={144} aria-hidden>
|
||||
<rect x={4} y={22} width={252} height={84} rx={10} fill="#1f5132" />
|
||||
{cells.map((i) => (
|
||||
<rect key={i} x={10 + i * 36} y={30} width={32} height={32} rx={5} fill="#2d6a43" stroke="#4c8a5f" />
|
||||
))}
|
||||
{cells.map((i) => (
|
||||
<rect key={`b${i}`} x={10 + i * 36} y={66} width={32} height={32} rx={5} fill="#2d6a43" stroke="#4c8a5f" />
|
||||
))}
|
||||
<rect x={226} y={30} width={4} height={68} fill="#fff" />
|
||||
<g transform="translate(84 30) scale(0.32)">
|
||||
<MascotFace id="H" />
|
||||
</g>
|
||||
<g transform="translate(120 66) rotate(80 16 16) scale(0.32)">
|
||||
<MascotFace id="G" />
|
||||
</g>
|
||||
<text x={150} y={22} fontSize={16} fontWeight={900} fill="#dc2626">
|
||||
쾅!
|
||||
</text>
|
||||
<text x={130} y={126} textAnchor="middle" fontSize={14} fontWeight={800} fill="#111827">
|
||||
카드가 저절로 넘어가요. 구경하며 응원!
|
||||
</text>
|
||||
<text x={130} y={145} textAnchor="middle" fontSize={12} fill="#374151">
|
||||
셋이 들어오거나 실격하면 정산
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <BetPic />,
|
||||
alt: '댕글, 고블러 마스코트 티켓과 YES 티켓 중 댕글 티켓을 골라요',
|
||||
title: '티켓을 뽑아 걸어요',
|
||||
text: '뱀 순서로 티켓을 한 장씩 가져와요. 안전 면은 조금씩 확실하게, 위험 면은 1등이면 크게! 사이드 질문 YES·NO에도 걸 수 있어요.',
|
||||
},
|
||||
{
|
||||
pic: <SecretPic />,
|
||||
alt: '손패 카드 중 한 장을 뒷면 덱에 몰래 넣어요',
|
||||
title: '카드 한 장 몰래 넣기',
|
||||
text: '손패에서 카드 한 장을 경주 덱에 몰래 넣어요. 내가 건 마스코트를 밀어 주거나 다른 마스코트를 넘어뜨려요.',
|
||||
},
|
||||
{
|
||||
pic: <RacePic />,
|
||||
alt: '경주로에서 헐리가 달리고 고블러가 쾅 넘어졌어요',
|
||||
title: '구경하며 소리 질러요',
|
||||
text: '경주는 카드가 몇 초마다 넘어가며 저절로 진행돼요. 셋이 결승이나 실격이 되면 정산하고, 경주 세 번 뒤 돈이 많으면 이겨요.',
|
||||
},
|
||||
];
|
||||
405
apps/web/src/games/hot-streak/track.tsx
Normal file
405
apps/web/src/games/hot-streak/track.tsx
Normal file
@@ -0,0 +1,405 @@
|
||||
/**
|
||||
* 핫스트릭 경주로 (docs/games/hot-streak.md §9): PC는 가로(왼쪽 13번 칸 → 오른쪽 결승선·시상대), 휴대폰은 세로(위가 결승선).
|
||||
* The view already has the result of every card; `useReplay` draws the race record a beat behind, card by card:
|
||||
* the card turns over, the mascot hops space by space, then bumps / falls / 실격 / 결승 show up.
|
||||
*/
|
||||
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, useMotionHold } from '../../lib/motion';
|
||||
import { MascotFace } from './art';
|
||||
|
||||
export const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
// ---------------------------------------------------------------- geometry
|
||||
|
||||
export interface Geo {
|
||||
vertical: boolean;
|
||||
w: number;
|
||||
h: number;
|
||||
/** Cell box of (lane, space). */
|
||||
cell(lane: number, pos: number): { x: number; y: number; w: number; h: number };
|
||||
/** Podium slot box in the finish zone (1~4). */
|
||||
slot(place: number): { x: number; y: number; w: number; h: number };
|
||||
tok: number;
|
||||
/** Line between space p+1 and p (fold lines): from / to points. */
|
||||
between(p: number): [number, number, number, number];
|
||||
}
|
||||
|
||||
const H_LM = 30;
|
||||
const H_CW = 62;
|
||||
const H_LH = 58;
|
||||
const H_TM = 24;
|
||||
const H_FW = 118;
|
||||
export const WIDE: Geo = {
|
||||
vertical: false,
|
||||
w: H_LM + 13 * H_CW + H_FW,
|
||||
h: H_TM + 4 * H_LH + 6,
|
||||
cell: (lane, pos) => ({ x: H_LM + (13 - pos) * H_CW, y: H_TM + lane * H_LH, w: H_CW, h: H_LH }),
|
||||
slot: (place) => ({ x: H_LM + 13 * H_CW, y: H_TM + (place - 1) * H_LH, w: H_FW, h: H_LH }),
|
||||
tok: 46,
|
||||
between: (p) => {
|
||||
const x = H_LM + (13 - p) * H_CW;
|
||||
return [x, H_TM, x, H_TM + 4 * H_LH];
|
||||
},
|
||||
};
|
||||
|
||||
const V_LM = 4;
|
||||
const V_LW = 76;
|
||||
const V_CH = 34;
|
||||
const V_FH = 66;
|
||||
export const TALL: Geo = {
|
||||
vertical: true,
|
||||
w: V_LM * 2 + 4 * V_LW,
|
||||
h: V_FH + 13 * V_CH + 6,
|
||||
cell: (lane, pos) => ({ x: V_LM + lane * V_LW, y: V_FH + (pos - 1) * V_CH, w: V_LW, h: V_CH }),
|
||||
slot: (place) => ({ x: V_LM + (place - 1) * V_LW, y: 0, w: V_LW, h: V_FH - 4 }),
|
||||
tok: 30,
|
||||
between: (p) => {
|
||||
const y = V_FH + p * V_CH;
|
||||
return [V_LM, y, V_LM + 4 * V_LW, y];
|
||||
},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- replay
|
||||
|
||||
export interface Shown {
|
||||
racers: Racer[];
|
||||
trackEnd: number;
|
||||
/** Line on screen (card, text). */
|
||||
line: RaceLine | null;
|
||||
/** Index of the hop in the current walk (forces a re-render). */
|
||||
hop: number;
|
||||
}
|
||||
|
||||
interface Float {
|
||||
k: number;
|
||||
id: MascotId;
|
||||
text: string;
|
||||
cls: string;
|
||||
lane: number;
|
||||
pos: number;
|
||||
}
|
||||
|
||||
const START: Racer[] = MASCOT_IDS.map((id) => ({ id, lane: MASCOTS[id].lane, pos: 11, facing: 'fwd', down: false, status: 'racing' }));
|
||||
|
||||
const raceSound = {
|
||||
hop: (i: number) => tone(i % 2 ? 640 : 560, 35, 'triangle', 0.06),
|
||||
bump: () => {
|
||||
noise(110, 0.18, 0, 'lowpass', 600);
|
||||
tone(140, 160, 'square', 0.05);
|
||||
},
|
||||
down: () => tone(320, 220, 'sawtooth', 0.05, 0, { slideTo: 120 }),
|
||||
dq: () => [520, 390, 260].forEach((f, i) => tone(f, 120, 'square', 0.05, i * 90)),
|
||||
finish: () => [784, 988, 1318].forEach((f, i) => tone(f, 130, 'triangle', 0.1, i * 80)),
|
||||
fold: () => {
|
||||
noise(380, 0.12, 0, 'lowpass', 500);
|
||||
tone(110, 300, 'sine', 0.08);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Plays new race lines one after the other. A race already running when the board opens is shown as it is. When the
|
||||
* screen falls behind (빨리 보기, a slow phone) the next lines play faster. `busy` is true while lines are still queued.
|
||||
*/
|
||||
export function useReplay(r: HsRaceView | null) {
|
||||
const [shown, setShown] = useState<Shown>(() => ({ racers: r ? r.log.at(-1)?.racers ?? r.racers : START, trackEnd: r?.trackEnd ?? 13, line: r?.log.at(-1) ?? null, hop: 0 }));
|
||||
const [floats, setFloats] = useState<Float[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const q = useRef<RaceLine[]>([]);
|
||||
const st = useRef({ race: r?.no ?? 0, last: r?.log.at(-1)?.n ?? 0, playing: false, k: 0, dead: false });
|
||||
const timers = useRef(new Set<ReturnType<typeof setTimeout>>());
|
||||
const later = (fn: () => void, ms: number) => {
|
||||
const t = setTimeout(() => {
|
||||
timers.current.delete(t);
|
||||
if (!st.current.dead) fn();
|
||||
}, ms);
|
||||
timers.current.add(t);
|
||||
};
|
||||
useEffect(() => {
|
||||
const s = st.current;
|
||||
s.dead = false;
|
||||
return () => {
|
||||
s.dead = true;
|
||||
for (const t of timers.current) clearTimeout(t);
|
||||
timers.current.clear();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const pump = () => {
|
||||
const s = st.current;
|
||||
const line = q.current.shift();
|
||||
if (!line) {
|
||||
s.playing = false;
|
||||
setBusy(false);
|
||||
return;
|
||||
}
|
||||
s.playing = true;
|
||||
setBusy(true);
|
||||
const behind = q.current.length;
|
||||
const speed = behind > 4 ? 0.25 : behind > 1 ? 0.5 : 1;
|
||||
const T = (ms: number) => Math.max(10, Math.round(fxMs(ms) * speed));
|
||||
const finishLine = () => {
|
||||
setShown({ racers: line.racers, trackEnd: line.trackEnd, line, hop: 0 });
|
||||
for (const f of line.fx ?? []) {
|
||||
const x = line.racers.find((y) => y.id === f.id)!;
|
||||
const text = { bump: '쾅!', down: '쿵!', dq: '실격!', finish: `${f.place ?? ''}등!`, turn: '↩', up: '벌떡!' }[f.t];
|
||||
const k = ++s.k;
|
||||
setFloats((fl) => [...fl.slice(-6), { k, id: f.id, text, cls: f.t, lane: x.lane, pos: x.pos }]);
|
||||
later(() => setFloats((fl) => fl.filter((z) => z.k !== k)), fxMs(1300));
|
||||
}
|
||||
const t = new Set((line.fx ?? []).map((f) => f.t));
|
||||
if (t.has('dq')) raceSound.dq();
|
||||
else if (t.has('finish')) raceSound.finish();
|
||||
else if (t.has('bump')) raceSound.bump();
|
||||
else if (t.has('down')) raceSound.down();
|
||||
if (line.kind === 'fold') raceSound.fold();
|
||||
later(pump, T(line.kind === 'flip' ? 260 : 380));
|
||||
};
|
||||
if (reducedMotion()) {
|
||||
setShown({ racers: line.racers, trackEnd: line.trackEnd, line, hop: 0 });
|
||||
later(pump, behind ? 30 : 200);
|
||||
return;
|
||||
}
|
||||
if (line.kind === 'flip') sfx.cardFlip();
|
||||
else if (line.kind === 'shuffle' || line.kind === 'start') sfx.shuffle();
|
||||
const moves = line.mv ?? [];
|
||||
const steps = Math.max(0, ...moves.map((m) => m.path.length - 1));
|
||||
// The card shows first, then the walk.
|
||||
setShown((sh) => ({ ...sh, line }));
|
||||
const hopMs = T(150);
|
||||
const lead = T(line.kind === 'flip' ? 320 : 120);
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
later(() => {
|
||||
raceSound.hop(i);
|
||||
setShown((sh) => ({
|
||||
...sh,
|
||||
hop: i,
|
||||
racers: sh.racers.map((x) => {
|
||||
const m = moves.find((mv) => mv.id === x.id);
|
||||
if (!m) return x;
|
||||
const [lane, pos] = m.path[Math.min(i, m.path.length - 1)]!;
|
||||
return { ...x, lane, pos };
|
||||
}),
|
||||
}));
|
||||
}, lead + (i - 1) * hopMs);
|
||||
}
|
||||
later(finishLine, lead + steps * hopMs + (steps ? T(60) : 0));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const s = st.current;
|
||||
if (!r) {
|
||||
if (s.race !== 0) {
|
||||
s.race = 0;
|
||||
s.last = 0;
|
||||
q.current = [];
|
||||
setShown({ racers: START, trackEnd: 13, line: null, hop: 0 });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (r.no !== s.race) {
|
||||
s.race = r.no;
|
||||
s.last = 0;
|
||||
q.current = [];
|
||||
}
|
||||
const fresh = r.log.filter((l) => l.n > s.last);
|
||||
if (!fresh.length) return;
|
||||
s.last = fresh.at(-1)!.n;
|
||||
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 };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- drawing
|
||||
|
||||
const tokenLabel = (x: Racer) =>
|
||||
`${MASCOTS[x.id].name}: ${x.status === 'finished' ? '결승' : x.status === 'dq' ? '실격' : `레인 ${x.lane + 1}, ${x.pos}번 칸${x.down ? ', 넘어짐' : ''}${x.facing === 'back' ? ', 뒤돌아 있음' : ''}`}`;
|
||||
|
||||
/** Where each mascot stands now (finished / DQ ones on their podium slot). */
|
||||
function placeOf(g: Geo, x: Racer, all: Racer[], slots: Map<MascotId, number>, ended: boolean): { cx: number; cy: number; onPodium: boolean } {
|
||||
const slot = slots.get(x.id);
|
||||
if (slot && (x.status !== 'racing' || ended)) {
|
||||
const b = g.slot(slot);
|
||||
return { cx: b.x + (g.vertical ? b.w / 2 : 30), cy: b.y + b.h / 2 + (g.vertical ? 6 : 0), onPodium: true };
|
||||
}
|
||||
const lane = Math.max(-0.6, Math.min(3.6, x.lane));
|
||||
const pos = Math.max(0.4, Math.min(13.6, x.pos));
|
||||
const base = g.vertical
|
||||
? { x: V_LM + lane * V_LW + V_LW / 2, y: V_FH + (pos - 1) * V_CH + V_CH / 2 }
|
||||
: { x: H_LM + (13 - pos) * H_CW + H_CW / 2, y: H_TM + lane * H_LH + H_LH / 2 };
|
||||
// Two or more on one space: spread them a little.
|
||||
const mates = all.filter((y) => y.status === 'racing' && y.lane === x.lane && y.pos === x.pos);
|
||||
const i = mates.indexOf(x);
|
||||
const off = mates.length > 1 ? (i - (mates.length - 1) / 2) * (g.vertical ? 14 : 16) : 0;
|
||||
return { cx: base.x + (g.vertical ? off : 0), cy: base.y + (g.vertical ? 0 : off), onPodium: false };
|
||||
}
|
||||
|
||||
export function Track({
|
||||
g,
|
||||
shown,
|
||||
floats,
|
||||
final,
|
||||
stars,
|
||||
hurdles,
|
||||
label,
|
||||
}: {
|
||||
g: Geo;
|
||||
shown: Shown;
|
||||
floats: Float[];
|
||||
/** The race's places as the view has them (podium slots never change once taken). */
|
||||
final: { top: MascotId[]; bottom: MascotId[][]; over: boolean } | null;
|
||||
stars: number[];
|
||||
hurdles: number[];
|
||||
label: string;
|
||||
}) {
|
||||
const { racers, trackEnd } = shown;
|
||||
const slots = new Map<MascotId, number>();
|
||||
if (final) {
|
||||
final.top.forEach((m, i) => slots.set(m, i + 1));
|
||||
let low = 4;
|
||||
for (const grp of final.bottom) {
|
||||
for (let j = grp.length - 1; j >= 0; j--) slots.set(grp[j]!, low--);
|
||||
}
|
||||
}
|
||||
const ended = shown.line?.kind === 'end';
|
||||
const cells: ReactElement[] = [];
|
||||
for (let lane = 0; lane < 4; lane++) {
|
||||
for (let pos = 1; pos <= 13; pos++) {
|
||||
const b = g.cell(lane, pos);
|
||||
const stretch = pos <= 3;
|
||||
cells.push(
|
||||
<rect key={`c${lane}-${pos}`} x={b.x + 1} y={b.y + 1} width={b.w - 2} height={b.h - 2} rx={6} className={`hs-cell${stretch ? ' stretch' : ''}${pos === 11 ? ' start' : ''}`} />,
|
||||
);
|
||||
if (stars.includes(pos))
|
||||
cells.push(
|
||||
<text key={`s${lane}-${pos}`} x={b.x + b.w - (g.vertical ? 12 : 13)} y={b.y + (g.vertical ? 13 : 16)} className="hs-star" fontSize={g.vertical ? 12 : 15} textAnchor="middle">
|
||||
★
|
||||
</text>,
|
||||
);
|
||||
if (hurdles.includes(pos))
|
||||
cells.push(
|
||||
<path
|
||||
key={`h${lane}-${pos}`}
|
||||
d={g.vertical ? `M${b.x + 6} ${b.y + b.h - 5} v-9 h14 v9` : `M${b.x + 6} ${b.y + b.h - 5} v-12 h16 v12`}
|
||||
className="hs-hurdle"
|
||||
/>,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Space numbers (once per row/column).
|
||||
const nums: ReactElement[] = [];
|
||||
for (let pos = 1; pos <= 13; pos++) {
|
||||
const b = g.cell(0, pos);
|
||||
if (g.vertical) continue;
|
||||
nums.push(
|
||||
<text key={`n${pos}`} x={b.x + b.w / 2} y={H_TM - 7} className="hs-num" textAnchor="middle" fontSize={13}>
|
||||
{pos}
|
||||
</text>,
|
||||
);
|
||||
}
|
||||
const finish = g.slot(1);
|
||||
const zone = g.vertical ? { x: V_LM, y: 0, w: 4 * V_LW, h: V_FH - 4 } : { x: finish.x, y: H_TM, w: H_FW, h: 4 * H_LH };
|
||||
const folded = 13 - trackEnd;
|
||||
const foldBox = folded <= 0 ? null : g.vertical ? { x: V_LM, y: V_FH + trackEnd * V_CH, w: 4 * V_LW, h: folded * V_CH } : { x: H_LM, y: H_TM, w: folded * H_CW, h: 4 * H_LH };
|
||||
return (
|
||||
<svg viewBox={`0 0 ${g.w} ${g.h}`} className="hs-svg" role="img" aria-label={label}>
|
||||
<defs>
|
||||
<pattern id="hs-fold" width="16" height="16" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
|
||||
<rect width="16" height="16" fill="#facc15" />
|
||||
<rect width="8" height="16" fill="#eab308" />
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x={0} y={0} width={g.w} height={g.h} rx={14} className="hs-bg" />
|
||||
{/* lane colour stripes */}
|
||||
{MASCOT_IDS.map((m, lane) => {
|
||||
const a = g.cell(lane, 13);
|
||||
const b = g.cell(lane, 1);
|
||||
return g.vertical ? (
|
||||
<rect key={m} x={a.x + 2} y={b.y} width={4} height={a.y + a.h - b.y} fill={MASCOTS[m].color} opacity={0.7} rx={2} />
|
||||
) : (
|
||||
<rect key={m} x={a.x} y={a.y + 2} width={b.x + b.w - a.x} height={4} fill={MASCOTS[m].color} opacity={0.7} rx={2} />
|
||||
);
|
||||
})}
|
||||
{cells}
|
||||
{nums}
|
||||
{!g.vertical &&
|
||||
MASCOT_IDS.map((m, lane) => {
|
||||
const b = g.cell(lane, 13);
|
||||
return (
|
||||
<text key={`l${m}`} x={H_LM / 2} y={b.y + b.h / 2 + 5} textAnchor="middle" fontSize={13} fontWeight={800} fill={MASCOTS[m].color}>
|
||||
{lane + 1}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{[3, 7, 10].map((p) => {
|
||||
const [x1, y1, x2, y2] = g.between(p);
|
||||
return <line key={`f${p}`} x1={x1} y1={y1} x2={x2} y2={y2} className="hs-foldline" />;
|
||||
})}
|
||||
<rect x={zone.x + 2} y={zone.y + 2} width={zone.w - 4} height={zone.h - 4} rx={10} className="hs-zone" />
|
||||
{[1, 2, 3, 4].map((pl) => {
|
||||
const b = g.slot(pl);
|
||||
return (
|
||||
<text key={`p${pl}`} x={g.vertical ? b.x + b.w / 2 : b.x + b.w - 26} y={g.vertical ? b.y + 14 : b.y + b.h / 2 + 6} textAnchor="middle" className="hs-place" fontSize={g.vertical ? 12 : 16}>
|
||||
{pl}등
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
{/* finish line */}
|
||||
{g.vertical ? (
|
||||
<rect x={V_LM} y={V_FH - 4} width={4 * V_LW} height={4} className="hs-finish" />
|
||||
) : (
|
||||
<rect x={finish.x - 2} y={H_TM} width={5} height={4 * H_LH} className="hs-finish" />
|
||||
)}
|
||||
{foldBox && <rect x={foldBox.x} y={foldBox.y} width={foldBox.w} height={foldBox.h} fill="url(#hs-fold)" opacity={0.92} className="hs-folded" rx={6} />}
|
||||
{racers.map((x) => {
|
||||
const { cx, cy, onPodium } = placeOf(g, x, racers, slots, ended);
|
||||
const s = g.tok;
|
||||
const dq = x.status === 'dq';
|
||||
const turn = x.facing === 'back';
|
||||
return (
|
||||
<g key={x.id} className="hs-tok" style={{ transform: `translate(${cx}px, ${cy}px)` }} aria-label={tokenLabel(x)} role="img">
|
||||
<g className={`hs-body${x.down && !onPodium ? ' down' : ''}${dq ? ' dq' : ''}`}>
|
||||
<circle r={s / 2 + 3} className="hs-ring" style={{ stroke: MASCOTS[x.id].color }} />
|
||||
<g transform={`translate(${-s / 2} ${-s / 2}) scale(${s / 100})${turn && !onPodium ? ` translate(100 0) scale(-1 1)` : ''}`}>
|
||||
<MascotFace id={x.id} />
|
||||
</g>
|
||||
</g>
|
||||
{turn && !onPodium && !dq && (
|
||||
<text x={s / 2} y={-s / 2 + 6} className="hs-turn" fontSize={g.vertical ? 12 : 15} textAnchor="middle">
|
||||
↩
|
||||
</text>
|
||||
)}
|
||||
{dq && (
|
||||
<text x={0} y={5} className="hs-stamp" fontSize={g.vertical ? 11 : 14} textAnchor="middle">
|
||||
실격
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{floats.map((f) => {
|
||||
const x = racers.find((y) => y.id === f.id);
|
||||
if (!x) return null;
|
||||
const { cx, cy } = placeOf(g, { ...x, lane: f.lane, pos: f.pos }, racers, slots, ended);
|
||||
return (
|
||||
<text key={f.k} x={cx} y={cy - g.tok / 2 - 4} className={`hs-float ${f.cls}`} textAnchor="middle" fontSize={g.vertical ? 15 : 20}>
|
||||
{f.text}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** One sentence for screen readers about a race line. */
|
||||
export function lineSpeech(l: RaceLine): string {
|
||||
return [l.text, ...(l.notes ?? [])].join(' ');
|
||||
}
|
||||
|
||||
export const nameGa = (id: MascotId) => josa(MASCOTS[id].name, '이', '가');
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 장기 화면 (docs/games/janggi.md §9). */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { Arrangement, JanggiMove, JanggiOptions, JanggiView, Piece, PieceKind, Side, Sq } from '@bg/games/janggi';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
@@ -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' };
|
||||
@@ -168,14 +168,38 @@ const JANGGI_CSS = `
|
||||
@keyframes jg-check { 0% { opacity: 0; transform: scale(.5); } 30% { opacity: 1; transform: scale(1.22); } 55% { transform: scale(.95); } 78% { transform: scale(1.08); } 100% { opacity: 1; transform: scale(1); } }
|
||||
.jg-fade { animation: jg-fade .3s ease-out both; }
|
||||
@keyframes jg-fade { from { opacity: 0; } }
|
||||
.board-wrap.jg-side { flex-direction: row; align-items: center; justify-content: center; gap: 20px; }
|
||||
.jg-side > .jg-rows { flex: 0 1 320px; min-width: 0; }
|
||||
`;
|
||||
|
||||
/** PC play-area size (.game-main, px), null under 1100px where the page scrolls and rows stay under the board. */
|
||||
function useWideMain(ref: React.RefObject<HTMLElement | null>) {
|
||||
const [size, setSize] = useState<{ w: number; h: number } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const main = ref.current?.closest<HTMLElement>('.game-main');
|
||||
if (!main) return;
|
||||
const wide = matchMedia('(min-width: 1100px)');
|
||||
const update = () => setSize(wide.matches ? { w: main.clientWidth, h: main.clientHeight } : null);
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(main);
|
||||
wide.addEventListener('change', update);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
wide.removeEventListener('change', update);
|
||||
};
|
||||
}, [ref]);
|
||||
return size;
|
||||
}
|
||||
|
||||
function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiView>) {
|
||||
const flip = v.mySide === 'han';
|
||||
const toScreen = (q: Sq) => (flip ? { x: 8 - q.f, y: q.r } : { x: q.f, y: 9 - q.r });
|
||||
const fromScreen = (x: number, y: number): Sq => (flip ? { f: 8 - x, r: y } : { f: x, r: 9 - y });
|
||||
const myTurn = v.phase === 'playing' && v.mySide === v.turn;
|
||||
const [hangul, setHangul] = useHangulLabels();
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const main = useWideMain(wrapRef);
|
||||
const [selected, setSelected] = useState<number | null>(null);
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const [preview, setPreview] = useState<number | null>(null);
|
||||
@@ -183,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 });
|
||||
|
||||
@@ -221,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') {
|
||||
@@ -245,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));
|
||||
@@ -337,15 +371,29 @@ 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;
|
||||
const setupMaxW = v.phase === 'setup' ? 'min(100%, calc((100vh - 400px) * 0.9))' : 'min(100%, calc((100vh - 250px) * 0.9))';
|
||||
// PC: the board fills the play-area height. The rows (alerts, setup picker, hangul toggle) go beside it when that
|
||||
// gives a bigger board than stacking them under it (which needs about `under` px of height).
|
||||
const ar = (8 + 2 * pad) / (9 + 2 * pad);
|
||||
const under = v.phase === 'setup' ? 320 : 170;
|
||||
const besideW = main ? Math.floor(Math.min(main.w - 320, main.h * ar)) : 0;
|
||||
const stackW = main ? Math.floor(Math.min(main.w, (main.h - under) * ar)) : 0;
|
||||
const side = !!main && besideW > stackW;
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: setupMaxW, minWidth: 'min(100%, 300px)' }}>
|
||||
<div
|
||||
ref={wrapRef}
|
||||
className={`board-wrap stack${side ? ' jg-side' : ''}`}
|
||||
style={{ gap: 10, maxWidth: side ? 'none' : main ? `min(100%, ${stackW}px)` : setupMaxW, minWidth: 'min(100%, 300px)' }}
|
||||
>
|
||||
<style>{BOARD_MOTION_CSS + JANGGI_CSS}</style>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<div style={{ position: 'relative', ...(side && { flex: '0 0 auto', width: besideW }) }}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${8 + 2 * pad} ${9 + 2 * pad}`}
|
||||
@@ -495,46 +543,48 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{v.phase === 'playing' && v.inCheck && (
|
||||
<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]} 장군!`}
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'playing' && v.bikjang && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.bikjang.calledBy === v.mySide
|
||||
? '빅장을 불렀어요. 상대가 막지 못하면 점수로 판정해요.'
|
||||
: v.mySide
|
||||
? '빅장이에요! 궁 사이를 막거나 궁을 옆으로 옮기지 않으면 점수로 판정해요.'
|
||||
: `${SIDE_KO[v.bikjang.calledBy]} 빅장!`}
|
||||
</div>
|
||||
)}
|
||||
{myTurn && v.repeatWarning && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.rules.repetition === 'forbid'
|
||||
? '같은 국면이 3번 나왔어요. 한 번 더 반복하는 수는 둘 수 없어요.'
|
||||
: v.rules.repetition === 'lose'
|
||||
? '같은 국면이 3번 나왔어요. 한 번 더 반복하면 실격패예요!'
|
||||
: '같은 국면이 3번 나왔어요. 한 번 더 반복하면 점수로 판정해요.'}
|
||||
</div>
|
||||
)}
|
||||
{preview !== null && selected !== null && myTurn && (
|
||||
<div className="row" style={{ justifyContent: 'center' }}>
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={pending} onClick={() => doMove(selected, preview)}>
|
||||
{`${v.board[selected] ? pieceName(v.board[selected]!) : ''} ${sqCode(fromKey(preview))}로 두기`}
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setPreview(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'setup' && (
|
||||
<SetupPicker view={v} act={act} pending={pending} tapConfirm={tapConfirm} mustChoose={mustChoose} onHover={setSetupHover} />
|
||||
)}
|
||||
<label className="row small muted" style={{ justifyContent: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={hangul} onChange={(e) => setHangul(e.target.checked)} />
|
||||
기물에 한글 이름 같이 보기
|
||||
</label>
|
||||
<div className="stack jg-rows" style={{ gap: 10 }}>
|
||||
{v.phase === 'playing' && checkShown && (
|
||||
<div className="card" role="alert" style={{ padding: '8px 12px', background: 'var(--danger-soft)', color: 'var(--danger)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{checkShown === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[checkShown]} 장군!`}
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'playing' && bikjangShown && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{bikjangShown === v.mySide
|
||||
? '빅장을 불렀어요. 상대가 막지 못하면 점수로 판정해요.'
|
||||
: v.mySide
|
||||
? '빅장이에요! 궁 사이를 막거나 궁을 옆으로 옮기지 않으면 점수로 판정해요.'
|
||||
: `${SIDE_KO[bikjangShown]} 빅장!`}
|
||||
</div>
|
||||
)}
|
||||
{myTurn && v.repeatWarning && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.rules.repetition === 'forbid'
|
||||
? '같은 국면이 3번 나왔어요. 한 번 더 반복하는 수는 둘 수 없어요.'
|
||||
: v.rules.repetition === 'lose'
|
||||
? '같은 국면이 3번 나왔어요. 한 번 더 반복하면 실격패예요!'
|
||||
: '같은 국면이 3번 나왔어요. 한 번 더 반복하면 점수로 판정해요.'}
|
||||
</div>
|
||||
)}
|
||||
{preview !== null && selected !== null && myTurn && (
|
||||
<div className="row" style={{ justifyContent: 'center' }}>
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={pending} onClick={() => doMove(selected, preview)}>
|
||||
{`${v.board[selected] ? pieceName(v.board[selected]!) : ''} ${sqCode(fromKey(preview))}로 두기`}
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setPreview(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'setup' && (
|
||||
<SetupPicker view={v} act={act} pending={pending} tapConfirm={tapConfirm} mustChoose={mustChoose} onHover={setSetupHover} />
|
||||
)}
|
||||
<label className="row small muted" style={{ justifyContent: 'center', gap: 6, cursor: 'pointer' }}>
|
||||
<input type="checkbox" checked={hangul} onChange={(e) => setHangul(e.target.checked)} />
|
||||
기물에 한글 이름 같이 보기
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -727,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)}`}>
|
||||
@@ -789,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 }}>
|
||||
@@ -805,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';
|
||||
@@ -174,6 +174,30 @@ button.lv-casino:hover { border-color: var(--primary); }
|
||||
@media (max-width: 1099px) {
|
||||
.lv-lower { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
/* PC: fill the play column; casinos take the spare height and everything on the table scales with --lv-u (1px at ~1100x760). */
|
||||
@media (min-width: 1100px) {
|
||||
.lv-wrap { --lv-u: clamp(1px, min(var(--play-w) / 1100, var(--play-h) / 760), 1.7px); max-width: none; flex: 1 1 auto; min-height: 0; justify-content: center; gap: calc(var(--lv-u) * 10); }
|
||||
.lv-help span { font-size: calc(var(--lv-u) * 16); }
|
||||
.lv-casinos { flex: 1 1 auto; min-height: 0; gap: calc(var(--lv-u) * 10); }
|
||||
.lv-casino { min-height: 196px; padding: calc(var(--lv-u) * 10); gap: calc(var(--lv-u) * 8); }
|
||||
.lv-ctop .lv-die { width: calc(var(--lv-u) * 30); height: calc(var(--lv-u) * 30); }
|
||||
.lv-cnum { font-size: calc(var(--lv-u) * 26); }
|
||||
.lv-cname { font-size: calc(var(--lv-u) * 13); }
|
||||
/* Bills stack down the casino as full-width notes, so the tall casinos are not empty. */
|
||||
.lv-casinos .lv-bills { flex-direction: column; flex-wrap: nowrap; gap: calc(var(--lv-u) * 6); }
|
||||
.lv-casinos .lv-bill { width: 100%; height: calc(var(--lv-u) * 40); font-size: calc(var(--lv-u) * 22); border-radius: calc(var(--lv-u) * 7); }
|
||||
.lv-casinos .lv-bill::before { font-size: calc(var(--lv-u) * 11); left: calc(var(--lv-u) * 6); top: 50%; transform: translateY(-50%); }
|
||||
.lv-stacks { gap: calc(var(--lv-u) * 5); }
|
||||
.lv-stack { font-size: calc(var(--lv-u) * 14); }
|
||||
.lv-pips { gap: calc(var(--lv-u) * 3); }
|
||||
.lv-casinos .lv-dot { width: calc(var(--lv-u) * 19); height: calc(var(--lv-u) * 19); border-radius: calc(var(--lv-u) * 4); }
|
||||
.lv-tag { font-size: calc(var(--lv-u) * 13); }
|
||||
.lv-group { min-width: calc(var(--lv-u) * 100); padding: calc(var(--lv-u) * 7) calc(var(--lv-u) * 12); }
|
||||
.lv-group b { font-size: calc(var(--lv-u) * 19); }
|
||||
.lv-tray .lv-die { width: calc(var(--lv-u) * 32); height: calc(var(--lv-u) * 32); }
|
||||
.lv-tray .lv-die.lg { width: calc(var(--lv-u) * 46); height: calc(var(--lv-u) * 46); }
|
||||
.lv-roll { min-height: calc(var(--lv-u) * 64); font-size: calc(var(--lv-u) * 19); }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.lv-casinos { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
|
||||
.lv-casino { min-height: 132px; padding: 6px; gap: 4px; }
|
||||
@@ -285,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(() => {
|
||||
@@ -363,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]);
|
||||
}
|
||||
@@ -443,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>
|
||||
)}
|
||||
@@ -735,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 (
|
||||
<>
|
||||
@@ -768,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>
|
||||
);
|
||||
@@ -789,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 ?? []} />
|
||||
@@ -819,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(',');
|
||||
|
||||
@@ -45,7 +45,7 @@ export function helpNow(v: LiarView, me: string | null, players: Record<string,
|
||||
return `${topic} 내 차례예요! 오른쪽 칸에 한 문장(80자까지)으로 설명하고 [말하기]를 눌러요.\n${tip} ${unl ? '시간 제한은 없어요.' : '시간이 지나면 넘어가요.'}`;
|
||||
}
|
||||
const round = v.rounds > 1 ? ` ${ph.round}/${v.rounds}바퀴예요${ph.round === 2 ? '(두 번째 바퀴는 거꾸로 돌아요)' : ''}.` : '';
|
||||
return `${topic} ${ph.speaker ? josa(n(ph.speaker), ['이', '가']) : '다른 사람이'} 설명하는 중이에요.${round}\n설명 기록을 잘 보고 어색한 사람을 기억해 둬요. ${mine}`;
|
||||
return `${topic} ${ph.speaker ? josa(n(ph.speaker), ['이', '가']) : '다른 사람이'} 설명하는 중이에요.${round}\n설명 기록을 잘 보고 어색한 사람을 기억해 둬요. [토론 채팅]은 지금도 쓸 수 있어요. ${mine}`;
|
||||
}
|
||||
case 'discussion':
|
||||
return `${topic} 자유 토론 시간이에요. [토론 채팅]으로 누가 라이어 같은지 이야기해요. 제시어는 직접 말할 수 없어요.\n${unl ? '토론 시간은 무제한이에요. ' : ''}다 이야기했으면 [토론 끝내기]를 눌러요. 모두 누르면 바로 투표로 넘어가요(${ph.readyCount}/${ph.readyNeeded}).`;
|
||||
|
||||
@@ -15,14 +15,42 @@ import { haptic, sfx, sounds, tone, useChatSound } from '../../lib/feedback';
|
||||
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useTypingSignal } from '../../lib/chat-input';
|
||||
import { keepFocus, useTypingSignal } from '../../lib/chat-input';
|
||||
import { useRoom } from '../../net/socket';
|
||||
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'];
|
||||
|
||||
// ---------------------------------------------------------------- topics (admins may add or delete some)
|
||||
|
||||
type TopicChoice = { id: string; ko: string };
|
||||
/** The topics new games can use; the code's list until the server answers. */
|
||||
let topicChoices: TopicChoice[] = TOPIC_IDS.map((id) => ({ id, ko: TOPIC_KO[id] }));
|
||||
let topicsLoad: Promise<TopicChoice[]> | null = null;
|
||||
function loadTopics(): Promise<TopicChoice[]> {
|
||||
topicsLoad ??= fetch('/api/liar/topics', { credentials: 'same-origin' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<{ topics: TopicChoice[] }>) : Promise.reject(new Error(String(r.status)))))
|
||||
.then((d) => (topicChoices = d.topics))
|
||||
.catch(() => ((topicsLoad = null), topicChoices));
|
||||
return topicsLoad;
|
||||
}
|
||||
const topicName = (id: string) => topicChoices.find((t) => t.id === id)?.ko ?? (TOPIC_KO as Record<string, string>)[id] ?? '관리자가 고른 주제';
|
||||
function useTopicChoices(): TopicChoice[] {
|
||||
const [list, setList] = useState(topicChoices);
|
||||
useEffect(() => {
|
||||
let on = true;
|
||||
void loadTopics().then((x) => on && setList(x));
|
||||
return () => {
|
||||
on = false;
|
||||
};
|
||||
}, []);
|
||||
return list;
|
||||
}
|
||||
|
||||
const PHASE_KO: Record<Kind, string> = {
|
||||
reveal: '제시어 확인',
|
||||
describe: '한 사람씩 설명',
|
||||
@@ -41,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;
|
||||
@@ -78,7 +115,7 @@ const CSS = `
|
||||
.lg-bar .tr { height: 14px; border-radius: 7px; background: var(--surface-2); overflow: hidden; }
|
||||
.lg-bar .tr i { display: block; height: 100%; background: #8b5cf6; border-radius: 7px; animation: lg-grow .7s ease-out; transform-origin: left; }
|
||||
.lg-bar[data-top='true'] .tr i { background: #dc2626; }
|
||||
.lg-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: 236px minmax(0, 1fr) 290px; grid-template-areas: 'players talk actions'; }
|
||||
.lg-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: clamp(236px, 17%, 340px) minmax(0, 1fr) clamp(290px, 20%, 400px); grid-template-areas: 'players talk actions'; }
|
||||
.lg-col { min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 8px; }
|
||||
.lg-players { grid-area: players; }
|
||||
.lg-talk { grid-area: talk; }
|
||||
@@ -116,11 +153,12 @@ button.lg-tile { cursor: pointer; }
|
||||
.lg-form { display: flex; gap: 6px; padding: 8px; border-top: 1px solid var(--border); flex-wrap: nowrap; }
|
||||
.lg-form .input { flex: 1; min-height: 44px; min-width: 0; }
|
||||
.lg-actions .lg-form { padding: 0; border: 0; }
|
||||
.lg-chat .bot-activity { padding: 4px 10px 0; }
|
||||
.lg-why { padding: 8px 10px; border-top: 1px solid var(--border); font-size: .88rem; color: var(--text-sub); font-weight: 600; margin: 0; }
|
||||
.lg-big { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.lg-big .btn { flex: 1 1 auto; min-height: 52px; }
|
||||
.lg-prompt { margin: 0; font-weight: 800; font-size: 1.02rem; }
|
||||
.lg-choices { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 6px; }
|
||||
.lg-choices { display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 6px; max-height: min(420px, 50vh); overflow-y: auto; }
|
||||
.lg-choice { min-height: 44px; border-radius: 10px; border: 2px solid var(--border); background: var(--surface-2); color: var(--text); font: inherit; font-weight: 700; cursor: pointer; }
|
||||
.lg-choice:hover { border-color: var(--primary); }
|
||||
.lg-final { border: 3px solid #16a34a; }
|
||||
@@ -267,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">
|
||||
@@ -327,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>
|
||||
@@ -352,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>}
|
||||
</>
|
||||
);
|
||||
@@ -360,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)
|
||||
@@ -423,19 +464,21 @@ 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));
|
||||
const talk = v.phase.kind === 'discussion' || v.phase.kind === 'vote';
|
||||
const canWrite = !!v.my?.canChat && talk;
|
||||
const canWrite = !!v.my?.canChat;
|
||||
const typing = useTypingSignal('game', canWrite);
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? '');
|
||||
// Who is typing sits right above the input, inside the chat (not on the status row: `typingInChat`).
|
||||
const room = useRoom((s) => s.room);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : (v.my.chatWhy ?? '');
|
||||
return (
|
||||
<section className="lg-box lg-chat" aria-label="토론 채팅">
|
||||
<h2>💬 토론 채팅</h2>
|
||||
@@ -453,6 +496,7 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
{room && <BotActivity room={room} only="typing" ch="game" hideBots={v.phase.kind === 'describe' && v.phase.speaker ? [v.phase.speaker] : undefined} />}
|
||||
{canWrite ? (
|
||||
<form
|
||||
className="lg-form"
|
||||
@@ -464,9 +508,11 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="input"
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
@@ -475,11 +521,13 @@ function ChatBox({ v, players, me, act }: { v: LiarView; players: Record<string,
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
maxLength={200}
|
||||
placeholder="누가 라이어일까요?"
|
||||
placeholder={v.my?.canDescribe ? '여기는 채팅이에요. 설명은 [말하기] 칸에 써 주세요' : '누가 라이어일까요?'}
|
||||
aria-label="토론 채팅 메시지"
|
||||
enterKeyHint="send"
|
||||
/>
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
<button className="btn btn-primary btn-sm" {...keepFocus}>
|
||||
보내기
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
why && <p className="lg-why">{why}</p>
|
||||
@@ -501,7 +549,7 @@ function DescribeForm({ act, pending }: { act: (a: unknown) => void; pending: bo
|
||||
e.preventDefault();
|
||||
const t = text.trim();
|
||||
if (!t) return;
|
||||
act({ type: 'chat', text: t.slice(0, 80) });
|
||||
act({ type: 'describe', text: t.slice(0, 80) });
|
||||
}}
|
||||
>
|
||||
<input ref={ref} className="input" value={text} onChange={(e) => setText(e.target.value)} maxLength={80} placeholder="예: 여름이면 생각나요" aria-label="내 설명 (한 문장)" enterKeyHint="send" />
|
||||
@@ -542,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>;
|
||||
@@ -630,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>
|
||||
);
|
||||
@@ -652,7 +703,7 @@ function FinalReveal({ v, players }: { v: LiarView; players: Record<string, Publ
|
||||
<h2>🏆 {f.winner === 'liar' ? '라이어 승리' : '시민 승리'}</h2>
|
||||
<span>{REASON_KO[f.reason]}.</span>
|
||||
<span>
|
||||
제시어 <span className="word">{f.word}</span> · 주제 {TOPIC_KO[f.topic]}
|
||||
제시어 <span className="word">{f.word}</span> · 주제 {f.topicKo ?? topicName(f.topic)}
|
||||
{f.liarWord ? ` · 라이어가 받은 단어: ${f.liarWord}` : ''}
|
||||
{f.guess !== null ? ` · 라이어의 답: "${f.guess}"` : ''}
|
||||
</span>
|
||||
@@ -706,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;
|
||||
@@ -767,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();
|
||||
@@ -778,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;
|
||||
@@ -800,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">
|
||||
@@ -849,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>
|
||||
@@ -944,13 +1009,16 @@ const secs = <T extends number>(...v: T[]): [T | null, string][] => [...v.map((x
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
const topics = useTopicChoices();
|
||||
// A topic an admin deleted plays as 무작위 (shown as such so the host isn't left with a hidden choice).
|
||||
const topic = o.topic === 'random' || topics.some((t) => t.id === o.topic) ? o.topic : 'random';
|
||||
const set = (patch: Partial<LiarOptions>) => onChange({ ...o, ...patch });
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<Field label="주제">
|
||||
<Seg<LiarOptions['topic']> label="주제" value={o.topic} options={[['random', '무작위'], ...TOPIC_IDS.map((t): [LiarOptions['topic'], string] => [t, TOPIC_KO[t]])]} onChange={(topic) => set({ topic })} />
|
||||
<Seg<string> label="주제" value={topic} options={[['random', '무작위'], ...topics.map((t): [string, string] => [t.id, t.ko])]} onChange={(next) => set({ topic: next })} />
|
||||
</Field>
|
||||
<Field label="바보 모드" help="켜면 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.">
|
||||
<Field label="바보 모드" help="켜면 라이어도 제시어와 비슷한 다른 단어(같은 묶음)를 받고, 자기가 라이어인지 몰라요.">
|
||||
<Seg label="바보 모드" value={o.foolMode} options={onOff} onChange={(foolMode) => set({ foolMode })} />
|
||||
</Field>
|
||||
<Field label="설명 바퀴 수" help="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
|
||||
@@ -1005,7 +1073,8 @@ function Options({ value: o, onChange }: OptionsProps<LiarOptions>) {
|
||||
}
|
||||
|
||||
function optionsSummary(o: LiarOptions): string {
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${TOPIC_KO[o.topic]}`];
|
||||
void loadTopics();
|
||||
const parts = [o.topic === 'random' ? '주제 무작위' : `주제 ${topicName(o.topic)}`];
|
||||
if (o.foolMode) parts.push('바보 모드');
|
||||
parts.push(o.rounds === 2 ? '두 바퀴' : '한 바퀴', o.describeSeconds === null ? '설명 무제한' : `설명 ${o.describeSeconds}초`, o.discussionSeconds === null ? '토론 무제한' : `토론 ${o.discussionSeconds}초`, o.guessMode === 'choice' ? '정답은 목록에서' : '정답은 직접 적기');
|
||||
return parts.join(' · ');
|
||||
@@ -1024,10 +1093,11 @@ function Rules() {
|
||||
</p>
|
||||
<ul className="small" style={{ margin: 0, paddingLeft: 18 }}>
|
||||
<li>제시어를 직접 말하면 안 돼요(띄어쓰기를 무시하고 막아요). 설명 차례에 시간이 지나면 넘어가요.</li>
|
||||
<li>토론 채팅은 게임 내내 열려 있어요. 설명하는 중에도 언제든 이야기할 수 있어요.</li>
|
||||
<li>투표는 나를 뺀 한 명을 골라요. 동점이면 동점인 사람끼리 한 번 더 투표하고, 또 동점이면 라이어가 이겨요.</li>
|
||||
<li>라이어가 아닌 사람이 지목되면 라이어 승리. 라이어가 지목되면 제시어를 한 번 맞힐 수 있어요(띄어쓰기·대소문자 무시). 맞히면 라이어, 틀리면 시민 승리예요.</li>
|
||||
<li>점수: 시민이 이기면 시민마다 1점, 라이어가 이기면 라이어 2점.</li>
|
||||
<li>바보 모드: 라이어도 같은 주제의 다른 단어를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
<li>바보 모드: 라이어도 제시어와 비슷한 다른 단어(같은 주제, 같은 묶음)를 받고, 자기가 라이어인지 몰라요.</li>
|
||||
<li>시간 무제한: 설명·토론·투표·정답 맞히기 시간을 무제한으로 할 수 있어요. 그 단계는 할 일을 다 마칠 때까지 기다려요.</li>
|
||||
</ul>
|
||||
<p className="small muted">내 제시어는 "내 제시어" 카드를 꾹 누르고 있을 때만 보여요. 게임 중에는 방 채팅 대신 게임 화면의 채팅을 써요.</p>
|
||||
@@ -1046,6 +1116,7 @@ const ui: GameUI<LiarView, LiarOptions> = {
|
||||
quickStart,
|
||||
helpNow,
|
||||
ownChat: true,
|
||||
typingInChat: true,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
|
||||
@@ -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';
|
||||
@@ -15,11 +15,11 @@ import { haptic, noise, sfx, sounds, tone, useChatSound } from '../../lib/feedba
|
||||
import { useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useTypingSignal } from '../../lib/chat-input';
|
||||
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)
|
||||
|
||||
@@ -114,7 +114,7 @@ const CSS = `
|
||||
.mf-bar .tr { height: 14px; border-radius: 7px; background: var(--surface-2); overflow: hidden; }
|
||||
.mf-bar .tr i { display: block; height: 100%; background: #f97316; border-radius: 7px; animation: mf-grow .7s ease-out; transform-origin: left; }
|
||||
.mf-bar[data-top='true'] .tr i { background: #dc2626; }
|
||||
.mf-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: 236px minmax(0, 1fr) 280px; grid-template-areas: 'players chat actions'; }
|
||||
.mf-grid { flex: 1; min-height: 0; display: grid; gap: 10px; grid-template-columns: clamp(236px, 17%, 340px) minmax(0, 1fr) clamp(280px, 20%, 400px); grid-template-areas: 'players chat actions'; }
|
||||
.mf-col { min-height: 0; overflow: auto; display: flex; flex-direction: column; gap: 8px; }
|
||||
.mf-players { grid-area: players; }
|
||||
.mf-chatwrap { grid-area: chat; }
|
||||
@@ -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>}
|
||||
@@ -485,6 +488,7 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
const canWrite = !!ch?.canWrite;
|
||||
// "입력 중" only from the public 전체 chat (night channels stay secret).
|
||||
const typing = useTypingSignal('game', canWrite && cur === 'day');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const why = ch ? ch.why : me ? '이 채팅은 읽기만 할 수 있어요.' : '관전 중에는 채팅을 쓸 수 없어요.';
|
||||
const onTabKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
@@ -542,9 +546,11 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="input"
|
||||
value={text}
|
||||
onChange={(e) => {
|
||||
@@ -557,7 +563,9 @@ function ChatBox({ v, players, me, act }: { v: MafiaView; players: Record<string
|
||||
aria-label={`${CHANNEL_KO[cur]} 채팅 메시지`}
|
||||
enterKeyHint="send"
|
||||
/>
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
<button className="btn btn-primary btn-sm" {...keepFocus}>
|
||||
보내기
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="mf-why">{why}</p>
|
||||
@@ -580,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>;
|
||||
@@ -715,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>
|
||||
@@ -787,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;
|
||||
@@ -823,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) => {
|
||||
@@ -851,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;
|
||||
@@ -875,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));
|
||||
@@ -902,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">
|
||||
@@ -917,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">
|
||||
@@ -955,6 +997,7 @@ function composition(setup: MafiaView['setup']): string {
|
||||
}
|
||||
|
||||
function MafiaSide({ view: v, players }: BoardProps<MafiaView>) {
|
||||
const events = useShownEvents(v);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -965,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'];
|
||||
|
||||
@@ -314,6 +314,25 @@ button.ma-card:hover:not(:disabled) { border-color: var(--primary); transform: t
|
||||
.ma-card small { font-size: .78rem; }
|
||||
.ma-legend { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
/* PC: fill the play column. The race board is as big as the column height allows and the log + racer list sit beside it
|
||||
when there is room (otherwise they wrap below as before). Without a board (draft) the panel fills the column. */
|
||||
@media (min-width: 1100px) {
|
||||
.ma-wrap { max-width: none; flex-direction: row; flex-wrap: wrap; justify-content: center; align-items: flex-start; align-content: flex-start; }
|
||||
.ma-wrap > .ma-track { width: min(100%, calc((var(--play-h) - 86px) * ${(BW / WIDE.bh).toFixed(3)})); }
|
||||
.ma-box { max-width: 100%; }
|
||||
.ma-wrap > .ma-lower { flex: 1 1 340px; width: auto; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
|
||||
.ma-die3d { --ds: clamp(64px, calc(var(--play-h) * .07), 96px); }
|
||||
.ma-wrap:not(:has(> .ma-track)) { flex: 1 1 auto; min-height: 0; flex-direction: column; flex-wrap: nowrap; align-items: stretch; }
|
||||
.ma-wrap:not(:has(> .ma-track)) > .ma-panel { flex: 1 1 auto; min-height: 0; }
|
||||
/* Rows grow up to a third of the column but share the height when there are many cards (5 players: 10 in the draft). */
|
||||
.ma-panel > .ma-cards { flex: 1 1 auto; min-height: 0; align-content: center; justify-content: center; gap: 14px;
|
||||
grid-template-columns: repeat(auto-fit, minmax(clamp(190px, calc(var(--play-w) * .19), 360px), clamp(190px, calc(var(--play-w) * .22), 360px)));
|
||||
grid-auto-rows: minmax(auto, clamp(104px, calc(var(--play-h) * .32), 380px)); }
|
||||
.ma-panel > .ma-cards .ma-card { padding: clamp(10px, calc(var(--play-h) * .02), 24px); gap: 10px; }
|
||||
.ma-panel > .ma-cards .ma-card .em { font-size: clamp(1.6rem, calc(var(--play-h) * .06), 4rem); }
|
||||
.ma-panel > .ma-cards .ma-card b { font-size: clamp(1.05rem, calc(var(--play-h) * .022), 1.6rem); }
|
||||
.ma-panel > .ma-cards .ma-card small { font-size: clamp(.875rem, calc(var(--play-h) * .016), 1.2rem); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ma-tok { transition: none; }
|
||||
.ma-hop, .ma-fly, .ma-trip-anim, .ma-ring, .ma-trail, .ma-float, .ma-conf, .ma-ticker div, .ma-die3d.rolling .ma-cube, .ma-die3d.rolling .ma-die-shadow { animation: none; }
|
||||
@@ -673,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 };
|
||||
}
|
||||
|
||||
@@ -1000,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 (
|
||||
@@ -1014,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>
|
||||
))}
|
||||
@@ -1040,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>
|
||||
@@ -1136,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;
|
||||
@@ -1159,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}
|
||||
@@ -1224,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(() => {
|
||||
@@ -1263,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>
|
||||
@@ -1288,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>
|
||||
@@ -1313,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) {
|
||||
@@ -158,7 +159,7 @@ function Bump({ value, children }: { value: number; children?: ReactNode }) {
|
||||
|
||||
const CSS = `
|
||||
.game-main:has(> .mj) { justify-content: flex-start; }
|
||||
.mj { position: relative; width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 8px; align-self: center; }
|
||||
.mj { position: relative; width: 100%; display: flex; flex-direction: column; gap: 8px; align-self: center; }
|
||||
.mj.wide { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-areas: 'table side' 'me me'; align-items: start; gap: 8px 12px; }
|
||||
.mj.wide .mj-opps { grid-area: side; flex-direction: column; flex-wrap: nowrap; }
|
||||
.mj.wide .mj-seat { max-width: none; flex: none; }
|
||||
@@ -443,7 +444,7 @@ const ROT = [0, -90, 180, 90];
|
||||
function Table({ v, players, width, callout, seen }: { v: MahjongView; players: Record<string, PublicUser>; width: number; callout: ReactNode; seen: Seen | null }) {
|
||||
// Pond: 6 tiles per row (+ room for one sideways riichi tile) × 4 rows. Table = H + W + H.
|
||||
// Total width ≈ 2H + W + padding/border = 17·tw + 37.
|
||||
const tw = Math.max(14, Math.min(30, Math.floor((width - 37) / 17)));
|
||||
const tw = Math.max(14, Math.min(64, Math.floor((width - 37) / 17)));
|
||||
const th = Math.round((tw * 4) / 3);
|
||||
const W = 5 * (tw + 1) + th + 2;
|
||||
const H = 4 * (th + 1) + 2;
|
||||
@@ -560,7 +561,7 @@ function MyArea({
|
||||
const beginner = my.prefs.beginner && v.options.beginnerMode;
|
||||
const phone = width > 0 && width < 600;
|
||||
const meldW = phone ? 18 : 26;
|
||||
const tw = width > 0 ? Math.max(20, Math.min(phone ? 40 : 48, Math.floor((width - 14 - n) / n))) : 40;
|
||||
const tw = width > 0 ? Math.max(20, Math.min(phone ? 40 : 60, Math.floor((width - 14 - n) / n))) : 40;
|
||||
|
||||
const send = (code: string) => {
|
||||
if (pending) return;
|
||||
@@ -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 && (
|
||||
@@ -1153,20 +1154,23 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const phone = width > 0 && width < 600;
|
||||
// PC: table on the left sized to the screen height, other players on the right, my hand below.
|
||||
const wide = width >= 900;
|
||||
const reserve = v.my ? 290 : 20;
|
||||
const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560, 600)) : width || 360;
|
||||
const showTable = v.phase === 'playing' || (v.phase === 'handResult' && !wide);
|
||||
const reserve = v.my ? 300 : 20;
|
||||
const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560)) : width || 360;
|
||||
// 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>
|
||||
<ul className="mj-opps" aria-label="다른 사람">
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.seat} v={v} s={s} players={players} me={me} deadline={deadline} w={phone ? 13 : 18} seen={seen} />
|
||||
<SeatChip key={s.seat} v={v} s={s} players={players} me={me} deadline={deadline} w={phone ? 13 : wide ? 24 : 18} seen={seen} />
|
||||
))}
|
||||
</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];
|
||||
|
||||
@@ -166,6 +166,15 @@ const CSS = `
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.mb-cell.pick .mb-pick, .mb-trail, .mb-hop, .mb-die.rolling, .mb-card, .mb-pop, .mb-fly, .mb-ring { animation: none; }
|
||||
}
|
||||
/* PC: the square board is as large as the play column allows; the centre (dice, prompt, title) grows with it. */
|
||||
@media (min-width: 1100px) {
|
||||
.mb-box { max-width: min(100%, var(--play-h)); }
|
||||
.mb-title { font-size: clamp(1.5rem, calc(var(--play-h) * .03), 2.4rem); }
|
||||
.mb-die { width: clamp(60px, calc(var(--play-h) * .07), 92px); height: clamp(60px, calc(var(--play-h) * .07), 92px); }
|
||||
.mb-dice { min-height: clamp(64px, calc(var(--play-h) * .074), 96px); }
|
||||
.mb-prompt { max-width: clamp(420px, calc(var(--play-h) * .5), 620px); }
|
||||
.mb-card { width: min(100%, clamp(320px, calc(var(--play-h) * .36), 440px)); }
|
||||
}
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- geometry (viewBox 0..1000)
|
||||
@@ -505,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();
|
||||
@@ -617,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;
|
||||
@@ -655,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;
|
||||
@@ -777,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>
|
||||
@@ -826,6 +843,7 @@ function Center({
|
||||
act,
|
||||
pending,
|
||||
rolling,
|
||||
settled,
|
||||
card,
|
||||
onCardClose,
|
||||
}: {
|
||||
@@ -835,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;
|
||||
}) {
|
||||
@@ -885,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>
|
||||
@@ -1180,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);
|
||||
@@ -1438,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%)`;
|
||||
|
||||
@@ -159,6 +195,18 @@ const CSS = `
|
||||
.nn-opps { flex-wrap: wrap; justify-content: center; overflow: visible; width: 100%; max-width: calc(var(--cols) * 184px - 4px); margin: 0 auto; }
|
||||
.nn-seat { flex: 0 1 calc((100% - (var(--cols) - 1) * 8px) / var(--cols)); min-width: 0; max-width: 176px; }
|
||||
}
|
||||
/* PC: fill the play column. The felt takes the spare height; dial, hand cards (--nn-dial / --nn-cw) and seats grow with the play area. */
|
||||
@media (min-width: 1100px) {
|
||||
.nn { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; gap: 12px;
|
||||
--nn-dial: min(var(--play-h) * .34, 420px); --nn-cw: min(var(--play-h) * .17, 200px); }
|
||||
.nn-opps { max-width: calc(var(--cols) * 256px - 4px); }
|
||||
.nn-seat { max-width: 248px; padding: 8px 12px; font-size: clamp(.9rem, calc(var(--play-h) / 62), 1.1rem); }
|
||||
.nn-table { flex: 1 1 auto; padding: 20px 28px; font-size: clamp(1rem, calc(var(--play-h) / 62), 1.2rem); }
|
||||
.nn-hand { gap: clamp(10px, 1.2vw, 20px); }
|
||||
.nn-table .nn-chip { font-size: .9em; }
|
||||
.nn-recent li { font-size: .88em; }
|
||||
.nn-recent .who { max-width: 140px; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.nn-table { grid-template-columns: 1fr auto; grid-template-areas: 'dial left' 'right right'; padding: 10px; gap: 8px 10px; border-width: 6px; }
|
||||
.nn-dial { grid-area: dial; }
|
||||
@@ -239,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' }}>
|
||||
@@ -271,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);
|
||||
const dial = 'clamp(150px, 20vw, 196px)';
|
||||
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}>
|
||||
@@ -294,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}
|
||||
@@ -310,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} />
|
||||
@@ -323,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>
|
||||
@@ -390,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('');
|
||||
@@ -413,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);
|
||||
@@ -445,8 +496,9 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus();
|
||||
};
|
||||
const n = my.hand.length;
|
||||
const cw = n <= 3 ? 'clamp(84px, 24vw, 104px)' : n === 4 ? 'clamp(72px, 20vw, 96px)' : 'clamp(62px, 16.5vw, 90px)';
|
||||
const meSeat = v.seats.find((s) => s.id === v.me);
|
||||
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 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">
|
||||
@@ -475,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>
|
||||
@@ -570,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 (
|
||||
@@ -578,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>
|
||||
@@ -647,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);
|
||||
@@ -664,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) {
|
||||
@@ -748,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>
|
||||
@@ -755,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} />
|
||||
@@ -784,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">
|
||||
@@ -796,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';
|
||||
@@ -131,8 +131,10 @@ function logText(e: LogEntry, players: Record<string, PublicUser>, me: string |
|
||||
// ---------------------------------------------------------------- styles
|
||||
|
||||
const CSS = `
|
||||
.om-board { width: 100%; max-width: 1040px; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; }
|
||||
.om-seats { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 10px; padding-top: 6px; }
|
||||
.om-board { width: 100%; max-height: 100%; overflow: auto; display: flex; flex-direction: column; gap: 12px; padding: 2px; flex: 1 1 auto; min-height: 0; }
|
||||
.om-board > * { flex: none; }
|
||||
.om-board > .om-table { flex: 1 0 auto; }
|
||||
.om-seats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 260px)); justify-content: center; gap: 10px; padding-top: 6px; }
|
||||
.om-seat { position: relative; background: var(--surface); border-radius: var(--radius-lg); padding: 8px 10px; box-shadow: var(--shadow); border: 3px solid transparent; display: flex; flex-direction: column; gap: 5px; min-width: 0; }
|
||||
.om-seat.turn { border-color: var(--focus); }
|
||||
.om-seat.target { border-color: var(--primary); border-style: dashed; }
|
||||
@@ -156,7 +158,7 @@ const CSS = `
|
||||
.om-mini.empty i { background: none; border-style: dashed; border-color: var(--border); box-shadow: none; }
|
||||
.om-mini.empty i::after { display: none; }
|
||||
.om-bubble { position: absolute; right: 8px; top: -12px; background: var(--text); color: var(--surface); border-radius: 12px; padding: 2px 10px; font-weight: 800; font-size: .8rem; box-shadow: var(--shadow); animation: om-pop .25s ease-out; z-index: 2; }
|
||||
.om-table { position: relative; color: #fff; border-radius: 22px; padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 10px; align-items: center; min-height: 200px;
|
||||
.om-table { position: relative; color: #fff; border-radius: 22px; padding: 12px 14px 14px; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; min-height: 200px;
|
||||
background: radial-gradient(ellipse 75% 60% at 50% 36%, rgba(255,255,255,.15), rgba(255,255,255,0) 70%), var(--felt);
|
||||
border: 6px solid var(--wood); box-shadow: inset 0 0 0 2px rgba(255,255,255,.07), inset 0 0 48px rgba(0,0,0,.32), var(--shadow); }
|
||||
.om-table .small { color: #fff; opacity: .92; text-shadow: 0 1px 2px rgba(0,0,0,.35); }
|
||||
@@ -194,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); }
|
||||
@@ -233,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; }
|
||||
}
|
||||
`;
|
||||
@@ -241,8 +244,10 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047,
|
||||
// ---------------------------------------------------------------- pieces
|
||||
|
||||
/** Width of an element, kept up to date (a callback ref, so it follows the element when it is re-created). */
|
||||
function useWidth<T extends HTMLElement>(): [(node: T | null) => void, number, { current: T | null }] {
|
||||
/** Width of the node + the play area height on PC (`--play-h` of .game-main, 0 when the page scrolls instead). */
|
||||
function useWidth<T extends HTMLElement>(): [(node: T | null) => void, number, { current: T | null }, number] {
|
||||
const [w, setW] = useState(0);
|
||||
const [h, setH] = useState(0);
|
||||
const el = useRef<T | null>(null);
|
||||
const ro = useRef<ResizeObserver | null>(null);
|
||||
const ref = useCallback((node: T | null) => {
|
||||
@@ -250,13 +255,28 @@ function useWidth<T extends HTMLElement>(): [(node: T | null) => void, number, {
|
||||
ro.current = null;
|
||||
el.current = node;
|
||||
if (!node) return;
|
||||
setW(node.clientWidth);
|
||||
const measure = () => {
|
||||
setW(node.clientWidth);
|
||||
setH(parseFloat(getComputedStyle(node).getPropertyValue('--play-h')) || 0);
|
||||
};
|
||||
measure();
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
ro.current = new ResizeObserver(() => setW(node.clientWidth));
|
||||
ro.current = new ResizeObserver(measure);
|
||||
ro.current.observe(node);
|
||||
const main = node.closest('.game-main');
|
||||
if (main) ro.current.observe(main);
|
||||
}
|
||||
}, []);
|
||||
return [ref, w, el];
|
||||
return [ref, w, el, h];
|
||||
}
|
||||
|
||||
/**
|
||||
* How much bigger than the base size the two card rows (table fan + my hand) can be on a big PC play area: both rows
|
||||
* share the height left after the seats, titles, notes and buttons (~520px + a row of seats per extra seat line).
|
||||
*/
|
||||
function cardGrow(v: OldMaidView, width: number, playH: number): number {
|
||||
const seatRows = Math.ceil(Math.max(1, v.order.length - 1) / Math.max(1, Math.floor((width + 50) / 270)));
|
||||
return Math.min(2, Math.max(1, Math.min(width / 900, (playH - 520 - (seatRows - 1) * 110) / 200)));
|
||||
}
|
||||
|
||||
const rowStyle = (l: FanLayout): CSSProperties => ({ '--cw': `${l.cw}px`, '--sw': `${l.step}px` }) as CSSProperties;
|
||||
@@ -311,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}
|
||||
@@ -331,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>}
|
||||
@@ -339,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>
|
||||
);
|
||||
@@ -405,7 +426,7 @@ function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidV
|
||||
const mine = !!v.my?.canDraw && v.my.from === target;
|
||||
const count = mine ? v.my!.count : (v.handCounts[target] ?? 0);
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [ref, width, box] = useWidth<HTMLDivElement>();
|
||||
const [ref, width, box, playH] = useWidth<HTMLDivElement>();
|
||||
// A new turn, or the owner shuffled / the fan changed: start over.
|
||||
useEffect(() => setSel(null), [v.turnNo, target, count, v.shuffles[target]]);
|
||||
// Where every card sits now (relative to the table), so a draw by someone else lifts that very card (useOldMaidFx).
|
||||
@@ -421,7 +442,8 @@ function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidV
|
||||
}),
|
||||
};
|
||||
});
|
||||
const l = fanLayout(count, width, width > 0 && width < 520 ? FAN_PHONE : { ...FAN_PC, wrapCw: count > 12 ? 50 : 60 });
|
||||
const g = cardGrow(v, width, playH);
|
||||
const l = fanLayout(count, width, width > 0 && width < 520 ? FAN_PHONE : { cw: Math.round(FAN_PC.cw * g), prefer: Math.round(FAN_PC.prefer * g), wrapCw: Math.round((count > 12 ? 50 : 60) * g) });
|
||||
const draw = (index: number) => {
|
||||
if (pending) return;
|
||||
myDrawRect = box.current?.querySelectorAll('button.om-back')[index]?.querySelector('.om-face')?.getBoundingClientRect() ?? null;
|
||||
@@ -495,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 ? '(시간 초과)' : ''}`;
|
||||
@@ -504,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} />}
|
||||
@@ -539,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 (
|
||||
@@ -587,13 +622,15 @@ 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(' ');
|
||||
const [ref, width, box] = useWidth<HTMLDivElement>();
|
||||
const [ref, width, box, playH] = useWidth<HTMLDivElement>();
|
||||
const narrow = width > 0 && width < 520;
|
||||
const l = fanLayout(hand.length, width, { ...(narrow ? HAND_PHONE : HAND_PC), wrapCw: narrow ? (hand.length > 12 ? 44 : 50) : hand.length > 12 ? 52 : 64 });
|
||||
const g = narrow ? 1 : cardGrow(v, width, playH);
|
||||
const base = narrow ? HAND_PHONE : HAND_PC;
|
||||
const l = fanLayout(hand.length, width, { cw: Math.round(base.cw * g), prefer: Math.round(base.prefer * g), wrapCw: Math.round((narrow ? (hand.length > 12 ? 44 : 50) : hand.length > 12 ? 52 : 64) * g) });
|
||||
// Shuffled (same cards, new order): every card slides with a little hop from its old place to its new one.
|
||||
const order = hand.join(',');
|
||||
const pos = useRef<{ order: string; at: Map<string, [number, number]> }>({ order: '', at: new Map() });
|
||||
@@ -646,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">
|
||||
@@ -693,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;
|
||||
@@ -713,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') {
|
||||
@@ -729,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) {
|
||||
@@ -747,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>
|
||||
@@ -769,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 });
|
||||
@@ -792,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();
|
||||
@@ -799,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;
|
||||
@@ -809,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':
|
||||
@@ -830,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;
|
||||
}
|
||||
@@ -847,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;
|
||||
@@ -855,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(() => {
|
||||
@@ -880,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: '백' };
|
||||
@@ -43,6 +43,8 @@ const OMOK_CSS = `
|
||||
@keyframes om-forbid { 0% { transform: scale(.3); opacity: 0; } 18% { transform: scale(1.25); opacity: 1; } 32% { transform: scale(1); } 75% { opacity: 1; } 100% { opacity: 0; } }
|
||||
.om-forbid-t { animation: om-forbid-t .9s ease-out both; pointer-events: none; }
|
||||
@keyframes om-forbid-t { 0% { transform: translateY(0); opacity: 0; } 20% { opacity: 1; } 100% { transform: translateY(-.9px); opacity: 0; } }
|
||||
/* PC: the board takes the whole play-area height minus the row that can show under it (--om-rows). */
|
||||
@media (min-width: 1100px) { .board-wrap.om-fit { max-width: min(100%, calc(var(--play-h) - var(--om-rows, 0px))); } }
|
||||
`;
|
||||
|
||||
function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>) {
|
||||
@@ -65,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.
|
||||
@@ -153,7 +165,8 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
const ghost = preview ?? (hover && canPlace(hover) ? hover : null);
|
||||
const pad = 0.9;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
// Touch with tap-confirm shows [두기][취소] under the board: keep room for it.
|
||||
<div className="board-wrap stack om-fit" style={{ gap: 10, '--om-rows': tapConfirm ? 'calc(var(--btn-h) + 10px)' : '0px' } as React.CSSProperties}>
|
||||
<style>{BOARD_MOTION_CSS + OMOK_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
@@ -224,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'];
|
||||
@@ -127,6 +127,15 @@ const CSS = `
|
||||
.oc-opps { flex-wrap: wrap; justify-content: center; overflow: visible; width: 100%; max-width: calc(var(--cols) * 184px - 4px); margin: 0 auto; }
|
||||
.oc-seat { flex: 0 1 calc((100% - (var(--cols) - 1) * 8px) / var(--cols)); min-width: 0; max-width: 176px; }
|
||||
}
|
||||
/* PC: fill the play column. The felt takes the spare height, piles and hand cards grow with the play area, seats get bigger. */
|
||||
@media (min-width: 1100px) {
|
||||
.oc { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; gap: 12px; }
|
||||
.oc-opps { max-width: calc(var(--cols) * 256px - 4px); }
|
||||
.oc-seat { max-width: 248px; padding: 8px 12px; font-size: clamp(.9rem, calc(var(--play-h) / 62), 1.1rem); }
|
||||
.oc-table { flex: 1 1 auto; grid-template-columns: 1fr auto auto 1fr; gap: clamp(16px, 2vw, 40px); padding: 20px 28px; font-size: clamp(1rem, calc(var(--play-h) / 62), 1.2rem); }
|
||||
.oc-table > .oc-pile { grid-column: 2; }
|
||||
.oc-hand { justify-content: center; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.oc-table { grid-template-columns: auto auto; padding: 10px; gap: 10px; border-width: 6px; justify-content: center; }
|
||||
.oc-info { grid-column: 1 / -1; align-items: center; }
|
||||
@@ -164,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>
|
||||
@@ -181,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>
|
||||
);
|
||||
@@ -218,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` }}>
|
||||
@@ -230,7 +244,7 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) {
|
||||
function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCardView; players: Record<string, PublicUser>; canDraw: boolean; onDraw: () => void; onDropCard: (id: string) => void; fx: Fx }) {
|
||||
const [over, setOver] = useState(false);
|
||||
const from = fx.playFrom && fx.playFrom.discard === v.discardCount ? fx.playFrom : null;
|
||||
const pw = 'clamp(64px, 9vw, 92px)';
|
||||
const pw = 'clamp(64px, min(9vw, var(--play-h) * .15), 210px)';
|
||||
const recent = v.recent;
|
||||
const top = recent[recent.length - 1];
|
||||
const drawText = v.pendingAttack > 0 ? `${v.pendingAttack}장 먹기` : '1장 먹기';
|
||||
@@ -333,18 +347,26 @@ function TableArea({ v, players, canDraw, onDraw, onDropCard, fx }: { v: OneCard
|
||||
|
||||
// ---------------------------------------------------------------- my hand
|
||||
|
||||
function useWidth<T extends HTMLElement>(): [React.RefObject<T | null>, number] {
|
||||
/** Element width plus the PC play-area height (--play-h on .game-main; 0 under 1100px where it is not measured). */
|
||||
function useWidth<T extends HTMLElement>(): [React.RefObject<T | null>, number, number] {
|
||||
const ref = useRef<T>(null);
|
||||
const [w, setW] = useState(0);
|
||||
const [h, setH] = useState(0);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
setW(el.clientWidth);
|
||||
const ro = new ResizeObserver(() => setW(el.clientWidth));
|
||||
const main = el.closest('.game-main');
|
||||
const update = () => {
|
||||
setW(el.clientWidth);
|
||||
setH(main && matchMedia('(min-width: 1100px)').matches ? parseFloat(getComputedStyle(main).getPropertyValue('--play-h')) || 0 : 0);
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
if (main) ro.observe(main);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
return [ref, w];
|
||||
return [ref, w, h];
|
||||
}
|
||||
|
||||
interface PickState {
|
||||
@@ -359,7 +381,7 @@ function MyHand({ v, act, pending, players, arrived }: { v: OneCardView; act: (a
|
||||
const [hints, setHints] = useState(true);
|
||||
const [pick, setPick] = useState<PickState | null>(null);
|
||||
const [note, setNote] = useState('');
|
||||
const [ref, width] = useWidth<HTMLDivElement>();
|
||||
const [ref, width, playH] = useWidth<HTMLDivElement>();
|
||||
const hand = sortHand(my.hand, sortBy);
|
||||
const legal = new Set(my.legalCardIds);
|
||||
const turnKey = `${v.turnNo}-${v.phase}`;
|
||||
@@ -417,7 +439,7 @@ function MyHand({ v, act, pending, players, arrived }: { v: OneCardView; act: (a
|
||||
// Layout: one overlapping row on wide screens, wrapped rows on phones (cards ≥ 48 × 68).
|
||||
const n = hand.length;
|
||||
const phone = width > 0 && width < 600;
|
||||
const cw = phone ? 54 : 78;
|
||||
const cw = phone ? 54 : Math.round(Math.min(156, Math.max(78, playH * 0.12)));
|
||||
let ov = 6;
|
||||
if (!phone && n > 1) ov = Math.max(-cw * 0.6, Math.min(6, (width - cw * n) / (n - 1)));
|
||||
if (phone) ov = n > 12 ? -14 : 4;
|
||||
@@ -790,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">
|
||||
@@ -823,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>
|
||||
@@ -837,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) => (
|
||||
@@ -875,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';
|
||||
@@ -33,7 +34,9 @@ const CSS = `
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.oth-flip { animation: none; }
|
||||
.oth-old { display: none; }
|
||||
}`;
|
||||
}
|
||||
/* PC: the board takes the whole play-area height minus the disc-count bar and the row that can show under it (--oth-rows). */
|
||||
@media (min-width: 1100px) { .board-wrap.oth-fit { max-width: min(100%, calc(var(--play-h) - var(--oth-rows, 0px))); } }`;
|
||||
|
||||
/** Disc set down, then one light click per disc as it turns over (staggered like the animation). */
|
||||
function placeSound(flipDelays: number[]) {
|
||||
@@ -72,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>();
|
||||
@@ -91,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 {
|
||||
@@ -101,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')) {
|
||||
@@ -186,24 +201,25 @@ 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 (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
// Disc bar (30px) above; with touch tap-confirm also [두기][취소] under the board.
|
||||
<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
|
||||
@@ -435,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>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 포커 화면 (docs/games/poker.md §9). Chips are room-only play points. */
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { BetActionType, LegalBetView, LogEntry, PokerMode, PokerOptions, PokerView, SeatView, Side, ViewCard } from '@bg/games/poker';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
@@ -7,11 +7,12 @@ import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { PLAYING_CARD_CREDIT, PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import { Chips, PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useWide } from '../../lib/media';
|
||||
import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useChange } 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';
|
||||
|
||||
const MODE_KO: Record<PokerMode, string> = {
|
||||
holdem: '텍사스 홀덤',
|
||||
@@ -60,12 +61,15 @@ const isDrawMode = (m: PokerMode) => m === 'badugi' || m === 'fiveDraw';
|
||||
/** Rank of a card id for the client-side "A를 남기면 4장" check. */
|
||||
const isAce = (c: string) => c[0] === 'A';
|
||||
|
||||
/** Width of my own (large) cards: 88 px, more on wide PC screens (see PokerBoard). */
|
||||
const MyCardW = createContext(88);
|
||||
|
||||
const CSS = `
|
||||
.pk-table { position: relative; width: 100%; aspect-ratio: 16 / 11; border-radius: 180px; border: 10px solid var(--wood);
|
||||
background: radial-gradient(ellipse at center, rgba(255,255,255,0.12) 0%, rgba(255,255,255,0) 60%), var(--felt); box-shadow: var(--shadow); }
|
||||
.pk-seat { position: absolute; left: var(--x); top: var(--y); transform: translate(-50%, -50%); width: var(--seat-w, 172px); z-index: 1;
|
||||
background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.25);
|
||||
border: 3px solid transparent; display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; transition: border-color .2s; }
|
||||
border: 3px solid transparent; display: flex; flex-direction: column; gap: 4px; font-size: calc(0.85rem * var(--pkf, 1)); transition: border-color .2s; }
|
||||
.pk-seat.turn { border-color: var(--focus); }
|
||||
.pk-seat.me { border-color: var(--primary); }
|
||||
.pk-seat.me.turn { border-color: var(--focus); }
|
||||
@@ -73,7 +77,7 @@ const CSS = `
|
||||
.pk-seat.out { opacity: 0.6; }
|
||||
.pk-center { position: absolute; left: 50%; top: 48%; transform: translate(-50%, -50%); text-align: center; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,.5); max-width: 52%; }
|
||||
.pk-board { display: flex; gap: 6px; justify-content: center; margin: 6px 0; }
|
||||
.pk-slot { width: 64px; height: 90px; border-radius: 8px; border: 2px dashed rgba(255,255,255,.35); flex: none; }
|
||||
.pk-slot { width: calc(64px * var(--pks, 1)); height: calc(90px * var(--pks, 1)); border-radius: 8px; border: 2px dashed rgba(255,255,255,.35); flex: none; }
|
||||
.pk-actions { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
|
||||
.pk-actions .btn { min-height: 64px; flex-direction: column; gap: 0; padding: 0 8px; line-height: 1.15; font-size: 1.1rem; }
|
||||
.pk-actions .btn small { font-weight: 600; font-size: .85rem; opacity: .9; }
|
||||
@@ -83,6 +87,11 @@ const CSS = `
|
||||
.pk-x::after { content: '✕'; position: absolute; inset: 0; display: grid; place-items: center; color: #dc2626; font-size: 3rem; font-weight: 900; pointer-events: none; }
|
||||
.pk-raise { display: grid; gap: 8px; }
|
||||
.pk-raise input[type=range] { width: 100%; min-height: 40px; }
|
||||
/* PC: the table is as wide as the play column and takes the height my area leaves (seats and cards grow, see PokerBoard). */
|
||||
@media (min-width: 1100px) {
|
||||
.pk-wrap.board-wrap { max-width: none; align-self: stretch; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
||||
.pk-table { flex: 1 1 0; aspect-ratio: auto; min-height: 420px; }
|
||||
}
|
||||
@media (max-width: 719px) {
|
||||
.pk-table { aspect-ratio: auto; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding: 10px; border-radius: 20px; border-width: 6px; }
|
||||
.pk-seat { position: static; transform: none; width: auto; }
|
||||
@@ -114,8 +123,8 @@ function seatBadges(seat: SeatView, v: PokerView): [string, string][] {
|
||||
return b;
|
||||
}
|
||||
|
||||
function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string | null }) {
|
||||
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.
|
||||
@@ -130,23 +139,26 @@ function SeatCards({ seat, v, me }: { seat: SeatView; v: PokerView; me: string |
|
||||
<PlayingCard
|
||||
key={x.key}
|
||||
card={x.c}
|
||||
size="sm"
|
||||
width={Math.round(44 * k)}
|
||||
highlight={!!x.c && best.has(x.c)}
|
||||
title={x.title}
|
||||
style={i > 0 ? { marginLeft: cards.length > 5 ? -24 : -16 } : undefined}
|
||||
style={i > 0 ? { marginLeft: Math.round((cards.length > 5 ? -24 : -16) * k) } : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: 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', '스몰 블라인드']);
|
||||
@@ -157,7 +169,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
|
||||
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} />
|
||||
@@ -173,7 +185,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
|
||||
{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>}
|
||||
@@ -187,8 +199,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SeatCards seat={seat} v={v} me={me} />
|
||||
{!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}
|
||||
@@ -199,20 +211,22 @@ function SeatBox({ seat, v, players, me, deadline, x, y }: { seat: SeatView; v:
|
||||
);
|
||||
}
|
||||
|
||||
function CenterInfo({ v, players }: { v: PokerView; players: Record<string, PublicUser> }) {
|
||||
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>}
|
||||
{isCommunity(v.mode) && (
|
||||
<div className="pk-board" aria-label="공용 카드" data-fx="poker-board">
|
||||
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} size="md" /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
|
||||
{Array.from({ length: 5 }, (_, i) => (v.board[i] ? <PlayingCard key={v.board[i]} card={v.board[i]!} width={Math.round(64 * k)} /> : <span key={`e${i}`} className="pk-slot" aria-hidden />))}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
||||
<div style={{ fontSize: '2.2rem', fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
|
||||
{formatChips(v.pot)}
|
||||
<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(pot)}
|
||||
</div>
|
||||
{v.pots.length > 1 && (
|
||||
<div className="small" style={{ opacity: 0.9 }}>
|
||||
@@ -249,6 +263,26 @@ 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);
|
||||
const [[tableW, tableH], setTableSize] = useState([890, 600]);
|
||||
useLayoutEffect(() => {
|
||||
const el = tableRef.current;
|
||||
if (!el) return undefined;
|
||||
const measure = () => setTableSize([el.clientWidth, el.clientHeight]);
|
||||
const ro = new ResizeObserver(measure);
|
||||
ro.observe(el);
|
||||
measure();
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
const k = wide ? Math.min(1.6, Math.max(1, Math.min(tableW / 890, tableH / 600))) : 1;
|
||||
// My cards follow the width only (my area's height decides the table's height, so no loop).
|
||||
const lgW = Math.round(88 * (wide ? Math.min(1.4, Math.max(1, tableW / 1300)) : 1));
|
||||
// Seats (≈170 px × k tall, centred on the oval) stay inside the felt when the table is short and wide.
|
||||
const ry = wide ? Math.max(28, Math.min(38, 50 - ((85 * k + 6) / Math.max(1, tableH)) * 100)) : 38;
|
||||
|
||||
useEffect(() => {
|
||||
if (mine && !prevWaiting.current) {
|
||||
@@ -260,28 +294,41 @@ 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 (
|
||||
<div className="board-wrap stack" style={{ gap: 12 }}>
|
||||
<style>{CSS}</style>
|
||||
<div className="pk-table" role="region" aria-label="포커 테이블" style={{ '--seat-w': n > 6 ? '150px' : '176px' } as React.CSSProperties}>
|
||||
{v.seats.map((s, i) => {
|
||||
const rel = (i - myIdx + n) % n;
|
||||
const ang = Math.PI / 2 + (rel * 2 * Math.PI) / n;
|
||||
return <SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * Math.cos(ang)} y={50 + 38 * Math.sin(ang)} />;
|
||||
})}
|
||||
<CenterInfo v={v} players={players} />
|
||||
<MyCardW.Provider value={lgW}>
|
||||
<div className="pk-wrap board-wrap stack" style={{ gap: 12 }}>
|
||||
<style>{CSS}</style>
|
||||
<div
|
||||
className="pk-table"
|
||||
ref={tableRef}
|
||||
role="region"
|
||||
aria-label="포커 테이블"
|
||||
style={{ '--seat-w': `${Math.round((n > 6 ? 150 : 176) * k)}px`, '--pks': k.toFixed(2), '--pkf': (1 + (k - 1) / 2).toFixed(2) } as React.CSSProperties}
|
||||
>
|
||||
{v.seats.map((s, i) => {
|
||||
const rel = (i - myIdx + n) % n;
|
||||
const ang = Math.PI / 2 + (rel * 2 * Math.PI) / n;
|
||||
// PC: pull side seats toward the table's corners so a short, wide table keeps them apart.
|
||||
const c = Math.cos(ang);
|
||||
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} endShown={endShown} />;
|
||||
})}
|
||||
<CenterInfo v={v} players={players} k={k} />
|
||||
</div>
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} endShown={endShown} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
</div>
|
||||
</MyCardW.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -623,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 }}>
|
||||
@@ -638,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>}
|
||||
@@ -662,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>
|
||||
);
|
||||
}
|
||||
@@ -693,25 +742,26 @@ function RevealBox({ v, act, pending }: { v: PokerView; act: (a: unknown) => voi
|
||||
}
|
||||
|
||||
function MyCards({ v, seat }: { v: PokerView; seat: SeatView }) {
|
||||
const lgW = useContext(MyCardW);
|
||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||
const best = new Set(sd?.best ?? []);
|
||||
return (
|
||||
<div className="pk-mine" aria-label="내 카드" data-fx="poker-mine">
|
||||
{seat.forehead !== undefined && (
|
||||
<div className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot="f">
|
||||
<PlayingCard card={seat.forehead} size="lg" title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
|
||||
<PlayingCard card={seat.forehead} width={lgW} title={seat.forehead ? undefined : '내 이마 카드(나만 못 봐요)'} />
|
||||
<span className="small muted">이마</span>
|
||||
</div>
|
||||
)}
|
||||
{seat.hole.map((c, i) => (
|
||||
<div key={`h${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `h${i}`}>
|
||||
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
||||
<PlayingCard card={c} width={lgW} highlight={!!c && best.has(c)} />
|
||||
{(isSevenMode(v.mode) || v.mode === 'indian') && <span className="small muted">{v.mode === 'indian' ? '손' : '나만 봄'}</span>}
|
||||
</div>
|
||||
))}
|
||||
{seat.up.map((c, i) => (
|
||||
<div key={`u${i}`} className="stack" style={{ gap: 2, alignItems: 'center' }} data-slot={c ?? `u${i}`}>
|
||||
<PlayingCard card={c} size="lg" highlight={!!c && best.has(c)} />
|
||||
<PlayingCard card={c} width={lgW} highlight={!!c && best.has(c)} />
|
||||
<span className="small muted">공개</span>
|
||||
</div>
|
||||
))}
|
||||
@@ -723,6 +773,7 @@ function MyCards({ v, seat }: { v: PokerView; seat: SeatView }) {
|
||||
function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unknown) => void; pending: boolean }) {
|
||||
const [discard, setDiscard] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<string | null>(null);
|
||||
const lgW = useContext(MyCardW);
|
||||
const tap = (c: string) => {
|
||||
sfx.select();
|
||||
if (!discard) setDiscard(c);
|
||||
@@ -741,7 +792,7 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
|
||||
<div className="pk-mine" data-fx="poker-mine">
|
||||
{cards.map((c) => (
|
||||
<span key={c} className={c === discard ? 'pk-x' : undefined} data-slot={c}>
|
||||
<PlayingCard card={c} size="lg" selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
|
||||
<PlayingCard card={c} width={lgW} selected={c === open} dimmed={c === discard} onClick={() => tap(c)} title={c === discard ? '버릴 카드(다시 누르면 취소)' : c === open ? '보여 줄 카드' : undefined} />
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
@@ -768,6 +819,7 @@ function ChoicePicker({ cards, act, pending }: { cards: string[]; act: (a: unkno
|
||||
/** 교환(바둑이 / 5카드 드로우): tap to lift the cards to change. */
|
||||
function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; act: (a: unknown) => void; pending: boolean }) {
|
||||
const [sel, setSel] = useState<string[]>([]);
|
||||
const lgW = useContext(MyCardW);
|
||||
const { drawMax, drawAceBonus } = v.my;
|
||||
const keepsAce = hole.some((c) => isAce(c) && !sel.includes(c));
|
||||
const limit = drawAceBonus && keepsAce ? drawMax + 1 : drawMax;
|
||||
@@ -785,7 +837,7 @@ function DrawPicker({ v, hole, act, pending }: { v: PokerView; hole: string[]; a
|
||||
</p>
|
||||
<div className="pk-mine">
|
||||
{hole.map((c) => (
|
||||
<PlayingCard key={c} card={c} size="lg" selected={sel.includes(c)} onClick={() => {
|
||||
<PlayingCard key={c} card={c} width={lgW} selected={sel.includes(c)} onClick={() => {
|
||||
sfx.select();
|
||||
setSel((s) => (s.includes(c) ? s.filter((x) => x !== c) : [...s, c]));
|
||||
}}
|
||||
@@ -1006,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 (
|
||||
<>
|
||||
@@ -1031,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>
|
||||
@@ -1085,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 {
|
||||
@@ -68,7 +69,31 @@ const CSS = `
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.qd-pawn { transition: none; }
|
||||
.qd-wall-new, .qd-turn-ring { animation: none; }
|
||||
}`;
|
||||
}
|
||||
.board-wrap.qd-side { flex-direction: row; align-items: center; justify-content: center; gap: 20px; }
|
||||
.qd-side > .qd-rows { flex: 0 1 380px; min-width: 0; }
|
||||
.qd-side .qd-modes { grid-template-columns: 1fr; }
|
||||
.qd-rows:empty { display: none; }`;
|
||||
|
||||
/** PC play-area size (.game-main, px), null under 1100px where the page scrolls and rows stay under the board. */
|
||||
function useWideMain(ref: React.RefObject<HTMLElement | null>) {
|
||||
const [size, setSize] = useState<{ w: number; h: number } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const main = ref.current?.closest<HTMLElement>('.game-main');
|
||||
if (!main) return;
|
||||
const wide = matchMedia('(min-width: 1100px)');
|
||||
const update = () => setSize(wide.matches ? { w: main.clientWidth, h: main.clientHeight } : null);
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(main);
|
||||
wide.addEventListener('change', update);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
wide.removeEventListener('change', update);
|
||||
};
|
||||
}, [ref]);
|
||||
return size;
|
||||
}
|
||||
|
||||
/** 판 돌리기: 모델 좌표(x 오른쪽, y 위쪽, 0~9) ↔ 화면 좌표(y 아래쪽). 네 가지 모두 자기 자신이 역변환. */
|
||||
function makeTf(seat: Seat | null) {
|
||||
@@ -159,6 +184,8 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const [cursor, setCursor] = useState<Pt>({ x: 4, y: 8 });
|
||||
const [kbd, setKbd] = useState(false);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const main = useWideMain(wrapRef);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
const [shake, setShake] = useState(0);
|
||||
@@ -170,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>();
|
||||
@@ -383,14 +412,25 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
return { x: N - off - w, y: 0, width: w, height: N };
|
||||
};
|
||||
|
||||
// PC: the board fills the play-area height. The rows (mode buttons, wall tray, hint) go beside it when that gives a
|
||||
// bigger board than stacking them under it (which needs about `under` px of height).
|
||||
const under = me ? (tapConfirm ? 190 : 175) : 60;
|
||||
const besideW = main ? Math.floor(Math.min(main.w - 320, main.h)) : 0;
|
||||
const stackW = main ? Math.floor(Math.min(main.w, main.h - under)) : 0;
|
||||
const beside = !!main && besideW > stackW;
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: 'min(100%, calc(100vh - 340px))', minWidth: 'min(100%, 300px)' }}>
|
||||
<div
|
||||
ref={wrapRef}
|
||||
className={`board-wrap stack${beside ? ' qd-side' : ''}`}
|
||||
style={{ gap: 10, maxWidth: beside ? 'none' : main ? `min(100%, ${stackW}px)` : 'min(100%, calc(100vh - 340px))', minWidth: 'min(100%, 300px)' }}
|
||||
>
|
||||
<style>{BOARD_MOTION_CSS + CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="qd-board"
|
||||
viewBox={`${-PAD} ${-PAD} ${N + 2 * PAD} ${N + 2 * PAD}`}
|
||||
style={{ width: '100%', display: 'block', background: 'var(--wood)', borderRadius: 14, touchAction: 'manipulation', cursor: myTurn ? 'pointer' : 'default', boxShadow: 'var(--shadow)' }}
|
||||
style={{ width: '100%', display: 'block', background: 'var(--wood)', borderRadius: 14, touchAction: 'manipulation', cursor: myTurn ? 'pointer' : 'default', boxShadow: 'var(--shadow)', ...(beside && { flex: '0 0 auto', width: besideW }) }}
|
||||
data-my-seat={v.mySeat ?? ''}
|
||||
data-mode={mode}
|
||||
data-path={path && v.myShortestPath ? v.myShortestPath.map(label).join(' ') : ''}
|
||||
@@ -525,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>
|
||||
@@ -564,61 +604,63 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{me && v.phase === 'playing' && me.status === 'playing' && (
|
||||
<div className="qd-modes" role="group" aria-label="할 일 고르기">
|
||||
<button type="button" className={`btn ${mode === 'move' ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={mode === 'move'} disabled={!myTurn} onClick={() => setModeTo('move')}>
|
||||
🚶 말 움직이기
|
||||
</button>
|
||||
<button type="button" className={`btn ${mode === 'wall' ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={mode === 'wall'} disabled={!canWall} onClick={() => setModeTo('wall')}>
|
||||
🧱 벽 세우기 ({wallsLeft}개)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{myTurn && mode === 'wall' && (
|
||||
<div className="qd-tray">
|
||||
<span className={`qd-hint small${preview?.why ? ' bad' : ''}`} role="status">
|
||||
{!preview
|
||||
? '판의 홈(칸 사이) 교차점을 눌러 벽 자리를 골라요.'
|
||||
: preview.why
|
||||
? `${wallText(preview.wall, t.swap)}: ${preview.why}`
|
||||
: `${wallText(preview.wall, t.swap)} · 상대 길 +${preview.legal!.opp}칸${preview.legal!.me ? ` · 내 길 +${preview.legal!.me}칸` : ''}`}
|
||||
</span>
|
||||
<button type="button" className="btn btn-secondary qd-rotate" onClick={() => {
|
||||
const o = orient === 'h' ? 'v' : 'h';
|
||||
setOrient(o);
|
||||
if (wallAt) pinWall(wallAt, o);
|
||||
}} aria-label={`벽 방향 바꾸기, 지금 ${orient === 'h' ? '가로' : '세로'}`}>
|
||||
↻ {orient === 'h' ? '가로' : '세로'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary qd-confirm" disabled={!previewAnchor || !!preview?.why || pending} onClick={() => previewAnchor && doWall(previewAnchor)}>
|
||||
벽 세우기 확인
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{myTurn && mode === 'move' && movePreview && (
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={pending} onClick={() => doMove(movePreview)}>
|
||||
{label(t.screenToCell(movePreview))}으로 이동
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setMovePreview(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{me && v.phase === 'playing' && !(myTurn && mode === 'wall') && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{me.status === 'playing'
|
||||
? `내 말은 ${COLOR_KO[me.seat]}(${SEAT_KO[me.seat]})이에요. ${myGoal} 줄(${COLOR_KO[me.seat]} 띠)에 먼저 닿으면 이겨요.`
|
||||
: me.status === 'finished'
|
||||
? '목표에 도착했어요! 남은 사람들의 순위가 정해질 때까지 지켜봐요.'
|
||||
: '게임에서 빠졌어요. 계속 지켜볼 수 있어요.'}
|
||||
</p>
|
||||
)}
|
||||
{!me && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{v.seats.map((x) => `${nick(x.playerId)}: ${COLOR_KO[x.seat]} → ${SIDE_KO[t.goalSide(x.seat)]} 줄`).join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
<div className="stack qd-rows" style={{ gap: 10 }}>
|
||||
{me && v.phase === 'playing' && me.status === 'playing' && (
|
||||
<div className="qd-modes" role="group" aria-label="할 일 고르기">
|
||||
<button type="button" className={`btn ${mode === 'move' ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={mode === 'move'} disabled={!myTurn} onClick={() => setModeTo('move')}>
|
||||
🚶 말 움직이기
|
||||
</button>
|
||||
<button type="button" className={`btn ${mode === 'wall' ? 'btn-primary' : 'btn-secondary'}`} aria-pressed={mode === 'wall'} disabled={!canWall} onClick={() => setModeTo('wall')}>
|
||||
🧱 벽 세우기 ({wallsLeft}개)
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{myTurn && mode === 'wall' && (
|
||||
<div className="qd-tray">
|
||||
<span className={`qd-hint small${preview?.why ? ' bad' : ''}`} role="status">
|
||||
{!preview
|
||||
? '판의 홈(칸 사이) 교차점을 눌러 벽 자리를 골라요.'
|
||||
: preview.why
|
||||
? `${wallText(preview.wall, t.swap)}: ${preview.why}`
|
||||
: `${wallText(preview.wall, t.swap)} · 상대 길 +${preview.legal!.opp}칸${preview.legal!.me ? ` · 내 길 +${preview.legal!.me}칸` : ''}`}
|
||||
</span>
|
||||
<button type="button" className="btn btn-secondary qd-rotate" onClick={() => {
|
||||
const o = orient === 'h' ? 'v' : 'h';
|
||||
setOrient(o);
|
||||
if (wallAt) pinWall(wallAt, o);
|
||||
}} aria-label={`벽 방향 바꾸기, 지금 ${orient === 'h' ? '가로' : '세로'}`}>
|
||||
↻ {orient === 'h' ? '가로' : '세로'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-primary qd-confirm" disabled={!previewAnchor || !!preview?.why || pending} onClick={() => previewAnchor && doWall(previewAnchor)}>
|
||||
벽 세우기 확인
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{myTurn && mode === 'move' && movePreview && (
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={pending} onClick={() => doMove(movePreview)}>
|
||||
{label(t.screenToCell(movePreview))}으로 이동
|
||||
</button>
|
||||
<button className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setMovePreview(null)}>
|
||||
취소
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{me && v.phase === 'playing' && !(myTurn && mode === 'wall') && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{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'
|
||||
? '목표에 도착했어요! 남은 사람들의 순위가 정해질 때까지 지켜봐요.'
|
||||
: '게임에서 빠졌어요. 계속 지켜볼 수 있어요.'}
|
||||
</p>
|
||||
)}
|
||||
{!me && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{v.seats.map((x) => `${nick(x.playerId)}: ${COLOR_KO[x.seat]} → ${SIDE_KO[t.goalSide(x.seat)]} 줄`).join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -652,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'
|
||||
@@ -660,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'),
|
||||
@@ -36,6 +42,12 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
liar: () => import('./liar'),
|
||||
'magical-athlete': () => import('./magical-athlete'),
|
||||
blackjack: () => import('./blackjack'),
|
||||
'six-nimmt': () => import('./six-nimmt'),
|
||||
gemblo: () => import('./gemblo'),
|
||||
'hot-streak': () => import('./hot-streak'),
|
||||
tichu: () => import('./tichu'),
|
||||
'case-file': () => import('./case-file'),
|
||||
'castles-of-burgundy': () => import('./castles-of-burgundy'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
@@ -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' };
|
||||
@@ -175,6 +175,9 @@ button.rk-tile:disabled { cursor: default; }
|
||||
.rk-result { display: grid; gap: 6px; }
|
||||
.rk-result-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.rk-mini { display: inline-flex; gap: 2px; flex-wrap: wrap; }
|
||||
@media (min-width: 1100px) {
|
||||
.rk-rack .rk-tile { --w: clamp(44px, var(--play-w) * .036, 58px); --h: calc(var(--w) * 1.36); }
|
||||
}
|
||||
@media (max-width: 1099px) {
|
||||
.rk-table { min-height: 160px; }
|
||||
}
|
||||
@@ -331,7 +334,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const z = Number(localStorage.getItem('rk-zoom'));
|
||||
return ZOOMS.includes(z) ? z : null;
|
||||
});
|
||||
const [boxW, setBoxW] = useState(0);
|
||||
const [box, setBox] = useState({ w: 0, h: 0 });
|
||||
const [msg, setMsg] = useState('');
|
||||
const [confirm, setConfirm] = useState<null | 'draw' | 'commit'>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
@@ -348,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);
|
||||
@@ -383,19 +389,23 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
// First-meld progress from what is on the board right now (new sets made of rack tiles only).
|
||||
const meldNow = groups.filter((g) => g.ok && g.tileIds.every((id) => !onTable0.has(id))).reduce((a, g) => a + g.points, 0);
|
||||
|
||||
// Grid size: fit the width, zoom in on small screens (the board scrolls).
|
||||
// Grid size: fit the width, zoom in on small screens (the board scrolls). On PC (fixed-height play area) the cells
|
||||
// may grow past 64px as long as the first MIN_ROWS rows still fit the height.
|
||||
useLayoutEffect(() => {
|
||||
const el = boxRef.current;
|
||||
if (!el) return;
|
||||
setBoxW(el.clientWidth);
|
||||
const wide = window.matchMedia('(min-width: 1100px)');
|
||||
const update = () => setBox({ w: el.clientWidth, h: wide.matches ? el.clientHeight : 0 });
|
||||
update();
|
||||
if (typeof ResizeObserver === 'undefined') return;
|
||||
const ro = new ResizeObserver(() => setBoxW(el.clientWidth));
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
const fit = boxW ? Math.floor((boxW - 2) / BOARD_COLS) : 36;
|
||||
const fit = box.w ? Math.floor((box.w - 2) / BOARD_COLS) : 36;
|
||||
const fitH = box.h ? Math.floor((box.h - 2) / MIN_ROWS / 1.36) : 0;
|
||||
const z = zoom ?? (fit >= 30 ? 1 : fit >= 21 ? 1.5 : 2);
|
||||
const cw = Math.max(16, Math.min(64, Math.round(fit * z)));
|
||||
const cw = Math.max(16, Math.min(100, Math.round(Math.max(Math.min(fit, 64), Math.min(fit, fitH)) * z)));
|
||||
const ch = Math.round(cw * 1.36);
|
||||
const lowest = cells.reduce((m, x) => Math.max(m, x.r), -1);
|
||||
const rows = Math.min(BOARD_ROWS, Math.max(MIN_ROWS, lowest + 2 + (hand ? 1 : 0)));
|
||||
@@ -478,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
|
||||
|
||||
@@ -997,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">
|
||||
@@ -1203,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 }}>
|
||||
@@ -1224,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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -65,7 +65,7 @@ test('섯다: 2장째를 받으면 지금 내 족보와 마지막 베팅, 족보
|
||||
|
||||
const off = setupGame('seotda', 2, { hints: false }).state;
|
||||
const p = view(off, null).toAct as string;
|
||||
expect(helpNow(view(off, p), p, users)).toContain("'족보 도우미'를 보고");
|
||||
expect(helpNow(view(off, p), p, users)).toContain("'족보'판을 보고");
|
||||
});
|
||||
|
||||
test('섯다: 3장 섯다 공개패 → 베팅 2번 → 고르기 단계(한게임)', () => {
|
||||
@@ -75,7 +75,15 @@ test('섯다: 3장 섯다 공개패 → 베팅 2번 → 고르기 단계(한게
|
||||
expect(helpNow(view(state, null), null, users)).toContain('공개패');
|
||||
for (const p of ['A', 'B', 'C']) state = applyAction('seotda', state, p, { type: 'open', cardId: view(state, p).seats.find((x) => x.id === p).cards[0].id });
|
||||
expect(helpNow(view(state, null), null, users)).not.toContain('공개패를 고르는 중');
|
||||
while (view(state, null).handPhase === 'betting') state = applyAction('seotda', state, view(state, null).toAct, { type: 'check' });
|
||||
// 1구 (한게임): 선은 하프·다이만, 그다음은 체크 없이 콜. 2구는 체크.
|
||||
const dealer = view(state, null).toAct as string;
|
||||
expect(helpNow(view(state, dealer), dealer, users)).toContain('선이 [하프]나 [다이]만');
|
||||
while (view(state, null).handPhase === 'betting') {
|
||||
const who = view(state, null).toAct as string;
|
||||
const legal = view(state, who).legal.map((l: { type: string }) => l.type);
|
||||
const t = ['check', 'call', 'half'].find((x) => legal.includes(x))!;
|
||||
state = applyAction('seotda', state, who, { type: t });
|
||||
}
|
||||
expect(view(state, null).handPhase).toBe('choose');
|
||||
expect(view(state, null).street).toBe(1);
|
||||
expect(helpNow(view(state, null), null, users)).toContain('패를 공개해요');
|
||||
|
||||
@@ -21,6 +21,7 @@ function who(players: Record<string, PublicUser>, id: string): string {
|
||||
/** Which betting round this is, in plain words. */
|
||||
function roundText(v: SeotdaView): string {
|
||||
const o = v.options;
|
||||
if (o.cardMode === 'three' && !v.threeCard) return '재경기는 2장 섯다로 해요. 2장을 한 번에 받고 한 번만 베팅한 뒤 남은 사람끼리 패를 공개해요.';
|
||||
if (o.cardMode === 'three')
|
||||
return v.street === 0
|
||||
? '2장을 받고 하는 첫 베팅이에요. 끝나면 1장을 더 받아 3장 중 쓸 2장을 골라요.'
|
||||
@@ -34,15 +35,15 @@ function roundText(v: SeotdaView): string {
|
||||
/** My current hand as the view gives it (hints option on). */
|
||||
function handLine(v: SeotdaView, seat: SeotdaSeatView): string {
|
||||
const h = v.myHand;
|
||||
if (!h) return seat.cards.length > 0 ? "이 방은 족보 이름을 따로 보여 주지 않아요. '족보 도우미'를 보고 내 패를 맞춰 보세요." : '';
|
||||
if (!h) return seat.cards.length > 0 ? "이 방은 족보 이름을 따로 보여 주지 않아요. 아래 '족보'판을 보고 내 패를 맞춰 보세요." : '';
|
||||
if (h.special) return h.hint;
|
||||
if (h.value === null) return `지금은 ${h.name}만 받았어요. ${h.hint}`;
|
||||
return `지금 내 족보: ${h.name}${h.strength ? `(${STRENGTH_KO[h.strength]})` : ''}. 족보 도우미에 '내 패'로 표시돼요.`;
|
||||
return `지금 내 족보: ${h.name}${h.strength ? `(${STRENGTH_KO[h.strength]})` : ''}. 아래 족보판에 보라색으로 표시돼요.`;
|
||||
}
|
||||
|
||||
function rematchLine(v: SeotdaView): string {
|
||||
if (v.rematchNo === 0 || !v.rematchReason) return '';
|
||||
return `재경기 ${v.rematchNo}회차(${REMATCH_KO[v.rematchReason]})예요. 판돈은 그대로 두고, 기본금은 다시 내지 않아요.`;
|
||||
return `재경기 ${v.rematchNo}회차(${REMATCH_KO[v.rematchReason]})예요. 판돈은 그대로 두고, 기본금은 다시 내지 않아요.${v.options.cardMode === 'three' ? ' 재경기는 2장 섯다로 해요(공개패 없음).' : ''}`;
|
||||
}
|
||||
|
||||
function resultLine(v: SeotdaView, players: Record<string, PublicUser>): string {
|
||||
@@ -65,7 +66,7 @@ function resultLine(v: SeotdaView, players: Record<string, PublicUser>): string
|
||||
|
||||
function waitingLine(v: SeotdaView, players: Record<string, PublicUser>): string {
|
||||
if (v.handPhase === 'betting') {
|
||||
const oneRound = v.options.cardMode === 'two' && v.options.dealMode === 'oneRound';
|
||||
const oneRound = !v.threeCard && (v.options.cardMode === 'three' || v.options.dealMode === 'oneRound');
|
||||
const round = oneRound ? '베팅' : v.street === 0 ? '첫 베팅' : '마지막 베팅';
|
||||
return v.toAct ? `${who(players, v.toAct)} 차례예요(${round}).` : '카드를 나눠 주는 중이에요.';
|
||||
}
|
||||
@@ -93,12 +94,19 @@ function myBetting(v: SeotdaView, seat: SeotdaSeatView): string {
|
||||
const lines = [`내 차례예요. ${roundText(v)}`];
|
||||
const hand = handLine(v, seat);
|
||||
if (hand) lines.push(hand);
|
||||
lines.push(`누를 수 있는 버튼: ${buttons.map((t) => `[${BET_KO[t]}]`).join(' ')}. 버튼 아래 적힌 금액이 바로 판돈에 들어가요. PC에서는 버튼 왼쪽 위 숫자 키(${buttons.map((t) => `${BET_KO[t]} ${BET_KEY[t]}`).join(', ')})로도 걸 수 있어요.`);
|
||||
lines.push(`누를 수 있는 버튼: ${buttons.map((t) => `[${BET_KO[t]}]`).join(' ')}. 버튼 아래 적힌 금액이 바로 판돈에 들어가요. PC에서는 버튼 왼쪽에 적힌 숫자 키(${buttons.map((t) => `${BET_KO[t]} ${BET_KEY[t]}`).join(', ')})로도 걸 수 있어요.`);
|
||||
const tips: string[] = [];
|
||||
if (v.forcedHalf) tips.push(`이 방은 베팅 규칙 ${v.options.betRule}이라 첫 베팅에서 앞쪽 사람은 [하프]나 [다이]만 할 수 있어요.`);
|
||||
if (v.forcedHalf)
|
||||
tips.push(
|
||||
v.options.betRule === 'free'
|
||||
? '3장 섯다 1구에서는 선이 [하프]나 [다이]만 할 수 있어요(한게임 방식).'
|
||||
: `이 방은 베팅 규칙 ${v.options.betRule}이라 첫 베팅에서 앞쪽 사람은 [하프]나 [다이]만 할 수 있어요.`,
|
||||
);
|
||||
if (v.threeCard && v.street === 0 && v.options.threeOpen && v.options.threePick === 'end' && !v.forcedHalf)
|
||||
tips.push('3장 섯다 1구에서는 [체크]를 할 수 없어요. 걸거나 다이해요.');
|
||||
const call = legal.get('call');
|
||||
if (call) tips.push(`앞사람이 걸었어요. [콜]은 그만큼(${won(call.amount)}) 맞추는 거예요.`);
|
||||
else if (legal.has('ping')) tips.push(`[체크]는 걸지 않고 넘기고, [삥]은 기본금만큼 ${won(v.baseUnit)}을 걸어요.`);
|
||||
else if (legal.has('ping')) tips.push(legal.has('check') ? `[체크]는 걸지 않고 넘기고, [삥]은 기본금만큼 ${won(v.baseUnit)}을 걸어요.` : `[삥]은 기본금만큼 ${won(v.baseUnit)}을 걸어요.`);
|
||||
if (!buttons.some((t) => RAISES.includes(t)) && seat.lastAction) tips.push('이번 라운드에 이미 한 번 해서 더 올릴 수는 없어요(올리기는 한 라운드에 한 번).');
|
||||
if (v.legal.some((l) => l.allIn)) tips.push('가진 금액이 모자라면 가진 만큼 다 내는 올인이 돼요.');
|
||||
tips.push('패가 약하면 [다이]로 이번 판을 포기할 수 있어요.');
|
||||
|
||||
@@ -3,126 +3,33 @@
|
||||
* 원은 이 방 안에서만 쓰는 놀이용 숫자다(§12): 진짜 돈과 바꿀 수 없고 방이 끝나면 사라진다.
|
||||
*/
|
||||
import { useState } from 'react';
|
||||
import type { SeotdaOptions, SeotdaView, SpecialKind } from '@bg/games/seotda';
|
||||
import type { SeotdaOptions, SeotdaView } from '@bg/games/seotda';
|
||||
import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/money';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { HWATU_CREDIT, HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||
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';
|
||||
import { helpNow } from './help';
|
||||
import { JokboTable } from './jokbo';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
/** Illustration card for the 족보표 (no rule code needed on the client). */
|
||||
function illus(month: number, special: boolean): HwatuInfo {
|
||||
const gwang = [1, 3, 8].includes(month);
|
||||
const kind: HwatuInfo['kind'] = special ? (gwang ? 'gwang' : 'yeol') : month === 8 ? 'pi' : 'tti';
|
||||
return {
|
||||
id: (month - 1) * 4 + (special ? 0 : 1),
|
||||
month,
|
||||
kind,
|
||||
...(kind === 'tti' ? { tti: 'plain' as const } : {}),
|
||||
name: `${month}월 ${special ? (gwang ? '광' : '열끗') : month === 8 ? '기러기' : '띠'}`,
|
||||
};
|
||||
}
|
||||
|
||||
const PLAY_MONEY_NOTICE = '여기 나오는 원과 판돈은 이 방 안에서만 쓰는 놀이용 숫자예요. 진짜 돈과는 아무 상관이 없고, 바꾸거나 주고받을 수 없으며 방이 끝나면 사라져요.';
|
||||
|
||||
// ---------------------------------------------------------------- 족보 도우미
|
||||
|
||||
interface JokboRow {
|
||||
name: string;
|
||||
cards: [number, boolean][];
|
||||
note: string;
|
||||
match: (value: number | null, special: SpecialKind | null) => boolean;
|
||||
/** 특수 족보 (numbered "특" like the 한게임 족보 list). */
|
||||
special?: boolean;
|
||||
}
|
||||
|
||||
function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
const v = (lo: number, hi = lo) => (x: number | null, sp: SpecialKind | null) => !sp && x !== null && x >= lo && x <= hi;
|
||||
const rows: JokboRow[] = [
|
||||
{ name: '38광땡', cards: [[3, true], [8, true]], note: '가장 센 패', match: v(1000) },
|
||||
...(o.gwangTtaeng === 'all'
|
||||
? [
|
||||
{ name: '18광땡', cards: [[1, true], [8, true]], note: '', match: v(990) } as JokboRow,
|
||||
{ name: '13광땡', cards: [[1, true], [3, true]], note: '', match: v(980) } as JokboRow,
|
||||
]
|
||||
: []),
|
||||
{ name: '장땡(10땡)', cards: [[10, true], [10, false]], note: '같은 달 두 장 중 최고', match: v(910) },
|
||||
{ name: '9땡 ~ 삥땡(1땡)', cards: [[9, true], [9, false]], note: '숫자가 클수록 셈', match: v(901, 909) },
|
||||
{ name: '알리', cards: [[1, true], [2, false]], note: '1 + 2', match: v(806) },
|
||||
{ name: '독사', cards: [[1, true], [4, false]], note: '1 + 4', match: v(805) },
|
||||
{ name: '구삥', cards: [[1, true], [9, false]], note: '1 + 9', match: v(804) },
|
||||
{ name: '장삥', cards: [[1, true], [10, false]], note: '1 + 10', match: v(803) },
|
||||
{ name: '장사', cards: [[4, false], [10, false]], note: '4 + 10', match: v(802) },
|
||||
{ name: '세륙', cards: [[4, false], [6, false]], note: '4 + 6', match: v(801) },
|
||||
{ name: '갑오(9끗)', cards: [[2, false], [7, false]], note: '두 달을 더한 일의 자리 9', match: v(9) },
|
||||
{ name: '8끗 ~ 1끗', cards: [[3, false], [5, false]], note: '일의 자리가 클수록 셈', match: v(1, 8) },
|
||||
{ name: '망통(0끗)', cards: [[2, false], [8, false]], note: '가장 약한 패', match: v(0) },
|
||||
];
|
||||
const sp = (k: SpecialKind) => (_x: number | null, s: SpecialKind | null) => s === k;
|
||||
if (o.ttaengjabi !== 'off')
|
||||
rows.push({
|
||||
name: '땡잡이',
|
||||
special: true,
|
||||
cards: [[3, true], [7, true]],
|
||||
note: `${o.ttaengjabi === 'strict' ? '3월 광 + 7월 열끗' : '3월 + 7월'}. 상대 최고가 1~9땡이면 이김, 아니면 망통`,
|
||||
match: sp('ttaengjabi'),
|
||||
});
|
||||
if (o.amhaeng) rows.push({ name: '암행어사', special: true, cards: [[4, true], [7, true]], note: '4·7월 열끗. 13·18광땡을 잡음, 아니면 1끗', match: sp('amhaeng') });
|
||||
if (o.gusa) {
|
||||
rows.push({ name: '구사', special: true, cards: [[4, false], [9, true]], note: '4 + 9. 상대가 알리 이하면 재경기, 아니면 3끗', match: sp('gusa') });
|
||||
if (o.mungGusa !== 'off') {
|
||||
const upTo = o.mungGusa === 'upTo9' ? '9땡' : o.mungGusa === 'upToJang' ? '장땡' : '8땡';
|
||||
rows.push({ name: '멍텅구리구사', special: true, cards: [[4, true], [9, true]], note: `4·9월 열끗. 상대가 ${upTo} 이하면 재경기`, match: sp('mungGusa') });
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function JokboTable({ options, mine }: { options: SeotdaOptions; mine?: SeotdaView['myHand'] }) {
|
||||
const rows = jokboRows(options);
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem' }}>
|
||||
<tbody>
|
||||
{rows.map((r, i) => {
|
||||
const hit = !!mine && options.hints && r.match(mine.value, mine.special);
|
||||
return (
|
||||
<tr
|
||||
key={r.name}
|
||||
style={{ background: hit ? 'color-mix(in srgb, #7c3aed 22%, transparent)' : undefined, borderBottom: '1px solid var(--border)' }}
|
||||
aria-current={hit ? 'true' : undefined}
|
||||
>
|
||||
<td style={{ padding: '3px 4px', fontWeight: 800, color: 'var(--text-sub)', width: 28, textAlign: 'right', whiteSpace: 'nowrap' }}>{r.special ? '특' : i + 1}</td>
|
||||
<td style={{ padding: '3px 2px', whiteSpace: 'nowrap' }}>
|
||||
{r.cards.map(([m, sp], j) => (
|
||||
<HwatuCard key={j} card={illus(m, sp)} width={30} showMonth={false} style={{ marginRight: 2 }} />
|
||||
))}
|
||||
</td>
|
||||
<td style={{ padding: '3px 6px' }}>
|
||||
<strong>{r.name}</strong>
|
||||
{hit && (
|
||||
<span className="sd-tag" style={{ background: '#7c3aed', color: '#fff', marginLeft: 4, borderRadius: 999, padding: '0 7px', fontSize: '.74rem', fontWeight: 800 }}>
|
||||
내 패
|
||||
</span>
|
||||
)}
|
||||
{r.note && <div className="small muted">{r.note}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side panel
|
||||
|
||||
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 (
|
||||
<>
|
||||
@@ -156,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) => (
|
||||
@@ -181,15 +88,11 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보 도우미</summary>
|
||||
<JokboTable options={v.options} mine={v.myHand} />
|
||||
</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})` : ''}
|
||||
@@ -202,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>
|
||||
@@ -216,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">
|
||||
@@ -448,7 +351,7 @@ function Rules({ options }: { options?: SeotdaOptions }) {
|
||||
<strong>진행</strong>: 판마다 모두 <strong>기본금</strong>을 판돈에 내요. 선부터 패를 받고 차례로 베팅해요.
|
||||
{o?.cardMode === 'three'
|
||||
? o.threeOpen && o.threePick === 'end'
|
||||
? ' 3장 섯다(한게임)는 2장을 받아 그중 1장을 골라 모두에게 보여 주고(공개패) → 첫 베팅 → 1장을 더 받아 → 마지막 베팅 → 3장 중 쓸 2장을 골라 공개해요. 버린 1장은 공개패가 아니면 끝까지 아무도 못 봐요.'
|
||||
? ' 3장 섯다(한게임)는 2장을 받아 그중 1장을 골라 모두에게 보여 주고(공개패) → 1구 베팅 → 1장을 더 받아(밀어 올려 확인하는 패쪼기) → 2구 베팅 → 3장 중 쓸 2장을 골라 공개해요. 1구에서는 선이 하프나 다이만 할 수 있고, 체크는 없어요. 버린 1장은 공개패가 아니면 끝까지 아무도 못 봐요. 족보판의 [예상족보]를 켜면 다음 패로 만들 수 있는 족보만 밝게 보여요.'
|
||||
: ` 3장 섯다는 2장을 받고${o.threeOpen ? ' 1장을 골라 모두에게 보여 준 뒤' : ''} 베팅 → 1장을 더 받아 ${o.threePick === 'end' ? '마지막 베팅 → 3장 중 쓸 2장을 골라 공개해요' : '3장 중 쓸 2장을 몰래 고르고 → 마지막 베팅 후 공개해요'}. 버린 1장은 끝까지 아무도 못 봐요.`
|
||||
: o?.dealMode === 'twoRounds'
|
||||
? ' 1장 받고 베팅, 1장 더 받고 베팅한 뒤 남은 사람끼리 패를 공개해요.'
|
||||
@@ -467,6 +370,7 @@ function Rules({ options }: { options?: SeotdaOptions }) {
|
||||
<JokboTable options={o ?? ({ gwangTtaeng: 'all', ttaengjabi: 'loose', amhaeng: true, gusa: true, mungGusa: 'upTo9', hints: false } as SeotdaOptions)} />
|
||||
<p>
|
||||
<strong>재경기</strong>: 구사나 같은 족보{o?.tieRule === 'split' ? '(이 방은 같은 족보면 나눠 가져요)' : ''}로 재경기가 되면 판돈은 그대로 두고 남은 사람끼리 새로 패를 받아요. 기본금은 다시 내지 않아요.
|
||||
{o?.cardMode === 'three' ? ' 3장 섯다 방이어도 재경기는 2장 섯다로 해요: 2장을 한 번에 받고(공개패 없음) 한 번만 베팅한 뒤 공개해요.' : ''}
|
||||
{o && o.rejoinCost !== 'none' ? ` 구사 재경기 때 다이한 사람은 판돈의 ${o.rejoinCost === 'half' ? '절반' : '전부'}만큼 내고 다시 들어올 수 있어요.` : ''} 한 판에서 재경기가{' '}
|
||||
{o?.maxRematches ?? 3}번을 넘으면 나눠 가져요.
|
||||
</p>
|
||||
|
||||
170
apps/web/src/games/seotda/jokbo.tsx
Normal file
170
apps/web/src/games/seotda/jokbo.tsx
Normal file
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* 섯다 족보 (docs/games/seotda.md §3): the rows for the current room rules, the full table (규칙 화면) and the compact
|
||||
* 족보판 at the left of the bottom bar (한게임 섯다처럼 3열 목록 + 고른 족보 설명).
|
||||
*/
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { SeotdaOptions, SeotdaView, SpecialKind } from '@bg/games/seotda';
|
||||
import { HwatuCard, type HwatuInfo } from '../../components/cards/HwatuCard';
|
||||
|
||||
/** Illustration card for the 족보표 (no rule code needed on the client). */
|
||||
export function illus(month: number, special: boolean): HwatuInfo {
|
||||
const gwang = [1, 3, 8].includes(month);
|
||||
const kind: HwatuInfo['kind'] = special ? (gwang ? 'gwang' : 'yeol') : month === 8 ? 'pi' : 'tti';
|
||||
return {
|
||||
id: (month - 1) * 4 + (special ? 0 : 1),
|
||||
month,
|
||||
kind,
|
||||
...(kind === 'tti' ? { tti: 'plain' as const } : {}),
|
||||
name: `${month}월 ${special ? (gwang ? '광' : '열끗') : month === 8 ? '기러기' : '띠'}`,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
export interface JokboRow {
|
||||
name: string;
|
||||
/** Short label for the compact 족보 board under the table. */
|
||||
short: string;
|
||||
cards: [number, boolean][];
|
||||
note: string;
|
||||
match: (value: number | null, special: SpecialKind | null) => boolean;
|
||||
/** 특수 족보 (numbered "특" like the 한게임 족보 list). */
|
||||
special?: boolean;
|
||||
}
|
||||
|
||||
export function jokboRows(o: SeotdaOptions): JokboRow[] {
|
||||
const v = (lo: number, hi = lo) => (x: number | null, sp: SpecialKind | null) => !sp && x !== null && x >= lo && x <= hi;
|
||||
const rows: JokboRow[] = [
|
||||
{ name: '38광땡', short: '38광땡', cards: [[3, true], [8, true]], note: '가장 센 패', match: v(1000) },
|
||||
...(o.gwangTtaeng === 'all'
|
||||
? [
|
||||
{ name: '18광땡', short: '18광땡', cards: [[1, true], [8, true]], note: '1월 광 + 8월 광', match: v(990) } as JokboRow,
|
||||
{ name: '13광땡', short: '13광땡', cards: [[1, true], [3, true]], note: '1월 광 + 3월 광', match: v(980) } as JokboRow,
|
||||
]
|
||||
: []),
|
||||
{ name: '장땡(10땡)', short: '장땡', cards: [[10, true], [10, false]], note: '같은 달 두 장 중 최고', match: v(910) },
|
||||
{ name: '9땡 ~ 삥땡(1땡)', short: '9~1땡', cards: [[9, true], [9, false]], note: '숫자가 클수록 셈', match: v(901, 909) },
|
||||
{ name: '알리', short: '알리', cards: [[1, true], [2, false]], note: '1 + 2', match: v(806) },
|
||||
{ name: '독사', short: '독사', cards: [[1, true], [4, false]], note: '1 + 4', match: v(805) },
|
||||
{ name: '구삥', short: '구삥', cards: [[1, true], [9, false]], note: '1 + 9', match: v(804) },
|
||||
{ name: '장삥', short: '장삥', cards: [[1, true], [10, false]], note: '1 + 10', match: v(803) },
|
||||
{ name: '장사', short: '장사', cards: [[4, false], [10, false]], note: '4 + 10', match: v(802) },
|
||||
{ name: '세륙', short: '세륙', cards: [[4, false], [6, false]], note: '4 + 6', match: v(801) },
|
||||
{ name: '갑오(9끗)', short: '갑오', cards: [[2, false], [7, false]], note: '두 달을 더한 일의 자리 9', match: v(9) },
|
||||
{ name: '8끗 ~ 1끗', short: '8~1끗', cards: [[3, false], [5, false]], note: '일의 자리가 클수록 셈', match: v(1, 8) },
|
||||
{ name: '망통(0끗)', short: '망통', cards: [[2, false], [8, false]], note: '가장 약한 패', match: v(0) },
|
||||
];
|
||||
const sp = (k: SpecialKind) => (_x: number | null, s: SpecialKind | null) => s === k;
|
||||
if (o.ttaengjabi !== 'off')
|
||||
rows.push({
|
||||
name: '땡잡이',
|
||||
short: '땡잡이',
|
||||
special: true,
|
||||
cards: [[3, true], [7, true]],
|
||||
note: `${o.ttaengjabi === 'strict' ? '3월 광 + 7월 열끗' : '3월 + 7월'}. 상대 최고가 1~9땡이면 이김, 아니면 망통`,
|
||||
match: sp('ttaengjabi'),
|
||||
});
|
||||
if (o.amhaeng) rows.push({ name: '암행어사', short: '암행어사', special: true, cards: [[4, true], [7, true]], note: '4·7월 열끗. 13·18광땡을 잡음, 아니면 1끗', match: sp('amhaeng') });
|
||||
if (o.gusa) {
|
||||
rows.push({ name: '구사', short: '구사', special: true, cards: [[4, false], [9, true]], note: '4 + 9. 상대가 알리 이하면 재경기, 아니면 3끗', match: sp('gusa') });
|
||||
if (o.mungGusa !== 'off') {
|
||||
const upTo = o.mungGusa === 'upTo9' ? '9땡' : o.mungGusa === 'upToJang' ? '장땡' : '8땡';
|
||||
rows.push({ name: '멍텅구리구사', short: '멍구사', special: true, cards: [[4, true], [9, true]], note: `4·9월 열끗. 상대가 ${upTo} 이하면 재경기`, match: sp('mungGusa') });
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function JokboTable({ options, mine }: { options: SeotdaOptions; mine?: SeotdaView['myHand'] }) {
|
||||
const rows = jokboRows(options);
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '0.88rem' }}>
|
||||
<tbody>
|
||||
{rows.map((r, i) => {
|
||||
const hit = !!mine && options.hints && r.match(mine.value, mine.special);
|
||||
return (
|
||||
<tr
|
||||
key={r.name}
|
||||
style={{ background: hit ? 'color-mix(in srgb, #7c3aed 22%, transparent)' : undefined, borderBottom: '1px solid var(--border)' }}
|
||||
aria-current={hit ? 'true' : undefined}
|
||||
>
|
||||
<td style={{ padding: '3px 4px', fontWeight: 800, color: 'var(--text-sub)', width: 28, textAlign: 'right', whiteSpace: 'nowrap' }}>{r.special ? '특' : i + 1}</td>
|
||||
<td style={{ padding: '3px 2px', whiteSpace: 'nowrap' }}>
|
||||
{r.cards.map(([m, sp], j) => (
|
||||
<HwatuCard key={j} card={illus(m, sp)} width={30} showMonth={false} style={{ marginRight: 2 }} />
|
||||
))}
|
||||
</td>
|
||||
<td style={{ padding: '3px 6px' }}>
|
||||
<strong>{r.name}</strong>
|
||||
{hit && (
|
||||
<span className="sd-tag" style={{ background: '#7c3aed', color: '#fff', marginLeft: 4, borderRadius: 999, padding: '0 7px', fontSize: '.74rem', fontWeight: 800 }}>
|
||||
내 패
|
||||
</span>
|
||||
)}
|
||||
{r.note && <div className="small muted">{r.note}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact 족보판 (bottom-left of the table, like 한게임 섯다): every hand in 3 columns, my current hand lit up (when
|
||||
* hints are on); the line below explains the selected hand (my hand by default, or the one clicked).
|
||||
*/
|
||||
export function JokboBoard({ options, mine, reach }: { options: SeotdaOptions; mine: SeotdaView['myHand']; reach?: SeotdaView['myReach'] }) {
|
||||
const rows = jokboRows(options);
|
||||
// 예상족보 (한게임처럼 켜고 끌 수 있음): rows my next card can still make stay bright, the rest fade.
|
||||
const [outlook, setOutlook] = useState(true);
|
||||
const can = reach && outlook ? (r: JokboRow) => reach.some((x) => r.match(x.value, x.special)) : null;
|
||||
const hitIdx = mine && options.hints ? rows.findIndex((r) => r.match(mine.value, mine.special)) : -1;
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
useEffect(() => setSel(null), [hitIdx]);
|
||||
const shown = rows[sel ?? (hitIdx >= 0 ? hitIdx : 0)]!;
|
||||
let n = 0;
|
||||
return (
|
||||
<section className="sd-jokbo" aria-label="족보">
|
||||
<h3>
|
||||
족보
|
||||
{reach && (
|
||||
<button type="button" className={`sd-outlook${outlook ? ' on' : ''}`} aria-pressed={outlook} onClick={() => setOutlook(!outlook)} title="다음 패로 만들 수 있는 족보만 밝게 보여요">
|
||||
예상족보 {outlook ? '켬' : '끔'}
|
||||
</button>
|
||||
)}
|
||||
</h3>
|
||||
<ol style={{ gridTemplateRows: `repeat(${Math.ceil(rows.length / 3)}, auto)` }}>
|
||||
{rows.map((r, i) => {
|
||||
const label = r.special ? `*${r.short}` : `${++n}.${r.short}`;
|
||||
return (
|
||||
<li key={r.name}>
|
||||
<button
|
||||
type="button"
|
||||
className={`${i === hitIdx ? 'hit' : ''}${shown === r ? ' sel' : ''}${can && !can(r) ? ' no' : ''}`}
|
||||
aria-pressed={shown === r}
|
||||
aria-current={i === hitIdx ? 'true' : undefined}
|
||||
title={`${r.name}${r.note ? `: ${r.note}` : ''}${can ? (can(r) ? ' (다음 패로 만들 수 있어요)' : ' (다음 패로는 못 만들어요)') : ''}`}
|
||||
onClick={() => setSel(sel === i ? null : i)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
<div className="sd-jokbo-desc" aria-live="polite">
|
||||
<span className="pics" aria-hidden>
|
||||
{shown.cards.map(([m, sp], j) => (
|
||||
<HwatuCard key={j} card={illus(m, sp)} width={22} showMonth={false} />
|
||||
))}
|
||||
</span>
|
||||
<span>
|
||||
<strong>{shown.name}</strong>
|
||||
{shown.note ? ` ${shown.note}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user