Compare commits
36 Commits
ca8baf5cc8
...
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 |
11
README.md
11
README.md
@@ -5,13 +5,14 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (40개)
|
||||
## 게임 (46개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
@@ -19,10 +20,10 @@
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 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();
|
||||
|
||||
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
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) => {
|
||||
|
||||
@@ -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';
|
||||
@@ -102,6 +103,9 @@ export function createHttpApp(d: HttpDeps) {
|
||||
});
|
||||
});
|
||||
|
||||
// 라이어 게임 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 }));
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,6 +115,11 @@ export const LUCK_BUDGET_MS = 1500;
|
||||
const ERROR_LIMIT = 3;
|
||||
/** Streaming actions (drawing) are logged in batches: at most this long between snapshot writes. */
|
||||
const STREAM_FLUSH_MS = 1000;
|
||||
/**
|
||||
* Longest a player's clock waits for their screen to finish animating a change (ms at game speed ×1 before the
|
||||
* shared 1.5× slowdown; scaled like the animations). A screen that never reports (an old tab, a hidden tab) costs at most this.
|
||||
*/
|
||||
export const REVEAL_MAX_MS = 10_000;
|
||||
|
||||
export class Room {
|
||||
status: 'lobby' | 'playing' | 'finished' | 'paused' | 'broken' = 'lobby';
|
||||
@@ -154,6 +159,15 @@ export class Room {
|
||||
/** When each person last said they were typing (to drop repeats within a second). */
|
||||
private typingAt = new Map<string, number>();
|
||||
private consecutiveErrors = 0;
|
||||
/**
|
||||
* The last game state change and when each player's screen finished animating it (client `settled`). A player's
|
||||
* clock starts then, so a choice shown after the animation still gets its full time (`revealExtra`).
|
||||
*/
|
||||
private reveal: { seq: number; at: number; done: Map<string, number>; key: string } | null = null;
|
||||
/** The deadline last sent to the clients (state / deadline messages), so a moved deadline is always told. */
|
||||
private sentDeadline: number | null = null;
|
||||
/** Players whose screens report `settled` (pages from before 2026-11-08 don't: their clocks run as before). */
|
||||
private settles = new Set<string>();
|
||||
private readonly now: () => number;
|
||||
/** Plays the computer players' moves (docs/06 §12). */
|
||||
readonly bots: BotDriver;
|
||||
@@ -462,7 +476,7 @@ export class Room {
|
||||
view,
|
||||
events: [],
|
||||
active: this.game.finished ? [] : def.activePlayers(this.game.state),
|
||||
deadline: this.game.finished ? null : this.effectiveDeadline(),
|
||||
deadline: (this.sentDeadline = this.game.finished ? null : this.publicDeadline()),
|
||||
...(cs !== undefined ? { cs } : {}),
|
||||
};
|
||||
}
|
||||
@@ -474,6 +488,10 @@ export class Room {
|
||||
|
||||
private broadcastState(events: unknown[], actor?: string, cs?: number): void {
|
||||
if (!this.game) return;
|
||||
// A change that leaves the step as it was (a chat line, a move inside the same shared clock) keeps the time
|
||||
// already given for the step's animation; a new step (new clock, new players to act) starts a new reveal.
|
||||
const key = this.revealKey();
|
||||
if (!this.reveal || this.reveal.key !== key) this.reveal = { seq: this.seq, at: this.now(), done: new Map(), key };
|
||||
let spectatorMsg: ServerMessage | null = null;
|
||||
for (const c of this.conns.values()) {
|
||||
let msg: ServerMessage | null;
|
||||
@@ -904,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 };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1127,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;
|
||||
@@ -1138,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;
|
||||
@@ -1182,7 +1254,7 @@ export class Room {
|
||||
const timed = def.timeoutPlayers ? def.timeoutPlayers(g.state) : def.activePlayers(g.state);
|
||||
const graceMs = def.disconnectGraceMs?.(g.state) ?? this.config.graceSec * 1000;
|
||||
for (const u of timed) {
|
||||
let d = base;
|
||||
let d = base === null ? null : base + this.clockExtra(u);
|
||||
const p = this.presence.get(u);
|
||||
if (p && !p.connected) {
|
||||
const grace = p.since + graceMs;
|
||||
|
||||
115
apps/server/src/rooms/shisen.room.test.ts
Normal file
115
apps/server/src/rooms/shisen.room.test.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/** 사천성 through a real Room: a practice race against a computer to the end, away players (docs/games/shisen.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { findPair, type ShisenState, type ShisenView } from '@bg/games/shisen';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as ShisenView;
|
||||
|
||||
function twoPlayers(timeLimitSec: number | null) {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'shisen', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { size: 'small', hints: true, timeLimitSec } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { h, room, a, b, s: () => room.game!.state as ShisenState };
|
||||
}
|
||||
|
||||
describe('사천성 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 2초마다 한 쌍씩 없애다 1분 뒤 포기하고, 컴퓨터는 자기 판을 끝까지 풀어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'shisen') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let removed = 0;
|
||||
const s = () => room.game!.state as ShisenState;
|
||||
for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const p = findPair(v.board.cells, v.board.rows, v.board.cols);
|
||||
if (p) {
|
||||
room.act('A', ++cs, { type: 'pair', a: p[0], b: p[1] });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().boards.A!.removed).toBe(removed);
|
||||
expect(removed).toBeGreaterThan(20);
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id)).toEqual([bot, 'A']);
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const { h, room, b, s } = twoPlayers(300);
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const { h, room, b, s } = twoPlayers(null);
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.ranking.map((r) => r.status)).toEqual(['done', 'done']);
|
||||
});
|
||||
});
|
||||
121
apps/server/src/rooms/solitaire.room.test.ts
Normal file
121
apps/server/src/rooms/solitaire.room.test.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
/** 솔리테어 through a real Room: a practice race against a computer, hidden cards never reach my screen, away players (docs/games/solitaire.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { legalOn, type SolitaireState, type SolitaireView } from '@bg/games/solitaire';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as SolitaireView;
|
||||
|
||||
function twoPlayers(h: ReturnType<typeof harness>, options: Record<string, unknown>) {
|
||||
const r = h.manager.create('A', 'solitaire', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { room, a, b, s: () => room.game!.state as SolitaireState };
|
||||
}
|
||||
|
||||
describe('solitaire · 솔리테어 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 2초마다 한 수, 1분 뒤 포기하고 컴퓨터는 끝까지 가요. 내 화면에는 뒤집힌 카드와 더미가 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'solitaire') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let moves = 0;
|
||||
const s = () => room.game!.state as SolitaireState;
|
||||
for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
|
||||
if (playing) {
|
||||
const b = s().boards.A!;
|
||||
const json = JSON.stringify(v);
|
||||
for (const c of [...b.stock, ...b.t.flatMap((col, k) => col.slice(0, b.down[k]))]) expect(json).not.toContain(`"${c}"`);
|
||||
}
|
||||
if (i % 8 === 0 && playing) {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const legal = legalOn(v.board!).filter((m) => m.type !== 'undo' && m.type !== 'auto');
|
||||
const m = legal.find((x) => x.type === 'move' && x.to === 'f') ?? legal.find((x) => x.type === 'draw') ?? legal[0];
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
moves++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(moves).toBeGreaterThan(10);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().boards[bot]!.hist.length).toBeGreaterThan(0);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayers(h, { mode: 'spider', draw: 1, suits: 2, timeLimitSec: 600 });
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const { room, b, s } = twoPlayers(h, { mode: 'freecell', draw: 1, suits: 1, timeLimitSec: null });
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
126
apps/server/src/rooms/sudoku.room.test.ts
Normal file
126
apps/server/src/rooms/sudoku.room.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/** 스도쿠 through a real Room: a practice race against a computer, the solution never reaches my screen, away players (docs/games/sudoku.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { SudokuState, SudokuView } from '@bg/games/sudoku';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as SudokuView;
|
||||
|
||||
describe('sudoku room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 맞는 숫자를 하나씩 넣고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 다 풀기 전 내 화면에는 정답이 없어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'sudoku') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
for (let i = 0; i < 4 * 1900 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing';
|
||||
if (playing) {
|
||||
expect(v.board!.solution).toBeUndefined();
|
||||
expect(JSON.stringify(v)).not.toContain(s().puzzle.solution);
|
||||
}
|
||||
// The person fills the first empty cell with the right number every 2 s.
|
||||
if (i % 8 === 0 && playing) {
|
||||
const k = v.board!.values.indexOf('0');
|
||||
if (k >= 0) room.act('A', ++cs, { type: 'set', i: k, n: Number(s().puzzle.solution[k]) });
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().status.A).toBe('solved');
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
expect(lastView(a).board!.solution).toBe(s().puzzle.solution);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'sudoku', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { difficulty: 'easy', hints: true, timeLimitSec: 600 } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'sudoku', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { difficulty: 'normal', hints: false, timeLimitSec: null } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as SudokuState;
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
h.clock.advance(60_000);
|
||||
room.onTimer();
|
||||
expect(s().status.A).toBe('playing');
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
});
|
||||
159
apps/server/src/rooms/typing.room.test.ts
Normal file
159
apps/server/src/rooms/typing.room.test.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
/** 타자 대결 through a real Room: progress streams, a practice game against a computer, away players (docs/games/typing.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { TypingState, TypingView } from '@bg/games/typing';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as TypingView;
|
||||
|
||||
function twoPlayers(options: Record<string, unknown>) {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'typing', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, ...options } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { h, room, a, b, s: () => room.game!.state as TypingState };
|
||||
}
|
||||
|
||||
describe('타자 대결 room flow', () => {
|
||||
test('연습: 먼저 다 친 사람이 방을 나가도 남은 사람은 끝까지 쳐요', () => {
|
||||
const { h, room, b, s } = twoPlayers({ mode: 'practice', category: 'word' });
|
||||
const typeAll = (who: string) => {
|
||||
const n = s().items.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
h.clock.advance(3000);
|
||||
room.act(who, 100 + i, { type: 'submit', item: i, text: s().items[i]! });
|
||||
}
|
||||
};
|
||||
typeAll('A');
|
||||
expect(s().rs.A!.finishedAt).not.toBeNull();
|
||||
room.leave('A');
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(lastView(b).upcoming[0]!.idx).toBe(0);
|
||||
typeAll('B');
|
||||
expect(b.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(s().phase).toBe('ended');
|
||||
expect(s().final!.ranking[0]).toMatchObject({ id: 'B', left: false });
|
||||
});
|
||||
|
||||
test('진행은 stream으로만 가고(보기 다시 계산 없음), 먼저 정확하게 친 사람이 점수를 얻어요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ rounds: 1 });
|
||||
const v = lastView(b);
|
||||
expect(v.phase).toBe('playing');
|
||||
const item = v.upcoming[0]!;
|
||||
// A paste the moment the text appears is refused.
|
||||
room.act('B', 1, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect((b.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string }).reason).toContain('너무 빨라요');
|
||||
const states = b.msgs.filter((m) => m.t === 'state').length;
|
||||
h.clock.advance(1500);
|
||||
room.act('A', 1, { type: 'progress', item: item.idx, text: item.text.slice(0, 2) });
|
||||
const stream = b.msgs.filter((m) => m.t === 'stream').at(-1) as Extract<ServerMessage, { t: 'stream' }>;
|
||||
expect(stream.events).toEqual([expect.objectContaining({ type: 'progress', player: 'A', item: item.idx })]);
|
||||
expect(b.msgs.filter((m) => m.t === 'state').length).toBe(states);
|
||||
h.clock.advance(3000);
|
||||
room.act('A', 2, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect(a.msgs.filter((m) => m.t === 'reject').map((m) => JSON.stringify(m))).toEqual([]);
|
||||
expect(s().totals.A!.points).toBe(1);
|
||||
expect(lastView(b).last).toMatchObject({ winner: 'A', text: item.text });
|
||||
// The next item opens after the gap, from the server clock.
|
||||
expect(lastView(b).upcoming).toEqual([]);
|
||||
h.clock.advance(1500);
|
||||
room.onTimer();
|
||||
expect(lastView(b).upcoming[0]!.idx).toBe(1);
|
||||
});
|
||||
|
||||
test('컴퓨터와 연습(타수 비교): 사람도 컴퓨터도 끝까지 치고, 거절 없이 끝나요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'typing') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, mode: 'speed', rounds: 1 } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
for (let i = 0; i < 4 * 400 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
// The person sends a line every 6 seconds, read from their own screen.
|
||||
const v = lastView(a);
|
||||
const me = v.seats.find((x) => x.id === 'A')!;
|
||||
if (i % 24 === 23 && v.phase === 'playing' && !me.finished && v.upcoming[0]) room.act('A', ++cs, { type: 'submit', item: v.upcoming[0].idx, text: v.upcoming[0].text });
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as TypingState;
|
||||
expect(s.totals.A!.keys).toBeGreaterThan(0);
|
||||
expect(s.totals[bot]!.keys).toBeGreaterThan(0);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('서바이벌 문장별(무제한은 자동 시간으로): 끊긴 사람을 기다리지 않고, 먼저 친 사람이 남아 이겨요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ mode: 'survival', elimination: 'sentence', timeLimit: null, rounds: 1 });
|
||||
// 서바이벌 always has a clock (무제한 plays as 자동).
|
||||
expect(s().curEndsAt).not.toBeNull();
|
||||
room.disconnect(b);
|
||||
const item = lastView(a).upcoming[0]!;
|
||||
h.clock.advance(4000);
|
||||
room.act('A', 1, { type: 'submit', item: item.idx, text: item.text });
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().rs.B!.outReason).toBe('slowest');
|
||||
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
|
||||
});
|
||||
|
||||
test('타수 비교 무제한: 끊긴 사람은 유예 뒤 친 데까지로 멈추고, 다음 타이머는 없어요', () => {
|
||||
const { h, room, a, b, s } = twoPlayers({ mode: 'speed', timeLimit: null, rounds: 1 });
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
expect(d).toBeGreaterThan(h.clock.now());
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().rs.B!.finishedAt).not.toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
let cs = 0;
|
||||
while (!room.game!.finished) {
|
||||
const v = lastView(a);
|
||||
h.clock.advance(5000);
|
||||
room.act('A', ++cs, { type: 'submit', item: v.upcoming[0]!.idx, text: v.upcoming[0]!.text });
|
||||
}
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs } from '../../lib/motion';
|
||||
|
||||
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
|
||||
const ROWS = 10;
|
||||
@@ -553,16 +553,17 @@ function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
|
||||
<small>합이 10이 되게 사과를 묶어요!</small>
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
|
||||
{/* My final count shows after the last apples have popped. */}
|
||||
<AfterMotion when={!!mine && mine.status === 'stuck' && v.phase === 'playing'}>
|
||||
<div className="ap-over note" role="status">
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개{extraText(mine)} · 끝날 때까지 기다려요
|
||||
더 지울 수 있는 사과가 없어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
{mine && mine.status === 'done' && v.phase === 'playing' && (
|
||||
</AfterMotion>
|
||||
<AfterMotion when={!!mine && mine.status === 'done' && v.phase === 'playing'}>
|
||||
<div className="ap-over note" role="status">
|
||||
여기까지 했어요! 사과 {mine.score}개{extraText(mine)} · 모두 끝날 때까지 기다려요
|
||||
여기까지 했어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 모두 끝날 때까지 기다려요
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
|
||||
</div>
|
||||
@@ -635,22 +636,24 @@ function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
{extraText(r)}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
|
||||
{extraText(r)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -756,6 +759,7 @@ const ui: GameUI<AppleView, AppleOptions> = {
|
||||
Board: AppleBoard,
|
||||
Side: AppleSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -10,7 +10,7 @@ import { reducedMotion, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
type Color = 'black' | 'white';
|
||||
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
||||
@@ -160,6 +160,9 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
|
||||
// Counting starts / the game ends (for both players and watchers).
|
||||
const prevPhase = useRef(v.phase);
|
||||
// The winner banner waits for the territory marks to finish popping in (held, so the result window waits too).
|
||||
const [endWait, setEndWait] = useState(false);
|
||||
useMotionHold(endWait);
|
||||
useEffect(() => {
|
||||
const before = prevPhase.current;
|
||||
prevPhase.current = v.phase;
|
||||
@@ -168,8 +171,21 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
showBanner('계가', 'blue', '두 사람 모두 패스했어요. 사석을 확인해요');
|
||||
sfx.whoosh();
|
||||
} else if (v.phase === 'finished' && v.result) {
|
||||
const w = v.result.winner;
|
||||
showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', v.result.summaryKo);
|
||||
const r = v.result;
|
||||
const w = r.winner;
|
||||
setEndWait(true);
|
||||
// Marks pop in staggered from the corner (up to 0.9 s) and take 0.32 s each.
|
||||
const t = setTimeout(
|
||||
() => {
|
||||
setEndWait(false);
|
||||
showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', r.summaryKo);
|
||||
},
|
||||
r.score && !reducedMotion() ? fxMs(1250) : 0,
|
||||
);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
setEndWait(false);
|
||||
};
|
||||
}
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -490,7 +506,7 @@ function ScoreTable({ score, heading }: { score: ScoreBreakdown; heading?: boole
|
||||
);
|
||||
}
|
||||
|
||||
function ScoringPanel({ view: v, act, pending }: { view: BadukView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function ScoringPanel({ view: v, act, pending, deadline }: { view: BadukView; act: (a: unknown) => void; pending: boolean; deadline: number | null }) {
|
||||
const [confirmResume, setConfirmResume] = useState(false);
|
||||
const sc = v.scoring!;
|
||||
const p = sc.preview;
|
||||
@@ -500,7 +516,7 @@ function ScoringPanel({ view: v, act, pending }: { view: BadukView; act: (a: unk
|
||||
<div className="card stack" style={{ padding: 14, gap: 10 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong style={{ fontSize: '1.1rem' }}>사석 확인</strong>
|
||||
<TurnTimer deadline={sc.deadlineAt} totalMs={sc.durationMs} mine={!!mine && !sc.agreed[mine]} size={40} />
|
||||
<TurnTimer deadline={sc.deadlineAt === null ? null : Math.max(sc.deadlineAt, deadline ?? sc.deadlineAt)} totalMs={sc.durationMs} mine={!!mine && !sc.agreed[mine]} size={40} />
|
||||
</div>
|
||||
<p className="small" style={{ margin: 0 }}>
|
||||
대국이 멈췄어요. 판 위의 <strong>죽은 돌</strong>을 눌러 ✕ 표시를 맞춘 뒤 두 사람 모두 <strong>동의</strong>하면 계가가 끝나요. 처음 표시는 컴퓨터의 추정이라 틀릴 수 있어요.
|
||||
@@ -566,18 +582,25 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
<strong>상대가 패스했어요.</strong> 끝내려면 나도 패스하세요. 더 둘 곳이 있으면 계속 둬도 돼요.
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'scoring' && <ScoringPanel view={v} act={act} pending={pending} />}
|
||||
{/* The counted score and the result show once the 계가 banner / territory marks / winner banner have played. */}
|
||||
{v.phase === 'scoring' && (
|
||||
<AfterMotion>
|
||||
<ScoringPanel view={v} act={act} pending={pending} deadline={deadline} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.phase === 'finished' && v.result?.score && (
|
||||
<div className="card stack" style={{ padding: 14, gap: 8 }}>
|
||||
<strong style={{ fontSize: '1.15rem' }}>{v.result.summaryKo}</strong>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 800, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<span className="sr-only">{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`}</span>
|
||||
<span aria-hidden>
|
||||
흑 <CountUp to={v.result.score.black.total} live={ended.current.live} /> : 백 <CountUp to={v.result.score.white.total} live={ended.current.live} />
|
||||
</span>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ padding: 14, gap: 8 }}>
|
||||
<strong style={{ fontSize: '1.15rem' }}>{v.result.summaryKo}</strong>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 800, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<span className="sr-only">{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`}</span>
|
||||
<span aria-hidden>
|
||||
흑 <CountUp to={v.result.score.black.total} live={ended.current.live} /> : 백 <CountUp to={v.result.score.white.total} live={ended.current.live} />
|
||||
</span>
|
||||
</div>
|
||||
<ScoreTable score={v.result.score} heading />
|
||||
</div>
|
||||
<ScoreTable score={v.result.score} heading />
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.phase === 'playing' && v.myColor && (
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
@@ -685,6 +708,8 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView;
|
||||
const c = v.clock;
|
||||
const elapsed = active ? Math.max(0, now - c.turnStartedAt) : 0;
|
||||
const mine = id === me;
|
||||
// The capture count goes up once the captured stones have been lifted off the board.
|
||||
const captures = useAfterMotionValue(v.captures[color]);
|
||||
let clock: React.ReactNode = null;
|
||||
let periodSecLeft: number | null = null;
|
||||
if (c.kind === 'byoyomi') {
|
||||
@@ -742,7 +767,7 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView;
|
||||
{mine && <span className="muted small"> (나)</span>}
|
||||
</div>
|
||||
<div className="muted small">
|
||||
{COLOR_KO[color]} · 따낸 돌 {v.captures[color]}
|
||||
{COLOR_KO[color]} · 따낸 돌 {captures}
|
||||
{color === 'white' && v.rules.komi ? ` · 덤 ${v.rules.komi}` : ''}
|
||||
{active ? ' · 두는 중' : ''}
|
||||
{v.phase === 'scoring' && v.scoring?.agreed[color] ? ' · 동의함' : ''}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- names (display names live only here, docs §12)
|
||||
|
||||
@@ -295,7 +295,8 @@ function CardFaceInner({ card, info }: { card: CardFace; info: (typeof CARD_INFO
|
||||
}
|
||||
|
||||
function Hp({ life, max }: { life: number; max: number }) {
|
||||
const n = Math.max(0, life);
|
||||
// Life changes once the shot / beer that caused it has played.
|
||||
const n = Math.max(0, useAfterMotionValue(life));
|
||||
return (
|
||||
<span className="bg-hp" role="img" aria-label={`생명 ${n}/${max}`}>
|
||||
{Array.from({ length: max }, (_, i) => (
|
||||
@@ -373,6 +374,7 @@ function Seat({
|
||||
mark,
|
||||
onPick,
|
||||
style,
|
||||
shift,
|
||||
}: {
|
||||
p: PlayerView;
|
||||
v: BangView;
|
||||
@@ -381,15 +383,20 @@ function Seat({
|
||||
mark: TargetMark | null;
|
||||
onPick: (id: string) => void;
|
||||
style?: CSSProperties;
|
||||
/** How much later than its own the room times this table (see BangBoard). */
|
||||
shift: number;
|
||||
}) {
|
||||
const u = userOf(players, p.id);
|
||||
const r = v.reactions.find((x) => x.who === p.id);
|
||||
// A player falls once the shot that downed them has played (the role badge has its own flip, see useBangFx 'dead').
|
||||
const alive = useAfterMotionValue(p.alive);
|
||||
const role = shownRole(p, v, me);
|
||||
const timer = r ? (
|
||||
<TurnTimer deadline={r.deadline} totalMs={v.reactionTotalMs} mine={p.id === me} size={26} />
|
||||
<TurnTimer deadline={r.deadline === null ? null : r.deadline + shift} totalMs={v.reactionTotalMs} mine={p.id === me} size={26} />
|
||||
) : p.isTurn && !v.reactions.length && !v.winner ? (
|
||||
<TurnTimer deadline={v.turnDeadline} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
<TurnTimer deadline={v.turnDeadline === null ? null : v.turnDeadline + shift} totalMs={v.deadlineTotalMs} mine={p.id === me} size={26} />
|
||||
) : null;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`;
|
||||
const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!alive ? ' dead' : ''}`;
|
||||
const body = (
|
||||
<>
|
||||
<span className="bg-row nw">
|
||||
@@ -401,10 +408,10 @@ function Seat({
|
||||
{timer}
|
||||
</span>
|
||||
<span className="bg-row nw rc">
|
||||
<RoleBadge role={shownRole(p, v, me)} alive={p.alive} />
|
||||
<RoleBadge role={role} alive={alive} />
|
||||
<span className="bg-char">{p.character ? CHAR_INFO[p.character].name : '캐릭터 고르는 중'}</span>
|
||||
</span>
|
||||
{p.alive ? (
|
||||
{alive ? (
|
||||
<span className="bg-row">
|
||||
<Hp life={p.life} max={p.maxLife} />
|
||||
<span className="bg-cnt" aria-hidden>
|
||||
@@ -438,7 +445,7 @@ function Seat({
|
||||
data-player={p.id}
|
||||
data-fx-seat={p.id}
|
||||
aria-pressed={mark.selected}
|
||||
aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`}
|
||||
aria-label={`${seatLabel(p, players, me, role)}. 대상으로 고르기`}
|
||||
onClick={() => onPick(p.id)}
|
||||
>
|
||||
{body}
|
||||
@@ -446,7 +453,7 @@ function Seat({
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, shownRole(p, v, me)) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
<div className={cls} style={style} data-target={mark ? 'no' : undefined} data-player={p.id} data-fx-seat={p.id} role="group" aria-label={seatLabel(p, players, me, role) + (mark?.reason ? `. ${mark.reason}` : '')}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
@@ -467,6 +474,8 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
const PURPOSE: Record<string, string> = { dynamite: '다이너마이트', jail: '감옥', barrel: '술통', jourdonnais: '주르도네' };
|
||||
const waitingFor = v.reactions.length ? [...new Set(v.reactions.map((r) => r.who))] : [];
|
||||
const last = v.log[v.log.length - 1];
|
||||
// The latest event's text changes once its animation has played.
|
||||
const lastText = useAfterMotionValue(last ? logText(last, players) : '');
|
||||
return (
|
||||
<div className="bg-center">
|
||||
<div className="bg-piles" data-fx="bang-piles">
|
||||
@@ -482,7 +491,7 @@ function Center({ v, players }: { v: BangView; players: Record<string, PublicUse
|
||||
</span>
|
||||
)}
|
||||
{waitingFor.length > 0 && <span className="bg-chip">{waitingFor.map((id) => `${nick(players, id)}님`).join(', ')} 기다리는 중…</span>}
|
||||
{last && <span className="bg-last">{logText(last, players)}</span>}
|
||||
{lastText && <span className="bg-last">{lastText}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -624,6 +633,8 @@ function MyArea({
|
||||
}) {
|
||||
const my = v.my!;
|
||||
const meP = v.players.find((p) => p.id === v.me);
|
||||
// "쓰러졌어요" waits for the shot that downed me.
|
||||
const meAlive = useAfterMotionValue(meP?.alive ?? false);
|
||||
const [multi, setMulti] = useState<string[]>([]);
|
||||
const [sidMode, setSidMode] = useState(false);
|
||||
const [note, setNote] = useState('');
|
||||
@@ -692,7 +703,7 @@ function MyArea({
|
||||
<span className="stack" style={{ gap: 2, flex: '1 1 220px', minWidth: 0 }}>
|
||||
<strong>
|
||||
{my.character ? CHAR_INFO[my.character].name : '캐릭터를 고르는 중'}
|
||||
{meP && meP.alive && (
|
||||
{meP && meAlive && (
|
||||
<>
|
||||
{' '}
|
||||
<Hp life={meP.life} max={meP.maxLife} />
|
||||
@@ -707,7 +718,7 @@ function MyArea({
|
||||
</span>
|
||||
{meP && <Equip cards={meP.inPlay} />}
|
||||
</div>
|
||||
{meP && !meP.alive && !v.winner && <strong>쓰러졌어요. 남은 게임을 지켜봐요.</strong>}
|
||||
{meP && !meAlive && !v.winner && <strong>쓰러졌어요. 남은 게임을 지켜봐요.</strong>}
|
||||
{prompt?.kind === 'draw' && <DrawPanel prompt={prompt} act={act} pending={pending} players={players} />}
|
||||
{meP?.alive && (
|
||||
<HandCards
|
||||
@@ -812,7 +823,7 @@ function DrawPanel({ prompt, act, pending, players }: { prompt: Extract<Prompt,
|
||||
|
||||
// ---------------------------------------------------------------- reaction prompt
|
||||
|
||||
function PromptModal({ v, act, pending, players }: { v: BangView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
function PromptModal({ v, act, pending, players, shift }: { v: BangView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser>; shift: number }) {
|
||||
const my = v.my!;
|
||||
const p = my.prompt;
|
||||
const [picked, setPicked] = useState<string[]>([]);
|
||||
@@ -828,7 +839,7 @@ function PromptModal({ v, act, pending, players }: { v: BangView; act: (a: unkno
|
||||
}, [p?.kind]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
if (!p || p.kind === 'discard' || p.kind === 'draw') return null;
|
||||
const r = v.reactions.find((x) => x.who === v.me);
|
||||
const timer = r ? <TurnTimer deadline={r.deadline} totalMs={v.reactionTotalMs} mine size={44} /> : null;
|
||||
const timer = r ? <TurnTimer deadline={r.deadline === null ? null : r.deadline + shift} totalMs={v.reactionTotalMs} mine size={44} /> : null;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
const hand = my.hand;
|
||||
const sidBox = my.canSidHeal && (
|
||||
@@ -1048,8 +1059,13 @@ function logText(e: LogEntry, players: Record<string, PublicUser>): string {
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>) {
|
||||
function BangBoard({ view: v, me, players, act, pending, deadline }: BoardProps<BangView>) {
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
// The room's deadline is the game's (the earliest reaction, else the turn) plus the time the screens took to finish
|
||||
// animating: every clock on the table moves by that much.
|
||||
const ds = v.reactions.flatMap((r) => (r.deadline === null ? [] : [r.deadline]));
|
||||
const own = v.winner ? null : ds.length ? Math.min(...ds) : v.reactions.length ? null : v.turnDeadline;
|
||||
const shift = own !== null && deadline !== null ? Math.max(0, deadline - own) : 0;
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const mine = isMyTurn(v, me);
|
||||
const prevMine = useRef(false);
|
||||
@@ -1102,6 +1118,7 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
me={me}
|
||||
mark={markOf(p.id)}
|
||||
onPick={pick}
|
||||
shift={shift}
|
||||
style={{ '--x': `${50 + 41 * Math.cos(ang)}%`, '--y': `${50 + 37 * Math.sin(ang)}%`, order: rel } as CSSProperties}
|
||||
/>
|
||||
);
|
||||
@@ -1109,7 +1126,12 @@ function BangBoard({ view: v, me, players, act, pending }: BoardProps<BangView>)
|
||||
<Center v={v} players={players} />
|
||||
</div>
|
||||
{v.my && <MyArea v={v} act={act} pending={pending} players={players} sel={sel} setSel={setSel} />}
|
||||
{v.my && <PromptModal v={v} act={act} pending={pending} players={players} />}
|
||||
{/* A reaction / choice window opens once the card that caused it has landed (it mounts then, so focus works). */}
|
||||
{v.my && (
|
||||
<AfterMotion key={v.my.prompt?.kind} when={!!v.my.prompt && v.my.prompt.kind !== 'discard' && v.my.prompt.kind !== 'draw'}>
|
||||
<PromptModal v={v} act={act} pending={pending} players={players} shift={shift} />
|
||||
</AfterMotion>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -1156,6 +1178,11 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
return place(id);
|
||||
};
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
// The steps below are staged with timers (shots, banners, bumps): results wait until the last one has played.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const stageTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []);
|
||||
|
||||
useNewEntries(
|
||||
keyed,
|
||||
@@ -1389,9 +1416,15 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
case 'end':
|
||||
// The room already plays the win / lose sound.
|
||||
later(at + 300, () => showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner]));
|
||||
t += 300;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (t > 0) {
|
||||
setStaging(true);
|
||||
if (stageTimer.current) clearTimeout(stageTimer.current);
|
||||
stageTimer.current = setTimeout(() => setStaging(false), fxMs(Math.min(t, 3000) + 400));
|
||||
}
|
||||
},
|
||||
30,
|
||||
);
|
||||
@@ -1422,6 +1455,24 @@ function useBangFx(v: BangView, me: string | null, players: Record<string, Publi
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
/** One player in the side list; a fall and the role it shows wait for the shot's animation (like the seat). */
|
||||
function SideRow({ p, v, me, players }: { p: PlayerView; v: BangView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const alive = useAfterMotionValue(p.alive);
|
||||
const role = useAfterMotionValue(shownRole(p, v, me));
|
||||
return (
|
||||
<li className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: alive ? 1 : 0.55 }} aria-label={seatLabel(p, players, me, role)}>
|
||||
<Avatar user={userOf(players, p.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p.id === me ? 800 : 600 }}>
|
||||
{p.isTurn ? '▶ ' : ''}
|
||||
{nick(players, p.id)}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleBadge role={role} alive={alive} />
|
||||
{alive ? <Hp life={p.life} max={p.maxLife} /> : <span className="small">쓰러짐</span>}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
return (
|
||||
<>
|
||||
@@ -1436,34 +1487,27 @@ function BangSide({ view: v, me, players }: BoardProps<BangView>) {
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.players.map((p) => (
|
||||
<li key={p.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: p.alive ? 1 : 0.55 }} aria-label={seatLabel(p, players, me, shownRole(p, v, me))}>
|
||||
<Avatar user={userOf(players, p.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p.id === me ? 800 : 600 }}>
|
||||
{p.isTurn ? '▶ ' : ''}
|
||||
{nick(players, p.id)}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleBadge role={shownRole(p, v, me)} alive={p.alive} />
|
||||
{p.alive ? <Hp life={p.life} max={p.maxLife} /> : <span className="small">쓰러짐</span>}
|
||||
</li>
|
||||
<SideRow key={p.id} p={p} v={v} me={me} players={players} />
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>{TEAM_KO[v.result.winnerTeam]} 승리</strong>
|
||||
{v.result.ranking.map((id) => {
|
||||
const r = v.result!.players.find((x) => x.id === id)!;
|
||||
return (
|
||||
<span key={id}>
|
||||
{r.won ? '🏆 ' : ''}
|
||||
{nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name}
|
||||
<span className="muted small">{r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>{TEAM_KO[v.result.winnerTeam]} 승리</strong>
|
||||
{v.result.ranking.map((id) => {
|
||||
const r = v.result!.players.find((x) => x.id === id)!;
|
||||
return (
|
||||
<span key={id}>
|
||||
{r.won ? '🏆 ' : ''}
|
||||
{nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name}
|
||||
<span className="muted small">{r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps } from '../types';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
@@ -200,6 +200,24 @@ function useDealQueue(v: BlackjackView) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The cards of `shown` whose fly-in has finished (the screen stood still since they appeared): totals, bust / 블랙잭
|
||||
* tags count only these, so a number never changes while its card is still in the air.
|
||||
*/
|
||||
function useLandedCards(shown: string[]): string[] {
|
||||
const key = shown.join(',');
|
||||
const settled = useAfterMotionValue(key);
|
||||
return settled === key ? shown : settled.split(',').filter((k) => k && shown.includes(k));
|
||||
}
|
||||
|
||||
/** Everyone's chips as of the last still screen: the chip counts change only after the hand's cards have landed. */
|
||||
export function useLandedChips(v: BlackjackView): (id: string) => number {
|
||||
const key = v.seats.map((s) => `${s.id}:${s.chips}`).join(',');
|
||||
const settled = useAfterMotionValue(key);
|
||||
const map = new Map(settled.split(',').filter(Boolean).map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))]));
|
||||
return (id) => map.get(id) ?? v.seats.find((s) => s.id === id)?.chips ?? 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pieces
|
||||
|
||||
function totalOf(cards: string[]): { total: number; soft: boolean } {
|
||||
@@ -235,7 +253,8 @@ function DealtCard({ id, width, anim }: { id: string | null; width: number; anim
|
||||
|
||||
function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; width: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
|
||||
const cards = h.cards.filter((c) => q.shown(c));
|
||||
const done = cards.length === h.cards.length;
|
||||
const landed = useLandedCards(cards);
|
||||
const done = landed.length === h.cards.length;
|
||||
const tag = final && h.outcome ? OUTCOME_KO[h.outcome] : done ? HAND_KO[h.status] : '';
|
||||
const color =
|
||||
h.outcome === 'win' || h.outcome === 'blackjack' || h.outcome === 'bonus' ? '#16a34a' : h.outcome === 'lose' || h.status === 'bust' ? '#dc2626' : h.outcome === 'push' ? '#6b7280' : '#b45309';
|
||||
@@ -247,7 +266,7 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean;
|
||||
))}
|
||||
</div>
|
||||
<div className="meta">
|
||||
<TotalBadge cards={cards} status={h.status} final={done} />
|
||||
<TotalBadge cards={landed} status={h.status} final={done} />
|
||||
<span className="bj-bet" title="건 칩">
|
||||
<ChipIcon size={14} />
|
||||
{h.bet.toLocaleString('ko-KR')}
|
||||
@@ -263,14 +282,14 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean;
|
||||
);
|
||||
}
|
||||
|
||||
function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record<string, PublicUser>; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType<typeof useDealQueue>; final: boolean }) {
|
||||
function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final, chips }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record<string, PublicUser>; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType<typeof useDealQueue>; final: boolean; chips: number }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const isTurn = v.phase === 'playing' && v.turn === seat.id;
|
||||
const style = { ...(pos ? { '--x': `${pos.x}%`, '--y': `${pos.y}%` } : {}), '--mw': `${maxW}px` } as CSSProperties;
|
||||
const hands = seat.hands ?? [];
|
||||
const per = Math.ceil(hands.length / rows);
|
||||
return (
|
||||
<div className={`bj-seat${isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${seat.status !== 'playing' ? ' out' : ''}`} style={style} aria-label={`${u.nickname}${seat.id === me ? '(나)' : ''}, ${formatChips(seat.chips)}`}>
|
||||
<div className={`bj-seat${isTurn ? ' turn' : ''}${seat.id === me ? ' me' : ''}${seat.status !== 'playing' ? ' out' : ''}`} style={style} aria-label={`${u.nickname}${seat.id === me ? '(나)' : ''}, ${formatChips(chips)}`}>
|
||||
{seat.hands ? (
|
||||
<div className="hands">
|
||||
{Array.from({ length: rows }, (_, r) => (
|
||||
@@ -294,7 +313,7 @@ function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat
|
||||
{u.nickname}
|
||||
{seat.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<span className="ch">{seat.chips.toLocaleString('ko-KR')}</span>
|
||||
<span className="ch">{chips.toLocaleString('ko-KR')}</span>
|
||||
{seat.status === 'out' && <span className="small">칩 소진</span>}
|
||||
{seat.status === 'left' && <span className="small">나감</span>}
|
||||
</div>
|
||||
@@ -528,7 +547,7 @@ function Actions({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => v
|
||||
);
|
||||
}
|
||||
|
||||
function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean }) {
|
||||
function Dock({ v, me, players, act, pending, deadline, mine, final, chips }: { v: BlackjackView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean; chips: (id: string) => number }) {
|
||||
const seat = me ? v.seats.find((s) => s.id === me) : undefined;
|
||||
const u = seat ? userOf(players, seat.id) : null;
|
||||
let main: ReactNode;
|
||||
@@ -597,7 +616,7 @@ function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: Blac
|
||||
<Avatar user={u} size={44} />
|
||||
<span className="nm">{u.nickname} (나)</span>
|
||||
<span className="ch">
|
||||
<ChipIcon size={18} /> {seat.chips.toLocaleString('ko-KR')}
|
||||
<ChipIcon size={18} /> {chips(seat.id).toLocaleString('ko-KR')}
|
||||
</span>
|
||||
{mine && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine size={30} />}
|
||||
</div>
|
||||
@@ -643,11 +662,16 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
const mine = isMyTurn(v, me);
|
||||
const phone = usePhone();
|
||||
const q = useDealQueue(v);
|
||||
// Results (outcome tags, +/-) wait until every card has landed.
|
||||
const final = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy;
|
||||
// Cards still queued (dealt one by one with timers) hold results; then the last fly-in must finish too.
|
||||
useMotionHold(q.busy);
|
||||
const ended = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy;
|
||||
// Results (outcome tags, +/-, banner, 다음 판) wait until every card has landed.
|
||||
const final = useMotionSettled(ended);
|
||||
const chips = useLandedChips(v);
|
||||
const d = v.dealer;
|
||||
const dealerCards = d.cards.map((c) => c ?? holeKey(v)).filter((k) => q.shown(k));
|
||||
const dealerReal = d.cards.filter((c): c is string => !!c && q.shown(c));
|
||||
const dealerLanded = useLandedCards(dealerCards);
|
||||
const dealerReal = dealerLanded.filter((k) => k !== holeKey(v));
|
||||
const slots = seatLayout(v, me);
|
||||
// Table width for fitting cards into each seat's share (phone: my seat a full row, others two per row).
|
||||
const tableRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -707,7 +731,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
prevTurn.current = v.turn;
|
||||
}, [v.turn]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const dealerDone = dealerCards.length === d.cards.length;
|
||||
const dealerDone = dealerLanded.length === d.cards.length;
|
||||
const seatEls = slots.map(({ id, x, y, share }) => {
|
||||
const seat = v.seats.find((s) => s.id === id)!;
|
||||
const hands = seat.hands ?? [];
|
||||
@@ -718,7 +742,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
const roomH = (tableH * y) / 100 - (40 + dealerW * 1.4 + 12) - 64;
|
||||
const capH = phone ? 999 : Math.floor((roomH / rows - 50) / 1.4);
|
||||
const width = Math.max(26, Math.min(capH, fitCardWidth(hands, avail, id === me ? myW : otherW, rows)));
|
||||
return <Seat key={id} seat={seat} v={v} me={me} players={players} pos={phone ? null : { x, y }} width={width} rows={rows} maxW={avail} q={q} final={final} />;
|
||||
return <Seat key={id} seat={seat} v={v} me={me} players={players} pos={phone ? null : { x, y }} width={width} rows={rows} maxW={avail} q={q} final={final} chips={chips(id)} />;
|
||||
});
|
||||
return (
|
||||
<div className="bj-wrap">
|
||||
@@ -761,7 +785,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} />
|
||||
<Dock v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} mine={mine} final={final} chips={chips} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard';
|
||||
import { PlayChipNotice, formatChips } from '../../components/cards/Chips';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { BlackjackBoard, isMyTurn } from './board';
|
||||
import { BlackjackBoard, isMyTurn, useLandedChips } from './board';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
@@ -29,7 +29,9 @@ function statusText(v: BlackjackView, me: string | null, players: Record<string,
|
||||
// ---------------------------------------------------------------- side (standings only; every control is on the board)
|
||||
|
||||
function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
const ranked = [...v.seats].sort((a, b) => b.chips - a.chips);
|
||||
// Chip counts change only once the hand's cards have landed on the board.
|
||||
const chips = useLandedChips(v);
|
||||
const ranked = [...v.seats].sort((a, b) => chips(b.id) - chips(a.id));
|
||||
return (
|
||||
<div className="stack" style={{ gap: 12 }}>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
@@ -42,7 +44,7 @@ function Side({ view: v, me, players }: BoardProps<BlackjackView>) {
|
||||
{s.status === 'out' && ' (칩 소진)'}
|
||||
{s.status === 'left' && ' (나감)'}
|
||||
</span>
|
||||
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(s.chips)}</span>
|
||||
<span className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>{formatChips(chips(s.id))}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -26,6 +26,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { DieFace, FILL, GOODS_FILL, INK, Pips, SPACE, TileHex, axial, goodsName, hexPoints, monasteryText, tileName } from './hex';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
type M = { a: CobAction; cost: number };
|
||||
type Sel = { kind: 'die'; i: 0 | 1 } | { kind: 'buy' } | { kind: 'pick'; tile: string } | null;
|
||||
@@ -513,7 +514,17 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
const [ask, setAsk] = useState<Ask>(null);
|
||||
const [tab, setTab] = useState<'duchy' | 'depots' | 'others'>('duchy');
|
||||
const [banner, showBanner] = useBanner();
|
||||
// Banners (and their sounds) wait until the placed tile has settled: queued here, played once the board is still.
|
||||
const [due, setDue] = useState<(() => void)[]>([]);
|
||||
const dueReady = useMotionSettled(due.length > 0);
|
||||
useEffect(() => {
|
||||
if (!dueReady) return;
|
||||
for (const f of due) f();
|
||||
setDue([]);
|
||||
}, [dueReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const later = (f: () => void) => setDue((q) => [...q, f]);
|
||||
const myPv = me ? v.players[me] : undefined;
|
||||
const myVp = useAfterMotionValue(myPv?.vp ?? 0);
|
||||
const moves = useMemo(() => moveList(v), [v]);
|
||||
const top = topOf(v);
|
||||
const mineNow = !!v.my;
|
||||
@@ -547,15 +558,19 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
sfx.piece();
|
||||
if (e.p === me) bump(fxEl(`me-${e.space}`));
|
||||
} else if (e.t === 'region' && e.p === me) {
|
||||
sfx.good();
|
||||
showBanner(`+${e.vp}점`, 'green', '구역 완성!');
|
||||
later(() => {
|
||||
sfx.good();
|
||||
showBanner(`+${e.vp}점`, 'green', '구역 완성!');
|
||||
});
|
||||
} else if (e.t === 'colorBonus') {
|
||||
sfx.good();
|
||||
showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`);
|
||||
later(() => {
|
||||
sfx.good();
|
||||
showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`);
|
||||
});
|
||||
} else if (e.t === 'sell') sfx.coin();
|
||||
else if (e.t === 'ship') sfx.whoosh();
|
||||
else if (e.t === 'phase' && e.phase > 0) showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요');
|
||||
else if (e.t === 'soloTarget') showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`);
|
||||
else if (e.t === 'phase' && e.phase > 0) later(() => showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요'));
|
||||
else if (e.t === 'soloTarget') later(() => showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`));
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -712,8 +727,8 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar
|
||||
<span className="cob-res" title="은화" aria-label={`은화 ${myPv.silver}개`}>
|
||||
🪙 {myPv.silver}
|
||||
</span>
|
||||
<span className="cob-res" aria-label={`점수 ${myPv.vp}점`}>
|
||||
⭐ {myPv.vp}
|
||||
<span className="cob-res" aria-label={`점수 ${myVp}점`}>
|
||||
⭐ {myVp}
|
||||
</span>
|
||||
{sel?.kind === 'die' && workersMove(sel.i) && (
|
||||
<button className="btn btn-secondary btn-sm" onClick={() => send(workersMove((sel as { i: 0 | 1 }).i)!.a)} disabled={busy}>
|
||||
@@ -1053,6 +1068,9 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
);
|
||||
const order = v.roundOrder.length ? v.roundOrder : v.seats;
|
||||
const rows = v.final ? [...v.final].sort((a, b) => b.total - a.total) : null;
|
||||
// Points change once the tile that scored them has settled on the board.
|
||||
const vps = useAfterMotionValue(v.seats.map((p) => v.players[p]!.vp).join(',')).split(',');
|
||||
const vpOf = (p: string) => vps[v.seats.indexOf(p)] ?? String(v.players[p]!.vp);
|
||||
return (
|
||||
<>
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="참가자">
|
||||
@@ -1076,8 +1094,8 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
{pv.conceded ? '기권' : pv.away ? '자리 비움' : `👷${pv.workers} 🪙${pv.silver} 🎲${pv.dice.join('·')} · 빈칸 ${pv.emptySpaces}`}
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontWeight: 900, fontSize: '1.2rem' }} aria-label={`${nick(players, p)} ${pv.vp}점`}>
|
||||
{pv.vp}
|
||||
<span style={{ fontWeight: 900, fontSize: '1.2rem' }} aria-label={`${nick(players, p)} ${vpOf(p)}점`}>
|
||||
{vpOf(p)}
|
||||
</span>
|
||||
{turn && v.stage !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.deadlineMs || 60_000} mine={p === me} size={34} />}
|
||||
</div>
|
||||
@@ -1092,22 +1110,25 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps<CobView>) {
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
{rows && (
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="최종 점수">
|
||||
<strong>최종 점수</strong>
|
||||
{rows.map((r) => (
|
||||
<div key={r.player} className="small">
|
||||
<strong>
|
||||
{nick(players, r.player)} {r.total}점
|
||||
</strong>{' '}
|
||||
= 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers}
|
||||
{r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''}
|
||||
{r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{/* The final scores wait for the last move to finish animating. */}
|
||||
<AfterMotion when={!!rows}>
|
||||
{rows && (
|
||||
<section className="cob-card stack" style={{ gap: 4 }} aria-label="최종 점수">
|
||||
<strong>최종 점수</strong>
|
||||
{rows.map((r) => (
|
||||
<div key={r.player} className="small">
|
||||
<strong>
|
||||
{nick(players, r.player)} {r.total}점
|
||||
</strong>{' '}
|
||||
= 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers}
|
||||
{r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''}
|
||||
{r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{log.length > 0 && (
|
||||
<details className="cob-card" open>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- constants (mirror packages/games/src/catchmind/types.ts)
|
||||
|
||||
@@ -685,6 +685,23 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string
|
||||
const prevRole = useRef(v.role);
|
||||
const prevTurn = useRef(v.turnNo);
|
||||
const popTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The answer screen (and its sound) waits until my "정답!" pop has played.
|
||||
const over = v.phase === 'reveal' || v.phase === 'ended';
|
||||
const overShown = useMotionSettled(over);
|
||||
const prevPhase = useRef(v.phase);
|
||||
const revealSound = useRef<(() => void) | null>(null);
|
||||
useEffect(() => {
|
||||
if (prevTurn.current === v.turnNo && prevPhase.current === 'drawing' && v.phase === 'reveal') {
|
||||
revealSound.current = v.endReason === 'report' ? sfx.alarm : v.endReason === 'allSolved' ? sfx.fanfare : v.solvers.length === 0 ? sfx.bad : sfx.cardFlip;
|
||||
}
|
||||
prevPhase.current = v.phase;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [v.phase, v.turnNo]);
|
||||
useEffect(() => {
|
||||
if (!overShown || !revealSound.current) return;
|
||||
revealSound.current();
|
||||
revealSound.current = null;
|
||||
}, [overShown]);
|
||||
useEffect(() => {
|
||||
if (prevTurn.current === v.turnNo && prevRole.current === 'guesser' && v.role === 'solver') {
|
||||
setPop(v.solvers.find((s) => s.id === me)?.points ?? 0);
|
||||
@@ -707,7 +724,7 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string
|
||||
) : null;
|
||||
return (
|
||||
<>
|
||||
<OverlayMain v={v} act={act} players={players} onSave={onSave} />
|
||||
{(!over || overShown) && <OverlayMain v={v} act={act} players={players} onSave={onSave} />}
|
||||
{popEl}
|
||||
</>
|
||||
);
|
||||
@@ -1061,7 +1078,7 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act:
|
||||
);
|
||||
}
|
||||
|
||||
/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */
|
||||
/** Sounds for what happens on the table (my own "정답!" and the answer reveal are played by the overlay). */
|
||||
function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
const prev = useRef(v);
|
||||
useEffect(() => {
|
||||
@@ -1083,12 +1100,6 @@ function useTableSounds(v: CatchmindView, me: string | null): void {
|
||||
if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect();
|
||||
if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react();
|
||||
if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close();
|
||||
if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') {
|
||||
if (v.endReason === 'report') sfx.alarm();
|
||||
else if (v.endReason === 'allSolved') sfx.fanfare();
|
||||
else if (v.solvers.length === 0) sfx.bad();
|
||||
else sfx.cardFlip();
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
|
||||
@@ -1358,6 +1369,7 @@ const ui: GameUI<CatchmindView, CatchmindOptions> = {
|
||||
Board: CatchmindBoard,
|
||||
Side: CatchmindSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import { AfterMotion, useAfterMotionValue } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { CHESS_PIECE_CREDIT, pieceSrc } from './art';
|
||||
import { chessCues, chessMotion } from './fx';
|
||||
@@ -542,12 +543,15 @@ function ChessSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.result && REASON_HELP[v.result.reason] && (
|
||||
<div className="card" style={{ padding: 12 }}>
|
||||
<strong>{v.result.summary}</strong>
|
||||
<div className="muted small">{REASON_HELP[v.result.reason]}</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Checkmate / stalemate explained once the last move has landed. */}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && REASON_HELP[v.result.reason] && (
|
||||
<div className="card" style={{ padding: 12 }}>
|
||||
<strong>{v.result.summary}</strong>
|
||||
<div className="muted small">{REASON_HELP[v.result.reason]}</div>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
<MoveList view={v} />
|
||||
{incoming && (
|
||||
<Sheet onClose={() => {}} label="상대의 요청">
|
||||
@@ -661,8 +665,9 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: ChessView;
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const caps = [...v.captured[color]].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b));
|
||||
const adv = color === 'white' ? v.materialDiff : -v.materialDiff;
|
||||
// A captured piece joins the row (and the material count changes) once the capturing move has landed.
|
||||
const caps = [...useAfterMotionValue(v.captured[color].join(''))].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b));
|
||||
const adv = useAfterMotionValue(color === 'white' ? v.materialDiff : -v.materialDiff);
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<div className="row" style={{ gap: 10 }}>
|
||||
|
||||
@@ -28,7 +28,7 @@ import { cssEsc, flyGhost, reducedMotion } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
export const SUSPECT_COLOR: Record<Suspect, string> = {
|
||||
scarlet: '#dc2626',
|
||||
@@ -302,6 +302,10 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null);
|
||||
|
||||
useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]);
|
||||
// The dice total (and the rooms it reaches) shows once the dice have stopped rolling.
|
||||
const diceKey = v.dice ? `${v.turnNo}-${v.dice[0]}-${v.dice[1]}` : '';
|
||||
const shownDice = useAfterMotionValue(diceKey);
|
||||
const rolling = diceKey !== '' && shownDice !== diceKey;
|
||||
|
||||
// Tokens and weapons slide on the map from where they were (anyone's move, a suggestion pulling them into a room).
|
||||
// Places are kept relative to the map, so scrolling between two moves does not matter.
|
||||
@@ -431,8 +435,8 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
<div className="cl-board" role="region" aria-label="클루 판">
|
||||
<style>{CSS}</style>
|
||||
<div className="cl-top">
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} />
|
||||
<Mansion view={v} me={me} myTurn={myTurn && !pending && !rolling} sel={sel} setSel={setSel} landed={landed?.room ?? null} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} setSel={setSel} rolling={rolling} />
|
||||
</div>
|
||||
{amPlayer && <MyCards view={v} me={me!} />}
|
||||
{amPlayer && <Notebook view={v} me={me!} players={players} />}
|
||||
@@ -635,6 +639,9 @@ function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act
|
||||
|
||||
function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const last = lastOf(v.suggestions);
|
||||
// The answer shows once the suggested cards have flown into the envelope / the shown card has reached the suggester.
|
||||
const answerKey = `${v.suggestions.length}|${last?.refuter ?? ''}|${v.phase.kind === 'refute'}`;
|
||||
const answered = useAfterMotionValue(answerKey) === answerKey;
|
||||
if (!last || last.turnNo !== v.turnNo) return null;
|
||||
const by = last.by === me ? '내' : `${nick(players, last.by)}님의`;
|
||||
return (
|
||||
@@ -643,7 +650,7 @@ function LastResult({ view: v, me, players }: { view: ClueView; me: string | nul
|
||||
{by} 추리: <strong>{triple(last)}</strong>
|
||||
{last.passed.length > 0 && <span className="muted"> · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}</span>}
|
||||
</span>
|
||||
{last.refuter ? (
|
||||
{!answered ? null : last.refuter ? (
|
||||
last.shown ? (
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<Card id={last.shown} flip label={`${last.refuter === me ? '내가 보여 준' : `${nick(players, last.refuter)}님이 보여 준`} 카드: ${ITEM_KO[itemOf(last.shown)]}`} />
|
||||
@@ -674,6 +681,7 @@ function ActionPanel({
|
||||
myTurn,
|
||||
sel,
|
||||
setSel,
|
||||
rolling,
|
||||
}: {
|
||||
view: ClueView;
|
||||
me: string | null;
|
||||
@@ -683,6 +691,7 @@ function ActionPanel({
|
||||
myTurn: boolean;
|
||||
sel: Room | null;
|
||||
setSel: (r: Room | null) => void;
|
||||
rolling: boolean;
|
||||
}) {
|
||||
const [accusing, setAccusing] = useState(false);
|
||||
const known = useMemo(() => {
|
||||
@@ -694,18 +703,21 @@ function ActionPanel({
|
||||
const ph = v.phase;
|
||||
|
||||
if (ph.kind === 'finished') {
|
||||
// The answer opens after the accusation banner has played.
|
||||
return (
|
||||
<div className="cl-panel" aria-live="polite">
|
||||
<strong>게임이 끝났어요</strong>
|
||||
<span>{v.final?.summary}</span>
|
||||
{v.solution && (
|
||||
<div className="cl-cards" aria-label="사건 봉투 속 정답">
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
|
||||
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="cl-panel" aria-live="polite">
|
||||
<strong>게임이 끝났어요</strong>
|
||||
<span>{v.final?.summary}</span>
|
||||
{v.solution && (
|
||||
<div className="cl-cards" aria-label="사건 봉투 속 정답">
|
||||
{[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => (
|
||||
<Card key={x} id={`card-${x}`} fresh delay={i * 250} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -739,7 +751,7 @@ function ActionPanel({
|
||||
if (!myTurn) {
|
||||
const doing: Record<string, string> = {
|
||||
move: '이동하는 중이에요',
|
||||
moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`,
|
||||
moveTo: rolling ? '주사위를 굴리는 중이에요' : `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`,
|
||||
suggest: '추리할 카드를 고르는 중이에요',
|
||||
afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요',
|
||||
};
|
||||
@@ -822,13 +834,15 @@ function ActionPanel({
|
||||
<span key={`b${v.turnNo}-${v.dice[1]}`} className="anim-roll" style={{ animationDelay: '80ms' }} aria-hidden>
|
||||
{DICE[v.dice[1]]}
|
||||
</span>
|
||||
<b aria-hidden>= {sum}칸</b>
|
||||
{!rolling && <b aria-hidden>= {sum}칸</b>}
|
||||
</div>
|
||||
)}
|
||||
<strong>지도에서 갈 방을 눌러 주세요.</strong>
|
||||
<span className="small muted">
|
||||
{free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
|
||||
</span>
|
||||
<strong>{rolling ? '주사위를 굴리는 중…' : '지도에서 갈 방을 눌러 주세요.'}</strong>
|
||||
{!rolling && (
|
||||
<span className="small muted">
|
||||
{free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`}
|
||||
</span>
|
||||
)}
|
||||
<div className="cl-btns">
|
||||
{sel && enter && (
|
||||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'go', room: sel })}>
|
||||
@@ -985,7 +999,11 @@ function logLines(v: ClueView, me: string | null, players: Record<string, Public
|
||||
|
||||
function ClueSide({ view: v, me, players, deadline }: BoardProps<ClueView>) {
|
||||
const running = v.phase.kind !== 'finished';
|
||||
const lines = logLines(v, me, players);
|
||||
// Accusation results, the winner and the answer show after the accusation banner has played on the board.
|
||||
const shownAcc = useAfterMotionValue(v.accusations.length);
|
||||
const pendingAcc = v.accusations.slice(shownAcc);
|
||||
const ended = useMotionSettled(!running);
|
||||
const lines = logLines(pendingAcc.length ? { ...v, accusations: v.accusations.slice(0, shownAcc) } : v, me, players);
|
||||
const wait = waitingOn(v);
|
||||
return (
|
||||
<>
|
||||
@@ -1011,14 +1029,14 @@ function ClueSide({ view: v, me, players, deadline }: BoardProps<ClueView>) {
|
||||
카드 {v.handCounts[p]}장
|
||||
</span>
|
||||
{running && wait === p && <span className="cl-badge turn">{v.phase.kind === 'refute' ? '보여 주는 중' : '차례'}</span>}
|
||||
{v.final?.winner === p && <span className="cl-badge ok">승리</span>}
|
||||
{v.left[p] ? <span className="cl-badge out">나감</span> : v.out[p] && <span className="cl-badge out">고발 실패</span>}
|
||||
{ended && v.final?.winner === p && <span className="cl-badge ok">승리</span>}
|
||||
{v.left[p] ? <span className="cl-badge out">나감</span> : v.out[p] && !pendingAcc.some((a) => a.by === p) && <span className="cl-badge out">고발 실패</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
{v.hands && v.solution && (
|
||||
{ended && v.hands && v.solution && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>정답: {triple(v.solution)}</strong>
|
||||
{v.seats.map((p) => (
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, flyGhost, seatEl, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
|
||||
const KINDS: Kind[] = ['cockroach', 'bat', 'fly', 'toad', 'rat', 'scorpion', 'spider', 'stinkbug'];
|
||||
@@ -246,6 +246,9 @@ const CSS = `
|
||||
.cp-chip.danger .cp-mini:last-child { box-shadow: 0 0 0 3px #ef4444, 0 0 12px rgba(239,68,68,.8); }
|
||||
.cp-chip.danger .cp-n { background: #dc2626; animation: cp-breathe 1s ease-in-out infinite; }
|
||||
.cp-chip.new .cp-mini:last-of-type { animation: cp-land .5s cubic-bezier(.3,.7,.3,1.3) 1.4s both; }
|
||||
/* The new count shows as the card lands, not before. */
|
||||
.cp-chip.new .cp-n { animation: cp-pop .25s ease-out 1.65s both; }
|
||||
.cp-chip.new.danger .cp-n { animation: cp-pop .25s ease-out 1.65s both, cp-breathe 1s ease-in-out 1.9s infinite; }
|
||||
${KINDS.map((k) => `.fx-ghost.cp-face-${k} { background: ${KIND_COLOR[k].bg}; color: ${KIND_COLOR[k].ink}; border: 2px solid ${KIND_COLOR[k].ink}; border-radius: 7px; display: flex; align-items: flex-end; justify-content: center; font: 800 9px/1.6 system-ui, sans-serif; box-shadow: 0 3px 8px rgba(0,0,0,.35); }`).join('\n')}
|
||||
.cp-empty { font-size: .8rem; opacity: .75; }
|
||||
.cp-bubble { position: absolute; right: 8px; top: -14px; background: #fff; color: #1c1e21; border-radius: 12px; padding: 3px 10px; font-weight: 800; font-size: .85rem; box-shadow: 0 3px 10px rgba(0,0,0,.3); animation: cp-pop .25s ease-out; z-index: 3; max-width: 80%; }
|
||||
@@ -427,12 +430,13 @@ function HandFan({ n }: { n: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v: CockroachView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null; fresh: Kind | null }) {
|
||||
function Seat({ id, v, me, players, deadline, bubble, fresh, final }: { id: string; v: CockroachView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null; fresh: Kind | null; final: CockroachView['final'] }) {
|
||||
const u = userOf(players, id);
|
||||
const r = v.round;
|
||||
const active = waitingOn(v) === id;
|
||||
const loser = v.final?.loser === id;
|
||||
const loser = final?.loser === id;
|
||||
const front = v.fronts[id]!;
|
||||
const frontTotal = useAfterMotionValue(front.total);
|
||||
const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null;
|
||||
const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`;
|
||||
return (
|
||||
@@ -454,12 +458,12 @@ function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v:
|
||||
{role && <span className="cp-badge turn">{role}</span>}
|
||||
{r.holder !== null && r.seen.includes(id) && <span className="cp-badge seen">👁 봤어요</span>}
|
||||
{v.away[id] && <span className="cp-badge">자리 비움</span>}
|
||||
{v.final && <span className={`cp-badge ${loser ? 'lose' : 'win'}`}>{loser ? '패배' : '승리'}</span>}
|
||||
{final && <span className={`cp-badge ${loser ? 'lose' : 'win'}`}>{loser ? '패배' : '승리'}</span>}
|
||||
</div>
|
||||
<div className="cp-meta" aria-hidden>
|
||||
<HandFan n={v.handCounts[id] ?? 0} />
|
||||
<span>손패 {v.handCounts[id]}장</span>
|
||||
<span>· 앞마당 {front.total}장</span>
|
||||
<span>· 앞마당 {frontTotal}장</span>
|
||||
</div>
|
||||
<div className="cp-front" aria-hidden>
|
||||
<FrontChips front={front} loseCount={v.loseCount} fresh={fresh} small />
|
||||
@@ -491,6 +495,9 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players:
|
||||
const truth = rv.kind === rv.claim;
|
||||
const caller = rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`;
|
||||
const taker = rv.takenBy === me ? '내' : `${nick(players, rv.takenBy)}님`;
|
||||
// A fresh verdict is written out only after the card has turned, been stamped and flown to its taker.
|
||||
const settled = useMotionSettled(fresh);
|
||||
const told = !fresh || settled;
|
||||
return (
|
||||
<div className={`cp-reveal${big ? ' big' : ''}`} role="group" aria-label="지난 판정">
|
||||
<span className="cp-revealcard">
|
||||
@@ -501,7 +508,7 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players:
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="small" style={{ lineHeight: 1.45 }}>
|
||||
<span className="small" style={{ lineHeight: 1.45, visibility: told ? undefined : 'hidden' }} aria-hidden={told ? undefined : true}>
|
||||
"{KIND_KO[rv.claim]}"{hasBatchim(KIND_KO[rv.claim]) ? "이라는" : "라는"} 말에 {caller} "{callWord}"{rv.auto ? '(시간 초과)' : ''} → 실제로는 {KIND_KO[rv.kind]}({truth ? '진짜' : '거짓'})
|
||||
<br />
|
||||
<span className={`verdict ${rv.correct ? 'ok' : 'no'}`}>{rv.correct ? '맞혔어요!' : '틀렸어요!'}</span> {kj(rv.kind, '은', '는')} {taker} 앞마당으로
|
||||
@@ -520,9 +527,12 @@ function Who({ id, players, me }: { id: string; players: Record<string, PublicUs
|
||||
}
|
||||
|
||||
/** The middle of the felt: the card being passed (with what was said), or the last verdict while the next card is chosen. */
|
||||
function Table({ v, me, players, fresh }: { v: CockroachView; me: string | null; players: Record<string, PublicUser>; fresh: { slide: boolean; flip: boolean } }) {
|
||||
function Table({ v, me, players, fresh, over }: { v: CockroachView; me: string | null; players: Record<string, PublicUser>; fresh: { slide: boolean; flip: boolean }; over: boolean }) {
|
||||
const r = v.round;
|
||||
if (v.phase === 'finished') {
|
||||
// The call that ended the game is played out like any other (card turns, stamp, flight, the loss banner): the end
|
||||
// shows only once all of it has finished (`over`), not when the card's own flip is done.
|
||||
const lastCall = v.phase === 'finished' && !over ? v.lastReveal : null;
|
||||
if (v.phase === 'finished' && !lastCall) {
|
||||
const f = v.final!;
|
||||
return (
|
||||
<div className="cp-center cp-table" role="group" aria-label="테이블">
|
||||
@@ -564,11 +574,11 @@ function Table({ v, me, players, fresh }: { v: CockroachView; me: string | null;
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const last = v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null;
|
||||
const last = lastCall ?? (v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null);
|
||||
return (
|
||||
<div className="cp-center cp-table" role="group" aria-label="테이블">
|
||||
{last ? <RevealLine rv={last} players={players} me={me} fresh={fresh.flip} big /> : <BackCard size="lg" />}
|
||||
<span className="cp-wait">{r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`}</span>
|
||||
{!lastCall && <span className="cp-wait">{r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -760,8 +770,9 @@ function RespondPanel({ v, players, act, pending }: { v: CockroachView; players:
|
||||
);
|
||||
}
|
||||
|
||||
function WaitPanel({ v, players, me }: { v: CockroachView; players: Record<string, PublicUser>; me: string | null }) {
|
||||
function WaitPanel({ v, players, me, over }: { v: CockroachView; players: Record<string, PublicUser>; me: string | null; over: boolean }) {
|
||||
if (v.phase === 'finished') {
|
||||
if (!over) return null;
|
||||
const f = v.final!;
|
||||
return (
|
||||
<div className="cp-panel" aria-live="polite">
|
||||
@@ -793,21 +804,25 @@ function MyArea({
|
||||
offering,
|
||||
bubble,
|
||||
fresh,
|
||||
final,
|
||||
}: {
|
||||
v: CockroachView;
|
||||
me: string;
|
||||
players: Record<string, PublicUser>;
|
||||
deadline: number | null;
|
||||
offering: boolean;
|
||||
/** The result, once the last call has played out. */
|
||||
final: CockroachView['final'];
|
||||
/** What I just said with 빠른 말: shown over my own area too, like everybody else's. */
|
||||
bubble: string | null;
|
||||
fresh: Kind | null;
|
||||
}) {
|
||||
const front = v.fronts[me]!;
|
||||
const frontTotal = useAfterMotionValue(front.total);
|
||||
const active = waitingOn(v) === me;
|
||||
const total = v.handCounts[me] ?? 0;
|
||||
return (
|
||||
<section className={`cp-me${active ? ' turn' : ''}${v.final?.loser === me ? ' loser' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
<section className={`cp-me${active ? ' turn' : ''}${final?.loser === me ? ' loser' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
{bubble && (
|
||||
<span className="cp-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -838,7 +853,7 @@ function MyArea({
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="small">내 앞마당 {front.total}장</span>
|
||||
<span className="small">내 앞마당 {frontTotal}장</span>
|
||||
<div className="cp-front" role="img" aria-label={`내 ${frontText(front, v.loseCount)}`}>
|
||||
<FrontChips front={front} loseCount={v.loseCount} fresh={fresh} />
|
||||
</div>
|
||||
@@ -856,6 +871,19 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const [bubbles, setBubbles] = useState<Record<string, string>>({});
|
||||
const [fresh, setFresh] = useState({ slide: false, flip: false });
|
||||
const [banner, showBanner] = useBanner();
|
||||
// A call is played out with timers (verdict, flight, the loss): results wait until its last step.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const stageTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []);
|
||||
const stageFor = (ms: number) => {
|
||||
if (stageTimer.current) clearTimeout(stageTimer.current);
|
||||
setStaging(true);
|
||||
stageTimer.current = setTimeout(() => setStaging(false), ms);
|
||||
};
|
||||
// The end of the game (badges, the table's result, the panel) shows once the last call has played out.
|
||||
const overShown = useMotionSettled(v.phase === 'finished');
|
||||
const final = overShown ? v.final : null;
|
||||
const prev = useRef({
|
||||
claims: v.round.claims.length + v.round.no * 100,
|
||||
reveal: v.lastReveal?.round ?? 0,
|
||||
@@ -887,8 +915,13 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
sfx.cardFlip();
|
||||
setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), fxMs(260));
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
// The verdict comes when the 진짜/거짓 stamp has landed on the turned card (flip .6s, stamp .55s + .45s).
|
||||
setTimeout(() => {
|
||||
if (rv.correct) sfx.good();
|
||||
else cpSfx.wrong();
|
||||
showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`);
|
||||
}, fxMs(1000));
|
||||
stageFor(fxMs(over ? 2600 : 1600));
|
||||
// After the flip and the stamp, a face-up copy goes to the 앞마당 of whoever takes it.
|
||||
flyGhost(document.querySelector('.cp-revealcard') ?? document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 1000, ms: 480, className: `cp-face-${rv.kind}`, label: KIND_KO[rv.kind] });
|
||||
setTimeout(() => {
|
||||
@@ -904,7 +937,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined);
|
||||
cpSfx.danger();
|
||||
bump(seatEl(f.loser), 'shake');
|
||||
}, flip ? fxMs(1900) : 0);
|
||||
}, flip ? fxMs(2500) : 0); // after the verdict banner and the card's landing
|
||||
}
|
||||
if (flip) {
|
||||
const rv = v.lastReveal!;
|
||||
@@ -940,8 +973,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
const responding = amPlayer && v.round.holder === me && !v.round.peeked && v.phase === 'respond';
|
||||
const seats = amPlayer ? v.order.slice(v.order.indexOf(me!) + 1).concat(v.order.slice(0, v.order.indexOf(me!))) : v.order;
|
||||
|
||||
// A new verdict counts as fresh from its first render (the effect that sets `fresh` runs after it), so the card
|
||||
// never shows face up or its verdict before the flip.
|
||||
const freshNow = { slide: fresh.slide, flip: fresh.flip || (v.lastReveal?.round ?? 0) !== prev.current.reveal };
|
||||
// The card that just went face up lands in front of whoever took it.
|
||||
const landed = fresh.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null;
|
||||
const landed = freshNow.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null;
|
||||
const landedFor = (id: string) => (landed?.id === id ? landed.kind : null);
|
||||
|
||||
return (
|
||||
@@ -950,11 +986,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
<div className="cp-felt">
|
||||
<div className="cp-opps">
|
||||
{seats.map((p) => (
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} fresh={landedFor(p)} />
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} fresh={landedFor(p)} final={final} />
|
||||
))}
|
||||
</div>
|
||||
<Table v={v} me={me} players={players} fresh={fresh} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} bubble={bubbles[me!] ?? null} fresh={landedFor(me!)} />}
|
||||
<Table v={v} me={me} players={players} fresh={freshNow} over={overShown} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} deadline={deadline} offering={offering} bubble={bubbles[me!] ?? null} fresh={landedFor(me!)} final={final} />}
|
||||
</div>
|
||||
<div className="cp-actions">
|
||||
{offering || passing ? (
|
||||
@@ -962,7 +998,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
|
||||
) : responding ? (
|
||||
<RespondPanel v={v} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<WaitPanel v={v} players={players} me={me} />
|
||||
<WaitPanel v={v} players={players} me={me} over={overShown} />
|
||||
)}
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -1002,12 +1038,15 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const running = v.phase !== 'finished';
|
||||
const w = waitingOn(v);
|
||||
const r = v.round;
|
||||
// Who lost (and the 앞마당 counts) show once the last call has played out on the board.
|
||||
const final = useMotionSettled(v.phase === 'finished') ? v.final : null;
|
||||
const fronts = useAfterMotionValue(v.order.map((p) => v.fronts[p]!.total).join(',')).split(',');
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 8, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>{running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : '게임 끝'}</strong>
|
||||
<strong>{running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : final ? '게임 끝' : `${r.no}라운드`}</strong>
|
||||
{running && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine={w === me} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">{optionsSummary(v.options, v.order.length)}</span>
|
||||
@@ -1018,17 +1057,17 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: p === me ? 800 : 600 }} aria-hidden>
|
||||
{nick(players, p)}
|
||||
{w === p ? ' · 차례' : ''}
|
||||
{v.final ? (v.final.loser === p ? ' · 패배' : ' · 승리') : ''}
|
||||
{final ? (final.loser === p ? ' · 패배' : ' · 승리') : ''}
|
||||
</span>
|
||||
<span className="small muted" style={{ whiteSpace: 'nowrap' }} aria-hidden>
|
||||
손 {v.handCounts[p]} · 앞 {v.fronts[p]!.total}
|
||||
손 {v.handCounts[p]} · 앞 {fronts[v.order.indexOf(p)] ?? v.fronts[p]!.total}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{v.removedCount > 0 && running && <span className="small muted">2명 게임이라 카드 {v.removedCount}장을 보지 않고 뺐어요.</span>}
|
||||
</div>
|
||||
{v.final && <FinalCard v={v} players={players} />}
|
||||
{final && <FinalCard v={v} players={players} />}
|
||||
{running && v.options.claimHistory && r.claims.length > 0 && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>이번 라운드 주장</strong>
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -132,7 +133,10 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
|
||||
const ghostCol = preview ?? (hover !== null && canDrop(hover) ? hover : myTurn && kbd && open(cursor) ? cursor : null);
|
||||
const ghostLand = ghostCol !== null ? landing(ghostCol) : -1;
|
||||
const winSet = new Set((v.winLine ?? []).map((p) => p.y * cols + p.x));
|
||||
// The winning four light up only once the last disc has landed.
|
||||
const winShown = useMotionSettled(!!v.winLine?.length);
|
||||
const winLine = winShown ? (v.winLine ?? []) : [];
|
||||
const winSet = new Set(winLine.map((p) => p.y * cols + p.x));
|
||||
const last = v.lastMove ? v.lastMove.y * cols + v.lastMove.x : -1;
|
||||
const pad = 0.15;
|
||||
const cells = Array.from({ length: cols * rows }, (_, i) => i);
|
||||
@@ -196,7 +200,7 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
opacity={0.85}
|
||||
/>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
{winLine.map((p, k) => (
|
||||
<circle
|
||||
key={`w${p.x}-${p.y}`}
|
||||
className="c4-win"
|
||||
|
||||
@@ -9,7 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const JESTER = 13;
|
||||
/** Same names as the rules module (kept here so the screen chunk does not pull in the rules code). */
|
||||
@@ -752,7 +752,14 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const prevMine = useRef(false);
|
||||
const lastLog = v.log[v.log.length - 1];
|
||||
const [banner, showBanner] = useBanner();
|
||||
useDalmutiFx(v, me, players, showBanner);
|
||||
const end = useRoundEnd(v);
|
||||
const endDone = useMotionSettled(!!end);
|
||||
const showEnd = end && !endDone ? end : null;
|
||||
const resumeFx = useDalmutiFx(v, me, players, showBanner, !!showEnd);
|
||||
// The next round's panel is on screen now: deal its cards (and the rest of what was held back).
|
||||
useLayoutEffect(() => {
|
||||
if (endDone) resumeFx();
|
||||
}, [endDone]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (mine && !prevMine.current) {
|
||||
haptic(40);
|
||||
@@ -768,17 +775,27 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
<div className="dm">
|
||||
<style>{CSS}</style>
|
||||
<Tip />
|
||||
<Seats v={v} players={players} me={me} deadline={deadline} />
|
||||
<RevolutionBanner v={v} players={players} me={me} />
|
||||
{v.phase === 'revolutionCheck' && <RevolutionPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'taxReturn' && <TaxPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'playing' && <TableArea v={v} players={players} me={me} />}
|
||||
{v.phase === 'playing' && v.my && <PlayHand v={v} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
<div className="dm-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result.summary}</span>
|
||||
</div>
|
||||
{showEnd ? (
|
||||
<>
|
||||
{/* The round is over: its last cards land and the 등 banners play before the results and the next round. */}
|
||||
<Seats v={showEnd} players={players} me={me} deadline={null} />
|
||||
<TableArea v={showEnd} players={players} me={me} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Seats v={v} players={players} me={me} deadline={deadline} />
|
||||
<RevolutionBanner v={v} players={players} me={me} />
|
||||
{v.phase === 'revolutionCheck' && <RevolutionPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'taxReturn' && <TaxPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'playing' && <TableArea v={v} players={players} me={me} />}
|
||||
{v.phase === 'playing' && v.my && <PlayHand v={v} act={act} pending={pending} />}
|
||||
<AfterMotion when={v.phase === 'finished' && !!v.result}>
|
||||
<div className="dm-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result?.summary}</span>
|
||||
</div>
|
||||
</AfterMotion>
|
||||
</>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
@@ -788,10 +805,33 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The table as it stood when the round ended (the last play on top, seats before the new titles), from the moment
|
||||
* the round-ending view arrives until the next playing phase; null otherwise. Computed during render so the cards
|
||||
* are on screen in the same frame as their fly-in.
|
||||
*/
|
||||
function useRoundEnd(v: DalmutiView): DalmutiView | null {
|
||||
const r = useRef<{ cur: DalmutiView; end: DalmutiView | null }>({ cur: v, end: null });
|
||||
const s = r.current;
|
||||
if (s.cur !== v) {
|
||||
const p = s.cur;
|
||||
s.cur = v;
|
||||
if (v.phase === 'playing') s.end = null;
|
||||
else if (p.phase === 'playing') {
|
||||
const seen = new Set(p.log.map(logKey));
|
||||
const play = [...v.log].reverse().find((e): e is Extract<LogEntry, { t: 'play' }> => e.t === 'play' && !seen.has(logKey(e)));
|
||||
const top: PlayView | null = play ? { by: play.p, count: play.count, rank: play.rank, cards: play.cards } : null;
|
||||
const trick = top ? { leader: p.trick?.leader ?? top.by, top, pile: [...(p.trick?.pile ?? []), top] } : p.trick;
|
||||
s.end = { ...p, trick, current: null, seats: p.seats.map((x) => ({ ...x, isTurn: false })) };
|
||||
}
|
||||
}
|
||||
return s.end;
|
||||
}
|
||||
|
||||
const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`;
|
||||
|
||||
/** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */
|
||||
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1], roundEnding: boolean): () => void {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`);
|
||||
// A new round (or the very first deal): cards go from the middle to everyone.
|
||||
@@ -802,7 +842,14 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 }));
|
||||
for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 });
|
||||
};
|
||||
// While the ended round is still on screen, the new round's part (the deal, tax flights) waits for `resume`.
|
||||
const deferred = useRef<LogEntry[]>([]);
|
||||
useNewEntries(v.log, logKey, (fresh) => {
|
||||
const r = roundEnding ? fresh.findIndex((e) => e.t === 'round') : -1;
|
||||
if (r >= 0) deferred.current = fresh.slice(r);
|
||||
run(r >= 0 ? fresh.slice(0, r) : fresh);
|
||||
});
|
||||
function run(fresh: LogEntry[]) {
|
||||
const lastPlay = [...fresh].reverse().find((e) => e.t === 'play');
|
||||
let t = 0;
|
||||
for (const e of fresh) {
|
||||
@@ -863,7 +910,7 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
if (started.current) return;
|
||||
@@ -876,6 +923,11 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record<string,
|
||||
: v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done));
|
||||
if (fresh) deal();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return () => {
|
||||
const d = deferred.current;
|
||||
deferred.current = [];
|
||||
if (d.length) run(d);
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
@@ -896,7 +948,13 @@ function rulesLine(o: DalmutiOptions): string {
|
||||
|
||||
function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>) {
|
||||
const phaseKo = v.phase === 'revolutionCheck' ? '손패 확인' : v.phase === 'taxReturn' ? '세금 교환' : v.phase === 'playing' ? '진행 중' : '게임 끝';
|
||||
const rounds = v.roundResults;
|
||||
// Points and round ranks change once the round's last cards and banners have played on the board.
|
||||
const shownRounds = useAfterMotionValue(v.roundResults.length);
|
||||
const shownRef = useRef(v);
|
||||
if (shownRounds === v.roundResults.length) shownRef.current = v;
|
||||
const sv = shownRef.current;
|
||||
const totalOf = (id: string) => (sv.seats.find((x) => x.id === id) ?? v.seats.find((x) => x.id === id))?.total ?? 0;
|
||||
const rounds = sv.roundResults;
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -921,7 +979,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
{s.id === me ? ' (나)' : ''} <span className="small muted">{s.title}</span>
|
||||
</span>
|
||||
<span className="small" aria-hidden>
|
||||
{s.total}점
|
||||
{totalOf(s.id)}점
|
||||
</span>
|
||||
<span className="dm-count" aria-hidden>
|
||||
<i />
|
||||
@@ -947,7 +1005,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(v.result ? v.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => (
|
||||
{(sv.result ? sv.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => (
|
||||
<tr key={p}>
|
||||
<th scope="row" style={{ fontWeight: p === me ? 800 : 600 }}>
|
||||
{nick(players, p)}
|
||||
@@ -956,13 +1014,13 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps<DalmutiView>
|
||||
<td key={r.round}>{r.order.indexOf(p) + 1}등</td>
|
||||
))}
|
||||
<td>
|
||||
<b>{v.seats.find((s) => s.id === p)?.total ?? 0}점</b>
|
||||
<b>{totalOf(p)}점</b>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{v.result && <p className="small muted" style={{ margin: '6px 0 0' }}>{v.result.summary}</p>}
|
||||
{sv.result && <p className="small muted" style={{ margin: '6px 0 0' }}>{sv.result.summary}</p>}
|
||||
</div>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const COLOR_KO: Record<TColor, string> = { black: '검은색', white: '흰색' };
|
||||
const COLOR_SHORT: Record<TColor, string> = { black: '검정', white: '흰색' };
|
||||
@@ -251,6 +251,15 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
const [banner, setBanner] = useTimed<{ text: string; s: number }>();
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const seq = useRef(0);
|
||||
// "○○님 탈락!" waits for the flip of the tile that put them out; meanwhile the screen counts as moving.
|
||||
const [bannerWait, setBannerWait] = useState(false);
|
||||
const bannerTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useMotionHold(bannerWait);
|
||||
useEffect(() => () => clearTimeout(bannerTimer.current), []);
|
||||
// A new guess is told (panel, last guess line) only once its tile has turned over; the end panel after the reveal.
|
||||
const shownHist = useAfterMotionValue(v.history.length);
|
||||
const endShown = useMotionSettled(v.phase === 'finished');
|
||||
const settling = shownHist !== v.history.length ? 'guess' : v.phase === 'finished' && !endShown ? 'end' : null;
|
||||
const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record<string, boolean[]> } | null>(null);
|
||||
const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`);
|
||||
|
||||
@@ -325,9 +334,16 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
if (now.elim > prev.elim) {
|
||||
const out = v.eliminationOrder[v.eliminationOrder.length - 1]!;
|
||||
if (!v.left[out]) {
|
||||
setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700);
|
||||
// The match result sound itself is played by the room page.
|
||||
if (v.phase !== 'finished') snd.out(t + 250);
|
||||
const text = out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`;
|
||||
const more = v.phase !== 'finished';
|
||||
clearTimeout(bannerTimer.current);
|
||||
setBannerWait(true);
|
||||
bannerTimer.current = setTimeout(() => {
|
||||
setBannerWait(false);
|
||||
setBanner({ text, s: ++seq.current }, 1700);
|
||||
// The match result sound itself is played by the room page.
|
||||
if (more) snd.out(0);
|
||||
}, fxMs(t + 500));
|
||||
}
|
||||
}
|
||||
if (prev.phase !== 'finished' && v.phase === 'finished') {
|
||||
@@ -377,8 +393,8 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
))}
|
||||
</div>
|
||||
<div className="dv-mid">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} pendFx={pendFx} lastNo={shownHist} />
|
||||
<ActionPanel view={v} me={me} players={players} act={act} pending={pending} myTurn={myTurn} settling={settling} sel={sel} val={val} setVal={setVal} onCancel={() => (setSel(null), setVal(null))} />
|
||||
</div>
|
||||
{amPlayer && <MyRow view={v} me={me!} players={players} act={act} pending={pending} myTurn={myTurn} deadline={deadline} fx={fx ?? NO_FX} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -395,9 +411,11 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
|
||||
function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: DavinciView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
const u = userOf(players, id);
|
||||
const row = v.rows[id] ?? [];
|
||||
const st = v.stats[id] ?? { guesses: 0, correct: 0 };
|
||||
const outRank = v.eliminationOrder.indexOf(id);
|
||||
// Counts, 탈락 and 승리 change once the tile that changed them has turned over (`r`); the turn is live (`v`).
|
||||
const r = useAfterMotionValue(v);
|
||||
const row = r.rows[id] ?? [];
|
||||
const st = r.stats[id] ?? { guesses: 0, correct: 0 };
|
||||
const outRank = r.eliminationOrder.indexOf(id);
|
||||
const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id;
|
||||
const choosing = v.phase === 'chooseStart' && v.alive[id] && v.picked && !v.picked[id];
|
||||
return (
|
||||
@@ -408,12 +426,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view:
|
||||
{id === me && <span className="muted"> (나)</span>}
|
||||
</span>
|
||||
{isTurn && <span className="dv-badge turn">차례</span>}
|
||||
{v.final?.winner === id && <span className="dv-badge ok">승리</span>}
|
||||
{!v.alive[id] && <span className="dv-badge out">{v.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${v.seats.length - outRank}위` : ''}</span>}
|
||||
{r.final?.winner === id && <span className="dv-badge ok">승리</span>}
|
||||
{!r.alive[id] && <span className="dv-badge out">{r.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${r.seats.length - outRank}위` : ''}</span>}
|
||||
{v.alive[id] && (v.idle[id] ?? 0) >= 3 && <span className="dv-badge">자리 비움</span>}
|
||||
{v.phase === 'chooseStart' && v.alive[id] && <span className={`dv-badge${choosing ? '' : ' ok'}`}>{choosing ? '고르는 중' : '다 골랐어요'}</span>}
|
||||
<span className="small muted" style={{ marginLeft: 'auto' }}>
|
||||
{v.phase !== 'chooseStart' && (
|
||||
{r.phase !== 'chooseStart' && (
|
||||
<>
|
||||
숨은 타일 <Bump value={hiddenLeft(row)}>{hiddenLeft(row)}</Bump>개 ·{' '}
|
||||
</>
|
||||
@@ -558,6 +576,7 @@ function Center({
|
||||
pending,
|
||||
myTurn,
|
||||
pendFx,
|
||||
lastNo,
|
||||
}: {
|
||||
view: DavinciView;
|
||||
me: string | null;
|
||||
@@ -566,10 +585,12 @@ function Center({
|
||||
pending: boolean;
|
||||
myTurn: boolean;
|
||||
pendFx: Fx | null;
|
||||
/** How many guesses have been shown so far (the newest one waits for its tile to turn). */
|
||||
lastNo: number;
|
||||
}) {
|
||||
const drawing = myTurn && v.phase === 'draw' && !pending;
|
||||
const total = v.pool.black + v.pool.white;
|
||||
const last = v.history[v.history.length - 1];
|
||||
const last = v.history[Math.min(lastNo, v.history.length) - 1];
|
||||
return (
|
||||
<div className="dv-center" role="group" aria-label="더미">
|
||||
{v.options.chooseColors ? (
|
||||
@@ -643,6 +664,7 @@ function ActionPanel({
|
||||
act,
|
||||
pending,
|
||||
myTurn,
|
||||
settling,
|
||||
sel,
|
||||
val,
|
||||
setVal,
|
||||
@@ -654,11 +676,21 @@ function ActionPanel({
|
||||
act: (a: unknown) => void;
|
||||
pending: boolean;
|
||||
myTurn: boolean;
|
||||
/** A tile is still turning over: say what was guessed, not yet whether it was right (or who won). */
|
||||
settling: 'guess' | 'end' | null;
|
||||
sel: Sel | null;
|
||||
val: TileValue | null;
|
||||
setVal: (v: TileValue | null) => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
if (settling) {
|
||||
const g = settling === 'guess' ? v.history[v.history.length - 1] : undefined;
|
||||
return (
|
||||
<div className="dv-panel">
|
||||
<strong>{g ? `${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리했어요…` : '…'}</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (v.phase === 'finished') {
|
||||
return (
|
||||
<div className="dv-panel" aria-live="polite">
|
||||
@@ -886,7 +918,9 @@ function StartChooser({ view: v, me, act, pending }: { view: DavinciView; me: st
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function DavinciSide({ view: v, me, players, deadline }: BoardProps<DavinciView>) {
|
||||
function DavinciSide({ view, me, players, deadline }: BoardProps<DavinciView>) {
|
||||
// The side panel (counts, ranks, the guess log) follows the board once its tiles have turned over.
|
||||
const v = useAfterMotionValue(view);
|
||||
const running = v.phase !== 'finished';
|
||||
const ranking = v.final?.ranking ?? null;
|
||||
return (
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { ICON_NAMES, SymbolArt } from './art';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
/** Taps this soon after one of the two cards changed are dropped as late (they were aimed at the previous card). */
|
||||
const TAP_GRACE_MS = 250;
|
||||
@@ -283,6 +283,10 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
const [shake, setShake] = useState(false);
|
||||
const [hitArt, setHitArt] = useState<number | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
// The round result waits until the last find has played (its bubble and the cards changing); the next round's
|
||||
// countdown is real time and never waits.
|
||||
const [roundNote, setRoundNote] = useState<{ bubble: Bubble; bad: boolean } | null>(null);
|
||||
const roundReady = useMotionSettled(roundNote !== null, fxMs(1000));
|
||||
const prev = useRef<DobbleView | null>(null);
|
||||
const changed = useRef({ sig: '', at: 0 });
|
||||
|
||||
@@ -380,10 +384,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
const r = v.lastRound;
|
||||
if (r && r.round !== p.lastRound?.round) {
|
||||
const text = r.loser ? `${r.round}라운드 끝! ${r.loser === me ? '내가' : `${nick(players, r.loser)}님이`} 카드 ${r.cards}장을 벌점으로 받아요` : `${r.round}라운드는 무효예요`;
|
||||
setBubble({ key: `r${r.round}`, kind: r.loser === me ? 'bad' : 'info', text });
|
||||
setAnnounce(text);
|
||||
if (r.loser === me) sfx.bad();
|
||||
else sfx.whoosh();
|
||||
setRoundNote({ bubble: { key: `r${r.round}`, kind: r.loser === me ? 'bad' : 'info', text }, bad: r.loser === me });
|
||||
}
|
||||
// Someone emptied their cards / escaped this round.
|
||||
const done = v.seats.filter((s) => (s.status === 'finished' || s.status === 'escaped') && p.seats.find((x) => x.id === s.id)?.status === 'playing');
|
||||
@@ -392,6 +393,15 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
if (v.hint.length && v.hintUntil !== p.hintUntil && v.hintUntil > 0) sfx.select();
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!roundReady || !roundNote) return;
|
||||
setBubble(roundNote.bubble);
|
||||
setAnnounce(roundNote.bubble.text);
|
||||
if (roundNote.bad) sfx.bad();
|
||||
else sfx.whoosh();
|
||||
setRoundNote(null);
|
||||
}, [roundReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubble) return;
|
||||
const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1700));
|
||||
@@ -554,7 +564,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps<DobbleVi
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="db-count" aria-hidden>
|
||||
<div className="db-count" aria-hidden data-motion-free>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>{v.phase === 'roundEnd' ? '다음 라운드를 준비해요' : '두 카드에 똑같이 있는 그림을 찾아요!'}</small>
|
||||
</div>
|
||||
@@ -903,6 +913,7 @@ const ui: GameUI<DobbleView, DobbleOptions> = {
|
||||
Board: DobbleBoard,
|
||||
Side: DobbleSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -24,6 +24,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic } from '../../lib/feedback';
|
||||
import { toast } from '../../store/toast';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GEM, GemCell, MiniHex, PieceIcon, SQ3, hexPoints, hx } from './draw';
|
||||
import { helpNow } from './help';
|
||||
@@ -302,6 +303,14 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
const fresh = before && forward ? before.n : Infinity;
|
||||
const glowKey = v.placements.length;
|
||||
const prevHist = useRef(v.history.length);
|
||||
// "더 놓을 곳이 없어요" / "모두 놓았어요" toasts wait until the block has landed.
|
||||
const [toastQ, setToastQ] = useState<string[]>([]);
|
||||
const toastReady = useMotionSettled(toastQ.length > 0);
|
||||
useEffect(() => {
|
||||
if (!toastReady) return;
|
||||
toastQ.forEach((t) => toast(t));
|
||||
setToastQ([]);
|
||||
}, [toastReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useLayoutEffect(() => {
|
||||
const prev = prevHist.current;
|
||||
prevHist.current = v.history.length;
|
||||
@@ -316,10 +325,10 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
for (const m of added) {
|
||||
if (m.kind !== 'out') continue;
|
||||
if (m.reason === 'blocked') {
|
||||
toast(`${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`);
|
||||
setToastQ((q) => [...q, `${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`]);
|
||||
gmSound.out();
|
||||
} else if (m.reason === 'allPlaced') {
|
||||
toast(`${eun(m.color)} 18개를 모두 놓았어요!`);
|
||||
setToastQ((q) => [...q, `${eun(m.color)} 18개를 모두 놓았어요!`]);
|
||||
gmSound.allPlaced();
|
||||
}
|
||||
}
|
||||
@@ -823,7 +832,9 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps<GembloVi
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'finished' && <LeftPieces view={v} players={players} />}
|
||||
<AfterMotion when={v.phase === 'finished'}>
|
||||
<LeftPieces view={v} players={players} />
|
||||
</AfterMotion>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -869,7 +880,7 @@ function ColorChip({ v, i }: { v: GembloView; i: number }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPlayerView; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
|
||||
function PlayerRow({ v, shown, p, players, deadline, me }: { v: GembloView; shown: GembloView; p: GembloPlayerView; players: Record<string, PublicUser>; deadline: number | null; me: string | null }) {
|
||||
const u = players[p.id] ?? { id: p.id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
|
||||
const active = v.phase !== 'finished' && v.turnPlayer === p.id;
|
||||
const now = useServerNow(500);
|
||||
@@ -886,7 +897,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl
|
||||
} else if (active && (tc.kind === 'perMove' || v.phase !== 'playing')) {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={v.phase === 'playing' ? tc.perMoveSec * 1000 : 60_000} mine={p.id === me} size={40} />;
|
||||
}
|
||||
const left = p.colors.reduce((n, i) => n + v.colors[i]!.leftCells, 0);
|
||||
const left = p.colors.reduce((n, i) => n + shown.colors[i]!.leftCells, 0);
|
||||
const teamColors = p.team !== null && v.teams ? ` · ${p.team + 1}팀` : '';
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? GEM[v.colors[v.turn]!.color].fill : 'transparent'}`, opacity: p.out ? 0.6 : 1 }}>
|
||||
@@ -907,7 +918,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl
|
||||
</div>
|
||||
<div className="gm-chips" style={{ marginTop: 6 }}>
|
||||
{p.colors.map((i) => (
|
||||
<ColorChip key={i} v={v} i={i} />
|
||||
<ColorChip key={i} v={shown} i={i} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
@@ -922,10 +933,15 @@ function GembloSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const incoming = live && u && u.by !== me && !u.accepted.includes(me!) ? u : null;
|
||||
const waiting = live && u && (u.by === me || u.accepted.includes(me!));
|
||||
const order = mine ? [...v.players.filter((p) => p.id !== me), mine] : v.players;
|
||||
// Cells left / 끝 per color change once the block has landed on the board.
|
||||
const shownMoves = useAfterMotionValue(v.history.length);
|
||||
const shownRef = useRef(v);
|
||||
if (shownMoves === v.history.length) shownRef.current = v;
|
||||
const shown = shownRef.current.colors.length === v.colors.length ? shownRef.current : v;
|
||||
return (
|
||||
<>
|
||||
{order.map((p) => (
|
||||
<PlayerRow key={p.id} v={v} p={p} players={players} deadline={deadline} me={me} />
|
||||
<PlayerRow key={p.id} v={v} shown={shown} p={p} players={players} deadline={deadline} me={me} />
|
||||
))}
|
||||
{live && (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: v.undo.allowed ? '1fr 1fr' : '1fr', gap: 8 }}>
|
||||
|
||||
@@ -11,7 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string | null | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : '');
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
@@ -238,18 +238,21 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) {
|
||||
|
||||
function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) {
|
||||
const s = seat.score;
|
||||
const items: [string, boolean][] = [
|
||||
const now: [string, boolean][] = [
|
||||
[`광 ${s.gwang}장`, s.gwang >= 3],
|
||||
[`열끗 ${s.yeol}/5`, s.yeol >= 5],
|
||||
[`띠 ${s.tti}/5`, s.tti >= 5],
|
||||
[`피 ${s.pi}/10`, s.pi >= 10],
|
||||
];
|
||||
if (s.godori) items.push([`고도리 ${s.godori}/3`, s.godori === 3]);
|
||||
if (s.hong) items.push([`홍단 ${s.hong}/3`, s.hong === 3]);
|
||||
if (s.cheong) items.push([`청단 ${s.cheong}/3`, s.cheong === 3]);
|
||||
if (s.cho) items.push([`초단 ${s.cho}/3`, s.cho === 3]);
|
||||
if (s.godori) now.push([`고도리 ${s.godori}/3`, s.godori === 3]);
|
||||
if (s.hong) now.push([`홍단 ${s.hong}/3`, s.hong === 3]);
|
||||
if (s.cheong) now.push([`청단 ${s.cheong}/3`, s.cheong === 3]);
|
||||
if (s.cho) now.push([`초단 ${s.cho}/3`, s.cho === 3]);
|
||||
// Progress changes once the taken cards have flown into the pile.
|
||||
const [total, ...rest] = useAfterMotionValue([String(s.total), ...now.map(([t, d]) => `${d ? 1 : 0}${t}`)].join('|')).split('|');
|
||||
const items = rest.map((x): [string, boolean] => [x.slice(1), x[0] === '1']);
|
||||
return (
|
||||
<div className="gs-prog" aria-label={`족보 진행: ${items.map((x) => x[0]).join(', ')}. 지금 ${s.total}점, 기준 ${winScore}점`}>
|
||||
<div className="gs-prog" aria-label={`족보 진행: ${items.map((x) => x[0]).join(', ')}. 지금 ${total}점, 기준 ${winScore}점`}>
|
||||
{items.map(([t, done]) => (
|
||||
<span key={t} className={done ? 'done' : undefined}>
|
||||
{t}
|
||||
@@ -260,9 +263,11 @@ function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) {
|
||||
}
|
||||
|
||||
function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) {
|
||||
// The score changes once the taken cards have flown into the pile.
|
||||
const score = useAfterMotionValue(seat.score.total);
|
||||
return (
|
||||
<div className="gs-badges">
|
||||
{seat.participant && <span className="gs-badge score" title="이번 판 지금 점수">지금 {seat.score.total}점</span>}
|
||||
{seat.participant && <span className="gs-badge score" title="이번 판 지금 점수">지금 {score}점</span>}
|
||||
{seat.goCount > 0 && <span className="gs-badge go">{seat.goCount}고</span>}
|
||||
{seat.shakes > 0 && <span className="gs-badge">흔듦 {seat.shakes}</span>}
|
||||
{seat.bombs > 0 && <span className="gs-badge">폭탄 {seat.bombs}</span>}
|
||||
@@ -279,8 +284,10 @@ function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) {
|
||||
function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: GostopView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const u = userOf(players, seat.id);
|
||||
const active = actorOf(v) === seat.id;
|
||||
// Room points change once the round's payments have flown.
|
||||
const total = useAfterMotionValue(seat.total);
|
||||
return (
|
||||
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(seat.total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<li className={`gs-seat${active ? ' turn anim-glow' : ''}${!seat.participant && v.step !== 'sell' ? ' out' : ''}`} data-fx-seat={seat.id} aria-label={`${u.nickname}, 방 점수 ${signed(total)}${seat.isDealer ? ', 선' : ''}${seat.participant ? `, 지금 ${seat.score.total}점, 손패 ${seat.handCount}장` : ''}`}>
|
||||
<div className="gs-head">
|
||||
<Avatar user={u} size={26} />
|
||||
<span className="nm">
|
||||
@@ -289,7 +296,7 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop
|
||||
</span>
|
||||
{seat.isDealer && <span className="gs-badge dealer">선</span>}
|
||||
<span style={{ fontVariantNumeric: 'tabular-nums' }} title="방 점수 합계">
|
||||
합계 <strong>{signed(seat.total)}</strong>
|
||||
합계 <strong>{signed(total)}</strong>
|
||||
</span>
|
||||
{(seat.participant || v.step === 'sell') && (
|
||||
<span className="gs-backs" aria-label={`손패 ${seat.handCount}장`}>
|
||||
@@ -405,7 +412,12 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set<number>;
|
||||
}
|
||||
|
||||
function LastTurn({ v, players }: { v: GostopView; players: Record<string, PublicUser> }) {
|
||||
const t = v.lastTurn;
|
||||
// A new turn (what was flipped and taken) shows once its cards have landed; until then the previous one stays.
|
||||
const key = `${v.roundNo}-${v.lastTurn?.seq ?? 0}`;
|
||||
const shownKey = useAfterMotionValue(key);
|
||||
const kept = useRef(v.lastTurn);
|
||||
if (shownKey === key) kept.current = v.lastTurn;
|
||||
const t = kept.current;
|
||||
if (!t) return <div className="gs-last" aria-hidden />;
|
||||
const tags = t.tags.map((x) => TAG_KO[x]).filter(Boolean);
|
||||
const stolen = t.stolen.reduce((a, s) => a + s.cards.length, 0);
|
||||
@@ -459,7 +471,7 @@ type Ask = { kind: 'target' | 'shake' | 'bomb'; h: HandCardView } | null;
|
||||
function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; onFocusCard: (h: HandCardView | null) => void }) {
|
||||
const [lifted, setLifted] = useState<number | null>(null);
|
||||
const [ask, setAsk] = useState<Ask>(null);
|
||||
const canPlay = v.step === 'play' && v.turn === v.me && !pending;
|
||||
const canPlay = v.phase === 'playing' && v.step === 'play' && v.turn === v.me && !pending;
|
||||
const hints = v.rules.hints;
|
||||
const cw = useCardW();
|
||||
useEffect(() => {
|
||||
@@ -578,12 +590,13 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a
|
||||
);
|
||||
}
|
||||
|
||||
function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView | null) => void }) {
|
||||
const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard } = props;
|
||||
function MyArea(props: BoardProps<GostopView> & { onFocusCard: (h: HandCardView | null) => void; holdOpen: boolean }) {
|
||||
const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard, holdOpen } = props;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!seat || !me) return null;
|
||||
const active = actorOf(v) === me;
|
||||
if (v.phase !== 'playing') return null;
|
||||
// After the round ends my area stays until the result panel shows, so the last cards can still fly into my pile.
|
||||
if (v.phase !== 'playing' && !(v.outcome && holdOpen)) return null;
|
||||
return (
|
||||
<div className={`gs-me${active ? ' turn anim-glow' : ''}`} data-fx-seat={me} aria-label="내 자리">
|
||||
<div className="gs-head">
|
||||
@@ -644,7 +657,13 @@ function SellPanel({ v, me, players, act, pending }: { v: GostopView; me: string
|
||||
|
||||
// ---------------------------------------------------------------- decisions (sheets)
|
||||
|
||||
function Decisions({ view: v, me, players, act, pending }: BoardProps<GostopView>) {
|
||||
/** A decision sheet (고·스톱, 뒤집은 패, 총통, 국진) opens once the cards that led to it have landed. */
|
||||
function Decisions(props: BoardProps<GostopView>) {
|
||||
const sheet = DecisionSheet(props);
|
||||
return sheet && <AfterMotion key={props.view.step}>{sheet}</AfterMotion>;
|
||||
}
|
||||
|
||||
function DecisionSheet({ view: v, me, players, act, pending }: BoardProps<GostopView>): React.ReactElement | null {
|
||||
if (!me || v.phase !== 'playing') return null;
|
||||
const nop = () => {};
|
||||
if (v.step === 'goStop' && v.goStop && v.turn === me) {
|
||||
@@ -744,11 +763,14 @@ function outcomeTitle(o: OutcomeView, players: Record<string, PublicUser>, me: s
|
||||
|
||||
function RoundResult({ view: v, me, players, act, pending }: BoardProps<GostopView>) {
|
||||
const o = v.outcome;
|
||||
// The panel waits (invisible, so the payment chips can still fly to it) until the last cards, the 스톱! banner and
|
||||
// the chips have played.
|
||||
const shown = useMotionSettled(!!o && v.phase !== 'playing');
|
||||
if (!o || v.phase === 'playing') return null;
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1;
|
||||
return (
|
||||
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite">
|
||||
<section className="gs-panel gs-res" data-fx="gs-result" aria-label={`${v.roundNo}판 결과`} aria-live="polite" aria-hidden={!shown || undefined} style={shown ? undefined : { visibility: 'hidden' }}>
|
||||
<h2 style={{ margin: 0 }}>
|
||||
{v.roundNo}판 결과 · {outcomeTitle(o, players, me)}
|
||||
</h2>
|
||||
@@ -1190,11 +1212,12 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
}
|
||||
prevMine.current = mine;
|
||||
}, [mine]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const resultShown = useMotionSettled(!!v.outcome && v.phase !== 'playing');
|
||||
useEffect(() => {
|
||||
if (v.outcome && v.phase !== 'playing') {
|
||||
if (resultShown && v.outcome && v.phase !== 'playing') {
|
||||
setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`);
|
||||
}
|
||||
}, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [v.roundNo, v.phase, resultShown]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
useGostopFx(v, me, players, showBanner);
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
@@ -1212,7 +1235,7 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
</ul>
|
||||
<Floor v={v} glow={glow} narrow={narrow} players={players} />
|
||||
<RoundResult {...props} />
|
||||
<MyArea {...props} onFocusCard={setFocus} />
|
||||
<MyArea {...props} onFocusCard={setFocus} holdOpen={!resultShown} />
|
||||
<Decisions {...props} />
|
||||
{banner}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -1226,8 +1249,14 @@ function GostopBoard(props: BoardProps<GostopView>) {
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>) {
|
||||
const ranked = [...v.seats].sort((a, b) => b.total - a.total);
|
||||
const mySeat = v.seats.find((s) => s.id === me);
|
||||
// Points change once the cards / payment chips that caused them have landed.
|
||||
const shownTotals = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.total}`).join(','));
|
||||
const totalOf = new Map(shownTotals.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const));
|
||||
const total = (s: SeatView) => totalOf.get(s.id) ?? s.total;
|
||||
const ranked = [...v.seats].sort((a, b) => total(b) - total(a));
|
||||
const myScore = mySeat ? `${mySeat.score.total}\n${mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')}` : '';
|
||||
const [myTotal, myItems] = useAfterMotionValue(myScore).split('\n');
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -1253,7 +1282,7 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
{s.isDealer ? ' · 선' : ''}
|
||||
{s.left ? ' · 나감' : s.autoPilot ? ' · 자동' : ''}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{signed(s.total)}</strong>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>{signed(total(s))}</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -1261,10 +1290,10 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
{mySeat?.participant && v.phase === 'playing' && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>
|
||||
내 점수 {mySeat.score.total}점 / 기준 {v.rules.winScore}점
|
||||
내 점수 {myTotal}점 / 기준 {v.rules.winScore}점
|
||||
</strong>
|
||||
{mySeat.score.items.length > 0 ? (
|
||||
<span className="small">{mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')}</span>
|
||||
{myItems ? (
|
||||
<span className="small">{myItems}</span>
|
||||
) : (
|
||||
<span className="small muted">아직 점수 족보가 없어요.</span>
|
||||
)}
|
||||
@@ -1285,19 +1314,21 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps<GostopView>)
|
||||
</details>
|
||||
)}
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)})
|
||||
</span>
|
||||
))}
|
||||
{v.stats.bestRound && (
|
||||
<span className="small muted">
|
||||
가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)})
|
||||
</span>
|
||||
))}
|
||||
{v.stats.bestRound && (
|
||||
<span className="small muted">
|
||||
가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
<details className="card" style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보표</summary>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { socket, useRoom } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs } from '../../lib/motion';
|
||||
import { useWide } from '../../lib/media';
|
||||
|
||||
const FRUITS: Fruit[] = ['strawberry', 'banana', 'lime', 'plum'];
|
||||
@@ -975,21 +975,24 @@ function HalliGalliSide({ view: v, me, players }: BoardProps<HalliGalliView>) {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong}
|
||||
{/* The ranking waits for the last bell's slap and card flights. */}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
@@ -1221,6 +1224,7 @@ const ui: GameUI<HalliGalliView, HalliGalliOptions> = {
|
||||
Board: HalliGalliBoard,
|
||||
Side: HalliGalliSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(40);
|
||||
expect(IDS).toHaveLength(46);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -20,6 +20,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { MascotIcon, RaceCard } from './art';
|
||||
import { helpNow } from './help';
|
||||
@@ -708,8 +709,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps<HotStreakView>
|
||||
}
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const lastRes = v.results.at(-1);
|
||||
const showPayout = v.phase === 'payout' && lastRes && !replay.busy;
|
||||
const answered = v.phase === 'payout' && lastRes && !replay.busy ? lastRes.side.yes : null;
|
||||
// The payout and the side answer wait until the race has played to the end (its last 1등!/실격! floats included).
|
||||
const showPayout = useMotionSettled(v.phase === 'payout' && !!lastRes && !replay.busy);
|
||||
const answered = showPayout && lastRes ? lastRes.side.yes : null;
|
||||
const r = v.race;
|
||||
const house = HOUSE(v);
|
||||
const shownLog = r && line ? r.log.filter((l) => l.n <= line.n) : [];
|
||||
@@ -726,12 +728,14 @@ function Board({ view: v, me, players, act, pending }: BoardProps<HotStreakView>
|
||||
))}
|
||||
{v.phase !== 'finished' && <SideCard v={v} answered={answered} />}
|
||||
</div>
|
||||
{v.result && <FinalPanel v={v} me={me} players={players} />}
|
||||
<AfterMotion when={!!v.result}>
|
||||
<FinalPanel v={v} me={me} players={players} />
|
||||
</AfterMotion>
|
||||
{v.phase === 'draft' && v.mode === 'tickets' && v.draft && <DraftPanel v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'double' && <DoublePanel v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'draft' && v.mode === 'pots' && <PotPanel v={v} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'submit' && <SubmitPanel v={v} me={me} act={act} pending={pending} />}
|
||||
{showPayout && <PayoutPanel v={v} me={me} players={players} act={act} pending={pending} res={lastRes} />}
|
||||
{showPayout && lastRes && <PayoutPanel v={v} me={me} players={players} act={act} pending={pending} res={lastRes} />}
|
||||
<RaceArea v={v} me={me} act={act} pending={pending} replay={replay} compact={compact} />
|
||||
{v.faceUp.length > 0 && (v.phase === 'draft' || v.phase === 'double' || v.phase === 'submit') && <DeckList v={v} />}
|
||||
{shownLog.length > 0 && (
|
||||
@@ -779,6 +783,9 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<HotStr
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const playing = v.phase !== 'finished';
|
||||
const timed = v.phase === 'draft' || v.phase === 'double' || v.phase === 'submit';
|
||||
// Money changes at the payout: the new amounts show once the race has finished playing on the board.
|
||||
const moneyKey = useAfterMotionValue(v.seats.map((p) => v.money[p] ?? 0).join(','));
|
||||
const money = Object.fromEntries(v.seats.map((p, i) => [p, Number(moneyKey.split(',')[i] ?? v.money[p] ?? 0)]));
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 12, gap: 8 }} aria-label="참가자">
|
||||
@@ -797,8 +804,8 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<HotStr
|
||||
</div>
|
||||
<div className="small muted">{statusOf(v, p)}</div>
|
||||
</div>
|
||||
<strong style={{ fontSize: '1.15rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} ${v.money[p]}달러`}>
|
||||
{$(v.money[p]!)}
|
||||
<strong style={{ fontSize: '1.15rem', fontVariantNumeric: 'tabular-nums' }} aria-label={`${nick(players, p)} ${money[p]}달러`}>
|
||||
{$(money[p]!)}
|
||||
</strong>
|
||||
{on && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={34} />}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useEffect, useRef, useState, type ReactElement } from 'react';
|
||||
import type { HsRaceView, RaceLine, Racer } from '@bg/games/hot-streak';
|
||||
import { MASCOTS, MASCOT_IDS, josa, type MascotId } from '@bg/games/hot-streak/cards';
|
||||
import { noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionHold } from '../../lib/motion';
|
||||
import { MascotFace } from './art';
|
||||
|
||||
export const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
@@ -210,6 +210,8 @@ export function useReplay(r: HsRaceView | null) {
|
||||
q.current.push(...fresh);
|
||||
if (!s.playing) pump();
|
||||
}, [r?.no, r?.log.at(-1)?.n]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The lines play with timers (gaps between hops are not animations): results wait until the last line has played.
|
||||
useMotionHold(busy);
|
||||
|
||||
return { shown, floats, busy };
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import { addedPieces, janggiCues, janggiMotion } from './fx';
|
||||
import { helpNow } from './help';
|
||||
import { nopeSound, pickSound, playJanggi, setupSound } from './sound';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const SIDE_KO: Record<Side, string> = { cho: '초', han: '한' };
|
||||
const INK: Record<Side, string> = { cho: '#1d4ed8', han: '#c0262d' };
|
||||
@@ -207,6 +207,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
const [kbd, setKbd] = useState(false);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [bubble, setBubble] = useState<Bubble | null>(null);
|
||||
// 장군!/멍군!/빅장! wait until the piece has landed (and the 장군 pulse has played).
|
||||
const [dueBubble, setDueBubble] = useState<Bubble | null>(null);
|
||||
const bubbleReady = useMotionSettled(dueBubble !== null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prev = useRef({ count: v.moveCount, inCheck: v.inCheck, bikjang: v.bikjang, phase: v.phase });
|
||||
|
||||
@@ -245,8 +248,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
// Sounds, bubbles and announcements when the position changes.
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
const show = (text: string, color: string) => setBubble({ text, color, id: Date.now() });
|
||||
playJanggi(janggiCues(p, v), landSec * 1000);
|
||||
const show = (text: string, color: string) => setDueBubble({ text, color, id: Date.now() });
|
||||
// The slide plays at the game speed, so the landing sounds wait the scaled time.
|
||||
playJanggi(janggiCues(p, v), fxMs(landSec * 1000));
|
||||
if (v.moveCount > p.count) {
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
if (m.kind === 'move') {
|
||||
@@ -269,6 +273,12 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
setPreview(null);
|
||||
}, [v.moveCount, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubbleReady || !dueBubble) return;
|
||||
setBubble(dueBubble);
|
||||
setDueBubble(null);
|
||||
}, [bubbleReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!bubble) return;
|
||||
const t = setTimeout(() => setBubble(null), fxMs(1600));
|
||||
@@ -361,6 +371,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
const ghostTo = selected !== null ? (preview ?? (hover !== null && legal.get(selected)?.some((m) => m.to === hover) ? hover : null)) : null;
|
||||
const vias = new Set<number>();
|
||||
for (const t of targets) if (t.via !== null && (ghostTo === null || t.to === ghostTo)) vias.add(t.via);
|
||||
// The 장군 / 빅장 notes under the board show once the move that caused them has landed.
|
||||
const checkShown = useAfterMotionValue(v.inCheck);
|
||||
const bikjangShown = useAfterMotionValue(v.bikjang?.calledBy ?? null);
|
||||
const kingInCheck = v.inCheck ? v.board.findIndex((p) => p?.kind === 'king' && p.side === v.inCheck) : -1;
|
||||
const last = v.lastMove;
|
||||
const pad = 0.95;
|
||||
@@ -531,18 +544,18 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
{announce}
|
||||
</p>
|
||||
<div className="stack jg-rows" style={{ gap: 10 }}>
|
||||
{v.phase === 'playing' && v.inCheck && (
|
||||
{v.phase === 'playing' && checkShown && (
|
||||
<div className="card" role="alert" style={{ padding: '8px 12px', background: 'var(--danger-soft)', color: 'var(--danger)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.inCheck === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[v.inCheck]} 장군!`}
|
||||
{checkShown === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[checkShown]} 장군!`}
|
||||
</div>
|
||||
)}
|
||||
{v.phase === 'playing' && v.bikjang && (
|
||||
{v.phase === 'playing' && bikjangShown && (
|
||||
<div className="card" style={{ padding: '8px 12px', background: 'var(--warning-soft)', color: 'var(--warning)', fontWeight: 700, textAlign: 'center' }}>
|
||||
{v.bikjang.calledBy === v.mySide
|
||||
{bikjangShown === v.mySide
|
||||
? '빅장을 불렀어요. 상대가 막지 못하면 점수로 판정해요.'
|
||||
: v.mySide
|
||||
? '빅장이에요! 궁 사이를 막거나 궁을 옆으로 옮기지 않으면 점수로 판정해요.'
|
||||
: `${SIDE_KO[v.bikjang.calledBy]} 빅장!`}
|
||||
: `${SIDE_KO[bikjangShown]} 빅장!`}
|
||||
</div>
|
||||
)}
|
||||
{myTurn && v.repeatWarning && (
|
||||
@@ -764,7 +777,8 @@ function JanggiSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
}
|
||||
|
||||
function ScoreBar({ view: v }: { view: JanggiView }) {
|
||||
const { cho, han } = v.scores;
|
||||
// A capture changes the score once the capturing piece has landed.
|
||||
const [cho, han] = useAfterMotionValue(`${v.scores.cho}|${v.scores.han}`).split('|').map(Number) as [number, number];
|
||||
const pct = (cho / (cho + han)) * 100;
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px' }} aria-label={`점수 초 ${fmtScore(cho)}, 한 ${fmtScore(han)}`}>
|
||||
@@ -826,7 +840,10 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView;
|
||||
const id = v.players[side];
|
||||
const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const };
|
||||
const active = (v.phase === 'playing' && v.turn === side) || (v.phase === 'setup' && v.setup.waitingFor.includes(side));
|
||||
const caps = [...v.captured[side]].sort((a, b) => VALUE[b] - VALUE[a]);
|
||||
// Captured pieces and the 장군 mark appear once the move has landed.
|
||||
const capsKey = useAfterMotionValue(v.captured[side].join(','));
|
||||
const inCheck = useAfterMotionValue(v.inCheck);
|
||||
const caps = (capsKey ? (capsKey.split(',') as PieceKind[]) : []).sort((a, b) => VALUE[b] - VALUE[a]);
|
||||
return (
|
||||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? INK[side] : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<div className="row" style={{ gap: 10 }}>
|
||||
@@ -842,7 +859,7 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView;
|
||||
<div className="small" style={{ color: INK[side], fontWeight: 700 }}>
|
||||
{SIDE_KO[side]} {side === 'cho' ? '· 선수' : '· 후수 덤 1.5'}
|
||||
{v.phase === 'playing' && v.turn === side ? ' · 두는 중' : ''}
|
||||
{v.inCheck === side ? ' · 장군!' : ''}
|
||||
{inCheck === side ? ' · 장군!' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<Clock view={v} side={side} deadline={deadline} mine={id === me} />
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const ROLL_MS = 650;
|
||||
const HOUSE = 'house';
|
||||
@@ -309,6 +309,16 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevRoll = useRef(v.rollSeq);
|
||||
const prevView = useRef(v);
|
||||
// The dice tumble (timers + flicking faces): what was rolled shows only after it.
|
||||
useMotionHold(rolling);
|
||||
// A round's banner ("+30점") waits until its settlement has been dealt out on the screen.
|
||||
const [bannerNext, setBannerNext] = useState<{ text: string; sub?: string; key: number } | null>(null);
|
||||
const bannerReady = useMotionSettled(!!bannerNext);
|
||||
useEffect(() => {
|
||||
if (!bannerReady || !bannerNext) return;
|
||||
setBanner(bannerNext);
|
||||
setBannerNext(null);
|
||||
}, [bannerReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// New roll: tumble animation + screen-reader text.
|
||||
useLayoutEffect(() => {
|
||||
@@ -387,11 +397,15 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
settleSound(delay + 150, ties, awards.length, mineAw.length > 0, more);
|
||||
const seated = !!me && v.seats.includes(me) && !v.conceded.includes(me);
|
||||
const got = mineAw.reduce((t, a) => t + (a.note ?? 0), 0);
|
||||
setBanner({
|
||||
text: more ? `${rr.round}라운드 정산` : '최종 정산',
|
||||
sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined,
|
||||
key: v.roundResults.length,
|
||||
});
|
||||
// The last one only announces the final settlement right away (the room's result window waits for it); the
|
||||
// amounts are in the final table that follows.
|
||||
if (more) {
|
||||
setBannerNext({
|
||||
text: `${rr.round}라운드 정산`,
|
||||
sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined,
|
||||
key: v.roundResults.length,
|
||||
});
|
||||
} else setBanner({ text: '최종 정산', key: v.roundResults.length });
|
||||
if (more) setDealt(v.round);
|
||||
haptic([50, 30, 50]);
|
||||
}
|
||||
@@ -467,7 +481,9 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps<LasVeg
|
||||
)}
|
||||
{v.result && lastRR && (
|
||||
<div className="lv-lower">
|
||||
<FinalTable v={v} me={me} players={players} />
|
||||
<AfterMotion>
|
||||
<FinalTable v={v} me={me} players={players} />
|
||||
</AfterMotion>
|
||||
<Settlement round={lastRR.round} payouts={lastRR.payouts} v={v} me={me} players={players} />
|
||||
</div>
|
||||
)}
|
||||
@@ -759,6 +775,8 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
const [ask, setAsk] = useState(false);
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const mine = me ? v.money[me] : undefined;
|
||||
const myCount = useAfterMotionValue(mine?.count ?? 0);
|
||||
const myTotal = useAfterMotionValue(mine?.total ?? 0);
|
||||
const playing = v.phase !== 'finished';
|
||||
return (
|
||||
<>
|
||||
@@ -792,17 +810,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
{out ? '기권' : v.away.includes(p) ? '자리 비움' : playing ? `주사위 ${h.own}${v.neutralPer ? ` · 흰 ${h.neutral}` : ''}` : '끝'}
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}
|
||||
aria-label={`${nick(players, p)} 지폐 ${m.count}장${m.total !== null ? `, ${m.total}점` : ''}`}
|
||||
>
|
||||
<strong style={{ fontSize: '1.2rem' }}>
|
||||
<Bump value={m.total}>{m.total !== null ? `${m.total}점` : '?'}</Bump>
|
||||
</strong>
|
||||
<div className="small muted">
|
||||
<Bump value={m.count}>{m.count}장</Bump>
|
||||
</div>
|
||||
</span>
|
||||
<Money name={nick(players, p)} total={m.total} count={m.count} />
|
||||
{turn && playing && <TurnTimer deadline={deadline} totalMs={total} mine={p === me} size={40} />}
|
||||
</div>
|
||||
);
|
||||
@@ -813,7 +821,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
<div className="row small" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>내 지폐</strong>
|
||||
<span>
|
||||
{mine.count}장 · {mine.total ?? 0}점
|
||||
{myCount}장 · {myTotal}점
|
||||
</span>
|
||||
</div>
|
||||
<MyBills notes={mine.notes ?? []} />
|
||||
@@ -843,6 +851,22 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps<LasVeg
|
||||
);
|
||||
}
|
||||
|
||||
/** A seat's money; changes once the settlement has been dealt out on the board. */
|
||||
function Money({ name, total: totalNow, count: countNow }: { name: string; total: number | null; count: number }) {
|
||||
const total = useAfterMotionValue(totalNow);
|
||||
const count = useAfterMotionValue(countNow);
|
||||
return (
|
||||
<span style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }} aria-label={`${name} 지폐 ${count}장${total !== null ? `, ${total}점` : ''}`}>
|
||||
<strong style={{ fontSize: '1.2rem' }}>
|
||||
<Bump value={total}>{total !== null ? `${total}점` : '?'}</Bump>
|
||||
</strong>
|
||||
<div className="small muted">
|
||||
<Bump value={count}>{count}장</Bump>
|
||||
</div>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** My bills; the ones just received fly in (my own amounts are always visible to me). */
|
||||
function MyBills({ notes }: { notes: number[] }) {
|
||||
const sig = notes.join(',');
|
||||
|
||||
@@ -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}).`;
|
||||
|
||||
@@ -16,13 +16,41 @@ import { cssEsc, useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
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;
|
||||
@@ -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,20 +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);
|
||||
// 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 ? '관전 중에는 채팅을 쓸 수 없어요.' : talk ? (v.my.chatWhy ?? '') : v.phase.kind === 'describe' ? '토론 채팅은 설명이 다 끝나면 열려요.' : (v.my.chatWhy ?? '');
|
||||
const why = !me || !v.my ? '관전 중에는 채팅을 쓸 수 없어요.' : (v.my.chatWhy ?? '');
|
||||
return (
|
||||
<section className="lg-box lg-chat" aria-label="토론 채팅">
|
||||
<h2>💬 토론 채팅</h2>
|
||||
@@ -454,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"
|
||||
@@ -478,7 +521,7 @@ 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"
|
||||
/>
|
||||
@@ -506,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" />
|
||||
@@ -547,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>;
|
||||
@@ -635,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>
|
||||
);
|
||||
@@ -657,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>
|
||||
@@ -711,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;
|
||||
@@ -772,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();
|
||||
@@ -783,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;
|
||||
@@ -805,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">
|
||||
@@ -854,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>
|
||||
@@ -949,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="두 바퀴면 두 번째 바퀴는 거꾸로 돌아요.">
|
||||
@@ -1010,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(' · ');
|
||||
@@ -1029,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>
|
||||
@@ -1051,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';
|
||||
@@ -19,7 +19,7 @@ import { keepFocus, useTypingSignal } from '../../lib/chat-input';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// ---------------------------------------------------------------- names (original names only, docs §12)
|
||||
|
||||
@@ -392,15 +392,18 @@ type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void
|
||||
/** Tiles animating right now: who just left the game (turns over and greys out), who was spared. */
|
||||
type TileFx = { dying: string[]; saved: string[] };
|
||||
|
||||
function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null }) {
|
||||
function Players({ v, players, me, pick, pending, fx, hiddenDead, hideRoles }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null; hiddenDead: string[]; hideRoles: boolean }) {
|
||||
const mafiaChoice = v.my?.night?.action === 'mafiaTarget' ? v.my.night.choice : null;
|
||||
// Deaths whose turn-over has not played yet still look alive (the sun is still coming up).
|
||||
const aliveCount = v.aliveCount + hiddenDead.length;
|
||||
return (
|
||||
<section className="mf-box" aria-label={`사람들. 살아 있는 사람 ${v.aliveCount}명`}>
|
||||
<section className="mf-box" aria-label={`사람들. 살아 있는 사람 ${aliveCount}명`}>
|
||||
<h2>
|
||||
사람들 <span className="small muted">살아 있는 사람 {v.aliveCount}명</span>
|
||||
사람들 <span className="small muted">살아 있는 사람 {aliveCount}명</span>
|
||||
</h2>
|
||||
<div className="mf-tiles">
|
||||
{v.players.map((p) => {
|
||||
{v.players.map((q) => {
|
||||
const p = hiddenDead.includes(q.id) ? { ...q, alive: true, role: q.id === me || v.my?.mates.includes(q.id) ? q.role : null, team: null } : q;
|
||||
const u = userOf(players, p.id);
|
||||
const cls = `mf-tile${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}${p.id === v.phase.accused ? ' accused' : ''}${fx?.dying.includes(p.id) ? ' dying' : fx?.saved.includes(p.id) ? ' saved' : ''}`;
|
||||
const can = pick?.ids.includes(p.id) ?? false;
|
||||
@@ -411,7 +414,7 @@ function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players:
|
||||
{u.nickname}
|
||||
{p.id === me ? ' (나)' : ''}
|
||||
</span>
|
||||
<RoleTag p={p} meId={me} />
|
||||
{!hideRoles && <RoleTag p={p} meId={me} />}
|
||||
{!p.alive && <span className="mf-tag">탈락 · {p.diedDay}일차</span>}
|
||||
{p.id === v.phase.accused && <span className="mf-tag mark">지목됨</span>}
|
||||
{mafiaChoice === p.id && !pick && <span className="mf-tag mark">🎯 오늘 밤 대상</span>}
|
||||
@@ -585,6 +588,9 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
const my = v.my;
|
||||
const ph = v.phase;
|
||||
const n = (id: string) => `${nick(players, id)}님`;
|
||||
// A night's investigation result shows once the morning has come up on screen.
|
||||
const resultCount = useAfterMotionValue(my?.results.length ?? 0);
|
||||
const results = my ? my.results.slice(0, resultCount) : [];
|
||||
let body: ReactNode = null;
|
||||
if (!my) {
|
||||
body = <p className="mf-prompt">관전 중이에요. 낮 채팅과 발표만 볼 수 있어요.</p>;
|
||||
@@ -720,11 +726,11 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco
|
||||
<h2>{ph.kind === 'night' ? '🌙 오늘 밤' : ph.kind === 'ended' ? '🏁 결과' : '☀️ 할 일'}</h2>
|
||||
{body}
|
||||
{my?.idleWarning && ph.kind !== 'ended' && <strong style={{ color: 'var(--danger)' }}>오늘도 아무것도 하지 않으면 자리 비움으로 탈락해요.</strong>}
|
||||
{my && my.results.length > 0 && (
|
||||
{my && results.length > 0 && (
|
||||
<>
|
||||
<strong className="small">{my.role === 'medium' ? '영매 결과 (나만 봐요)' : '조사 결과 (나만 봐요)'}</strong>
|
||||
<ul className="mf-results">
|
||||
{my.results.map((r) => (
|
||||
{results.map((r) => (
|
||||
<li key={r.id}>{resultText(r, players)}</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -792,11 +798,16 @@ type ShowBanner = (text: string, tone?: BannerTone, sub?: string) => void;
|
||||
* Sounds and motion for what anyone did: announcements (votes, deaths, saves, the end), choices, the done count.
|
||||
* Banners come one after another (a morning death, then the winning side); a new announcement cancels queued ones.
|
||||
*/
|
||||
function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): void {
|
||||
function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): string[] {
|
||||
const prev = useRef(v);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
// The banners / tile motion still to come (timers): results wait for them. Deaths whose tile has not turned over yet.
|
||||
const [staging, setStaging] = useState(false);
|
||||
const [hiddenDead, setHiddenDead] = useState<string[]>([]);
|
||||
useMotionHold(staging);
|
||||
useEffect(() => () => timers.current.forEach(clearTimeout), []);
|
||||
useEffect(() => {
|
||||
// Layout effect: a new death must not show on its tile for even one frame before its turn.
|
||||
useLayoutEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
@@ -828,11 +839,18 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
|
||||
timers.current = [];
|
||||
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f());
|
||||
const start = isNight(p) && !isNight(v) ? 900 : 0;
|
||||
setHiddenDead(dying);
|
||||
if (dying.length || saved.length) {
|
||||
later(start, () => setTileFx({ dying, saved }));
|
||||
later(start, () => {
|
||||
setHiddenDead([]);
|
||||
setTileFx({ dying, saved });
|
||||
});
|
||||
later(start + 1200, () => setTileFx(null));
|
||||
}
|
||||
banners.forEach(([text, tone, sub], i) => later(start + i * 1500, () => showBanner(text, tone, sub)));
|
||||
const end = Math.max(dying.length || saved.length ? start + 1200 : 0, banners.length ? start + (banners.length - 1) * 1500 : 0);
|
||||
setStaging(end > 0);
|
||||
later(end, () => setStaging(false));
|
||||
}
|
||||
let played = false;
|
||||
const play = (f: () => void) => {
|
||||
@@ -856,9 +874,16 @@ function useMafiaFx(v: MafiaView, players: Record<string, PublicUser>, showBanne
|
||||
if (my && pm && (my.vote !== pm.vote || my.ballot !== pm.ballot || my.night?.choice !== pm.night?.choice)) return play(sfx.select);
|
||||
if (v.phase.readyCount > p.phase.readyCount && v.phase.kind === p.phase.kind) play(sfx.chip);
|
||||
}, [v]);
|
||||
return hiddenDead;
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView>) {
|
||||
/** `v.events` up to the last one whose banners / motion have finished playing. */
|
||||
function useShownEvents(v: MafiaView): PublicEvent[] {
|
||||
const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0);
|
||||
return useMemo(() => (v.events.at(-1)?.n ?? 0) <= shownN ? v.events : v.events.filter((e) => e.n <= shownN), [v.events, shownN]);
|
||||
}
|
||||
|
||||
function MafiaBoard({ view: v, me, players, act, pending, deadline }: BoardProps<MafiaView>) {
|
||||
// The room chat is closed while playing, so this game's own chat lines play the chat sound.
|
||||
useChatSound(v.chat.at(-1)?.key);
|
||||
const ph = v.phase;
|
||||
@@ -880,7 +905,14 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const [banner, showBanner] = useBanner();
|
||||
const [tileFx, setTileFx] = useState<TileFx | null>(null);
|
||||
useMafiaFx(v, players, showBanner, setTileFx);
|
||||
const hiddenDead = useMafiaFx(v, players, showBanner, setTileFx);
|
||||
// Announcements (news, chat lines) and the final reveal show once the banners and the sky have played.
|
||||
const shownEvents = useShownEvents(v);
|
||||
const shownV = shownEvents === v.events ? v : { ...v, events: shownEvents };
|
||||
const endShown = useMotionSettled(ph.kind === 'ended');
|
||||
// My own death shows (role card, 탈락 panel) when my tile turns over, like everyone else's.
|
||||
const meHidden = !!me && !!my && hiddenDead.includes(me);
|
||||
const actV = meHidden ? { ...v, my: { ...my!, alive: true } } : v;
|
||||
// Night falls / morning comes (for everyone, whoever's button press moved the phase on).
|
||||
const [sky, setSky] = useState<{ kind: 'night' | 'day'; key: string } | null>(null);
|
||||
const wasNight = useRef(isNight(v));
|
||||
@@ -907,7 +939,9 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
: ph.kind === 'discussion' && ph.adjustedBy.length
|
||||
? `시간 바꾼 사람: ${ph.adjustedBy.map((id) => nick(players, id)).join(', ')}`
|
||||
: ph.kind === 'ended'
|
||||
? v.final?.summary
|
||||
? endShown
|
||||
? v.final?.summary
|
||||
: ''
|
||||
: `살아 있는 사람 ${v.aliveCount}명`;
|
||||
return (
|
||||
<div className="mf">
|
||||
@@ -922,20 +956,23 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
</strong>
|
||||
<span className="s">{sub}</span>
|
||||
</span>
|
||||
<Clock endsAt={ph.endsAt} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <RoleCard role={my.role} mates={my.mates} players={players} always={!!v.winner || !my.alive} />}
|
||||
{/* The room's deadline is the phase clock plus the time the screens took to finish animating (it only moves later). */}
|
||||
<Clock endsAt={ph.endsAt === null ? null : Math.max(ph.endsAt, deadline ?? ph.endsAt)} unlimited={ph.endsAt === null && ph.kind !== 'ended'} />
|
||||
{my && <RoleCard role={my.role} mates={my.mates} players={players} always={!!v.winner || !actV.my!.alive} />}
|
||||
</section>
|
||||
<News v={v} players={players} />
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<News v={shownV} players={players} />
|
||||
<AfterMotion when={!!v.final}>
|
||||
<FinalReveal v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<div className="mf-grid">
|
||||
<div className="mf-col mf-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} fx={tileFx} />
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} fx={tileFx} hiddenDead={hiddenDead} hideRoles={ph.kind === 'ended' && !endShown} />
|
||||
</div>
|
||||
<div className="mf-col mf-chatwrap">
|
||||
<ChatBox v={v} players={players} me={me} act={act} />
|
||||
<ChatBox v={shownV} players={players} me={me} act={act} />
|
||||
</div>
|
||||
<div className="mf-col mf-actions">
|
||||
<Actions v={v} players={players} me={me} act={act} pending={pending} />
|
||||
<Actions v={actV} players={players} me={me} act={act} pending={pending} />
|
||||
</div>
|
||||
</div>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -960,6 +997,7 @@ function composition(setup: MafiaView['setup']): string {
|
||||
}
|
||||
|
||||
function MafiaSide({ view: v, players }: BoardProps<MafiaView>) {
|
||||
const events = useShownEvents(v);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -970,11 +1008,11 @@ function MafiaSide({ view: v, players }: BoardProps<MafiaView>) {
|
||||
<span className="small">이번 판 직업: {composition(v.setup)}</span>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
</div>
|
||||
{v.events.length > 0 && (
|
||||
{events.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>발표 기록</summary>
|
||||
<ol className="mf-log">
|
||||
{[...v.events]
|
||||
{[...events]
|
||||
.reverse()
|
||||
.filter((e) => e.t !== 'phase')
|
||||
.map((e) => (
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { itemsOf, type Item } from './replay';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4'];
|
||||
|
||||
@@ -692,6 +692,10 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) {
|
||||
pump();
|
||||
}, [r?.no, lastN]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The drawing replays the race step by step with timers: results (scores, the next race, 결과) wait for it.
|
||||
const w = d.current;
|
||||
useMotionHold(!!w.timer || w.q.length > 0 || !!w.walk || !!w.die?.rolling);
|
||||
|
||||
return { d: d.current, floats, confetti, banner };
|
||||
}
|
||||
|
||||
@@ -1019,7 +1023,13 @@ const STEP_TITLE: Record<MaPrompt['step'], string> = {
|
||||
};
|
||||
|
||||
function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; rolling: boolean }) {
|
||||
const pr = v.prompt;
|
||||
// A new choice (it can tell the roll: "다시 굴릴까요?", "4칸 가기") shows once the die and the runners have stopped;
|
||||
// until then the previous one stays, greyed out.
|
||||
const key = v.prompt ? `${v.prompt.owner}|${v.prompt.step}|${v.prompt.racer ?? ''}|${v.prompt.options.map((o) => o.key).join(',')}` : '';
|
||||
const settling = useAfterMotionValue(key) !== key;
|
||||
const kept = useRef(v.prompt);
|
||||
if (!settling) kept.current = v.prompt;
|
||||
const pr = kept.current;
|
||||
if (v.phase !== 'race') return null;
|
||||
const mine = !!pr && pr.owner === me;
|
||||
return (
|
||||
@@ -1033,7 +1043,7 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet
|
||||
</h3>
|
||||
<div className={`ma-opts${pr.options.length > 2 ? ' many' : ''}`} role="group" aria-label={STEP_TITLE[pr.step]}>
|
||||
{pr.options.map((o, i) => (
|
||||
<button key={o.key} type="button" className={`btn ${i === 0 ? 'btn-primary' : 'btn-secondary'} btn-block`} disabled={pending || rolling} onClick={() => act(actionFor(pr, o.key))}>
|
||||
<button key={o.key} type="button" className={`btn ${i === 0 ? 'btn-primary' : 'btn-secondary'} btn-block`} disabled={pending || rolling || settling} onClick={() => act(actionFor(pr, o.key))}>
|
||||
{pr.step === 'roll' && o.key === 'roll' ? `🎲 ${o.label}` : o.label}
|
||||
</button>
|
||||
))}
|
||||
@@ -1059,7 +1069,8 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet
|
||||
}
|
||||
|
||||
function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const r = v.race!;
|
||||
// Positions, falls and places as of the last still screen (the board replays the race behind the view).
|
||||
const r = JSON.parse(useAfterMotionValue(JSON.stringify({ cur: v.race!.cur, racers: v.race!.racers }))) as { cur: RacerId | null; racers: MaRacerView[] };
|
||||
return (
|
||||
<section className="card ma-panel" aria-label="이번 경주 선수">
|
||||
<h3>이번 경주 선수</h3>
|
||||
@@ -1155,7 +1166,9 @@ function Select({ v, me, players, act, pending }: { v: MagicalAthleteView; me: s
|
||||
}
|
||||
|
||||
function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
if (!v.results.length) return null;
|
||||
// A race's result row shows once its finish has been drawn.
|
||||
const results = v.results.slice(0, useAfterMotionValue(v.results.length));
|
||||
if (!results.length) return null;
|
||||
const cell = (id: RacerId | null, rr: RaceResult) => {
|
||||
if (!id) return '—';
|
||||
const o = rr.field.find((x) => x.id === id)!.owner;
|
||||
@@ -1178,7 +1191,7 @@ function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null;
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.results.map((rr) => (
|
||||
{results.map((rr) => (
|
||||
<tr key={rr.no}>
|
||||
<td>
|
||||
{rr.no}
|
||||
@@ -1243,6 +1256,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
const prevLog = useRef<number>(v.race?.log.at(-1)?.n ?? 0);
|
||||
const prevRace = useRef<number>(v.race?.no ?? 0);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
// The race log lists new lines once the board has drawn them.
|
||||
const [logRace, logN] = useAfterMotionValue(`${v.race?.no ?? 0}:${v.race?.log.at(-1)?.n ?? 0}`).split(':').map(Number);
|
||||
const logShown = { race: logRace!, n: logN! };
|
||||
|
||||
// New log lines → screen-reader announcement (the board draws and sounds them).
|
||||
useEffect(() => {
|
||||
@@ -1282,22 +1298,29 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
}, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const r = v.race;
|
||||
// A race's end (the next race's selection, the final table, the header) shows once the board has finished
|
||||
// replaying it; until then the screen stays on the race.
|
||||
const stage = `${v.phase}:${v.raceNo}`;
|
||||
const shownStage = useAfterMotionValue(stage);
|
||||
const ready = shownStage === stage;
|
||||
const [phase, raceNo] = ready ? [v.phase, v.raceNo] : [shownStage.slice(0, shownStage.indexOf(':')), Number(shownStage.slice(shownStage.indexOf(':') + 1))];
|
||||
const medal = v.medals[Math.min(raceNo, v.races) - 1] ?? v.medals[0]!;
|
||||
return (
|
||||
<div className="ma-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="card ma-head">
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? '선수 뽑기' : `${v.raceNo} / ${v.races} 경주`}</strong>
|
||||
{r && v.phase === 'race' && <span className={`ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>}
|
||||
<strong>{phase === 'finished' ? '게임 끝' : phase === 'draft' ? '선수 뽑기' : `${raceNo} / ${v.races} 경주`}</strong>
|
||||
{r && phase === 'race' && <span className={`ma-side-tag ${r.side}`}>{r.side === 'wild' ? '거친 판' : '순한 판'}</span>}
|
||||
<span className="small muted">
|
||||
{v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.gold}점 · 2등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.silver}점
|
||||
{v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {medal.gold}점 · 2등 {medal.silver}점
|
||||
</span>
|
||||
</div>
|
||||
{v.result && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.result && ready && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft && <Draft v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'select' && <Select v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'select' && ready && <Select v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{r && (
|
||||
<>
|
||||
{v.phase !== 'race' && (
|
||||
{v.phase !== 'race' && ready && (
|
||||
<p className="small muted" style={{ margin: 0 }}>
|
||||
{r.no}번째 경주가 끝났을 때 모습이에요.
|
||||
</p>
|
||||
@@ -1307,7 +1330,7 @@ function Board({ view: v, me, players, act, pending }: BoardProps<MagicalAthlete
|
||||
<section className="card ma-panel" aria-label="경주 기록">
|
||||
<h3>경주 기록</h3>
|
||||
<ul className="ma-log" tabIndex={0} aria-label="경주 기록 (최신이 위)">
|
||||
{[...r.log].reverse().map((l) => (
|
||||
{[...r.log.filter((l) => logShown.race === r.no && l.n <= logShown.n)].reverse().map((l) => (
|
||||
<li key={l.n} className={l.kind}>
|
||||
{ICON[l.kind]} {l.text}
|
||||
</li>
|
||||
@@ -1332,11 +1355,15 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps<Magica
|
||||
const [ask, setAsk] = useState(false);
|
||||
const total = v.options.turnSeconds ? v.options.turnSeconds * 1000 : 30_000;
|
||||
const playing = v.phase !== 'finished';
|
||||
// Points change once the finish / star that gave them has been drawn.
|
||||
const scoreKey = v.seats.map((p) => [v.scores[p]!.gold, v.scores[p]!.silver, v.scores[p]!.bonus, v.scores[p]!.total].join(',')).join('|');
|
||||
const shownScores = useAfterMotionValue(scoreKey).split('|');
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 12, gap: 8 }} aria-label="참가자">
|
||||
{v.seats.map((p) => {
|
||||
const sc = v.scores[p]!;
|
||||
{v.seats.map((p, i) => {
|
||||
const [gold, silver, bonus, tot] = (shownScores[i] ?? '').split(',').map(Number);
|
||||
const sc = shownScores.length === v.seats.length ? { gold: gold!, silver: silver!, bonus: bonus!, total: tot! } : v.scores[p]!;
|
||||
const on = active.includes(p);
|
||||
return (
|
||||
<div key={p} style={{ padding: '4px 6px', borderRadius: 10, border: `3px solid ${on ? 'var(--focus)' : 'transparent'}` }}>
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MAHJONG_TILE_CREDIT, Tile, tileName, tileOrder, tileShort } from './Tile';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const WIND = ['동', '남', '서', '북'];
|
||||
const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽'];
|
||||
@@ -141,8 +141,9 @@ function useSeen(v: MahjongView): Seen | null {
|
||||
return s.hand === handId(v) ? s : null;
|
||||
}
|
||||
|
||||
/** A number that pops when it changes (not on the first render). */
|
||||
function Bump({ value, children }: { value: number; children?: ReactNode }) {
|
||||
/** A number that pops when it changes (not on the first render), once the move that changed it has played. */
|
||||
function Bump({ value: live, children }: { value: number; children?: ReactNode }) {
|
||||
const value = useAfterMotionValue(live);
|
||||
const prev = useRef(value);
|
||||
const moved = useRef(false);
|
||||
if (prev.current !== value) {
|
||||
@@ -737,12 +738,12 @@ function MyArea({
|
||||
)}
|
||||
{riichiMode && <p className="mj-hint">밝은 패를 버리면 리치예요. 리치하면 1,000점을 공탁에 내고, 그다음부터는 쯔모한 패만 버려요.</p>}
|
||||
{!myTurn && v.phase === 'playing' && v.turn !== null && v.stage !== 'claim' && <p className="mj-hint muted">{nick(players, v.seats[v.turn]!.id)}님 차례예요.</p>}
|
||||
<ClaimPanel v={v} my={my} act={act} pending={pending} players={players} />
|
||||
<ClaimPanel v={v} my={my} act={act} pending={pending} players={players} deadline={deadline} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser> }) {
|
||||
function ClaimPanel({ v, my, act, pending, players, deadline }: { v: MahjongView; my: MyView; act: (a: unknown) => void; pending: boolean; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
const c = my.claim;
|
||||
const beginner = my.prefs.beginner && v.options.beginnerMode;
|
||||
const [chiPick, setChiPick] = useState(false);
|
||||
@@ -779,7 +780,7 @@ function ClaimPanel({ v, my, act, pending, players }: { v: MahjongView; my: MyVi
|
||||
{from}님이 {what} {tileShort(c.tile)}
|
||||
</strong>
|
||||
</span>
|
||||
<TurnTimer deadline={c.deadline} totalMs={c.totalMs} mine size={40} />
|
||||
<TurnTimer deadline={c.deadline === null ? null : Math.max(c.deadline, deadline ?? c.deadline)} totalMs={c.totalMs} mine size={40} />
|
||||
</div>
|
||||
<div className="mj-actions">
|
||||
{c.ron && (
|
||||
@@ -1155,7 +1156,10 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const wide = width >= 900;
|
||||
const reserve = v.my ? 300 : 20;
|
||||
const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560)) : width || 360;
|
||||
const showTable = v.phase === 'playing' || (v.phase === 'handResult' && !wide);
|
||||
// The hand's result (and the final ranking) shows once the 론·쯔모·유국 banner and the last tiles have finished.
|
||||
const resultShown = useMotionSettled(v.phase === 'handResult' && !!v.result);
|
||||
const finalShown = useMotionSettled(v.phase === 'finished');
|
||||
const showTable = v.phase === 'playing' || (v.phase === 'handResult' && (!wide || !resultShown));
|
||||
return (
|
||||
<div className={`mj${wide ? ' wide' : ''}`} ref={ref}>
|
||||
<style>{CSS}</style>
|
||||
@@ -1165,8 +1169,8 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
))}
|
||||
</ul>
|
||||
<div className="mj-main" style={wide ? { width: tableWidth, maxHeight: mainH > 0 ? mainH - 12 : undefined } : undefined}>
|
||||
{v.phase === 'handResult' && v.result && <ResultPanel v={v} players={players} me={me} act={act} pending={pending} deadline={deadline} />}
|
||||
{v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||||
{resultShown && v.phase === 'handResult' && v.result && <ResultPanel v={v} players={players} me={me} act={act} pending={pending} deadline={deadline} />}
|
||||
{finalShown && v.phase === 'finished' && <FinalPanel v={v} players={players} me={me} />}
|
||||
{showTable && (
|
||||
<div className="mj-table-wrap">
|
||||
<Table v={v} players={players} width={tableWidth} callout={callout ? <span key={callout.seq} className={`mj-callout c-${callout.call}`}>{callout.text}</span> : null} seen={seen} />
|
||||
@@ -1217,6 +1221,8 @@ function Toggles({ v, act, pending }: { v: MahjongView; act: (a: unknown) => voi
|
||||
}
|
||||
|
||||
function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProps<MahjongView>) {
|
||||
// A hand's score change is listed once its result has played on the board.
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const turnSeat = v.phase === 'playing' && v.stage !== 'claim' ? v.turn : null;
|
||||
return (
|
||||
<>
|
||||
@@ -1257,11 +1263,11 @@ function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProp
|
||||
</ol>
|
||||
</div>
|
||||
<Toggles v={v} act={act} pending={pending} />
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<details className="card" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>국별 점수 변화</summary>
|
||||
<ol className="mj-hist">
|
||||
{[...v.history].reverse().map((h, i) => (
|
||||
{[...history].reverse().map((h, i) => (
|
||||
<li key={i}>
|
||||
<strong>{h.label}</strong> {h.kind === 'agari' ? '화료' : h.kind === 'exhaustive' ? '유국' : '도중유국'} ·{' '}
|
||||
{v.seats.map((s) => `${nick(players, s.id)} ${signed(h.deltas[s.seat]!)}`).join(' / ')}
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { newEvents, toSegments, type Seg } from './events';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
type GameEvent = MarbleView['log'][number];
|
||||
|
||||
@@ -514,10 +514,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
for (;;) {
|
||||
const seg = w.q[0];
|
||||
if (!seg) {
|
||||
if (w.cur) {
|
||||
w.cur = null;
|
||||
rerender((x) => x + 1);
|
||||
}
|
||||
// Always re-render at the end of the queue: the motion hold below is read from the walker while rendering.
|
||||
w.cur = null;
|
||||
rerender((x) => x + 1);
|
||||
return;
|
||||
}
|
||||
const wait = w.hold - Date.now();
|
||||
@@ -626,19 +625,28 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
seen.current.current = v.current;
|
||||
}, [v.current]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// The dice and the walking tokens are played with timers: results (and the room's result window) wait for them.
|
||||
const walking = rolling !== null || !!walker.current.cur || walker.current.q.length > 0;
|
||||
useMotionHold(walking);
|
||||
// What the view says now shows once the board has caught up (the prompt, new owners). `v.owned` / `v.log` come
|
||||
// straight from the view state, so their identity only changes with a new view.
|
||||
const owned = useAfterMotionValue(v.owned);
|
||||
const stepKey = [v.phase, v.current, v.lastRoll?.seq ?? 0, JSON.stringify(v.log[v.log.length - 1] ?? null)].join('|');
|
||||
const settled = useAfterMotionValue(stepKey) === stepKey;
|
||||
|
||||
// Newly bought land / new building: pop in once (not on the first render).
|
||||
const ownSeen = useRef(new Map(v.owned.map((o) => [o.pos, o])));
|
||||
const ownSeen = useRef(new Map(owned.map((o) => [o.pos, o])));
|
||||
const [fresh, setFresh] = useState<Record<number, { claim?: string; level?: number }>>({});
|
||||
useLayoutEffect(() => {
|
||||
const upd: Record<number, { claim?: string; level?: number }> = {};
|
||||
for (const o of v.owned) {
|
||||
for (const o of owned) {
|
||||
const was = ownSeen.current.get(o.pos);
|
||||
if (!was || was.owner !== o.owner) upd[o.pos] = { claim: o.owner };
|
||||
else if (o.level > was.level) upd[o.pos] = { level: o.level };
|
||||
}
|
||||
ownSeen.current = new Map(v.owned.map((o) => [o.pos, o]));
|
||||
ownSeen.current = new Map(owned.map((o) => [o.pos, o]));
|
||||
if (Object.keys(upd).length) setFresh((f) => ({ ...f, ...upd }));
|
||||
}, [v.owned]);
|
||||
}, [owned]);
|
||||
|
||||
const moveCell = (to: number) => {
|
||||
const n = (to + 40) % 40;
|
||||
@@ -664,9 +672,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
|
||||
const ownedAt = useMemo(() => {
|
||||
const m = new Map<number, MarbleOwnedView>();
|
||||
for (const o of v.owned) m.set(o.pos, o);
|
||||
for (const o of owned) m.set(o.pos, o);
|
||||
return m;
|
||||
}, [v.owned]);
|
||||
}, [owned]);
|
||||
const seatOf = (id: string) => v.players.find((p) => p.id === id)?.seat ?? 0;
|
||||
const walk = walker.current.cur;
|
||||
const trail = walk && walk.seg.walk ? new Set(walk.seg.path.slice(1, walk.i + 1)) : null;
|
||||
@@ -786,7 +794,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps<MarbleVi
|
||||
})}
|
||||
</svg>
|
||||
<div className="mb-center">
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling !== null} card={card} onCardClose={() => setCard(null)} />
|
||||
<Center view={v} me={me} players={players} act={act} pending={pending} rolling={rolling !== null} settled={settled} card={card} onCardClose={() => setCard(null)} />
|
||||
</div>
|
||||
{banner && (
|
||||
<div className="mb-banner-wrap" aria-hidden>
|
||||
@@ -835,6 +843,7 @@ function Center({
|
||||
act,
|
||||
pending,
|
||||
rolling,
|
||||
settled,
|
||||
card,
|
||||
onCardClose,
|
||||
}: {
|
||||
@@ -844,6 +853,8 @@ function Center({
|
||||
act: (a: unknown) => void;
|
||||
pending: boolean;
|
||||
rolling: boolean;
|
||||
/** The dice and tokens have finished showing the latest move: the prompt and the result may show. */
|
||||
settled: boolean;
|
||||
card: { id: CardId; player: string; seq: number } | null;
|
||||
onCardClose: () => void;
|
||||
}) {
|
||||
@@ -894,8 +905,15 @@ function Center({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{v.phase !== 'finished' && <Prompt view={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
{v.phase !== 'finished' &&
|
||||
(settled ? (
|
||||
<Prompt view={v} me={me} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<div className="mb-prompt" role="status">
|
||||
<p>…</p>
|
||||
</div>
|
||||
))}
|
||||
{settled && v.phase === 'finished' && v.result && (
|
||||
<div className="mb-prompt">
|
||||
<h3>{v.result.summary}</h3>
|
||||
</div>
|
||||
@@ -1189,7 +1207,9 @@ function SpaceSheet({
|
||||
|
||||
// ---------------------------------------------------------------- side panel
|
||||
|
||||
function PlayerCard({ p, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
function PlayerCard({ p: live, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record<string, PublicUser>; deadline: number | null }) {
|
||||
// Points, lands and 파산 / 무인도 change once the token has got there (the view's player object is stable per view).
|
||||
const p = useAfterMotionValue(live);
|
||||
const active = v.phase !== 'finished' && ((v.phase === 'debt' && v.debt?.debtor === p.id) || (v.phase === 'tradeResponse' && v.trade?.to === p.id) || (v.phase !== 'debt' && v.phase !== 'tradeResponse' && v.current === p.id));
|
||||
const prev = useRef(p.cash);
|
||||
const [delta, setDelta] = useState<{ n: number; k: number } | null>(null);
|
||||
@@ -1447,7 +1467,9 @@ function MarbleSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [trade, setTrade] = useState(false);
|
||||
const ref = useRef<HTMLOListElement>(null);
|
||||
const lines = v.log.map((e) => logLine(e, players)).filter((x): x is string => !!x);
|
||||
// A move is written down once the board has played it.
|
||||
const log = useAfterMotionValue(v.log);
|
||||
const lines = log.map((e) => logLine(e, players)).filter((x): x is string => !!x);
|
||||
useEffect(() => {
|
||||
ref.current?.scrollTo({ top: ref.current.scrollHeight });
|
||||
}, [v.turnSeq]);
|
||||
|
||||
60
apps/web/src/games/minesweeper/art.tsx
Normal file
60
apps/web/src/games/minesweeper/art.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 지뢰찾기 cell pictures (SVG, no image files). */
|
||||
|
||||
/** SVG units per cell. */
|
||||
export const S = 32;
|
||||
const NUM_COLOR = ['', '#1d4ed8', '#15803d', '#dc2626', '#1e3a8a', '#7f1d1d', '#0f766e', '#111827', '#6b7280'];
|
||||
|
||||
function Flag({ x, y, wrong }: { x: number; y: number; wrong?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M12 7 V25" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<path d="M12 7 L24 11.5 L12 16 Z" fill="#dc2626" />
|
||||
<path d="M8 25 H18" stroke="#111827" strokeWidth={2.4} strokeLinecap="round" />
|
||||
{wrong && <path d="M5 5 L27 27 M27 5 L5 27" stroke="#111827" strokeWidth={2.6} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Mine({ x, y }: { x: number; y: number }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M16 6 V26 M6 16 H26 M9 9 L23 23 M23 9 L9 23" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<circle cx={16} cy={16} r={7.5} fill="#111827" />
|
||||
<circle cx={13.5} cy={13.5} r={2} fill="#fff" opacity={0.8} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small stand-alone pictures for rules and help cards. */
|
||||
export function MiniCell({ ch, size = 30 }: { ch: string; size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 32 32" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
|
||||
<CellArt ch={ch} x={0} y={0} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CellArt({ ch, x, y, cls, i }: { ch: string; x: number; y: number; cls?: string; i?: number }) {
|
||||
const closed = ch === '#' || ch === 'F' || ch === 'x';
|
||||
return (
|
||||
<g className={cls} data-i={i} data-ch={i === undefined ? undefined : ch}>
|
||||
{closed ? (
|
||||
<>
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={4} fill="#e5e7eb" />
|
||||
<path d={`M${x + 2} ${y + S - 3} V${y + 3} Q${x + 2} ${y + 2} ${x + 3} ${y + 2} H${x + S - 3}`} stroke="#fff" strokeWidth={2} fill="none" />
|
||||
<path d={`M${x + 3} ${y + S - 2} H${x + S - 3} Q${x + S - 2} ${y + S - 2} ${x + S - 2} ${y + S - 3} V${y + 3}`} stroke="#9ca3af" strokeWidth={2} fill="none" />
|
||||
</>
|
||||
) : (
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={3} fill={ch === '!' ? '#ef4444' : '#f8fafc'} />
|
||||
)}
|
||||
{(ch === 'F' || ch === 'x') && <Flag x={x} y={y} wrong={ch === 'x'} />}
|
||||
{(ch === '*' || ch === '!') && <Mine x={x} y={y} />}
|
||||
{ch >= '1' && ch <= '8' && (
|
||||
<text x={x + S / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={900} fill={NUM_COLOR[Number(ch)]} pointerEvents="none">
|
||||
{ch}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
17
apps/web/src/games/minesweeper/help.ts
Normal file
17
apps/web/src/games/minesweeper/help.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** 지뢰찾기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'연 칸의 숫자는 그 칸을 둘러싼 8칸에 있는 지뢰 수예요. 지뢰가 없는 칸을 모두 열면 다 푼 거예요.',
|
||||
'지뢰가 확실한 칸에는 깃발을 꽂아요(PC 오른쪽 클릭, 휴대폰 길게 누르기). 깃발 수가 숫자와 같아진 숫자 칸을 누르면 주변을 한꺼번에 열어요.',
|
||||
'지뢰를 밟으면 그 판은 끝이에요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 열기, F로 깃발이에요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '지뢰를 밟았어요.');
|
||||
if (v.board && v.phase === 'playing') return `${lines}\n남은 지뢰(전체 지뢰 − 내 깃발)는 ${v.board.mines - v.board.flags}개예요.`;
|
||||
return lines;
|
||||
}
|
||||
321
apps/web/src/games/minesweeper/index.tsx
Normal file
321
apps/web/src/games/minesweeper/index.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
/** 지뢰찾기 화면 (docs/games/minesweeper.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { LEVELS, type Level, type MinesweeperOptions, type MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { CellArt, MiniCell, S } from './art';
|
||||
|
||||
const FAIL = '지뢰를 밟았어요!';
|
||||
const LONG_PRESS_MS = 420;
|
||||
|
||||
type Cell = [number, number];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ms-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation;
|
||||
border-radius: 10px; background: #9ca3af; box-shadow: var(--shadow); outline: none; cursor: pointer; }
|
||||
.ms-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ms-board[data-off='true'] { cursor: default; }
|
||||
.ms-new { animation: ms-in .28s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ms-boom { animation: ms-boom .6s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
@keyframes ms-in { from { opacity: 0; transform: scale(.6); } }
|
||||
@keyframes ms-boom { 0% { transform: scale(.4); } 40% { transform: scale(1.3); } 100% { transform: scale(1); } }
|
||||
@media (prefers-reduced-motion: reduce) { .ms-new, .ms-boom { animation: none; } }
|
||||
`;
|
||||
|
||||
const describeCh = (ch: string) =>
|
||||
ch === '#' ? '닫힌 칸' : ch === 'F' ? '깃발' : ch === '0' ? '빈 칸' : ch === '*' ? '지뢰' : ch === '!' ? '터진 지뢰' : ch === 'x' ? '잘못 꽂은 깃발' : `숫자 ${ch}`;
|
||||
|
||||
function MinesBoard({ view: v, me, players, act }: BoardProps<MinesweeperView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [flagMode, setFlagMode] = useState(false);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const press = useRef<{ i: number; x: number; y: number; timer: ReturnType<typeof setTimeout> | null; long: boolean; button: number } | null>(null);
|
||||
const prev = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
// Newly opened cells pop in; sounds for what changed.
|
||||
useEffect(() => {
|
||||
const cur = b?.cells ?? null;
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!cur || !was || was.length !== cur.length) return;
|
||||
const added = new Set<number>();
|
||||
let flagged = 0;
|
||||
for (let i = 0; i < cur.length; i++) {
|
||||
if (was[i] === '#' && cur[i]! >= '0' && cur[i]! <= '8') added.add(i);
|
||||
if (was[i] !== cur[i] && (cur[i] === 'F' || was[i] === 'F') && cur[i] !== '*') flagged++;
|
||||
}
|
||||
if (cur.includes('!') && !was.includes('!')) {
|
||||
noise(500, 0.2, 0, 'lowpass', 400, 0.7);
|
||||
haptic([30, 40, 60]);
|
||||
} else if (added.size > 8) sfx.whoosh();
|
||||
else if (added.size) tone(900, 40, 'triangle', 0.1);
|
||||
else if (flagged === 1) tone(640, 50, 'square', 0.05);
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(320));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.cells]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자를 보고 지뢰를 피해 모든 칸을 열어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const turn = phone && b.cols > b.rows;
|
||||
const dR = turn ? b.cols : b.rows;
|
||||
const dC = turn ? b.rows : b.cols;
|
||||
const toDisp = (i: number): Cell => {
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
return turn ? [c, b.rows - 1 - r] : [r, c];
|
||||
};
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (b.rows - 1 - dc) * b.cols + dr : dr * b.cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }) => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1);
|
||||
const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1);
|
||||
return toIndex(dr, dc);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${describeCh(b.cells[i]!)}`;
|
||||
};
|
||||
/** Primary action on a cell: open a closed one, open around a number, or flag (깃발 mode / right click / long press). */
|
||||
const hit = (i: number, flag: boolean) => {
|
||||
if (!playing) return;
|
||||
const ch = b.cells[i]!;
|
||||
if (flag) {
|
||||
if (ch === '#' || ch === 'F') {
|
||||
act({ type: 'flag', i });
|
||||
haptic(10);
|
||||
setAnnounce(ch === 'F' ? '깃발을 치웠어요.' : '깃발을 꽂았어요.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ch === '#') act({ type: 'open', i });
|
||||
else if (ch >= '1' && ch <= '8') {
|
||||
// A number opens the cells around it once its flags match.
|
||||
let flags = 0;
|
||||
let closed = 0;
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
for (let y = r - 1; y <= r + 1; y++)
|
||||
for (let x = c - 1; x <= c + 1; x++) {
|
||||
if (y < 0 || x < 0 || y >= b.rows || x >= b.cols || (y === r && x === c)) continue;
|
||||
const k = b.cells[y * b.cols + x];
|
||||
if (k === 'F') flags++;
|
||||
else if (k === '#') closed++;
|
||||
}
|
||||
if (closed && flags === Number(ch)) act({ type: 'chord', i });
|
||||
else if (closed) setAnnounce(`주변 깃발이 ${flags}개예요. ${ch}개를 꽂아야 한꺼번에 열 수 있어요.`);
|
||||
} else if (ch === 'F') setAnnounce('깃발을 꽂은 칸이에요. 깃발 모드나 오른쪽 클릭으로 치워요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing) return;
|
||||
const i = cellAt(e);
|
||||
setCursor(i);
|
||||
const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType<typeof setTimeout> | null, long: false, button: e.button };
|
||||
if (e.pointerType !== 'mouse')
|
||||
p.timer = setTimeout(() => {
|
||||
p.long = true;
|
||||
hit(p.i, !flagMode);
|
||||
}, LONG_PRESS_MS);
|
||||
press.current = p;
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > 10) {
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
press.current = null; // scrolling, not a tap
|
||||
}
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (!p) return;
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
if (p.long) return;
|
||||
if (cellAt(e) !== p.i) return;
|
||||
hit(p.i, p.button === 2 || flagMode);
|
||||
};
|
||||
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, Cell> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const [dr, dc] = toDisp(cursor);
|
||||
const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) hit(cursor, flagMode);
|
||||
} else if (e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') {
|
||||
e.preventDefault();
|
||||
hit(cursor, true);
|
||||
}
|
||||
};
|
||||
|
||||
const [cr, cc] = toDisp(cursor);
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${dC * 56}px, calc((var(--play-h, 100vh) - 170px) * ${dC / dR}))`, minWidth: Math.min(280, dC * 22) };
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 지뢰 ${b.mines - b.flags}개`}>
|
||||
💣 <b>{b.mines - b.flags}</b>
|
||||
</span>
|
||||
{mine && v.phase === 'playing' && (
|
||||
<button type="button" className="rc-pill" aria-pressed={flagMode} onClick={() => setFlagMode((f) => !f)} aria-label="깃발 모드">
|
||||
{flagMode ? '🚩 깃발 꽂기' : '⛏ 칸 열기'}
|
||||
</button>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ms-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${dC * S} ${dR * S}`}
|
||||
role="application"
|
||||
aria-roledescription="지뢰 판"
|
||||
aria-label={playing ? `지뢰 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 열기, F로 깃발. 지금 ${describe(cursor)}` : '지뢰 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => {
|
||||
if (press.current?.timer) clearTimeout(press.current.timer);
|
||||
press.current = null;
|
||||
}}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.cells, (ch, i) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return <CellArt key={i} i={i} ch={ch} x={dc * S} y={dr * S} cls={ch === '!' ? 'ms-boom' : fresh.has(i) ? 'ms-new' : undefined} />;
|
||||
})}
|
||||
{focused && playing && <rect x={cc * S + 1.5} y={cr * S + 1.5} width={S - 3} height={S - 3} rx={5} fill="none" stroke="#f59e0b" strokeWidth={3} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`;
|
||||
|
||||
function MinesSide(props: BoardProps<MinesweeperView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="지뢰찾기" info={levelInfo(props.view.options.level)} />;
|
||||
}
|
||||
|
||||
function statusText(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<MinesweeperOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.level}
|
||||
options={(Object.keys(LEVELS) as Level[]).map((l) => [l, LEVELS[l].name])}
|
||||
onChange={(level) => onChange({ ...o, level })}
|
||||
/>
|
||||
<span className="small muted">{levelInfo(o.level)}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[180, 300, 600, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: MinesweeperOptions): string {
|
||||
return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: MinesweeperOptions }) {
|
||||
const level = options?.level ?? 'beginner';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 <strong>모두 열면</strong> 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<MiniCell ch="1" />
|
||||
<MiniCell ch="2" />
|
||||
<MiniCell ch="3" />
|
||||
<span>연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수</span>
|
||||
</div>
|
||||
<p>
|
||||
시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 <MiniCell ch="F" size={22} /> 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이
|
||||
한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요).
|
||||
</p>
|
||||
<p>
|
||||
<strong>지뢰를 밟으면</strong> 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '}
|
||||
{limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<MinesweeperView, MinesweeperOptions> = {
|
||||
Board: MinesBoard,
|
||||
Side: MinesSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/** 지뢰찾기 30초 규칙 요약 (docs/07 §5). Small boards drawn with the game's own cells. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniCell } from './art';
|
||||
|
||||
function Grid({ rows }: { rows: string[] }) {
|
||||
return (
|
||||
<svg viewBox={`0 0 ${rows[0]!.length * 32} ${rows.length * 32}`} width={rows[0]!.length * 30} height={rows.length * 30} aria-hidden>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => (
|
||||
<svg key={`${r}-${c}`} x={c * 32} y={r * 32} width={32} height={32} viewBox="0 0 32 32">
|
||||
<MiniCell ch={ch} size={32} />
|
||||
</svg>
|
||||
)),
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <Grid rows={['1##', '1#1', '110']} />,
|
||||
alt: '닫힌 칸 사이에 숫자 1이 적힌 연 칸들이 있어요',
|
||||
title: '숫자 = 주변 지뢰 수',
|
||||
text: '연 칸의 숫자는 둘러싼 8칸에 있는 지뢰 수예요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F#', '1#1', '110']} />,
|
||||
alt: '지뢰가 확실한 칸에 빨간 깃발을 꽂은 모습이에요',
|
||||
title: '지뢰에는 깃발',
|
||||
text: '지뢰가 확실한 칸에 깃발을 꽂아요(오른쪽 클릭, 휴대폰은 길게 누르기). 지뢰를 밟으면 끝이에요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F1', '111', '110']} />,
|
||||
alt: '지뢰 칸만 남기고 모든 칸이 열렸어요',
|
||||
title: '모든 칸을 열면 승리',
|
||||
text: '지뢰 없는 칸을 모두 열면 다 푼 거예요. 여럿이면 가장 먼저 다 연 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -11,7 +11,7 @@ import { useSeatRows } from '../../lib/seat-rows';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow, resolvedHandSize } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const MODE_KO: Record<NNOptions['mode'], string> = { 'kr-product': '전용 카드', classic: '트럼프 카드' };
|
||||
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
|
||||
@@ -68,6 +68,42 @@ function useCountUp(target: number): number {
|
||||
return shown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The table as of the last still screen: the total, the recent plays, lives / 탈락, the round and the final ranking
|
||||
* change only after the card that caused them has flown to the dial (and its banners have played).
|
||||
*/
|
||||
function useShownTable(v: NinetyNineView) {
|
||||
const total = useAfterMotionValue(v.total);
|
||||
const round = useAfterMotionValue(v.round);
|
||||
const recentKey = useAfterMotionValue(v.recent.map((e) => `${e.seq}-${e.p}`).join(','));
|
||||
const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.lives}:${s.alive ? 1 : 0}`).join(','));
|
||||
const lastKey = v.log.length ? nnLogKey(v.log[v.log.length - 1]!) : '';
|
||||
const shownLastKey = useAfterMotionValue(lastKey);
|
||||
const result = useMotionSettled(!!v.result) ? v.result : null;
|
||||
const seatSnap = new Map(
|
||||
seatKey
|
||||
.split(',')
|
||||
.filter(Boolean)
|
||||
.map((x) => {
|
||||
const [lives, alive] = x.split(':').slice(-2);
|
||||
return [x.split(':').slice(0, -2).join(':'), { lives: Number(lives), alive: alive === '1' }];
|
||||
}),
|
||||
);
|
||||
const recentShown = new Set(recentKey.split(','));
|
||||
const logEnd = v.log.findIndex((e) => nnLogKey(e) === shownLastKey);
|
||||
return {
|
||||
total,
|
||||
round,
|
||||
result,
|
||||
/** The total has not caught up with the last play yet (the card is still in the air). */
|
||||
settling: total !== v.total,
|
||||
recent: v.recent.filter((e) => recentShown.has(`${e.seq}-${e.p}`)),
|
||||
seat: (x: SeatView): SeatView => ({ ...x, ...seatSnap.get(x.id) }),
|
||||
log: logEnd < 0 ? v.log : v.log.slice(0, logEnd + 1),
|
||||
};
|
||||
}
|
||||
type ShownTable = ReturnType<typeof useShownTable>;
|
||||
|
||||
/** Green → yellow → red as the total nears 99. */
|
||||
const gaugeColor = (t: number) => `hsl(${Math.max(0, 130 - (t / 99) * 130)} 78% 46%)`;
|
||||
|
||||
@@ -251,9 +287,9 @@ function seatLabel(s: SeatView, v: NinetyNineView, players: Record<string, Publi
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
function SeatChip({ s, v, players, me, deadline, result }: { s: SeatView; v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; result: NinetyNineView['result'] }) {
|
||||
const u = userOf(players, s.id);
|
||||
const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||
const rank = result?.ranking.find((r) => r.player === s.id)?.rank;
|
||||
return (
|
||||
<li className={`nn-seat${s.isTurn ? ' turn anim-glow' : ''}${s.alive ? '' : ' out'}`} data-fx-seat={s.id} aria-label={seatLabel(s, v, players, me)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
@@ -283,12 +319,13 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineV
|
||||
|
||||
// ---------------------------------------------------------------- table
|
||||
|
||||
function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const shown = useCountUp(v.total);
|
||||
function Table({ v, players, me, deadline, st }: { v: NinetyNineView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; st: ShownTable }) {
|
||||
const total = st.total;
|
||||
const shown = useCountUp(total);
|
||||
const dial = 'max(clamp(150px, 20vw, 196px), var(--nn-dial, 0px))';
|
||||
const r = 44;
|
||||
const c = 2 * Math.PI * r;
|
||||
const frac = Math.min(1, v.total / 99);
|
||||
const frac = Math.min(1, total / 99);
|
||||
const cur = v.current;
|
||||
return (
|
||||
<div className="nn-table" role="region" aria-label="카드 판" style={{ '--dial': dial } as CSSProperties}>
|
||||
@@ -306,12 +343,12 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
<span className="nn-chip" data-fx="nn-deck" aria-label={`뽑을 카드 ${v.drawPileCount}장`}>
|
||||
더미 {v.drawPileCount}장
|
||||
</span>
|
||||
{v.livesStart > 0 && <span className="nn-chip">{v.round}판째</span>}
|
||||
{v.livesStart > 0 && <span className="nn-chip">{st.round}판째</span>}
|
||||
</div>
|
||||
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${v.total}`}>
|
||||
<div className="nn-dial" data-fx="nn-dial" role="img" aria-label={`지금 합계 ${total}`}>
|
||||
<svg viewBox="0 0 100 100" width="100%" height="100%" aria-hidden>
|
||||
<circle cx="50" cy="50" r={r} fill="rgba(0,0,0,.28)" stroke="rgba(255,255,255,.18)" strokeWidth="8" />
|
||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(v.total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||
<circle cx="50" cy="50" r={r} fill="none" stroke={gaugeColor(total)} strokeWidth="8" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} />
|
||||
</svg>
|
||||
<span className="nn-total" aria-hidden>
|
||||
{shown}
|
||||
@@ -322,9 +359,9 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
</div>
|
||||
<div className="nn-right">
|
||||
<span className="nn-rule">99를 넘기면 안 돼요!</span>
|
||||
{v.recent.length > 0 ? (
|
||||
{st.recent.length > 0 ? (
|
||||
<ol className="nn-recent" aria-label="최근에 낸 카드">
|
||||
{v.recent.slice(-4).map((e) => (
|
||||
{st.recent.slice(-4).map((e) => (
|
||||
<li key={`${e.seq}-${e.p}`}>
|
||||
<span className="who">{nick(players, e.p)}</span>
|
||||
<Mini face={e.face} kind={e.kind} />
|
||||
@@ -335,7 +372,7 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<span className="nn-chip">{v.round > 1 ? `${v.round}판 시작! 합계 ${v.total}` : v.total > 0 ? `시작 숫자 ${v.total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'}</span>
|
||||
<span className="nn-chip">{st.round > 1 ? `${st.round}판 시작! 합계 ${total}` : total > 0 ? `시작 숫자 ${total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -402,11 +439,12 @@ function JokerDial({ c, total, pending, onPlay }: { c: HandCardView; total: numb
|
||||
);
|
||||
}
|
||||
|
||||
function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function MyHand({ v, act, pending, st }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean; st: ShownTable }) {
|
||||
const my = v.my!;
|
||||
const [sel, setSel] = useState<string | null>(null);
|
||||
const [note, setNote] = useState('');
|
||||
const myTurn = my.myTurn;
|
||||
// The previews (→ new total) and legality give the new total away: they show once the last card has landed.
|
||||
const myTurn = my.myTurn && !st.settling;
|
||||
useEffect(() => {
|
||||
setSel(null);
|
||||
setNote('');
|
||||
@@ -425,6 +463,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
};
|
||||
const single = (c: HandCardView) => c.choices.length === 1 && !c.joker;
|
||||
const tap = (c: HandCardView) => {
|
||||
if (st.settling) return;
|
||||
if (!myTurn) {
|
||||
setNote('지금은 내 차례가 아니에요. 카드를 누르면 낼 때 합계를 미리 볼 수 있어요.');
|
||||
setSel(sel === c.id ? null : c.id);
|
||||
@@ -458,7 +497,8 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
};
|
||||
const n = my.hand.length;
|
||||
const cw = `max(${n <= 3 ? 'clamp(84px, 24vw, 104px)' : n === 4 ? 'clamp(72px, 20vw, 96px)' : 'clamp(62px, 16.5vw, 90px)'}, var(--nn-cw, 0px))`;
|
||||
const meSeat = v.seats.find((s) => s.id === v.me);
|
||||
const meSeatNow = v.seats.find((s) => s.id === v.me);
|
||||
const meSeat = meSeatNow && st.seat(meSeatNow);
|
||||
const legalCount = my.hand.filter((c) => c.legal).length;
|
||||
return (
|
||||
<div className="nn-hand-wrap">
|
||||
@@ -487,7 +527,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v
|
||||
onClick={() => tap(c)}
|
||||
>
|
||||
<span className={`nn-prev ${p.cls}`} aria-hidden>
|
||||
{p.text}
|
||||
{st.settling ? '…' : p.text}
|
||||
</span>
|
||||
<Face face={c.face} kind={c.kind} jokerRange={c.joker ?? undefined} />
|
||||
</button>
|
||||
@@ -582,7 +622,9 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
const myIdx = v.seats.findIndex((s) => s.id === me);
|
||||
const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)];
|
||||
const opps = useSeatRows<HTMLUListElement>(others.length);
|
||||
const meSeat = v.seats.find((s) => s.id === me);
|
||||
const st = useShownTable(v);
|
||||
const meSeatNow = v.seats.find((s) => s.id === me);
|
||||
const meSeat = meSeatNow && st.seat(meSeatNow);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useNinetyNineFx(v, me, players, showBanner);
|
||||
return (
|
||||
@@ -590,11 +632,11 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps<Nine
|
||||
<style>{CSS}</style>
|
||||
<ul className="nn-opps" aria-label="다른 사람" ref={opps.ref} style={opps.style}>
|
||||
{others.map((s) => (
|
||||
<SeatChip key={s.id} s={s} v={v} players={players} me={me} deadline={deadline} />
|
||||
<SeatChip key={s.id} s={st.seat(s)} v={v} players={players} me={me} deadline={deadline} result={st.result} />
|
||||
))}
|
||||
</ul>
|
||||
<Table v={v} players={players} me={me} deadline={deadline} />
|
||||
{v.my && meSeat?.alive && v.phase === 'playing' && <MyHand v={v} act={act} pending={pending} />}
|
||||
<Table v={v} players={players} me={me} deadline={deadline} st={st} />
|
||||
{v.my && meSeat?.alive && v.phase === 'playing' && <MyHand v={v} act={act} pending={pending} st={st} />}
|
||||
{meSeat && !meSeat.alive && v.phase === 'playing' && (
|
||||
<div className="nn-panel">
|
||||
<strong>{meSeat.left ? '게임에서 나갔어요.' : '탈락했어요. 남은 게임을 지켜봐요.'}</strong>
|
||||
@@ -659,8 +701,10 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<s
|
||||
};
|
||||
useNewEntries(v.log, nnLogKey, (fresh) => {
|
||||
let t = 0;
|
||||
// When the last played card reaches the dial: what it caused (no card, a life, 탈락) shows after that.
|
||||
let landed = 0;
|
||||
for (const e of fresh) {
|
||||
const at = t;
|
||||
const at = e.t === 'play' ? t : Math.max(t, landed);
|
||||
switch (e.t) {
|
||||
case 'play': {
|
||||
const from = e.p === me ? (myPlayRect ?? fxEl('nn-hand')) : seatEl(e.p);
|
||||
@@ -676,26 +720,32 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record<s
|
||||
if (e.kind === 'to99') later(at + 300, () => showBanner('99!', 'red', `${who(e.p)} 바로 99`));
|
||||
// Refill: the player takes one card from the pile (mine flies in from MyHand).
|
||||
if (v.options.refill && e.p !== me) flyGhost(fxEl('nn-deck'), seatEl(e.p), { delay: at + 420, ms: 380 });
|
||||
landed = at + 400;
|
||||
t += 160;
|
||||
break;
|
||||
}
|
||||
case 'noCard':
|
||||
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||
later(at, sfx.bad);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
later(at, () => {
|
||||
showBanner('낼 카드가 없어요!', 'red', who(e.p));
|
||||
sfx.bad();
|
||||
bump(seatEl(e.p), 'shake');
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'life':
|
||||
later(at, nnSfx.heart);
|
||||
bump(seatEl(e.p), 'shake');
|
||||
t += 200;
|
||||
later(at, () => {
|
||||
nnSfx.heart();
|
||||
bump(seatEl(e.p), 'shake');
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'out':
|
||||
if (e.why === 'noCard') {
|
||||
showBanner('탈락!', 'dark', who(e.p));
|
||||
later(at + 120, sfx.bad);
|
||||
}
|
||||
t += 200;
|
||||
if (e.why === 'noCard')
|
||||
later(at, () => {
|
||||
showBanner('탈락!', 'dark', who(e.p));
|
||||
later(120, sfx.bad);
|
||||
});
|
||||
t = at + 200;
|
||||
break;
|
||||
case 'round':
|
||||
if (e.round > 1) {
|
||||
@@ -760,6 +810,7 @@ function rulesLine(o: NNOptions): string {
|
||||
}
|
||||
|
||||
function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
const st = useShownTable(v);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -767,14 +818,14 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
구십구 · {MODE_KO[v.mode]}
|
||||
{v.livesStart > 0 ? ` · ${v.round}판` : ''}
|
||||
{v.phase === 'finished' ? ' · 게임 끝' : ''}
|
||||
{v.livesStart > 0 ? ` · ${st.round}판` : ''}
|
||||
{st.result ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
{v.current && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
|
||||
</div>
|
||||
<span className="small muted">{rulesLine(v.options)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.seats.map((s) => (
|
||||
{v.seats.map(st.seat).map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.alive ? 1 : 0.55 }} aria-label={seatLabel(s, v, players, me)}>
|
||||
<span style={{ filter: s.alive ? 'none' : 'grayscale(1)', display: 'inline-flex' }}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
@@ -796,10 +847,10 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{st.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
{st.result.ranking.map((r) => (
|
||||
<span key={r.player}>
|
||||
{r.rank}등 {nick(players, r.player)}
|
||||
<span className="muted small">
|
||||
@@ -808,14 +859,14 @@ function Side({ view: v, me, players, deadline }: BoardProps<NinetyNineView>) {
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
<span className="small muted">{st.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
{v.log.length > 0 && (
|
||||
{st.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
<ol className="nn-log">
|
||||
{[...v.log].reverse().map((e, i) => (
|
||||
{[...st.log].reverse().map((e, i) => (
|
||||
<li key={`${e.seq}-${e.t}-${i}`} className="small">
|
||||
{logText(e, players)}
|
||||
</li>
|
||||
|
||||
53
apps/web/src/games/nonogram/art.tsx
Normal file
53
apps/web/src/games/nonogram/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 네모네모 로직 small pictures for the rules and the 30-second cards (SVG, no image files). */
|
||||
|
||||
/** Run lengths of the '#' cells; an empty line is [0]. */
|
||||
export function runsOf(line: string): number[] {
|
||||
const out = line.split(/[^#]+/).filter(Boolean).map((s) => s.length);
|
||||
return out.length ? out : [0];
|
||||
}
|
||||
|
||||
/**
|
||||
* A small puzzle: clues from `answer`, cells from `marks` ('#' filled, 'x' X, '.' empty; default = the answer).
|
||||
* `color` paints the filled cells (a solved picture).
|
||||
*/
|
||||
export function MiniNono({ answer, marks = answer, color, cell = 22 }: { answer: string[]; marks?: string[]; color?: string; cell?: number }) {
|
||||
const n = answer.length;
|
||||
const S = 20;
|
||||
const rows = answer.map(runsOf);
|
||||
const cols = Array.from({ length: n }, (_, c) => runsOf(answer.map((r) => r[c]).join('')));
|
||||
const left = Math.max(...rows.map((r) => r.length)) * 12 + 6;
|
||||
const top = Math.max(...cols.map((c) => c.length)) * 13 + 4;
|
||||
const w = left + n * S;
|
||||
const h = top + n * S;
|
||||
return (
|
||||
<svg viewBox={`0 0 ${w} ${h}`} width={(w * cell) / S} height={(h * cell) / S} aria-hidden style={{ maxWidth: '100%', height: 'auto' }}>
|
||||
{cols.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} x={left + c * S + S / 2} y={top - 4 - (clue.length - 1 - j) * 13} textAnchor="middle" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rows.map((clue, r) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`r${r}-${j}`} x={left - 6 - (clue.length - 1 - j) * 12} y={top + r * S + 14.5} textAnchor="end" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{marks.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const x = left + c * S;
|
||||
const y = top + r * S;
|
||||
return (
|
||||
<g key={`${r}-${c}`}>
|
||||
<rect x={x} y={y} width={S} height={S} fill={ch === '#' ? (color ?? 'var(--text)') : 'var(--surface)'} stroke="var(--border)" strokeWidth={1} />
|
||||
{ch === 'x' && <path d={`M${x + 6} ${y + 6} L${x + S - 6} ${y + S - 6} M${x + S - 6} ${y + 6} L${x + 6} ${y + S - 6}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
<rect x={left} y={top} width={n * S} height={n * S} fill="none" stroke="var(--text-sub)" strokeWidth={1.5} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
18
apps/web/src/games/nonogram/help.ts
Normal file
18
apps/web/src/games/nonogram/help.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** 네모네모 로직 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'줄 옆의 숫자는 그 줄에서 이어서 칠할 칸 수예요. 숫자가 여러 개면 그 순서대로, 덩어리 사이는 한 칸 이상 띄어요.',
|
||||
'모든 가로줄과 세로줄이 숫자와 맞게 칠하면 그림이 나오고 다 푼 거예요. 칠한 칸이 맞는지는 알려 주지 않아요.',
|
||||
'비어야 할 칸에는 ✕를 해 두면 헷갈리지 않아요(PC 오른쪽 클릭, 휴대폰은 [✕ 표시]로 바꿔서). 끌면 한 줄을 한 번에 칠해요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 칠하기, X로 ✕ 표시예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
if (v.board && v.phase === 'playing' && v.options.hints && v.seats.some((s) => s.id === me && s.status === 'playing'))
|
||||
return `${lines}\n막히면 [💡 힌트]로 틀렸거나 모르는 칸 하나를 바르게 고칠 수 있어요(쓴 횟수는 결과에 나와요). 지금까지 ${v.board.hints}번 썼어요.`;
|
||||
return lines;
|
||||
}
|
||||
412
apps/web/src/games/nonogram/index.tsx
Normal file
412
apps/web/src/games/nonogram/index.tsx
Normal file
@@ -0,0 +1,412 @@
|
||||
/** 네모네모 로직 화면 (docs/games/nonogram.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import type { MarkValue, NonogramOptions, NonogramSize, NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniNono, runsOf } from './art';
|
||||
|
||||
/** SVG units per cell. */
|
||||
const S = 20;
|
||||
const SIZE_NAME: Record<NonogramSize, string> = { 5: '쉬움', 10: '보통', 15: '어려움' };
|
||||
const sizeInfo = (n: NonogramSize) => `${n}×${n} ${SIZE_NAME[n]}`;
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const MARK_WORD: Record<string, string> = { '0': '빈 칸', '1': '칠한 칸', '2': '✕ 표시' };
|
||||
|
||||
const CSS = `
|
||||
.ng-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none;
|
||||
border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); outline: none; cursor: crosshair; }
|
||||
.ng-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ng-board[data-off='true'] { cursor: default; }
|
||||
.ng-clue { font-weight: 800; fill: var(--text); transition: opacity .3s; }
|
||||
.ng-clue[data-ok='true'] { opacity: .3; }
|
||||
.ng-new { animation: ng-in .22s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-color { animation: ng-color .7s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-hint { animation: ng-hint 1.2s ease-out 2 both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-title { font-weight: 900; font-size: 1.15rem; color: var(--success); margin: 0; text-align: center; }
|
||||
.ng-title.ans { color: var(--text-sub); font-size: 1rem; }
|
||||
@keyframes ng-in { from { transform: scale(.4); } }
|
||||
@keyframes ng-color { 0% { fill: var(--text); transform: scale(1); } 40% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes ng-hint { 0% { opacity: 1; stroke-width: 4; } 100% { opacity: .2; stroke-width: 2; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ng-new, .ng-color, .ng-hint { animation: none; } .ng-clue { transition: none; } }
|
||||
`;
|
||||
|
||||
interface Drag {
|
||||
start: number;
|
||||
end: number;
|
||||
axis: 'row' | 'col' | null;
|
||||
/** The mark the first cell had: the drag only changes cells that have it too. */
|
||||
from: string;
|
||||
value: MarkValue;
|
||||
}
|
||||
|
||||
function NonoBoard({ view: v, me, players, act }: BoardProps<NonogramView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [mode, setMode] = useState<1 | 2>(1);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [drag, setDrag] = useState<Drag | null>(null);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prev = useRef<{ marks: string; ok: number; hint: number | null } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const n = b?.size ?? 10;
|
||||
const rowClues = (b?.rows ?? []).map((c) => (c.length ? c : [0]));
|
||||
const colClues = (b?.cols ?? []).map((c) => (c.length ? c : [0]));
|
||||
const lineOf = (line: number) => (line < n ? Array.from({ length: n }, (_, c) => line * n + c) : Array.from({ length: n }, (_, r) => r * n + line - n));
|
||||
const okLines = b ? [...rowClues, ...colClues].map((clue, line) => runsOf(lineOf(line).map((i) => (b.marks[i] === '1' ? '#' : '.')).join('')).join() === clue.join()) : [];
|
||||
const okCount = okLines.filter(Boolean).length;
|
||||
|
||||
// Sounds and the pop of newly marked cells; say when a line comes right.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const was = prev.current;
|
||||
prev.current = { marks: b.marks, ok: okCount, hint: b.lastHint };
|
||||
if (!was || was.marks.length !== b.marks.length) return;
|
||||
const changed = new Set<number>();
|
||||
let filled = 0;
|
||||
let crossed = 0;
|
||||
for (let i = 0; i < b.marks.length; i++) {
|
||||
if (was.marks[i] === b.marks[i]) continue;
|
||||
changed.add(i);
|
||||
if (b.marks[i] === '1') filled++;
|
||||
else if (b.marks[i] === '2') crossed++;
|
||||
}
|
||||
if (b.lastHint !== was.hint && b.hints) sfx.pop();
|
||||
else if (okCount > was.ok) tone(1175, 90, 'triangle', 0.09);
|
||||
else if (filled) tone(820, 40, 'triangle', 0.1);
|
||||
else if (crossed) tone(520, 40, 'square', 0.04);
|
||||
else if (changed.size) tone(400, 40, 'sine', 0.06);
|
||||
if (okCount !== was.ok) setAnnounce(`맞는 줄 ${okCount}/${2 * n}`);
|
||||
if (changed.size) {
|
||||
setFresh(changed);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(260));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.marks, b?.lastHint]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자대로 칸을 칠해 그림을 완성해요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Layout in SVG units: row clues on the left, column clues on top, then the grid.
|
||||
const numW = (x: number) => (x >= 10 ? 0.95 : 0.62) * S;
|
||||
const L = Math.max(...rowClues.map((c) => c.reduce((a, x) => a + numW(x), 0))) + 0.4 * S;
|
||||
const T = Math.max(...colClues.map((c) => c.length)) * 0.72 * S + 0.35 * S;
|
||||
const W = L + n * S;
|
||||
const H = T + n * S;
|
||||
const answer = b.answer;
|
||||
|
||||
const cellAt = (e: { clientX: number; clientY: number }, inside: boolean): number | null => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const k = W / box.width;
|
||||
const c = Math.floor(((e.clientX - box.left) * k - L) / S);
|
||||
const r = Math.floor(((e.clientY - box.top) * k - T) / S);
|
||||
if (inside && (c < 0 || r < 0 || c >= n || r >= n)) return null;
|
||||
return clamp(r, 0, n - 1) * n + clamp(c, 0, n - 1);
|
||||
};
|
||||
const dragCells = (d: Drag): number[] => {
|
||||
const r0 = Math.floor(d.start / n);
|
||||
const c0 = d.start % n;
|
||||
const out: number[] = [];
|
||||
if (d.axis === 'row') {
|
||||
const c1 = d.end % n;
|
||||
for (let c = c0; ; c += Math.sign(c1 - c0)) {
|
||||
out.push(r0 * n + c);
|
||||
if (c === c1) break;
|
||||
}
|
||||
} else if (d.axis === 'col') {
|
||||
const r1 = Math.floor(d.end / n);
|
||||
for (let r = r0; ; r += Math.sign(r1 - r0)) {
|
||||
out.push(r * n + c0);
|
||||
if (r === r1) break;
|
||||
}
|
||||
} else out.push(d.start);
|
||||
return out.filter((i) => b.marks[i] === d.from);
|
||||
};
|
||||
const valueFor = (i: number, m: 1 | 2): MarkValue => (b.marks[i] === String(m) ? 0 : m);
|
||||
const paint = (cells: number[], value: MarkValue) => {
|
||||
if (!playing || !cells.length) return;
|
||||
act({ type: 'paint', cells, value });
|
||||
haptic(8);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 2)) return;
|
||||
const i = cellAt(e, true);
|
||||
if (i === null) return;
|
||||
e.preventDefault();
|
||||
svgRef.current!.setPointerCapture?.(e.pointerId);
|
||||
setCursor(i);
|
||||
setDrag({ start: i, end: i, axis: null, from: b.marks[i]!, value: valueFor(i, e.button === 2 ? 2 : mode) });
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!drag) return;
|
||||
const i = cellAt(e, false)!;
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
const r0 = Math.floor(drag.start / n);
|
||||
const c0 = drag.start % n;
|
||||
if (i === drag.start && !drag.axis) return;
|
||||
// The first step away from the start cell decides the row or column; then the line follows the pointer along it.
|
||||
const axis = drag.axis ?? (r === r0 ? 'row' : c === c0 ? 'col' : Math.abs(c - c0) >= Math.abs(r - r0) ? 'row' : 'col');
|
||||
const end = axis === 'row' ? r0 * n + c : r * n + c0;
|
||||
if (end !== drag.end || axis !== drag.axis) setDrag({ ...drag, axis, end });
|
||||
};
|
||||
const onUp = () => {
|
||||
if (!drag) return;
|
||||
setDrag(null);
|
||||
paint(dragCells(drag), drag.value);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
return `${r + 1}줄 ${c + 1}칸, ${MARK_WORD[b.marks[i]!]}. 가로 숫자 ${rowClues[r]!.join(' ')}, 세로 숫자 ${colClues[c]!.join(' ')}`;
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const next = clamp(Math.floor(cursor / n) + m[0], 0, n - 1) * n + clamp((cursor % n) + m[1], 0, n - 1);
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 1));
|
||||
} else if (e.key === 'x' || e.key === 'X' || e.key === 'ㅌ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 2));
|
||||
}
|
||||
};
|
||||
|
||||
const preview = new Map<number, MarkValue>();
|
||||
if (drag) for (const i of dragCells(drag)) preview.set(i, drag.value);
|
||||
const cr = Math.floor(cursor / n);
|
||||
const cc = cursor % n;
|
||||
const showCursor = focused && playing;
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${Math.round((W / S) * 40)}px, calc((var(--play-h, 100vh) - 230px) * ${(W / H).toFixed(3)}))`, minWidth: Math.min(320, (W / S) * 24) };
|
||||
const fill = (i: number) => {
|
||||
if (answer) return answer.solution[i] === '#' ? answer.color : 'var(--surface)';
|
||||
const m = preview.get(i) ?? Number(b.marks[i]);
|
||||
return m === 1 ? 'var(--text)' : 'var(--surface)';
|
||||
};
|
||||
const xMark = (i: number) => !answer && (preview.get(i) ?? Number(b.marks[i])) === 2;
|
||||
const solvedByMe = mine?.status === 'solved';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`맞는 줄 ${okCount}개, 전체 ${2 * n}줄`}>
|
||||
✔ <b>{okCount}/{2 * n}</b>
|
||||
</span>
|
||||
{mine && playing && (
|
||||
<>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 1} onClick={() => setMode(1)}>
|
||||
■ 채우기
|
||||
</button>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 2} onClick={() => setMode(2)}>
|
||||
✕ 표시
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="rc-pill" onClick={() => act({ type: 'hint' })} aria-label={`힌트 쓰기, 지금까지 ${b.hints}번`}>
|
||||
💡 힌트{b.hints ? ` ${b.hints}` : ''}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
{answer && (
|
||||
<p className={`ng-title${solvedByMe ? '' : ' ans'}`} role="status">
|
||||
{solvedByMe ? `다 풀었어요! ${answer.name}` : `정답 그림: ${answer.name}`}
|
||||
</p>
|
||||
)}
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ng-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
role="application"
|
||||
aria-roledescription="네모네모 로직 판"
|
||||
aria-label={playing ? `네모네모 로직 ${n}×${n}. 화살표로 옮기고 스페이스로 칠하기, X로 ✕ 표시. 지금 ${describe(cursor)}` : '네모네모 로직 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => setDrag(null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
<rect x={0} y={0} width={L} height={H} fill="var(--surface-2)" />
|
||||
<rect x={L} y={0} width={n * S} height={T} fill="var(--surface-2)" />
|
||||
{showCursor && (
|
||||
<>
|
||||
<rect x={0} y={T + cr * S} width={L} height={S} fill="var(--primary-soft)" />
|
||||
<rect x={L + cc * S} y={0} width={S} height={T} fill="var(--primary-soft)" />
|
||||
</>
|
||||
)}
|
||||
{colClues.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} className="ng-clue" data-ok={okLines[n + c]} data-line={n + c} data-k={j} x={L + c * S + S / 2} y={T - 0.3 * S - (clue.length - 1 - j) * 0.72 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rowClues.map((clue, r) => {
|
||||
let x = L - 0.25 * S;
|
||||
return [...clue].reverse().map((num, j) => {
|
||||
const at = x - numW(num) / 2;
|
||||
x -= numW(num);
|
||||
return (
|
||||
<text key={`r${r}-${j}`} className="ng-clue" data-ok={okLines[r]} data-line={r} data-k={clue.length - 1 - j} x={at} y={T + r * S + 0.71 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{num}
|
||||
</text>
|
||||
);
|
||||
});
|
||||
})}
|
||||
{Array.from(b.marks, (ch, i) => {
|
||||
const x = L + (i % n) * S;
|
||||
const y = T + Math.floor(i / n) * S;
|
||||
const colored = !!answer && answer.solution[i] === '#';
|
||||
return (
|
||||
<g key={i} data-i={i} data-m={ch} className={!answer && fresh.has(i) ? 'ng-new' : undefined}>
|
||||
<rect
|
||||
x={x}
|
||||
y={y}
|
||||
width={S}
|
||||
height={S}
|
||||
fill={fill(i)}
|
||||
opacity={preview.has(i) ? 0.6 : 1}
|
||||
className={colored ? 'ng-color' : undefined}
|
||||
style={colored ? { animationDelay: `${fxMs(((i % n) + Math.floor(i / n)) * 18)}ms` } : undefined}
|
||||
/>
|
||||
{xMark(i) && <path d={`M${x + 5.5} ${y + 5.5} L${x + S - 5.5} ${y + S - 5.5} M${x + S - 5.5} ${y + 5.5} L${x + 5.5} ${y + S - 5.5}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" opacity={preview.has(i) ? 0.6 : 1} />}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{Array.from({ length: n + 1 }, (_, k) => {
|
||||
const thick = k % 5 === 0 || k === n;
|
||||
const style = { stroke: thick ? 'var(--text-sub)' : 'var(--border)', strokeWidth: thick ? 1.4 : 0.6 };
|
||||
return (
|
||||
<g key={`l${k}`} pointerEvents="none">
|
||||
<line x1={L + k * S} y1={thick ? 0 : T} x2={L + k * S} y2={H} {...style} />
|
||||
<line x1={thick ? 0 : L} y1={T + k * S} x2={W} y2={T + k * S} {...style} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{!answer && b.lastHint !== null && (
|
||||
<rect key={`h${b.hints}`} className="ng-hint" x={L + (b.lastHint % n) * S + 1.5} y={T + Math.floor(b.lastHint / n) * S + 1.5} width={S - 3} height={S - 3} rx={3} fill="none" stroke="#f59e0b" strokeWidth={2} pointerEvents="none" />
|
||||
)}
|
||||
{showCursor && <rect x={L + cc * S + 1} y={T + cr * S + 1} width={S - 2} height={S - 2} rx={3} fill="none" stroke="var(--focus)" strokeWidth={2.4} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 오른쪽 클릭·끌기: ✕ 표시 · 키보드: 화살표 + 스페이스 칠하기, X ✕ 표시</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 한 줄로 끌면 한 번에 · 칠한 칸을 다시 누르면 지워요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NonoSide(props: BoardProps<NonogramView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="네모네모 로직" info={`${sizeInfo(props.view.options.size)} · 힌트 ${props.view.options.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자대로 칸을 칠해 그림을 완성해요', playing: '줄마다 숫자 = 이어서 칠할 칸 수 · 모든 줄을 숫자와 맞게 칠해요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<NonogramOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>크기</strong>
|
||||
<Seg label="크기" value={o.size} options={([5, 10, 15] as NonogramSize[]).map((s) => [s, sizeInfo(s)])} onChange={(size) => onChange({ ...o, size })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg label="힌트" value={o.hints} options={[[true, '켬'], [false, '끔']]} onChange={(hints) => onChange({ ...o, hints })} />
|
||||
<span className="small muted">{o.hints ? '막히면 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 1200, 1800]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as NonogramOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: NonogramOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: NonogramOptions }) {
|
||||
const size = options?.size ?? 10;
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
줄마다 적힌 숫자대로 칸을 칠하면 <strong>그림</strong>이 나와요. 모두 <strong>똑같은 그림</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center' }}>
|
||||
<MiniNono answer={['.#.#.', '#####', '#####', '.###.', '..#..']} marks={['x#x#x', '#####', '.....', '.....', '.....']} cell={18} />
|
||||
<span>숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"은 한 칸, 한 칸 이상 띄고, 또 한 칸이에요. 숫자 순서대로 놓여요.</span>
|
||||
</div>
|
||||
<p>
|
||||
확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 두면 좋아요(✕는 답에 상관없어요). 칠한 칸이 맞는지는 알려 주지 않아요. 숫자와 맞게 칠해진 줄은 숫자가 흐려져요. 칠한 칸이 그림과
|
||||
똑같아지면 다 푼 거예요.
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 <strong>숫자와 맞는 줄</strong>이 많은 사람이 이겨요. 힌트를 켜면 막힐 때 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요(쓴 횟수는
|
||||
결과에 나와요). 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1200)}이고, 지금 크기는 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭·끌기 칠하기, 오른쪽 클릭·끌기 ✕. 휴대폰: 누르거나 끌어서 칠하고, 위의 [✕ 표시]로 바꾸면 ✕를 해요. 칠한 칸을 다시 누르면 지워요. 키보드: 화살표, 스페이스 칠하기, X로 ✕.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<NonogramView, NonogramOptions> = {
|
||||
Board: NonoBoard,
|
||||
Side: NonoSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
26
apps/web/src/games/nonogram/quick.tsx
Normal file
26
apps/web/src/games/nonogram/quick.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
/** 네모네모 로직 30초 규칙 요약 (docs/07 §5). Small puzzles drawn with ./art. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniNono } from './art';
|
||||
|
||||
const HEART = ['.#.#.', '#####', '#####', '.###.', '..#..'];
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['.....', '.....', '.....', '.....', '.....']} />,
|
||||
alt: '5×5 빈 칸 위와 왼쪽에 줄마다 숫자가 적혀 있어요',
|
||||
title: '숫자 = 칠할 칸 덩어리',
|
||||
text: '줄 옆 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"이면 한 칸, 띄고, 한 칸이에요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['x#x#x', '#####', '#####', '.....', '.....']} />,
|
||||
alt: '위 세 줄은 칠한 칸과 ✕ 표시로 채워져 있어요',
|
||||
title: '칠하기와 ✕ 표시',
|
||||
text: '확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 둬요. 끌면 한 줄을 한 번에 칠해요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} color="#ef4444" />,
|
||||
alt: '다 칠한 칸이 빨간 하트 그림이 됐어요',
|
||||
title: '다 칠하면 그림이 나와요',
|
||||
text: '모든 줄이 숫자와 맞으면 그림이 나와요. 모두 같은 그림이라 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import { fanCard, fanLayout, type FanLayout } from './fan';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { fxAnim, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
// Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod.
|
||||
const JOKER = 'X1';
|
||||
@@ -196,7 +196,8 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047,
|
||||
box-shadow: 0 6px 16px rgba(0,0,0,.4), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; will-change: transform, opacity; }
|
||||
.om-ghost::after { content: ''; position: absolute; left: 50%; top: 50%; width: 34%; height: 24%; background: #3b82f6; transform: translate(-50%, -50%) rotate(45deg); border-radius: 2px; }
|
||||
.om-last { display: flex; align-items: center; gap: 12px; background: rgba(0,0,0,.24); border: 1px solid rgba(255,255,255,.1); border-radius: 14px; padding: 8px 14px; width: 100%; max-width: 620px; justify-content: center; }
|
||||
.om-last .cards { display: flex; flex: none; padding: 2px 4px; }
|
||||
.om-thief-joker { animation: om-pop .45s ease-out; }
|
||||
.om-last .cards { display: flex; flex: none; padding: 2px 4px; animation: om-pop .3s ease-out; }
|
||||
.om-last .cards .om-card { --cw: 40px; transform-origin: 50% 100%; filter: drop-shadow(-1px 2px 2px rgba(0,0,0,.3)); }
|
||||
.om-last .cards .om-card:first-child:not(:last-child) { transform: rotate(-7deg); }
|
||||
.om-last .cards .om-card + .om-card { margin-left: -12px; transform: rotate(7deg); }
|
||||
@@ -235,7 +236,7 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047,
|
||||
.om-last .cards .om-card { --cw: 36px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn { animation: none; }
|
||||
.om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn, .om-last .cards, .om-thief-joker { animation: none; }
|
||||
.om-strip { transition: none; }
|
||||
}
|
||||
`;
|
||||
@@ -330,13 +331,14 @@ function seatLabel(v: OldMaidView, id: string, me: string | null, players: Recor
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaidView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null }) {
|
||||
/** `r`: the view as of the last time the table stood still (counts, places, the thief), `v`: the live view (whose turn). */
|
||||
function Seat({ id, v, r, me, players, deadline, bubble }: { id: string; v: OldMaidView; r: OldMaidView; me: string | null; players: Record<string, PublicUser>; deadline: number | null; bubble: string | null }) {
|
||||
const u = userOf(players, id);
|
||||
const st = v.status[id];
|
||||
const thief = v.final?.thief === id;
|
||||
const st = r.status[id];
|
||||
const thief = r.final?.thief === id;
|
||||
const cls = ['om-seat', v.turn === id ? 'turn anim-glow' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' ');
|
||||
return (
|
||||
<section className={cls} data-fx-seat={id} aria-label={seatLabel(v, id, me, players)}>
|
||||
<section className={cls} data-fx-seat={id} aria-label={seatLabel(r, id, me, players)}>
|
||||
{bubble && (
|
||||
<span className="om-bubble" aria-hidden>
|
||||
{bubble}
|
||||
@@ -350,7 +352,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
|
||||
<div className="om-badges" aria-hidden>
|
||||
{v.turn === id && <span className="om-badge turn">{v.target === me ? '내 카드 뽑는 중' : '뽑는 중'}</span>}
|
||||
{v.target === id && <span className="om-badge target">{v.turn === me ? '내가 여기서 뽑아요' : '뽑히는 중'}</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {v.places[id]}등</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {r.places[id]}등</span>}
|
||||
{st === 'left' && <span className="om-badge">나감</span>}
|
||||
{thief && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{v.away[id] && <span className="om-badge">자리 비움</span>}
|
||||
@@ -358,15 +360,15 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
|
||||
<div className="om-meta" aria-hidden>
|
||||
{st === 'playing' || thief ? (
|
||||
<>
|
||||
<MiniFan n={v.handCounts[id] ?? 0} />
|
||||
<MiniFan n={r.handCounts[id] ?? 0} />
|
||||
<span>
|
||||
<strong>{v.handCounts[id]}</strong>장
|
||||
<strong>{r.handCounts[id]}</strong>장
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span>{st === 'out' ? '다 털었어요' : '나갔어요'}</span>
|
||||
)}
|
||||
<span>· 짝 {v.pairCounts[id]}</span>
|
||||
<span>· 짝 {r.pairCounts[id]}</span>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
@@ -515,7 +517,11 @@ function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidV
|
||||
}
|
||||
|
||||
function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; players: Record<string, PublicUser> }) {
|
||||
const d = v.lastDraw;
|
||||
// A new draw (the card drawn, the pair thrown away) is told only once its card has landed.
|
||||
const shownNo = useAfterMotionValue(v.lastDraw?.no ?? 0);
|
||||
const kept = useRef(v.lastDraw);
|
||||
if ((v.lastDraw?.no ?? 0) === shownNo) kept.current = v.lastDraw;
|
||||
const d = kept.current;
|
||||
if (!d) return null;
|
||||
const mineDraw = d.drawer === me;
|
||||
const text = `${drawerSubj(players, d.drawer, me)} ${whose(players, d.from, me)} ${d.index + 1}번째 카드를 뽑았어요${d.auto ? '(시간 초과)' : ''}`;
|
||||
@@ -524,7 +530,7 @@ function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; playe
|
||||
else if (mineDraw && d.card) tail = d.card === JOKER ? '앗, 조커를 뽑았어요!' : `뽑은 카드 ${cardName(d.card)} · 짝이 없어서 손에 넣었어요`;
|
||||
else tail = '짝이 없어서 손에 넣었어요';
|
||||
return (
|
||||
<div className="om-last" role="status" aria-label={`${text}. ${tail}`}>
|
||||
<div key={d.no} className="om-last" role="status" aria-label={`${text}. ${tail}`}>
|
||||
{(d.pair || (mineDraw && d.card)) && (
|
||||
<span className="cards" aria-hidden>
|
||||
{d.pair ? d.pair.map((c) => <Card key={c} card={c} />) : <Card card={d.card} />}
|
||||
@@ -559,8 +565,17 @@ function Pile({ v }: { v: OldMaidView }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Table(props: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean }) {
|
||||
function Table(props: { v: OldMaidView; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean; revealed: boolean }) {
|
||||
const { v, me, players } = props;
|
||||
if (v.phase === 'finished' && !props.revealed) {
|
||||
// The last card is still flying (or the thief banner is up): the thief is unmasked after that.
|
||||
return (
|
||||
<div className="om-table" role="group" aria-label="테이블" data-fx="om-table">
|
||||
<LastDraw v={v} me={me} players={players} />
|
||||
<Pile v={v} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (v.phase === 'finished') {
|
||||
const f = v.final!;
|
||||
return (
|
||||
@@ -607,7 +622,7 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record<strin
|
||||
const HAND_PC = { cw: 72, prefer: 46 };
|
||||
const HAND_PHONE = { cw: 50, prefer: 34 };
|
||||
|
||||
function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
||||
function MyArea({ v, r, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; r: OldMaidView; me: string; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) {
|
||||
const hand = v.myHand ?? [];
|
||||
const st = v.status[me];
|
||||
const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' ');
|
||||
@@ -668,8 +683,8 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
|
||||
</span>
|
||||
)}
|
||||
{v.away[me] && <span className="om-badge">자리 비움</span>}
|
||||
{st === 'out' && <span className="om-badge win">🎉 {v.places[me]}등</span>}
|
||||
{v.final?.thief === me && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{r.status[me] === 'out' && <span className="om-badge win">🎉 {r.places[me]}등</span>}
|
||||
{r.final?.thief === me && <span className="om-badge lose">🃏 도둑</span>}
|
||||
{v.turn === me && <TurnTimer deadline={deadline} totalMs={v.turnMs} mine size={30} />}
|
||||
</div>
|
||||
<div className="om-mine">
|
||||
@@ -715,6 +730,29 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn });
|
||||
const [banner, showBanner] = useBanner();
|
||||
useOldMaidFx(v, me, players, showBanner);
|
||||
// "조커를 뽑았어요!" tells what the card is: only once it has landed in my hand.
|
||||
const [note, setNote] = useState<{ text: string; buzz: number | number[] } | null>(null);
|
||||
const noteReady = useMotionSettled(!!note);
|
||||
useEffect(() => {
|
||||
if (!noteReady || !note) return;
|
||||
toast(note.text);
|
||||
haptic(note.buzz);
|
||||
setNote(null);
|
||||
}, [noteReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// Places, counts and the thief change on screen once the cards have landed; the end table after the thief banner.
|
||||
const shown = useAfterMotionValue(v);
|
||||
const revealed = useMotionSettled(v.phase === 'finished');
|
||||
const popBubbles = (bub: Record<string, string>) => {
|
||||
setBubbles((b) => ({ ...b, ...bub }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
|
||||
};
|
||||
const [bubQ, setBubQ] = useState<Record<string, string> | null>(null);
|
||||
const bubReady = useMotionSettled(!!bubQ);
|
||||
useEffect(() => {
|
||||
if (!bubReady || !bubQ) return;
|
||||
popBubbles(bubQ);
|
||||
setBubQ(null);
|
||||
}, [bubReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
@@ -735,13 +773,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
const hand = v.myHand ?? [];
|
||||
const ld = v.lastDraw;
|
||||
if (amPlayer && ld && added.some((e) => e.t === 'draw')) {
|
||||
if (ld.drawer === me && ld.card === JOKER) {
|
||||
toast('앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.');
|
||||
haptic([40, 30, 40]);
|
||||
} else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) {
|
||||
toast('조커를 넘겼어요! 😆');
|
||||
haptic(40);
|
||||
}
|
||||
if (ld.drawer === me && ld.card === JOKER) setNote({ text: '앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.', buzz: [40, 30, 40] });
|
||||
else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) setNote({ text: '조커를 넘겼어요! 😆', buzz: 40 });
|
||||
setFresh(ld.drawer === me && !ld.pair ? ld.card : null);
|
||||
}
|
||||
if (amPlayer && v.turn === me && p.turn !== me && v.phase === 'playing') {
|
||||
@@ -751,8 +784,9 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
}
|
||||
if (msgs.length) setAnnounce(msgs.join(' '));
|
||||
if (Object.keys(bub).length) {
|
||||
setBubbles((b) => ({ ...b, ...bub }));
|
||||
setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500));
|
||||
// "짝!" / "다 털었어요" once the drawn card has landed; "섞었어요" right away (it goes with the riffle).
|
||||
if (added.some((e) => e.t !== 'shuffle')) setBubQ((q) => ({ ...q, ...bub }));
|
||||
else popBubbles(bub);
|
||||
}
|
||||
prev.current = { logCount: v.logCount, hand, turn: v.turn };
|
||||
if (shuffled) {
|
||||
@@ -769,11 +803,11 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
|
||||
<style>{CSS}</style>
|
||||
<div className="om-seats">
|
||||
{seats.map((p) => (
|
||||
<Seat key={p} id={p} v={v} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} />
|
||||
<Seat key={p} id={p} v={v} r={shown} me={me} players={players} deadline={deadline} bubble={bubbles[p] ?? null} />
|
||||
))}
|
||||
</div>
|
||||
<Table v={v} me={me} players={players} act={act} pending={pending} tapConfirm={tapConfirm} riffle={riffle} />
|
||||
{amPlayer && <MyArea v={v} me={me!} players={players} act={act} pending={pending} deadline={deadline} fresh={fresh} bubble={bubbles[me!] ?? null} />}
|
||||
<Table v={v} me={me} players={players} act={act} pending={pending} tapConfirm={tapConfirm} riffle={riffle} revealed={revealed} />
|
||||
{amPlayer && <MyArea v={v} r={shown} me={me!} players={players} act={act} pending={pending} deadline={deadline} fresh={fresh} bubble={bubbles[me!] ?? null} />}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -791,11 +825,32 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
const hand = v.myHand ?? [];
|
||||
const prevHand = useRef(hand);
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
// Banners ("1등!", "도둑!") wait until the card that caused them has landed; the screen counts as moving meanwhile,
|
||||
// so the room's result window opens only after the banner.
|
||||
const flightEnd = useRef(0);
|
||||
const bannerTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
const [bannerWait, setBannerWait] = useState(false);
|
||||
useMotionHold(bannerWait);
|
||||
useEffect(() => () => clearTimeout(bannerTimer.current), []);
|
||||
const bannerAfterFlight = (...args: Parameters<typeof showBanner>) => {
|
||||
clearTimeout(bannerTimer.current);
|
||||
const wait = flightEnd.current - performance.now();
|
||||
if (wait <= 0) {
|
||||
setBannerWait(false);
|
||||
return showBanner(...args);
|
||||
}
|
||||
setBannerWait(true);
|
||||
bannerTimer.current = setTimeout(() => {
|
||||
setBannerWait(false);
|
||||
showBanner(...args);
|
||||
}, wait);
|
||||
};
|
||||
/** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */
|
||||
const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p));
|
||||
const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i }));
|
||||
useNewEntries(entries, (x) => x.n, (fresh) => {
|
||||
let t = 0;
|
||||
let end = 0; // when the last flying card lands (written ms)
|
||||
const ld = v.lastDraw;
|
||||
const pile = (pairs: [string, string][], from: Element | null, delay: number) => {
|
||||
for (const p of pairs) flyFrom(document.querySelector(`.om-pile [data-pair="${cssEsc(pairKey(p))}"]`), from, { delay, ms: 420, rotate: 14 });
|
||||
@@ -814,6 +869,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.drawer === me) myDrawRect = null;
|
||||
fanSnap = null;
|
||||
const land = lifted ? LIFT_MS - 140 : 300;
|
||||
end = Math.max(end, at + (lifted ? LIFT_MS : 420));
|
||||
later(at, () => {
|
||||
if (e.auto) sfx.tick();
|
||||
sfx.draw();
|
||||
@@ -821,7 +877,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.pair) {
|
||||
pile([e.pair], spot(e.drawer), at + land);
|
||||
later(at + land + 30, omSfx.pair);
|
||||
later(at + land + 30, () => bump(document.querySelector('.om-last .cards'), 'pop'));
|
||||
end = Math.max(end, at + land + 420);
|
||||
t += land + 120;
|
||||
} else t += 160;
|
||||
break;
|
||||
@@ -831,7 +887,8 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
omSfx.out();
|
||||
bump(seatEl(e.player), 'pop');
|
||||
});
|
||||
showBanner(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
|
||||
flightEnd.current = performance.now() + fxMs(end);
|
||||
bannerAfterFlight(`${e.place}등!`, 'green', e.player === me ? '손패를 다 털었어요' : `${nick(players, e.player)}님 다 털었어요`);
|
||||
t += 150;
|
||||
break;
|
||||
case 'shuffle':
|
||||
@@ -852,7 +909,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
if (e.pairs.length) {
|
||||
pile(e.pairs, seatEl(e.player), at + 350);
|
||||
later(at + 380, omSfx.pair);
|
||||
end = Math.max(end, at + 350 + 420);
|
||||
}
|
||||
end = Math.max(end, at + 480 + 60 * Math.max(0, n - 1));
|
||||
t += 400;
|
||||
break;
|
||||
}
|
||||
@@ -869,6 +928,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
});
|
||||
} else if (had && !has && v.phase === 'playing') later(t + 150, omSfx.jokerGone);
|
||||
}
|
||||
flightEnd.current = performance.now() + fxMs(end);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
prevHand.current = hand;
|
||||
@@ -877,11 +937,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
useChange(v.phase, (now) => {
|
||||
const thief = v.final?.thief;
|
||||
if (now !== 'finished' || !thief) return;
|
||||
showBanner('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
|
||||
setTimeout(() => {
|
||||
bump(seatEl(thief), 'shake');
|
||||
bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop');
|
||||
}, fxMs(200));
|
||||
bannerAfterFlight('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`);
|
||||
// (The joker on the end table pops by itself when it shows, after the banner.)
|
||||
setTimeout(() => bump(seatEl(thief), 'shake'), Math.max(0, flightEnd.current - performance.now()) + fxMs(200));
|
||||
});
|
||||
const started = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
@@ -902,7 +960,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record<string,
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function OldMaidSide({ view: v, me, players, deadline }: BoardProps<OldMaidView>) {
|
||||
function OldMaidSide({ view, me, players, deadline }: BoardProps<OldMaidView>) {
|
||||
// The side panel (places, the thief, the log) follows the board once its cards have landed.
|
||||
const v = useAfterMotionValue(view);
|
||||
const running = v.phase === 'playing';
|
||||
const log = v.log.filter((e) => e.t !== 'shuffle').slice(-8).reverse();
|
||||
return (
|
||||
|
||||
@@ -6,11 +6,11 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import { bump, useBanner } from '../card-fx';
|
||||
import { bump, useBanner, type BannerTone } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
type Color = 'black' | 'white';
|
||||
const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
||||
@@ -67,16 +67,26 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
}, [refused]);
|
||||
|
||||
// The game is over: "오목!" for five in a row (who won underneath), otherwise just who won.
|
||||
// Shown once the last stone has set down (it waits in `endBanner` until the board is still).
|
||||
const prevPhase = useRef(v.phase);
|
||||
const [endBanner, setEndBanner] = useState<[string, BannerTone, string | undefined] | null>(null);
|
||||
const endReady = useMotionSettled(!!endBanner);
|
||||
useEffect(() => {
|
||||
const before = prevPhase.current;
|
||||
prevPhase.current = v.phase;
|
||||
if (before === v.phase || v.phase !== 'finished' || !v.result) return;
|
||||
const w = v.result.winner;
|
||||
const tone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue';
|
||||
if (v.winLine?.length) showBanner('오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined);
|
||||
else showBanner(w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary);
|
||||
const tone: BannerTone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue';
|
||||
if (v.winLine?.length) setEndBanner(['오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined]);
|
||||
else setEndBanner([w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary]);
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => {
|
||||
if (!endReady || !endBanner) return;
|
||||
showBanner(...endBanner);
|
||||
setEndBanner(null);
|
||||
}, [endReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The winning five light up only after the last stone has landed.
|
||||
const winShown = useMotionSettled(!!v.winLine?.length);
|
||||
|
||||
const forbidden = useMemo(() => new Set(v.forbidden.map((p) => p.y * n + p.x)), [v.forbidden, n]);
|
||||
// What the board was before the last change: a new stone sets down, stones taken back by 무르기 fade away.
|
||||
@@ -227,7 +237,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
<circle className={fresh ? 'anim-pop' : undefined} style={{ animationDelay: '0.2s', transformBox: 'fill-box', transformOrigin: 'center' }} cx={v.lastMove.x} cy={v.lastMove.y} r={0.13} fill="#ef4444" />
|
||||
</g>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
{(winShown ? (v.winLine ?? []) : []).map((p, k) => (
|
||||
<circle
|
||||
key={`win${p.x}-${p.y}`}
|
||||
className="bm-win"
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
* 원카드 소리·움직임 (docs/games/one-card.md §9). Everything reacts to new public log lines, so other players' moves
|
||||
* sound and move too, and each change plays once (lines are handled by their `seq`).
|
||||
*/
|
||||
import { useLayoutEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';
|
||||
import type { CardFace, LogEntry, OneCardView } from '@bg/games/one-card';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { fxAnim, fxMs, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
export interface Banner {
|
||||
key: number;
|
||||
@@ -182,9 +182,31 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
const round = useRef(v.round);
|
||||
const keyRef = useRef(1);
|
||||
const timers = useRef<number[]>([]);
|
||||
// Results (등수, 파산, 의심 결과, 판 끝) wait until the card that caused them has landed.
|
||||
const [late, setLate] = useState<{ banners: Banner[]; sounds: string[] }>({ banners: [], sounds: [] });
|
||||
const lateReady = useMotionSettled(late.banners.length > 0);
|
||||
|
||||
useLayoutEffect(() => () => timers.current.forEach((t) => clearTimeout(t)), []);
|
||||
|
||||
const showBanners = (banners: Banner[], next: Partial<Fx> = {}) => {
|
||||
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
|
||||
for (const b of banners) {
|
||||
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700));
|
||||
timers.current.push(t);
|
||||
}
|
||||
timers.current = timers.current.slice(-20);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!lateReady) return;
|
||||
const q = late;
|
||||
setLate({ banners: [], sounds: [] });
|
||||
if (q.sounds.includes('out')) sfx.fanfare();
|
||||
if (q.sounds.includes('good')) sfx.good();
|
||||
if (q.sounds.includes('bad')) sfx.bad();
|
||||
showBanners(q.banners);
|
||||
}, [lateReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0;
|
||||
const myHand = v.my?.hand ?? [];
|
||||
@@ -197,6 +219,12 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
let drawGap = 0;
|
||||
let myDraw = 0;
|
||||
const banner = (b: Omit<Banner, 'key'>) => banners.push({ ...b, key: keyRef.current++ });
|
||||
const lateBanners: Banner[] = [];
|
||||
const lateSounds: string[] = [];
|
||||
const later = (b: Omit<Banner, 'key'>, sound?: string) => {
|
||||
lateBanners.push({ ...b, key: keyRef.current++ });
|
||||
if (sound) lateSounds.push(sound);
|
||||
};
|
||||
const who = (p: string) => (p === me ? '내가' : `${nick(p)}님이`);
|
||||
const rootEl = root.current;
|
||||
const layerEl = layer.current;
|
||||
@@ -283,19 +311,16 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
next.shuffle = (next.shuffle ?? fx.shuffle) + 1;
|
||||
break;
|
||||
case 'out':
|
||||
if (v.phase !== 'finished') sounds.add('out');
|
||||
banner({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' });
|
||||
later({ text: `${e.place}등!`, sub: `${who(e.p)} 카드를 모두 냈어요`, kind: 'win' }, v.phase !== 'finished' ? 'out' : undefined);
|
||||
break;
|
||||
case 'bankrupt':
|
||||
sounds.add('bad');
|
||||
banner({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' });
|
||||
later({ text: '파산!', sub: `${who(e.p)} 탈락했어요`, kind: 'caught' }, 'bad');
|
||||
break;
|
||||
case 'challenge':
|
||||
sounds.add(e.illegal ? 'good' : 'bad');
|
||||
banner({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' });
|
||||
later({ text: e.illegal ? '의심 성공!' : '의심 실패', kind: e.illegal ? 'block' : 'caught' }, e.illegal ? 'good' : 'bad');
|
||||
break;
|
||||
case 'round':
|
||||
banner({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' });
|
||||
later({ text: `${e.round}판 끝`, sub: e.winner ? `${nick(e.winner)}님 +${e.points}점` : undefined, kind: 'win' });
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -335,19 +360,10 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject<HTMLDiv
|
||||
else if (sounds.has('alarm')) sfx.alarm();
|
||||
if (sounds.has('call')) ocSound.call();
|
||||
if (sounds.has('oneLeft')) ocSound.oneLeft();
|
||||
if (sounds.has('out')) sfx.fanfare();
|
||||
if (sounds.has('good')) sfx.good();
|
||||
if (sounds.has('bad')) sfx.bad();
|
||||
if (myDraw >= 2) haptic([30, 30, 30]);
|
||||
|
||||
if (banners.length || Object.keys(next).length) {
|
||||
setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) }));
|
||||
for (const b of banners) {
|
||||
const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700));
|
||||
timers.current.push(t);
|
||||
}
|
||||
}
|
||||
timers.current = timers.current.slice(-20);
|
||||
if (banners.length || Object.keys(next).length) showBanners(banners, next);
|
||||
if (lateBanners.length) setLate((q) => ({ banners: [...q.banners, ...lateBanners], sounds: [...q.sounds, ...lateSounds] }));
|
||||
}, [v.log.length ? v.log[v.log.length - 1]!.seq : 0, v.round, v.my?.hand.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return fx;
|
||||
|
||||
@@ -12,7 +12,7 @@ import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard';
|
||||
import { FX_CSS, useOneCardFx, type Fx } from './fx';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const SUITS: Suit[] = ['S', 'H', 'D', 'C'];
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
@@ -173,8 +173,11 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
|
||||
function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||||
const u = userOf(players, s.id);
|
||||
const place = v.result?.players.find((p) => p.player === s.id)?.rank;
|
||||
// 다 냄 / 파산 and points change once the last card has landed.
|
||||
const status = useAfterMotionValue(s.status);
|
||||
const score = useAfterMotionValue(s.score);
|
||||
return (
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${s.status === 'bankrupt' || s.status === 'left' ? ' gone' : ''}`} data-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||
<li className={`oc-seat${s.isTurn ? ' turn' : ''}${status === 'bankrupt' || status === 'left' ? ' gone' : ''}`} data-seat={s.id} aria-label={seatLabel(s, players, me, v)}>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={24} />
|
||||
<span className="nm">{u.nickname}</span>
|
||||
@@ -190,11 +193,11 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView
|
||||
{s.oneCard === 'declared' ? '원카드!' : '1장!'}
|
||||
</span>
|
||||
)}
|
||||
{s.status === 'out' && <span className="oc-badge" style={{ background: 'var(--success)', color: '#fff' }}>{place ? `${place}등` : '다 냄'}</span>}
|
||||
{s.status === 'bankrupt' && <span className="oc-badge" style={{ background: 'var(--danger)', color: '#fff' }}>파산</span>}
|
||||
{status === 'out' && <span className="oc-badge" style={{ background: 'var(--success)', color: '#fff' }}>{place ? `${place}등` : '다 냄'}</span>}
|
||||
{status === 'bankrupt' && <span className="oc-badge" style={{ background: 'var(--danger)', color: '#fff' }}>파산</span>}
|
||||
{s.status === 'left' && <span className="oc-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
|
||||
{s.away && <span className="oc-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
|
||||
{v.mode === 'uno-style' && v.options.unoTargetScore > 0 && <span className="small muted">{s.score}점</span>}
|
||||
{v.mode === 'uno-style' && v.options.unoTargetScore > 0 && <span className="small muted">{score}점</span>}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -227,6 +230,8 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) {
|
||||
);
|
||||
return () => window.clearInterval(id);
|
||||
}, [n]);
|
||||
// Counting up card by card (timer steps): results wait for the count.
|
||||
useMotionHold(shown < n);
|
||||
if (n <= 0) return null;
|
||||
return (
|
||||
<span key={shown} className="oc-attack grow" aria-live="polite" aria-label={`${uno ? '먹을 카드' : '공격'} ${n}장`} style={{ fontSize: `${1.4 + Math.min(shown, 15) * 0.07}rem` }}>
|
||||
@@ -807,8 +812,12 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro
|
||||
}}
|
||||
/>
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
<AfterMotion when={!!v.reveal}>
|
||||
<RevealPanel v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<AfterMotion when={v.phase === 'roundEnd'}>
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
</AfterMotion>
|
||||
{v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} arrived={fx.arrived} />}
|
||||
{meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
|
||||
<div className="oc-panel">
|
||||
@@ -840,6 +849,12 @@ function rulesLine(v: Pick<OneCardView, 'mode' | 'options' | 'penalty' | 'bankru
|
||||
function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>) {
|
||||
const scoreMode = v.mode === 'uno-style' && v.options.unoTargetScore > 0;
|
||||
const waitingId = v.current;
|
||||
// Seats, the 기록 and the final ranking show what happened only after it has played on the table.
|
||||
const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0;
|
||||
const shownSeq = useAfterMotionValue(lastSeq);
|
||||
const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.status}:${s.score}`).join(','));
|
||||
const seatShown = seatKey.split(',');
|
||||
const showResult = useAfterMotionValue(!!v.result);
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
@@ -854,25 +869,28 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>
|
||||
</div>
|
||||
<span className="small muted">{rulesLine(v)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{v.seats.map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'bankrupt' || s.status === 'left' ? 0.55 : 1 }} aria-label={seatLabel(s, players, me, v)}>
|
||||
{v.seats.map((s, i) => {
|
||||
const [status, score] = (seatShown[i] ?? `${s.status}:${s.score}`).split(':') as [SeatView['status'], string];
|
||||
return (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: status === 'bankrupt' || status === 'left' ? 0.55 : 1 }} aria-label={seatLabel(s, players, me, v)}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
|
||||
{s.isTurn ? '▶ ' : ''}
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.status === 'out' ? ' · 다 냄' : s.status === 'bankrupt' ? ' · 파산' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
{status === 'out' ? ' · 다 냄' : status === 'bankrupt' ? ' · 파산' : status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
{scoreMode && <span className="small">{s.score}점</span>}
|
||||
{scoreMode && <span className="small">{score}점</span>}
|
||||
<span className="oc-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{showResult && v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
@@ -892,7 +910,7 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps<OneCardView>
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
<ol className="oc-log">
|
||||
{[...v.log].reverse().map((e) => (
|
||||
{v.log.filter((e) => e.seq <= shownSeq).reverse().map((e) => (
|
||||
<li key={`${e.seq}-${e.t}-${'p' in e ? e.p : ''}`} className="small">
|
||||
{logText(e, players)}
|
||||
</li>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS } from '../board-motion';
|
||||
import { useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import { toast } from '../../store/toast';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
@@ -74,6 +75,16 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
const [anim, setAnim] = useState<Anim | null>(null);
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
// Pass notices wait until the flips of the move before them have played.
|
||||
const [passMsgs, setPassMsgs] = useState<string[]>([]);
|
||||
const passReady = useMotionSettled(passMsgs.length > 0);
|
||||
useEffect(() => {
|
||||
if (!passReady) return;
|
||||
for (const m of passMsgs) toast(m);
|
||||
setPassMsgs([]);
|
||||
}, [passReady]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The disc counts change once the discs have finished turning over.
|
||||
const [black, white] = useAfterMotionValue(`${v.discs.black},${v.discs.white}`).split(',').map(Number) as [number, number];
|
||||
|
||||
const legal = useMemo(() => {
|
||||
const m = new Map<number, OthelloLegalMove>();
|
||||
@@ -93,6 +104,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
}
|
||||
const added = v.moves.slice(prev);
|
||||
const texts: string[] = [];
|
||||
const passes: string[] = [];
|
||||
for (const m of added) {
|
||||
if (m.kind === 'place') texts.push(`${COLOR_KO[m.color]}이 ${label(m)}에 두어 ${m.flipped.length}개를 뒤집었어요.`);
|
||||
else {
|
||||
@@ -103,9 +115,10 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
? '상대가 둘 곳이 없어서 내 차례가 한 번 더 와요'
|
||||
: `${COLOR_KO[m.color]}이 둘 곳이 없어서 차례가 넘어갔어요`;
|
||||
texts.push(msg + '.');
|
||||
toast(msg);
|
||||
passes.push(msg);
|
||||
}
|
||||
}
|
||||
if (passes.length) setPassMsgs((q) => [...q, ...passes]);
|
||||
setAnnounce(texts.join(' '));
|
||||
const lm = v.lastMove;
|
||||
if (lm && added.some((m) => m.kind === 'place')) {
|
||||
@@ -188,7 +201,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
const showFlips = !!targetMove && (v.showLegalMoves || !!preview);
|
||||
const flipSet = new Set(showFlips ? targetMove!.flipped : []);
|
||||
const showGhost = !!target && v.myColor && v.board[target.y * N + target.x] === 0 && (!!targetMove || !v.showLegalMoves);
|
||||
const total = v.discs.black + v.discs.white;
|
||||
const total = black + white;
|
||||
const pad = 0.55;
|
||||
|
||||
return (
|
||||
@@ -196,17 +209,17 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
<div className="board-wrap stack oth-fit" style={{ gap: 10, '--oth-rows': tapConfirm ? 'calc(var(--btn-h) + 50px)' : '40px' } as React.CSSProperties}>
|
||||
<style>{BOARD_MOTION_CSS + CSS}</style>
|
||||
<div
|
||||
aria-label={`돌 수: 흑 ${v.discs.black}개, 백 ${v.discs.white}개`}
|
||||
aria-label={`돌 수: 흑 ${black}개, 백 ${white}개`}
|
||||
role="img"
|
||||
style={{ display: 'flex', height: 30, borderRadius: 15, overflow: 'hidden', border: '2px solid var(--border)', fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}
|
||||
>
|
||||
<div style={{ flex: `${v.discs.black} 1 0`, minWidth: 48, background: '#161616', color: '#fff', display: 'flex', alignItems: 'center', paddingLeft: 12, transition: 'flex-grow 0.4s' }}>
|
||||
● {v.discs.black}
|
||||
<div style={{ flex: `${black} 1 0`, minWidth: 48, background: '#161616', color: '#fff', display: 'flex', alignItems: 'center', paddingLeft: 12, transition: 'flex-grow 0.4s' }}>
|
||||
● {black}
|
||||
</div>
|
||||
<div
|
||||
style={{ flex: `${total ? v.discs.white : 1} 1 0`, minWidth: 48, background: '#fafaf7', color: '#161616', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 12, transition: 'flex-grow 0.4s' }}
|
||||
style={{ flex: `${total ? white : 1} 1 0`, minWidth: 48, background: '#fafaf7', color: '#161616', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: 12, transition: 'flex-grow 0.4s' }}
|
||||
>
|
||||
{v.discs.white} ○
|
||||
{white} ○
|
||||
</div>
|
||||
</div>
|
||||
<svg
|
||||
@@ -438,7 +451,8 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: OthelloVie
|
||||
} else if (active && tc.kind === 'perMove') {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={id === me} />;
|
||||
}
|
||||
const score = v.result ? v.result.displayScore[color] : v.discs[color];
|
||||
// Shown once the discs of the last move have turned over.
|
||||
const score = useAfterMotionValue(v.result ? v.result.displayScore[color] : v.discs[color]);
|
||||
return (
|
||||
<div className="card row" style={{ padding: '8px 12px', gap: 10, border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||||
<svg width={28} height={28} viewBox="-0.5 -0.5 1 1" aria-hidden>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxAnim, fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
|
||||
const MODE_KO: Record<PokerMode, string> = {
|
||||
holdem: '텍사스 홀덤',
|
||||
@@ -123,8 +123,8 @@ function seatBadges(seat: SeatView, v: PokerView): [string, string][] {
|
||||
return b;
|
||||
}
|
||||
|
||||
function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: string | null; k: number }) {
|
||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||
function SeatCards({ seat, v, me, k, endShown }: { seat: SeatView; v: PokerView; me: string | null; k: number; endShown: boolean }) {
|
||||
const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined;
|
||||
const cards: { c: ViewCard; key: string; title?: string }[] = [];
|
||||
if (seat.forehead !== undefined) cards.push({ c: seat.forehead, key: 'f', title: seat.forehead ? undefined : seat.id === me ? '내 이마 카드(나만 못 봐요)' : '이마 카드' });
|
||||
// Hidden cards arrive as null; at showdown the view already reveals them.
|
||||
@@ -149,13 +149,16 @@ function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: strin
|
||||
);
|
||||
}
|
||||
|
||||
function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number; k: number }) {
|
||||
function SeatBox({ seat, v, players, me, deadline, x, y, k, endShown }: { seat: SeatView; v: PokerView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; x: number; y: number; k: number; endShown: boolean }) {
|
||||
const u = userOf(players, seat.id);
|
||||
// Chips change once the flying chips have landed.
|
||||
const stack = useAfterMotionValue(seat.stack);
|
||||
const badges = seatBadges(seat, v);
|
||||
const waiting = v.waiting.includes(seat.id) && v.handPhase !== 'handEnd';
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const won = v.handPhase === 'handEnd' && v.winners.includes(seat.id);
|
||||
const sd = v.showdown?.find((e) => e.id === seat.id);
|
||||
// Winner, hand names and best cards show once the cards have been turned over (endShown).
|
||||
const won = endShown && v.handPhase === 'handEnd' && v.winners.includes(seat.id);
|
||||
const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined;
|
||||
const marks: [string, string, string][] = [];
|
||||
if (seat.dealer) marks.push(['D', '#facc15', '딜러']);
|
||||
if (seat.sb) marks.push(['SB', '#93c5fd', '스몰 블라인드']);
|
||||
@@ -166,7 +169,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`}
|
||||
style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties}
|
||||
data-fx-seat={seat.id}
|
||||
aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||
aria-label={`${u.nickname} ${formatChips(stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`}
|
||||
>
|
||||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={u} size={22} />
|
||||
@@ -182,7 +185,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
{waiting && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={seat.id === me} size={28} />}
|
||||
</div>
|
||||
<div className="row" style={{ gap: 6, justifyContent: 'space-between' }}>
|
||||
<Chips n={seat.stack} strong />
|
||||
<Chips n={stack} strong />
|
||||
{seat.roundBet > 0 && <span className="small" title="이번 라운드에 건 칩">+{seat.roundBet.toLocaleString('ko-KR')}</span>}
|
||||
</div>
|
||||
{seat.lastAction && !seat.folded && <span className="small muted">{seat.lastAction}</span>}
|
||||
@@ -196,8 +199,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SeatCards seat={seat} v={v} me={me} k={k} />
|
||||
{!sd && v.foldShown?.id === seat.id && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{v.foldShown.handName}</strong>}
|
||||
<SeatCards seat={seat} v={v} me={me} k={k} endShown={endShown} />
|
||||
{!sd && endShown && v.foldShown?.id === seat.id && <strong style={{ color: 'var(--primary)', textAlign: 'center' }}>{v.foldShown.handName}</strong>}
|
||||
{sd && (
|
||||
<strong style={{ color: 'var(--primary)', textAlign: 'center' }}>
|
||||
{sd.handName}
|
||||
@@ -211,6 +214,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView;
|
||||
function CenterInfo({ v, players, k }: { v: PokerView; players: Record<string, PublicUser>; k: number }) {
|
||||
const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : '';
|
||||
const penalty = v.penalties.reduce((a, p) => a + p.amount, 0);
|
||||
// The pot changes once the chips have flown in (or out to the winner).
|
||||
const pot = useAfterMotionValue(v.pot);
|
||||
return (
|
||||
<div className="pk-center" data-fx="poker-center">
|
||||
{v.streetName && <div className="pk-badge" style={{ background: '#fde047', color: '#422006', fontSize: '0.95rem', padding: '2px 12px' }}>{v.streetName}</div>}
|
||||
@@ -221,7 +226,7 @@ function CenterInfo({ v, players, k }: { v: PokerView; players: Record<string, P
|
||||
)}
|
||||
<div style={{ fontSize: '0.95rem', opacity: 0.9 }}>모인 칩</div>
|
||||
<div style={{ fontSize: `${(2.2 * (1 + (k - 1) / 2)).toFixed(2)}rem`, fontWeight: 900, fontVariantNumeric: 'tabular-nums' }} aria-live="polite" data-fx="poker-pot">
|
||||
{formatChips(v.pot)}
|
||||
{formatChips(pot)}
|
||||
</div>
|
||||
{v.pots.length > 1 && (
|
||||
<div className="small" style={{ opacity: 0.9 }}>
|
||||
@@ -258,6 +263,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const showKey = `${v.handNo}-${v.handPhase}`;
|
||||
const [banner, showBanner] = useBanner();
|
||||
usePokerFx(v, me, players, showBanner);
|
||||
// The hand's outcome (winner, hand names, 이번 판 결과, 다음 판으로) waits until the showdown flips and chips are done.
|
||||
const endShown = useMotionSettled(v.handPhase === 'handEnd');
|
||||
// PC: seats, cards and the pot grow with the table (1 at the old 890×600 table, up to 1.6×).
|
||||
const wide = useWide();
|
||||
const tableRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -287,10 +294,10 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
}, [mine, v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (v.handPhase !== 'handEnd') return;
|
||||
if (!endShown || v.handPhase !== 'handEnd') return;
|
||||
setAnnounce(resultLine(v, players));
|
||||
if (me && v.winners.includes(me)) sounds.win();
|
||||
}, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}, [showKey, endShown]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return (
|
||||
<MyCardW.Provider value={lgW}>
|
||||
@@ -311,11 +318,11 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
const sn = Math.sin(ang);
|
||||
const cx = wide ? Math.sign(c) * Math.abs(c) ** 0.7 : c;
|
||||
const sy = wide ? Math.sign(sn) * Math.abs(sn) ** 0.7 : sn;
|
||||
return <SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * cx} y={50 + ry * sy} k={k} />;
|
||||
return <SeatBox key={s.id} seat={s} v={v} players={players} me={me} deadline={deadline} x={50 + 40 * cx} y={50 + ry * sy} k={k} endShown={endShown} />;
|
||||
})}
|
||||
<CenterInfo v={v} players={players} k={k} />
|
||||
</div>
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} />
|
||||
<MyArea v={v} me={me} players={players} act={act} pending={pending} endShown={endShown} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -663,9 +670,11 @@ interface AreaProps {
|
||||
pending: boolean;
|
||||
}
|
||||
|
||||
function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
function MyArea({ v, me, players, act, pending, endShown }: AreaProps & { endShown: boolean }) {
|
||||
const seat = v.seats.find((s) => s.id === me);
|
||||
if (!me || !seat) return v.handPhase === 'handEnd' ? <ResultPanel v={v} players={players} /> : null;
|
||||
// My hand's name changes once the new card has flown in.
|
||||
const [handName, lowName] = useAfterMotionValue(`${v.my.handName ?? ''}\n${v.my.lowName ?? ''}`).split('\n');
|
||||
if (!me || !seat) return v.handPhase === 'handEnd' && endShown ? <ResultPanel v={v} players={players} /> : null;
|
||||
const m = v.my;
|
||||
return (
|
||||
<div className="stack" style={{ gap: 10 }}>
|
||||
@@ -678,10 +687,10 @@ function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
) : (
|
||||
<MyCards v={v} seat={seat} />
|
||||
)}
|
||||
{(m.handName || m.lowName) && (
|
||||
{(handName || lowName) && (
|
||||
<div style={{ textAlign: 'center', fontSize: '1.4rem', fontWeight: 900 }}>
|
||||
지금: {m.handName}
|
||||
{m.lowName && <span className="small" style={{ marginLeft: 8 }}>로우 {m.lowName}</span>}
|
||||
지금: {handName}
|
||||
{lowName && <span className="small" style={{ marginLeft: 8 }}>로우 {lowName}</span>}
|
||||
</div>
|
||||
)}
|
||||
{seat.folded && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>이번 판은 포기했어요. 내 카드는 나만 볼 수 있어요.</p>}
|
||||
@@ -702,13 +711,13 @@ function MyArea({ v, me, players, act, pending }: AreaProps) {
|
||||
</p>
|
||||
)}
|
||||
{seat.inHand && v.handPhase === 'betting' && !seat.folded && !seat.allIn && <BetBar v={v} me={me} players={players} act={act} pending={pending} />}
|
||||
{v.handPhase === 'handEnd' && <ResultPanel v={v} players={players} />}
|
||||
{m.canReady && (
|
||||
{v.handPhase === 'handEnd' && endShown && <ResultPanel v={v} players={players} />}
|
||||
{m.canReady && endShown && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={pending} onClick={() => act({ type: 'ready' })}>
|
||||
다음 판으로
|
||||
</button>
|
||||
)}
|
||||
{v.handPhase === 'handEnd' && seat.inHand && seat.ready && seat.status !== 'left' && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>다른 사람을 기다리는 중…</p>}
|
||||
{v.handPhase === 'handEnd' && endShown && seat.inHand && seat.ready && seat.status !== 'left' && <p className="small muted" style={{ margin: 0, textAlign: 'center' }}>다른 사람을 기다리는 중…</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1049,7 +1058,11 @@ function HandRanks({ mode, o }: { mode: PokerMode; o: Pick<PokerOptions, 'indian
|
||||
|
||||
function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<PokerView>) {
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
|
||||
// Chip counts change once the chips have landed on the table.
|
||||
const shownStacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(','));
|
||||
const stackOf = new Map(shownStacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const));
|
||||
const stack = (s: SeatView) => stackOf.get(s.id) ?? s.stack;
|
||||
const ranked = [...v.seats].sort((a, b) => stack(b) - stack(a));
|
||||
const scoreBy = v.options.endCondition === 'hands' || v.handsPlayed >= 300;
|
||||
return (
|
||||
<>
|
||||
@@ -1074,31 +1087,33 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
{s.rebuys > 0 ? ` · 리바이 ${s.rebuys}` : ''}
|
||||
{s.status === 'eliminated' ? ' · 탈락' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
<Chips n={s.stack} />
|
||||
<Chips n={stack(s)} />
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => {
|
||||
const sc = v.result!.scores[g[0]!] ?? 0;
|
||||
return (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
|
||||
{scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''}
|
||||
<AfterMotion>
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => {
|
||||
const sc = v.result!.scores[g[0]!] ?? 0;
|
||||
return (
|
||||
<span key={i}>
|
||||
{v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')}
|
||||
{scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{scoreBy && <span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>}
|
||||
{v.stats.bestHand && (
|
||||
<span className="small">
|
||||
최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판)
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{scoreBy && <span className="small muted">점수 = 마지막 칩 − 시작 칩 × 리바이 횟수</span>}
|
||||
{v.stats.bestHand && (
|
||||
<span className="small">
|
||||
최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판)
|
||||
</span>
|
||||
)}
|
||||
{v.stats.biggestPot && <span className="small">가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)</span>}
|
||||
</div>
|
||||
)}
|
||||
{v.stats.biggestPot && <span className="small">가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)</span>}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
)}
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>족보</summary>
|
||||
@@ -1128,20 +1143,22 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
</details>
|
||||
)}
|
||||
{v.my.canRebuy && !confirmQuit && (
|
||||
<Sheet onClose={() => {}} label="칩 다시 받기">
|
||||
<h2>칩을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rebuy', accept: true })}>
|
||||
칩 다시 받기
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ flex: 1 }} disabled={pending} onClick={() => setConfirmQuit(true)}>
|
||||
그만하기
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
<AfterMotion>
|
||||
<Sheet onClose={() => {}} label="칩 다시 받기">
|
||||
<h2>칩을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요.
|
||||
</p>
|
||||
<div className="row">
|
||||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'rebuy', accept: true })}>
|
||||
칩 다시 받기
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ flex: 1 }} disabled={pending} onClick={() => setConfirmQuit(true)}>
|
||||
그만하기
|
||||
</button>
|
||||
</div>
|
||||
</Sheet>
|
||||
</AfterMotion>
|
||||
)}
|
||||
{confirmQuit && v.my.canRebuy && (
|
||||
<ConfirmSheet
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { JUMP_LAND_MS, qdSound } from './sound';
|
||||
import { useAfterMotionValue } from '../../lib/motion';
|
||||
|
||||
type O = 'h' | 'v';
|
||||
interface Pt {
|
||||
@@ -196,6 +197,8 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const newWall = recent?.kind === 'wall' ? wallKey(recent.wall) : null;
|
||||
const goalSeat = recent?.kind === 'move' && reachedGoal(recent.seat, before?.seats ?? [], v.seats) ? recent.seat : null;
|
||||
const takenBack = before && !forward ? before.walls.filter((w) => !v.walls.some((x) => wallKey(x) === wallKey(w))) : [];
|
||||
// Who has reached their goal, as shown: the winner's ring only once the pawn has landed on the goal row.
|
||||
const arrived = useAfterMotionValue(v.seats.filter((x) => x.status === 'finished').map((x) => x.seat).join(''));
|
||||
|
||||
const legalCells = useMemo(() => {
|
||||
const m = new Set<string>();
|
||||
@@ -562,7 +565,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
return (
|
||||
<g key={x.seat} className={`qd-pawn${moved && jumped ? ' jump' : ''}`} style={{ transform: `translate(${p.x + 0.5}px, ${p.y + 0.5}px)` }} data-pawn={x.seat} data-at={label(x.pos)}>
|
||||
{turn && <circle className="qd-turn-ring" cx={0} cy={0} r={0.45} fill="none" stroke={SEAT_COLOR[x.seat]} strokeWidth={0.06} />}
|
||||
{x.status === 'finished' && <circle className="bm-win" cx={0} cy={0} r={0.47} fill="none" stroke="#fbbf24" strokeWidth={0.07} />}
|
||||
{x.status === 'finished' && arrived.includes(x.seat) && <circle className="bm-win" cx={0} cy={0} r={0.47} fill="none" stroke="#fbbf24" strokeWidth={0.07} />}
|
||||
<g key={`h${v.moveCount}`} className={moved ? (jumped ? 'qd-hop' : 'qd-step') : undefined}>
|
||||
<PawnMark seat={x.seat} cx={0} cy={0} />
|
||||
</g>
|
||||
@@ -645,7 +648,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
)}
|
||||
{me && v.phase === 'playing' && !(myTurn && mode === 'wall') && (
|
||||
<p className="small muted" style={{ margin: 0, textAlign: 'center' }}>
|
||||
{me.status === 'playing'
|
||||
{me.status === 'playing' || (me.status === 'finished' && !arrived.includes(me.seat))
|
||||
? `내 말은 ${COLOR_KO[me.seat]}(${SEAT_KO[me.seat]})이에요. ${myGoal} 줄(${COLOR_KO[me.seat]} 띠)에 먼저 닿으면 이겨요.`
|
||||
: me.status === 'finished'
|
||||
? '목표에 도착했어요! 남은 사람들의 순위가 정해질 때까지 지켜봐요.'
|
||||
@@ -691,7 +694,7 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid
|
||||
} else if (active && tc.kind === 'perMove') {
|
||||
clock = <TurnTimer deadline={deadline} totalMs={tc.perMoveSec * 1000} mine={x.playerId === me} size={40} />;
|
||||
}
|
||||
const state =
|
||||
const stateNow =
|
||||
x.status === 'finished'
|
||||
? `${x.finishOrder}등 도착`
|
||||
: x.status === 'resigned'
|
||||
@@ -699,6 +702,8 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid
|
||||
: x.status === 'timedOut'
|
||||
? '시간패'
|
||||
: `남은 길 ${x.distance}칸${x.autoMoveStreak > 0 ? ` · 자리 비움 ${x.autoMoveStreak}번` : ''}`;
|
||||
// "1등 도착" and the path length change once the move has played on the board.
|
||||
const state = useAfterMotionValue(stateNow);
|
||||
return (
|
||||
<div
|
||||
className="card row"
|
||||
|
||||
289
apps/web/src/games/race/kit.tsx
Normal file
289
apps/web/src/games/race/kit.tsx
Normal file
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Shared screen parts for the race games (docs/games/race.md §4): the clock row, everyone's progress chips, the side
|
||||
* ranking, the countdown and finished notes, 포기, the time limit option and the shared status / help lines.
|
||||
* Each game draws its own board in between.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { sfx, tone } from '../../lib/feedback';
|
||||
import { AfterMotion } from '../../lib/motion';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export { STATUS_WORD, limitLabel, mySeat, nick, raceHelp, raceIsMyTurn, raceStatusText } from './text';
|
||||
import { STATUS_WORD, limitLabel, mySeat, nick } from './text';
|
||||
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const clock = (ms: number) => {
|
||||
const s = Math.ceil(Math.max(0, ms) / 1000);
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
};
|
||||
/** Stopwatch: "1:05.4". */
|
||||
const watch = (ms: number) => {
|
||||
const t = Math.floor(Math.max(0, ms) / 100);
|
||||
return `${Math.floor(t / 600)}:${String(Math.floor((t % 600) / 10)).padStart(2, '0')}.${t % 10}`;
|
||||
};
|
||||
|
||||
export function canPlay(v: V, me: string | null, now: number): boolean {
|
||||
const s = mySeat(v, me);
|
||||
return !!s && s.status === 'playing' && v.phase === 'playing' && !!v.board && (v.endsAt === null || now < v.endsAt);
|
||||
}
|
||||
|
||||
export const RACE_CSS = `
|
||||
.rc { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
|
||||
.rc-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.rc-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; font-size: 1rem; white-space: nowrap; border: 0; color: inherit; }
|
||||
.rc-pill b { font-size: 1.1rem; }
|
||||
.rc-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
button.rc-pill { cursor: pointer; min-height: 36px; }
|
||||
button.rc-pill[aria-pressed='true'] { background: var(--primary); color: #fff; }
|
||||
.rc-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
|
||||
.rc-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; }
|
||||
.rc-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rc-others li b { font-variant-numeric: tabular-nums; margin-left: 2px; }
|
||||
.rc-others li[data-me='true'] { background: var(--primary-soft); }
|
||||
.rc-others li[data-out='true'] { opacity: .55; }
|
||||
.rc-wrap { position: relative; max-width: 100%; }
|
||||
.rc-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
|
||||
border-radius: 12px; text-align: center; padding: 12px; z-index: 4; }
|
||||
.rc-over.count { background: rgba(0,0,0,.4); color: #fff; font-size: 4.5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); min-height: 180px; }
|
||||
.rc-over.count small { font-size: 1.05rem; font-weight: 800; }
|
||||
.rc-over.count b { display: block; animation: rc-count .9s ease-out both; }
|
||||
.rc-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
|
||||
.rc-over.note.win { color: var(--success); border: 3px solid var(--success); }
|
||||
.rc-acts { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
|
||||
.rc-acts .btn { min-height: 40px; }
|
||||
.rc-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
|
||||
.rc-wait { min-height: 220px; width: min(100%, 520px); border-radius: 12px; background: var(--surface-2); }
|
||||
@keyframes rc-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
|
||||
@media (prefers-reduced-motion: reduce) { .rc-over.count b { animation: none; } }
|
||||
`;
|
||||
|
||||
/** Clock values for the board: time left (time limit) or my stopwatch (무제한), the 3·2·1 countdown. */
|
||||
export function useRaceClock(v: V, me: string | null) {
|
||||
const now = useServerNow(v.endsAt === null ? 100 : 200);
|
||||
const mine = mySeat(v, me);
|
||||
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
|
||||
const elapsed = mine?.timeMs ?? (v.phase === 'playing' && (!mine || mine.status === 'playing') ? Math.max(0, now - v.countdownEndsAt) : null);
|
||||
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
// Sounds that follow the clock: 3·2·1, start, the last 10 seconds, finishing.
|
||||
const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0;
|
||||
const heard = useRef({ countdown: 0, lastSec: 0, status: mine?.status ?? null });
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) tone(660, 90, 'triangle', 0.12);
|
||||
else if (was.countdown > 0 && v.phase === 'playing') {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
}
|
||||
}
|
||||
if (lastSec && lastSec !== was.lastSec) sfx.tick();
|
||||
const st = mine?.status ?? null;
|
||||
if (st !== was.status && was.status === 'playing') {
|
||||
if (st === 'solved') sfx.fanfare();
|
||||
else if (st === 'failed') sfx.bad();
|
||||
}
|
||||
heard.current = { countdown, lastSec, status: st };
|
||||
});
|
||||
return { now, left, elapsed, countdown, mine };
|
||||
}
|
||||
|
||||
/** Top row: the clock first, then the game's own pills. */
|
||||
export function RaceTop({ v, left, elapsed, children }: { v: V; left: number | null; elapsed: number | null; children?: ReactNode }) {
|
||||
return (
|
||||
<div className="rc-top">
|
||||
{left === null ? (
|
||||
<span className="rc-pill" aria-label={elapsed === null ? '제한 시간 없음' : `걸린 시간 ${formatElapsed(elapsed)}`}>
|
||||
⏱ {elapsed === null ? '무제한' : <b style={{ fontSize: '1rem' }}>{watch(elapsed)}</b>}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`rc-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
|
||||
⏱ {clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everyone's progress (live), ranked; only with more than one player. */
|
||||
export function RaceSeats({ v, me, players }: { v: V; me: string | null; players: Record<string, PublicUser> }) {
|
||||
if (v.seats.length < 2) return null;
|
||||
return (
|
||||
<ol className="rc-others" aria-label="진행 상황">
|
||||
{rankSeats(v.seats).map((s) => (
|
||||
<li
|
||||
key={s.id}
|
||||
data-me={s.id === me}
|
||||
data-out={s.status === 'left'}
|
||||
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, ${s.status === 'solved' ? `다 풀었어요 ${formatElapsed(s.timeMs ?? 0)}` : s.progressText}${s.status !== 'playing' && s.status !== 'solved' ? `, ${STATUS_WORD[s.status]}` : ''}`}
|
||||
>
|
||||
<Avatar user={userOf(players, s.id)} size={20} />
|
||||
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<b key={s.progress} className={s.progress ? 'anim-bump' : undefined}>
|
||||
{s.status === 'solved' ? `✔ ${formatElapsed(s.timeMs ?? 0)}` : s.progressText.replace(/^[^\d]*/, '')}
|
||||
</b>
|
||||
{s.status !== 'playing' && s.status !== 'solved' && <span aria-hidden>· {STATUS_WORD[s.status]}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
/** Countdown over the (still hidden) board. */
|
||||
export function RaceCountdown({ countdown, text }: { countdown: number; text: string }) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<div className="rc-over count" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>{text}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Notes over the board once I am finished, left, or watching. */
|
||||
export function RaceNotes({ v, mine, failText }: { v: V; mine: RaceSeat | null; failText: string }) {
|
||||
const playing = v.phase === 'playing';
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
return (
|
||||
<>
|
||||
<AfterMotion when={!!mine && mine.status === 'solved' && playing}>
|
||||
<div className="rc-over note win" role="status">
|
||||
다 풀었어요! {formatElapsed(mine?.timeMs ?? 0)}
|
||||
{mine?.extra}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
<AfterMotion when={!!mine && mine.status === 'failed' && playing}>
|
||||
<div className="rc-over note" role="status">
|
||||
{failText} {mine?.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
{mine?.status === 'done' && playing && (
|
||||
<div className="rc-over note" role="status">
|
||||
포기했어요. {mine.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
)}
|
||||
{mine?.status === 'left' && v.phase !== 'ended' && <div className="rc-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="rc-over note">관전 중이에요 · 위에서 진행 상황을 볼 수 있어요</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 포기: press twice (the first press only asks). */
|
||||
export function GiveUp({ act }: { act: (a: unknown) => void }) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!ask) return;
|
||||
const t = setTimeout(() => setAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [ask]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${ask ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => {
|
||||
if (!ask) return setAsk(true);
|
||||
setAsk(false);
|
||||
act({ type: 'stop' });
|
||||
}}
|
||||
>
|
||||
{ask ? '한 번 더 누르면 포기해요' : '포기할래요'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Right panel: the live ranking, then the final one. */
|
||||
export function RaceSide({ v, me, players, title, info }: { v: V; me: string | null; players: Record<string, PublicUser>; title: string; info: string }) {
|
||||
return (
|
||||
<>
|
||||
<style>{RACE_CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>
|
||||
{title}
|
||||
{v.phase === 'ended' ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
<span className="small muted">
|
||||
{info} · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rankSeats(v.seats).map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}>
|
||||
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
|
||||
{s.rank}등
|
||||
</span>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{STATUS_WORD[s.status] ? ` · ${STATUS_WORD[s.status]}` : ''}
|
||||
</span>
|
||||
<strong className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.status === 'solved' ? formatElapsed(s.timeMs ?? 0) : s.progressText}
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small"> · {r.text}</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Time limit choice for the room settings. */
|
||||
export function TimeLimitOption({ value, choices, onChange }: { value: number | null; choices: number[]; onChange: (v: number | null) => void }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>제한 시간</strong>
|
||||
<Seg label="제한 시간" value={value} options={[...choices.map((c) => [c, limitLabel(c)] as [number, string]), [null, '무제한']]} onChange={onChange} />
|
||||
<span className="small muted">
|
||||
{value === null ? '시간 제한 없이 각자 다 풀거나 포기할 때까지 해요. 스톱워치로 걸린 시간을 재요.' : '시간이 끝나면 다 못 푼 사람은 푼 만큼으로 순위를 매겨요.'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Narrow screens (phones). */
|
||||
export function useNarrow(): boolean {
|
||||
const q = '(max-width: 640px)';
|
||||
const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches);
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia(q);
|
||||
const on = () => setM(mq.matches);
|
||||
mq.addEventListener('change', on);
|
||||
return () => mq.removeEventListener('change', on);
|
||||
}, []);
|
||||
return m;
|
||||
}
|
||||
55
apps/web/src/games/race/text.ts
Normal file
55
apps/web/src/games/race/text.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/** Pure text helpers for the race games (status line, [?] help); no DOM, so help tests can import them. */
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
export const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
|
||||
export const STATUS_WORD: Record<RaceSeat['status'], string> = { playing: '', solved: '다 풂', failed: '실패', done: '포기', left: '나감' };
|
||||
|
||||
export function mySeat(v: V, me: string | null): RaceSeat | null {
|
||||
return v.seats.find((s) => s.id === me) ?? null;
|
||||
}
|
||||
|
||||
/** I can make moves now. */
|
||||
export function raceIsMyTurn(v: V, me: string | null): boolean {
|
||||
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
|
||||
}
|
||||
|
||||
/** Status line; `playing` is the game's line while I am still solving. */
|
||||
export function raceStatusText(v: V, me: string | null, players: Record<string, PublicUser>, texts: { countdown: string; playing: string; failed: string }): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return texts.countdown;
|
||||
const mine = mySeat(v, me);
|
||||
if (!mine) {
|
||||
const top = rankSeats(v.seats)[0];
|
||||
return top && top.status === 'solved' ? `${nick(players, top.id)}님이 가장 먼저 다 풀었어요` : '모두 같은 판을 풀고 있어요';
|
||||
}
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
if (mine.status === 'left') return '게임에서 나갔어요';
|
||||
if (mine.status === 'solved') return `다 풀었어요! ${formatElapsed(mine.timeMs ?? 0)}${mine.extra}${wait}`;
|
||||
if (mine.status === 'failed') return `${texts.failed} ${mine.progressText}${wait}`;
|
||||
if (mine.status === 'done') return `포기했어요 · ${mine.progressText}${wait}`;
|
||||
return texts.playing;
|
||||
}
|
||||
|
||||
/** [?] lines every race game shares: phase, my state, who leads. `how` explains the game's moves. */
|
||||
export function raceHelp(v: V, me: string | null, players: Record<string, PublicUser>, how: string[], failed: string): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 걸린 시간과 푼 만큼을 볼 수 있어요.';
|
||||
const secs = v.options.timeLimitSec;
|
||||
const limitLine = secs === null ? '제한 시간은 없어요. 다 풀거나 포기할 때까지 해요.' : `제한 시간은 ${limitLabel(secs)}이에요.`;
|
||||
const winLine = v.seats.length > 1 ? '가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 푼 사람이 이겨요.' : '';
|
||||
if (v.phase === 'countdown') return [`곧 시작해요. 모두 똑같은 판을 각자 풀어요. ${limitLine}`, ...how].join('\n');
|
||||
const mine = mySeat(v, me);
|
||||
const solved = rankSeats(v.seats).filter((s) => s.status === 'solved');
|
||||
const lead = v.seats.length > 1 && solved.length ? `지금까지 ${solved.map((s) => (s.id === me ? '나' : `${nick(players, s.id)}님`)).join(', ')}이(가) 다 풀었어요.` : '';
|
||||
if (!mine) return [`모두 똑같은 판을 각자 풀고 있어요. ${winLine}`, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
const waitLine = v.seats.length > 1 ? '모두 끝나면 순위가 나와요.' : '';
|
||||
if (mine.status === 'solved') return [`다 풀었어요! 걸린 시간은 ${formatElapsed(mine.timeMs ?? 0)}이에요.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'failed') return [`${failed} ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'done') return [`포기했어요. ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
return [...how, `지금 ${mine.progressText}.`, limitLine, winLine, lead, '그만하고 싶으면 [포기할래요]를 두 번 눌러요.'].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
'cockroach-poker': () => import('./cockroach-poker'),
|
||||
'ninety-nine': () => import('./ninety-nine'),
|
||||
'connect-four': () => import('./connect-four'),
|
||||
typing: () => import('./typing'),
|
||||
minesweeper: () => import('./minesweeper'),
|
||||
shisen: () => import('./shisen'),
|
||||
solitaire: () => import('./solitaire'),
|
||||
sudoku: () => import('./sudoku'),
|
||||
nonogram: () => import('./nonogram'),
|
||||
'old-maid': () => import('./old-maid'),
|
||||
dobble: () => import('./dobble'),
|
||||
catchmind: () => import('./catchmind'),
|
||||
|
||||
@@ -34,7 +34,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useNewEntries
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
@@ -351,8 +351,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const movedFrom = useRef<Map<string, DOMRect> | null>(null);
|
||||
/** Who had the turn on the previous render: tiles that newly show up on the table come from that seat. */
|
||||
const prevCurrent = useRef(v.current);
|
||||
const winTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(winTimer.current), []);
|
||||
// The round / match end banners are staged with timers (after the last tiles have landed): results wait for them.
|
||||
const endTimers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
const [ending, setEnding] = useState(false);
|
||||
useMotionHold(ending);
|
||||
useEffect(() => () => endTimers.current.forEach(clearTimeout), []);
|
||||
const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record<string, boolean>; table: Set<string> } | null>(null);
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
const boardRef = useRef<HTMLDivElement>(null);
|
||||
@@ -485,23 +488,42 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
// Somebody else is moving tiles around in their turn.
|
||||
snd.shuffleQuiet();
|
||||
}
|
||||
const endSteps: (() => void)[] = [];
|
||||
// The round is over: "루미큐브!" when somebody emptied the rack (the match result sound itself is played by the room page).
|
||||
if (prev.phase === 'playing' && v.phase !== 'playing' && v.round) {
|
||||
const w = v.round.winners;
|
||||
const who = w.includes(me ?? '') ? '내가' : `${w.map((p) => nick(players, p)).join(', ')}님이`;
|
||||
if (v.round.endReason === 'rackEmpty') {
|
||||
showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`);
|
||||
for (const p of w) bump(seatEl(p));
|
||||
if (v.phase === 'roundEnd') sfx.fanfare();
|
||||
} else if (v.round.endReason === 'stalemate') showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요');
|
||||
const roundEnd = v.phase === 'roundEnd';
|
||||
if (v.round.endReason === 'rackEmpty')
|
||||
endSteps.push(() => {
|
||||
showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`);
|
||||
for (const p of w) bump(seatEl(p));
|
||||
if (roundEnd) sfx.fanfare();
|
||||
});
|
||||
else if (v.round.endReason === 'stalemate') endSteps.push(() => showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요'));
|
||||
}
|
||||
// The match is over: who won (after the round banner, if there was one).
|
||||
if (prev.phase !== 'finished' && v.phase === 'finished' && v.result?.reason === 'normal') {
|
||||
const top = v.result.ranking[0] ?? [];
|
||||
const iWon = top.includes(me ?? '');
|
||||
const text = iWon ? '승리!' : top.length ? `${top.map((p) => nick(players, p)).join(', ')}님 승리` : '게임 끝';
|
||||
clearTimeout(winTimer.current);
|
||||
winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? fxMs(1500) : 0);
|
||||
const sub = v.match.total > 1 ? `${v.match.total}판 합계` : undefined;
|
||||
endSteps.push(() => showBanner(text, iWon ? 'gold' : 'blue', sub));
|
||||
}
|
||||
if (endSteps.length) {
|
||||
// The last tiles put down (new on the screen: they fly in from the seat, see below) land first, then the banners
|
||||
// one by one. `prevCells` (declared below) still holds the previous render's board here.
|
||||
const before = prevCells.current;
|
||||
const landed = before ? cells.filter((x) => !before.has(x.id)).length : 0;
|
||||
const lead = prev.phase === 'playing' && landed ? fxMs(380 + Math.min(landed, 20) * 60) : 0;
|
||||
endTimers.current.forEach(clearTimeout);
|
||||
setEnding(true);
|
||||
endTimers.current = endSteps.map((f, i) =>
|
||||
setTimeout(() => {
|
||||
f();
|
||||
if (i === endSteps.length - 1) setEnding(false);
|
||||
}, lead + i * fxMs(1500)),
|
||||
);
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -1004,7 +1026,9 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
</>
|
||||
)}
|
||||
|
||||
{v.phase !== 'playing' && v.round && <RoundPanel v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} />}
|
||||
<AfterMotion when={v.phase !== 'playing' && !!v.round}>
|
||||
<RoundPanel v={v} me={me} players={players} act={act} pending={pending} deadline={deadline} />
|
||||
</AfterMotion>
|
||||
|
||||
{my && v.phase === 'playing' && (
|
||||
<div className="rk-rackwrap">
|
||||
@@ -1210,14 +1234,24 @@ function logText(e: LogEntry, players: Record<string, PublicUser>, me: string |
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function RummikubSide({ view: v, me, players }: BoardProps<RummikubView>) {
|
||||
const order = [...v.seats].sort((a, b) => b.wins - a.wins || b.total - a.total);
|
||||
// Wins / points (and 게임 끝) change when a round ends: they show once the board has played the end of the round.
|
||||
const scoreKey = useAfterMotionValue(`${v.phase === 'finished' ? 'f' : ''}|${v.seats.map((s) => `${s.id}:${s.wins}:${s.total}`).join(',')}`);
|
||||
const [shownEnd, shownScores] = scoreKey.split('|') as [string, string];
|
||||
const score = new Map(
|
||||
shownScores.split(',').map((x) => {
|
||||
const [id, w, t] = x.split(':');
|
||||
return [id!, { wins: Number(w), total: Number(t) }];
|
||||
}),
|
||||
);
|
||||
const sc = (s: RummikubView['seats'][number]) => score.get(s.id) ?? { wins: s.wins, total: s.total };
|
||||
const order = [...v.seats].sort((a, b) => sc(b).wins - sc(a).wins || sc(b).total - sc(a).total);
|
||||
const lastRound = v.opening.length ? Math.max(...v.opening.map((o) => o.round)) : 0;
|
||||
return (
|
||||
<>
|
||||
<style>{CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'}</strong>
|
||||
<strong>{shownEnd ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'}</strong>
|
||||
<span className="small muted">남은 타일 {v.poolCount}장</span>
|
||||
</div>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
@@ -1231,8 +1265,8 @@ function RummikubSide({ view: v, me, players }: BoardProps<RummikubView>) {
|
||||
<span className="small">{s.tiles}장</span>
|
||||
{v.match.total > 1 && (
|
||||
<span className="small muted">
|
||||
{s.wins}승 · {s.total > 0 ? '+' : ''}
|
||||
{s.total}점
|
||||
{sc(s).wins}승 · {sc(s).total > 0 ? '+' : ''}
|
||||
{sc(s).total}점
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { HWATU_RATIO, HwatuBack, HwatuCard } from '../../components/cards/HwatuC
|
||||
import { haptic, sfx, sounds } from '../../lib/feedback';
|
||||
import { usePhone } from '../../lib/media';
|
||||
import type { BoardProps } from '../types';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import { JokboBoard } from './jokbo';
|
||||
|
||||
export const BET_KO: Record<BetType, string> = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' };
|
||||
@@ -319,6 +319,10 @@ function ActBubble({ seat }: { seat: SeotdaSeatView }) {
|
||||
interface SeatProps {
|
||||
seat: SeotdaSeatView;
|
||||
view: SeotdaView;
|
||||
/** The cards have finished turning over: 족보 seals may show. */
|
||||
revealed: boolean;
|
||||
/** The payout has finished: the hand's +/- may show. */
|
||||
settled: boolean;
|
||||
players: Record<string, PublicUser>;
|
||||
me: string | null;
|
||||
deadline: number | null;
|
||||
@@ -328,8 +332,10 @@ interface SeatProps {
|
||||
setRef: (id: string, el: HTMLElement | null) => void;
|
||||
}
|
||||
|
||||
function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) {
|
||||
function Seat({ seat, view: v, revealed, settled, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) {
|
||||
const u = userOf(players, seat.id);
|
||||
// The money changes once the coins have flown (bets to the 판돈, the 판돈 to the winner).
|
||||
const stack = useAfterMotionValue(seat.stack);
|
||||
const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null);
|
||||
const tags: [string, string][] = [];
|
||||
if (seat.left) tags.push(['나감', '#b91c1c']);
|
||||
@@ -367,7 +373,7 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef
|
||||
</div>
|
||||
<div className="row" style={{ justifyContent: 'space-between', gap: 4, flexWrap: 'nowrap' }}>
|
||||
<span className="sd-money" title="보유 금액">
|
||||
{formatWonShort(seat.stack)}원
|
||||
{formatWonShort(stack)}원
|
||||
</span>
|
||||
{seat.matchBet > 0 && (
|
||||
<span className="small sub" style={{ whiteSpace: 'nowrap' }} title="이번 판에 건 돈">
|
||||
@@ -375,8 +381,8 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{seat.handName && <div className={`sd-seal${isBig(seat.handName) ? ' big' : ''} anim-pop`}>{seat.handName}</div>}
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
{revealed && seat.handName && <div className={`sd-seal${isBig(seat.handName) ? ' big' : ''} anim-pop`}>{seat.handName}</div>}
|
||||
{settled && seat.handDelta !== null && seat.handDelta !== 0 && (
|
||||
<div className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</div>
|
||||
)}
|
||||
{tags.length > 0 && (
|
||||
@@ -449,6 +455,14 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
const [banner, setBanner] = useState<{ text: string; key: number } | null>(null);
|
||||
const seen = useRef<{ match: string; log: number; cards: number; phase: string | null } | null>(null);
|
||||
const flyId = useRef(0);
|
||||
const match = `${v.handNo}-${v.rematchNo}`;
|
||||
// Bet coins still to fly (staged with timers): results wait for them.
|
||||
const [queued, setQueued] = useState(0);
|
||||
useMotionHold(queued > 0);
|
||||
// The hand's result waits until the cards have turned over; `revealedAt` = the (re)match whose payout has started.
|
||||
const [payout, setPayout] = useState<{ winners: Set<string>; banner: string | null } | null>(null);
|
||||
const cardsTurned = useMotionSettled(!!payout);
|
||||
const [revealedAt, setRevealedAt] = useState<string | null>(() => (v.handPhase === 'handEnd' ? match : null));
|
||||
|
||||
const center = (el: HTMLElement | null | undefined) => {
|
||||
const t = tableRef.current?.getBoundingClientRect();
|
||||
@@ -467,7 +481,6 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const match = `${v.handNo}-${v.rematchNo}`;
|
||||
const cards = v.seats.reduce((a, s) => a + s.cards.length, 0);
|
||||
const prev = seen.current;
|
||||
seen.current = { match, log: v.betLog.length, cards, phase: v.handPhase };
|
||||
@@ -481,8 +494,10 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
}
|
||||
// Bets since last time (anyone's): coins fly from the seat to the 판돈.
|
||||
const fresh: BetLogEntry[] = sameMatch ? v.betLog.slice(prev.log) : v.betLog;
|
||||
if (fresh.length) setQueued((q) => q + fresh.length);
|
||||
fresh.forEach((e, i) => {
|
||||
setTimeout(() => {
|
||||
setQueued((q) => q - 1);
|
||||
if (e.t === 'die') sfx.whoosh();
|
||||
else if (e.amount <= 0) sfx.tick();
|
||||
else {
|
||||
@@ -492,36 +507,41 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb
|
||||
}
|
||||
}, fxMs(i * 220));
|
||||
});
|
||||
// Result: reveal, payout, banner.
|
||||
// Result: the cards turn over, then (once they have) the payout and the banner.
|
||||
if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') {
|
||||
if (v.showdown || v.foldWin?.shown) sfx.cardFlip();
|
||||
const winners = new Set<string>();
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
const b = bannerOf(v);
|
||||
setTimeout(() => {
|
||||
for (const w of winners) launch('pot', w, 5);
|
||||
if (winners.size) sfx.collect();
|
||||
if (b) {
|
||||
setBanner({ text: b, key: Date.now() });
|
||||
if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare();
|
||||
else sfx.pop();
|
||||
}
|
||||
if (me && winners.has(me)) {
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
|
||||
}, fxMs(v.showdown ? 450 : 150));
|
||||
setPayout({ winners, banner: bannerOf(v) });
|
||||
}
|
||||
}); // every render: cheap comparisons against the refs
|
||||
|
||||
useEffect(() => {
|
||||
if (!cardsTurned || !payout) return;
|
||||
const { winners, banner: b } = payout;
|
||||
setPayout(null);
|
||||
setRevealedAt(match);
|
||||
for (const w of winners) launch('pot', w, 5);
|
||||
if (winners.size) sfx.collect();
|
||||
if (b) {
|
||||
setBanner({ text: b, key: Date.now() });
|
||||
if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare();
|
||||
else sfx.pop();
|
||||
}
|
||||
if (me && winners.has(me)) {
|
||||
sounds.win();
|
||||
haptic([40, 30, 80]);
|
||||
} else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose();
|
||||
}, [cardsTurned]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!banner) return undefined;
|
||||
const t = setTimeout(() => setBanner(null), fxMs(1700));
|
||||
return () => clearTimeout(t);
|
||||
}, [banner]);
|
||||
|
||||
return { flies, banner };
|
||||
return { flies, banner, revealed: v.handPhase === 'handEnd' && revealedAt === match && !payout };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- bottom bar (한게임 섯다처럼: 족보 · 내 얼굴 · 내 패 · 베팅 버튼)
|
||||
@@ -657,6 +677,8 @@ interface DockProps {
|
||||
pending: boolean;
|
||||
deadline: number | null;
|
||||
winner: boolean;
|
||||
revealed: boolean;
|
||||
settled: boolean;
|
||||
setRef: SeatProps['setRef'];
|
||||
phone: boolean;
|
||||
/** My card size factor (PC: grows with the table width). */
|
||||
@@ -668,7 +690,7 @@ interface DockProps {
|
||||
* them, then the number-key bet buttons. In 3장 섯다 the cards themselves are clicked to pick the open card / the two
|
||||
* cards to use, and the bet buttons make room for that step's button.
|
||||
*/
|
||||
function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, phone, scale }: DockProps) {
|
||||
function Dock({ view: v, seat, players, act, pending, deadline, winner, revealed, settled, setRef, phone, scale }: DockProps) {
|
||||
const [pick, setPick] = useState<number[]>([]);
|
||||
useEffect(() => setPick([]), [v.handNo, v.rematchNo, v.handPhase]);
|
||||
const [hover, setHover] = useState<BetType | null>(null);
|
||||
@@ -679,7 +701,11 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
const myKeys = (seat?.cards ?? []).filter(isCard).map((c) => c.key);
|
||||
if (myKeys.length && first.current?.tag !== matchTag) first.current = { tag: matchTag, keys: new Set(myKeys) };
|
||||
const squeezing = (key: string) => !!first.current && first.current.tag === matchTag && !first.current.keys.has(key) && !peeked.has(key) && !seat?.handName;
|
||||
const peeking = myKeys.some(squeezing);
|
||||
// Cards still being dealt in: the 족보 they make shows once they have landed.
|
||||
const cardKey = myKeys.join(',');
|
||||
const dealing = useAfterMotionValue(cardKey) !== cardKey;
|
||||
const peeking = myKeys.some(squeezing) || dealing;
|
||||
const stack = useAfterMotionValue(seat?.stack ?? 0);
|
||||
const u = seat ? userOf(players, seat.id) : null;
|
||||
const cards = seat?.cards ?? [];
|
||||
const opening = !!seat && v.handPhase === 'open' && seat.opening === false;
|
||||
@@ -702,7 +728,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
|
||||
// Under my cards: the 족보 (or, with 3 cards, every pair's 족보 like 한게임; clickable while choosing).
|
||||
let under: ReactNode = null;
|
||||
if (seat?.handName) under = <span className={`sd-seal anim-pop${isBig(seat.handName) ? ' big' : ''}`}>{seat.handName}</span>;
|
||||
if (seat?.handName && revealed) under = <span className={`sd-seal anim-pop${isBig(seat.handName) ? ' big' : ''}`}>{seat.handName}</span>;
|
||||
else if (seat?.folded) under = <span className="sd-seal die">다이</span>;
|
||||
else if (playing && hints && v.myCombos && !v.myChosen && !peeking)
|
||||
under = (
|
||||
@@ -766,7 +792,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
else if (v.handPhase === 'handEnd')
|
||||
actions = (
|
||||
<>
|
||||
<ResultPanel view={v} players={players} />
|
||||
{settled ? <ResultPanel view={v} players={players} /> : <p>결과를 확인하는 중이에요…</p>}
|
||||
{seat && seat.status === 'playing' && !seat.left && (
|
||||
<button type="button" className="btn btn-primary btn-block" disabled={seat.ready || pending} onClick={() => act({ type: 'ready' })}>
|
||||
{seat.ready ? '다른 사람을 기다리는 중…' : v.next === 'rematch' ? '재경기 시작' : '다음 판으로'}
|
||||
@@ -798,7 +824,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
<ActBubble seat={seat} />
|
||||
<Avatar user={u} size={phone ? 34 : 52} />
|
||||
<strong className="nm">{u.nickname} (나)</strong>
|
||||
<span className="sd-money">{formatWonShort(seat.stack)}원</span>
|
||||
<span className="sd-money">{formatWonShort(stack)}원</span>
|
||||
<span className="row" style={{ gap: 4, justifyContent: 'center', minHeight: 30 }}>
|
||||
{seat.isDealer && (
|
||||
<span className="sd-tag" style={{ background: '#facc15', color: '#422006' }} title="선(먼저 받고 먼저 거는 사람)">
|
||||
@@ -807,7 +833,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
)}
|
||||
{timed && <TurnTimer deadline={deadline} totalMs={totalMsOf(v)} mine size={30} />}
|
||||
</span>
|
||||
{seat.handDelta !== null && seat.handDelta !== 0 && <span className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</span>}
|
||||
{settled && seat.handDelta !== null && seat.handDelta !== 0 && <span className={`sd-delta anim-slide-up ${seat.handDelta > 0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}</span>}
|
||||
</div>
|
||||
)}
|
||||
<div className="sd-play" role={group ? 'group' : undefined} aria-label={group}>
|
||||
@@ -838,7 +864,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef,
|
||||
)}
|
||||
</div>
|
||||
{under && <div className="under">{under}</div>}
|
||||
{playing && h && hints && !seat.handName && <span className="hint">{h.hint}</span>}
|
||||
{playing && h && hints && !(seat.handName && revealed) && <span className="hint">{h.hint}</span>}
|
||||
{seat.folded && !seat.handName && <span className="hint">다이했어요. 내 패는 나만 볼 수 있어요.</span>}
|
||||
</div>
|
||||
)}
|
||||
@@ -923,7 +949,9 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
if (el) seatEls.current.set(id, el);
|
||||
else seatEls.current.delete(id);
|
||||
};
|
||||
const { flies, banner } = useTableEffects(v, me, tableRef, seatEls, potEl);
|
||||
const { flies, banner, revealed } = useTableEffects(v, me, tableRef, seatEls, potEl);
|
||||
// Result panel, winners' glow and +/- wait for the payout coins and the banner.
|
||||
const settled = useMotionSettled(revealed);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const prevToAct = useRef(v.toAct);
|
||||
useLayoutEffect(() => {
|
||||
@@ -937,7 +965,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
prevToAct.current = v.toAct;
|
||||
}, [v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const winners = new Set<string>();
|
||||
if (v.handPhase === 'handEnd') {
|
||||
if (v.handPhase === 'handEnd' && settled) {
|
||||
if (v.foldWin) winners.add(v.foldWin.winner);
|
||||
for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w);
|
||||
}
|
||||
@@ -966,6 +994,8 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
key={s.id}
|
||||
seat={s}
|
||||
view={v}
|
||||
revealed={revealed}
|
||||
settled={settled}
|
||||
players={players}
|
||||
me={me}
|
||||
deadline={deadline}
|
||||
@@ -996,7 +1026,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Dock view={v} seat={mySeat} players={players} act={act} pending={pending} deadline={deadline} winner={!!mySeat && winners.has(mySeat.id)} setRef={setRef} phone={phone} scale={dockScale} />
|
||||
<Dock view={v} seat={mySeat} players={players} act={act} pending={pending} deadline={deadline} winner={!!mySeat && winners.has(mySeat.id)} revealed={revealed} settled={settled} setRef={setRef} phone={phone} scale={dockScale} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/mone
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import { HWATU_CREDIT } from '../../components/cards/HwatuCard';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { BET_KO, SeotdaBoard, nick, resultLine, totalMsOf, userOf } from './board';
|
||||
@@ -21,7 +22,14 @@ const PLAY_MONEY_NOTICE = '여기 나오는 원과 판돈은 이 방 안에서
|
||||
|
||||
function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps<SeotdaView>) {
|
||||
const [confirmQuit, setConfirmQuit] = useState(false);
|
||||
const ranked = [...v.seats].sort((a, b) => b.stack - a.stack);
|
||||
// Money, 판 기록 and the popups below change only after the table has finished animating (coins, cards).
|
||||
const stacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(','));
|
||||
const stackOf = new Map(stacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))]));
|
||||
const ranked = v.seats.map((s) => ({ ...s, stack: stackOf.get(s.id) ?? s.stack })).sort((a, b) => b.stack - a.stack);
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const showResult = useMotionSettled(!!v.result);
|
||||
const showRejoin = useMotionSettled(!!v.rejoin?.mine);
|
||||
const showRebuy = useMotionSettled(!!v.rebuy?.mine);
|
||||
const log = v.betLog;
|
||||
return (
|
||||
<>
|
||||
@@ -55,7 +63,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
{showResult && v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((g, i) => (
|
||||
@@ -80,11 +88,11 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<details className="card" style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>판 기록</summary>
|
||||
<ol style={{ listStyle: 'none', margin: '8px 0 0', padding: 0, display: 'grid', gap: 2, maxHeight: 180, overflow: 'auto' }}>
|
||||
{[...v.history].reverse().map((r, i) => (
|
||||
{[...history].reverse().map((r, i) => (
|
||||
<li key={i} className="small">
|
||||
<span className="muted">
|
||||
{r.handNo}판{r.rematchNo ? `(재${r.rematchNo})` : ''}
|
||||
@@ -97,7 +105,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
{v.rejoin?.mine && (
|
||||
{showRejoin && v.rejoin?.mine && (
|
||||
<Sheet onClose={() => {}} label="재경기 참가">
|
||||
<h2>구사 재경기에 다시 들어갈까요?</h2>
|
||||
<p className="muted">판돈에 {formatWon(v.rejoin.cost)}을 더 내면 재경기에 참가할 수 있어요. 시간이 지나면 참가하지 않아요.</p>
|
||||
@@ -111,7 +119,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
</div>
|
||||
</Sheet>
|
||||
)}
|
||||
{v.rebuy?.mine && !confirmQuit && (
|
||||
{showRebuy && v.rebuy?.mine && !confirmQuit && (
|
||||
<Sheet onClose={() => {}} label="시작 금액 다시 받기">
|
||||
<h2>가진 원을 모두 잃었어요</h2>
|
||||
<p className="muted">
|
||||
|
||||
41
apps/web/src/games/shisen/art.tsx
Normal file
41
apps/web/src/games/shisen/art.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 사천성 board geometry and small pictures for the rules and help cards (tiles: ../mahjong/Tile). */
|
||||
import { Tile } from '../mahjong/Tile';
|
||||
|
||||
/** Felt behind the tiles (the same in light and dark mode). */
|
||||
export const FELT = '#2f6b4f';
|
||||
export const LINE = '#fbbf24';
|
||||
|
||||
/**
|
||||
* Where things sit on a board of `dR`×`dC` tiles `tw` px wide: tiles are 3:4, with a half-tile margin all round that
|
||||
* connecting lines may run through. Margin rows/columns (-1 and dR/dC) map to the middle of that strip.
|
||||
*/
|
||||
export function geom(tw: number, dR: number, dC: number) {
|
||||
const th = Math.round((tw * 4) / 3);
|
||||
const m = Math.round(tw / 2);
|
||||
const x = (c: number) => (c < 0 ? m / 2 : c >= dC ? m + dC * tw + m / 2 : m + (c + 0.5) * tw);
|
||||
const y = (r: number) => (r < 0 ? m / 2 : r >= dR ? m + dR * th + m / 2 : m + (r + 0.5) * th);
|
||||
return { tw, th, m, w: dC * tw + 2 * m, h: dR * th + 2 * m, x, y, left: (c: number) => m + c * tw, top: (r: number) => m + r * th };
|
||||
}
|
||||
|
||||
/** A tiny board (rows of kind codes, '' = empty) with an optional line through [row, col] points. */
|
||||
export function MiniBoard({ rows, path, tw = 26, dim = [] }: { rows: string[][]; path?: [number, number][]; tw?: number; dim?: string[] }) {
|
||||
const g = geom(tw, rows.length, rows[0]!.length);
|
||||
return (
|
||||
<div aria-hidden style={{ position: 'relative', width: g.w, height: g.h, background: FELT, borderRadius: 8, flex: 'none' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
row.map((k, c) =>
|
||||
k ? (
|
||||
<div key={`${r}-${c}`} style={{ position: 'absolute', left: g.left(c), top: g.top(r), opacity: dim.includes(k) ? 0.35 : 1 }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
) : null,
|
||||
),
|
||||
)}
|
||||
{path && (
|
||||
<svg width={g.w} height={g.h} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
|
||||
<polyline points={path.map(([r, c]) => `${g.x(c)},${g.y(r)}`).join(' ')} fill="none" stroke={LINE} strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
apps/web/src/games/shisen/help.ts
Normal file
19
apps/web/src/games/shisen/help.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/** 사천성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { ShisenView } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'같은 그림의 패 두 장을 차례로 누르면 없어져요. 두 패 사이를 빈 칸으로만 지나는 선이 두 번 이하로 꺾여야 해요(판 바깥 테두리로 돌아가도 돼요).',
|
||||
'고른 패를 다시 누르면 취소돼요. 이을 수 있는 쌍이 하나도 없으면 남은 패가 저절로 섞여요.',
|
||||
'키보드: 화살표로 옮기고 스페이스(또는 Enter)로 골라요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!v.board || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const left = v.board.cells.filter((k) => k !== null).length;
|
||||
const hint = !v.options.hints ? '이 방은 힌트를 쓰지 않아요.' : v.board.hint ? '빛나는 두 장이 힌트예요.' : '막히면 [💡 힌트]로 이을 수 있는 쌍 하나를 볼 수 있어요.';
|
||||
return `${lines}\n남은 패는 ${left}장이에요. ${hint}`;
|
||||
}
|
||||
445
apps/web/src/games/shisen/index.tsx
Normal file
445
apps/web/src/games/shisen/index.tsx
Normal file
@@ -0,0 +1,445 @@
|
||||
/** 사천성 화면 (docs/games/shisen.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { SIZES, findPath, type Point, type ShisenOptions, type ShisenView, type Size } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { MAHJONG_TILE_CREDIT, Tile, tileName } from '../mahjong/Tile';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { FELT, LINE, MiniBoard, geom } from './art';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const NOT_SAME = '같은 패가 아니에요';
|
||||
const TOO_MANY_TURNS = '두 번 넘게 꺾여야 이어져요';
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ss-fit { width: 100%; display: flex; justify-content: center; }
|
||||
.ss-board { position: relative; border-radius: 12px; background: ${FELT}; box-shadow: var(--shadow), inset 0 0 0 2px rgba(0,0,0,.18);
|
||||
touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; outline: none; cursor: pointer; }
|
||||
.ss-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ss-board[data-off='true'] { cursor: default; }
|
||||
.ss-cell { position: absolute; transition: transform .12s ease; pointer-events: none; }
|
||||
.ss-cell .mj-tile { filter: drop-shadow(0 1.5px 1px rgba(0,0,0,.4)); }
|
||||
.ss-cell::after { content: ''; position: absolute; inset: -1px; border-radius: 7px; pointer-events: none; }
|
||||
.ss-cell.sel { transform: translateY(-4px); z-index: 2; }
|
||||
.ss-cell.sel::after { box-shadow: 0 0 0 3px #f59e0b, 0 0 12px 3px rgba(245,158,11,.75); }
|
||||
.ss-cell.hint { transform: translateY(-2px); z-index: 2; }
|
||||
.ss-cell.hint::after { box-shadow: 0 0 0 4px #0ea5e9, 0 0 16px 5px rgba(14,165,233,.95); animation: ss-pulse .8s ease-in-out infinite alternate; }
|
||||
.ss-cell.cur::after { outline: 3px dashed #fff; outline-offset: 1px; }
|
||||
.ss-shake { animation: ss-shake .35s ease both; }
|
||||
.ss-gone { z-index: 3; animation: ss-gone var(--ss-ms) ease-in forwards; }
|
||||
.ss-line { position: absolute; inset: 0; pointer-events: none; z-index: 4; overflow: visible; }
|
||||
.ss-line polyline { animation: ss-fade var(--ss-ms) ease-in forwards; }
|
||||
.ss-toast { position: absolute; top: 6px; left: 50%; transform: translateX(-50%); z-index: 5; padding: 6px 14px; border-radius: 999px; background: var(--surface);
|
||||
color: var(--text); font-weight: 800; box-shadow: var(--shadow); pointer-events: none; white-space: nowrap; animation: ss-pop .25s ease-out both; }
|
||||
.ss-toast.bad { color: var(--danger); }
|
||||
.ss-probe-box { position: relative; width: 0; height: 0; overflow: hidden; flex: none; }
|
||||
.ss-probe { position: absolute; top: 0; left: 0; width: 1px; height: var(--play-h, 100vh); visibility: hidden; }
|
||||
@keyframes ss-shake { 20% { transform: translateX(-5px); } 40% { transform: translateX(5px); } 60% { transform: translateX(-3px); } 80% { transform: translateX(2px); } }
|
||||
@keyframes ss-gone { to { opacity: 0; transform: scale(.7); } }
|
||||
@keyframes ss-fade { 0%, 55% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@keyframes ss-pop { from { opacity: 0; transform: translate(-50%, -6px); } }
|
||||
@keyframes ss-pulse { from { opacity: .6; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ss-shake, .ss-toast, .ss-cell.hint::after, .ss-line polyline { animation: none; }
|
||||
.ss-cell { transition: none; }
|
||||
.ss-gone { animation: none; opacity: 0; }
|
||||
}
|
||||
`;
|
||||
|
||||
const sizeInfo = (s: Size) => `${SIZES[s].name} ${SIZES[s].cols}×${SIZES[s].rows} · ${SIZES[s].rows * SIZES[s].cols}패`;
|
||||
|
||||
interface Flash {
|
||||
key: number;
|
||||
pts: Point[];
|
||||
a: number;
|
||||
b: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
function ShisenBoard({ view: v, me, players, act }: BoardProps<ShisenView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
// The keyboard cursor shows only while playing by keyboard (not after a click or tap).
|
||||
const [keyCursor, setKeyCursor] = useState(false);
|
||||
const [flash, setFlash] = useState<Flash | null>(null);
|
||||
const [shake, setShake] = useState<{ key: number; ids: number[] } | null>(null);
|
||||
const [toast, setToast] = useState<{ key: number; text: string; bad: boolean } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [tw, setTw] = useState(40);
|
||||
const fitRef = useRef<HTMLDivElement>(null);
|
||||
const probeRef = useRef<HTMLDivElement>(null);
|
||||
const boardRef = useRef<HTMLDivElement>(null);
|
||||
const press = useRef<number | null>(null);
|
||||
const seenShuffles = useRef<number | null>(null);
|
||||
const seenHint = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const rows = b?.rows ?? SIZES[v.options.size].rows;
|
||||
const cols = b?.cols ?? SIZES[v.options.size].cols;
|
||||
// Phones: a wide board is turned so it is taller than wide.
|
||||
const turn = phone && cols > rows;
|
||||
const dR = turn ? cols : rows;
|
||||
const dC = turn ? rows : cols;
|
||||
|
||||
// Tile width: fit the column width and the visible height. PC: the play area (--play-h, measured by a probe) minus
|
||||
// the rows above and below the board. Phone: the first screen from the board's top down, minus the buttons below.
|
||||
useLayoutEffect(() => {
|
||||
const fit = fitRef.current;
|
||||
const probe = probeRef.current;
|
||||
if (!fit || !probe) return;
|
||||
const update = () => {
|
||||
const availH = phone ? window.innerHeight - (fit.getBoundingClientRect().top + window.scrollY) - 96 : probe.offsetHeight - 175;
|
||||
const w = Math.floor(Math.min(fit.clientWidth / (dC + 1), availH / ((dR * 4) / 3 + 1), 64));
|
||||
setTw(Math.max(phone ? 34 : 28, w)); // phones: at least a finger-sized tile, scrolling if needed
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(fit);
|
||||
ro.observe(probe);
|
||||
ro.observe(document.body); // rows above the board change height (status text)
|
||||
window.addEventListener('resize', update);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, [dC, dR, phone, !!b]);
|
||||
|
||||
// Auto-reshuffle: say so for a moment.
|
||||
useEffect(() => {
|
||||
const n = b?.shuffles ?? null;
|
||||
const was = seenShuffles.current;
|
||||
seenShuffles.current = n;
|
||||
if (n === null || was === null || n <= was) return;
|
||||
setSel(null);
|
||||
setToast({ key: Date.now(), text: '섞었어요!', bad: false });
|
||||
sfx.shuffle();
|
||||
setAnnounce('이을 수 있는 쌍이 없어서 남은 패를 섞었어요.');
|
||||
}, [b?.shuffles]);
|
||||
|
||||
// A new hint: announce the pair.
|
||||
useEffect(() => {
|
||||
const h = b?.hint ? `${b.hint[0]}-${b.hint[1]}` : null;
|
||||
if (h && h !== seenHint.current && b?.hint) {
|
||||
sfx.pop();
|
||||
setAnnounce(`힌트: 빛나는 ${tileName(b.cells[b.hint[0]]!)} 두 장을 이을 수 있어요.`);
|
||||
}
|
||||
seenHint.current = h;
|
||||
}, [b?.hint?.[0], b?.hint?.[1]]);
|
||||
|
||||
// The selected tile went away (removed, reshuffled): drop the selection.
|
||||
useEffect(() => {
|
||||
if (sel !== null && b && b.cells[sel] == null) setSel(null);
|
||||
}, [b?.cells, sel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), fxMs(350));
|
||||
return () => clearTimeout(t);
|
||||
}, [flash?.key]);
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(null), fxMs(400));
|
||||
return () => clearTimeout(t);
|
||||
}, [shake?.key]);
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const t = setTimeout(() => setToast(null), fxMs(1200));
|
||||
return () => clearTimeout(t);
|
||||
}, [toast?.key]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="같은 패 두 장을 두 번 이하로 꺾인 선으로 이어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const g = geom(tw, dR, dC);
|
||||
const toDisp = (r: number, c: number): Point => (turn ? [c, rows - 1 - r] : [r, c]);
|
||||
const dispOf = (i: number) => toDisp(Math.floor(i / cols), i % cols);
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (rows - 1 - dc) * cols + dr : dr * cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }): number | null => {
|
||||
const box = boardRef.current!.getBoundingClientRect();
|
||||
const dc = Math.floor((e.clientX - box.left - g.m) / g.tw);
|
||||
const dr = Math.floor((e.clientY - box.top - g.m) / g.th);
|
||||
return dr < 0 || dc < 0 || dr >= dR || dc >= dC ? null : toIndex(dr, dc);
|
||||
};
|
||||
const tilesLeft = b.cells.filter((k) => k !== null).length;
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
const k = b.cells[i];
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${k ? tileName(k) : '빈 칸'}${i === sel ? '(고름)' : ''}`;
|
||||
};
|
||||
|
||||
const tap = (i: number) => {
|
||||
if (!playing) return;
|
||||
setCursor(i);
|
||||
const k = b.cells[i];
|
||||
if (k == null) return;
|
||||
if (sel === null || b.cells[sel] == null) {
|
||||
setSel(i);
|
||||
sfx.select();
|
||||
setAnnounce(`골랐어요: ${describe(i)}. 같은 패를 하나 더 골라요.`);
|
||||
return;
|
||||
}
|
||||
if (sel === i) {
|
||||
setSel(null);
|
||||
sfx.click();
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
return;
|
||||
}
|
||||
const pts = b.cells[sel] === k ? findPath(b.cells, b.rows, b.cols, sel, i) : null;
|
||||
if (!pts) {
|
||||
// Not a pair: shake both, say why, and start again from the tile just picked.
|
||||
const why = b.cells[sel] === k ? TOO_MANY_TURNS : NOT_SAME;
|
||||
setShake({ key: Date.now(), ids: [sel, i] });
|
||||
setToast({ key: Date.now(), text: why, bad: true });
|
||||
setSel(i);
|
||||
tone(220, 120, 'square', 0.05);
|
||||
haptic(30);
|
||||
setAnnounce(`${why}. 새로 고른 패: ${describe(i)}.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'pair', a: sel, b: i });
|
||||
setFlash({ key: Date.now(), pts, a: sel, b: i, kind: k });
|
||||
setSel(null);
|
||||
tone(880, 60, 'triangle', 0.12);
|
||||
tone(1320, 110, 'triangle', 0.1, 60);
|
||||
haptic(12);
|
||||
setAnnounce(`${tileName(k)} 한 쌍을 없앴어요. 남은 패 ${tilesLeft - 2}장.`);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0)) return;
|
||||
setKeyCursor(false);
|
||||
press.current = cellAt(e);
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (p !== null && cellAt(e) === p) tap(p);
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, Point> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
const [dr, dc] = dispOf(cursor);
|
||||
const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
} else if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
if (!e.repeat) tap(cursor);
|
||||
} else if (e.key === 'Escape' && sel !== null) {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
}
|
||||
};
|
||||
|
||||
const hint: number[] = b.hint ?? [];
|
||||
const msVar = { '--ss-ms': `${fxMs(350)}ms` } as CSSProperties;
|
||||
const showHint = !!mine && v.phase === 'playing' && v.options.hints;
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 패 ${tilesLeft}장`}>
|
||||
🀄 <b>{tilesLeft}</b>
|
||||
</span>
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
<div className="rc-wrap" style={{ width: g.w }}>
|
||||
<div
|
||||
ref={boardRef}
|
||||
className="ss-board"
|
||||
data-off={!playing}
|
||||
data-rows={rows}
|
||||
data-cols={cols}
|
||||
style={{ width: g.w, height: g.h, ...msVar }}
|
||||
role="application"
|
||||
aria-roledescription="사천성 판"
|
||||
aria-label={playing ? `사천성 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 패 고르기. 지금 ${describe(cursor)}` : '사천성 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => (press.current = null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={(e) => setKeyCursor(e.currentTarget.matches(':focus-visible'))}
|
||||
onBlur={() => setKeyCursor(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{b.cells.map((k, i) => {
|
||||
if (k == null || (flash && (i === flash.a || i === flash.b))) return null;
|
||||
const [dr, dc] = dispOf(i);
|
||||
const cls = ['ss-cell', i === sel && 'sel', hint.includes(i) && 'hint', keyCursor && playing && i === cursor && 'cur', shake?.ids.includes(i) && 'ss-shake'].filter(Boolean).join(' ');
|
||||
return (
|
||||
<div key={i} className={cls} data-i={i} data-k={k} style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{keyCursor && playing && b.cells[cursor] == null && (
|
||||
<div className="ss-cell cur" style={{ left: g.left(dispOf(cursor)[1]), top: g.top(dispOf(cursor)[0]), width: g.tw, height: g.th }} />
|
||||
)}
|
||||
{flash &&
|
||||
[flash.a, flash.b].map((i) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
return (
|
||||
<div key={`g${flash.key}-${i}`} className="ss-cell ss-gone" style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={flash.kind} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{flash && (
|
||||
<svg key={flash.key} className="ss-line" width={g.w} height={g.h} aria-hidden>
|
||||
<polyline
|
||||
points={flash.pts.map(([r, c]) => toDisp(r, c)).map(([dr, dc]) => `${g.x(dc)},${g.y(dr)}`).join(' ')}
|
||||
fill="none"
|
||||
stroke={LINE}
|
||||
strokeWidth={Math.max(3, tw / 10)}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
{toast && (
|
||||
<div key={toast.key} className={`ss-toast${toast.bad ? ' bad' : ''}`} aria-hidden>
|
||||
{toast.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
{showHint && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!!b.hint} onClick={() => act({ type: 'hint' })}>
|
||||
💡 힌트{b.hints ? ` (${b.hints}번 씀)` : ''}
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">같은 패 두 장을 차례로 클릭 · 고른 패를 다시 누르면 취소 · 키보드: 화살표 + 스페이스, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">같은 패 두 장을 차례로 눌러요 · 고른 패를 다시 누르면 취소</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ShisenSide(props: BoardProps<ShisenView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="사천성" info={`${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 같은 패 두 장을 이어서 없애요', playing: '같은 패 두 장을 두 번 이하로 꺾인 선으로 이으면 없어져요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<ShisenOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>판 크기</strong>
|
||||
<Seg label="판 크기" value={o.size} options={(Object.keys(SIZES) as Size[]).map((s) => [s, SIZES[s].name])} onChange={(size) => onChange({ ...o, size })} />
|
||||
<span className="small muted">{sizeInfo(o.size)}</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '쓰기'],
|
||||
[false, '안 쓰기'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]를 누르면 이을 수 있는 쌍 하나를 보여 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 900, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as ShisenOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: ShisenOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: ShisenOptions }) {
|
||||
const size = options?.size ?? 'normal';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
마작패가 깔린 판에서 <strong>같은 그림의 패 두 장</strong>을 골라 없애요. 패를 모두 없애면 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
<span>두 패를 잇는 선이 빈 칸으로만 지나고 두 번까지만 꺾이면 돼요. 판 바깥 테두리로 돌아가도 돼요.</span>
|
||||
</div>
|
||||
<p>
|
||||
이을 수 있는 쌍이 하나도 없으면 남은 패가 같은 자리에서 저절로 섞여요(언제나 다 풀 수 있게). 판은 처음부터 끝까지 풀 수 있게 만들어져요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못
|
||||
풀면 없앤 쌍이 많은 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 900)}이고, 지금 판은 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 패를 차례로 클릭. 휴대폰: 패를 차례로 눌러요(넓은 판은 세로로 돌려 보여 줘요). 키보드: 화살표로 옮기고 스페이스로 골라요. 힌트를 쓰는 방이면 [💡 힌트]로 한 쌍을 볼 수 있어요.</p>
|
||||
<p className="small muted">{MAHJONG_TILE_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<ShisenView, ShisenOptions> = {
|
||||
Board: ShisenBoard,
|
||||
Side: ShisenSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
60
apps/web/src/games/shisen/quick.tsx
Normal file
60
apps/web/src/games/shisen/quick.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 사천성 30초 규칙 요약 (docs/07 §5). Small boards drawn with the mahjong tiles. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniBoard } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['3p', '', '3p'],
|
||||
['1z', '5s', '2m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '같은 통수 3 두 장이 빈 칸을 지나는 곧은 선으로 이어져 있어요',
|
||||
title: '같은 패 두 장을 이어요',
|
||||
text: '같은 그림의 패 두 장을 차례로 누르면 없어져요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '가운데가 막힌 중 두 장이 판 바깥을 돌아 두 번 꺾인 선으로 이어져 있어요',
|
||||
title: '두 번까지 꺾여도 돼요',
|
||||
text: '빈 칸으로만 지나는 선이 두 번 이하로 꺾이면 이어져요. 판 바깥 테두리로 돌아가도 돼요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['', '5z', ''],
|
||||
['', '', '5z'],
|
||||
]}
|
||||
path={[
|
||||
[0, 1],
|
||||
[1, 1],
|
||||
[1, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '판에 백 두 장만 남아 한 번 꺾인 선으로 이어져 있어요',
|
||||
title: '모두 없애면 승리',
|
||||
text: '패를 모두 없애면 다 푼 거예요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 이을 쌍이 없으면 저절로 섞여요.',
|
||||
},
|
||||
];
|
||||
@@ -6,7 +6,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -137,6 +137,26 @@ function usePlayback(v: SixNimmtView): Playback {
|
||||
return { rows: st.rows, marker: st.marker, step: st, waiting, busy: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scores as of the last still screen: totals, this round's bulls and the round columns change only after the replay
|
||||
* has shown the take that caused them.
|
||||
*/
|
||||
function useShownScores(v: SixNimmtView): (p: string) => { total: number; roundBulls: number; roundScores: number[] } {
|
||||
const now = (p: string) => ({ total: v.players[p]!.total, roundBulls: v.players[p]!.roundBulls, roundScores: v.roundScores[p] ?? [] });
|
||||
const key = v.seats.map((p) => `${p}|${now(p).total}|${now(p).roundBulls}|${now(p).roundScores.join('.')}`).join(',');
|
||||
const shown = useAfterMotionValue(key);
|
||||
const map = new Map(
|
||||
shown
|
||||
.split(',')
|
||||
.filter(Boolean)
|
||||
.map((x) => {
|
||||
const [id, total, roundBulls, rs] = x.split('|') as [string, string, string, string];
|
||||
return [id, { total: Number(total), roundBulls: Number(roundBulls), roundScores: rs ? rs.split('.').map(Number) : [] }];
|
||||
}),
|
||||
);
|
||||
return (p) => map.get(p) ?? now(p);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rows
|
||||
|
||||
function Rows({ v, pb, me, players, act, pending, overlay }: { v: SixNimmtView; pb: Playback; me: string | null; players: Record<string, PublicUser>; act: (a: unknown) => void; pending: boolean; overlay?: ReactNode }) {
|
||||
@@ -223,10 +243,11 @@ function recommendRow(v: SixNimmtView): number {
|
||||
|
||||
function Strip({ v, me, players, active, deadline }: { v: SixNimmtView; me: string | null; players: Record<string, PublicUser>; active: string[]; deadline: number | null }) {
|
||||
const playing = v.phase !== 'finished';
|
||||
const score = useShownScores(v);
|
||||
return (
|
||||
<section className="sx-strip" aria-label="참가자">
|
||||
{v.seats.map((p) => {
|
||||
const pv = v.players[p]!;
|
||||
const pv = { ...v.players[p]!, ...score(p) };
|
||||
const on = playing && active.includes(p);
|
||||
const state = pv.left ? '나감' : pv.away ? '자리 비움' : v.phase === 'select' ? (pv.picked ? '골랐어요' : '고르는 중') : v.phase === 'choose' && v.pending?.player === p ? '줄 고르는 중' : v.phase === 'draft' && v.draft?.at === p ? '카드 가져가는 중' : '';
|
||||
return (
|
||||
@@ -286,7 +307,7 @@ function previewText(p: Preview | undefined): string {
|
||||
return `${p.row + 1}번 줄 ${p.side === 'L' ? '왼쪽' : `${p.pos}번째`}${'tie' in p && p.tie ? '(고름)' : ''}`;
|
||||
}
|
||||
|
||||
function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean }) {
|
||||
function Hand({ v, act, pending, replaying }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean; replaying: boolean }) {
|
||||
const my = v.my!;
|
||||
const [pick, setPick] = useState<Card | null>(null);
|
||||
const [flip, setFlip] = useState(false);
|
||||
@@ -324,7 +345,8 @@ function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void;
|
||||
<div className="sx-hand" role="group" aria-label="손패">
|
||||
{my.hand.map((h) => {
|
||||
const up = chosen === h.n;
|
||||
const pv = flip && h.flipped ? h.flipped.preview : h.preview;
|
||||
// The previews use the rows after the turn still being replayed: they show once it has played.
|
||||
const pv = replaying ? undefined : flip && h.flipped ? h.flipped.preview : h.preview;
|
||||
return (
|
||||
<button
|
||||
key={h.n}
|
||||
@@ -471,14 +493,18 @@ function FinalTable({ v, me, players }: { v: SixNimmtView; me: string | null; pl
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function Board({ view: v, me, players, act, pending, active, deadline }: BoardProps<SixNimmtView>) {
|
||||
const pb = usePlayback(v);
|
||||
const replay = usePlayback(v);
|
||||
// The replay steps are timers: results wait for it, then for the last card to finish landing.
|
||||
useMotionHold(replay.busy);
|
||||
const still = useMotionSettled(!replay.busy);
|
||||
const pb: Playback = { ...replay, busy: !still };
|
||||
const [roundShown, setRoundShown] = useState<number>(v.lastRound?.round ?? 0);
|
||||
const [roundOpen, setRoundOpen] = useState(false);
|
||||
const prevTurn = useRef(v.turnSeq);
|
||||
const prevPicked = useRef(0);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
|
||||
// Round result window: once the replay of the last turn is done, for 5 seconds (closable).
|
||||
// Round result window: once the replay of the last turn is done and the screen is still, for 5 seconds (closable).
|
||||
useEffect(() => {
|
||||
if (!v.lastRound || v.lastRound.round === roundShown || pb.busy) return;
|
||||
setRoundShown(v.lastRound.round);
|
||||
@@ -517,11 +543,12 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
|
||||
const seated = !!me && v.seats.includes(me) && !v.players[me]!.left;
|
||||
const pd = v.pending;
|
||||
const head = useAfterMotionValue(v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? `${v.round}라운드 · 카드 골라 가기` : `${v.round}라운드 · ${v.turn}/10번째 카드`);
|
||||
return (
|
||||
<div className="sx-wrap">
|
||||
<style>{CSS}</style>
|
||||
<div className="card sx-head">
|
||||
<strong>{v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? `${v.round}라운드 · 카드 골라 가기` : `${v.round}라운드 · ${v.turn}/10번째 카드`}</strong>
|
||||
<strong>{head}</strong>
|
||||
<span className="small muted">
|
||||
{v.options.endMode === 'score' ? `${v.options.endScore}점이 넘으면 끝` : `${v.options.rounds}라운드까지`}
|
||||
{v.options.fanCard !== 'none' ? ` · ${FAN_KO[v.options.fanCard]}` : ''}
|
||||
@@ -529,8 +556,8 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
</span>
|
||||
</div>
|
||||
<Strip v={v} me={me} players={players} active={active} deadline={deadline} />
|
||||
{v.result && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft ? (
|
||||
{v.result && !pb.busy && <FinalTable v={v} me={me} players={players} />}
|
||||
{v.phase === 'draft' && v.draft && !pb.busy ? (
|
||||
<Draft v={v} me={me} players={players} act={act} pending={pending} />
|
||||
) : (
|
||||
<>
|
||||
@@ -545,7 +572,7 @@ function Board({ view: v, me, players, act, pending, active, deadline }: BoardPr
|
||||
</div>
|
||||
)}
|
||||
<Rows v={v} pb={pb} me={me} players={players} act={act} pending={pending} overlay={roundOpen && v.lastRound && !(v.phase === 'choose' && pd?.player === me) ? <RoundResult v={v} me={me} players={players} onClose={() => setRoundOpen(false)} /> : null} />
|
||||
{seated && v.my && v.phase !== 'finished' && <Hand v={v} act={act} pending={pending} />}
|
||||
{seated && v.my && v.phase !== 'finished' && <Hand v={v} act={act} pending={pending} replaying={pb.busy} />}
|
||||
</>
|
||||
)}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
@@ -606,7 +633,11 @@ function Tracker({ v, me, players }: { v: SixNimmtView; me: string | null; playe
|
||||
|
||||
function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
const rounds = Math.max(0, ...v.seats.map((p) => v.roundScores[p]!.length));
|
||||
const score = useShownScores(v);
|
||||
// Takes join the log once the board has replayed them.
|
||||
const shownLog = useAfterMotionValue(v.log.at(-1)?.n ?? 0);
|
||||
const log = v.log.filter((e) => e.n <= shownLog);
|
||||
const rounds = Math.max(0, ...v.seats.map((p) => score(p).roundScores.length));
|
||||
const playing = v.phase !== 'finished';
|
||||
return (
|
||||
<>
|
||||
@@ -629,11 +660,11 @@ function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
<tr key={p}>
|
||||
<td className="sx-td-name">{who(players, me, p)}</td>
|
||||
{Array.from({ length: rounds }, (_, i) => (
|
||||
<td key={i}>{v.roundScores[p]![i] ?? ''}</td>
|
||||
<td key={i}>{score(p).roundScores[i] ?? ''}</td>
|
||||
))}
|
||||
{playing && <td>{v.players[p]!.roundBulls ? `+${v.players[p]!.roundBulls}` : ''}</td>}
|
||||
{playing && <td>{score(p).roundBulls ? `+${score(p).roundBulls}` : ''}</td>}
|
||||
<td>
|
||||
<b>{v.players[p]!.total}</b>
|
||||
<b>{score(p).total}</b>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -642,11 +673,11 @@ function Side({ view: v, me, players, act }: BoardProps<SixNimmtView>) {
|
||||
</div>
|
||||
</section>
|
||||
<Tracker v={v} me={me} players={players} />
|
||||
{v.log.length > 0 && (
|
||||
{log.length > 0 && (
|
||||
<section className="card sx-logbox" aria-label="기록">
|
||||
<h3>기록</h3>
|
||||
<ul className="sx-log" tabIndex={0} aria-label="기록 (최신이 위)">
|
||||
{[...v.log]
|
||||
{[...log]
|
||||
.reverse()
|
||||
.slice(0, 30)
|
||||
.map((e) => (
|
||||
|
||||
29
apps/web/src/games/solitaire/help.ts
Normal file
29
apps/web/src/games/solitaire/help.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/** 솔리테어 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { Mode, SolitaireView } from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW: Record<Mode, string[]> = {
|
||||
klondike: [
|
||||
'클론다이크: 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 줄에는 K만 놓아요. 카드를 옮기면 아래 뒤집힌 카드가 열려요.',
|
||||
'더미를 누르면 카드를 넘겨요. 더미가 비면 버린 카드를 다시 뒤집어 써요. A부터 무늬별로 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
freecell: [
|
||||
'프리셀: 모든 카드가 앞면이에요. 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 칸 4개에는 카드를 한 장씩 잠깐 둘 수 있어요.',
|
||||
'여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요. 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
spider: [
|
||||
'스파이더: 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요.',
|
||||
'K부터 A까지 같은 무늬 한 줄이 되면 저절로 빠져요. 8줄을 모두 빼면 다 푼 거예요. 더미를 누르면 열 줄에 한 장씩 나눠요(빈 줄이 있으면 못 나눠요).',
|
||||
],
|
||||
};
|
||||
const COMMON = ['카드를 눌러 고르고 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [되돌리기]로 한 수씩 되돌릴 수 있어요(횟수가 결과에 적혀요).'];
|
||||
|
||||
export function helpNow(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, [...HOW[v.options.mode], ...COMMON], '실패했어요.');
|
||||
const b = v.board;
|
||||
if (!b || v.phase !== 'playing') return lines;
|
||||
if (b.mode === 'spider') return `${lines}\n더미에서 ${b.stock / 10}번 더 나눌 수 있어요.`;
|
||||
if (b.mode === 'klondike') return `${lines}\n더미에 ${b.stock}장, 버린 카드 ${b.waste.length}장이 있어요.`;
|
||||
return `${lines}\n빈 칸 ${b.cells.filter((c) => !c).length}개가 비어 있어요.`;
|
||||
}
|
||||
510
apps/web/src/games/solitaire/index.tsx
Normal file
510
apps/web/src/games/solitaire/index.tsx
Normal file
@@ -0,0 +1,510 @@
|
||||
/** 솔리테어 화면 (docs/games/solitaire.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import {
|
||||
MODE_NAME,
|
||||
TIME_CHOICES,
|
||||
canAuto,
|
||||
freecellCapacity,
|
||||
isRun,
|
||||
moveProblem,
|
||||
rankOf,
|
||||
type Mode,
|
||||
type SolitaireBoardView,
|
||||
type SolitaireMove,
|
||||
type SolitaireOptions,
|
||||
type SolitaireView,
|
||||
} from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT, PlayingCard, cardAria } from '../../components/cards/PlayingCard';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const FAIL = '실패했어요.';
|
||||
const DOUBLE_TAP_MS = 380;
|
||||
|
||||
const CSS = `
|
||||
.sl-felt { width: 100%; border-radius: 14px; background: var(--felt); box-shadow: inset 0 0 40px rgba(0,0,0,.25), var(--shadow); color: #fff;
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; }
|
||||
.sl-row { display: grid; justify-content: center; align-items: start; }
|
||||
.sl-pile { position: relative; }
|
||||
.sl-slot { display: flex; align-items: center; justify-content: center; border-radius: 8%/6%; border: 2px dashed rgba(255,255,255,.45); background: rgba(0,0,0,.12);
|
||||
color: rgba(255,255,255,.7); font-weight: 900; padding: 0; cursor: pointer; font-family: inherit; }
|
||||
.sl-slot[data-hint='true'] { border-color: #fbbf24; border-style: solid; background: rgba(251,191,36,.18); }
|
||||
.sl-slot:disabled { cursor: default; }
|
||||
.sl-card { position: absolute; left: 0; padding: 0; border: 0; background: none; cursor: pointer; display: block; border-radius: 9%/6%; }
|
||||
.sl-card:disabled, span.sl-card { cursor: default; }
|
||||
.sl-card:focus-visible, .sl-slot:focus-visible, .sl-stock:focus-visible { outline: 3px solid #fbbf24; outline-offset: 2px; z-index: 50; }
|
||||
.sl-stock { position: relative; padding: 0; border: 0; background: none; cursor: pointer; display: block; }
|
||||
.sl-stock:disabled { cursor: default; }
|
||||
.sl-badge { position: absolute; right: -4px; bottom: -6px; min-width: 22px; padding: 1px 5px; border-radius: 999px; background: #111827; color: #fff; font-size: .72rem;
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; box-shadow: 0 1px 3px rgba(0,0,0,.4); pointer-events: none; }
|
||||
.sl-in { animation: sl-in .26s ease-out both; }
|
||||
.sl-shake { animation: sl-shake .3s ease-in-out; }
|
||||
@keyframes sl-in { from { transform: translateY(-14px) scale(1.06); opacity: .5; } }
|
||||
@keyframes sl-shake { 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } }
|
||||
@media (prefers-reduced-motion: reduce) { .sl-in, .sl-shake { animation: none; } }
|
||||
`;
|
||||
|
||||
interface Sel {
|
||||
from: string;
|
||||
n: number;
|
||||
}
|
||||
|
||||
const colsOf = (mode: Mode) => (mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10);
|
||||
const fTotal = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0);
|
||||
const pileName = (id: string) =>
|
||||
id === 'w' ? '버린 카드' : id === 'f' ? '파운데이션' : id[0] === 't' ? `${Number(id.slice(1)) + 1}번째 줄` : id[0] === 'c' ? `빈 칸 ${Number(id.slice(1)) + 1}` : `파운데이션 ${Number(id.slice(1)) + 1}`;
|
||||
|
||||
/** Every visible card on its pile ("t3:4" → "KS"), to spot cards that just arrived. */
|
||||
function cardSpots(b: SolitaireBoardView): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
b.t.forEach((c, i) => c.forEach((x, k) => out.set(`t${i}:${k}`, x ?? '')));
|
||||
b.waste.forEach((x, k) => out.set(`w:${k}`, x));
|
||||
b.cells.forEach((x, i) => x && out.set(`c${i}:0`, x));
|
||||
b.f.forEach((x, i) => x && out.set(`f${i}:0`, x));
|
||||
return out;
|
||||
}
|
||||
|
||||
function SolBoard({ view: v, me, players, act }: BoardProps<SolitaireView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [fresh, setFresh] = useState<Set<string>>(new Set());
|
||||
const [shake, setShake] = useState(0);
|
||||
const [box, setBox] = useState({ w: 0, h: 800 });
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const lastTap = useRef<{ key: string; at: number } | null>(null);
|
||||
const prev = useRef<SolitaireBoardView | null>(null);
|
||||
const bKey = b ? JSON.stringify(b) : '';
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = wrapRef.current;
|
||||
if (!el) return;
|
||||
const update = () => {
|
||||
const playH = parseFloat(getComputedStyle(el).getPropertyValue('--play-h'));
|
||||
setBox({ w: el.clientWidth, h: Number.isFinite(playH) && playH > 0 ? playH : window.innerHeight });
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [!!b]);
|
||||
|
||||
// Cards that just arrived slide in; sounds for what changed. Any change ends the current selection.
|
||||
useEffect(() => {
|
||||
const was = prev.current;
|
||||
prev.current = b;
|
||||
setSel(null);
|
||||
if (!b || !was) return;
|
||||
const before = cardSpots(was);
|
||||
const added = new Set<string>();
|
||||
for (const [k, c] of cardSpots(b)) if (c && before.get(k) !== c) added.add(k);
|
||||
const up = fTotal(b.f) - fTotal(was.f);
|
||||
if (b.done.length > was.done.length) {
|
||||
sfx.good();
|
||||
haptic([20, 30, 20]);
|
||||
setAnnounce(`K부터 A까지 한 줄을 완성해서 뺐어요. 완성 ${b.done.length}/8줄`);
|
||||
} else if (up > 0) {
|
||||
[1046, 1318].forEach((f, i) => tone(f, 70, 'triangle', 0.1, i * 60));
|
||||
setAnnounce(`파운데이션에 올렸어요. 올린 카드 ${fTotal(b.f)}/52`);
|
||||
} else if (b.stock < was.stock && b.mode === 'spider') sfx.deal(10, 35);
|
||||
else if (b.stock !== was.stock || b.waste.length !== was.waste.length) sfx.cardFlip();
|
||||
else if (added.size) sfx.cardPlay();
|
||||
if (b.undos > was.undos) setAnnounce('한 수 되돌렸어요.');
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(300));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [bKey]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text={`${MODE_NAME[v.options.mode]} · 모두 같은 패예요!`} />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Card size: the columns fill the width (phones: 7–8 columns ≈ 47 px, 10 columns ≈ 34 px).
|
||||
const N = colsOf(b.mode);
|
||||
const gap = phone ? (N >= 10 ? 2 : 4) : N >= 10 ? 8 : 12;
|
||||
const pad = phone ? 4 : 14;
|
||||
const w = Math.max(24, Math.min(N >= 10 ? 78 : 96, Math.floor((box.w - 2 * pad - gap * (N - 1)) / N)));
|
||||
const h = Math.round(w * 1.4);
|
||||
const colMax = phone ? Infinity : Math.max(h * 3, box.h - h - 230);
|
||||
const offsets = (col: (string | null)[]) => {
|
||||
const downs = col.filter((x) => x === null).length;
|
||||
const ups = col.length - downs;
|
||||
let dOff = Math.round(h * 0.11);
|
||||
let uOff = Math.round(h * (phone ? 0.3 : 0.38));
|
||||
if (h + downs * dOff + Math.max(0, ups - 1) * uOff > colMax) {
|
||||
dOff = Math.max(3, Math.round(h * 0.05));
|
||||
uOff = Math.max(Math.round(h * 0.24), Math.floor((colMax - h - downs * dOff) / Math.max(1, ups - 1)));
|
||||
}
|
||||
let y = 0;
|
||||
return col.map((x) => {
|
||||
const top = y;
|
||||
y += x === null ? dOff : uOff;
|
||||
return top;
|
||||
});
|
||||
};
|
||||
const grid: CSSProperties = { gridTemplateColumns: `repeat(${N}, ${w}px)`, gap, padding: `${pad}px ${pad}px 0` };
|
||||
|
||||
const tops = (pile: string): number => {
|
||||
if (pile === 'w') return b.waste.length - 1;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]!.length - 1;
|
||||
return 0;
|
||||
};
|
||||
const cardAt = (pile: string, i: number): string | null => {
|
||||
if (pile === 'w') return b.waste[i] ?? null;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]![i] ?? null;
|
||||
if (pile[0] === 'c') return b.cells[Number(pile.slice(1))] || null;
|
||||
return b.f[Number(pile.slice(1))] || null;
|
||||
};
|
||||
const nope = (why: string) => {
|
||||
setAnnounce(why);
|
||||
setShake((x) => x + 1);
|
||||
tone(220, 110, 'sine', 0.07);
|
||||
haptic(15);
|
||||
};
|
||||
const send = (m: SolitaireMove) => {
|
||||
const why = moveProblem(b, m);
|
||||
if (why) return nope(why);
|
||||
act(m);
|
||||
};
|
||||
const dropOn = (pile: string) => {
|
||||
if (!sel) return;
|
||||
setSel(null);
|
||||
const m: SolitaireMove = { type: 'move', from: sel.from, n: sel.n, to: pile };
|
||||
// A foundation tap means "up there": use the slot that fits when the tapped one does not.
|
||||
if (pile[0] === 'f' && moveProblem(b, m)) m.to = 'f';
|
||||
send(m);
|
||||
};
|
||||
const toFoundation = (pile: string) => {
|
||||
const m: SolitaireMove = { type: 'move', from: pile, n: 1, to: 'f' };
|
||||
setSel(null);
|
||||
send(m);
|
||||
};
|
||||
|
||||
const tapCard = (pile: string, i: number) => {
|
||||
if (!playing) return;
|
||||
const t = performance.now();
|
||||
const key = `${pile}:${i}`;
|
||||
const dbl = lastTap.current?.key === key && t - lastTap.current.at < DOUBLE_TAP_MS;
|
||||
lastTap.current = dbl ? null : { key, at: t };
|
||||
const card = cardAt(pile, i);
|
||||
if (dbl && pile[0] !== 'f' && i === tops(pile) && !moveProblem(b, { type: 'move', from: pile, n: 1, to: 'f' })) return toFoundation(pile);
|
||||
if (sel && sel.from !== pile && pile !== 'w') return dropOn(pile);
|
||||
if (!card) return;
|
||||
const n = pile[0] === 't' ? b.t[Number(pile.slice(1))]!.length - i : 1;
|
||||
if (sel && sel.n === n) {
|
||||
setSel(null);
|
||||
setAnnounce('고른 카드를 내려놓았어요.');
|
||||
return;
|
||||
}
|
||||
if (pile[0] === 'f' && b.mode !== 'klondike') return nope('올린 카드는 내릴 수 없어요.');
|
||||
if (pile[0] === 't' && !isRun(b.mode, b.t[Number(pile.slice(1))]!.slice(i)))
|
||||
return nope(b.mode === 'spider' ? '같은 무늬로 이어진 카드만 함께 옮길 수 있어요.' : '색이 번갈아 하나씩 작아지게 이어진 카드만 함께 옮길 수 있어요.');
|
||||
setSel({ from: pile, n });
|
||||
sfx.select();
|
||||
setAnnounce(`${cardAria(card)}${n > 1 ? `부터 ${n}장` : ''}을 골랐어요. 놓을 곳을 눌러요.`);
|
||||
};
|
||||
const onCardKey = (pile: string, i: number) => (e: ReactKeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 그만뒀어요.');
|
||||
} else if ((e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') && i === tops(pile) && pile[0] !== 'f') {
|
||||
e.preventDefault();
|
||||
if (playing) toFoundation(pile);
|
||||
}
|
||||
};
|
||||
const tapStock = () => {
|
||||
if (!playing) return;
|
||||
setSel(null);
|
||||
send(b.mode === 'spider' ? { type: 'deal' } : { type: 'draw' });
|
||||
};
|
||||
|
||||
/** Piles the selected cards may go to (a soft glow helps beginners). */
|
||||
const fits = (to: string) => !!sel && sel.from !== to && moveProblem(b, { type: 'move', from: sel.from, n: sel.n, to }) === null;
|
||||
const isSel = (pile: string, i: number) => !!sel && sel.from === pile && i >= tops(pile) - sel.n + 1;
|
||||
|
||||
const cardButton = (pile: string, i: number, card: string, style: CSSProperties, label: string) => (
|
||||
<button
|
||||
key={`${pile}-${i}`}
|
||||
type="button"
|
||||
className={`sl-card${fresh.has(`${pile}:${i}`) ? ' sl-in' : ''}`}
|
||||
style={{ ...style, zIndex: i + 1 }}
|
||||
data-card={card}
|
||||
aria-label={label}
|
||||
aria-pressed={isSel(pile, i)}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
onClick={() => tapCard(pile, i)}
|
||||
onKeyDown={onCardKey(pile, i)}
|
||||
>
|
||||
<PlayingCard card={card} width={w} selected={isSel(pile, i)} highlight={i === tops(pile) && fits(pile)} />
|
||||
</button>
|
||||
);
|
||||
const slot = (pile: string, text: string, label: string, onClick?: () => void) => (
|
||||
<button
|
||||
key={`${pile}-slot`}
|
||||
type="button"
|
||||
className="sl-slot"
|
||||
style={{ width: w, height: h, fontSize: Math.max(11, w * 0.32) }}
|
||||
data-hint={fits(pile)}
|
||||
aria-label={label}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
disabled={!playing}
|
||||
onClick={onClick ?? (() => dropOn(pile))}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Top row: stock / waste / foundations (Klondike), free cells / foundations (FreeCell), stock / completed runs (Spider).
|
||||
const stockLeft = b.mode === 'spider' ? b.stock / 10 : b.stock;
|
||||
const stock = (
|
||||
<div className="sl-pile" data-pile="s" data-count={b.stock} style={{ gridColumn: 1 }}>
|
||||
{b.stock > 0 || b.mode === 'spider' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="sl-stock"
|
||||
disabled={!playing || b.stock === 0}
|
||||
onClick={tapStock}
|
||||
aria-label={b.mode === 'spider' ? (b.stock ? `카드 나누기, ${stockLeft}번 남음` : '나눌 카드가 없어요') : `더미에서 카드 넘기기, ${b.stock}장 남음`}
|
||||
style={{ width: w, height: h }}
|
||||
>
|
||||
{b.stock > 0 ? (
|
||||
Array.from({ length: Math.min(b.mode === 'spider' ? stockLeft : 3, 5) }, (_, k) => (
|
||||
<span key={k} style={{ position: 'absolute', left: k * Math.max(2, w * 0.06), top: 0 }}>
|
||||
<PlayingCard card={null} width={w} />
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />
|
||||
)}
|
||||
{b.stock > 0 && <span className="sl-badge">{b.mode === 'spider' ? `${stockLeft}번` : b.stock}</span>}
|
||||
</button>
|
||||
) : (
|
||||
slot('s', b.waste.length ? '↻' : '', b.waste.length ? '버린 카드를 다시 더미로 뒤집기' : '더미가 비었어요', tapStock)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
const fan = b.draw === 3 ? Math.round(w * 0.32) : 0;
|
||||
const shownWaste = b.waste.slice(-(b.draw === 3 ? 3 : 2));
|
||||
const waste = (
|
||||
<div className="sl-pile" data-pile="w" style={{ gridColumn: 2, width: w, height: h }}>
|
||||
{!b.waste.length && <span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />}
|
||||
{shownWaste.map((c, k) => {
|
||||
const i = b.waste.length - shownWaste.length + k;
|
||||
const x = b.draw === 3 ? k * fan : 0;
|
||||
return i === b.waste.length - 1 ? (
|
||||
cardButton('w', i, c, { left: x, top: 0 }, `버린 카드 맨 위 ${cardAria(c)}. 두 번 누르면 파운데이션으로`)
|
||||
) : (
|
||||
<span key={`w-${i}`} className="sl-card" style={{ left: x, top: 0, zIndex: k }} aria-hidden>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
const foundations = b.f.map((c, i) => (
|
||||
<div key={`f${i}`} className="sl-pile" data-pile={`f${i}`} data-top={c} style={{ gridColumn: N - 3 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`f${i}`, 0, c, { top: 0 }, `파운데이션 ${i + 1}, 맨 위 ${cardAria(c)}`) : slot(`f${i}`, 'A', `파운데이션 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const cells = b.cells.map((c, i) => (
|
||||
<div key={`c${i}`} className="sl-pile" data-pile={`c${i}`} style={{ gridColumn: 1 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`c${i}`, 0, c, { top: 0 }, `빈 칸 ${i + 1}의 ${cardAria(c)}`) : slot(`c${i}`, '', `빈 칸 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const done = Array.from({ length: 8 }, (_, i) => (
|
||||
<div key={`d${i}`} className="sl-pile" style={{ gridColumn: 3 + i, width: w, height: h }} aria-hidden>
|
||||
{b.done[i] ? <span className="sl-done-card"><PlayingCard card={`K${b.done[i]}`} width={w} /></span> : <span className="sl-slot" style={{ width: w, height: h, cursor: 'default', opacity: 0.6 }} />}
|
||||
</div>
|
||||
));
|
||||
|
||||
const columns = b.t.map((col, i) => {
|
||||
const pile = `t${i}`;
|
||||
const ys = offsets(col);
|
||||
const height = (ys.at(-1) ?? 0) + h;
|
||||
return (
|
||||
<div key={pile} className="sl-pile" data-pile={pile} role="group" aria-label={`${i + 1}번째 줄, ${col.length}장`} style={{ width: w, height: height + Math.round(w * 0.25) }}>
|
||||
{!col.length && slot(pile, b.mode === 'klondike' ? 'K' : '', `${i + 1}번째 줄, 비었어요${b.mode === 'klondike' ? '. K만 놓을 수 있어요' : ''}`)}
|
||||
{col.map((c, k) =>
|
||||
c === null ? (
|
||||
<span key={`${pile}-${k}`} className="sl-card" style={{ top: ys[k], zIndex: k + 1 }} data-card="">
|
||||
<PlayingCard card={null} width={w} title="뒤집힌 카드" />
|
||||
</span>
|
||||
) : (
|
||||
cardButton(pile, k, c, { top: ys[k] }, `${i + 1}번째 줄 ${k + 1}번째 ${cardAria(c)}${k === col.length - 1 ? ', 맨 위' : ''}`)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const autoOk = b.mode !== 'spider' && canAuto(b);
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill">{MODE_NAME[b.mode]}</span>
|
||||
<span className="rc-pill" aria-label={b.mode === 'spider' ? `완성 ${b.done.length}/8줄` : `올린 카드 ${fTotal(b.f)}/52`}>
|
||||
{b.mode === 'spider' ? '🂮' : '🂡'} <b>{b.mode === 'spider' ? `${b.done.length}/8` : `${fTotal(b.f)}/52`}</b>
|
||||
</span>
|
||||
{b.mode === 'freecell' && (
|
||||
<span className="rc-pill" aria-label={`한 번에 ${freecellCapacity(b, false)}장까지 옮길 수 있어요`}>
|
||||
⇅ <b>{freecellCapacity(b, false)}장</b>
|
||||
</span>
|
||||
)}
|
||||
{b.undos > 0 && <span className="rc-pill" aria-label={`되돌리기 ${b.undos}번`}>↶ {b.undos}</span>}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={{ width: '100%' }} ref={wrapRef}>
|
||||
<div key={shake} className={`sl-felt${shake ? ' sl-shake' : ''}`} data-mode={b.mode} style={{ paddingBottom: pad }}>
|
||||
<div className="sl-row" style={grid} role="group" aria-label={b.mode === 'freecell' ? '빈 칸과 파운데이션' : b.mode === 'spider' ? '더미와 완성한 줄' : '더미, 버린 카드, 파운데이션'}>
|
||||
{b.mode === 'klondike' && [stock, waste, ...foundations]}
|
||||
{b.mode === 'freecell' && [...cells, ...foundations]}
|
||||
{b.mode === 'spider' && [stock, ...done]}
|
||||
</div>
|
||||
<div className="sl-row" style={{ ...grid, paddingTop: Math.max(8, Math.round(h * 0.18)) }}>
|
||||
{columns}
|
||||
</div>
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<button type="button" className="btn btn-secondary" disabled={!b.canUndo} onClick={() => send({ type: 'undo' })}>
|
||||
↶ 되돌리기
|
||||
</button>
|
||||
{b.mode !== 'spider' && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!autoOk} onClick={() => send({ type: 'auto' })}>
|
||||
자동 정리
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로 · 키보드: Tab으로 옮기고 Enter로 고르기·놓기, F 파운데이션, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const modeInfo = (o: SolitaireOptions) =>
|
||||
o.mode === 'klondike' ? `클론다이크 · ${o.draw}장씩 넘기기` : o.mode === 'spider' ? `스파이더 · 무늬 ${o.suits}가지` : '프리셀 · 빈 칸 4개';
|
||||
|
||||
function SolSide(props: BoardProps<SolitaireView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="솔리테어" info={modeInfo(props.view.options)} />;
|
||||
}
|
||||
|
||||
const PLAYING_LINE: Record<Mode, string> = {
|
||||
klondike: '색을 번갈아 하나씩 작게 쌓고, A부터 무늬별로 파운데이션에 올려요',
|
||||
freecell: '빈 칸 4개를 잘 써서 모든 카드를 A부터 무늬별로 올려요',
|
||||
spider: '하나 작은 수 위에 쌓아 K부터 A까지 같은 무늬 한 줄을 만들어요',
|
||||
};
|
||||
|
||||
function statusText(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: `곧 시작해요! ${MODE_NAME[v.options.mode]} · 모두 같은 패예요`, playing: PLAYING_LINE[v.options.mode], failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SolitaireOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>종류</strong>
|
||||
<Seg label="종류" value={o.mode} options={(Object.keys(MODE_NAME) as Mode[]).map((m) => [m, MODE_NAME[m]])} onChange={(mode) => onChange({ ...o, mode })} />
|
||||
<span className="small muted">
|
||||
{o.mode === 'klondike'
|
||||
? '일곱 줄, 더미에서 카드를 넘겨 가며 풀어요.'
|
||||
: o.mode === 'freecell'
|
||||
? '모든 카드가 앞면으로 여덟 줄. 빈 칸 4개를 잠깐 쓸 수 있어요.'
|
||||
: '카드 두 벌로 열 줄. K부터 A까지 같은 무늬 한 줄을 만들면 빠져요.'}
|
||||
</span>
|
||||
</div>
|
||||
{o.mode === 'klondike' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>한 번에 넘기는 카드</strong>
|
||||
<Seg label="한 번에 넘기는 카드" value={o.draw} options={[[1, '1장(쉬움)'], [3, '3장(어려움)']]} onChange={(draw) => onChange({ ...o, draw })} />
|
||||
</div>
|
||||
)}
|
||||
{o.mode === 'spider' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>무늬 수</strong>
|
||||
<Seg label="무늬 수" value={o.suits} options={[[1, '1가지(쉬움)'], [2, '2가지(보통)'], [4, '4가지(어려움)']]} onChange={(suits) => onChange({ ...o, suits })} />
|
||||
</div>
|
||||
)}
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[...TIME_CHOICES]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SolitaireOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SolitaireOptions): string {
|
||||
return `${modeInfo(o)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SolitaireOptions }) {
|
||||
const o = options ?? { mode: 'klondike', draw: 1, suits: 1, timeLimitSec: 900 };
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
윈도우에 있던 그 카드놀이예요. 모두 <strong>똑같은 패</strong>를 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. 지금은 {modeInfo(o)}, 제한 시간 {limitLabel(o.timeLimitSec)}이에요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<PlayingCard card="8S" width={40} />
|
||||
<PlayingCard card="7H" width={40} style={{ marginLeft: -22, marginTop: 14 }} />
|
||||
<PlayingCard card="6C" width={40} style={{ marginLeft: -22, marginTop: 28 }} />
|
||||
<span style={{ marginLeft: 8 }}>줄에는 색을 번갈아 하나씩 작은 수를 쌓아요(스파이더는 색 상관없이).</span>
|
||||
</div>
|
||||
<p>
|
||||
<strong>클론다이크</strong>: 일곱 줄 가운데 맨 위만 앞면이에요. 아래 카드를 옮기면 뒤집힌 카드가 저절로 열려요. 빈 줄에는 K만 놓을 수 있어요. 더미를 누르면 카드를 1장(또는 3장)씩 넘기고,
|
||||
더미가 비면 버린 카드를 다시 뒤집어 써요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>프리셀</strong>: 모든 카드가 앞면이에요. 빈 칸 4개에 카드를 한 장씩 잠깐 둘 수 있고, 빈 줄에는 아무 카드나 놓아요. 여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>스파이더</strong>: 카드 두 벌로 열 줄이에요. 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요. K부터 A까지 같은 무늬 한 줄이 되면 저절로
|
||||
빠져요. 더미를 누르면 열 줄에 한 장씩 나눠 주는데, 빈 줄이 있으면 나눌 수 없어요.
|
||||
</p>
|
||||
<p>
|
||||
카드를 눌러 고르고(위에 얹힌 카드까지 함께) 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [자동 정리]는 올릴 수 있는 카드를 모두 올려요. [되돌리기]는 몇 번이든 쓸 수 있지만 결과에 횟수가
|
||||
적혀요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 올린(스파이더는 많이 완성한) 사람이 이겨요. 클론다이크는 가끔 풀 수 없는 패도 나와요.
|
||||
</p>
|
||||
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SolitaireView, SolitaireOptions> = {
|
||||
Board: SolBoard,
|
||||
Side: SolSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
63
apps/web/src/games/solitaire/quick.tsx
Normal file
63
apps/web/src/games/solitaire/quick.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
/** 솔리테어 30초 규칙 요약 (docs/07 §5). Small tables drawn with the real playing cards. */
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** A fanned column: face-down cards (null) then face-up ones. */
|
||||
function Fan({ cards, w = 34 }: { cards: (string | null)[]; w?: number }) {
|
||||
const h = Math.round(w * 1.4);
|
||||
let y = 0;
|
||||
const ys = cards.map((c) => {
|
||||
const top = y;
|
||||
y += c === null ? h * 0.12 : h * 0.3;
|
||||
return top;
|
||||
});
|
||||
return (
|
||||
<span style={{ position: 'relative', display: 'inline-block', width: w, height: (ys.at(-1) ?? 0) + h }}>
|
||||
{cards.map((c, i) => (
|
||||
<span key={i} style={{ position: 'absolute', left: 0, top: ys[i] }}>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const row = { display: 'inline-flex', gap: 6, alignItems: 'flex-start' } as const;
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, null, 'KS', 'QH', 'JC']} />
|
||||
<Fan cards={[null, '8D', '7S', '6H']} />
|
||||
</span>
|
||||
),
|
||||
alt: '두 줄에 카드가 색을 번갈아 하나씩 작은 수로 쌓여 있어요',
|
||||
title: '색을 번갈아 내려 쌓기',
|
||||
text: '줄에는 색을 번갈아 하나씩 작은 수를 쌓아요. 모두 똑같은 패를 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<PlayingCard card="AH" width={34} />
|
||||
<PlayingCard card="2H" width={34} />
|
||||
<PlayingCard card="3H" width={34} />
|
||||
</span>
|
||||
),
|
||||
alt: '하트 A, 2, 3이 차례로 놓여 있어요',
|
||||
title: 'A부터 무늬별로 올리기',
|
||||
text: '파운데이션에 A부터 같은 무늬로 차례대로 올려요. 두 번 누르면 바로 올라가요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, 'KS', 'QS', 'JS', 'TS']} w={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
</span>
|
||||
),
|
||||
alt: '스페이드가 K부터 차례로 이어진 줄과 완성한 줄이에요',
|
||||
title: '세 가지 솔리테어',
|
||||
text: '클론다이크·프리셀은 52장을 다 올리면, 스파이더는 K→A 같은 무늬 8줄을 빼면 다 풀어요.',
|
||||
},
|
||||
];
|
||||
@@ -22,7 +22,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntr
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// Type-only imports above keep the rules module out of the bundle; the few constants live here.
|
||||
const COLORS: Color[] = ['W', 'U', 'G', 'R', 'K'];
|
||||
@@ -54,6 +54,18 @@ const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.n
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 });
|
||||
const sum = (t: Partial<Record<TokenColor, number>>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0);
|
||||
|
||||
/** Everyone's points as they were when the board last stood still: a new score shows once the card / noble has landed. */
|
||||
function useShownPoints(v: SplendorView): Record<string, number> {
|
||||
const key = useAfterMotionValue(v.order.map((p) => `${p}:${v.players[p]?.points ?? 0}`).join(','));
|
||||
const out: Record<string, number> = {};
|
||||
for (const p of v.order) out[p] = v.players[p]?.points ?? 0;
|
||||
for (const x of key ? key.split(',') : []) {
|
||||
const [p, n] = x.split(':');
|
||||
if (p! in out) out[p!] = Number(n);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const costText = (cost: Partial<Record<TokenColor, number>>) =>
|
||||
TOKEN_COLORS.filter((c) => cost[c])
|
||||
.map((c) => `${SHORT[c]} ${cost[c]}`)
|
||||
@@ -426,6 +438,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
const prevLog = useRef(v.log.at(-1)?.n ?? 0);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useSplendorFx(v, me, players, showBanner);
|
||||
const pts = useShownPoints(v);
|
||||
|
||||
// Reset local choices whenever the turn or phase moves on.
|
||||
useEffect(() => {
|
||||
@@ -609,12 +622,12 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board
|
||||
className={`sp-chip${v.current === p ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}`}
|
||||
data-fx-seat={p}
|
||||
aria-expanded={openOpp === p}
|
||||
aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||
aria-label={`${nick(players, p)} ${pts[p]}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`}
|
||||
onClick={() => setOpenOpp(openOpp === p ? null : p)}
|
||||
>
|
||||
<Avatar user={userOf(players, p)} size={24} />
|
||||
<span style={{ maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 700 }}>{nick(players, p)}</span>
|
||||
<span className="pt">{pv.points}점</span>
|
||||
<span className="pt">{pts[p]}점</span>
|
||||
<span className="muted small">
|
||||
💎{pv.tokenCount} 🃏{pv.cards.length}
|
||||
{pv.reservedCount ? ` 📌${pv.reservedCount}` : ''}
|
||||
@@ -966,7 +979,22 @@ function gemSpot(p: string, c: TokenColor, me: string | null): Element | null {
|
||||
* previous view). Nothing on the first render (join, reload, replay jump).
|
||||
*/
|
||||
function useSplendorFx(v: SplendorView, me: string | null, players: Record<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f());
|
||||
// Staged steps (banners, bumps) wait in timers: results wait for them too (the gaps are not animations).
|
||||
const [staged, setStaged] = useState(0);
|
||||
useMotionHold(staged > 0);
|
||||
const wait = (realMs: number, f: () => void) => {
|
||||
setStaged((n) => n + 1);
|
||||
setTimeout(() => {
|
||||
setStaged((n) => n - 1);
|
||||
f();
|
||||
}, realMs);
|
||||
};
|
||||
const later = (ms: number, f: () => void) => (ms ? wait(fxMs(ms), f) : f());
|
||||
// When the flights started by the last view end (performance.now() ms): the game-end banner comes after them.
|
||||
const flightsEnd = useRef(0);
|
||||
const till = (ms: number) => {
|
||||
flightsEnd.current = Math.max(flightsEnd.current, performance.now() + fxMs(ms));
|
||||
};
|
||||
// Board of the previous view (slot key → card id) to know where a bought / reserved card was.
|
||||
const prevBoard = useRef<Record<string, string | null> | null>(null);
|
||||
// Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still
|
||||
@@ -990,6 +1018,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
const bank = fxEl(`sp-bank-${c}`);
|
||||
const spot = gemSpot(p, c, me);
|
||||
flyGhost(toBank ? spot : bank, toBank ? bank : spot, { kind: 'chip', count: n, gap: 80, delay: at + i * 80, ms: 420, label: SHORT[c], className: `sp-fx-gem sp-fx-${c}` });
|
||||
till(at + (i + n - 1) * 80 + 420);
|
||||
for (let k = 0; k < n; k++) (toBank ? spSfx.clack : spSfx.clink)(at + (i + k) * 80 + (toBank ? 380 : 120), i + k);
|
||||
i += n;
|
||||
}
|
||||
@@ -1024,6 +1053,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
? (snap.current.rects.get(`r:${e.cardId}`) ?? fxEl('sp-reserved'))
|
||||
: seatOf(e.p, me);
|
||||
flyGhost(from, to, { kind: 'card', delay: at, ms: 520, className: `sp-fx-card sp-fx-b-${bonus}` });
|
||||
till(at + 520);
|
||||
later(at + 480, () => bump(to));
|
||||
spSfx.buy(at);
|
||||
const paid = sum(e.paid);
|
||||
@@ -1040,6 +1070,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (newCard && isShown(newCard)) flyFrom(newCard, from, { delay: at, ms: 460, rotate: -8 });
|
||||
else flyGhost(from, e.p === me ? fxEl('sp-reserved') : seatOf(e.p, me), { kind: 'card', delay: at, ms: 500, className: `sp-fx-card ${look}` });
|
||||
spSfx.reserve(at);
|
||||
till(at + (e.gold ? 600 : 500));
|
||||
if (e.gold) {
|
||||
flyGhost(fxEl('sp-bank-gold'), gemSpot(e.p, 'gold', me), { kind: 'chip', delay: at + 180, ms: 420, label: SHORT.gold, className: 'sp-fx-gem sp-fx-gold' });
|
||||
spSfx.gold(at + 520);
|
||||
@@ -1051,6 +1082,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
const from = snap.current.rects.get(`n:${e.nobleId}`) ?? fxEl('sp-nobles');
|
||||
const at2 = at + 150;
|
||||
flyGhost(from, seatOf(e.p, me), { kind: 'card', delay: at2, ms: 560, label: '👑', className: 'sp-fx-noble' });
|
||||
till(at2 + 560);
|
||||
later(at2, () => showBanner('👑 귀족 방문!', 'gold', `${NOBLE_NAME[e.nobleId] ?? '귀족'} → ${e.p === me ? '나' : `${nick(players, e.p)}님`} (+3점)`));
|
||||
spSfx.noble(at2);
|
||||
later(at2 + 560, () => bump(seatOf(e.p, me)));
|
||||
@@ -1094,6 +1126,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (!c || before[k] === c.id || before[k] === undefined) return;
|
||||
const delay = 260 + n * 120;
|
||||
flyFrom(fxEl(`sp-slot-${k}`), fxEl(`sp-deck-${t}`), { delay, ms: 420, rotate: 8, scale: 0.7 });
|
||||
till(delay + 420);
|
||||
spSfx.flip(delay + 380);
|
||||
n++;
|
||||
});
|
||||
@@ -1104,7 +1137,8 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record<strin
|
||||
if (now !== 'finished' || !v.result) return;
|
||||
const w = v.result.winners;
|
||||
const sub = w.length ? (w.includes(me ?? '') && w.length === 1 ? '내가 이겼어요!' : `${w.map((p) => nick(players, p)).join(', ')}님 승리`) : undefined;
|
||||
later(700, () => showBanner('게임 끝', 'gold', sub));
|
||||
// After the last move's flights (cards, gems, a noble) have landed.
|
||||
wait(Math.max(fxMs(700), flightsEnd.current - performance.now() + fxMs(100)), () => showBanner('게임 끝', 'gold', sub));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1128,11 +1162,12 @@ function MyArea({
|
||||
flag: (key: string) => React.ReactNode;
|
||||
}) {
|
||||
const turn = v.current === me;
|
||||
const pts = useShownPoints(v);
|
||||
return (
|
||||
<section className={`sp-mine${turn && v.phase !== 'finished' ? ' anim-glow' : ''}`} aria-label="내 자리" data-fx="sp-mine" style={{ border: `3px solid ${turn ? 'var(--focus)' : 'transparent'}` }}>
|
||||
<div className="sp-mine-head">
|
||||
<strong>
|
||||
나 · <span style={{ fontSize: '1.2rem' }}>{pv.points}점</span>
|
||||
나 · <span style={{ fontSize: '1.2rem' }}>{pts[me] ?? pv.points}점</span>
|
||||
<span className="muted small"> / {v.options.targetPoints}점</span>
|
||||
</strong>
|
||||
<span className="small">
|
||||
@@ -1239,13 +1274,14 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
const [ask, setAsk] = useState(false);
|
||||
const mine = me ? v.players[me] : undefined;
|
||||
const log = useMemo(() => [...v.log].reverse(), [v.log]);
|
||||
const pts = useShownPoints(v);
|
||||
// 마지막 라운드 / 게임 끝 show once the move that caused them has played on the board.
|
||||
const head = useAfterMotionValue(v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`);
|
||||
return (
|
||||
<>
|
||||
<section className="card stack" style={{ padding: 10, gap: 6 }} aria-label="참가자">
|
||||
<div className="row small" style={{ justifyContent: 'space-between' }}>
|
||||
<strong>
|
||||
{v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`}
|
||||
</strong>
|
||||
<strong>{head}</strong>
|
||||
</div>
|
||||
{v.order.map((p, i) => {
|
||||
const pv = v.players[p]!;
|
||||
@@ -1266,8 +1302,8 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
{pv.conceded ? '기권' : pv.away ? '자리 비움' : `보석 ${pv.tokenCount} · 카드 ${pv.cards.length} · 예약 ${pv.reservedCount}`}
|
||||
</div>
|
||||
</div>
|
||||
<span style={{ fontWeight: 900, fontSize: '1.3rem' }} aria-label={`${nick(players, p)} ${pv.points}점`}>
|
||||
{pv.points}
|
||||
<span style={{ fontWeight: 900, fontSize: '1.3rem' }} aria-label={`${nick(players, p)} ${pts[p]}점`}>
|
||||
{pts[p]}
|
||||
</span>
|
||||
{turn && v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.turnMs || 60_000} mine={p === me} size={36} />}
|
||||
</div>
|
||||
@@ -1276,21 +1312,23 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps<Splend
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
{v.result && (
|
||||
<section className="card stack" style={{ padding: 10, gap: 4 }} aria-label="최종 순위">
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<div key={r.player} className="row small" style={{ gap: 6 }}>
|
||||
<strong style={{ width: 32 }}>{r.rank}위</strong>
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{nick(players, r.player)}</span>
|
||||
<span>
|
||||
{r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<section className="card stack" style={{ padding: 10, gap: 4 }} aria-label="최종 순위">
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<div key={r.player} className="row small" style={{ gap: 6 }}>
|
||||
<strong style={{ width: 32 }}>{r.rank}위</strong>
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{nick(players, r.player)}</span>
|
||||
<span>
|
||||
{r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''}
|
||||
{r.conceded ? ' · 기권' : ''}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{log.length > 0 && (
|
||||
<details className="card" open style={{ padding: 10 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
53
apps/web/src/games/sudoku/art.tsx
Normal file
53
apps/web/src/games/sudoku/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 스도쿠 small pictures for the rules and the summary cards (SVG, no image files). */
|
||||
|
||||
const U = 32;
|
||||
|
||||
/**
|
||||
* A few rows of cells. Per char: '1'..'9' given (bold), 'a'..'i' my number 1..9 (blue), '.' empty, '*' the selected
|
||||
* empty cell. `bad` cells are red (a digit twice), `notes` puts small pencil marks in empty cells, `box` draws thick
|
||||
* lines every 3 cells.
|
||||
*/
|
||||
export function MiniSudoku({ rows, bad = [], notes = {}, box = true, size = 28 }: { rows: string[]; bad?: number[]; notes?: Record<number, string>; box?: boolean; size?: number }) {
|
||||
const cols = rows[0]!.length;
|
||||
const w = cols * U;
|
||||
const h = rows.length * U;
|
||||
return (
|
||||
<svg viewBox={`-2 -2 ${w + 4} ${h + 4}`} width={cols * size} height={rows.length * size} aria-hidden style={{ verticalAlign: 'middle', maxWidth: '100%' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const i = r * cols + c;
|
||||
const x = c * U;
|
||||
const y = r * U;
|
||||
const mine = ch >= 'a' && ch <= 'i';
|
||||
const d = mine ? String(ch.charCodeAt(0) - 96) : ch >= '1' && ch <= '9' ? ch : '';
|
||||
const red = bad.includes(i);
|
||||
return (
|
||||
<g key={i}>
|
||||
<rect x={x} y={y} width={U} height={U} fill={red ? '#fee2e2' : ch === '*' ? '#dbe7ff' : '#ffffff'} stroke="#cbd5e1" strokeWidth={1} />
|
||||
{ch === '*' && <rect x={x + 2} y={y + 2} width={U - 4} height={U - 4} fill="none" stroke="#2563eb" strokeWidth={3} />}
|
||||
{d && (
|
||||
<text x={x + U / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={mine ? 600 : 900} fill={red ? '#dc2626' : mine ? '#2563eb' : '#111827'}>
|
||||
{d}
|
||||
</text>
|
||||
)}
|
||||
{!d &&
|
||||
[...(notes[i] ?? '')].map((n) => {
|
||||
const k = Number(n) - 1;
|
||||
return (
|
||||
<text key={n} x={x + 6 + (k % 3) * 10} y={y + 10 + Math.floor(k / 3) * 10} textAnchor="middle" fontSize={8.5} fontWeight={700} fill="#64748b">
|
||||
{n}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(cols / 3) + 1 }, (_, k) => <line key={`v${k}`} x1={k * 3 * U} y1={0} x2={k * 3 * U} y2={h} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(rows.length / 3) + 1 }, (_, k) => <line key={`h${k}`} x1={0} y1={k * 3 * U} x2={w} y2={k * 3 * U} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{!box && <rect x={0} y={0} width={w} height={h} fill="none" stroke="#111827" strokeWidth={2.5} />}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
41
apps/web/src/games/sudoku/help.ts
Normal file
41
apps/web/src/games/sudoku/help.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 스도쿠 [?] "지금 할 수 있는 것" (docs/07 §5) and the conflict check the board uses. Pure: only reads the client view. */
|
||||
import type { SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
/** Cells whose digit shows up twice in a row, column or box (visible numbers only, no answer). */
|
||||
export function conflicts(values: string): Set<number> {
|
||||
const out = new Set<number>();
|
||||
const units: number[][] = [];
|
||||
for (let k = 0; k < 9; k++) {
|
||||
units.push(Array.from({ length: 9 }, (_, c) => k * 9 + c));
|
||||
units.push(Array.from({ length: 9 }, (_, r) => r * 9 + k));
|
||||
units.push(Array.from({ length: 9 }, (_, j) => (Math.floor(k / 3) * 3 + Math.floor(j / 3)) * 9 + (k % 3) * 3 + (j % 3)));
|
||||
}
|
||||
for (const u of units) {
|
||||
const seen = new Map<string, number[]>();
|
||||
for (const i of u) if (values[i] !== '0') seen.set(values[i]!, [...(seen.get(values[i]!) ?? []), i]);
|
||||
for (const cells of seen.values()) if (cells.length > 1) for (const i of cells) out.add(i);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const HOW = [
|
||||
'가로줄·세로줄·굵은 선 3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 다 맞게 채우면 다 푼 거예요.',
|
||||
'칸을 고르고 아래 숫자를 누르거나 키보드로 숫자를 쳐요. 맞는지는 알려 주지 않아요(종이처럼). 같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요.',
|
||||
'[메모]를 켜면 숫자가 작은 후보 메모로 들어가요. 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는 지워져요.',
|
||||
'키보드: 화살표로 칸을 옮기고 1~9 넣기, Backspace·Delete·0 지우기, N이나 스페이스로 메모 켜고 끄기예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const b = v.board;
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!b || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const extra: string[] = [];
|
||||
const bad = conflicts(b.values).size;
|
||||
if (bad) extra.push(`지금 숫자가 겹친 빨간 칸이 ${bad}개 있어요. 둘 중 하나는 틀렸어요.`);
|
||||
if (v.options.hints) extra.push(`막히면 [💡 힌트]를 눌러요. 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(지금까지 ${b.hints}번, 결과에 남아요).`);
|
||||
else extra.push('이 방은 힌트를 쓸 수 없어요.');
|
||||
return [lines, ...extra].join('\n');
|
||||
}
|
||||
428
apps/web/src/games/sudoku/index.tsx
Normal file
428
apps/web/src/games/sudoku/index.tsx
Normal file
@@ -0,0 +1,428 @@
|
||||
/** 스도쿠 화면 (docs/games/sudoku.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { DIFFICULTIES, type Difficulty, type SudokuOptions, type SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { conflicts, helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const rowOf = (i: number) => Math.floor(i / 9);
|
||||
const colOf = (i: number) => i % 9;
|
||||
const boxOf = (i: number) => Math.floor(rowOf(i) / 3) * 3 + Math.floor(colOf(i) / 3);
|
||||
|
||||
const CSS = `
|
||||
.sd-main { display: flex; gap: 18px; align-items: flex-start; justify-content: center; width: 100%; }
|
||||
.sd-main.phone { flex-direction: column; align-items: stretch; gap: 10px; }
|
||||
.sd-grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(9, 1fr); aspect-ratio: 1; width: 100%;
|
||||
background: var(--surface); border: 3px solid var(--text); border-radius: 8px; overflow: hidden; box-shadow: var(--shadow);
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; outline: none; cursor: pointer; }
|
||||
.sd-grid:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.sd-grid[data-off='true'] { cursor: default; }
|
||||
.sd-cell { position: relative; display: flex; align-items: center; justify-content: center; min-width: 0; min-height: 0;
|
||||
border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums;
|
||||
font-size: clamp(1.15rem, 6vw, 2rem); line-height: 1; transition: background-color .12s; }
|
||||
.sd-cell[data-c='2'], .sd-cell[data-c='5'] { border-right: 2px solid var(--text); }
|
||||
.sd-cell[data-c='8'] { border-right: 0; }
|
||||
.sd-cell[data-r='2'], .sd-cell[data-r='5'] { border-bottom: 2px solid var(--text); }
|
||||
.sd-cell[data-r='8'] { border-bottom: 0; }
|
||||
.sd-cell.peer { background: var(--surface-2); }
|
||||
.sd-cell.same { background: var(--primary-soft); }
|
||||
.sd-cell.hint { background: var(--warning-soft); }
|
||||
.sd-cell.sel { background: var(--primary-soft); box-shadow: inset 0 0 0 3px var(--primary); }
|
||||
.sd-cell .d { font-weight: 600; color: var(--primary); }
|
||||
.sd-cell[data-given='true'] .d { font-weight: 900; color: var(--text); }
|
||||
.sd-cell.same .d { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; }
|
||||
.sd-cell.bad { background: var(--danger-soft); }
|
||||
.sd-cell.bad .d { color: var(--danger); }
|
||||
.sd-cell.sol .d { color: var(--success); font-weight: 600; opacity: .85; }
|
||||
.sd-cell.wrong { background: var(--danger-soft); }
|
||||
.sd-cell.wrong .d { color: var(--success); }
|
||||
.sd-notes { position: absolute; inset: 2px; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr);
|
||||
font-size: clamp(.55rem, 2.6vw, .78rem); font-weight: 700; color: var(--text-sub); line-height: 1; }
|
||||
.sd-notes span { display: flex; align-items: center; justify-content: center; }
|
||||
.sd-notes span.on { color: var(--primary); }
|
||||
.sd-pop .d { animation: sd-pop .3s ease-out both; }
|
||||
.sd-glow { animation: sd-glow .9s ease-out both; }
|
||||
@keyframes sd-pop { from { transform: scale(.4); opacity: .3; } 60% { transform: scale(1.18); } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes sd-glow { 0% { box-shadow: inset 0 0 0 0 var(--warning); } 40% { box-shadow: inset 0 0 0 5px var(--warning); } 100% { box-shadow: inset 0 0 0 0 var(--warning); } }
|
||||
.sd-pad { display: flex; flex-direction: column; gap: 8px; width: 216px; flex: none; }
|
||||
.sd-digits { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||||
.sd-tools { display: grid; grid-template-columns: 1fr; gap: 6px; }
|
||||
.sd-main.phone .sd-pad { width: 100%; }
|
||||
.sd-main.phone .sd-digits { grid-template-columns: repeat(9, 1fr); gap: 4px; }
|
||||
.sd-main.phone .sd-tools { grid-template-columns: repeat(3, 1fr); }
|
||||
.sd-key { position: relative; border: 0; border-radius: 10px; background: var(--surface); color: var(--primary); box-shadow: var(--shadow); cursor: pointer;
|
||||
font-size: 1.7rem; font-weight: 800; min-height: 64px; padding: 0; font-variant-numeric: tabular-nums; touch-action: manipulation; }
|
||||
.sd-main.phone .sd-key { min-height: 54px; font-size: 1.45rem; border-radius: 8px; }
|
||||
.sd-key small { position: absolute; right: 6px; bottom: 4px; font-size: .7rem; font-weight: 700; color: var(--text-sub); }
|
||||
.sd-main.phone .sd-key small { right: 0; left: 0; bottom: 2px; text-align: center; font-size: .62rem; }
|
||||
.sd-key[data-done='true'] { opacity: .35; }
|
||||
.sd-key[data-memo='true'] { color: var(--text-sub); font-size: 1.15rem; }
|
||||
.sd-key:active { transform: scale(.95); }
|
||||
.sd-key:disabled { cursor: default; }
|
||||
.sd-tool { min-height: 44px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-weight: 800; font-size: .98rem; cursor: pointer; padding: 0 8px; touch-action: manipulation; }
|
||||
.sd-tool[aria-pressed='true'] { background: var(--primary); color: var(--primary-text); }
|
||||
.sd-tool:disabled { opacity: .5; cursor: default; }
|
||||
@media (prefers-reduced-motion: reduce) { .sd-pop .d, .sd-glow { animation: none; } .sd-key:active { transform: none; } }
|
||||
`;
|
||||
|
||||
const notesOf = (mask: number) => DIGITS.filter((n) => mask & (1 << n));
|
||||
|
||||
function SudokuBoardView({ view: v, me, players, act }: BoardProps<SudokuView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState(40);
|
||||
const [memo, setMemo] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [glow, setGlow] = useState<number | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const prev = useRef<{ values: string; notes: string; hints: number; bad: number } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
const bad = b ? conflicts(b.values) : new Set<number>();
|
||||
|
||||
// Pop-in for new numbers, a glow on the hinted cell, sounds for what changed.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const cur = { values: b.values, notes: b.notes.join(','), hints: b.hints, bad: bad.size };
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!was || was.values.length !== cur.values.length) return;
|
||||
const added = new Set<number>();
|
||||
let cleared = 0;
|
||||
for (let i = 0; i < 81; i++) {
|
||||
if (was.values[i] === cur.values[i]) continue;
|
||||
if (cur.values[i] === '0') cleared++;
|
||||
else added.add(i);
|
||||
}
|
||||
if (cur.hints > was.hints) {
|
||||
sfx.good();
|
||||
setGlow(b.hintAt);
|
||||
} else if (cur.bad > was.bad) {
|
||||
tone(240, 120, 'square', 0.05);
|
||||
haptic([20, 30, 20]);
|
||||
} else if (added.size) tone(880 + Number(b.values[[...added][0]!]) * 40, 60, 'triangle', 0.1);
|
||||
else if (cleared) tone(420, 50, 'triangle', 0.07);
|
||||
else if (cur.notes !== was.notes) tone(1300, 25, 'triangle', 0.05);
|
||||
const timers: ReturnType<typeof setTimeout>[] = [];
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
timers.push(setTimeout(() => setFresh(new Set()), fxMs(320)));
|
||||
}
|
||||
if (cur.hints > was.hints) timers.push(setTimeout(() => setGlow(null), fxMs(900)));
|
||||
return () => timers.forEach(clearTimeout);
|
||||
}, [b?.values, b?.notes.join(','), b?.hints]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="가로·세로·상자에 1~9를 한 번씩!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const given = (i: number) => b.givens[i] === '1';
|
||||
const reveal = b.solution;
|
||||
const counts = DIGITS.map((n) => [...b.values].filter((ch) => ch === String(n)).length);
|
||||
const describe = (i: number) => {
|
||||
const where = `${rowOf(i) + 1}줄 ${colOf(i) + 1}칸`;
|
||||
const ch = b.values[i]!;
|
||||
if (given(i)) return `${where}, 처음 숫자 ${ch}`;
|
||||
if (ch !== '0') return `${where}, 내 숫자 ${ch}${bad.has(i) ? ', 겹침' : ''}`;
|
||||
const ns = notesOf(b.notes[i]!);
|
||||
return `${where}, 빈칸${ns.length ? `, 메모 ${ns.join(' ')}` : ''}`;
|
||||
};
|
||||
|
||||
const select = (i: number, speak: boolean) => {
|
||||
setSel(i);
|
||||
if (speak) setAnnounce(describe(i));
|
||||
};
|
||||
const enter = (n: number) => {
|
||||
if (!playing) return;
|
||||
const ch = b.values[sel]!;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 바꿀 수 없어요.');
|
||||
if (memo) {
|
||||
if (ch !== '0') return setAnnounce('숫자가 있는 칸에는 메모할 수 없어요. 먼저 지워 주세요.');
|
||||
act({ type: 'note', i: sel, n });
|
||||
setAnnounce(b.notes[sel]! & (1 << n) ? `메모 ${n}을(를) 지웠어요.` : `메모 ${n}을(를) 적었어요.`);
|
||||
return;
|
||||
}
|
||||
haptic(8);
|
||||
if (ch === String(n)) {
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce(`${n}을(를) 지웠어요.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'set', i: sel, n });
|
||||
const dup = [...b.values].some((c, j) => j !== sel && c === String(n) && (rowOf(j) === rowOf(sel) || colOf(j) === colOf(sel) || boxOf(j) === boxOf(sel)));
|
||||
setAnnounce(`${n}을(를) 넣었어요.${dup ? ' 같은 줄·칸·상자에 이미 있는 숫자예요.' : ''}`);
|
||||
};
|
||||
const erase = () => {
|
||||
if (!playing) return;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 지울 수 없어요.');
|
||||
if (b.values[sel] === '0' && !b.notes[sel]) return setAnnounce('지울 것이 없어요.');
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce('지웠어요.');
|
||||
};
|
||||
const toggleMemo = () => {
|
||||
setMemo((m) => !m);
|
||||
setAnnounce(memo ? '메모 모드를 껐어요. 숫자를 넣어요.' : '메모 모드를 켰어요. 숫자가 작은 메모로 들어가요.');
|
||||
};
|
||||
const hint = () => {
|
||||
if (!playing || !v.options.hints) return;
|
||||
act({ type: 'hint' });
|
||||
setAnnounce('힌트로 한 칸을 맞는 숫자로 채웠어요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const box = gridRef.current!.getBoundingClientRect();
|
||||
const c = clamp(Math.floor(((e.clientX - box.left) / box.width) * 9), 0, 8);
|
||||
const r = clamp(Math.floor(((e.clientY - box.top) / box.height) * 9), 0, 8);
|
||||
select(r * 9 + c, false);
|
||||
if (e.pointerType === 'mouse') gridRef.current!.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
const onButton = (e.target as HTMLElement).tagName === 'BUTTON';
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
select(clamp(rowOf(sel) + m[0], 0, 8) * 9 + clamp(colOf(sel) + m[1], 0, 8), true);
|
||||
return;
|
||||
}
|
||||
const num = /^(Digit|Numpad)([0-9])$/.exec(e.code)?.[2] ?? (/^[0-9]$/.test(e.key) ? e.key : null);
|
||||
if (num !== null) {
|
||||
e.preventDefault();
|
||||
if (num === '0') erase();
|
||||
else enter(Number(num));
|
||||
} else if (e.key === 'Backspace' || e.key === 'Delete') {
|
||||
e.preventDefault();
|
||||
erase();
|
||||
} else if ((e.key === ' ' && !onButton) || e.key === 'n' || e.key === 'N' || e.key === 'ㅜ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) toggleMemo();
|
||||
}
|
||||
};
|
||||
|
||||
const wrapStyle: CSSProperties = phone ? { width: '100%' } : { width: 'min(100%, 600px, calc(var(--play-h, 100vh) - 150px))', minWidth: 300, flex: '0 1 auto' };
|
||||
const showPad = !!mine && mine.status === 'playing' && v.phase === 'playing';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
{mine && (
|
||||
<span className="rc-pill" aria-label={mine.progressText}>
|
||||
✏️ <b>{mine.progressText.replace(/^[^\d]*/, '')}</b>
|
||||
</span>
|
||||
)}
|
||||
{b.hints > 0 && (
|
||||
<span className="rc-pill" aria-label={`힌트 ${b.hints}번`}>
|
||||
💡 <b>{b.hints}</b>
|
||||
</span>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className={`sd-main${phone ? ' phone' : ''}`} onKeyDown={onKey}>
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<div
|
||||
ref={gridRef}
|
||||
className="sd-grid"
|
||||
data-off={!playing}
|
||||
role="application"
|
||||
aria-roledescription="스도쿠 판"
|
||||
aria-label={playing ? `스도쿠 판. 화살표로 옮기고 1~9로 넣기, Backspace로 지우기, N으로 메모. 지금 ${describe(sel)}` : '스도쿠 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.values, (ch, i) => {
|
||||
const r = rowOf(i);
|
||||
const c = colOf(i);
|
||||
// Selection shading only while I can still play.
|
||||
const s = playing ? b.values[sel]! : '0';
|
||||
const cls = ['sd-cell'];
|
||||
const sol = reveal && ch !== reveal[i] ? reveal[i]! : null;
|
||||
if (sol) cls.push(ch === '0' ? 'sol' : 'wrong');
|
||||
else if (bad.has(i)) cls.push('bad');
|
||||
if (playing && i === sel) cls.push('sel');
|
||||
else if (s !== '0' && ch === s) cls.push('same');
|
||||
else if (glow === i || (b.hintAt === i && playing)) cls.push('hint');
|
||||
else if (playing && (r === rowOf(sel) || c === colOf(sel) || boxOf(i) === boxOf(sel))) cls.push('peer');
|
||||
if (fresh.has(i)) cls.push('sd-pop');
|
||||
if (glow === i) cls.push('sd-glow');
|
||||
const shown = sol ?? (ch !== '0' ? ch : null);
|
||||
return (
|
||||
<div key={i} className={cls.join(' ')} data-i={i} data-v={ch} data-r={r} data-c={c} data-given={given(i)} data-bad={bad.has(i)} aria-hidden>
|
||||
{shown ? (
|
||||
<span className="d">{shown}</span>
|
||||
) : b.notes[i] ? (
|
||||
<span className="sd-notes">
|
||||
{DIGITS.map((n) => (
|
||||
<span key={n} className={s !== '0' && String(n) === s ? 'on' : undefined}>
|
||||
{b.notes[i]! & (1 << n) ? n : ''}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{showPad && (
|
||||
<div className="sd-pad" role="group" aria-label="숫자 패드">
|
||||
<div className="sd-digits">
|
||||
{DIGITS.map((n, k) => {
|
||||
const rest = 9 - counts[k]!;
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className="sd-key"
|
||||
data-n={n}
|
||||
data-done={rest <= 0}
|
||||
data-memo={memo}
|
||||
disabled={!playing}
|
||||
aria-label={`${memo ? '메모 ' : ''}${n}, ${Math.max(0, rest)}개 남음`}
|
||||
onClick={() => enter(n)}
|
||||
>
|
||||
{n}
|
||||
<small aria-hidden>{Math.max(0, rest)}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="sd-tools">
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={erase}>
|
||||
⌫ 지우기
|
||||
</button>
|
||||
<button type="button" className="sd-tool" aria-pressed={memo} onClick={toggleMemo}>
|
||||
✏️ 메모 {memo ? '켬' : '끔'}
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={hint}>
|
||||
💡 힌트
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && showPad && <p className="rc-keys">칸 클릭 또는 화살표로 고르고 1~9 넣기 · Backspace·Delete·0 지우기 · N·스페이스 메모 켜고 끄기 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{phone && showPad && <p className="rc-keys">칸을 누르고 아래 숫자를 눌러요 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{reveal && v.phase === 'ended' && <p className="rc-keys">초록 숫자 = 정답(빈칸이었거나 틀린 칸)</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const diffInfo = (d: Difficulty) => `${DIFFICULTIES[d].name} · ${DIFFICULTIES[d].givens}`;
|
||||
|
||||
function SudokuSide(props: BoardProps<SudokuView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="스도쿠" info={`${diffInfo(o.difficulty)} · 힌트 ${o.hints ? '있음' : '없음'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 가로·세로·상자에 1~9를 한 번씩 넣어요', playing: '가로·세로·3×3 상자마다 1~9가 한 번씩 · 빈칸을 모두 맞게 채워요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SudokuOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.difficulty}
|
||||
options={(Object.keys(DIFFICULTIES) as Difficulty[]).map((d) => [d, DIFFICULTIES[d].name])}
|
||||
onChange={(difficulty) => onChange({ ...o, difficulty })}
|
||||
/>
|
||||
<span className="small muted">
|
||||
처음부터 있는 {DIFFICULTIES[o.difficulty].givens}
|
||||
{o.difficulty === 'easy' ? ' · 차근차근 하나씩 찾으면 풀려요' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '있음'],
|
||||
[false, '없음'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]로 한 칸씩 맞는 숫자를 받을 수 있어요. 쓴 횟수는 결과에 남아요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[600, 1200, 1800, 3600]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SudokuOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SudokuOptions): string {
|
||||
return `${DIFFICULTIES[o.difficulty].name} · 힌트 ${o.hints ? '있음' : '없음'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SudokuOptions }) {
|
||||
const d = options?.difficulty ?? 'easy';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
9×9 판의 <strong>가로줄·세로줄·굵은 선 3×3 상자</strong>마다 1부터 9까지가 <strong>한 번씩</strong> 들어가게 빈칸을 채워요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요. 답은 딱 하나뿐인 판만 나와요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={26} />
|
||||
<span>굵은 숫자는 처음부터 있던 것, 파란 숫자는 내가 넣은 것, 작은 숫자는 메모예요.</span>
|
||||
</div>
|
||||
<p>
|
||||
칸을 고르고 숫자를 넣어요. 맞는지는 알려 주지 않지만(종이처럼), 같은 줄·칸·상자에 같은 숫자가 겹치면 빨갛게 보여요. [메모]를 켜면 후보 숫자를 작게 적어 둘 수 있고, 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는
|
||||
저절로 지워져요. {options?.hints === false ? '이 방은 힌트가 없어요.' : '[💡 힌트]를 누르면 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(쓴 횟수는 결과에 남아요).'}
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 <strong>가장 먼저 다 맞게 채운 사람</strong>이 이기고, 아무도 못 풀면 많이 채운 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1800)}이고, 지금 난이도는 {diffInfo(d)}예요.
|
||||
</p>
|
||||
<p>PC: 칸을 클릭하거나 화살표로 고르고 1~9, Backspace로 지우기, N이나 스페이스로 메모. 휴대폰: 칸을 누르고 아래 숫자 버튼을 눌러요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SudokuView, SudokuOptions> = {
|
||||
Board: SudokuBoardView,
|
||||
Side: SudokuSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
24
apps/web/src/games/sudoku/quick.tsx
Normal file
24
apps/web/src/games/sudoku/quick.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 스도쿠 30초 규칙 요약 (docs/07 §5). Small grids drawn with the game's own look. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6.9', '.87']} size={30} />,
|
||||
alt: '굵은 선 3×3 상자 하나에 숫자 몇 개가 처음부터 들어 있어요',
|
||||
title: '1~9를 한 번씩',
|
||||
text: '가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={30} />,
|
||||
alt: '고른 칸이 파랗게 표시되고, 내가 넣은 숫자는 파란색, 빈칸에는 작은 메모가 있어요',
|
||||
title: '칸을 고르고 숫자',
|
||||
text: '칸을 누르고 아래 숫자를 눌러요. [메모]를 켜면 작은 후보 숫자로 적어 둘 수 있어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6i9', '.87']} bad={[4, 5]} size={30} />,
|
||||
alt: '같은 줄에 9가 두 번 들어가 두 칸이 빨갛게 보여요',
|
||||
title: '겹치면 빨강',
|
||||
text: '같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요. 다 맞게 채우면 끝! 여럿이면 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -8,7 +8,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { bump, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx';
|
||||
import { fxAnim } from '../../lib/motion';
|
||||
import { fxAnim, useAfterMotionValue, useMotionSettled } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { CardFace, TCard } from './cards';
|
||||
import { helpNow } from './help';
|
||||
@@ -767,10 +767,13 @@ function RoundEndPanel({ v, players, me, act, pending }: { v: TichuView; players
|
||||
|
||||
function Standings({ v, players, me }: { v: TichuView; players: Players; me: string | null }) {
|
||||
const target = v.mode === 'threechu' ? null : v.options.targetScore;
|
||||
const max = Math.max(target ?? 1, ...v.scores.map((x) => Math.abs(x)), 1);
|
||||
// New round scores show once the last trick has flown to its winner (and the 원투! banner has played).
|
||||
const scoreKey = useAfterMotionValue(v.scores.join(','));
|
||||
const scores = scoreKey.split(',').length === v.scores.length ? scoreKey.split(',').map(Number) : v.scores;
|
||||
const max = Math.max(target ?? 1, ...scores.map((x) => Math.abs(x)), 1);
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }} aria-label="점수">
|
||||
{v.scores.map((sc, i) => {
|
||||
{scores.map((sc, i) => {
|
||||
const owners = v.scoreOwners[i]!;
|
||||
const team = v.scoreOwners.length === 2;
|
||||
const label = team ? `${teamName(i)} ${owners.map((p) => (p === me ? '나' : short(nick(players, p)))).join('·')}` : owners[0] === me ? '나' : nick(players, owners[0]!);
|
||||
@@ -866,6 +869,16 @@ function Tip() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The round / game result waits until the board has stopped moving (the last trick flying to its winner, 원투!).
|
||||
* Meanwhile an empty table stays in its place, so the flight still has its start point (`tc-center`).
|
||||
*/
|
||||
function AfterTable({ when, children }: { when: boolean; children: ReactNode }) {
|
||||
const shown = useMotionSettled(when);
|
||||
if (!when) return null;
|
||||
return shown ? children : <div className="tc-table" data-fx="tc-center" aria-hidden />;
|
||||
}
|
||||
|
||||
function useTichuFx(v: TichuView, me: string | null, players: Players, showBanner: ReturnType<typeof useBanner>[1]) {
|
||||
const seatFx = (seat: number) => seatEl(`seat-${seat}`) ?? (v.seats[seat]?.owner === me ? fxEl('tc-hand') : null);
|
||||
useNewEntries(
|
||||
@@ -968,15 +981,17 @@ function TichuBoard({ view: v, me, players, act, pending, deadline }: BoardProps
|
||||
{playingish && <TableArea v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'grand' && <GrandPanel v={v} act={act} pending={pending} />}
|
||||
{v.phase === 'exchange' && <ExchangePanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'roundEnd' && <RoundEndPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||||
{v.phase === 'finished' && v.result && (
|
||||
<AfterTable when={v.phase === 'roundEnd'}>
|
||||
<RoundEndPanel v={v} players={players} me={me} act={act} pending={pending} />
|
||||
</AfterTable>
|
||||
<AfterTable when={v.phase === 'finished' && !!v.result}>
|
||||
<div className="tc-panel">
|
||||
<h3>게임이 끝났어요</h3>
|
||||
<span>{v.result.summary}</span>
|
||||
<span>{v.result?.summary}</span>
|
||||
{v.lastRound && <RoundTable v={v} r={v.lastRound} players={players} me={me} />}
|
||||
<Standings v={v} players={players} me={me} />
|
||||
</div>
|
||||
)}
|
||||
</AfterTable>
|
||||
</div>
|
||||
</div>
|
||||
{v.mySeat !== null && v.seats[v.mySeat] && (playingish || v.phase === 'roundEnd') && (
|
||||
@@ -1037,7 +1052,9 @@ function PlayedTable({ cards }: { cards: string[] }) {
|
||||
}
|
||||
|
||||
function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
const phaseKo = { grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase];
|
||||
// 라운드 결과 / 게임 끝 and the new history row show once the end of the round has played on the board.
|
||||
const phaseKo = useAfterMotionValue({ grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase]);
|
||||
const history = v.history.slice(0, useAfterMotionValue(v.history.length));
|
||||
const [showLast, setShowLast] = useState(false);
|
||||
return (
|
||||
<>
|
||||
@@ -1052,7 +1069,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
<Standings v={v} players={players} me={me} />
|
||||
</div>
|
||||
{v.history.length > 0 && (
|
||||
{history.length > 0 && (
|
||||
<div className="card" style={{ padding: 12, overflowX: 'auto', flex: 'none' }}>
|
||||
<strong>라운드 기록</strong>
|
||||
<table className="tc-tbl small" style={{ marginTop: 6 }}>
|
||||
@@ -1067,7 +1084,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps<TichuView>) {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{v.history.map((h) => (
|
||||
{history.map((h) => (
|
||||
<tr key={h.round}>
|
||||
<td>
|
||||
{h.round}
|
||||
|
||||
@@ -37,8 +37,15 @@ export interface GameUI<V = any, O = any> {
|
||||
Options: ComponentType<OptionsProps<O>>;
|
||||
optionsSummary(options: O): string;
|
||||
Rules: ComponentType<{ options?: O }>;
|
||||
/**
|
||||
* Real-time games (할리갈리, 도블, 사과 게임, 그림 맞히기): the turn status changes the moment the state does. Other games show
|
||||
* a new status only after the board has finished animating the move that caused it (lib/motion `useAfterMotionValue`).
|
||||
*/
|
||||
liveStatus?: boolean;
|
||||
/** The board has its own chat channels; the room chat panel is hidden while the game runs (마피아). */
|
||||
ownChat?: boolean;
|
||||
/** The board's chat box shows who is typing in it ("입력 중…"); the status row then shows only the computers thinking (라이어 게임). */
|
||||
typingInChat?: boolean;
|
||||
/** 30초 규칙 요약: 3 cards shown the first time this device plays the game (docs/07 §5). */
|
||||
quickStart?: QuickCard[];
|
||||
/** [?] "지금 할 수 있는 것": the current situation in plain words for this viewer (docs/07 §5). */
|
||||
|
||||
57
apps/web/src/games/typing/help.test.ts
Normal file
57
apps/web/src/games/typing/help.test.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { setupGame, usersOf } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { marks } from './marks';
|
||||
import { helpNow } from './help';
|
||||
|
||||
const users = usersOf(['A', 'B', 'C']);
|
||||
const def = GAMES.typing!;
|
||||
const view = (s: unknown, who: string | null) => def.view(s, who) as any;
|
||||
const tick = (s: any, now: number) => def.apply(s, 'A', { type: 'tick' }, { rng: { next: () => 0, int: () => 0, shuffle: (a: unknown[]) => [...a] } as any, now }).state as any;
|
||||
|
||||
test('타자 대결: 카운트다운 / 치는 중 / 관전 / 1등', () => {
|
||||
const { state: s0, now } = setupGame('typing', 3);
|
||||
expect(helpNow(view(s0, 'A'), 'A', users)).toContain('곧 시작해요');
|
||||
const s = tick(s0, now + 3000);
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('Enter');
|
||||
expect(t).toContain('가장 먼저 정확하게');
|
||||
expect(t).toContain('한/영');
|
||||
expect(helpNow(view(s, null), null, users)).toContain('관전 중');
|
||||
s.totals.B.points = 2;
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(2점)');
|
||||
});
|
||||
|
||||
test('타자 대결: 서바이벌 목숨 / 탈락 / 끝', () => {
|
||||
const { state: s0, now } = setupGame('typing', 3, { mode: 'survival', lives: 2 });
|
||||
const s = tick(s0, now + 3000);
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('목숨은 2개');
|
||||
s.rs.B.alive = false;
|
||||
expect(helpNow(view(s, 'B'), 'B', users)).toContain('탈락했어요');
|
||||
s.phase = 'ended';
|
||||
s.final = { ranking: [], summary: '라운드 점수가 가장 높은 사람이 이겼어요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('라운드 점수가 가장 높은');
|
||||
});
|
||||
|
||||
test('글자 표시: 맞음·틀림·조합 중인 글자', () => {
|
||||
expect(marks('강아지', '강').marks).toEqual(['ok', '', '']);
|
||||
expect(marks('강아지', '가').marks).toEqual(['comp', '', '']);
|
||||
// 도깨비불: "가나" 쪽으로 가는 "간"은 아직 조합 중이에요.
|
||||
expect(marks('가나', '간').marks).toEqual(['comp', '']);
|
||||
expect(marks('강아지', '강오').marks).toEqual(['ok', 'bad', '']);
|
||||
expect(marks('강아지', '강앚').marks).toEqual(['ok', 'comp', '']);
|
||||
expect(marks('강아지', '강오지').marks).toEqual(['ok', 'bad', 'ok']);
|
||||
expect(marks('abc', 'abcd')).toEqual({ marks: ['ok', 'ok', 'ok'], extra: 1 });
|
||||
});
|
||||
|
||||
test('타자 대결: 연습은 라운드·점수 없이 평균·최고 타수', () => {
|
||||
const { state: s0, now } = setupGame('typing', 1, { mode: 'practice' });
|
||||
const s = tick(s0, now + 3000);
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('연습.');
|
||||
expect(t).not.toContain('라운드');
|
||||
expect(t).toContain('최고 0타');
|
||||
s.phase = 'ended';
|
||||
s.final = { ranking: [], summary: '연습 끝! 타수와 정확도를 확인해요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('연습이 끝났어요');
|
||||
});
|
||||
51
apps/web/src/games/typing/help.ts
Normal file
51
apps/web/src/games/typing/help.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
/** 타자 대결 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import { ELIM_KO, MODE_KO, type TypingView } from '@bg/games/typing';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
const HOW = '위에 나온 글을 입력 칸에 그대로 치고 Enter를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 안 돼요.';
|
||||
|
||||
const MODE_LINE: Record<TypingView['options']['mode'], string> = {
|
||||
first: '가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 빨간 글자를 고쳐서 다시 Enter를 눌러요.',
|
||||
survival: '탈락 조건에 걸리지 않게 끝까지 버티면 라운드 1점이에요. 문제마다 제한 시간이 조금씩 줄어요.',
|
||||
speed: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 라운드 타수(1분에 친 타 수, 틀린 만큼은 빼요)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 정확도가 가장 높은 사람이 1점이에요(같으면 타수).',
|
||||
timeAttack: '시간이 끝날 때까지 나오는 글을 계속 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '제한 시간과 점수 없이 한 줄씩 제 속도로 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
|
||||
function leader(v: TypingView, players: Record<string, PublicUser>, me: string | null): string {
|
||||
const live = v.seats.filter((s) => !s.left);
|
||||
if (live.length < 2) return '';
|
||||
const best = Math.max(...live.map((s) => s.points));
|
||||
if (best === 0) return '아직 아무도 점수가 없어요.';
|
||||
const top = live.filter((s) => s.points === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
|
||||
return `지금 1등은 ${top.join(', ')}(${best}${v.options.mode === 'first' ? '점' : '승'})예요.`;
|
||||
}
|
||||
|
||||
export function helpNow(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended')
|
||||
return v.options.mode === 'practice'
|
||||
? `연습이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n평균·최고 타수와 정확도를 확인하고, [한 판 더]로 한 번 더 연습할 수 있어요.'
|
||||
: `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자의 점수, 평균 타수와 정확도를 볼 수 있어요.';
|
||||
const mode = v.options.mode;
|
||||
const surv = mode === 'survival' ? ` 탈락 조건은 "${ELIM_KO[v.options.elimination]}"${v.options.elimination === 'wrong' ? `, 목숨은 ${v.options.lives}개` : ''}예요.` : '';
|
||||
const head = mode === 'practice' ? `${MODE_KO[mode]}.` : `${MODE_KO[mode]} · 라운드 ${v.round}/${v.options.rounds}.${surv}`;
|
||||
const lead = leader(v, players, me);
|
||||
if (v.phase === 'countdown') return `${head}\n곧 시작해요. ${HOW}\n${MODE_LINE[mode]}`;
|
||||
if (v.phase === 'roundEnd') return `${head}\n라운드가 끝났어요. ${v.rounds.at(-1)?.summary ?? ''}. 잠시 뒤 다음 라운드가 시작해요.${lead ? `\n${lead}` : ''}`;
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
if (!mine) return `${head}\n관전 중이에요. 아래 막대로 각자 얼마나 쳤는지 볼 수 있어요.${lead ? `\n${lead}` : ''}`;
|
||||
if (mine.left) return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
if (!mine.alive) return `${head}\n이번 라운드에서 탈락했어요. 다음 라운드에 다시 참가해요.${lead ? `\n${lead}` : ''}`;
|
||||
const lines = [head];
|
||||
if (v.flow === 'shared' && v.upcoming.length === 0) lines.push('다음 문제가 곧 나와요. 나오자마자 쳐요!');
|
||||
else if (v.flow === 'shared' && mine.solved) lines.push('이번 문제를 쳤어요. 다른 사람이 끝내기를 기다려요.');
|
||||
else if (v.flow === 'lane' && mine.finished) lines.push('이번 라운드를 다 쳤어요. 다른 사람이 끝내기를 기다려요.');
|
||||
else lines.push(HOW);
|
||||
lines.push(MODE_LINE[mode]);
|
||||
lines.push(`${mode === 'practice' ? `지금까지: 평균 ${mine.roundKpm}타, 최고 ${mine.bestKpm}타` : `이번 라운드: ${mine.roundKpm}타`}, 정확도 ${mine.roundTried ? `${mine.roundAcc}%` : '아직 없음'}${mine.wrong ? `, 틀린 Enter ${mine.wrong}번` : ''}.`);
|
||||
if (mode === 'survival' && v.options.elimination === 'wrong') lines.push(`남은 목숨 ${mine.lives}개.`);
|
||||
if (lead) lines.push(lead);
|
||||
lines.push(v.options.lang === 'ko' ? '영어가 쳐지면 한/영 키를 눌러 한글로 바꿔요.' : '한글이 쳐지면 한/영 키를 눌러 영어로 바꿔요.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
875
apps/web/src/games/typing/index.tsx
Normal file
875
apps/web/src/games/typing/index.tsx
Normal file
@@ -0,0 +1,875 @@
|
||||
/** 타자 대결 화면 (docs/games/typing.md §9). */
|
||||
import { useEffect, useRef, useState, type FormEvent, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import {
|
||||
CATEGORY_KO,
|
||||
ELIM_KO,
|
||||
LANG_KO,
|
||||
MODE_KO,
|
||||
TOPIC_BY_ID,
|
||||
correctKeys,
|
||||
keyCount,
|
||||
kpm,
|
||||
normalize,
|
||||
topicsFor,
|
||||
type Category,
|
||||
type Elim,
|
||||
type Mode,
|
||||
type RoundResult,
|
||||
type SeatView,
|
||||
type TypingOptions,
|
||||
type TypingView,
|
||||
} from '@bg/games/typing';
|
||||
import type { PublicUser, ServerMessage } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { socket } from '../../net/socket';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { marks } from './marks';
|
||||
import { AfterMotion } from '../../lib/motion';
|
||||
|
||||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const secs = (ms: number) => Math.max(0, Math.ceil(ms / 1000));
|
||||
const clock = (ms: number) => {
|
||||
const s = secs(ms);
|
||||
return s >= 60 ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` : `${s}초`;
|
||||
};
|
||||
/** Progress is sent at most this often while typing. */
|
||||
const PROGRESS_MS = 300;
|
||||
|
||||
const tySound = {
|
||||
key: () => tone(1800, 12, 'square', 0.025),
|
||||
right: () => {
|
||||
tone(880, 70, 'triangle', 0.13);
|
||||
tone(1320, 110, 'triangle', 0.11, 60);
|
||||
},
|
||||
wrong: () => sounds.buzz(),
|
||||
first: () => sfx.fanfare(),
|
||||
out: () => [440, 330, 247].forEach((f, i) => tone(f, 160, 'sine', 0.13, i * 130)),
|
||||
count: () => tone(660, 90, 'triangle', 0.12),
|
||||
go: () => {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
},
|
||||
};
|
||||
|
||||
const OUT_KO: Record<string, string> = { lives: '목숨을 다 썼어요', slowest: '가장 늦게 쳤어요', least: '가장 적게 쳤어요', time: '시간 안에 못 쳤어요', left: '나갔어요' };
|
||||
|
||||
const CSS = `
|
||||
.ty { width: 100%; max-width: 860px; margin: 0 auto; display: flex; flex-direction: column; gap: 10px; }
|
||||
.ty-top { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.ty-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow);
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.ty-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
.ty-card { position: relative; background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 16px; display: flex; flex-direction: column; gap: 12px; min-height: 180px; }
|
||||
.ty-topic { color: var(--text-sub); font-weight: 700; font-size: .9rem; text-align: center; }
|
||||
.ty-target { font-size: clamp(1.25rem, 4.2vw, 1.9rem); font-weight: 800; line-height: 1.5; text-align: center; word-break: keep-all; overflow-wrap: anywhere; letter-spacing: .01em; }
|
||||
.ty-target span { border-radius: 3px; }
|
||||
.ty-target .ok { color: var(--success); }
|
||||
.ty-target .bad { color: #fff; background: var(--danger); }
|
||||
.ty-target .comp { color: var(--primary); text-decoration: underline; }
|
||||
.ty-target .cur { box-shadow: inset 0 -3px 0 var(--primary); }
|
||||
.ty-target .extra { color: #fff; background: var(--danger); margin-left: 2px; }
|
||||
.ty-next { color: var(--text-sub); font-size: 1.05rem; font-weight: 600; text-align: center; opacity: .8; word-break: keep-all; }
|
||||
.ty-passage { max-height: 210px; overflow: auto; border-radius: 10px; background: var(--surface-2); padding: 8px 12px; margin: 0; list-style: none; display: grid; gap: 2px; }
|
||||
.ty-passage li { font-size: .98rem; line-height: 1.5; color: var(--text-sub); }
|
||||
.ty-passage li[data-s='done'] { color: var(--success); }
|
||||
.ty-passage li[data-s='cur'] { color: var(--text); font-weight: 800; }
|
||||
.ty-form { display: flex; gap: 8px; }
|
||||
.ty-input { flex: 1; min-width: 0; font-size: 1.25rem !important; padding: 12px 14px !important; border-radius: 12px; font-weight: 700; }
|
||||
.ty-input[data-shake='true'] { animation: ty-shake .35s; border-color: var(--danger) !important; }
|
||||
.ty-stats { display: flex; flex-wrap: wrap; gap: 4px 14px; justify-content: center; color: var(--text-sub); font-weight: 700; font-size: .92rem; font-variant-numeric: tabular-nums; }
|
||||
.ty-warn { color: var(--danger); font-weight: 800; text-align: center; }
|
||||
.ty-banner { text-align: center; font-weight: 900; font-size: 1.15rem; padding: 8px 12px; border-radius: 12px; background: var(--primary-soft); animation: ty-pop .35s ease-out; }
|
||||
.ty-banner.bad { background: var(--danger-soft); color: var(--danger); }
|
||||
.ty-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; border-radius: 16px;
|
||||
background: rgba(0,0,0,.45); color: #fff; text-align: center; padding: 12px; z-index: 2; }
|
||||
.ty-over b { font-size: 4.5rem; font-weight: 900; line-height: 1; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
|
||||
.ty-over small { font-size: 1.05rem; font-weight: 800; }
|
||||
.ty-seats { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
|
||||
.ty-seat { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 4px 8px; align-items: center; background: var(--surface); border-radius: 12px; padding: 6px 10px; box-shadow: var(--shadow); }
|
||||
.ty-seat[data-me='true'] { outline: 2px solid var(--primary); }
|
||||
.ty-seat[data-out='true'] { background: var(--surface-2); }
|
||||
.ty-seat .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
|
||||
.ty-seat .sc { font-weight: 900; font-variant-numeric: tabular-nums; }
|
||||
.ty-bar { grid-column: 1 / -1; height: 8px; border-radius: 99px; background: var(--surface-2); overflow: hidden; }
|
||||
.ty-bar i { display: block; height: 100%; border-radius: 99px; background: var(--primary); transition: width .25s ease-out; }
|
||||
.ty-bar i[data-s='done'] { background: var(--success); }
|
||||
.ty-bar i[data-s='out'] { background: var(--border); }
|
||||
.ty-hearts { color: var(--danger); letter-spacing: 1px; }
|
||||
.ty-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
||||
.ty-table th, .ty-table td { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border); font-size: .92rem; }
|
||||
.ty-table td.n { text-align: right; }
|
||||
@keyframes ty-shake { 0%,100% { transform: translateX(0); } 25% { transform: translateX(-6px); } 75% { transform: translateX(6px); } }
|
||||
@keyframes ty-pop { from { transform: scale(.9); opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ty-input[data-shake='true'], .ty-banner { animation: none; } .ty-bar i { transition: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- text marks
|
||||
|
||||
function Target({ text, typed }: { text: string; typed: string }) {
|
||||
const { marks: m, extra } = marks(text, typed);
|
||||
const at = Math.min([...typed.replace(/^\s+/, '')].length, m.length);
|
||||
return (
|
||||
<div className="ty-target" aria-hidden>
|
||||
{[...text].map((ch, i) => (
|
||||
<span key={i} className={`${m[i]}${i === at ? ' cur' : ''}`}>
|
||||
{ch === ' ' && m[i] === 'bad' ? '␣' : ch}
|
||||
</span>
|
||||
))}
|
||||
{extra > 0 && <span className="extra">+{extra}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Typed in the wrong keyboard language (한/영). */
|
||||
const wrongLang = (lang: 'ko' | 'en', typed: string) => (lang === 'ko' ? /[a-zA-Z]{2,}/.test(typed) : /[ㄱ-ㅎㅏ-ㅣ가-힣]/.test(typed));
|
||||
|
||||
// ---------------------------------------------------------------- live progress (streamed)
|
||||
|
||||
type Live = Record<string, { round: number; item: number; n: number; of: number }>;
|
||||
|
||||
function useLiveProgress(round: number): Live {
|
||||
const [live, setLive] = useState<Live>({});
|
||||
useEffect(() => setLive({}), [round]);
|
||||
useEffect(
|
||||
() =>
|
||||
socket.subscribe((m: ServerMessage) => {
|
||||
if (m.t !== 'stream') return;
|
||||
const evs = (m.events as { type?: string; player?: string; item?: number; n?: number; of?: number }[]).filter((e) => e.type === 'progress' && e.player);
|
||||
if (!evs.length) return;
|
||||
setLive((cur) => {
|
||||
const next = { ...cur };
|
||||
for (const e of evs) next[e.player!] = { round, item: e.item ?? 0, n: e.n ?? 0, of: e.of ?? 1 };
|
||||
return next;
|
||||
});
|
||||
}),
|
||||
[round],
|
||||
);
|
||||
return live;
|
||||
}
|
||||
|
||||
/** A seat's progress on its current item, 0..1: the latest streamed value when it is about the same item. */
|
||||
function progOf(s: SeatView, v: TypingView, live: Live): number {
|
||||
if (v.flow === 'shared' ? s.solved : s.finished) return 1;
|
||||
const l = live[s.id];
|
||||
const idx = v.flow === 'shared' ? v.cur : s.idx;
|
||||
if (l && l.round === v.round && l.item === idx) return Math.min(1, l.n / Math.max(1, l.of));
|
||||
return s.prog;
|
||||
}
|
||||
|
||||
/** Whole-round bar for lanes with a fixed number of items; the current item otherwise. */
|
||||
function barOf(s: SeatView, v: TypingView, live: Live): number {
|
||||
const p = progOf(s, v, live);
|
||||
if (v.flow === 'lane' && v.total) return s.finished ? 1 : Math.min(1, (s.done + p) / v.total);
|
||||
return p;
|
||||
}
|
||||
|
||||
function Hearts({ n, max }: { n: number; max: number }) {
|
||||
return (
|
||||
<span className="ty-hearts" aria-label={`목숨 ${n}개`}>
|
||||
{'♥'.repeat(Math.max(0, n))}
|
||||
<span style={{ opacity: 0.25 }}>{'♥'.repeat(Math.max(0, max - n))}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Seats({ v, me, players, live }: { v: TypingView; me: string | null; players: Record<string, PublicUser>; live: Live }) {
|
||||
const surv = v.options.mode === 'survival';
|
||||
const lives = surv && v.options.elimination === 'wrong';
|
||||
const unit = v.options.mode === 'first' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<ul className="ty-seats" aria-label="참가자">
|
||||
{v.seats.map((s) => {
|
||||
const out = !s.alive && v.phase === 'playing';
|
||||
const bar = barOf(s, v, live);
|
||||
const state = out ? 'out' : (v.flow === 'shared' ? s.solved : s.finished) ? 'done' : '';
|
||||
const tag = s.left ? '나감' : out ? `탈락 · ${OUT_KO[s.outReason ?? ''] ?? ''}` : v.flow === 'shared' && s.solved ? '✓ 쳤어요' : s.finished && v.phase === 'playing' ? '✓ 다 쳤어요' : '';
|
||||
return (
|
||||
<li key={s.id} className="ty-seat" data-me={s.id === me} data-out={out || s.left}>
|
||||
<Avatar user={userOf(players, s.id)} size={24} />
|
||||
<span className="nm">
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{tag && <span className="small muted"> · {tag}</span>}
|
||||
</span>
|
||||
<span className="sc">
|
||||
{lives && s.alive && <Hearts n={s.lives} max={v.options.lives} />} {practice ? `${s.roundKpm}타` : `${s.points}${unit}`}
|
||||
</span>
|
||||
<span className="ty-bar" role="progressbar" aria-label={`${nick(players, s.id)} 진행`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(bar * 100)}>
|
||||
<i data-s={state} style={{ width: `${Math.round(bar * 100)}%` }} />
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function RoundTable({ r, players, mode }: { r: RoundResult; players: Record<string, PublicUser>; mode: Mode }) {
|
||||
return (
|
||||
<table className="ty-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>순위</th>
|
||||
<th>이름</th>
|
||||
<th className="n">{mode === 'first' ? '먼저 친 문제' : mode === 'survival' ? '친 문제' : '친 줄'}</th>
|
||||
<th className="n">타수</th>
|
||||
<th className="n">정확도</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{r.rows.map((row) => (
|
||||
<tr key={row.id}>
|
||||
<td>
|
||||
{row.rank}등{r.winners.includes(row.id) ? ' 🏆' : ''}
|
||||
</td>
|
||||
<td>
|
||||
{nick(players, row.id)}
|
||||
{row.out && row.out !== 'left' ? <span className="small muted"> · 탈락</span> : row.out === 'left' ? <span className="small muted"> · 나감</span> : null}
|
||||
</td>
|
||||
<td className="n">{row.done}</td>
|
||||
<td className="n">{row.kpm}타</td>
|
||||
<td className="n">{row.acc}%</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
const now = useServerNow(200);
|
||||
const live = useLiveProgress(v.round);
|
||||
const mine = v.seats.find((s) => s.id === me) ?? null;
|
||||
const shared = v.flow === 'shared';
|
||||
const [typed, setTyped] = useState('');
|
||||
const [shake, setShake] = useState(false);
|
||||
const [note, setNote] = useState<{ key: number; text: string; bad: boolean } | null>(null);
|
||||
// Lanes: the line I have sent but the server has not confirmed yet (so the next line shows at once).
|
||||
const [sent, setSent] = useState<{ round: number; idx: number } | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const composing = useRef(false);
|
||||
const enterAfterCompose = useRef(false);
|
||||
const lastSubmit = useRef(0);
|
||||
const lastProgress = useRef({ at: 0, text: '' });
|
||||
const seq = useRef(0);
|
||||
const passageRef = useRef<HTMLOListElement>(null);
|
||||
|
||||
const serverIdx = mine ? (shared ? v.cur : mine.idx) : 0;
|
||||
const myIdx = !shared && sent && sent.round === v.round && sent.idx >= serverIdx ? sent.idx + 1 : serverIdx;
|
||||
const item = v.upcoming.find((u) => u.idx === myIdx) ?? null;
|
||||
const following = shared ? [] : v.upcoming.filter((u) => u.idx > myIdx).slice(0, 2);
|
||||
const laneDone = !shared && v.total !== null && myIdx >= v.total;
|
||||
const canType = !!mine && mine.alive && !mine.left && v.phase === 'playing' && !!item && !(shared && mine.solved) && !(!shared && (mine.finished || laneDone));
|
||||
const itemKey = `${v.round}:${myIdx}`;
|
||||
const practice = v.options.mode === 'practice';
|
||||
// When the current item's clock started (연습: at its first key, 0 = not yet).
|
||||
const startedAt = useRef<{ key: string; at: number }>({ key: '', at: 0 });
|
||||
if (startedAt.current.key !== itemKey && item) startedAt.current = { key: itemKey, at: practice ? 0 : shared ? Math.max(v.curAt, now) : now };
|
||||
|
||||
// A new item: empty box, focus on it.
|
||||
useEffect(() => {
|
||||
setTyped('');
|
||||
lastProgress.current = { at: 0, text: '' };
|
||||
if (canType) inputRef.current?.focus({ preventScroll: true });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [itemKey, canType]);
|
||||
useEffect(() => setSent(null), [v.round]);
|
||||
// Long texts: keep the line I am on in the middle of the passage box.
|
||||
useEffect(() => {
|
||||
const ol = passageRef.current;
|
||||
const li = ol?.querySelector<HTMLElement>('li[data-s="cur"]');
|
||||
if (ol && li) ol.scrollTop = Math.max(0, li.offsetTop - ol.offsetTop - ol.clientHeight / 2 + li.clientHeight / 2);
|
||||
}, [myIdx, v.passage]);
|
||||
// A refused line (too fast, time over): back to what the server has.
|
||||
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setSent(null)), []);
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(false), 400);
|
||||
return () => clearTimeout(t);
|
||||
}, [shake]);
|
||||
useEffect(() => {
|
||||
if (!note) return;
|
||||
const t = setTimeout(() => setNote(null), 1600);
|
||||
return () => clearTimeout(t);
|
||||
}, [note]);
|
||||
|
||||
// What happened: first typist, wrong answers, people knocked out, my lines.
|
||||
const lastKey = v.last ? `${v.round}:${v.cur}:${v.last.winner}:${v.last.out.join(',')}` : '';
|
||||
const heardLast = useRef(lastKey);
|
||||
useEffect(() => {
|
||||
if (!v.last || heardLast.current === lastKey) return;
|
||||
heardLast.current = lastKey;
|
||||
if (v.last.winner === me) tySound.first();
|
||||
else if (me && v.last.out.includes(me)) tySound.out();
|
||||
else if (v.last.winner) tySound.wrong();
|
||||
}, [lastKey, v.last, me]);
|
||||
|
||||
const sendProgress = (text: string, force = false) => {
|
||||
if (!item) return;
|
||||
const t = Date.now();
|
||||
if (!force && t - lastProgress.current.at < PROGRESS_MS) return;
|
||||
if (text === lastProgress.current.text) return;
|
||||
lastProgress.current = { at: t, text };
|
||||
act({ type: 'progress', item: item.idx, text: text.slice(0, 400) });
|
||||
};
|
||||
// Throttled progress also goes out when typing pauses.
|
||||
useEffect(() => {
|
||||
if (!canType || !typed) return;
|
||||
const t = setTimeout(() => sendProgress(typed, true), PROGRESS_MS);
|
||||
return () => clearTimeout(t);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [typed, canType]);
|
||||
|
||||
const submit = (raw: string) => {
|
||||
if (!canType || !item) return;
|
||||
const t = Date.now();
|
||||
if (t - lastSubmit.current < 150) return; // Enter that the IME reported twice
|
||||
const text = raw.slice(0, 400);
|
||||
if (!normalize(text)) return;
|
||||
lastSubmit.current = t;
|
||||
const right = normalize(text) === normalize(item.text);
|
||||
act({ type: 'submit', item: item.idx, text });
|
||||
if (shared) {
|
||||
if (right) {
|
||||
tySound.right();
|
||||
haptic(15);
|
||||
setTyped('');
|
||||
} else {
|
||||
tySound.wrong();
|
||||
haptic([40, 30, 40]);
|
||||
setShake(true);
|
||||
++seq.current;
|
||||
const surv = v.options.mode === 'survival' && v.options.elimination === 'wrong';
|
||||
setNote({ key: seq.current, text: surv ? '틀렸어요! 목숨 하나를 잃었어요' : '틀린 곳이 있어요. 빨간 글자를 고쳐요', bad: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Lane: the line goes in as typed; the next one shows right away.
|
||||
if (right) tySound.right();
|
||||
else tySound.wrong();
|
||||
setSent({ round: v.round, idx: item.idx });
|
||||
setTyped('');
|
||||
};
|
||||
|
||||
const onKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key !== 'Enter') return;
|
||||
e.preventDefault();
|
||||
// Enter while a syllable is being composed: the IME finishes it first, then the line goes.
|
||||
if (e.nativeEvent.isComposing || composing.current || e.keyCode === 229) {
|
||||
enterAfterCompose.current = true;
|
||||
return;
|
||||
}
|
||||
submit(e.currentTarget.value);
|
||||
};
|
||||
const onSubmitForm = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!composing.current) submit(inputRef.current?.value ?? typed);
|
||||
};
|
||||
|
||||
// Clocks.
|
||||
const countdown = v.phase === 'countdown' && v.phaseEndsAt ? Math.max(1, Math.ceil((v.phaseEndsAt - now) / 1000)) : 0;
|
||||
const gap = shared && v.phase === 'playing' && !item && now < v.curAt;
|
||||
const clockEnd = v.phase !== 'playing' ? null : shared ? (item ? v.curEndsAt : null) : v.options.mode === 'survival' ? v.nextCutAt : v.roundEndsAt;
|
||||
const left = clockEnd === null ? null : clockEnd - now;
|
||||
const heard = useRef({ countdown: 0, warn: 0 });
|
||||
const warnSec = left !== null && left > 0 && left <= 5000 ? secs(left) : 0;
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) tySound.count();
|
||||
else if (was.countdown > 0) tySound.go();
|
||||
}
|
||||
if (warnSec && warnSec !== was.warn && canType) sfx.tick();
|
||||
heard.current = { countdown, warn: warnSec };
|
||||
});
|
||||
|
||||
const ck = item ? correctKeys(item.text, typed) : 0;
|
||||
const elapsed = item && startedAt.current.at ? Math.max(0, now - startedAt.current.at) : 0;
|
||||
const curKpm = typed && elapsed > 500 ? kpm(ck, elapsed) : 0;
|
||||
const langWarn = typed.length >= 2 && wrongLang(v.options.lang, typed);
|
||||
const surv = v.options.mode === 'survival';
|
||||
const roundLabel = practice ? null : `라운드 ${v.round}/${v.options.rounds}`;
|
||||
// 연습: how long I have been at it (like 한컴 타자연습's 경과 시간).
|
||||
const spent = practice && v.phase === 'playing' && mine && !mine.finished && !laneDone ? Math.max(0, now - v.roundStartedAt) : null;
|
||||
const progressPct = v.total ? Math.round((Math.min(myIdx, v.total) / v.total) * 100) : 0;
|
||||
const itemLabel = shared ? (v.total ? `${Math.min(v.cur + 1, v.total)}/${v.total}번째` : `${v.cur + 1}번째`) : v.total ? `${Math.min(myIdx + 1, v.total)}/${v.total}줄` : `${myIdx + 1}번째 줄`;
|
||||
const lastRound = v.rounds.at(-1);
|
||||
const alive = v.seats.filter((s) => s.alive).length;
|
||||
|
||||
let banner: { text: string; bad: boolean } | null = null;
|
||||
if (v.phase === 'playing' && shared && !item && v.last) {
|
||||
const w = v.last.winner;
|
||||
const outs = v.last.out.map((p) => (p === me ? '나' : `${nick(players, p)}님`));
|
||||
if (w) banner = { text: `${w === me ? '내가' : `${nick(players, w)}님이`} 먼저 쳤어요! ${v.last.kpm}타`, bad: false };
|
||||
else if (outs.length) banner = { text: `${outs.join(', ')} 탈락!`, bad: true };
|
||||
else banner = { text: v.options.mode === 'first' ? '시간 끝! 아무도 못 쳤어요' : '다음 문제!', bad: v.options.mode === 'first' };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="ty">
|
||||
<style>{CSS}</style>
|
||||
<div className="ty-top">
|
||||
{roundLabel && <span className="ty-pill">{roundLabel}</span>}
|
||||
<span className="ty-pill">{MODE_KO[v.options.mode]}</span>
|
||||
{v.phase === 'playing' && <span className="ty-pill">{itemLabel}</span>}
|
||||
{surv && v.phase === 'playing' && <span className="ty-pill">남은 사람 {alive}명</span>}
|
||||
{left !== null && (
|
||||
<span className={`ty-pill ${left <= 5000 ? 'warn' : ''}`} aria-label={`남은 시간 ${secs(left)}초`}>
|
||||
⏱ {surv && !shared ? `탈락까지 ${clock(left)}` : clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{spent !== null && (
|
||||
<span className="ty-pill" aria-label={`걸린 시간 ${clock(spent)}`}>
|
||||
⏱ {clock(spent)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ty-card">
|
||||
{v.passage && (
|
||||
<div className="stack" style={{ gap: 4 }}>
|
||||
<div className="ty-topic">
|
||||
{v.passageTitle}
|
||||
{v.passageBy ? ` · ${v.passageBy}` : ''}
|
||||
</div>
|
||||
<ol className="ty-passage" aria-label="긴글 전체" ref={passageRef}>
|
||||
{v.passage.map((l, i) => (
|
||||
<li key={i} data-s={i < myIdx ? 'done' : i === myIdx ? 'cur' : ''}>
|
||||
{l}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
{item && !v.passage && <div className="ty-topic">{TOPIC_BY_ID[item.topic]?.name ?? ''}</div>}
|
||||
{item ? (
|
||||
<>
|
||||
<p className="sr-only">칠 글: {item.text}</p>
|
||||
<Target text={item.text} typed={canType ? typed : ''} />
|
||||
</>
|
||||
) : (
|
||||
<div className="ty-target" style={{ color: 'var(--text-sub)', fontSize: '1.15rem' }}>
|
||||
{v.phase === 'ended'
|
||||
? practice
|
||||
? '연습 끝!'
|
||||
: '게임 끝!'
|
||||
: v.phase === 'countdown'
|
||||
? '곧 시작해요!'
|
||||
: gap
|
||||
? '다음 문제가 곧 나와요…'
|
||||
: v.phase === 'roundEnd'
|
||||
? '라운드 끝!'
|
||||
: !mine
|
||||
? '관전 중이에요 · 아래에서 진행을 볼 수 있어요'
|
||||
: mine.left
|
||||
? '게임에서 나갔어요'
|
||||
: !mine.alive
|
||||
? '탈락했어요. 다음 라운드를 기다려요'
|
||||
: laneDone || mine.finished
|
||||
? '다 쳤어요! 다른 사람을 기다려요'
|
||||
: ''}
|
||||
</div>
|
||||
)}
|
||||
{following.map((u) => (
|
||||
<div key={u.idx} className="ty-next" aria-hidden>
|
||||
{u.text}
|
||||
</div>
|
||||
))}
|
||||
{banner && (
|
||||
<div key={lastKey} className={`ty-banner ${banner.bad ? 'bad' : ''}`} role="status">
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
{mine && !mine.left && v.phase !== 'ended' && (
|
||||
<form className="ty-form" onSubmit={onSubmitForm} autoComplete="off">
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="input ty-input"
|
||||
data-shake={shake}
|
||||
value={typed}
|
||||
disabled={!canType}
|
||||
lang={v.options.lang === 'ko' ? 'ko' : 'en'}
|
||||
inputMode="text"
|
||||
enterKeyHint="send"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
maxLength={400}
|
||||
aria-label={item ? `여기에 쳐요: ${item.text}` : '입력 칸'}
|
||||
placeholder={canType ? '위의 글을 그대로 치고 Enter' : ''}
|
||||
onChange={(e) => {
|
||||
const t = e.target.value;
|
||||
if (t.length > typed.length && !composing.current) tySound.key();
|
||||
if (practice && !startedAt.current.at && normalize(t)) startedAt.current.at = socket.now();
|
||||
setTyped(t);
|
||||
sendProgress(t);
|
||||
}}
|
||||
onCompositionStart={() => {
|
||||
composing.current = true;
|
||||
}}
|
||||
onCompositionEnd={(e) => {
|
||||
composing.current = false;
|
||||
const el = e.currentTarget;
|
||||
if (enterAfterCompose.current) {
|
||||
enterAfterCompose.current = false;
|
||||
setTimeout(() => submit(el.value), 0);
|
||||
}
|
||||
}}
|
||||
onKeyDown={onKeyDown}
|
||||
onPaste={(e) => e.preventDefault()}
|
||||
onDrop={(e) => e.preventDefault()}
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={!canType} onPointerDown={(e) => e.preventDefault()} onMouseDown={(e) => e.preventDefault()}>
|
||||
입력
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{langWarn && <div className="ty-warn">{v.options.lang === 'ko' ? '한/영 키를 눌러 한글로 바꿔 주세요' : 'Press the 한/영 key to type in English (영어로 바꿔 주세요)'}</div>}
|
||||
{note && (
|
||||
<div key={note.key} className={`ty-banner ${note.bad ? 'bad' : ''}`} role="alert">
|
||||
{note.text}
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>진행 {progressPct}%</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'ended' && practice && (
|
||||
<div className="ty-stats" role="status" style={{ fontSize: '1.05rem' }}>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>
|
||||
{mine.done}줄 중 틀린 줄 {mine.wrong}개
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && !practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>이번 라운드 {mine.roundKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
{mine.wrong > 0 && <span>틀림 {mine.wrong}번</span>}
|
||||
{item && <span>{keyCount(item.text)}타짜리</span>}
|
||||
</div>
|
||||
)}
|
||||
{countdown > 0 && (
|
||||
<div className="ty-over" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>
|
||||
{v.round > 1 && !practice ? `라운드 ${v.round} · ` : ''}
|
||||
{CATEGORY_KO[v.options.category]} · {MODE_KO[v.options.mode]}
|
||||
</small>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{v.phase === 'roundEnd' && lastRound && (
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }} role="status">
|
||||
<strong>
|
||||
라운드 {lastRound.round} 결과 · {lastRound.summary}
|
||||
</strong>
|
||||
<RoundTable r={lastRound} players={players} mode={v.options.mode} />
|
||||
{v.phaseEndsAt && <span className="small muted">{secs(v.phaseEndsAt - now)}초 뒤 다음 라운드</span>}
|
||||
</div>
|
||||
)}
|
||||
<Seats v={v} me={me} players={players} live={live} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- side
|
||||
|
||||
function TypingSide({ view: v, players }: BoardProps<TypingView>) {
|
||||
const rows = [...v.seats].sort((a, b) => Number(a.left) - Number(b.left) || b.points - a.points || b.kpm - a.kpm);
|
||||
const unit = v.options.mode === 'first' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>타자 대결{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
|
||||
<span className="small muted">{optionsSummary(v.options)}</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rows.map((s, i) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.left ? 0.6 : 1 }}>
|
||||
<span style={{ width: 22, fontWeight: 800 }}>{i + 1}</span>
|
||||
<Avatar user={userOf(players, s.id)} size={22} />
|
||||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 600 }}>
|
||||
{nick(players, s.id)}
|
||||
{s.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
<span className="small muted" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.kpm}타 · {s.tried ? `${s.acc}%` : '-'}
|
||||
</span>
|
||||
{!practice && (
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.points}
|
||||
{unit}
|
||||
</strong>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.rounds.length > 0 && (
|
||||
<details className="card" style={{ padding: 12 }} open={v.phase === 'ended'}>
|
||||
<summary style={{ fontWeight: 800, cursor: 'pointer' }}>라운드 기록 ({v.rounds.length})</summary>
|
||||
<div className="stack" style={{ gap: 10, marginTop: 8 }}>
|
||||
{v.rounds.map((r) => (
|
||||
<div key={r.round} className="stack" style={{ gap: 4 }}>
|
||||
<span className="small" style={{ fontWeight: 700 }}>
|
||||
{practice ? '연습 기록' : `라운드 ${r.round} · ${r.winners.length ? r.winners.map((w) => nick(players, w)).join(', ') : '승자 없음'}`}
|
||||
</span>
|
||||
<RoundTable r={r} players={players} mode={v.options.mode} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {practice ? '' : `${r.points}${unit} · `}평균 {r.kpm}타 · 정확도 {r.acc}%{r.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- status
|
||||
|
||||
function isMyTurn(v: TypingView, me: string | null): boolean {
|
||||
const s = v.seats.find((x) => x.id === me);
|
||||
if (!s || v.phase !== 'playing' || !s.alive) return false;
|
||||
return v.flow === 'shared' ? v.upcoming.length > 0 && !s.solved : !s.finished;
|
||||
}
|
||||
|
||||
function statusText(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return `${v.options.mode === 'practice' ? '연습' : `라운드 ${v.round}`} 곧 시작! 나오는 글을 그대로 쳐요`;
|
||||
if (v.phase === 'roundEnd') return v.rounds.at(-1)?.summary ?? '라운드 끝';
|
||||
const s = v.seats.find((x) => x.id === me);
|
||||
if (!s) return v.options.mode === 'practice' ? MODE_KO.practice : `${MODE_KO[v.options.mode]} · 라운드 ${v.round}/${v.options.rounds}`;
|
||||
if (s.left) return '게임에서 나갔어요';
|
||||
if (!s.alive) return '탈락했어요 · 다음 라운드를 기다려요';
|
||||
if (v.flow === 'shared') {
|
||||
if (!v.upcoming.length) return v.last?.winner ? `${v.last.winner === me ? '내가' : `${nick(players, v.last.winner)}님이`} 먼저 쳤어요!` : '다음 문제가 곧 나와요';
|
||||
if (s.solved) return '쳤어요! 다른 사람을 기다려요';
|
||||
return v.options.mode === 'first' ? '가장 먼저 정확하게 치면 1점!' : '제한 시간 안에 정확하게 쳐요!';
|
||||
}
|
||||
if (s.finished) return '다 쳤어요! 다른 사람을 기다려요';
|
||||
return v.options.mode === 'timeAttack' ? '시간 안에 최대한 많이 쳐요!' : v.options.mode === 'practice' ? '한 줄씩 치고 Enter! 천천히 정확하게 연습해요' : '한 줄씩 치고 Enter!';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label} style={{ flexWrap: 'wrap' }}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MODE_HELP: Record<Mode, string> = {
|
||||
first: '모두에게 같은 글이 나오고, 가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 고쳐서 다시 쳐요.',
|
||||
survival: '같은 글을 모두 함께 치고, 탈락 조건에 걸리면 빠져요. 끝까지 남은 사람이 라운드 1점. 문제마다 제한 시간이 조금씩 줄어요.',
|
||||
speed: '각자 자기 속도로 글을 치고, 라운드의 타수(1분에 친 타 수, 오타는 빼고)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 글을 치고, 정확도가 가장 높은 사람이 1점이에요. 정확도가 같으면 타수가 높은 사람이 이겨요.',
|
||||
timeAttack: '정해진 시간 동안 끝없이 나오는 글을 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '한컴 타자연습처럼 혼자(또는 함께) 제 속도로 연습해요. 제한 시간과 점수 없이 짧은글은 10문장, 단어는 20개, 긴글은 한 편을 처음부터 끝까지 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
const ELIM_HELP: Record<Elim, string> = {
|
||||
wrong: '틀린 채로 Enter를 누르거나 시간 안에 못 치면 목숨이 하나 줄고, 목숨을 다 쓰면 탈락해요.',
|
||||
sentence: '문장마다 가장 늦게 친 한 사람이 탈락해요.',
|
||||
interval: '모두 각자 치다가, 정해진 시간마다 그때까지 가장 적게 친 사람이 탈락해요.',
|
||||
deadline: '문장마다 제한 시간 안에 못 친 사람은 모두 탈락해요.',
|
||||
};
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
|
||||
const set = (p: Partial<TypingOptions>) => onChange({ ...o, ...p });
|
||||
const topics = topicsFor(o.lang, o.category);
|
||||
const picked = o.topics.filter((t) => topics.some((x) => x.id === t));
|
||||
const toggle = (id: string) => {
|
||||
const others = o.topics.filter((t) => !topics.some((x) => x.id === t));
|
||||
const next = picked.includes(id) ? picked.filter((t) => t !== id) : [...picked, id];
|
||||
set({ topics: [...others, ...next] });
|
||||
};
|
||||
const timeLabel = o.mode === 'speed' || o.mode === 'accuracy' ? '라운드 제한 시간' : '한 문제 제한 시간';
|
||||
const practice = o.mode === 'practice';
|
||||
const showTime = o.mode !== 'timeAttack' && !practice && !(o.mode === 'survival' && o.elimination === 'interval');
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>언어</strong>
|
||||
<Seg label="언어" value={o.lang} options={[['ko', LANG_KO.ko], ['en', LANG_KO.en]]} onChange={(lang) => set({ lang })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>대결 방식</strong>
|
||||
<Seg label="대결 방식" value={o.mode} options={(Object.keys(MODE_KO) as Mode[]).map((m) => [m, MODE_KO[m]])} onChange={(mode) => set({ mode })} />
|
||||
<span className="small muted">{MODE_HELP[o.mode]}</span>
|
||||
</div>
|
||||
{o.mode === 'survival' && (
|
||||
<div className="stack" style={{ gap: 6, paddingLeft: 10, borderLeft: '3px solid var(--border)' }}>
|
||||
<strong>탈락 조건</strong>
|
||||
<Seg label="탈락 조건" value={o.elimination} options={(Object.keys(ELIM_KO) as Elim[]).map((m) => [m, ELIM_KO[m].replace(/\(.*\)/, '')])} onChange={(elimination) => set({ elimination })} />
|
||||
<span className="small muted">{ELIM_HELP[o.elimination]}</span>
|
||||
{o.elimination === 'wrong' && (
|
||||
<>
|
||||
<strong>목숨</strong>
|
||||
<Seg label="목숨" value={o.lives} options={[1, 2, 3, 4, 5].map((n) => [n, `${n}개`] as [number, string])} onChange={(lives) => set({ lives })} />
|
||||
</>
|
||||
)}
|
||||
{o.elimination === 'interval' && (
|
||||
<>
|
||||
<strong>탈락 간격</strong>
|
||||
<Seg label="탈락 간격" value={o.intervalSec} options={([10, 15, 20, 30] as const).map((n) => [n, `${n}초`] as [typeof n, string])} onChange={(intervalSec) => set({ intervalSec })} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{practice ? '연습 종목' : '대결 종목'}</strong>
|
||||
<Seg label={practice ? '연습 종목' : '대결 종목'} value={o.category} options={(['word', 'short', 'long'] as Category[]).map((c) => [c, CATEGORY_KO[c]])} onChange={(category) => set({ category })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>주제 (여러 개 고를 수 있어요)</strong>
|
||||
<div className="segmented" role="group" aria-label="주제" style={{ flexWrap: 'wrap' }}>
|
||||
<button type="button" aria-pressed={picked.length === 0} onClick={() => set({ topics: o.topics.filter((t) => !topics.some((x) => x.id === t)) })}>
|
||||
전체
|
||||
</button>
|
||||
{topics.map((t) => (
|
||||
<button key={t.id} type="button" aria-pressed={picked.includes(t.id)} onClick={() => toggle(t.id)}>
|
||||
{t.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="small muted">
|
||||
{picked.length === 0 ? `전체 ${topics.length}개 주제에서 골고루 나와요.` : `${picked.map((id) => topics.find((t) => t.id === id)?.name).join(', ')}에서 나와요.`}
|
||||
{o.category === 'long' ? (practice ? ' 연습은 그중 한 편을 처음부터 끝까지 쳐요.' : ' 긴글은 라운드마다 한 단락(8줄 안팎)씩 이어서 쳐요.') : ''}
|
||||
</span>
|
||||
</div>
|
||||
{!practice && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>라운드</strong>
|
||||
<Seg label="라운드" value={o.rounds} options={Array.from({ length: 10 }, (_, i) => [i + 1, `${i + 1}`] as [number, string])} onChange={(rounds) => set({ rounds })} />
|
||||
</div>
|
||||
)}
|
||||
{showTime && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{timeLabel}</strong>
|
||||
<select
|
||||
className="input"
|
||||
aria-label={timeLabel}
|
||||
style={{ maxWidth: 260 }}
|
||||
value={o.timeLimit === null ? 'null' : String(o.timeLimit)}
|
||||
onChange={(e) => set({ timeLimit: (e.target.value === 'null' ? null : Number(e.target.value)) as TypingOptions['timeLimit'] })}
|
||||
>
|
||||
<option value="0">자동(글 길이에 맞게)</option>
|
||||
{[10, 20, 30, 60, 120, 180, 300].map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n < 60 ? `${n}초` : `${n / 60}분`}
|
||||
</option>
|
||||
))}
|
||||
<option value="null">{o.mode === 'survival' ? '무제한(서바이벌은 자동으로 해요)' : '무제한'}</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
{o.mode === 'timeAttack' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>타임어택 시간</strong>
|
||||
<Seg label="타임어택 시간" value={o.attackSec} options={([30, 60, 90, 120] as const).map((n) => [n, n < 60 ? `${n}초` : n === 90 ? '1분 30초' : `${n / 60}분`] as [typeof n, string])} onChange={(attackSec) => set({ attackSec })} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: TypingOptions): string {
|
||||
const topics = topicsFor(o.lang, o.category);
|
||||
const picked = topics.filter((t) => o.topics.includes(t.id)).map((t) => t.name);
|
||||
const sub = o.mode === 'survival' ? `(${ELIM_KO[o.elimination].replace(/\(.*\)/, '')}${o.elimination === 'wrong' ? ` · 목숨 ${o.lives}` : ''})` : '';
|
||||
return `${LANG_KO[o.lang]} · ${MODE_KO[o.mode]}${sub} · ${CATEGORY_KO[o.category]}(${picked.length ? picked.join(', ') : '전체 주제'})${o.mode === 'practice' ? '' : ` · ${o.rounds}라운드`}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
|
||||
function Rules({ options: o }: { options?: TypingOptions }) {
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
모두에게 <strong>같은 글</strong>이 나와요. 입력 칸에 그대로 치고 <strong>Enter</strong>를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 쓸 수 없어요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>타수</strong>는 1분 동안 친 자판 수예요(두벌식: "강" = ㄱ·ㅏ·ㅇ 3타, "과" = ㄱ·ㅗ·ㅏ 3타). 틀린 만큼은 빼고 세요. <strong>정확도</strong>는 글과 얼마나 똑같이 쳤는지예요.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>가장 먼저 입력</strong>: 같은 글을 동시에 치고, 가장 먼저 정확하게 친 사람이 1점. 단어는 한 라운드에 10개, 짧은글은 5문장, 긴글은 한 단락을 한 줄씩 겨뤄요.
|
||||
</li>
|
||||
<li>
|
||||
<strong>서바이벌</strong>: 탈락 조건 — 틀렸을 때(목숨, 기본 3개), 문장별(가장 늦게 친 사람), 시간별(정해진 시간마다 가장 적게 친 사람), 시간 초과(제한 시간 안에 못 친 사람). 끝까지 남으면 1점. 문제마다 제한 시간이 조금씩 줄어요. 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않아요.
|
||||
</li>
|
||||
<li>
|
||||
<strong>타수 비교</strong>: 각자 자기 속도로 치고, 라운드 타수가 가장 높은 사람이 1점.
|
||||
</li>
|
||||
<li>
|
||||
<strong>정확도 대결</strong>: 정확도가 가장 높은 사람이 1점(같으면 타수).
|
||||
</li>
|
||||
<li>
|
||||
<strong>타임어택</strong>: 정해진 시간 동안 끝없이 나오는 글을 쳐서, 정확하게 친 타 수가 가장 많은 사람이 1점.
|
||||
</li>
|
||||
<li>
|
||||
<strong>연습</strong>: 한컴 타자연습처럼 제한 시간·점수 없이 제 속도로 쳐요. 짧은글 10문장, 단어 20개, 긴글은 한 편 전체. 지금·평균·최고 타수, 정확도, 진행률과 걸린 시간을 보여 줘요.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
라운드는 1~10번(기본 3번)이에요. 모두 끝나면 점수가 가장 높은 사람이 이기고, 같으면 평균 타수가 높은 사람이 앞서요. 한국어·영어, 단어·짧은글·긴글과 주제(여러 개)를 방 설정에서 골라요. 혼자서도, 컴퓨터와도 할 수
|
||||
있어요.
|
||||
</p>
|
||||
{o && <p className="small muted">이 방: {optionsSummary(o)}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<TypingView, TypingOptions> = {
|
||||
Board: TypingBoard,
|
||||
Side: TypingSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
17
apps/web/src/games/typing/marks.ts
Normal file
17
apps/web/src/games/typing/marks.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** 타자 대결: how each letter of the text looks against what is typed (pure, for the screen and its tests). */
|
||||
import { toKeys } from '@bg/games/typing';
|
||||
|
||||
export type Mark = 'ok' | 'bad' | 'comp' | '';
|
||||
|
||||
/** How each letter of the target looks against what is typed: right, wrong, or the syllable still being composed. */
|
||||
export function marks(target: string, typed: string): { marks: Mark[]; extra: number } {
|
||||
const t = [...target];
|
||||
const y = [...typed.replace(/^\s+/, '')];
|
||||
const out: Mark[] = t.map(() => '');
|
||||
for (let i = 0; i < y.length && i < t.length; i++) {
|
||||
if (y[i] === t[i]) out[i] = 'ok';
|
||||
else if (i === y.length - 1 && toKeys(t.slice(i).join('')).startsWith(toKeys(y[i]!))) out[i] = 'comp';
|
||||
else out[i] = 'bad';
|
||||
}
|
||||
return { marks: out, extra: Math.max(0, y.length - t.length) };
|
||||
}
|
||||
99
apps/web/src/games/typing/quick.tsx
Normal file
99
apps/web/src/games/typing/quick.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
/** 타자 대결 30초 규칙 요약 (docs/07 §5). Simple redraws of the typing card. */
|
||||
import type { ReactNode } from 'react';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
function Frame({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<svg viewBox="0 0 240 150" width={240} height={150} aria-hidden>
|
||||
<rect x={0} y={0} width={240} height={150} rx={14} fill="#eef2ff" />
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** A text line where the first `ok` letters are green and letter `bad` (if any) is red. */
|
||||
function Line({ y, text, ok, bad = -1, size = 20 }: { y: number; text: string; ok: number; bad?: number; size?: number }) {
|
||||
const chars = [...text];
|
||||
const w = size * 0.95;
|
||||
const x0 = 120 - (chars.length * w) / 2;
|
||||
return (
|
||||
<>
|
||||
{chars.map((c, i) => (
|
||||
<g key={i}>
|
||||
{i === bad && <rect x={x0 + i * w - 1} y={y - size + 2} width={w} height={size + 4} rx={3} fill="#dc2626" />}
|
||||
<text x={x0 + i * w + w / 2} y={y} textAnchor="middle" fontSize={size} fontWeight={800} fill={i === bad ? '#fff' : i < ok ? '#16a34a' : '#1f2937'}>
|
||||
{c}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Box({ y, text }: { y: number; text: string }) {
|
||||
return (
|
||||
<>
|
||||
<rect x={20} y={y} width={200} height={32} rx={8} fill="#fff" stroke="#6366f1" strokeWidth={2} />
|
||||
<text x={30} y={y + 22} fontSize={15} fontWeight={700} fill="#1f2937">
|
||||
{text}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Bar({ y, name, frac, color }: { y: number; name: string; frac: number; color: string }) {
|
||||
return (
|
||||
<>
|
||||
<text x={20} y={y + 9} fontSize={12} fontWeight={700} fill="#374151">
|
||||
{name}
|
||||
</text>
|
||||
<rect x={70} y={y} width={150} height={10} rx={5} fill="#e5e7eb" />
|
||||
<rect x={70} y={y} width={150 * frac} height={10} rx={5} fill={color} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Line y={52} text="티끌 모아 태산." ok={4} />
|
||||
<Box y={80} text="티끌 모|" />
|
||||
</Frame>
|
||||
),
|
||||
alt: '위에 "티끌 모아 태산."이 있고, 아래 입력 칸에 "티끌 모"까지 쳤어요. 친 글자는 초록이에요',
|
||||
title: '나온 글을 그대로',
|
||||
text: '모두에게 같은 글이 나와요. 입력 칸에 그대로 치고 Enter! 맞은 글자는 초록, 틀린 글자는 빨강이에요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Bar y={34} name="호랑이" frac={1} color="#16a34a" />
|
||||
<Bar y={64} name="나" frac={0.7} color="#6366f1" />
|
||||
<Bar y={94} name="토끼" frac={0.4} color="#6366f1" />
|
||||
<text x={120} y={135} textAnchor="middle" fontSize={15} fontWeight={900} fill="#15803d">
|
||||
호랑이님이 먼저 쳤어요! 352타
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '세 사람의 진행 막대예요. 호랑이가 먼저 다 쳤어요',
|
||||
title: '빠르고 정확하게',
|
||||
text: '가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택 중에서 골라요. 다른 사람이 친 만큼 막대로 보여요. 혼자 연습하려면 연습!',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<Frame>
|
||||
<Line y={52} text="천 리 길도" ok={2} bad={2} size={22} />
|
||||
<text x={120} y={92} textAnchor="middle" fontSize={22} fill="#dc2626">
|
||||
♥♥♡
|
||||
</text>
|
||||
<text x={120} y={128} textAnchor="middle" fontSize={14} fontWeight={800} fill="#374151">
|
||||
라운드 1/3 · 평균 280타 · 정확도 97%
|
||||
</text>
|
||||
</Frame>
|
||||
),
|
||||
alt: '틀린 글자가 빨갛게 보이고, 목숨 하트 3개 중 1개가 비었어요',
|
||||
title: '라운드 점수로 승부',
|
||||
text: '서바이벌은 틀리면 목숨이 줄어요. 1~10라운드(기본 3) 점수를 모아 1등을 가려요. 혼자서도 OK!',
|
||||
},
|
||||
];
|
||||
@@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { AfterMotion, fxMs, useAfterMotionValue } from '../../lib/motion';
|
||||
|
||||
const COLORS: Color[] = ['R', 'Y', 'G', 'B'];
|
||||
|
||||
@@ -193,6 +193,11 @@ function seatLabel(s: SeatView, players: Record<string, PublicUser>, me: string
|
||||
return parts.join(', ');
|
||||
}
|
||||
|
||||
/** A score that changes only once the round's last card (and the points flying to the winner) has landed. */
|
||||
function Score({ n, className }: { n: number; className?: string }) {
|
||||
return <span className={className}>{useAfterMotionValue(n)}점</span>;
|
||||
}
|
||||
|
||||
function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record<string, PublicUser>; me: string | null; deadline: number | null; next: boolean }) {
|
||||
const u = userOf(players, s.id);
|
||||
return (
|
||||
@@ -215,7 +220,7 @@ function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoVi
|
||||
{s.left && <span className="un-badge" style={{ background: 'var(--text-sub)', color: '#fff' }}>나감</span>}
|
||||
{s.away && <span className="un-badge" style={{ background: 'var(--warning)', color: '#fff' }}>자리 비움</span>}
|
||||
{!s.isTurn && next && <span className="small muted">다음</span>}
|
||||
{v.options.scoring === 'to500' && <span className="small muted">{s.score}점</span>}
|
||||
{v.options.scoring === 'to500' && <Score n={s.score} className="small muted" />}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -705,8 +710,13 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps<U
|
||||
/>
|
||||
<StartColorPanel v={v} act={act} pending={pending} />
|
||||
<Wild4Panel v={v} players={players} act={act} pending={pending} />
|
||||
<RevealPanel v={v} players={players} />
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
{/* Results show once the card that led to them has landed. */}
|
||||
<AfterMotion when={!!v.reveal}>
|
||||
<RevealPanel v={v} players={players} />
|
||||
</AfterMotion>
|
||||
<AfterMotion when={v.phase === 'roundEnd'}>
|
||||
<RoundPanel v={v} players={players} act={act} pending={pending} />
|
||||
</AfterMotion>
|
||||
{v.my && meSeat && !meSeat.left && v.phase !== 'roundEnd' && v.phase !== 'finished' && <MyHand v={v} act={act} pending={pending} players={players} />}
|
||||
{meSeat?.left && v.phase !== 'finished' && (
|
||||
<div className="un-panel">
|
||||
@@ -853,7 +863,7 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''}
|
||||
</span>
|
||||
{multi && <span className="small">{s.score}점</span>}
|
||||
{multi && <Score n={s.score} className="small" />}
|
||||
<span className="un-count" aria-hidden>
|
||||
<i />
|
||||
{s.cards}
|
||||
@@ -862,21 +872,23 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps<UnoView>) {
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
<span key={p.player}>
|
||||
{p.rank}등 {nick(players, p.player)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`}
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.players.map((p) => (
|
||||
<span key={p.player}>
|
||||
{p.rank}등 {nick(players, p.player)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
{v.log.length > 0 && (
|
||||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import { fxMs, useMotionHold } from '../../lib/motion';
|
||||
|
||||
// The client draws from the view only; names and hints live here so the rules module isn't bundled.
|
||||
const NAME: Record<Category, string> = {
|
||||
@@ -202,6 +202,8 @@ function DiceRow({ dice, size }: { dice: number[]; size?: number }) {
|
||||
interface RollAnim {
|
||||
key: number;
|
||||
mask: boolean[];
|
||||
/** All five the same: the 요트! flash waits until the dice have landed. */
|
||||
yacht?: { sub?: string };
|
||||
}
|
||||
|
||||
function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardProps<YachtView>) {
|
||||
@@ -225,6 +227,12 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
if (!pending) setHeld(v.held);
|
||||
}, [v.held, v.turnSeq, v.rollSeq, pending]);
|
||||
|
||||
const yachtFlash = (sub: string | undefined, key: number) => {
|
||||
setFlash({ text: '요트!', sub, key });
|
||||
sfx.fanfare();
|
||||
haptic([80, 40, 80]);
|
||||
};
|
||||
|
||||
// Roll animation, sound, yacht flash and screen-reader text when a new roll arrives (anyone's roll).
|
||||
useLayoutEffect(() => {
|
||||
if (v.rollSeq <= prevRoll.current || !v.dice) {
|
||||
@@ -237,12 +245,9 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h);
|
||||
const animated = !reducedMotion();
|
||||
rollSound(mask.filter(Boolean).length, animated);
|
||||
if (v.dice.every((d) => d === v.dice![0])) {
|
||||
setFlash({ text: '요트!', sub: v.current === me ? undefined : nick(players, v.current ?? ''), key: v.rollSeq });
|
||||
sfx.fanfare();
|
||||
haptic([80, 40, 80]);
|
||||
}
|
||||
if (animated) setAnim({ key: v.rollSeq, mask });
|
||||
const yacht = v.dice.every((d) => d === v.dice![0]) ? { sub: v.current === me ? undefined : nick(players, v.current ?? '') } : undefined;
|
||||
if (animated) setAnim({ key: v.rollSeq, mask, yacht });
|
||||
else if (yacht) yachtFlash(yacht.sub, v.rollSeq);
|
||||
}, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Someone else (re)holding dice: the same knock I hear on my own taps.
|
||||
@@ -261,12 +266,15 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
const end = setTimeout(() => {
|
||||
setAnim(null);
|
||||
setFlick(null);
|
||||
if (anim.yacht) yachtFlash(anim.yacht.sub, anim.key);
|
||||
}, fxMs(ROLL_MS));
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
clearTimeout(end);
|
||||
};
|
||||
}, [anim]);
|
||||
}, [anim]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The tumble is staged with timers (flicking faces): results wait for it.
|
||||
useMotionHold(!!anim);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
@@ -382,7 +390,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro
|
||||
{myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 && <p className="muted small" style={{ textAlign: 'center' }}>남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.</p>}
|
||||
{v.lastScore && <LastScore key={`${v.lastScore.player}:${v.lastScore.category}`} entry={v.lastScore} view={v} me={me} players={players} />}
|
||||
</section>
|
||||
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} onScore={score} pointer={pointer} />
|
||||
<ScoreSheet view={v} me={me} players={players} myTurn={myTurn} pending={pending} rolling={!!anim} onScore={score} pointer={pointer} />
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
@@ -429,6 +437,7 @@ function ScoreSheet({
|
||||
players,
|
||||
myTurn,
|
||||
pending,
|
||||
rolling,
|
||||
onScore,
|
||||
pointer,
|
||||
}: {
|
||||
@@ -437,6 +446,8 @@ function ScoreSheet({
|
||||
players: Record<string, PublicUser>;
|
||||
myTurn: boolean;
|
||||
pending: boolean;
|
||||
/** Dice still tumbling: the points they make are not shown (or pickable) until they land. */
|
||||
rolling: boolean;
|
||||
onScore: (c: Category, points: number, viaMouse: boolean) => void;
|
||||
pointer: React.MutableRefObject<string>;
|
||||
}) {
|
||||
@@ -461,12 +472,12 @@ function ScoreSheet({
|
||||
const prev = v.current === p ? v.preview?.[c] : undefined;
|
||||
if (p === me && myTurn && v.rollsUsed > 0 && prev !== undefined) {
|
||||
const allowed = v.allowed.includes(c);
|
||||
const show = v.options.showPreview;
|
||||
const show = v.options.showPreview && !rolling;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`yt-cell${show && prev > 0 ? ' good' : ''}${show && prev === 0 ? ' zero' : ''}`}
|
||||
disabled={!allowed || pending}
|
||||
disabled={!allowed || pending || rolling}
|
||||
aria-label={`${catName(c, v.options.scoring)}에 ${show ? `${prev}점 ` : ''}기록하기${allowed ? '' : ' (지금은 넣을 수 없어요)'}`}
|
||||
onPointerDown={(e) => (pointer.current = e.pointerType)}
|
||||
onClick={(e) => {
|
||||
@@ -475,11 +486,11 @@ function ScoreSheet({
|
||||
onScore(c, prev, viaMouse);
|
||||
}}
|
||||
>
|
||||
{show ? prev : '기록'}
|
||||
{show ? prev : rolling ? '' : '기록'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
if (prev !== undefined && v.options.showPreview) return <span className="yt-ghost">{prev}</span>;
|
||||
if (prev !== undefined && v.options.showPreview && !rolling) return <span className="yt-ghost">{prev}</span>;
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
369
apps/web/src/games/yut/aug-icons/glyphs-a.tsx
Normal file
369
apps/web/src/games/yut/aug-icons/glyphs-a.tsx
Normal file
@@ -0,0 +1,369 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { AugId } from '@bg/games/yut/augments';
|
||||
import { C } from './palette';
|
||||
|
||||
/** A 4-point sparkle centred at (x, y), radius r. */
|
||||
const spark = (x: number, y: number, r: number) =>
|
||||
`M${x} ${y - r}Q${x} ${y} ${x + r} ${y}Q${x} ${y} ${x} ${y + r}Q${x} ${y} ${x - r} ${y}Q${x} ${y} ${x} ${y - r}Z`;
|
||||
|
||||
/** A spiky burst (n points) centred at (x, y) with outer radius r and inner radius ri. */
|
||||
const burst = (x: number, y: number, r: number, ri: number, n: number) =>
|
||||
Array.from({ length: n * 2 }, (_, i) => {
|
||||
const a = (i / (n * 2)) * Math.PI * 2 - Math.PI / 2;
|
||||
const d = i % 2 ? ri : r;
|
||||
return `${(x + Math.cos(a) * d).toFixed(1)},${(y + Math.sin(a) * d).toFixed(1)}`;
|
||||
}).join(' ');
|
||||
|
||||
/** Six wedges of the 돌림판, as path data. */
|
||||
const WHEEL = [C.r, C.w, C.b, C.w, C.y, C.w].map((fill, i) => {
|
||||
const a0 = ((i * 60 - 90) * Math.PI) / 180;
|
||||
const a1 = (((i + 1) * 60 - 90) * Math.PI) / 180;
|
||||
const pt = (a: number) => `${(24 + Math.cos(a) * 14).toFixed(2)} ${(27 + Math.sin(a) * 14).toFixed(2)}`;
|
||||
return { fill, d: `M24 27L${pt(a0)}A14 14 0 0 1 ${pt(a1)}Z` };
|
||||
});
|
||||
|
||||
export const GLYPHS_A: Partial<Record<AugId, ReactNode>> = {
|
||||
// 8톤 트럭: a white truck racing right, speed lines behind
|
||||
truck: (
|
||||
<g>
|
||||
<path d="M6 18h4M6 23h3M6 28h4" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".75" />
|
||||
<rect x="11" y="12" width="19" height="20" rx="1.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M30 18H36.5L41.5 24.5V32H30Z" fill={C.w} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M32.5 20.5H35.5L38.8 24.8H32.5Z" fill={C.b} stroke={C.k} strokeWidth="1.1" strokeLinejoin="round" />
|
||||
<text x="20.5" y="28" textAnchor="middle" fontSize="14" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.r}>8</text>
|
||||
<circle cx="17" cy="34" r="4.2" fill={C.k} />
|
||||
<circle cx="35" cy="34" r="4.2" fill={C.k} />
|
||||
<circle cx="17" cy="34" r="1.6" fill={C.gr} />
|
||||
<circle cx="35" cy="34" r="1.6" fill={C.gr} />
|
||||
</g>
|
||||
),
|
||||
// 3단 합체 필살기!!!: a stack of three pieces in front of a yellow explosion
|
||||
combo: (
|
||||
<g>
|
||||
<polygon points={burst(24, 24, 18, 11, 10)} fill={C.y} />
|
||||
<polygon points={burst(24, 24, 12, 7.5, 10)} fill={C.o} />
|
||||
<circle cx="24" cy="32" r="6" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="24" cy="24" r="6" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="24" cy="16" r="6" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
</g>
|
||||
),
|
||||
// 간택: a cat paw pressing down on an augment card
|
||||
chosen: (
|
||||
<g>
|
||||
<rect x="8" y="17" width="21" height="25" rx="3.5" transform="rotate(-12 18.5 29.5)" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d={spark(17, 32, 5)} fill={C.y} />
|
||||
<g transform="translate(-1.5 3)">
|
||||
<ellipse cx="30" cy="22" rx="8" ry="7" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<ellipse cx="22.5" cy="12.5" rx="3.2" ry="3.8" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="28.5" cy="8.8" rx="3.2" ry="3.8" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="35" cy="9.5" rx="3.2" ry="3.8" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="39.5" cy="15" rx="3" ry="3.6" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="30.5" cy="23" rx="4.5" ry="3.8" fill={C.pk} />
|
||||
<circle cx="23" cy="13" r="1.4" fill={C.pk} />
|
||||
<circle cx="28.5" cy="9.5" r="1.4" fill={C.pk} />
|
||||
<circle cx="34.8" cy="10.2" r="1.4" fill={C.pk} />
|
||||
<circle cx="39" cy="15.5" r="1.3" fill={C.pk} />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 게임 접어라: the 윷판 with its right half folding over the left, and a fold arrow
|
||||
fold: (
|
||||
<g>
|
||||
<rect x="7" y="16" width="17" height="25" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M7 16L24 28.5M7 41L24 28.5" stroke={C.k} strokeWidth="1.2" />
|
||||
<circle cx="7" cy="16" r="2" fill={C.k} />
|
||||
<circle cx="7" cy="41" r="2" fill={C.k} />
|
||||
<path d="M24 16L36 12.5V36.5L24 41Z" fill={C.b} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M24 16L36 36.5M24 41L36 12.5" stroke={C.k} strokeWidth="1" opacity=".6" />
|
||||
<path d="M39.5 16Q41 7.5 30 7.5Q21 7.5 17.5 11.5" stroke={C.w} strokeWidth="2.5" fill="none" strokeLinecap="round" />
|
||||
<path d="M13.5 9.5L16.5 15L20.5 10Z" fill={C.w} />
|
||||
</g>
|
||||
),
|
||||
// 고양이: a white cat face
|
||||
cat: (
|
||||
<g>
|
||||
<path d="M10 37C9 26 11 19 12.5 10.5L20 17.5Q24 16.5 28 17.5L35.5 10.5C37 19 39 26 38 37Q24 42.5 10 37Z" fill={C.w} />
|
||||
<path d="M14 14.5L18.5 18.5L14.8 21Z M34 14.5L29.5 18.5L33.2 21Z" fill={C.pk} />
|
||||
<ellipse cx="18.5" cy="27" rx="2.1" ry="2.8" fill={C.k} />
|
||||
<ellipse cx="29.5" cy="27" rx="2.1" ry="2.8" fill={C.k} />
|
||||
<path d="M22.4 31.2h3.2L24 33z" fill={C.pk} />
|
||||
<path d="M24 33v1.6M24 34.6q-2 1.6-3.6.4M24 34.6q2 1.6 3.6.4M8 30.5l7 1M8 34l7-.8M40 30.5l-7 1M40 34l-7-.8" stroke={C.k} strokeWidth="1.2" strokeLinecap="round" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 과유불급: six upright 윷가락 in a row, the last two (extra) ones yellow
|
||||
excess: (
|
||||
<g>
|
||||
{[0, 1, 2, 3, 4, 5].map((i) => (
|
||||
<rect key={i} x={7.6 + i * 5.6} y="10" width="4.4" height="28" rx="2.2" fill={i >= 4 ? C.y : C.wood} stroke={i >= 4 ? C.yd : C.woodd} strokeWidth="1.2" />
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 개돼지: a dog face and a pig face side by side
|
||||
doggy: (
|
||||
<g>
|
||||
<circle cx="15" cy="24" r="8.5" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<path d="M8 17.5C5 20 5.5 27 8 29.5L10.5 21.5Z M22 17.5C25 20 24.5 27 22 29.5L19.5 21.5Z" fill={C.wood} stroke={C.woodd} strokeWidth="1.1" strokeLinejoin="round" />
|
||||
<circle cx="12" cy="23" r="1.4" fill={C.k} />
|
||||
<circle cx="18" cy="23" r="1.4" fill={C.k} />
|
||||
<ellipse cx="15" cy="27.5" rx="2.2" ry="1.6" fill={C.k} />
|
||||
<path d="M15 29v1.5" stroke={C.k} strokeWidth="1.1" />
|
||||
<path d="M27 17L28.5 11.5L32.5 15.5Z M41 17L39.5 11.5L35.5 15.5Z" fill={C.pk} stroke={C.rd} strokeWidth="1.1" strokeLinejoin="round" />
|
||||
<circle cx="34" cy="25" r="8.5" fill={C.pk} stroke={C.rd} strokeWidth="1.4" />
|
||||
<circle cx="31" cy="22" r="1.4" fill={C.k} />
|
||||
<circle cx="37" cy="22" r="1.4" fill={C.k} />
|
||||
<ellipse cx="34" cy="28" rx="4" ry="2.8" fill={C.w} stroke={C.rd} strokeWidth="1.2" />
|
||||
<ellipse cx="32.6" cy="28" rx=".8" ry="1.1" fill={C.rd} />
|
||||
<ellipse cx="35.4" cy="28" rx=".8" ry="1.1" fill={C.rd} />
|
||||
</g>
|
||||
),
|
||||
// 거머리: a dark green leech latched onto another player's red piece
|
||||
leech: (
|
||||
<g>
|
||||
<circle cx="32" cy="16" r="7" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M9 37Q11 26 19 26Q25 26 27 21" stroke={C.k} strokeWidth="10" fill="none" strokeLinecap="round" />
|
||||
<path d="M9 37Q11 26 19 26Q25 26 27 21" stroke={C.gd} strokeWidth="7.4" fill="none" strokeLinecap="round" />
|
||||
<path d="M12.5 29.5l3 2.5M17 25.8l1 3.6M21.5 25.2l-.4 3.6" stroke={C.g} strokeWidth="1.3" strokeLinecap="round" />
|
||||
<circle cx="11" cy="35.5" r="1.3" fill={C.w} />
|
||||
<path d="M33 34l3.5-3M37 38l4-1.5M30 39l1.5-3.5" stroke={C.w} strokeWidth="1.8" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 나 누구게?: a grey piece with a big "?" above the four player colours
|
||||
whoami: (
|
||||
<g>
|
||||
<circle cx="24" cy="20.5" r="12.5" fill={C.gr} stroke={C.k} strokeWidth="1.8" />
|
||||
<text x="24" y="28.5" textAnchor="middle" fontSize="22" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.w}>?</text>
|
||||
{[C.r, C.b, C.g, C.y].map((f, i) => (
|
||||
<circle key={f} cx={12 + i * 8} cy="38" r="3.2" fill={f} stroke={C.k} strokeWidth="1.1" />
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 나만 아니면 돼~: a red piece blown up in a burst, my white piece safe and relieved below
|
||||
notme: (
|
||||
<g>
|
||||
<polygon points={burst(29, 19, 12.5, 7.5, 9)} fill={C.y} />
|
||||
<circle cx="29" cy="19" r="7" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M25.5 16.5l2.5 2.5M28 16.5l-2.5 2.5M30 16.5l2.5 2.5M32.5 16.5L30 19M27 22.5h4" stroke={C.k} strokeWidth="1.3" strokeLinecap="round" />
|
||||
<circle cx="15" cy="33" r="7.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M11.5 32q1.2-1.4 2.4 0M16.1 32q1.2-1.4 2.4 0M12.5 35.5q2.5 2.2 5 0" stroke={C.k} strokeWidth="1.3" fill="none" strokeLinecap="round" />
|
||||
<path d="M22.5 26.5q-1.6 2.6 0 3.4q1.6-.8 0-3.4Z" fill={C.b} stroke={C.bd} strokeWidth=".8" />
|
||||
</g>
|
||||
),
|
||||
// 내려: a ballot with a red down arrow going into a ballot box
|
||||
getoff: (
|
||||
<g>
|
||||
<rect x="16" y="6.5" width="16" height="19" rx="1.5" transform="rotate(8 24 16)" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M24.3 10v8.5M20.6 15.5l3.7 4.2l3.9-3.8" transform="rotate(8 24 16)" stroke={C.r} strokeWidth="2.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<rect x="8" y="22" width="32" height="19" rx="2" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<rect x="14" y="23.5" width="20" height="2.6" rx="1.3" fill={C.k} />
|
||||
<path d="M8 29.5H40" stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M19 35.5h10" stroke={C.gr} strokeWidth="2.4" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 도베르만: a black-and-tan doberman head with a gold dog coin
|
||||
doberman: (
|
||||
<g>
|
||||
<path d="M10 6L19 15L12 21Z M34 6L25 15L32 21Z" fill={C.k} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M12.5 10L16 14L13.3 16.5Z M31.5 10L28 14L30.7 16.5Z" fill={C.wood} />
|
||||
<ellipse cx="22" cy="22" rx="10.5" ry="9.5" fill={C.k} />
|
||||
<path d="M15.5 25Q22 21 28.5 25L27 35Q22 39 17 35Z" fill={C.wood} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<circle cx="18" cy="20" r="2" fill={C.w} />
|
||||
<circle cx="26" cy="20" r="2" fill={C.w} />
|
||||
<circle cx="18.3" cy="20.3" r="1" fill={C.k} />
|
||||
<circle cx="26.3" cy="20.3" r="1" fill={C.k} />
|
||||
<circle cx="18" cy="16.5" r="1.2" fill={C.wood} />
|
||||
<circle cx="26" cy="16.5" r="1.2" fill={C.wood} />
|
||||
<ellipse cx="22" cy="27.5" rx="3" ry="2.2" fill={C.k} />
|
||||
<path d="M22 29.5v2.5M19.5 33q2.5 1.5 5 0" stroke={C.k} strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
<circle cx="35" cy="34" r="6.5" fill={C.y} stroke={C.yd} strokeWidth="1.6" />
|
||||
<circle cx="35" cy="34" r="3.8" fill="none" stroke={C.yd} strokeWidth="1.2" />
|
||||
</g>
|
||||
),
|
||||
// 돌려돌려 돌림판: a spinning prize wheel with a pointer on top
|
||||
roulette: (
|
||||
<g>
|
||||
<path d="M7.5 22A17 17 0 0 1 12 14.5M40.5 32A17 17 0 0 1 36 39.5" stroke={C.w} strokeWidth="2" fill="none" strokeLinecap="round" opacity=".8" />
|
||||
{WHEEL.map((w) => (
|
||||
<path key={w.d} d={w.d} fill={w.fill} stroke={C.k} strokeWidth="1.1" strokeLinejoin="round" />
|
||||
))}
|
||||
<circle cx="24" cy="27" r="14" fill="none" stroke={C.k} strokeWidth="1.8" />
|
||||
<circle cx="24" cy="27" r="2.6" fill={C.k} />
|
||||
<path d="M19.5 6.5H28.5L24 15Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 명사수: a sniper scope's crosshair on a red piece
|
||||
sniper: (
|
||||
<g>
|
||||
<circle cx="24" cy="24" r="14.5" fill="none" stroke={C.w} strokeWidth="3" />
|
||||
<path d="M24 6.5V16M24 32V41.5M6.5 24H16M32 24H41.5" stroke={C.w} strokeWidth="2.6" strokeLinecap="round" />
|
||||
<circle cx="24" cy="24" r="6" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="24" cy="24" r="1.4" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 명탐정: a magnifying glass finding an augment card and crossing it out
|
||||
detective: (
|
||||
<g>
|
||||
<path d="M28.5 28.5L38.5 38.5" stroke={C.k} strokeWidth="8.5" strokeLinecap="round" />
|
||||
<path d="M28.5 28.5L38.5 38.5" stroke={C.wood} strokeWidth="5.5" strokeLinecap="round" />
|
||||
<circle cx="20.5" cy="20.5" r="12" fill={C.b} stroke={C.k} strokeWidth="1.4" />
|
||||
<circle cx="20.5" cy="20.5" r="10.5" fill={C.b} stroke={C.w} strokeWidth="2.6" />
|
||||
<rect x="15.5" y="13.5" width="10" height="14" rx="1.8" fill={C.w} stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M16.5 15.5L24.5 25.5M24.5 15.5L16.5 25.5" stroke={C.r} strokeWidth="2.4" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 모 아니면 도: a coin split in two, "모" on one half and "도" on the other
|
||||
moordo: (
|
||||
<g>
|
||||
<path d="M12.7 35.3A16 16 0 0 1 35.3 12.7Z" fill={C.w} />
|
||||
<path d="M12.7 35.3A16 16 0 0 0 35.3 12.7Z" fill={C.y} />
|
||||
<circle cx="24" cy="24" r="16" fill="none" stroke={C.k} strokeWidth="1.6" />
|
||||
<path d="M12.7 35.3L35.3 12.7" stroke={C.k} strokeWidth="1.6" />
|
||||
<text x="18" y="25" textAnchor="middle" fontSize="12.5" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.k}>모</text>
|
||||
<text x="30" y="36" textAnchor="middle" fontSize="12.5" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.k}>도</text>
|
||||
</g>
|
||||
),
|
||||
// 바둑: 바둑 grid lines, two white stones sandwiching two black stones
|
||||
baduk: (
|
||||
<g>
|
||||
<path d="M10.5 7V41M19.5 7V41M28.5 7V41M37.5 7V41M7 15H41M7 24H41M7 33H41" stroke={C.w} strokeWidth="1.2" opacity=".55" />
|
||||
{[10.5, 19.5, 28.5, 37.5].map((x, i) => (
|
||||
<circle key={x} cx={x} cy="24" r="4.6" fill={i === 0 || i === 3 ? C.w : C.k} stroke={C.k} strokeWidth="1.2" />
|
||||
))}
|
||||
<path d="M17.5 21.5l1.6-1M26.5 21.5l1.6-1" stroke={C.w} strokeWidth="1.2" strokeLinecap="round" opacity=".7" />
|
||||
</g>
|
||||
),
|
||||
// 배달: a delivery scooter with a red box (a star augment inside) on the back
|
||||
delivery: (
|
||||
<g>
|
||||
<path d="M6 22h3M6 27h4" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".75" />
|
||||
<rect x="10" y="11" width="15" height="13" rx="1.5" fill={C.r} stroke={C.k} strokeWidth="1.4" />
|
||||
<path d={spark(17.5, 17.5, 4.2)} fill={C.y} />
|
||||
<path d="M10 26H25Q28 26 29.5 29.5L31 33H14Q10 33 10 29.5Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<path d="M30 33L35 14M31.5 14H39" stroke={C.k} strokeWidth="2.2" strokeLinecap="round" />
|
||||
<circle cx="14.5" cy="35" r="4.5" fill={C.k} />
|
||||
<circle cx="35.5" cy="35" r="4.5" fill={C.k} />
|
||||
<circle cx="14.5" cy="35" r="1.7" fill={C.gr} />
|
||||
<circle cx="35.5" cy="35" r="1.7" fill={C.gr} />
|
||||
</g>
|
||||
),
|
||||
// 변환: 도깨비: a red 도깨비 face with yellow horns and fangs, holding a spiked club
|
||||
dokkaebi: (
|
||||
<g>
|
||||
<path d="M33 38L38.5 17" stroke={C.k} strokeWidth="3.6" strokeLinecap="round" />
|
||||
<path d="M33 38L38.5 17" stroke={C.wood} strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M36 21.5Q34 12 39 8Q44 12 41 22Z" fill={C.wood} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<circle cx="38.5" cy="12.5" r="1" fill={C.k} />
|
||||
<circle cx="39.2" cy="17" r="1" fill={C.k} />
|
||||
<path d="M12 18L9 7L18.5 14Z M28 18L31 7L21.5 14Z" fill={C.y} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<circle cx="20" cy="27" r="12" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M12.5 21.5l5 2M27.5 21.5l-5 2" stroke={C.k} strokeWidth="2" strokeLinecap="round" />
|
||||
<circle cx="15.5" cy="26" r="2.6" fill={C.w} />
|
||||
<circle cx="24.5" cy="26" r="2.6" fill={C.w} />
|
||||
<circle cx="16" cy="26.3" r="1.2" fill={C.k} />
|
||||
<circle cx="24" cy="26.3" r="1.2" fill={C.k} />
|
||||
<path d="M13.5 32.5Q20 36.5 26.5 32.5" stroke={C.k} strokeWidth="1.6" fill="none" strokeLinecap="round" />
|
||||
<path d="M15.5 33.3L16.5 30L17.8 33.9Z M24.5 33.3L23.5 30L22.2 33.9Z" fill={C.w} />
|
||||
</g>
|
||||
),
|
||||
// 변환: 선봉장: a piece carrying a red banner, with forward chevrons
|
||||
vanguard: (
|
||||
<g>
|
||||
<path d="M16 31V7" stroke={C.k} strokeWidth="3.4" strokeLinecap="round" />
|
||||
<path d="M16 31V7" stroke={C.wood} strokeWidth="1.8" strokeLinecap="round" />
|
||||
<path d="M17 8Q24 5 33 9.5Q27 13 33 18Q24 14 17 19Z" fill={C.r} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<circle cx="16" cy="34" r="7" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M27 27L32 32.5L27 38M34 27L39 32.5L34 38" stroke={C.y} strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 변환: 포: an octagonal 장기 piece with the red 包 (포) character
|
||||
cannon: (
|
||||
<g>
|
||||
<polygon points="38.8,30.1 30.1,38.8 17.9,38.8 9.2,30.1 9.2,17.9 17.9,9.2 30.1,9.2 38.8,17.9" fill={C.w} stroke={C.k} strokeWidth="1.6" strokeLinejoin="round" />
|
||||
<polygon points="35.5,28.8 28.8,35.5 19.2,35.5 12.5,28.8 12.5,19.2 19.2,12.5 28.8,12.5 35.5,19.2" fill="none" stroke={C.r} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<text x="24" y="30.5" textAnchor="middle" fontSize="17" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.r}>包</text>
|
||||
</g>
|
||||
),
|
||||
// 변환: 폰: a white chess pawn with a yellow forward step arrow
|
||||
pawn: (
|
||||
<g>
|
||||
<circle cx="21" cy="12.5" r="5.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M15.5 19.5H26.5L24.5 22.5C24.5 28 26 31 29 34H13C16 31 17.5 28 17.5 22.5Z" fill={C.w} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<rect x="10.5" y="33.5" width="21" height="6" rx="2" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M33 24H40M37 20.5L40.5 24L37 27.5" stroke={C.y} strokeWidth="2.8" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 사목: four pieces lined up on a diagonal, joined by a red line
|
||||
four: (
|
||||
<g>
|
||||
{[0, 1, 2, 3].flatMap((r) =>
|
||||
[0, 1, 2, 3].filter((c) => c !== 3 - r).map((c) => <circle key={`${r}${c}`} cx={11 + c * 8.7} cy={11 + r * 8.7} r="1.6" fill={C.w} opacity=".6" />),
|
||||
)}
|
||||
<path d="M8 40.1L40.1 8" stroke={C.r} strokeWidth="4.5" strokeLinecap="round" />
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<circle key={i} cx={11 + i * 8.7} cy={37.1 - i * 8.7} r="4.3" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 소 뒷걸음질: an ox head with horns, and a backward arrow
|
||||
ox: (
|
||||
<g>
|
||||
<path d="M17 16Q10 15 9.5 7.5Q14 12 19 12Z M33 16Q40 15 40.5 7.5Q36 12 31 12Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<ellipse cx="13.5" cy="20" rx="4" ry="2.5" transform="rotate(20 13.5 20)" fill={C.wood} stroke={C.k} strokeWidth="1.2" />
|
||||
<ellipse cx="36.5" cy="20" rx="4" ry="2.5" transform="rotate(-20 36.5 20)" fill={C.wood} stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M17 13H33Q34 22 32 29H18Q16 22 17 13Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<circle cx="20.5" cy="20" r="1.5" fill={C.k} />
|
||||
<circle cx="29.5" cy="20" r="1.5" fill={C.k} />
|
||||
<ellipse cx="25" cy="30" rx="8" ry="5.5" fill={C.pk} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="22" cy="30" rx="1.2" ry="1.7" fill={C.k} />
|
||||
<ellipse cx="28" cy="30" rx="1.2" ry="1.7" fill={C.k} />
|
||||
<path d="M17 39H7.5M11 35.5L7.5 39L11 42.5" stroke={C.w} strokeWidth="2.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 손은 눈보다 빠르다: a wide-open eye, and a 윷가락 whizzing past below it
|
||||
sleight: (
|
||||
<g>
|
||||
<path d="M7 16Q24 1 41 16Q24 31 7 16Z" fill={C.w} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<circle cx="24" cy="16" r="5.5" fill={C.bd} stroke={C.k} strokeWidth="1.2" />
|
||||
<circle cx="24" cy="16" r="2.4" fill={C.k} />
|
||||
<circle cx="25.8" cy="14.2" r="1.1" fill={C.w} />
|
||||
<rect x="17" y="31" width="24" height="6" rx="3" transform="rotate(-8 29 34)" fill={C.wood} stroke={C.woodd} strokeWidth="1.2" />
|
||||
<path d="M6.5 31.5h7M8 36.5h6.5M6.5 41h6" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".8" />
|
||||
</g>
|
||||
),
|
||||
// 시간 여행: a clock with a yellow counter-clockwise (rewind) arrow around it
|
||||
timetravel: (
|
||||
<g>
|
||||
<path d="M35.6 15.4A15 15 0 0 0 10 26" stroke={C.y} strokeWidth="3" fill="none" strokeLinecap="round" />
|
||||
<path d="M6.5 24H13.5L10 30Z" fill={C.y} />
|
||||
<circle cx="25" cy="27" r="11.5" fill={C.w} stroke={C.k} strokeWidth="1.6" />
|
||||
<path d="M25 27V20M25 27L30 30" stroke={C.k} strokeWidth="2" strokeLinecap="round" />
|
||||
<circle cx="25" cy="27" r="1.4" fill={C.k} />
|
||||
<path d="M25 16.5v1.6M25 35.9v1.6M14.5 27h1.6M33.9 27h1.6" stroke={C.k} strokeWidth="1.3" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 악보가 완성되었다!: a sheet of music with notes and a green "done" check
|
||||
score: (
|
||||
<g>
|
||||
<rect x="8.5" y="7" width="27" height="33" rx="2" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M11.5 14H32.5M11.5 17.5H32.5M11.5 21H32.5M11.5 24.5H32.5M11.5 28H32.5" stroke={C.gr} strokeWidth="1" />
|
||||
<ellipse cx="15.5" cy="26" rx="2.4" ry="1.8" transform="rotate(-20 15.5 26)" fill={C.k} />
|
||||
<ellipse cx="22.5" cy="22.5" rx="2.4" ry="1.8" transform="rotate(-20 22.5 22.5)" fill={C.k} />
|
||||
<ellipse cx="29" cy="19" rx="2.4" ry="1.8" transform="rotate(-20 29 19)" fill={C.k} />
|
||||
<path d="M17.6 25.4V12.5M24.6 21.9V11.5M31.1 18.4V10.5" stroke={C.k} strokeWidth="1.3" />
|
||||
<path d="M24.6 11.5L31.1 10.5" stroke={C.k} strokeWidth="2.4" />
|
||||
<circle cx="35" cy="35" r="6.5" fill={C.g} stroke={C.gd} strokeWidth="1.5" />
|
||||
<path d="M31.8 35l2.3 2.3L38.3 33" stroke={C.w} strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 안개: a piece peeking out from behind thick bands of fog
|
||||
fog: (
|
||||
<g>
|
||||
<circle cx="24" cy="18" r="7.5" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="21.3" cy="17" r="1.3" fill={C.k} />
|
||||
<circle cx="26.7" cy="17" r="1.3" fill={C.k} />
|
||||
<path d="M8 24.5H33" stroke={C.w} strokeWidth="6" strokeLinecap="round" opacity=".95" />
|
||||
<path d="M15 31.5H40" stroke={C.w} strokeWidth="6" strokeLinecap="round" opacity=".85" />
|
||||
<path d="M9 38.5H31" stroke={C.w} strokeWidth="5" strokeLinecap="round" opacity=".7" />
|
||||
<path d="M33 11.5H40M8 11.5h4" stroke={C.w} strokeWidth="3.5" strokeLinecap="round" opacity=".55" />
|
||||
</g>
|
||||
),
|
||||
};
|
||||
336
apps/web/src/games/yut/aug-icons/glyphs-b.tsx
Normal file
336
apps/web/src/games/yut/aug-icons/glyphs-b.tsx
Normal file
@@ -0,0 +1,336 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { AugId } from '@bg/games/yut/augments';
|
||||
import { C } from './palette';
|
||||
|
||||
/** A 4-point sparkle centred at (x, y), radius r. */
|
||||
const spark = (x: number, y: number, r: number) =>
|
||||
`M${x} ${y - r}Q${x} ${y} ${x + r} ${y}Q${x} ${y} ${x} ${y + r}Q${x} ${y} ${x - r} ${y}Q${x} ${y} ${x} ${y - r}Z`;
|
||||
|
||||
/** Shield outline centred on x = 24. */
|
||||
const SHIELD = 'M24 7L38.5 12.5V23.5C38.5 32.5 32 38.5 24 41.5C16 38.5 9.5 32.5 9.5 23.5V12.5Z';
|
||||
|
||||
/** Jagged speech-bubble burst for 이의있음! */
|
||||
const BURST = Array.from({ length: 20 }, (_, i) => {
|
||||
const a = (i / 20) * Math.PI * 2 - Math.PI / 2;
|
||||
const r = i % 2 ? 0.78 : 1;
|
||||
return `${(24 + Math.cos(a) * 17 * r).toFixed(1)},${(22 + Math.sin(a) * 14 * r).toFixed(1)}`;
|
||||
}).join(' ');
|
||||
|
||||
/** Pentagram points (radius 13.5 round 24,25), drawn in star order. */
|
||||
const STAR = [0, 2, 4, 1, 3]
|
||||
.map((k) => {
|
||||
const a = -Math.PI / 2 + (k * 2 * Math.PI) / 5;
|
||||
return `${(24 + Math.cos(a) * 13.5).toFixed(2)},${(25 + Math.sin(a) * 13.5).toFixed(2)}`;
|
||||
})
|
||||
.join(' ');
|
||||
|
||||
export const GLYPHS_B: Partial<Record<AugId, ReactNode>> = {
|
||||
// 알까기: a white piece flicked into a red piece that flies off the board edge
|
||||
alkkagi: (
|
||||
<g>
|
||||
<path d="M38 7V41" stroke={C.w} strokeWidth="2.5" strokeLinecap="round" strokeDasharray="3 3" />
|
||||
<path d="M6 31h6M7 36h7M8 26h4" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".75" />
|
||||
<circle cx="19" cy="31" r="6.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d={spark(26.5, 23.5, 5)} fill={C.y} />
|
||||
<circle cx="33" cy="15.5" r="5.5" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M39.5 9.5l2.5-2.5M40.5 14h2" stroke={C.w} strokeWidth="1.8" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 애묘인: a red heart with cat ears and a cat face
|
||||
catlover: (
|
||||
<g>
|
||||
<path d="M10.5 19L11.5 7.5L19.5 13.5Z M37.5 19L36.5 7.5L28.5 13.5Z" fill={C.r} stroke={C.rd} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M24 41C11 33 7 25 9.5 18.5C12 12 20 11.5 24 17C28 11.5 36 12 38.5 18.5C41 25 37 33 24 41Z" fill={C.r} stroke={C.rd} strokeWidth="1.2" />
|
||||
<ellipse cx="18.5" cy="24" rx="2" ry="2.6" fill={C.w} />
|
||||
<ellipse cx="29.5" cy="24" rx="2" ry="2.6" fill={C.w} />
|
||||
<path d="M22.5 28.5h3L24 30.2z" fill={C.pk} />
|
||||
<path d="M24 30.2q-1.8 1.8-3.4.6M24 30.2q1.8 1.8 3.4.6" stroke={C.w} strokeWidth="1.2" strokeLinecap="round" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 어부지리: a fishing rod with a fish on the hook
|
||||
fisherman: (
|
||||
<g>
|
||||
<path d="M8 41Q14 14 33 8" stroke={C.wood} strokeWidth="3" strokeLinecap="round" fill="none" />
|
||||
<path d="M8 41Q14 14 33 8" stroke={C.woodd} strokeWidth="1" strokeLinecap="round" fill="none" opacity=".6" />
|
||||
<path d="M33 8V20" stroke={C.w} strokeWidth="1.3" />
|
||||
<path d="M33 20v3.5a2 2 0 0 1-3.5 1.3" stroke={C.k} strokeWidth="1.4" fill="none" strokeLinecap="round" />
|
||||
<path d="M32 21.5C37.5 23.5 38.5 30 34 35L37.5 41H27.5L31 35C26.5 30 27 23.5 32 21.5Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<circle cx="32" cy="26" r="1.3" fill={C.k} />
|
||||
<path d="M29.5 30.5q2.5 1.5 5 0" stroke={C.k} strokeWidth="1" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 언제부터 착각한 거지?: an augment card growing cat ears, with dizzy swirl eyes
|
||||
illusion: (
|
||||
<g>
|
||||
<path d="M12 16L13 7L20 13Z M36 16L35 7L28 13Z" fill={C.w} />
|
||||
<path d="M13.8 13.5L14.2 10L17 12.5Z M34.2 13.5L33.8 10L31 12.5Z" fill={C.pk} />
|
||||
<rect x="10.5" y="12" width="27" height="29" rx="5" fill={C.w} />
|
||||
<path d="M17.6 26a1.4 1.4 0 1 1 1.4 1.4a2.8 2.8 0 1 1 2.8-2.8M30.4 26a1.4 1.4 0 1 0-1.4 1.4a2.8 2.8 0 1 0-2.8-2.8" stroke={C.k} strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
<path d="M21 34q3 2 6 0" stroke={C.k} strokeWidth="1.5" fill="none" strokeLinecap="round" />
|
||||
<path d={spark(38, 37, 4.5)} fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 윷을 잘 던져봐: a 윷가락 flying into a dizzy head
|
||||
throwyut: (
|
||||
<g>
|
||||
<path d="M6 10l6 3M6 16l5 1.5M10 6l3 5" stroke={C.w} strokeWidth="1.8" strokeLinecap="round" opacity=".75" />
|
||||
<rect x="15.5" y="6" width="5.5" height="22" rx="2.75" transform="rotate(-50 18 17)" fill={C.wood} stroke={C.woodd} strokeWidth="1.2" />
|
||||
<circle cx="31" cy="32" r="9" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M26.5 30l3 3M29.5 30l-3 3M32.5 30l3 3M35.5 30l-3 3" stroke={C.k} strokeWidth="1.4" strokeLinecap="round" />
|
||||
<path d="M29 37.5h4" stroke={C.k} strokeWidth="1.4" strokeLinecap="round" />
|
||||
<path d={spark(27, 21, 3.5)} fill={C.y} />
|
||||
<path d={spark(37.5, 20.5, 3)} fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 이도류: two 윷가락 crossed like swords, with sword grips
|
||||
dual: (
|
||||
<g>
|
||||
{[-35, 35].map((a) => (
|
||||
<g key={a} transform={`rotate(${a} 24 24)`}>
|
||||
<rect x="21.2" y="5.5" width="5.6" height="28" rx="2.8" fill={C.wood} stroke={C.woodd} strokeWidth="1.2" />
|
||||
<rect x="17.5" y="32" width="13" height="3.2" rx="1.6" fill={C.k} />
|
||||
<rect x="22.2" y="35" width="3.6" height="7" rx="1.6" fill={C.k} />
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 이의있음!: a jagged shout bubble with a big "!"
|
||||
objection: (
|
||||
<g>
|
||||
<path d="M14 31L8 42L22 34Z" fill={C.w} />
|
||||
<polygon points={BURST} fill={C.w} strokeLinejoin="round" />
|
||||
<text x="24" y="31" textAnchor="middle" fontSize="23" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.r}>!</text>
|
||||
</g>
|
||||
),
|
||||
// 자진모리 장단: a 장구 (hourglass drum) with its cords
|
||||
jajinmori: (
|
||||
<g>
|
||||
<path d="M10 13.5L24 21L38 13.5V34.5L24 27L10 34.5Z" fill={C.r} stroke={C.rd} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M10 15L17 32.5L24 21L31 32.5L38 15M10 33L17 15.5L24 27L31 15.5L38 33" stroke={C.w} strokeWidth="1.1" fill="none" opacity=".9" />
|
||||
<ellipse cx="10" cy="24" rx="3.6" ry="11.5" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="38" cy="24" rx="3.6" ry="11.5" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<rect x="22.8" y="20" width="2.4" height="8" fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 천마군림보 - 달걸음: a crescent moon inside a clockwise (reverse) arrow
|
||||
moonwalk: (
|
||||
<g>
|
||||
<path d="M10 24A14 14 0 1 1 17 36.1" stroke={C.w} strokeWidth="3" fill="none" strokeLinecap="round" />
|
||||
<path d="M11 30.5L19.6 32.5L13.8 39.6Z" fill={C.w} />
|
||||
<path d="M27 15A9 9 0 1 0 27 33A10.5 10.5 0 0 1 27 15Z" fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 천상의 보호막: a blue-and-white shield with heavenly sparkles
|
||||
shield: (
|
||||
<g>
|
||||
<path d={SHIELD} fill={C.w} />
|
||||
<path d="M24 11.5L34.5 15.5V23.5C34.5 30.5 30 35 24 37.5C18 35 13.5 30.5 13.5 23.5V15.5Z" fill={C.b} />
|
||||
<path d="M24 11.5V37.5M13.5 23.5H34.5" stroke={C.w} strokeWidth="2.2" />
|
||||
<path d={spark(39, 8.5, 4)} fill={C.y} />
|
||||
<path d={spark(8.5, 36, 3)} fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 크고 빨간 버튼: a big red push button on a grey base
|
||||
bigred: (
|
||||
<g>
|
||||
<ellipse cx="24" cy="36" rx="16" ry="5.5" fill={C.grd} />
|
||||
<rect x="8" y="30" width="32" height="6" fill={C.grd} />
|
||||
<ellipse cx="24" cy="30" rx="16" ry="5.5" fill={C.gr} stroke={C.grd} strokeWidth="1" />
|
||||
<path d="M12 30C12 15 36 15 36 30C36 33.5 12 33.5 12 30Z" fill={C.r} stroke={C.rd} strokeWidth="1.4" />
|
||||
<ellipse cx="19" cy="21.5" rx="3.2" ry="2" fill={C.w} opacity=".7" transform="rotate(-25 19 21.5)" />
|
||||
</g>
|
||||
),
|
||||
// 프랜드 실드: a white shield with a heart, two friends' pieces tucked behind it
|
||||
friendshield: (
|
||||
<g>
|
||||
<circle cx="11" cy="33" r="5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="37" cy="33" r="5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M24 8L35 12V22.5C35 30 30 35 24 38C18 35 13 30 13 22.5V12Z" fill={C.w} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M24 31C17.5 26.5 17 21.5 19 19.2C21 17 23.2 18 24 20C24.8 18 27 17 29 19.2C31 21.5 30.5 26.5 24 31Z" fill={C.r} />
|
||||
</g>
|
||||
),
|
||||
// 희생: a piece turned angel (halo and wings)
|
||||
sacrifice: (
|
||||
<g>
|
||||
<path d="M17 26C12 21 7 21 6 24C8 25 7 28 9 29C8 31 10 33 12 33C13 35 16 35 18 33Z" fill={C.w} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M31 26C36 21 41 21 42 24C40 25 41 28 39 29C40 31 38 33 36 33C35 35 32 35 30 33Z" fill={C.w} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<circle cx="24" cy="29" r="8.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M19.8 28.5q1.6 1.4 3.2 0M25 28.5q1.6 1.4 3.2 0" stroke={C.k} strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
<ellipse cx="24" cy="13.5" rx="7.5" ry="2.6" fill="none" stroke={C.y} strokeWidth="2.6" />
|
||||
</g>
|
||||
),
|
||||
// 히히 똥!: a grinning swirl of poop
|
||||
poop: (
|
||||
<g>
|
||||
<path d="M24 9C27 11 30 13 29 16.5C33 17 34.5 20.5 33 23C38 24 39.5 28 38 31C42.5 33 41 40 35 40H13C7 40 5.5 33 10 31C8.5 28 10 24 15 23C13.5 20.5 15 17 19 16.5C19 13 22 12.5 24 9Z" fill={C.wood} stroke={C.woodd} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<path d="M15 23Q24 25.5 33 23M10 31Q24 34 38 31" stroke={C.woodd} strokeWidth="1.2" fill="none" />
|
||||
<circle cx="19.5" cy="27" r="2.6" fill={C.w} />
|
||||
<circle cx="28.5" cy="27" r="2.6" fill={C.w} />
|
||||
<circle cx="20" cy="27.4" r="1.3" fill={C.k} />
|
||||
<circle cx="29" cy="27.4" r="1.3" fill={C.k} />
|
||||
<path d="M19 34.5Q24 38.5 29 34.5Z" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 등가교환: a level balance scale, a piece on one pan and a 윷가락 on the other
|
||||
equiv: (
|
||||
<g>
|
||||
<path d="M24 10V38M16 40H32M9 14H39" stroke={C.w} strokeWidth="2.5" strokeLinecap="round" />
|
||||
<circle cx="24" cy="10" r="2.5" fill={C.w} />
|
||||
<path d="M9 14L5.5 27M9 14L12.5 27M39 14L35.5 27M39 14L42.5 27" stroke={C.w} strokeWidth="1.1" />
|
||||
<path d="M5 27H13Q13 31 9 31Q5 31 5 27Z M35 27H43Q43 31 39 31Q35 31 35 27Z" fill={C.w} />
|
||||
<circle cx="9" cy="22.5" r="4.3" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<rect x="37.2" y="16.5" width="3.6" height="10.5" rx="1.8" fill={C.wood} stroke={C.woodd} strokeWidth="1" />
|
||||
</g>
|
||||
),
|
||||
// 말이오? 파티: a "?" item block
|
||||
party: (
|
||||
<g>
|
||||
<rect x="8.5" y="8.5" width="31" height="31" rx="3.5" fill={C.y} stroke={C.woodd} strokeWidth="2" />
|
||||
{[
|
||||
[12.5, 12.5],
|
||||
[35.5, 12.5],
|
||||
[12.5, 35.5],
|
||||
[35.5, 35.5],
|
||||
].map(([x, y]) => (
|
||||
<circle key={`${x}-${y}`} cx={x} cy={y} r="1.4" fill={C.woodd} />
|
||||
))}
|
||||
<text x="24" y="33.5" textAnchor="middle" fontSize="25" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.w} stroke={C.woodd} strokeWidth="1.5" paintOrder="stroke">?</text>
|
||||
</g>
|
||||
),
|
||||
// 스겜: a stopwatch with speed lines
|
||||
speedrun: (
|
||||
<g>
|
||||
<path d="M6 22h6M7 28h5M8 34h5" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".75" />
|
||||
<rect x="23.5" y="7" width="7" height="3.5" rx="1.2" fill={C.w} />
|
||||
<path d="M27 10.5v3M36 13.5l2.5-2.5" stroke={C.w} strokeWidth="2.6" strokeLinecap="round" />
|
||||
<circle cx="27" cy="27.5" r="13" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M27 17.5v2M37 27.5h-2M27 37.5v-2M17 27.5h2" stroke={C.k} strokeWidth="1.4" strokeLinecap="round" />
|
||||
<path d="M27 27.5L33 20" stroke={C.r} strokeWidth="2.4" strokeLinecap="round" />
|
||||
<circle cx="27" cy="27.5" r="1.8" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 시작 변환: 김첨지: a 인력거 (rickshaw) with its big wheel and long pull bars
|
||||
kim: (
|
||||
<g>
|
||||
<path d="M9 13Q11 8 19 8Q26 8 27 14V25H11Z" fill={C.r} stroke={C.rd} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M9 25H30L42 32" stroke={C.w} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" fill="none" />
|
||||
<circle cx="19" cy="32" r="8.5" fill="none" stroke={C.w} strokeWidth="2.6" />
|
||||
<path d="M19 23.5V40.5M10.5 32H27.5M13 26l12 12M25 26L13 38" stroke={C.w} strokeWidth="1.1" />
|
||||
<circle cx="19" cy="32" r="2" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 시작 변환: 중전마마: a piece wearing a golden crown
|
||||
queen: (
|
||||
<g>
|
||||
<circle cx="24" cy="31" r="9.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M11.5 22L13 9.5L18.5 15.5L24 7L29.5 15.5L35 9.5L36.5 22Z" fill={C.y} stroke={C.yd} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<rect x="11.5" y="19.5" width="25" height="3.5" rx="1" fill={C.yd} />
|
||||
<circle cx="24" cy="15" r="1.8" fill={C.r} />
|
||||
<circle cx="20.5" cy="31" r="1.4" fill={C.k} />
|
||||
<circle cx="27.5" cy="31" r="1.4" fill={C.k} />
|
||||
<path d="M21.5 35q2.5 1.6 5 0" stroke={C.k} strokeWidth="1.2" fill="none" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 웅녀: a bear face holding a garlic bulb
|
||||
bear: (
|
||||
<g>
|
||||
<circle cx="11.5" cy="12.5" r="4.5" fill={C.wood} stroke={C.woodd} strokeWidth="1.3" />
|
||||
<circle cx="30.5" cy="12.5" r="4.5" fill={C.wood} stroke={C.woodd} strokeWidth="1.3" />
|
||||
<circle cx="21" cy="23" r="12" fill={C.wood} stroke={C.woodd} strokeWidth="1.3" />
|
||||
<ellipse cx="21" cy="27.5" rx="5.5" ry="4.2" fill={C.w} opacity=".85" />
|
||||
<ellipse cx="21" cy="25.6" rx="2" ry="1.4" fill={C.k} />
|
||||
<circle cx="16.5" cy="20.5" r="1.4" fill={C.k} />
|
||||
<circle cx="25.5" cy="20.5" r="1.4" fill={C.k} />
|
||||
<path d="M35 27.5C35 30 32 31 31 34.5C30 38.5 33 41.5 36 41.5C39 41.5 42 38.5 41 34.5C40 31 37 30 37 27.5Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<path d="M36 25v3M36 32.5v8.5M33.5 34q0 5 2.5 7M38.5 34q0 5-2.5 7" stroke={C.k} strokeWidth="0.9" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 이리 오너라 업고 놀자: a tall tower of four stacked pieces
|
||||
piggyback: (
|
||||
<g>
|
||||
{[35, 27.5, 20, 12.5].map((y) => (
|
||||
<g key={y}>
|
||||
<path d={`M13 ${y}V${y + 4}A11 4 0 0 0 35 ${y + 4}V${y}`} fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="24" cy={y} rx="11" ry="4" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
</g>
|
||||
))}
|
||||
<circle cx="21" cy="12" r="1.1" fill={C.k} />
|
||||
<circle cx="27" cy="12" r="1.1" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 짐덩이와 복덩이: a red 복주머니 (lucky pouch) with a golden tie
|
||||
burden: (
|
||||
<g>
|
||||
<path d="M18 17C9 21 7.5 33 12 38C15 41 33 41 36 38C40.5 33 39 21 30 17Z" fill={C.r} stroke={C.rd} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<path d="M18 17L14.5 9.5Q19 11 21 8Q24 11 27 8Q29 11 33.5 9.5L30 17Z" fill={C.r} stroke={C.rd} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<rect x="16.5" y="15.5" width="15" height="3.5" rx="1.75" fill={C.y} stroke={C.yd} strokeWidth="1" />
|
||||
<path d="M22 19L19 26M26 19L29 26" stroke={C.y} strokeWidth="2" strokeLinecap="round" />
|
||||
<circle cx="24" cy="30.5" r="5.5" fill="none" stroke={C.y} strokeWidth="2" />
|
||||
<path d="M24 26.5V34.5M20 30.5H28" stroke={C.y} strokeWidth="1.6" />
|
||||
</g>
|
||||
),
|
||||
// 천상천하 유아독존: a single piece with golden rays all round it
|
||||
alone: (
|
||||
<g>
|
||||
{Array.from({ length: 12 }, (_, i) => {
|
||||
const a = (i * Math.PI) / 6;
|
||||
const r1 = 12.5;
|
||||
const r2 = i % 2 ? 16 : 18;
|
||||
return (
|
||||
<line key={i} x1={24 + Math.cos(a) * r1} y1={24 + Math.sin(a) * r1} x2={24 + Math.cos(a) * r2} y2={24 + Math.sin(a) * r2} stroke={C.y} strokeWidth="2.6" strokeLinecap="round" />
|
||||
);
|
||||
})}
|
||||
<circle cx="24" cy="24" r="9" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M24 26.5V19.5" stroke={C.k} strokeWidth="2.2" strokeLinecap="round" />
|
||||
<circle cx="24" cy="28.8" r="1.4" fill={C.k} />
|
||||
</g>
|
||||
),
|
||||
// 777: a slot-machine window showing 7 7 7
|
||||
triple7: (
|
||||
<g>
|
||||
<rect x="6.5" y="12" width="35" height="24" rx="4" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M18.2 12.8V35.2M29.8 12.8V35.2" stroke={C.gr} strokeWidth="1.2" />
|
||||
{[12.5, 24, 35.5].map((x) => (
|
||||
<text key={x} x={x} y="31" textAnchor="middle" fontSize="18" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.r}>7</text>
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 나만 친구 없어: a lonely crying piece
|
||||
nofriends: (
|
||||
<g>
|
||||
<circle cx="24" cy="25" r="14" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M16 20.5l4 1.5M32 20.5l-4 1.5" stroke={C.k} strokeWidth="1.5" strokeLinecap="round" />
|
||||
<circle cx="19" cy="25" r="1.6" fill={C.k} />
|
||||
<circle cx="29" cy="25" r="1.6" fill={C.k} />
|
||||
<path d="M19 33.5Q24 29.5 29 33.5" stroke={C.k} strokeWidth="1.6" fill="none" strokeLinecap="round" />
|
||||
<path d="M18 28.5C16.5 31.5 15.5 33 15.5 34.3a2.5 2.5 0 0 0 5 0C20.5 33 19.5 31.5 18 28.5Z" fill={C.b} stroke={C.bd} strokeWidth="1" />
|
||||
</g>
|
||||
),
|
||||
// 마신 소환: a glowing summoning circle with a pentagram
|
||||
summon: (
|
||||
<g>
|
||||
<circle cx="24" cy="25" r="16.5" fill={C.pd} stroke={C.w} strokeWidth="2.2" />
|
||||
<circle cx="24" cy="25" r="13.5" fill="none" stroke={C.p} strokeWidth="1" />
|
||||
<polygon points={STAR} fill="none" stroke={C.w} strokeWidth="1.8" strokeLinejoin="round" />
|
||||
<circle cx="24" cy="25.5" r="3" fill={C.r} />
|
||||
</g>
|
||||
),
|
||||
// 무신정변: a raised sword over four captured pieces
|
||||
coup: (
|
||||
<g>
|
||||
<path d="M24 5.5L27 10V27H21V10Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<path d="M24 10V26" stroke={C.gr} strokeWidth="1" />
|
||||
<rect x="15" y="27" width="18" height="3.5" rx="1.5" fill={C.yd} stroke={C.woodd} strokeWidth="1" />
|
||||
<rect x="22" y="30.5" width="4" height="6.5" fill={C.woodd} />
|
||||
<circle cx="24" cy="38.5" r="2" fill={C.yd} />
|
||||
{[
|
||||
[9, 35, C.r],
|
||||
[13, 41, C.b],
|
||||
[35, 41, C.g],
|
||||
[39, 35, C.y],
|
||||
].map(([x, y, c]) => (
|
||||
<circle key={`${x}`} cx={x as number} cy={y as number} r="3.5" fill={c as string} stroke={C.k} strokeWidth="1.2" />
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
};
|
||||
350
apps/web/src/games/yut/aug-icons/glyphs-c.tsx
Normal file
350
apps/web/src/games/yut/aug-icons/glyphs-c.tsx
Normal file
@@ -0,0 +1,350 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { AugId } from '@bg/games/yut/augments';
|
||||
import { C } from './palette';
|
||||
|
||||
/** Heart path centred on (x, y), half-width s. */
|
||||
const heart = (x: number, y: number, s: number) =>
|
||||
`M${x} ${y + s * 0.95}C${x - s * 0.3} ${y + s * 0.6} ${x - s} ${y + s * 0.15} ${x - s} ${y - s * 0.3}A${s * 0.5} ${s * 0.5} 0 0 1 ${x} ${y - s * 0.55}A${s * 0.5} ${s * 0.5} 0 0 1 ${x + s} ${y - s * 0.3}C${x + s} ${y + s * 0.15} ${x + s * 0.3} ${y + s * 0.6} ${x} ${y + s * 0.95}Z`;
|
||||
|
||||
/** An upright sword with its tip at (24, 6) and pommel at (24, 41). */
|
||||
const sword = (
|
||||
<>
|
||||
<path d="M21.8 31V10.5L24 6L26.2 10.5V31Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<rect x="17.5" y="30.5" width="13" height="3.4" rx="1.7" fill={C.wood} stroke={C.woodd} strokeWidth="1.2" />
|
||||
<rect x="22.4" y="33.8" width="3.2" height="5.6" fill={C.woodd} />
|
||||
<circle cx="24" cy="40.6" r="2" fill={C.wood} stroke={C.woodd} strokeWidth="1.1" />
|
||||
</>
|
||||
);
|
||||
|
||||
export const GLYPHS_C: Partial<Record<AugId, ReactNode>> = {
|
||||
// 역모: a crown with a dagger stabbed into it
|
||||
treason: (
|
||||
<g>
|
||||
<path d="M8.5 37L10 18.5L17 25.5L22.5 14L28 25.5L35 18.5L36.5 37Z" fill={C.y} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<circle cx="10" cy="17.5" r="2" fill={C.y} stroke={C.k} strokeWidth="1.2" />
|
||||
<circle cx="22.5" cy="13" r="2" fill={C.y} stroke={C.k} strokeWidth="1.2" />
|
||||
<circle cx="35" cy="17.5" r="2" fill={C.y} stroke={C.k} strokeWidth="1.2" />
|
||||
<circle cx="22.5" cy="31" r="2.2" fill={C.r} stroke={C.k} strokeWidth="1" />
|
||||
<g transform="rotate(35 33 24)">
|
||||
<path d="M31 30V14.5L33 10L35 14.5V30Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<rect x="28" y="29.5" width="10" height="3" rx="1.5" fill={C.k} />
|
||||
<rect x="31.5" y="32.5" width="3" height="7" rx="1.2" fill={C.rd} stroke={C.k} strokeWidth="1" />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 잠깐!: a white "stop" palm on a red stop-sign octagon
|
||||
wait: (
|
||||
<g>
|
||||
<polygon points="17,6.5 31,6.5 41.5,17 41.5,31 31,41.5 17,41.5 6.5,31 6.5,17" fill={C.r} stroke={C.w} strokeWidth="2" strokeLinejoin="round" />
|
||||
<g fill={C.w} stroke={C.k} strokeWidth="1.3">
|
||||
<rect x="9.5" y="22" width="5" height="11" rx="2.5" transform="rotate(-35 12 30)" />
|
||||
<rect x="15.2" y="14" width="4.4" height="14" rx="2.2" />
|
||||
<rect x="19.6" y="11" width="4.4" height="16" rx="2.2" />
|
||||
<rect x="24" y="11.5" width="4.4" height="16" rx="2.2" />
|
||||
<rect x="28.4" y="14.5" width="4.4" height="14" rx="2.2" />
|
||||
<path d="M15.2 24H32.8V31Q32.8 37.5 24 37.5Q15.2 37.5 15.2 31Z" />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 평화 협정: a peace sign
|
||||
peace: (
|
||||
<g fill="none" stroke={C.w} strokeWidth="4" strokeLinecap="round">
|
||||
<circle cx="24" cy="24" r="15" />
|
||||
<path d="M24 9.5V38.5M24 24L13.5 34.5M24 24L34.5 34.5" />
|
||||
</g>
|
||||
),
|
||||
// 계획대로: a clipboard listing everyone in order, all ticked
|
||||
plan: (
|
||||
<g>
|
||||
<rect x="10.5" y="9" width="27" height="33" rx="3" fill={C.wood} stroke={C.woodd} strokeWidth="1.4" />
|
||||
<rect x="13.5" y="13" width="21" height="26" rx="1.5" fill={C.w} />
|
||||
<rect x="18.5" y="6.5" width="11" height="5.5" rx="2" fill={C.gr} stroke={C.k} strokeWidth="1.3" />
|
||||
{([C.y, C.r, C.b] as const).map((c, i) => (
|
||||
<g key={c}>
|
||||
<circle cx="18.5" cy={19 + i * 7} r="2.6" fill={c} stroke={C.k} strokeWidth="1.1" />
|
||||
<path d={`M24 ${19 + i * 7}l2.3 2.3l4.5-4.8`} fill="none" stroke={C.gd} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 나에게 윷놀이는 "살인"이다: three life hearts (one lost) over a knife
|
||||
murder: (
|
||||
<g>
|
||||
<path d={heart(12.5, 14, 5)} fill={C.r} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d={heart(24, 14, 5)} fill={C.r} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d={heart(35.5, 14, 5)} fill={C.gr} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d="M19 26.5H36Q42 26.5 42 29Q36 34 19 34Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
<rect x="6" y="27" width="13.5" height="6.5" rx="2.5" fill={C.k} />
|
||||
<circle cx="10" cy="30.2" r="1" fill={C.gr} />
|
||||
<circle cx="15" cy="30.2" r="1" fill={C.gr} />
|
||||
<path d="M37.5 35.5q1.5 2.5 0 4q-1.5-1.5 0-4Z" fill={C.r} />
|
||||
</g>
|
||||
),
|
||||
// 네크로맨서: a skull with glowing green eyes and rising green sparks
|
||||
necro: (
|
||||
<g>
|
||||
<path d="M12 21.5A12 12 0 0 1 36 21.5Q36 27 32 30V36.5Q32 39 29.5 39H18.5Q16 39 16 36.5V30Q12 27 12 21.5Z" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<ellipse cx="19.3" cy="23.5" rx="3.6" ry="3.9" fill={C.k} />
|
||||
<ellipse cx="28.7" cy="23.5" rx="3.6" ry="3.9" fill={C.k} />
|
||||
<circle cx="19.3" cy="23.8" r="1.9" fill={C.g} />
|
||||
<circle cx="28.7" cy="23.8" r="1.9" fill={C.g} />
|
||||
<path d="M22.4 31.5L24 28.5L25.6 31.5Z" fill={C.k} />
|
||||
<path d="M20.5 34.5V39M24 34.5V39M27.5 34.5V39" stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M7.5 15l1.2-3l1.2 3l3 1.2l-3 1.2l-1.2 3l-1.2-3l-3-1.2Z M38.5 9l1-2.5l1 2.5l2.5 1l-2.5 1l-1 2.5l-1-2.5l-2.5-1Z" fill={C.g} />
|
||||
</g>
|
||||
),
|
||||
// 독이 든 성배: a golden goblet bubbling green poison, skull on the cup
|
||||
poison: (
|
||||
<g>
|
||||
<path d="M11.5 13H36.5Q36.5 28.5 24 29.5Q11.5 28.5 11.5 13Z" fill={C.y} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<ellipse cx="24" cy="13" rx="12.5" ry="3" fill={C.g} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M14.5 13.5q0 4.5 1.5 6.5" fill="none" stroke={C.g} strokeWidth="2.2" strokeLinecap="round" />
|
||||
<circle cx="20" cy="8" r="2.4" fill={C.g} stroke={C.k} strokeWidth="1" />
|
||||
<circle cx="27.5" cy="6.8" r="1.7" fill={C.g} stroke={C.k} strokeWidth="1" />
|
||||
<circle cx="24" cy="20.5" r="4" fill={C.w} stroke={C.k} strokeWidth="1.1" />
|
||||
<circle cx="22.5" cy="20.2" r="1.1" fill={C.k} />
|
||||
<circle cx="25.5" cy="20.2" r="1.1" fill={C.k} />
|
||||
<rect x="22" y="29" width="4" height="6.5" fill={C.yd} stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M15 40.5Q15 35.5 24 35.5Q33 35.5 33 40.5Z" fill={C.y} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 동메달도 잘한 거야: a bronze medal with a big 3 on a ribbon
|
||||
bronze: (
|
||||
<g>
|
||||
<path d="M12.5 6.5H20.5L27 21L21 24Z" fill={C.r} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<path d="M35.5 6.5H27.5L21 21L27 24Z" fill={C.b} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<circle cx="24" cy="30" r="11.5" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<circle cx="24" cy="30" r="8.6" fill={C.o} stroke={C.woodd} strokeWidth="1.2" />
|
||||
<text x="24" y="35.2" textAnchor="middle" fontSize="15" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.k}>3</text>
|
||||
</g>
|
||||
),
|
||||
// 라스트 댄스: a pair of beamed music notes with a sparkle
|
||||
lastdance: (
|
||||
<g>
|
||||
<path d="M17.5 33V13.5L36.5 8.5V28.5" fill="none" stroke={C.w} strokeWidth="3" strokeLinejoin="round" />
|
||||
<path d="M17.5 12L36.5 7V13L17.5 18Z" fill={C.w} />
|
||||
<ellipse cx="13.5" cy="34" rx="5.2" ry="4" transform="rotate(-22 13.5 34)" fill={C.w} stroke={C.k} strokeWidth="1.3" />
|
||||
<ellipse cx="32.5" cy="29.5" rx="5.2" ry="4" transform="rotate(-22 32.5 29.5)" fill={C.w} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d="M38 38.5l1-2.5l1 2.5l2.5 1l-2.5 1l-1 2.5l-1-2.5l-2.5-1Z" fill={C.y} />
|
||||
<path d="M8.5 13l.9-2.2l.9 2.2l2.2.9l-2.2.9l-.9 2.2l-.9-2.2l-2.2-.9Z" fill={C.y} />
|
||||
</g>
|
||||
),
|
||||
// 메아리의 형상: a piece sending out echo waves on both sides
|
||||
echo: (
|
||||
<g fill="none" stroke={C.w} strokeLinecap="round">
|
||||
<circle cx="24" cy="24" r="6" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M32.5 16.5A11 11 0 0 1 32.5 31.5M15.5 16.5A11 11 0 0 0 15.5 31.5" strokeWidth="3" />
|
||||
<path d="M37 11.5A17.5 17.5 0 0 1 37 36.5M11 11.5A17.5 17.5 0 0 0 11 36.5" strokeWidth="3" opacity=".55" />
|
||||
</g>
|
||||
),
|
||||
// 변환: 마라토너: a running figure with speed lines
|
||||
marathon: (
|
||||
<g fill="none" stroke={C.w} strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="30" cy="10.5" r="4.2" fill={C.w} stroke="none" />
|
||||
<path d="M27.5 16.5L23 27.5" strokeWidth="4.2" />
|
||||
<path d="M26.5 18L19.5 21L16.5 17M26.5 18L32 23.5L37 21" strokeWidth="3.2" />
|
||||
<path d="M23 27.5L30 32L28.5 40M23 27.5L18.5 34.5L11 34" strokeWidth="3.6" />
|
||||
<path d="M7 16H13M6.5 22.5H11.5M8 29H13" strokeWidth="2" opacity=".7" />
|
||||
</g>
|
||||
),
|
||||
// 승부다!: two crossed swords
|
||||
duel: (
|
||||
<g>
|
||||
<g transform="rotate(-42 24 24)">{sword}</g>
|
||||
<g transform="rotate(42 24 24)">{sword}</g>
|
||||
</g>
|
||||
),
|
||||
// 역전 찬스: three fanned mystery cards
|
||||
comeback: (
|
||||
<g>
|
||||
{[-22, 22, 0].map((a) => (
|
||||
<g key={a} transform={`rotate(${a} 24 40)`}>
|
||||
<rect x="16.5" y="10" width="15" height="21" rx="2.5" fill={C.w} stroke={C.k} strokeWidth="1.4" />
|
||||
<text x="24" y="26.5" textAnchor="middle" fontSize="14" fontWeight="900" fontFamily="system-ui, sans-serif" fill={a === 0 ? C.pd : C.p}>?</text>
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 영역 전개: a stack of pieces sealed under a barrier dome
|
||||
domain: (
|
||||
<g>
|
||||
<path d="M6.5 37A17.5 17.5 0 0 1 41.5 37Z" fill={C.w} fillOpacity=".25" stroke={C.w} strokeWidth="2.5" strokeLinejoin="round" />
|
||||
<path d="M12.5 37A11.5 11.5 0 0 1 35.5 37" fill="none" stroke={C.w} strokeWidth="1.4" strokeDasharray="2.5 2.5" />
|
||||
<path d="M6 37H42" stroke={C.w} strokeWidth="2.5" strokeLinecap="round" />
|
||||
<circle cx="24" cy="32" r="5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="24" cy="27" r="5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M24 8.5V13M15 12l2 3.5M33 12l-2 3.5" stroke={C.y} strokeWidth="2" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 취~소: a trophy under a red "no" sign
|
||||
cancel: (
|
||||
<g>
|
||||
<path d="M16 12.5Q10 12.5 10 17.5Q10 22 17 23M32 12.5Q38 12.5 38 17.5Q38 22 31 23" fill="none" stroke={C.k} strokeWidth="1.8" />
|
||||
<path d="M16 10H32V18Q32 27 24 27Q16 27 16 18Z" fill={C.y} stroke={C.k} strokeWidth="1.5" />
|
||||
<rect x="22" y="26.5" width="4" height="5" fill={C.yd} stroke={C.k} strokeWidth="1.2" />
|
||||
<rect x="17" y="31.5" width="14" height="5" rx="1.5" fill={C.y} stroke={C.k} strokeWidth="1.5" />
|
||||
<g fill="none" strokeLinecap="round">
|
||||
<circle cx="24" cy="24" r="16" stroke={C.w} strokeWidth="6.5" />
|
||||
<path d="M12.7 12.7L35.3 35.3" stroke={C.w} strokeWidth="6.5" />
|
||||
<circle cx="24" cy="24" r="16" stroke={C.r} strokeWidth="3.8" />
|
||||
<path d="M12.7 12.7L35.3 35.3" stroke={C.r} strokeWidth="3.8" />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 카니발리즘: a white piece with a gaping mouth about to eat another white piece
|
||||
cannibal: (
|
||||
<g>
|
||||
<path d="M21 24L32.3 17.5A13 13 0 1 0 32.3 30.5Z" fill={C.w} stroke={C.k} strokeWidth="1.5" strokeLinejoin="round" />
|
||||
<circle cx="19" cy="17.5" r="1.9" fill={C.k} />
|
||||
<path d="M27 21.2l1.3 2.3l1.3-3M27 26.8l1.3-2.3l1.3 3" fill={C.w} stroke={C.k} strokeWidth=".9" strokeLinejoin="round" />
|
||||
<circle cx="37" cy="24" r="4.8" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M35.3 23.3h.1M38.7 23.3h.1" stroke={C.k} strokeWidth="1.6" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 순간이동: a piece jumping from a blue portal to an orange one
|
||||
teleport: (
|
||||
<g>
|
||||
<ellipse cx="11" cy="30" rx="4.5" ry="10" fill={C.b} stroke={C.w} strokeWidth="2" />
|
||||
<ellipse cx="37" cy="30" rx="4.5" ry="10" fill={C.o} stroke={C.w} strokeWidth="2" />
|
||||
<path d="M13 17Q24 2 34 15" fill="none" stroke={C.w} strokeWidth="2.4" strokeDasharray="3 3" strokeLinecap="round" />
|
||||
<path d="M30.5 15.5L35 17L35.8 12.3" fill="none" stroke={C.w} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<circle cx="11" cy="30" r="4" fill={C.w} opacity=".45" />
|
||||
<circle cx="34" cy="30" r="5.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
</g>
|
||||
),
|
||||
// 지름길 달인: the board with a bold arrow cutting across the diagonal
|
||||
shortcut: (
|
||||
<g>
|
||||
<g fill="none" stroke={C.w} strokeWidth="2" opacity=".55">
|
||||
<rect x="8.5" y="8.5" width="31" height="31" rx="1" />
|
||||
<path d="M8.5 8.5L39.5 39.5" />
|
||||
</g>
|
||||
<g fill={C.w}>
|
||||
{[[8.5, 8.5], [39.5, 8.5], [8.5, 39.5], [39.5, 39.5], [24, 24]].map(([x, y]) => (
|
||||
<circle key={`${x}-${y}`} cx={x} cy={y} r="2.6" />
|
||||
))}
|
||||
</g>
|
||||
<path d="M37 11L13.5 34.5" stroke={C.y} strokeWidth="4.5" strokeLinecap="round" />
|
||||
<path d="M11 24.5V37H23.5" fill="none" stroke={C.y} strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 거북이 등껍질: a turtle seen from above, big patterned shell
|
||||
turtle: (
|
||||
<g>
|
||||
<g fill={C.gd} stroke={C.k} strokeWidth="1.3">
|
||||
<circle cx="24" cy="9.5" r="4.2" />
|
||||
<ellipse cx="12" cy="17" rx="3.5" ry="4.5" transform="rotate(-45 12 17)" />
|
||||
<ellipse cx="36" cy="17" rx="3.5" ry="4.5" transform="rotate(45 36 17)" />
|
||||
<ellipse cx="12" cy="35" rx="3.5" ry="4.5" transform="rotate(45 12 35)" />
|
||||
<ellipse cx="36" cy="35" rx="3.5" ry="4.5" transform="rotate(-45 36 35)" />
|
||||
<path d="M22 38L24 42.5L26 38Z" />
|
||||
</g>
|
||||
<circle cx="22.3" cy="8.5" r=".9" fill={C.k} />
|
||||
<circle cx="25.7" cy="8.5" r=".9" fill={C.k} />
|
||||
<ellipse cx="24" cy="26" rx="12.5" ry="13" fill={C.g} stroke={C.k} strokeWidth="1.5" />
|
||||
<g fill="none" stroke={C.gd} strokeWidth="1.6" strokeLinejoin="round">
|
||||
<polygon points="24,20.5 28.8,23.3 28.8,28.7 24,31.5 19.2,28.7 19.2,23.3" />
|
||||
<path d="M24 20.5V13.5M28.8 23.3L35 19.5M28.8 28.7L35 32.5M24 31.5V38.5M19.2 28.7L13 32.5M19.2 23.3L13 19.5" />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 복수의 칼날: a dagger inside a red "comes back around" arrow
|
||||
revenge: (
|
||||
<g>
|
||||
<path d="M36.5 15.5A14.5 14.5 0 1 0 38.5 27" fill="none" stroke={C.r} strokeWidth="3.6" strokeLinecap="round" />
|
||||
<path d="M31.5 13.5L38.5 16.5L39.3 9" fill="none" stroke={C.r} strokeWidth="3.6" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<g transform="rotate(40 24 24)">
|
||||
<path d="M21.8 27.5V12L24 7.5L26.2 12V27.5Z" fill={C.w} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<rect x="18.5" y="27" width="11" height="3" rx="1.5" fill={C.k} />
|
||||
<rect x="22.4" y="30" width="3.2" height="7" rx="1.2" fill={C.woodd} stroke={C.k} strokeWidth="1" />
|
||||
</g>
|
||||
</g>
|
||||
),
|
||||
// 손버릇: a burglar face with a black eye mask
|
||||
thief: (
|
||||
<g>
|
||||
<circle cx="24" cy="26" r="14" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M10.2 23.5A14 14 0 0 1 37.8 23.5Q37 13 24 11.5Q11 13 10.2 23.5Z" fill={C.k} />
|
||||
<path d="M8 24Q24 18 40 24L39 30Q24 25.5 9 30Z" fill={C.k} />
|
||||
<ellipse cx="18.5" cy="25.5" rx="3" ry="2.3" fill={C.w} />
|
||||
<ellipse cx="29.5" cy="25.5" rx="3" ry="2.3" fill={C.w} />
|
||||
<circle cx="19.2" cy="25.6" r="1.2" fill={C.k} />
|
||||
<circle cx="30.2" cy="25.6" r="1.2" fill={C.k} />
|
||||
<path d="M19 33.5Q24 37 29.5 32.5" fill="none" stroke={C.k} strokeWidth="1.6" strokeLinecap="round" />
|
||||
<path d="M10 11Q24 3 38 11" fill="none" stroke={C.r} strokeWidth="3" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 지뢰 매설: a spiked mine with a red light, half-buried in the ground
|
||||
mine: (
|
||||
<g>
|
||||
<g stroke={C.k} strokeWidth="3" strokeLinecap="round">
|
||||
{[0, 45, 90, 135, 180, 225, 270, 315].map((a) => (
|
||||
<path key={a} d="M24 11V14" transform={`rotate(${a} 24 25)`} />
|
||||
))}
|
||||
</g>
|
||||
<circle cx="24" cy="25" r="10.5" fill={C.k} />
|
||||
<path d="M17.5 22A7 7 0 0 1 22 17.5" fill="none" stroke={C.w} strokeWidth="2" strokeLinecap="round" opacity=".7" />
|
||||
<circle cx="24" cy="25" r="2.6" fill={C.r} stroke={C.w} strokeWidth="1" />
|
||||
<path d="M6.5 37.5H41.5" stroke={C.wood} strokeWidth="5" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
// 호랑이 기운: an orange tiger face with black stripes
|
||||
tiger: (
|
||||
<g>
|
||||
<circle cx="12.5" cy="12.5" r="5" fill={C.o} stroke={C.k} strokeWidth="1.4" />
|
||||
<circle cx="35.5" cy="12.5" r="5" fill={C.o} stroke={C.k} strokeWidth="1.4" />
|
||||
<circle cx="12.5" cy="12.5" r="2.2" fill={C.w} />
|
||||
<circle cx="35.5" cy="12.5" r="2.2" fill={C.w} />
|
||||
<ellipse cx="24" cy="25" rx="16" ry="15" fill={C.o} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M19.5 12.5H28.5M20.5 16H27.5M24 12.5V19M8.5 22.5L13 24M8.5 27.5L13 27.5M39.5 22.5L35 24M39.5 27.5L35 27.5" stroke={C.k} strokeWidth="1.8" strokeLinecap="round" />
|
||||
<ellipse cx="19.5" cy="33" rx="5.3" ry="4.5" fill={C.w} />
|
||||
<ellipse cx="28.5" cy="33" rx="5.3" ry="4.5" fill={C.w} />
|
||||
<ellipse cx="18" cy="24.5" rx="1.9" ry="2.3" fill={C.k} />
|
||||
<ellipse cx="30" cy="24.5" rx="1.9" ry="2.3" fill={C.k} />
|
||||
<path d="M21.5 29H26.5L24 31.5Z" fill={C.k} stroke={C.k} strokeWidth="1" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 쌍둥이: two identical smiling pieces side by side
|
||||
twins: (
|
||||
<g>
|
||||
{[16, 32].map((x) => (
|
||||
<g key={x}>
|
||||
<circle cx={x} cy="25" r="9" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx={x - 3} cy="23" r="1.4" fill={C.k} />
|
||||
<circle cx={x + 3} cy="23" r="1.4" fill={C.k} />
|
||||
<path d={`M${x - 3.2} 27.5q3.2 2.8 6.4 0`} fill="none" stroke={C.k} strokeWidth="1.4" strokeLinecap="round" />
|
||||
</g>
|
||||
))}
|
||||
<path d={heart(24, 12, 3.6)} fill={C.pk} stroke={C.k} strokeWidth="1.1" />
|
||||
</g>
|
||||
),
|
||||
// 자리 바꾸기: a white piece and a red piece trading places along two arrows
|
||||
swap: (
|
||||
<g>
|
||||
<g fill="none" stroke={C.w} strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M13 15Q24 4 35 15" />
|
||||
<path d="M30.5 14.5L35.5 15.5L36 10.5" />
|
||||
<path d="M35 33Q24 44 13 33" />
|
||||
<path d="M17.5 33.5L12.5 32.5L12 37.5" />
|
||||
</g>
|
||||
<circle cx="12" cy="24" r="6" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="36" cy="24" r="6" fill={C.r} stroke={C.k} strokeWidth="1.5" />
|
||||
</g>
|
||||
),
|
||||
// 회오리: a tornado flinging pieces around
|
||||
storm: (
|
||||
<g>
|
||||
<g fill="none" stroke={C.w} strokeWidth="3.4" strokeLinecap="round">
|
||||
<path d="M9 9.5H37" />
|
||||
<path d="M12 16H35" />
|
||||
<path d="M15 22.5H31" />
|
||||
<path d="M18 29H28.5" />
|
||||
<path d="M21.5 35H26.5" />
|
||||
<path d="M23.5 40.5H24.5" />
|
||||
</g>
|
||||
<circle cx="9.5" cy="27" r="3.6" fill={C.r} stroke={C.k} strokeWidth="1.3" />
|
||||
<circle cx="38.5" cy="29.5" r="3.6" fill={C.y} stroke={C.k} strokeWidth="1.3" />
|
||||
<circle cx="35" cy="39" r="2.8" fill={C.g} stroke={C.k} strokeWidth="1.2" />
|
||||
</g>
|
||||
),
|
||||
};
|
||||
238
apps/web/src/games/yut/aug-icons/glyphs-d.tsx
Normal file
238
apps/web/src/games/yut/aug-icons/glyphs-d.tsx
Normal file
@@ -0,0 +1,238 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { AugId } from '@bg/games/yut/augments';
|
||||
import { C } from './palette';
|
||||
|
||||
/** A game piece (말): round token. */
|
||||
const piece = (cx: number, cy: number, r: number, fill: string = C.w, key?: string | number) => (
|
||||
<circle key={key} cx={cx} cy={cy} r={r} fill={fill} stroke={C.k} strokeWidth="1.5" />
|
||||
);
|
||||
|
||||
/** A curved "turn around" arrow half (used twice for 다시 던지기). */
|
||||
const refreshHalf = (
|
||||
<g>
|
||||
<path d="M10.8 19.2A14 14 0 0 1 34.7 15" stroke={C.w} strokeWidth="3.4" strokeLinecap="round" fill="none" />
|
||||
<polygon points="38.4,19.3 30.3,16.9 37.4,10.5" fill={C.w} />
|
||||
</g>
|
||||
);
|
||||
|
||||
export const GLYPHS_D: Partial<Record<AugId, ReactNode>> = {
|
||||
// 다시 던지기: a 윷가락 inside a circular "again" arrow
|
||||
reroll: (
|
||||
<g>
|
||||
{refreshHalf}
|
||||
<g transform="rotate(180 24 24)">{refreshHalf}</g>
|
||||
<rect x="20.5" y="12.5" width="7" height="23" rx="3.5" fill={C.wood} stroke={C.woodd} strokeWidth="1.4" />
|
||||
</g>
|
||||
),
|
||||
// 곱빼기: one 윷가락 and its yellow copy, "×2"
|
||||
double: (
|
||||
<g>
|
||||
<rect x="7" y="11" width="5.5" height="26" rx="2.75" fill={C.wood} stroke={C.woodd} strokeWidth="1.3" />
|
||||
<rect x="14.5" y="11" width="5.5" height="26" rx="2.75" fill={C.y} stroke={C.woodd} strokeWidth="1.3" />
|
||||
<text x="31" y="31" textAnchor="middle" fontSize="17" fontWeight="900" fontFamily="system-ui, sans-serif" fill={C.w}>×2</text>
|
||||
</g>
|
||||
),
|
||||
// 올인: two stacks of poker chips
|
||||
gamble: (
|
||||
<g>
|
||||
{[0, 1, 2, 3, 4].map((i) => (
|
||||
<g key={`a${i}`}>
|
||||
<ellipse cx="17" cy={38 - i * 5} rx="9.5" ry="3.8" fill={C.r} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d={`M10 ${38 - i * 5}h2.5M21.5 ${38 - i * 5}h2.5`} stroke={C.w} strokeWidth="1.6" />
|
||||
</g>
|
||||
))}
|
||||
{[0, 1, 2].map((i) => (
|
||||
<g key={`b${i}`}>
|
||||
<ellipse cx="32" cy={38 - i * 5} rx="9.5" ry="3.8" fill={C.w} stroke={C.k} strokeWidth="1.3" />
|
||||
<path d={`M25 ${38 - i * 5}h2.5M36.5 ${38 - i * 5}h2.5`} stroke={C.k} strokeWidth="1.6" />
|
||||
</g>
|
||||
))}
|
||||
<ellipse cx="32" cy="28" rx="5" ry="1.8" fill="none" stroke={C.k} strokeWidth="1" />
|
||||
<ellipse cx="17" cy="18" rx="5" ry="1.8" fill="none" stroke={C.w} strokeWidth="1" />
|
||||
</g>
|
||||
),
|
||||
// 저주 인형: a stitched voodoo doll with a red pin
|
||||
curse: (
|
||||
<g>
|
||||
<circle cx="22" cy="15" r="8" fill={C.w} />
|
||||
<path d="M14 23h16l6 5-2 3-4-3v4l3 9h-5l-4-7-4 7h-5l3-9v-4l-4 3-2-3z" fill={C.w} strokeLinejoin="round" />
|
||||
<path d="M17.5 12.5l3 3M20.5 12.5l-3 3M23.5 12.5l3 3M26.5 12.5l-3 3M18 19.5h8M19.5 18.5v2M22 18.5v2M24.5 18.5v2" stroke={C.k} strokeWidth="1.3" strokeLinecap="round" />
|
||||
<path d="M22 26v6" stroke={C.k} strokeWidth="1.1" strokeDasharray="1.4 1.4" />
|
||||
<line x1="38" y1="9" x2="26" y2="21" stroke={C.grd} strokeWidth="1.6" strokeLinecap="round" />
|
||||
<circle cx="38.5" cy="8.5" r="3" fill={C.r} stroke={C.k} strokeWidth="1.2" />
|
||||
</g>
|
||||
),
|
||||
// 얼음!: a snowflake
|
||||
freeze: (
|
||||
<g stroke={C.w} strokeLinecap="round" fill="none">
|
||||
{[0, 60, 120].map((a) => (
|
||||
<g key={a} transform={`rotate(${a} 24 24)`}>
|
||||
<line x1="24" y1="7" x2="24" y2="41" strokeWidth="3.2" />
|
||||
<path d="M18.5 9.5L24 14l5.5-4.5M18.5 38.5L24 34l5.5 4.5" strokeWidth="2.6" strokeLinejoin="round" />
|
||||
</g>
|
||||
))}
|
||||
<circle cx="24" cy="24" r="3.4" fill={C.b} stroke={C.w} strokeWidth="2" />
|
||||
</g>
|
||||
),
|
||||
// 자석: a red horseshoe magnet pulling a piece
|
||||
magnet: (
|
||||
<g>
|
||||
<path d="M27 15H19A9 9 0 0 0 19 33H27" stroke={C.k} strokeWidth="10.5" fill="none" />
|
||||
<path d="M27 15H19A9 9 0 0 0 19 33H27" stroke={C.r} strokeWidth="7.5" fill="none" />
|
||||
<rect x="23" y="11.25" width="6" height="7.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<rect x="23" y="29.25" width="6" height="7.5" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<path d="M32 19.5q2.5 4.5 0 9" stroke={C.w} strokeWidth="1.8" strokeLinecap="round" fill="none" />
|
||||
{piece(38.5, 24, 4.5, C.y)}
|
||||
</g>
|
||||
),
|
||||
// 뒤로 돌아: a piece pushed back by a U-turn arrow
|
||||
pushback: (
|
||||
<g>
|
||||
<path d="M34 25V20A9.5 9.5 0 0 0 15 20V27" stroke={C.w} strokeWidth="4" strokeLinecap="round" fill="none" />
|
||||
<polygon points="8.5,26 21.5,26 15,35" fill={C.w} />
|
||||
{piece(34, 33, 6.5, C.r)}
|
||||
</g>
|
||||
),
|
||||
// 꼴찌의 반란: falling bars, the last one rising with a yellow arrow
|
||||
underdog: (
|
||||
<g>
|
||||
<rect x="8" y="16" width="8" height="23" rx="1.5" fill={C.w} opacity=".45" />
|
||||
<rect x="19" y="25" width="8" height="14" rx="1.5" fill={C.w} opacity=".45" />
|
||||
<rect x="30" y="33" width="8" height="6" rx="1.5" fill={C.w} />
|
||||
<path d="M34 30V13" stroke={C.k} strokeWidth="6" strokeLinecap="round" />
|
||||
<path d="M34 30V13" stroke={C.y} strokeWidth="3.6" strokeLinecap="round" />
|
||||
<polygon points="34,6 41,15 27,15" fill={C.y} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 텃세: my house guarded by a shield
|
||||
homeground: (
|
||||
<g>
|
||||
<polygon points="21,7 37,21 5,21" fill={C.w} strokeLinejoin="round" />
|
||||
<rect x="9" y="20" width="24" height="18" fill={C.w} />
|
||||
<rect x="17" y="27" width="8" height="11" rx="1" fill={C.k} />
|
||||
<path d="M35 24l7 2.5v5.5c0 4.5-3 7.5-7 9c-4-1.5-7-4.5-7-9v-5.5z" fill={C.b} stroke={C.bd} strokeWidth="1.6" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 따라쟁이: an augment card and its copy
|
||||
copycat: (
|
||||
<g>
|
||||
<rect x="8" y="9" width="20" height="26" rx="3" fill={C.p} stroke={C.k} strokeWidth="1.5" transform="rotate(-8 18 22)" />
|
||||
<rect x="19" y="14" width="20" height="26" rx="3" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<polygon points="29,19.5 31.2,24.3 36.3,24.8 32.4,28.2 33.6,33.2 29,30.6 24.4,33.2 25.6,28.2 21.7,24.8 26.8,24.3" fill={C.y} stroke={C.yd} strokeWidth="1" strokeLinejoin="round" />
|
||||
</g>
|
||||
),
|
||||
// 청개구리: a green frog face
|
||||
frog: (
|
||||
<g>
|
||||
<circle cx="15.5" cy="17" r="6.5" fill={C.g} stroke={C.gd} strokeWidth="1.5" />
|
||||
<circle cx="32.5" cy="17" r="6.5" fill={C.g} stroke={C.gd} strokeWidth="1.5" />
|
||||
<ellipse cx="24" cy="29" rx="17" ry="11" fill={C.g} stroke={C.gd} strokeWidth="1.5" />
|
||||
<circle cx="15.5" cy="17" r="4.5" fill={C.w} />
|
||||
<circle cx="32.5" cy="17" r="4.5" fill={C.w} />
|
||||
<circle cx="16" cy="17.5" r="2.2" fill={C.k} />
|
||||
<circle cx="32" cy="17.5" r="2.2" fill={C.k} />
|
||||
<path d="M13 29q11 8 22 0" stroke={C.k} strokeWidth="1.8" strokeLinecap="round" fill="none" />
|
||||
<circle cx="11.5" cy="31" r="2" fill={C.pk} />
|
||||
<circle cx="36.5" cy="31" r="2" fill={C.pk} />
|
||||
</g>
|
||||
),
|
||||
// 사냥꾼: a bow with an arrow
|
||||
hunter: (
|
||||
<g transform="rotate(-35 24 24)">
|
||||
<path d="M17 7Q5 24 17 41" stroke={C.woodd} strokeWidth="5" strokeLinecap="round" fill="none" />
|
||||
<path d="M17 7Q5 24 17 41" stroke={C.wood} strokeWidth="3" strokeLinecap="round" fill="none" />
|
||||
<line x1="17" y1="7" x2="17" y2="41" stroke={C.w} strokeWidth="1.2" />
|
||||
<line x1="10" y1="24" x2="37" y2="24" stroke={C.w} strokeWidth="2.6" strokeLinecap="round" />
|
||||
<polygon points="43,24 35,19.5 35,28.5" fill={C.r} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M9 20l4 4-4 4M13 20l4 4-4 4" stroke={C.y} strokeWidth="2" strokeLinejoin="round" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 줍줍: a piece on the path hopping onto a pile of pieces
|
||||
pickup: (
|
||||
<g>
|
||||
<line x1="6.5" y1="38" x2="41.5" y2="38" stroke={C.w} strokeWidth="2.4" strokeLinecap="round" />
|
||||
{piece(11, 32, 4.8)}
|
||||
{piece(27.5, 32, 5.6)}
|
||||
{piece(38, 32, 5.6, C.w, 'r')}
|
||||
{piece(32.75, 23, 5.6)}
|
||||
<path d="M10.5 24.5Q13 11 25 13" stroke={C.w} strokeWidth="2.6" strokeLinecap="round" fill="none" />
|
||||
<polygon points="29,13.5 22.5,9 23,17.5" fill={C.w} />
|
||||
</g>
|
||||
),
|
||||
// 도장 깨기: a stamp card with three of four red stamps
|
||||
stamp: (
|
||||
<g>
|
||||
<rect x="7" y="8" width="34" height="32" rx="4" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
{[
|
||||
[16, 17],
|
||||
[32, 17],
|
||||
[16, 31],
|
||||
].map(([x, y]) => (
|
||||
<g key={`${x}-${y}`}>
|
||||
<circle cx={x} cy={y} r="5.8" fill={C.r} />
|
||||
<circle cx={x} cy={y} r="3.6" fill="none" stroke={C.w} strokeWidth="1.2" />
|
||||
</g>
|
||||
))}
|
||||
<circle cx="32" cy="31" r="5.5" fill="none" stroke={C.gr} strokeWidth="1.5" strokeDasharray="2 2" />
|
||||
</g>
|
||||
),
|
||||
// 스타트 대시: a piece dashing off with speed lines
|
||||
dash: (
|
||||
<g>
|
||||
<path d="M8 17h12M5.5 24h13M8 31h12" stroke={C.w} strokeWidth="2.8" strokeLinecap="round" />
|
||||
{piece(31, 24, 9)}
|
||||
<path d="M27 21.5l4 2.5-4 2.5M32 21.5l4 2.5-4 2.5" stroke={C.k} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" fill="none" />
|
||||
</g>
|
||||
),
|
||||
// 방공호: a domed bunker behind sandbags
|
||||
bunker: (
|
||||
<g>
|
||||
<path d="M7 36A17 17 0 0 1 41 36Z" fill={C.w} />
|
||||
<path d="M10.5 28.5h27M15.5 21.5h17" stroke={C.gr} strokeWidth="2" />
|
||||
<path d="M18.5 36v-5a5.5 5.5 0 0 1 11 0v5z" fill={C.k} />
|
||||
{[11, 19, 27, 35].map((x) => (
|
||||
<rect key={x} x={x - 4} y="35" width="8" height="5" rx="2.5" fill={C.wood} stroke={C.woodd} strokeWidth="1.2" />
|
||||
))}
|
||||
</g>
|
||||
),
|
||||
// 벼락: a yellow lightning bolt striking between two pieces
|
||||
lightning: (
|
||||
<g>
|
||||
<polygon points="28,5 13,24 22,24 18,40 36,18 27,18 33,5" fill={C.y} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
{piece(10, 36, 4.5, C.r)}
|
||||
{piece(36, 36, 4.5, C.b)}
|
||||
</g>
|
||||
),
|
||||
// 블랙홀: a black hole with an orange ring
|
||||
blackhole: (
|
||||
<g>
|
||||
<ellipse cx="24" cy="24" rx="18" ry="6.5" fill="none" stroke={C.o} strokeWidth="3.4" transform="rotate(-18 24 24)" />
|
||||
<circle cx="24" cy="24" r="9.5" fill={C.k} stroke={C.w} strokeWidth="1.8" />
|
||||
<path d="M6 24A18 6.5 0 0 0 42 24" fill="none" stroke={C.y} strokeWidth="3.4" transform="rotate(-18 24 24)" />
|
||||
</g>
|
||||
),
|
||||
// 로켓 발사: a white rocket flying up-right
|
||||
rocket: (
|
||||
<g transform="rotate(45 24 24)">
|
||||
<path d="M20 31Q24 44 28 31Z" fill={C.o} />
|
||||
<path d="M21.5 31Q24 39 26.5 31Z" fill={C.y} />
|
||||
<path d="M18 23L11 32L18 31Z M30 23L37 32L30 31Z" fill={C.r} stroke={C.k} strokeWidth="1.3" strokeLinejoin="round" />
|
||||
<path d="M24 5C30 11 31 19 30 31H18C17 19 18 11 24 5Z" fill={C.w} stroke={C.k} strokeWidth="1.5" />
|
||||
<circle cx="24" cy="17.5" r="3.4" fill={C.b} stroke={C.k} strokeWidth="1.4" />
|
||||
</g>
|
||||
),
|
||||
// 최후의 일격: a sword striking the crowned leading piece
|
||||
finisher: (
|
||||
<g>
|
||||
<g transform="translate(-6 -0.75) rotate(-45 24 18.75)">
|
||||
<circle cx="24" cy="7" r="2.4" fill={C.y} stroke={C.k} strokeWidth="1.2" />
|
||||
<rect x="22.3" y="9" width="3.4" height="5.5" fill={C.woodd} />
|
||||
<rect x="15.5" y="14" width="17" height="3.6" rx="1.6" fill={C.y} stroke={C.k} strokeWidth="1.2" />
|
||||
<path d="M21 17.6H27V27.5L24 31.5L21 27.5Z" fill={C.w} stroke={C.k} strokeWidth="1.4" strokeLinejoin="round" />
|
||||
</g>
|
||||
{piece(34, 33, 6.5, C.r)}
|
||||
<polygon points="28.5,25 30,19 34,22.5 38,19 39.5,25" fill={C.y} stroke={C.k} strokeWidth="1.2" strokeLinejoin="round" />
|
||||
<path d="M21 34.5l3-1.5M23.5 39l2.5-3" stroke={C.y} strokeWidth="2" strokeLinecap="round" />
|
||||
</g>
|
||||
),
|
||||
};
|
||||
30
apps/web/src/games/yut/aug-icons/index.tsx
Normal file
30
apps/web/src/games/yut/aug-icons/index.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* One small picture per 증강 so it can be recognised without reading (docs/games/yut-augmented.md §아이콘).
|
||||
* The tile colour tells the kind (규칙 blue, 즉시 violet, 사용 teal, 승리 조건 amber); the glyph tells the augment.
|
||||
* Glyphs are plain SVG drawn in a 48×48 box (aug-icons/glyphs-*.tsx).
|
||||
*/
|
||||
import type { ReactNode } from 'react';
|
||||
import { AUGS, type AugId } from '@bg/games/yut/augments';
|
||||
import { TILE } from './palette';
|
||||
import { GLYPHS_A } from './glyphs-a';
|
||||
import { GLYPHS_B } from './glyphs-b';
|
||||
import { GLYPHS_C } from './glyphs-c';
|
||||
import { GLYPHS_D } from './glyphs-d';
|
||||
|
||||
export const GLYPHS: Partial<Record<AugId, ReactNode>> = { ...GLYPHS_A, ...GLYPHS_B, ...GLYPHS_C, ...GLYPHS_D };
|
||||
|
||||
export function tileColor(id: AugId): string {
|
||||
const a = AUGS[id];
|
||||
return a.win ? TILE.win : TILE[a.kind];
|
||||
}
|
||||
|
||||
/** The icon of augment `id`, `size` px square. Decorative by default (the name is always next to it). */
|
||||
export function AugIcon({ id, size = 32, cat = false, className }: { id: AugId; size?: number; cat?: boolean; className?: string }) {
|
||||
return (
|
||||
<svg className={className ? `aug-icon ${className}` : 'aug-icon'} viewBox="0 0 48 48" width={size} height={size} aria-hidden="true" focusable="false" style={{ flex: 'none', display: 'block' }}>
|
||||
<rect x="1" y="1" width="46" height="46" rx="11" fill={cat ? '#6b7280' : tileColor(id)} />
|
||||
<path d="M12 1h24a11 11 0 0 1 11 11v4C33 9 15 9 1 16v-4A11 11 0 0 1 12 1z" fill="#fff" opacity=".12" />
|
||||
{cat ? GLYPHS.cat : GLYPHS[id]}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
37
apps/web/src/games/yut/aug-icons/palette.ts
Normal file
37
apps/web/src/games/yut/aug-icons/palette.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Colours of the 증강 icons (aug-icons). Every glyph is drawn on a coloured tile (see index.tsx), so these colours do not
|
||||
* depend on the light / dark theme. Glyphs use only these.
|
||||
*/
|
||||
export const C = {
|
||||
/** white: the main glyph colour on the tile */
|
||||
w: '#ffffff',
|
||||
/** ink: outlines, eyes, dark details */
|
||||
k: '#1f2937',
|
||||
/** soft shadow / second tone on the tile */
|
||||
sh: 'rgba(0,0,0,.18)',
|
||||
r: '#ef4444',
|
||||
rd: '#b91c1c',
|
||||
o: '#fb923c',
|
||||
y: '#fde047',
|
||||
yd: '#eab308',
|
||||
g: '#4ade80',
|
||||
gd: '#15803d',
|
||||
b: '#93c5fd',
|
||||
bd: '#1d4ed8',
|
||||
p: '#d8b4fe',
|
||||
pd: '#7e22ce',
|
||||
pk: '#f9a8d4',
|
||||
/** wood (윷가락, 윷판) */
|
||||
wood: '#d6a35c',
|
||||
woodd: '#8a5a1f',
|
||||
gr: '#9ca3af',
|
||||
grd: '#4b5563',
|
||||
} as const;
|
||||
|
||||
/** Tile colours: one per kind, 승리 조건 augments are amber whatever their kind. */
|
||||
export const TILE = {
|
||||
passive: '#2563eb',
|
||||
instant: '#7c3aed',
|
||||
active: '#0d9488',
|
||||
win: '#d97706',
|
||||
} as const;
|
||||
270
apps/web/src/games/yut/aug-options.tsx
Normal file
270
apps/web/src/games/yut/aug-options.tsx
Normal file
@@ -0,0 +1,270 @@
|
||||
/** 증강 윷놀이 방 설정 (docs/games/yut-augmented.md): 혼돈 모드, 고르는 라운드, 후보 수, 나오게 할 증강 목록. */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { YutOptions } from '@bg/games/yut';
|
||||
import { Sheet } from '../../components/ui';
|
||||
import { AugIcon } from './aug-icons';
|
||||
import { AUGS, AUG_IDS, AUG_ROUNDS, KIND_KO, TIER_KO, selectionTier, type AugId, type AugRoundsKey, type AugTier } from '@bg/games/yut/augments';
|
||||
|
||||
const CATS: { key: string; title: string; ids: AugId[] }[] = [
|
||||
{ key: 'any', title: '범용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'any' && !AUGS[id].custom) },
|
||||
{ key: 'start', title: '시작 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'start' && !AUGS[id].custom) },
|
||||
{ key: 'mid', title: '중간 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'mid' && !AUGS[id].custom) },
|
||||
{ key: 'final', title: '마무리 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'final' && !AUGS[id].custom) },
|
||||
{ key: 'custom', title: '이 사이트 추가', ids: AUG_IDS.filter((id) => AUGS[id].custom) },
|
||||
];
|
||||
const WIN_IDS = AUG_IDS.filter((id) => AUGS[id].win);
|
||||
const CUSTOM_IDS = AUG_IDS.filter((id) => AUGS[id].custom);
|
||||
const ROUND_LABELS: Record<AugRoundsKey, string> = { standard: '1·6·12라운드', quick: '1·4·8라운드', many: '1·3·5·7·9라운드' };
|
||||
|
||||
const AUG_CSS = `
|
||||
.yut-aug-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.yut-aug-cat { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 10px; border: 1px dashed var(--border); border-radius: 12px; min-width: 0; }
|
||||
.yut-aug-cat-head { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; }
|
||||
.yut-aug-cat-head strong { margin-right: auto; }
|
||||
.yut-aug-row { display: flex; gap: 10px; align-items: center; min-height: 56px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; }
|
||||
.yut-aug-row.off { background: var(--surface-2, var(--surface)); }
|
||||
.yut-aug-row.off .yut-aug-body, .yut-aug-row.off .aug-icon { opacity: .55; }
|
||||
.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; overflow-wrap: anywhere; }
|
||||
.yut-aug-switch { flex: none; position: relative; width: 50px; height: 30px; margin: 0; appearance: none; -webkit-appearance: none; border-radius: 999px;
|
||||
background: var(--border); cursor: pointer; transition: background .15s; }
|
||||
.yut-aug-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 24px; height: 24px; border-radius: 50%; background: #fff;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, .3); transition: transform .15s; }
|
||||
.yut-aug-switch:checked { background: var(--primary); }
|
||||
.yut-aug-switch:checked::after { transform: translateX(20px); }
|
||||
.yut-aug-switch:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; }
|
||||
.yut-aug-switch:disabled { cursor: default; }
|
||||
.yut-aug-open { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 48px; }
|
||||
.sheet:has(.yut-aug-sheet) { width: min(100%, 640px); }
|
||||
.yut-aug-sheet { display: flex; flex-direction: column; gap: 10px; }
|
||||
.yut-aug-sheet-head { display: flex; flex-direction: column; gap: 8px; }
|
||||
.yut-aug-sheet-foot { position: sticky; bottom: calc(-20px - env(safe-area-inset-bottom)); background: var(--surface); padding: 8px 0 4px; border-top: 1px solid var(--border); }
|
||||
.yut-aug-name { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; font-weight: 700; }
|
||||
.yut-aug-badge { border-radius: 999px; padding: 0 7px; font-size: .75rem; font-weight: 700; background: var(--primary-soft); color: var(--text); white-space: nowrap; }
|
||||
.yut-aug-badge.win { background: var(--warning-soft, var(--primary-soft)); }
|
||||
.yut-aug-warn { color: var(--danger); }
|
||||
`;
|
||||
|
||||
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||||
return (
|
||||
<div className="segmented">
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>{label}</strong>
|
||||
{children}
|
||||
{hint && <span className="small muted">{hint}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange: (patch: Partial<YutOptions>) => void }) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [listOpen, setListOpen] = useState(false);
|
||||
// Inside the room's read-only settings view (not the host) the list can be read but not changed.
|
||||
const openBtn = useRef<HTMLButtonElement>(null);
|
||||
const [readOnly, setReadOnly] = useState(false);
|
||||
const off = new Set<AugId>(o.augOff ?? []);
|
||||
/** Keep `augOff` in AUG_IDS order so the value is stable. */
|
||||
const setOff = (next: Set<AugId>) => onChange({ augOff: AUG_IDS.filter((id) => next.has(id)) });
|
||||
const toggle = (id: AugId) => {
|
||||
const next = new Set(off);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
setOff(next);
|
||||
};
|
||||
const setMany = (ids: readonly AugId[], on: boolean) => {
|
||||
const next = new Set(off);
|
||||
for (const id of ids) {
|
||||
if (on) next.delete(id);
|
||||
else next.add(id);
|
||||
}
|
||||
setOff(next);
|
||||
};
|
||||
|
||||
const roundsKey: AugRoundsKey = o.augRounds ?? 'standard';
|
||||
const n = AUG_ROUNDS[roundsKey].length;
|
||||
const tiers = [...new Set(Array.from({ length: n }, (_, i) => selectionTier(i, n)))];
|
||||
const warnings = tiers.flatMap((t: Exclude<AugTier, 'any'>) => {
|
||||
const c = AUG_IDS.filter((id) => !off.has(id) && (AUGS[id].tier === 'any' || AUGS[id].tier === t)).length;
|
||||
return c < 3 ? [`${TIER_KO[t]} 선택 때 나올 수 있는 증강이 ${c}개뿐이에요(범용 + ${TIER_KO[t]}). 후보가 적게 나오거나 아예 안 나올 수 있어요.`] : [];
|
||||
});
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const match = (id: AugId) => !q || AUGS[id].name.toLowerCase().includes(q) || AUGS[id].text.toLowerCase().includes(q);
|
||||
const onCount = AUG_IDS.length - off.size;
|
||||
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<style>{AUG_CSS}</style>
|
||||
<Field label="혼돈 모드" hint="증강을 고를 때마다 두 번씩 골라요.">
|
||||
<Seg value={o.augChaos ? 'on' : 'off'} options={[['off', '끄기'], ['on', '켜기(한 번에 2개)']]} onChange={(k) => onChange({ augChaos: k === 'on' })} />
|
||||
</Field>
|
||||
<Field label="증강을 고르는 라운드" hint="첫 선택은 범용 + 시작 전용, 마지막 선택은 범용 + 마무리 전용, 그 사이는 범용 + 중간 전용 증강 중에서 나와요.">
|
||||
<Seg value={roundsKey} options={(Object.keys(AUG_ROUNDS) as AugRoundsKey[]).map((k) => [k, ROUND_LABELS[k]])} onChange={(augRounds) => onChange({ augRounds })} />
|
||||
</Field>
|
||||
<Field label="후보 수" hint="한 번 고를 때 보여 주는 증강 수예요.">
|
||||
<Seg value={o.augOffers ?? 3} options={[[2, '2개'], [3, '3개'], [4, '4개']]} onChange={(augOffers) => onChange({ augOffers })} />
|
||||
</Field>
|
||||
<div className="stack" style={{ gap: 8 }}>
|
||||
<strong>나오게 할 증강</strong>
|
||||
<button
|
||||
ref={openBtn}
|
||||
type="button"
|
||||
className="btn btn-secondary yut-aug-open"
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={listOpen}
|
||||
onClick={() => {
|
||||
setReadOnly(!!openBtn.current?.closest('.options-view'));
|
||||
setListOpen(true);
|
||||
}}
|
||||
>
|
||||
<span>📋 증강 목록 열기 (켜고 끄기)</span>
|
||||
<span className="yut-rules-count">
|
||||
켜짐 {onCount}/{AUG_IDS.length}
|
||||
</span>
|
||||
</button>
|
||||
<span className="small muted">끈 증강은 후보에 나오지 않아요. 이 사이트에서 만든 추가 증강 {CUSTOM_IDS.length}개는 처음에 꺼져 있어요.</span>
|
||||
{warnings.map((w) => (
|
||||
<span key={w} className="small yut-aug-warn" role="status">
|
||||
⚠ {w}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{listOpen &&
|
||||
createPortal(
|
||||
<AugListSheet readOnly={readOnly} onClose={() => setListOpen(false)}>
|
||||
<div className="yut-aug-sheet">
|
||||
<div className="yut-aug-sheet-head">
|
||||
<h2 style={{ margin: 0 }}>
|
||||
나오게 할 증강 <span className="yut-rules-count">켜짐 {onCount}/{AUG_IDS.length}</span>
|
||||
</h2>
|
||||
{readOnly ? (
|
||||
<span className="small muted">👑 방장만 바꿀 수 있어요. 여기서는 볼 수만 있어요.</span>
|
||||
) : (
|
||||
<span className="small muted">오른쪽 스위치로 켜고 꺼요. 끈 증강은 후보에 나오지 않아요.</span>
|
||||
)}
|
||||
<input className="input" type="search" placeholder="증강 이름이나 설명으로 찾기" aria-label="증강 찾기" value={query} onChange={(e) => setQuery(e.target.value)} />
|
||||
{!readOnly && (
|
||||
<div className="yut-aug-tools">
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setOff(new Set())} disabled={off.size === 0}>
|
||||
전체 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(WIN_IDS, false)}>
|
||||
승리 조건 증강 끄기
|
||||
</button>
|
||||
{CUSTOM_IDS.every((id) => off.has(id)) ? (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, true)}>
|
||||
추가 증강 켜기
|
||||
</button>
|
||||
) : (
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, false)}>
|
||||
추가 증강 끄기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{warnings.map((w) => (
|
||||
<span key={w} className="small yut-aug-warn" role="status">
|
||||
⚠ {w}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{CATS.map((cat) => {
|
||||
const shown = cat.ids.filter(match);
|
||||
if (!shown.length) return null;
|
||||
const on = cat.ids.filter((id) => !off.has(id)).length;
|
||||
return (
|
||||
<section key={cat.key} className="yut-aug-cat" aria-label={cat.title}>
|
||||
<div className="yut-aug-cat-head">
|
||||
<strong>
|
||||
{cat.title} <span className="small muted">켜짐 {on}/{cat.ids.length}</span>
|
||||
</strong>
|
||||
{!readOnly && (
|
||||
<>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, true)} disabled={on === cat.ids.length}>
|
||||
모두 켜기
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, false)} disabled={on === 0}>
|
||||
모두 끄기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{shown.map((id) => {
|
||||
const a = AUGS[id];
|
||||
const enabled = !off.has(id);
|
||||
return (
|
||||
<label key={id} className={`yut-aug-row${enabled ? '' : ' off'}`}>
|
||||
<AugIcon id={id} size={40} />
|
||||
<span className="yut-aug-body">
|
||||
<span className="yut-aug-name">
|
||||
{a.name}
|
||||
{cat.key === 'custom' && a.tier !== 'any' && <span className="yut-aug-badge">{TIER_KO[a.tier]}</span>}
|
||||
<span className={`yut-aug-badge${a.kind === 'win' ? ' win' : ''}`}>{KIND_KO[a.kind]}</span>
|
||||
{a.once && <span className="yut-aug-badge">1회</span>}
|
||||
{a.win && a.kind !== 'win' && <span className="yut-aug-badge win">승리 조건</span>}
|
||||
</span>
|
||||
<span className="small muted">{a.text}</span>
|
||||
{a.note && <span className="small muted" style={{ fontSize: '.8rem' }}>{a.note}</span>}
|
||||
</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
className="yut-aug-switch"
|
||||
checked={enabled}
|
||||
disabled={readOnly}
|
||||
aria-label={`${a.name} ${enabled ? '켜짐' : '꺼짐'}`}
|
||||
onChange={() => toggle(id)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
{q && CATS.every((c) => !c.ids.some(match)) && <span className="small muted">'{query.trim()}'에 맞는 증강이 없어요.</span>}
|
||||
<div className="yut-aug-sheet-foot">
|
||||
<button type="button" className="btn btn-primary btn-block" onClick={() => setListOpen(false)}>
|
||||
다 골랐어요 (켜짐 {onCount}/{AUG_IDS.length})
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</AugListSheet>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The augment list popup. It is opened from the room settings, which on phones are already a popup: Esc closes only
|
||||
* this one (the settings popup underneath stays open).
|
||||
*/
|
||||
function AugListSheet({ onClose, readOnly, children }: { onClose: () => void; readOnly: boolean; children: React.ReactNode }) {
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => {
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
e.stopPropagation();
|
||||
close.current();
|
||||
};
|
||||
document.addEventListener('keydown', key, true);
|
||||
return () => document.removeEventListener('keydown', key, true);
|
||||
}, []);
|
||||
return (
|
||||
<Sheet onClose={onClose} label={readOnly ? '나오게 할 증강 (보기)' : '나오게 할 증강 고르기'}>
|
||||
{children}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user