Compare commits
153 Commits
c7dab689ca
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2aaff5762 | ||
|
|
9f9d20a641 | ||
|
|
1b9acb9fc1 | ||
|
|
35f2310f8d | ||
|
|
892f64db0e | ||
|
|
943e4be3fd | ||
|
|
122cf5ed1f | ||
|
|
fffb860282 | ||
|
|
f793391b79 | ||
|
|
bc8cb7ae8c | ||
|
|
fa53175f51 | ||
|
|
4e0eb4d52c | ||
|
|
f18909c44f | ||
|
|
72f4f06e21 | ||
|
|
0cbda8f551 | ||
|
|
c2ce1979b2 | ||
|
|
7084a20e59 | ||
|
|
0e8ba529c0 | ||
|
|
2403b6747f | ||
|
|
f4fb796dfe | ||
|
|
f9ed734db4 | ||
|
|
daac1982fa | ||
|
|
5666b227e7 | ||
|
|
9ba93e9576 | ||
|
|
049d910dc6 | ||
|
|
28ef4ed947 | ||
|
|
d40ba1e121 | ||
|
|
1bd69200fd | ||
|
|
5a878ba991 | ||
|
|
17df65bccf | ||
|
|
19fd1fabf2 | ||
|
|
fdf54bd554 | ||
|
|
9f16bf833a | ||
|
|
03e0e8ed84 | ||
|
|
fcc79f05bc | ||
|
|
e9bc366305 | ||
|
|
ca8baf5cc8 | ||
|
|
adc3b5337a | ||
|
|
0335a09eef | ||
|
|
02c2a8508c | ||
|
|
c10fac8e82 | ||
|
|
9ec756bf38 | ||
|
|
81b257df74 | ||
|
|
3125008895 | ||
|
|
8e549a72c3 | ||
|
|
a81f73ef6d | ||
|
|
f1f1104abd | ||
|
|
e34745fe50 | ||
|
|
ce6f662a86 | ||
|
|
3769b20ac3 | ||
|
|
c9f4b782e8 | ||
|
|
609cd8b410 | ||
|
|
bdb415aff6 | ||
|
|
74f37131ea | ||
|
|
3b8a717888 | ||
|
|
8f59a99d7d | ||
|
|
4f69f19bf9 | ||
|
|
efa7adc0c2 | ||
|
|
8aad123222 | ||
|
|
97969a87bd | ||
|
|
b02c9870cf | ||
|
|
88db031d0a | ||
|
|
8620c82ca8 | ||
|
|
57351fd9d6 | ||
|
|
b61be627c9 | ||
|
|
42e8d7650b | ||
|
|
6b5e29a2e2 | ||
|
|
aed4dd0fce | ||
|
|
b7d5b3ad75 | ||
|
|
e0139f412e | ||
|
|
92aebb6a19 | ||
|
|
77e9688876 | ||
|
|
0bff06fa3e | ||
|
|
4d1deb8346 | ||
|
|
13a89a645e | ||
|
|
71bdfd201a | ||
|
|
b93228e5af | ||
|
|
96e8cdeb24 | ||
|
|
7f4b86e432 | ||
|
|
1f0b52685e | ||
|
|
ddd7d72050 | ||
|
|
966bc3c5ef | ||
|
|
1ba83766d0 | ||
|
|
18f0530237 | ||
|
|
73b929739d | ||
|
|
ff3c53ab4a | ||
|
|
cf2903dc75 | ||
|
|
7dccc8e713 | ||
|
|
18ef402a6a | ||
|
|
5e8f5b821f | ||
|
|
eeea9a468b | ||
|
|
be1ee44b17 | ||
|
|
e7d1c1d90c | ||
|
|
404d2a3261 | ||
|
|
6131e74511 | ||
|
|
843786f687 | ||
|
|
aac365606a | ||
|
|
a6b47be03f | ||
|
|
265a0c2ebf | ||
|
|
1cf556b431 | ||
|
|
9564e4604c | ||
|
|
b1b6cccad4 | ||
|
|
d35b7207a3 | ||
|
|
2489627bcd | ||
|
|
606756868c | ||
|
|
91fcf1c83d | ||
|
|
647e9bd448 | ||
|
|
764de1fe1a | ||
|
|
43291606ce | ||
|
|
085ddbaec3 | ||
|
|
99c25cb260 | ||
|
|
b6b9dbc963 | ||
|
|
8cde4fa525 | ||
|
|
4fa4c69725 | ||
|
|
36c8033b65 | ||
|
|
92c9a41d83 | ||
|
|
28590df429 | ||
|
|
743e5dc05e | ||
|
|
2136916a28 | ||
|
|
94f7120a51 | ||
|
|
a6ace5b5e8 | ||
|
|
1b4c80a2df | ||
|
|
f6a0cdcf14 | ||
|
|
8175cebd2c | ||
|
|
ac37a6a6d8 | ||
|
|
b8966db2a6 | ||
|
|
5e1e74da18 | ||
|
|
bafbf95d98 | ||
|
|
ec4c849096 | ||
|
|
0a406306da | ||
|
|
f620faf70b | ||
|
|
f053b8fc6b | ||
|
|
f12cf12b84 | ||
|
|
544f704397 | ||
|
|
89312e28f2 | ||
|
|
71381087cc | ||
|
|
65c56d3ae7 | ||
|
|
115969515c | ||
|
|
74a7daa4d3 | ||
|
|
bde430f33e | ||
|
|
609f458ed2 | ||
|
|
cf7523f862 | ||
|
|
3fffcec52b | ||
|
|
c9f81804cf | ||
|
|
b98775b0a6 | ||
|
|
2ec622ebf6 | ||
|
|
bd179c7a43 | ||
|
|
2fe43952d3 | ||
|
|
84d64b27f2 | ||
|
|
3cbc3698d3 | ||
|
|
07fe46562f | ||
|
|
5f60ad1dd4 | ||
|
|
119d10fac6 |
21
README.md
@@ -5,23 +5,25 @@
|
||||
|
||||
운영 중: https://game.tkrmagid.kr
|
||||
|
||||
## 게임 (26개)
|
||||
## 게임 (46개)
|
||||
| 종류 | 게임 |
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 섯다, 포커, 고스톱, 달무티, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이, 라스베가스, 부루마불, 스플렌더 |
|
||||
| 순발력·대화 | 할리갈리, 도블, 그림 맞히기, 마피아 |
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
|
||||
칩·포인트·지폐는 모두 놀이용이다(실제 돈과 무관).
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
## 주요 기능
|
||||
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
|
||||
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
|
||||
- 컴퓨터 상대: 실시간·대화 게임(할리갈리, 도블, 그림 맞히기, 마피아)을 뺀 22개 게임.
|
||||
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
|
||||
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
|
||||
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
|
||||
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 사용자·방 관리, 계정별 기록.
|
||||
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.
|
||||
|
||||
## 개발
|
||||
```bash
|
||||
@@ -47,6 +49,9 @@ bun e2e/pwa.e2e.ts # PWA: 매니페스트·아이콘, 서비스
|
||||
bun e2e/bots.e2e.ts # 컴퓨터 상대, 방 나가기, 게스트 로그아웃
|
||||
bun e2e/replay.e2e.ts # 다시 보기
|
||||
bun e2e/tutorial.e2e.ts # 처음 하는 사람용 규칙 요약
|
||||
bun e2e/speed.e2e.ts # 게임 속도 배율: 판 애니메이션 재생 속도와 컴퓨터 응답 시간
|
||||
bun e2e/settings.e2e.ts # 설정 팝업: 게임 중에 열어도 방에서 나가지 않음, 바로 적용, 닫기·포커스
|
||||
bun e2e/room-back.e2e.ts # 혼자인 대기실에서 뒤로가기 → 빈 방 바로 닫힘, 친구가 있으면 자리 유지, 규칙 팝업
|
||||
bun scripts/loadtest.ts --help # 부하·장애 주입 (docs/reports 참고)
|
||||
```
|
||||
|
||||
|
||||
@@ -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();
|
||||
@@ -196,6 +304,59 @@ describe('site settings, rooms, users', () => {
|
||||
expect((await chat).text).toBe('너 **야');
|
||||
});
|
||||
|
||||
test('game speed: 1/16~16 (default 1), shown in /api/config, out of range rejected', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site;
|
||||
expect(site.gameSpeed).toBe(1);
|
||||
expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(1);
|
||||
for (const bad of [0, 1 / 32, 17, -1]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: bad }) });
|
||||
expect(r.res.status).toBe(400);
|
||||
}
|
||||
for (const ok of [1 / 16, 16, 0.75]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: ok }) });
|
||||
expect(r.res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/config')).body.gameSpeed).toBe(ok);
|
||||
}
|
||||
// An open room gets the new speed at once (its screen's animations follow it).
|
||||
const g = await guest(s.base, '방장님');
|
||||
const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) });
|
||||
const c = await new Client(s.base, g.cookie, g.id).connect();
|
||||
clients.push(c);
|
||||
c.send({ t: 'join', code: room.body.code, as: 'player' });
|
||||
expect((await c.next('room')).room.gameSpeed).toBe(0.75);
|
||||
const next = c.next('room');
|
||||
await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, gameSpeed: 2 }) });
|
||||
expect((await next).room.gameSpeed).toBe(2);
|
||||
});
|
||||
|
||||
test('chat sound: 0~200% (default 80), shown in /api/config and open rooms, out of range rejected', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
const site = (await api(s.base, '/api/admin/site', { cookie: sup.cookie })).body.site;
|
||||
expect(site.chatSound).toBe(80);
|
||||
expect((await api(s.base, '/api/config')).body.chatSound).toBe(80);
|
||||
for (const bad of [-1, 201, 50.5]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: bad }) });
|
||||
expect(r.res.status).toBe(400);
|
||||
}
|
||||
for (const ok of [0, 200, 120]) {
|
||||
const r = await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: ok }) });
|
||||
expect(r.res.status).toBe(200);
|
||||
expect((await api(s.base, '/api/config')).body.chatSound).toBe(ok);
|
||||
}
|
||||
const g = await guest(s.base, '방장님');
|
||||
const room = await api(s.base, '/api/rooms', { method: 'POST', cookie: g.cookie, body: JSON.stringify({ gameId: 'omok' }) });
|
||||
const c = await new Client(s.base, g.cookie, g.id).connect();
|
||||
clients.push(c);
|
||||
c.send({ t: 'join', code: room.body.code, as: 'player' });
|
||||
expect((await c.next('room')).room.chatSound).toBe(120);
|
||||
const next = c.next('room');
|
||||
await api(s.base, '/api/admin/site', { method: 'PUT', cookie: sup.cookie, body: JSON.stringify({ ...site, chatSound: 30 }) });
|
||||
expect((await next).room.chatSound).toBe(30);
|
||||
});
|
||||
|
||||
test('admin closes a room: everyone is told and disconnected from it', async () => {
|
||||
const s = start();
|
||||
const sup = await discordLogin(s, SUPER);
|
||||
|
||||
153
apps/server/src/admin/liar-bank.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 라이어 게임 제시어 관리 (docs/games/liar.md §3.1, docs/14-admin.md §4.1): admins replace, delete or add whole topics.
|
||||
* The changes live in `liar_topics`; the merged bank is handed to the game module (`setLiarBank`) with a version name
|
||||
* (hash of the changes) that new games carry in their options. Every version is kept in `liar_bank_versions` so a replay
|
||||
* (or a game restored after a restart) sets up from the bank it started with.
|
||||
*/
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { z } from 'zod';
|
||||
import { TOPICS, mergeBank, setLiarBank, setLiarBankResolver, topicProblems, type LiarTopic, type TopicOverride } from '@bg/games/liar';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
|
||||
const line = (max: number) => z.string().trim().min(1).max(max);
|
||||
export const LiarTopicInputSchema = z.object({
|
||||
ko: line(20),
|
||||
generic: z.array(line(80)).max(20),
|
||||
words: z
|
||||
.array(
|
||||
z.object({
|
||||
word: line(20),
|
||||
aliases: z.array(line(20)).max(10).optional(),
|
||||
hints: z.array(line(80)).max(10),
|
||||
group: z.string().trim().max(20).optional(),
|
||||
}),
|
||||
)
|
||||
.max(300),
|
||||
});
|
||||
export type LiarTopicInput = z.infer<typeof LiarTopicInputSchema>;
|
||||
|
||||
/** Most topics an admin may add. */
|
||||
export const CUSTOM_TOPICS_MAX = 100;
|
||||
|
||||
export interface AdminLiarTopic extends Omit<LiarTopic, 'groups'> {
|
||||
builtin: boolean;
|
||||
/** Built-in topic changed by an admin (can be reset). */
|
||||
modified: boolean;
|
||||
/** Built-in topic an admin deleted (can be restored). */
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
/** Drops empty optional fields so the stored JSON stays small and stable. */
|
||||
function clean(t: LiarTopicInput): NonNullable<TopicOverride['topic']> {
|
||||
return {
|
||||
ko: t.ko,
|
||||
generic: t.generic,
|
||||
words: t.words.map((x) => ({
|
||||
word: x.word,
|
||||
hints: x.hints,
|
||||
...(x.aliases?.length ? { aliases: x.aliases } : {}),
|
||||
...(x.group ? { group: x.group } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export class LiarBankStore {
|
||||
private rows: TopicOverride[] = [];
|
||||
private versions = new Map<string, readonly LiarTopic[]>();
|
||||
|
||||
constructor(private db: Database) {
|
||||
this.load();
|
||||
setLiarBankResolver((ref) => this.version(ref));
|
||||
}
|
||||
|
||||
private load(): void {
|
||||
this.rows = this.db
|
||||
.query<{ id: string; json: string }, []>('SELECT id, json FROM liar_topics ORDER BY created_at, id')
|
||||
.all()
|
||||
.map((r) => ({ id: r.id, ...(JSON.parse(r.json) as Omit<TopicOverride, 'id'>) }));
|
||||
const ref = this.rows.length ? sha256Hex(JSON.stringify(this.rows)).slice(0, 16) : null;
|
||||
const topics = mergeBank(this.rows);
|
||||
if (ref) {
|
||||
this.db.query('INSERT OR IGNORE INTO liar_bank_versions (ref, json, created_at) VALUES (?, ?, ?)').run(ref, JSON.stringify(this.rows), Date.now());
|
||||
this.versions.set(ref, topics);
|
||||
}
|
||||
setLiarBank(topics, ref);
|
||||
}
|
||||
|
||||
/** A stored bank version (null if unknown: the game falls back to the bank in the code). */
|
||||
private version(ref: string): readonly LiarTopic[] | null {
|
||||
const hit = this.versions.get(ref);
|
||||
if (hit) return hit;
|
||||
const row = this.db.query<{ json: string }, [string]>('SELECT json FROM liar_bank_versions WHERE ref = ?').get(ref);
|
||||
if (!row) return null;
|
||||
const topics = mergeBank(JSON.parse(row.json) as TopicOverride[]);
|
||||
if (this.versions.size > 50) this.versions.clear();
|
||||
this.versions.set(ref, topics);
|
||||
return topics;
|
||||
}
|
||||
|
||||
/** Every topic for the admin screen: the bank in use (code order, then the admins' own), then deleted built-in ones. */
|
||||
list(): AdminLiarTopic[] {
|
||||
const by = new Map(this.rows.map((r) => [r.id, r]));
|
||||
const out: AdminLiarTopic[] = mergeBank(this.rows).map((t) => {
|
||||
const builtin = TOPICS.some((b) => b.id === t.id);
|
||||
return { id: t.id, ko: t.ko, generic: t.generic, words: t.words, builtin, modified: builtin && !!by.get(t.id)?.topic, deleted: false };
|
||||
});
|
||||
for (const b of TOPICS) if (by.get(b.id)?.deleted) out.push({ id: b.id, ko: b.ko, generic: b.generic, words: b.words, builtin: true, modified: false, deleted: true });
|
||||
return out;
|
||||
}
|
||||
|
||||
get(id: string): AdminLiarTopic | null {
|
||||
return this.list().find((t) => t.id === id) ?? null;
|
||||
}
|
||||
|
||||
/** Problems (Korean) with a topic as typed, or none. */
|
||||
problems(t: LiarTopicInput): string[] {
|
||||
return topicProblems(clean(t));
|
||||
}
|
||||
|
||||
private write(id: string, value: Omit<TopicOverride, 'id'>, by: string, now: number): void {
|
||||
this.db
|
||||
.query(
|
||||
'INSERT INTO liar_topics (id, json, created_at, updated_by, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET json = excluded.json, updated_by = excluded.updated_by, updated_at = excluded.updated_at',
|
||||
)
|
||||
.run(id, JSON.stringify(value), now, by, now);
|
||||
this.load();
|
||||
}
|
||||
|
||||
private remove(id: string): void {
|
||||
this.db.query('DELETE FROM liar_topics WHERE id = ?').run(id);
|
||||
this.load();
|
||||
}
|
||||
|
||||
/** Replaces a topic (built-in or the admins' own, also a deleted built-in one: that restores it). Validate first. */
|
||||
save(id: string, t: LiarTopicInput, by: string, now = Date.now()): void {
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
}
|
||||
|
||||
/** Adds a topic of the admins' own; returns its id, or null when there are too many. */
|
||||
create(t: LiarTopicInput, by: string, now = Date.now()): string | null {
|
||||
if (this.rows.filter((r) => !TOPICS.some((b) => b.id === r.id)).length >= CUSTOM_TOPICS_MAX) return null;
|
||||
let id: string;
|
||||
do id = `c_${now.toString(36)}${Math.floor(Math.random() * 36 ** 3).toString(36)}`;
|
||||
while (this.rows.some((r) => r.id === id));
|
||||
this.write(id, { topic: clean(t) }, by, now);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Deletes a topic: a built-in one is hidden (can be restored), an admin's own is gone. */
|
||||
delete(id: string, by: string, now = Date.now()): void {
|
||||
if (TOPICS.some((b) => b.id === id)) this.write(id, { deleted: true }, by, now);
|
||||
else this.remove(id);
|
||||
}
|
||||
|
||||
/** A built-in topic back to the code's words (undoes a change or a delete). */
|
||||
reset(id: string): void {
|
||||
this.remove(id);
|
||||
}
|
||||
|
||||
/** Topics new rooms can pick, for the lobby. */
|
||||
static choices(topics: readonly LiarTopic[]): { id: string; ko: string; words: number }[] {
|
||||
return topics.map((t) => ({ id: t.id, ko: t.ko, words: t.words.length }));
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Database } from 'bun:sqlite';
|
||||
import { z } from 'zod';
|
||||
import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { CATALOG, type CatalogEntry } from '@bg/shared';
|
||||
import { CATALOG, CHAT_SOUND_DEFAULT, CHAT_SOUND_MAX, CHAT_SOUND_MIN, GAME_SPEED_DEFAULT, GAME_SPEED_MAX, GAME_SPEED_MIN, type CatalogEntry } from '@bg/shared';
|
||||
|
||||
export const SiteSettingsSchema = z.object({
|
||||
siteName: z.string().trim().min(1).max(40).default('같이 놀자 보드게임'),
|
||||
@@ -17,6 +17,12 @@ export const SiteSettingsSchema = z.object({
|
||||
graceSec: z.number().int().min(10).max(600).default(60),
|
||||
chatEnabledDefault: z.boolean().default(true),
|
||||
chatFilterDefault: z.boolean().default(true),
|
||||
/** Chat flood guard (per-socket chat budget, docs/03 §8). Off: chat lines and 입력 중 signals are never limited. */
|
||||
chatFloodGuard: z.boolean().default(false),
|
||||
/** Animations and the computers' thinking time are divided by this (applies at once, also to running games). */
|
||||
gameSpeed: z.number().min(GAME_SPEED_MIN).max(GAME_SPEED_MAX).default(GAME_SPEED_DEFAULT),
|
||||
/** Chat sound in % of a game sound (0 = silent, applies at once, also to open rooms). */
|
||||
chatSound: z.number().int().min(CHAT_SOUND_MIN).max(CHAT_SOUND_MAX).default(CHAT_SOUND_DEFAULT),
|
||||
});
|
||||
export type SiteSettings = z.infer<typeof SiteSettingsSchema>;
|
||||
|
||||
|
||||
298
apps/server/src/ai/acts.ts
Normal file
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* What a move means, for the computers' talk (docs/06 §12.1): the model is told what someone did *and what it says
|
||||
* about them* (풀 베팅 = 세게 나옴, 다이 = 물러섬), and a line that contradicts it ("풀 베팅이라니 쫄았네") is thrown
|
||||
* away. Also the public facts of the table (칩·점수·카드 수) so the computers talk about this game, not in general.
|
||||
*/
|
||||
|
||||
/** strong = 세게·자신 있게 나옴, weak = 물러섬·포기, careful = 조심·지켜봄, neutral = 그냥 둔 수. */
|
||||
export type Tone = 'strong' | 'weak' | 'careful' | 'neutral';
|
||||
|
||||
/**
|
||||
* What kind of event a move is, for the built-in lines: the betting moves each have their own (센 베팅 = raise,
|
||||
* 콜 = call, 체크·삥 = check, 다이·폴드 = fold); other moves go by tone (bold = 고·론·우노 외침…, safe = 스톱·넘김,
|
||||
* giveUp = 기권). neutral = an ordinary move (a stone, a card): no line of its own.
|
||||
*/
|
||||
export type ActKind = 'raise' | 'call' | 'check' | 'fold' | 'bold' | 'safe' | 'giveUp' | 'neutral';
|
||||
|
||||
export interface ActMeaning {
|
||||
/** A few words for the move, e.g. "풀 베팅". */
|
||||
ko: string;
|
||||
/** What it means, for the model. */
|
||||
mean?: string;
|
||||
tone: Tone;
|
||||
/** Worth a word on its own (big bets, giving up, 고/스톱, …). Ordinary moves never get one. */
|
||||
notable: boolean;
|
||||
kind: ActKind;
|
||||
}
|
||||
|
||||
const TONE_KIND: Record<Tone, ActKind> = { strong: 'bold', weak: 'giveUp', careful: 'safe', neutral: 'neutral' };
|
||||
|
||||
const m = (ko: string, tone: Tone = 'neutral', notable = false, mean?: string, kind: ActKind = TONE_KIND[tone]): ActMeaning => ({
|
||||
ko,
|
||||
tone,
|
||||
notable,
|
||||
kind,
|
||||
...(mean ? { mean } : {}),
|
||||
});
|
||||
|
||||
const BET_TONE: Record<'raise' | 'call' | 'check' | 'fold', [Tone, boolean]> = {
|
||||
raise: ['strong', true],
|
||||
call: ['neutral', false],
|
||||
check: ['careful', false],
|
||||
fold: ['weak', true],
|
||||
};
|
||||
/** A betting move (섯다·포커): 센 베팅, 콜, 체크·삥, 다이·폴드. */
|
||||
const bet = (ko: string, kind: keyof typeof BET_TONE, mean: string): ActMeaning => m(ko, BET_TONE[kind][0], BET_TONE[kind][1], mean, kind);
|
||||
|
||||
const FULL = '판돈만큼 더 거는 가장 센 베팅. 패에 자신 있거나 세게 블러핑하는 공격적인 수다(겁먹은 게 아니다)';
|
||||
const HALF = '판돈의 절반을 더 걸며 크게 올림. 자신 있다는 뜻의 센 수다';
|
||||
const DIE = '이번 판을 포기하고 패를 접음. 물러선 것이다';
|
||||
const QUARTER = '판돈의 4분의 1을 더 걸며 올림. 세게 나온 수다';
|
||||
const DDADANG = '앞사람 베팅의 두 배로 올림. 세게 나온 것';
|
||||
const RAISE = '베팅을 올림. 자신 있다는 뜻의 센 수';
|
||||
const ALL_IN = '가진 것을 전부 검. 가장 센 승부수(겁먹은 게 아니다)';
|
||||
const CALL = '앞사람이 건 만큼 따라감. 승부를 받아들인 것';
|
||||
const CHECK = '더 걸지 않고 지켜봄. 조심스러운 수';
|
||||
const PING = '가장 작은 베팅으로 간을 봄. 조심스러운 수';
|
||||
const GIVE_UP = '이 판을 포기함';
|
||||
|
||||
/** Any game, by action type. */
|
||||
const COMMON: Record<string, ActMeaning> = {
|
||||
place: m('돌을 놓음'), drop: m('돌을 떨어뜨림'), move: m('말을 움직임'), MOVE: m('말을 움직임'), placeWall: m('벽을 세움'), castle: m('캐슬링'),
|
||||
play: m('카드를 냄'), discard: m('패를 버림'), DISCARD: m('패를 버림'), draw: m('패를 가져옴'), pass: m('넘김', 'careful'), PASS: m('넘김', 'careful'),
|
||||
// 섯다 (한게임식 이름: 삥·콜·따당·쿼터·하프·풀·다이)
|
||||
call: bet('콜', 'call', CALL),
|
||||
check: bet('체크', 'check', CHECK),
|
||||
ping: bet('삥', 'check', PING),
|
||||
die: bet('다이', 'fold', DIE),
|
||||
quarter: bet('쿼터 베팅', 'raise', QUARTER),
|
||||
half: bet('하프 베팅', 'raise', HALF),
|
||||
ddadang: bet('따당', 'raise', DDADANG),
|
||||
full: bet('풀 베팅', 'raise', FULL),
|
||||
raise: bet('레이즈', 'raise', RAISE),
|
||||
allIn: bet('올인', 'raise', ALL_IN),
|
||||
fold: bet('폴드', 'fold', DIE),
|
||||
roll: m('주사위를 굴림'), ROLL: m('주사위를 굴림'), hold: m('주사위를 고정함'), score: m('점수를 적음'),
|
||||
guess: m('추리함'), stop: m('추리를 멈춤', 'careful', true, '맞힌 뒤 더 노리지 않고 멈춤. 안전하게 간 것'),
|
||||
continue: m('계속 추리', 'strong', true, '맞힌 뒤 멈추지 않고 한 번 더 노림. 과감한 수'),
|
||||
offer: m('카드를 건넴'), peek: m('카드를 몰래 봄'), claim: m('선언함', 'strong', true), declare: m('선언함'),
|
||||
tsumo: m('쯔모', 'strong', true, '직접 뽑은 패로 났음'), ring: m('종을 침', 'strong', true), flip: m('카드를 뒤집음'),
|
||||
BUY: m('땅을 삼'), BUILD: m('건물을 지음'), sell: m('패를 팖'), SELL: m('땅을 팖', 'weak', false, undefined, 'neutral'),
|
||||
TAKEOVER: m('땅을 인수함', 'strong', true, '남의 땅을 빼앗아 옴'),
|
||||
THROW: m('윷을 던짐'), commit: m('타일을 내려놓음'), respond: m('대답함'), choose: m('골랐음'), vote: m('투표'),
|
||||
declareOneCard: m('원카드를 외침', 'strong', true, '카드가 한 장 남았다'), callUno: m('우노를 외침', 'strong', true, '카드가 한 장 남았다'),
|
||||
catchUno: m('우노 안 외친 사람을 잡음', 'strong', true), challenge: m('도전함', 'strong', true),
|
||||
accuse: m('최종 추리를 함', 'strong', true, '범인을 확신하고 승부를 건 것'),
|
||||
resign: m('기권', 'weak', true, GIVE_UP), concede: m('기권', 'weak', true, GIVE_UP), CONCEDE: m('기권', 'weak', true, GIVE_UP),
|
||||
giveUp: m('포기', 'weak', true, GIVE_UP),
|
||||
offerDraw: m('무승부를 제안함', 'careful', true), requestUndo: m('무르기를 부탁함', 'weak', true, undefined, 'neutral'),
|
||||
// 포커 (한국식 / 노리밋)
|
||||
'k.check': bet('체크', 'check', CHECK),
|
||||
'k.ping': bet('삥', 'check', PING),
|
||||
'k.call': bet('콜', 'call', CALL),
|
||||
'k.ddadang': bet('따당', 'raise', DDADANG),
|
||||
'k.quarter': bet('쿼터 베팅', 'raise', QUARTER),
|
||||
'k.half': bet('하프 베팅', 'raise', HALF),
|
||||
'k.full': bet('풀 베팅', 'raise', FULL),
|
||||
'k.die': bet('다이', 'fold', DIE),
|
||||
'nl.fold': bet('폴드', 'fold', DIE),
|
||||
'nl.check': bet('체크', 'check', CHECK),
|
||||
'nl.call': bet('콜', 'call', CALL),
|
||||
'nl.raise': bet('레이즈', 'raise', RAISE),
|
||||
'nl.allIn': bet('올인', 'raise', ALL_IN),
|
||||
};
|
||||
|
||||
/** Every move type the computers know the meaning of (for tests). */
|
||||
export const KNOWN_ACTIONS: readonly string[] = Object.keys(COMMON);
|
||||
|
||||
/** The meaning of `action` in `gameId` (payload-aware where one type covers opposite moves). */
|
||||
export function meaningOf(gameId: string, action: unknown): ActMeaning {
|
||||
const a = (action ?? {}) as { type?: string; decision?: string; call?: string; bet?: unknown; kind?: unknown; choice?: unknown };
|
||||
const type = String(a.type ?? '');
|
||||
if (gameId === 'gostop' && type === 'goStop') {
|
||||
return a.decision === 'go'
|
||||
? m('고', 'strong', true, '점수가 났는데 멈추지 않고 더 노림. 배짱 있는 수')
|
||||
: m('스톱', 'careful', true, '점수를 확정하고 판을 끝냄. 안전하게 간 것');
|
||||
}
|
||||
if (gameId === 'mahjong' && type === 'claim') {
|
||||
return a.call === 'ron' ? m('론', 'strong', true, '남이 버린 패로 났음') : m(`${a.call === 'pon' ? '퐁' : a.call === 'kan' ? '깡' : '치'}`, 'neutral');
|
||||
}
|
||||
if (gameId === 'dobble' && type === 'claim') return m('같은 그림을 찾음', 'strong');
|
||||
if (gameId === 'davinci-code' && type === 'guess') return m('상대 숫자를 추리함');
|
||||
if (COMMON[type]) return COMMON[type];
|
||||
// One action type for every bet with the bet in the payload ({ type: 'bet', bet: 'half' }).
|
||||
for (const k of [a.bet, a.kind, a.choice]) if (typeof k === 'string' && COMMON[k]) return COMMON[k];
|
||||
return m('수를 둠');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- contradictions
|
||||
|
||||
/** "겁먹었다", said about someone. */
|
||||
const FEAR = /쫄(?!깃)|겁\s?(먹|쟁이|나서|났|나냐|나지)|무서(웠|워서|워\s*[?ㅋ]|우냐|운가|운\s?거|운\s?가)|떨(려|리|고\s?있)|소심|도망|꽁무니|엄살/;
|
||||
/** "세게 나왔다", said about someone. */
|
||||
const BOLD = /세게|세다|과감|질렀|지르|지른|배짱|대담|공격적|화끈|자신감|용감|올인|풀\s?베팅|풀베|크게\s?(걸|건|질|나)/;
|
||||
/** "I'm scared / giving up", said about oneself while making a strong move. */
|
||||
const SELF_WEAK = /포기|접을|접어야|무섭|무서워|겁나|떨려|자신\s?없/;
|
||||
/** Bet names: a line naming another bet than the one made is talking about something that did not happen. */
|
||||
const BET_WORDS: [string, RegExp][] = [
|
||||
['다이', /다이/], ['콜', /콜(?!라)/], ['체크', /체크/], ['하프', /하프/], ['풀', /풀\s?(베팅|뱃|로)|풀베/], ['따당', /따당/],
|
||||
['삥', /삥/], ['쿼터', /쿼터/], ['올인', /올인/], ['폴드', /폴드/], ['레이즈', /레이즈/],
|
||||
];
|
||||
const betNames = (s: string) => BET_WORDS.filter(([, re]) => re.test(s)).map(([w]) => w);
|
||||
|
||||
/**
|
||||
* True when `line` says something the move contradicts. `mine` = the speaker made the move (taunting the others as
|
||||
* scared is fine then); otherwise the line is about the person who moved. `known` = other move names that came up
|
||||
* just before (a line may mention those).
|
||||
*/
|
||||
export function contradicts(line: string, meaning: ActMeaning, mine: boolean, known: string[] = []): boolean {
|
||||
if (meaning.tone === 'strong' && (mine ? SELF_WEAK : FEAR).test(line)) return true;
|
||||
if ((meaning.tone === 'weak' || meaning.tone === 'careful') && BOLD.test(line)) return true;
|
||||
const own = betNames(meaning.ko);
|
||||
if (!own.length) return false; // not a betting move: bet names don't apply
|
||||
const ok = new Set([...own, ...known.flatMap(betNames)]);
|
||||
return BET_WORDS.some(([w, re]) => re.test(line) && !ok.has(w));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- built-in lines
|
||||
|
||||
type Pool = { smart: string[]; casual: string[] };
|
||||
|
||||
/**
|
||||
* Built-in lines per kind of event, about someone else's move (`other`, `{who}` = that person) or one's own
|
||||
* (`mine`); `{act}` = the move's name (콜, 하프 베팅, 다이…). Said when the model is slow, down, or wrote a line
|
||||
* that contradicts the move — each one fits only its kind (no "쫄았네" on a raise, no "세게 나오네" on a fold;
|
||||
* tests check every line against `contradicts`). Ordinary moves (`neutral`) have none.
|
||||
*/
|
||||
const LINES: Partial<Record<ActKind, { other: Pool; mine: Pool }>> = {
|
||||
raise: {
|
||||
other: {
|
||||
casual: ['오 {who}, {act}? 세게 나오네 ㅋㅋ', '{act}? 패가 좋은가 보네 ㅋㅋ', '{who} 자신 있나 본데? 판이 커졌다 ㅋㅋ'],
|
||||
smart: ['{who}님, {act}? 세게 나오시네요.', '{act}? 패가 좋으신가 봐요.', '{who}님 자신 있으신가 봐요. 판이 커졌네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['{act} 간다! 따라올 수 있어? ㅋㅋ', '나는 {act}! 받을 거야? ㅋㅋ', '이번 판은 세게 간다 ㅋㅋ'],
|
||||
smart: ['{act} 갈게요. 따라오실 건가요?', '저는 {act}! 받으실 건가요?', '이번 판은 세게 가 볼게요.'],
|
||||
},
|
||||
},
|
||||
call: {
|
||||
other: {
|
||||
casual: ['{who}, {act} 받았네? 승부 보자는 거지 ㅋㅋ', '{act}? 좋아, 끝까지 가 보자 ㅋㅋ'],
|
||||
smart: ['{who}님, {act} 받으셨네요. 승부 보시죠.', '{act}? 좋아요, 끝까지 가 봐요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['{act}! 어디 패 한번 보자 ㅋㅋ', '받아 줄게, {act}!'],
|
||||
smart: ['{act}할게요. 패 한번 봐요.', '받아 드릴게요, {act}!'],
|
||||
},
|
||||
},
|
||||
check: {
|
||||
other: {
|
||||
casual: ['{who}, {act}? 간 보는 거야? ㅋㅋ', '{act}? 조심하는데? ㅋㅋ'],
|
||||
smart: ['{who}님, {act}? 간 보시는 건가요?', '{act}? 조심스럽게 가시네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['일단 {act}. 천천히 가자 ㅋㅋ', '{act}! 아직은 지켜볼게'],
|
||||
smart: ['일단 {act}할게요.', '{act}! 아직은 지켜볼게요.'],
|
||||
},
|
||||
},
|
||||
fold: {
|
||||
other: {
|
||||
casual: ['{who} 이번엔 {act}? 다음 판에 보자 ㅋㅋ', '{act}? 현명한 선택일지도 ㅋㅋ'],
|
||||
smart: ['{who}님은 이번엔 물러나시는군요.', '{act}? 다음 판을 노리시는군요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['이번 판은 {act}. 다음에 보자 ㅋㅋ', '아 이건 아니다, {act}!'],
|
||||
smart: ['이번 판은 {act}할게요.', '이번엔 물러날게요. 다음 판에 봬요.'],
|
||||
},
|
||||
},
|
||||
bold: {
|
||||
other: {
|
||||
casual: ['오 {who}, 과감한데? ㅋㅋ', '{who} 제법인데? 나도 질 수 없지 ㅋㅋ'],
|
||||
smart: ['{who}님, 과감하시네요.', '{who}님 제법이신데요? 저도 질 수 없죠.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['간다! 이번 판은 내가 가져간다 ㅋㅋ', '이 정도는 해 줘야지 ㅋㅋ'],
|
||||
smart: ['가 볼게요! 이번엔 제가 가져갈게요.', '이 정도는 해 봐야죠.'],
|
||||
},
|
||||
},
|
||||
safe: {
|
||||
other: {
|
||||
casual: ['{who}, 안전하게 가네? ㅋㅋ', '{who} 신중한데?'],
|
||||
smart: ['{who}님, 안전하게 가시네요.', '{who}님 신중하시네요.'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['여기선 안전하게 갈게 ㅋㅋ', '욕심은 여기까지 ㅋㅋ'],
|
||||
smart: ['여기선 안전하게 갈게요.', '욕심은 여기까지만 낼게요.'],
|
||||
},
|
||||
},
|
||||
giveUp: {
|
||||
other: {
|
||||
casual: ['{who}, 이번 판은 여기까지야? 아쉽다', '{who} 다음 판에 또 하자 ㅋㅋ'],
|
||||
smart: ['{who}님, 이번 판은 여기까지인가요?', '아쉽네요, 다음 판에 또 해요!'],
|
||||
},
|
||||
mine: {
|
||||
casual: ['이번 판은 내가 졌다 ㅋㅋ 다음 판!', '여기까지! 다음 판에 보자'],
|
||||
smart: ['이번 판은 제가 졌네요. 다음 판에 봬요.', '여기까지 할게요. 다음 판에 봬요.'],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Every built-in line for `meaning` (about `who`'s move, or one's own when `mine`); empty for ordinary moves. */
|
||||
export function cannedLines(meaning: ActMeaning, who: string, smart: boolean, mine: boolean): string[] {
|
||||
const pool = LINES[meaning.kind]?.[mine ? 'mine' : 'other'][smart ? 'smart' : 'casual'] ?? [];
|
||||
return pool.map((l) => l.replaceAll('{who}', who).replaceAll('{act}', meaning.ko));
|
||||
}
|
||||
|
||||
/** One built-in line for the move (null for ordinary moves). */
|
||||
export function cannedLine(meaning: ActMeaning, who: string, smart: boolean, mine: boolean, random: () => number): string | null {
|
||||
const all = cannedLines(meaning, who, smart, mine);
|
||||
return all.length ? all[Math.floor(random() * all.length) % all.length]! : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- facts
|
||||
|
||||
const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||||
|
||||
/**
|
||||
* Public facts of the table as `bot` sees them, in short Korean: 판돈, each player's 칩/돈/점수/카드 수, who has
|
||||
* folded. Read from the common shapes of the games' views (`seats`/`players` with ids, `money`, `sheets`, `pot`);
|
||||
* hidden things (anyone's hand) are never read. Empty when the view has none of these.
|
||||
*/
|
||||
export function tableFacts(view: unknown, bot: string, nameOf: (id: string) => string): string[] {
|
||||
if (!view || typeof view !== 'object') return [];
|
||||
const v = view as Record<string, unknown>;
|
||||
const out: string[] = [];
|
||||
const pot = num(v.pot);
|
||||
if (pot !== null && pot > 0) out.push(`판돈 ${pot}`);
|
||||
const who = (id: string) => (id === bot ? `${nameOf(id)}(나)` : nameOf(id));
|
||||
const rows = (Array.isArray(v.seats) ? v.seats : Array.isArray(v.players) ? v.players : []) as Record<string, unknown>[];
|
||||
const per: string[] = [];
|
||||
for (const r of rows) {
|
||||
if (!r || typeof r !== 'object' || typeof r.id !== 'string') continue;
|
||||
const bits: string[] = [];
|
||||
const stack = num(r.stack);
|
||||
if (stack !== null) bits.push(`칩 ${stack}`);
|
||||
const cash = num(r.cash);
|
||||
if (cash !== null) bits.push(`돈 ${cash}`);
|
||||
const score = num(r.score) ?? num(r.total);
|
||||
if (score !== null) bits.push(`${score}점`);
|
||||
const cards = num(r.cards) ?? num(r.handCount);
|
||||
if (cards !== null) bits.push(`카드 ${cards}장`);
|
||||
const tiles = num(r.tiles);
|
||||
if (tiles !== null) bits.push(`타일 ${tiles}장`);
|
||||
if (r.folded === true) bits.push('다이함');
|
||||
if (r.allIn === true) bits.push('올인함');
|
||||
if (bits.length) per.push(`${who(r.id)} ${bits.join(' ')}`);
|
||||
}
|
||||
for (const [key, label] of [['money', '돈'], ['sheets', '점']] as const) {
|
||||
const rec = v[key];
|
||||
if (!per.length && rec && typeof rec === 'object' && !Array.isArray(rec)) {
|
||||
for (const [id, x] of Object.entries(rec as Record<string, unknown>)) {
|
||||
const n = num(x) ?? num((x as { total?: unknown } | null)?.total);
|
||||
if (n !== null) per.push(label === '점' ? `${who(id)} ${n}점` : `${who(id)} 돈 ${n}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (per.length) out.push(per.slice(0, 6).join(', '));
|
||||
return out;
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { openDb } from '../db';
|
||||
import { RoomManager } from '../rooms/manager';
|
||||
import type { Room } from '../rooms/room';
|
||||
import { RoomStore } from '../rooms/store';
|
||||
import { BotBrain } from './brain';
|
||||
import { cannedLines, contradicts, KNOWN_ACTIONS, meaningOf, tableFacts, type ActKind } from './acts';
|
||||
import { ANSWERS_PER_MINUTE, BotBrain, TALK_BOT_GAP, TALK_ROOM_GAP, type BrainRoom } from './brain';
|
||||
import { cleanLine, temperOf, TEMPERS } from './lines';
|
||||
import { Llm } from './llm';
|
||||
|
||||
@@ -109,28 +110,27 @@ function harness(reply: (user: string, body: { format?: unknown }) => string | E
|
||||
const settle = () => new Promise((r) => setTimeout(r, 5));
|
||||
|
||||
describe('rooms with the model', () => {
|
||||
test('omok: the computer thinks (visible), types a taunt in the chat, then moves', async () => {
|
||||
test('omok: the computer thinks (visible) and moves; an ordinary move gets no word on its own (신고: 혼잣말)', async () => {
|
||||
const h = harness((u) => (u.includes('할 말') ? '흐음, 여기 두면 아프겠는데?' : '좋아'));
|
||||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' }, botChat: true });
|
||||
expect(room.start('A')).toBeNull();
|
||||
await settle();
|
||||
h.clock.advance(TALK_BOT_GAP);
|
||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||
const activity = a.msgs.filter((m) => m.t === 'room').map((m) => (m as { room: { botActivity?: Record<string, string> } }).room.botActivity ?? {});
|
||||
expect(activity.some((x) => Object.values(x).includes('thinking'))).toBe(true);
|
||||
room.bots.fire();
|
||||
for (let i = 0; i < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2; i++) await settle();
|
||||
expect((room.game!.state as { moves: unknown[] }).moves).toHaveLength(2);
|
||||
const chats = a.msgs.filter((m) => m.t === 'chat') as { from: { id: string } | null; text: string }[];
|
||||
expect(chats.some((c) => c.from && isBotId(c.from.id) && c.text === '흐음, 여기 두면 아프겠는데?')).toBe(true);
|
||||
// It typed for a while before sending, and "입력 중" was shown then cleared.
|
||||
expect(h.slept.some((ms) => ms >= 900)).toBe(true);
|
||||
// No greeting, no word with a stone: the model was only warmed up.
|
||||
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
|
||||
expect(h.prompts.every((p) => !p.includes('할 말'))).toBe(true);
|
||||
const last = a.msgs.filter((m) => m.t === 'room').at(-1) as { room: { botActivity?: object } };
|
||||
expect(last.room.botActivity).toBeUndefined();
|
||||
expect(h.prompts.some((p) => p.includes('오목'))).toBe(true);
|
||||
});
|
||||
|
||||
test('a person asks a computer by name: it answers in the room chat', async () => {
|
||||
@@ -139,6 +139,7 @@ describe('rooms with the model', () => {
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
room.configure('A', { botChat: true });
|
||||
expect(room.start('A')).toBeNull();
|
||||
room.chat('A', '컴퓨터 1 오목 잘해?');
|
||||
for (let i = 0; i < 20 && !a.msgs.some((m) => m.t === 'chat' && (m as { text: string }).text.startsWith('저요?')); i++) await settle();
|
||||
@@ -172,6 +173,7 @@ describe('rooms with the model', () => {
|
||||
rooms.push(room);
|
||||
const a = h.conn(`A${attempt}`);
|
||||
room.join(a, 'player');
|
||||
room.configure(`A${attempt}`, { botChat: true });
|
||||
expect(room.start(`A${attempt}`)).toBeNull();
|
||||
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
|
||||
if (!isBotId(st().round.starter)) continue;
|
||||
@@ -190,6 +192,59 @@ describe('rooms with the model', () => {
|
||||
expect(checked).toBe(true);
|
||||
});
|
||||
|
||||
test('컴퓨터 채팅 off (the default): computers never talk on their own — no taunts, answers, greetings or end words', async () => {
|
||||
const h = harness(() => '흐음, 여기 두면 아프겠는데?', () => 0);
|
||||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.roomView().botChat).toBe(false);
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
await settle();
|
||||
room.chat('A', '컴퓨터 1 오목 잘해?');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
room.act('A', i + 1, { type: 'place', x: [0, 14, 0][i]!, y: [0, 14, 14][i]! });
|
||||
room.bots.fire();
|
||||
for (let k = 0; k < 20 && (room.game!.state as { moves: unknown[] }).moves.length < 2 * (i + 1); k++) await settle();
|
||||
}
|
||||
expect((room.game!.state as { moves: unknown[] }).moves.length).toBe(6);
|
||||
expect(a.msgs.some((m) => m.t === 'chat' && (m as { from: { id: string } | null }).from && isBotId((m as { from: { id: string } }).from.id))).toBe(false);
|
||||
// The model isn't even warmed up: nothing in this game uses it.
|
||||
expect(h.prompts).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('컴퓨터 채팅 off: in 바퀴벌레 포커 the model still decides truth or bluff, the computer just says nothing', async () => {
|
||||
let checked = false;
|
||||
for (let attempt = 0; attempt < 12 && !checked; attempt++) {
|
||||
const h = harness((_u, body) => (body.format ? JSON.stringify({ bluff: false, say: '이건 진짜야, 믿어봐~' }) : '흠'));
|
||||
const room = h.manager.createPractice(`B${attempt}`, 'cockroach-poker') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn(`B${attempt}`);
|
||||
room.join(a, 'player');
|
||||
expect(room.start(`B${attempt}`)).toBeNull();
|
||||
const st = () => room.game!.state as { round: { claim: string | null; card: string | null; starter: string } };
|
||||
if (!isBotId(st().round.starter)) continue;
|
||||
for (let i = 0; i < 30 && !st().round.claim; i++) {
|
||||
room.bots.fire();
|
||||
await settle();
|
||||
}
|
||||
expect(st().round.claim).toBe(st().round.card!.replace(/-\d+$/, ''));
|
||||
expect(a.msgs.some((m) => m.t === 'chat')).toBe(false);
|
||||
checked = true;
|
||||
}
|
||||
expect(checked).toBe(true);
|
||||
});
|
||||
|
||||
test('마피아 needs its computers to talk: 컴퓨터 채팅 is always on there', () => {
|
||||
const h = harness(() => '흠');
|
||||
const room = h.manager.createPractice('A', 'mafia') as Room;
|
||||
rooms.push(room);
|
||||
room.join(h.conn('A'), 'player');
|
||||
room.configure('A', { botChat: false });
|
||||
expect(room.roomView().botChat).toBe(true);
|
||||
});
|
||||
|
||||
test('마피아: a computer says its planned line in its own words; a line claiming a role is thrown away', async () => {
|
||||
let n = 0;
|
||||
const h = harness(() => (n++ % 2 === 0 ? '안녕하세요~ 오늘 마피아 꼭 잡아봐요!' : '저 경찰이에요 믿어주세요'));
|
||||
@@ -211,11 +266,402 @@ describe('rooms with the model', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('BotBrain typing time grows with the line and stays human (0.9~6.5 s)', () => {
|
||||
test('BotBrain typing time grows with the line and stays quick (0.7~3.5 s)', () => {
|
||||
const brain = new BotBrain({} as never, null);
|
||||
const short = brain.typingMs('bot:1:x', 'ㅋㅋ');
|
||||
const long = brain.typingMs('bot:1:x', '이번 판은 내가 무조건 이긴다 각오해라 진짜로');
|
||||
expect(short).toBeGreaterThanOrEqual(900);
|
||||
expect(short).toBeGreaterThanOrEqual(700);
|
||||
expect(long).toBeGreaterThan(short);
|
||||
expect(long).toBeLessThanOrEqual(6500);
|
||||
for (let i = 0; i < 50; i++) expect(brain.typingMs(`bot:${i}:x`, '가'.repeat(40))).toBeLessThanOrEqual(3500);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- talking (fake room, fake model)
|
||||
|
||||
|
||||
/**
|
||||
* A BotBrain on a fake room: 철수 (A) with `bots` computers at 섯다. The model answers with `reply(prompt)`. Typing
|
||||
* advances the room clock; `hold` keeps a computer typing until `release()`.
|
||||
*/
|
||||
function talkHarness(
|
||||
reply: (user: string) => string | Error,
|
||||
opts: { bots?: number; humans?: string[]; random?: () => number; game?: string; llm?: (fetchFn: typeof fetch) => Llm | null } = {},
|
||||
) {
|
||||
let now = 1_000_000;
|
||||
const bots = Array.from({ length: opts.bots ?? 2 }, (_, i) => `bot:${i + 1}:x`);
|
||||
const humans = opts.humans ?? ['A'];
|
||||
const chats: { from: string; text: string; at: number }[] = [];
|
||||
const activity: { bot: string; a: string | null; at: number }[] = [];
|
||||
let hold: Promise<void> | null = null;
|
||||
let release = () => {};
|
||||
const { fetchFn, prompts } = fakeOllama((u) => reply(u));
|
||||
const llm = opts.llm ? opts.llm(fetchFn) : new Llm({ url: 'http://gpu', model: 'gemma3:4b', fetch: fetchFn });
|
||||
const view = { pot: 120, seats: [{ id: 'A', stack: 800, folded: false }, ...bots.map((b) => ({ id: b, stack: 500, folded: false }))] };
|
||||
const room: BrainRoom = {
|
||||
gameId: () => opts.game ?? 'seotda',
|
||||
gameName: () => '섯다',
|
||||
nameOf: (id) => (id === 'A' ? '철수' : id === 'B' ? '영희' : `컴퓨터 ${id.split(':')[1]}`),
|
||||
humans: () => humans,
|
||||
bots: () => bots,
|
||||
playing: () => true,
|
||||
roomChat: (bot, text) => void chats.push({ from: bot, text, at: now }),
|
||||
setActivity: (bot, a) => void activity.push({ bot, a, at: now }),
|
||||
recentChat: () => chats.slice(-8).map((c) => ({ from: c.from, text: c.text })),
|
||||
smart: () => false,
|
||||
chatty: () => true,
|
||||
now: () => now,
|
||||
view: () => view,
|
||||
};
|
||||
const brain = new BotBrain(room, llm, opts.random ?? (() => 0), async (ms) => {
|
||||
now += ms;
|
||||
if (hold) await hold;
|
||||
});
|
||||
return {
|
||||
brain,
|
||||
bots,
|
||||
chats,
|
||||
activity,
|
||||
prompts,
|
||||
advance: (ms: number) => (now += ms),
|
||||
now: () => now,
|
||||
holdTyping: () => {
|
||||
hold = new Promise<void>((r) => (release = () => ((hold = null), r())));
|
||||
},
|
||||
release: () => release(),
|
||||
/** Lets the fake model and typing finish. */
|
||||
flush: async () => {
|
||||
for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('answering people (신고: 한 번 답하고 그 뒤로 답장이 없음)', () => {
|
||||
test('every message to a computer gets an answer — named once, then just talking to it', async () => {
|
||||
let n = 0;
|
||||
// random 0.99: nothing is left to chance (the old code answered an unnamed line only 40% of the time).
|
||||
const h = talkHarness(() => `대답 ${++n}번째 ㅋㅋ`, { random: () => 0.99 });
|
||||
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', 'ㅋㅋ 너 지금 쫄았지?', '야', '이번 판 누가 이길 것 같아?'];
|
||||
for (const text of msgs) {
|
||||
h.brain.onHumanChat('A', text);
|
||||
await h.flush();
|
||||
h.advance(4000);
|
||||
}
|
||||
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
|
||||
expect(h.chats).toHaveLength(msgs.length);
|
||||
// Each prompt carries the person's message.
|
||||
for (const text of msgs) expect(h.prompts.some((p) => p.includes(text))).toBe(true);
|
||||
});
|
||||
|
||||
test('a message while the computer is typing is answered right after it, not dropped; a burst gets one answer', async () => {
|
||||
const h = talkHarness((u) => (u.includes('뒤질래') ? '어휴 무섭네 ㅋㅋ' : u.includes('세 번째') ? '세 번째에 대답 ㅋㅋ' : '첫 마디 ㅋㅋ'));
|
||||
h.holdTyping();
|
||||
h.brain.onHumanChat('A', '컴퓨터 1 안녕');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(0); // still typing
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 두 번째');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 세 번째');
|
||||
h.release();
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['첫 마디 ㅋㅋ', '세 번째에 대답 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('the model writes something unusable (rude, echo): the computer still answers, with a safe line', async () => {
|
||||
const h = talkHarness(() => '철수 이 망할 놈! 닥쳐 ㅋㅋ');
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뒤질래?');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(h.chats[0]!.text).not.toMatch(/놈|닥쳐/);
|
||||
});
|
||||
|
||||
test('with two people, an unnamed line is not taken as talking to a computer (unless it answers one)', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
|
||||
h.brain.onHumanChat('A', '영희야 이번 판 어때');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(0);
|
||||
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x']);
|
||||
h.advance(5000);
|
||||
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?'); // right after 컴퓨터 2 spoke: an answer to it
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.from)).toEqual(['bot:2:x', 'bot:2:x']);
|
||||
});
|
||||
|
||||
test('quick: "입력 중…" shows at once, a short answer is up within 3 s and a long one within 3.5 s', async () => {
|
||||
for (const [line, limit] of [['ㅋㅋ 내가 이기지', 3000], ['이번 판은 칩 많은 내가 무조건 가져간다 각오해 ㅋㅋ', 3500]] as const) {
|
||||
const h = talkHarness(() => line);
|
||||
const t0 = h.now();
|
||||
h.brain.onHumanChat('A', '컴퓨터1 누가 이겨?');
|
||||
// Before the model has answered: typing already shows.
|
||||
expect(h.activity[0]).toEqual({ bot: 'bot:1:x', a: 'typing', at: t0 });
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(h.chats[0]!.at - t0).toBeLessThanOrEqual(limit);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('answering without a quick model (신고: 답장이 느림)', () => {
|
||||
test('no model at all: every message to a computer still gets a fitting built-in answer, fast', async () => {
|
||||
const h = talkHarness(() => 'x', { llm: () => null });
|
||||
const msgs = ['컴퓨터1 뒤질래?', '왜 대답 안해', '컴퓨터1 안녕', '이번 판 누가 이길 것 같아?'];
|
||||
for (const text of msgs) {
|
||||
const t0 = h.now();
|
||||
h.brain.onHumanChat('A', text);
|
||||
await h.flush();
|
||||
expect(h.chats.at(-1)!.at - t0).toBeLessThanOrEqual(3500);
|
||||
h.advance(4000);
|
||||
}
|
||||
expect(h.chats.map((c) => c.from)).toEqual(msgs.map(() => 'bot:1:x'));
|
||||
const [jab, , hello, question] = h.chats.map((c) => c.text);
|
||||
expect(['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ']).toContain(jab!);
|
||||
expect(['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!']).toContain(hello!);
|
||||
expect(['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ']).toContain(question!);
|
||||
for (const c of h.chats) expect(cleanLine(c.text)).toBe(c.text);
|
||||
});
|
||||
|
||||
test('a hung model: the built-in answer is up within the wait (2.5 s), not after the model gives up', async () => {
|
||||
const hang = (async (_u: string, init: RequestInit) =>
|
||||
new Promise((_, rej) => init.signal!.addEventListener('abort', () => rej(new Error('aborted'))))) as unknown as typeof fetch;
|
||||
const h = talkHarness(() => 'x', { llm: () => new Llm({ url: 'http://gpu', model: 'm', fetch: hang, timeoutMs: 3000 }) });
|
||||
const t0 = Date.now();
|
||||
h.brain.onHumanChat('A', '컴퓨터1 뭐해?');
|
||||
for (let i = 0; i < 400 && !h.chats.length; i++) await new Promise((r) => setTimeout(r, 10));
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(Date.now() - t0).toBeLessThan(2900);
|
||||
expect(h.activity[0]!.a).toBe('typing'); // "입력 중…" from the start
|
||||
});
|
||||
|
||||
test('a flood is cut off: at most a few answers a minute to one person', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ');
|
||||
for (let i = 0; i < 40; i++) {
|
||||
h.brain.onHumanChat('A', `컴퓨터1 ${i}`);
|
||||
await h.flush();
|
||||
h.advance(1500);
|
||||
}
|
||||
expect(h.chats.length).toBeGreaterThanOrEqual(ANSWERS_PER_MINUTE);
|
||||
expect(h.chats.length).toBeLessThanOrEqual(ANSWERS_PER_MINUTE * 2);
|
||||
});
|
||||
|
||||
test('two people: after a computer answered, the next line is an answer to it — later lines between people are not', async () => {
|
||||
const h = talkHarness(() => '응 ㅋㅋ', { humans: ['A', 'B'], random: () => 0.99 });
|
||||
h.brain.onHumanChat('A', '컴퓨터 2 너는?');
|
||||
await h.flush();
|
||||
h.advance(3000);
|
||||
h.brain.onHumanChat('B', 'ㅋㅋ 진짜?');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(2);
|
||||
h.advance(1000);
|
||||
h.brain.onHumanChat('A', '영희야 우리 둘이 하자');
|
||||
h.brain.onHumanChat('B', '그래 좋아');
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('talking on its own (신고: 게임과 상관없는 혼잣말만 엄청함)', () => {
|
||||
test('rare: over 10 minutes of busy play at most one line per 40 s in the room and per 90 s per computer', async () => {
|
||||
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ 받아줄게');
|
||||
for (let t = 0; t < 600_000; t += 2000) {
|
||||
h.brain.onAction('A', { type: t % 4000 ? 'half' : 'call' });
|
||||
for (const b of h.bots) await h.brain.beforeMove(b, { type: 'full' }, {});
|
||||
await h.flush();
|
||||
h.advance(2000);
|
||||
}
|
||||
const lines = h.chats.length;
|
||||
expect(lines).toBeGreaterThan(0);
|
||||
expect(lines).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_ROOM_GAP));
|
||||
for (const b of h.bots) expect(h.chats.filter((c) => c.from === b).length).toBeLessThanOrEqual(Math.ceil(700_000 / TALK_BOT_GAP));
|
||||
for (let i = 1; i < h.chats.length; i++) expect(h.chats[i]!.at - h.chats[i - 1]!.at).toBeGreaterThanOrEqual(TALK_ROOM_GAP - 4000);
|
||||
});
|
||||
|
||||
test("a person's ordinary move never gets a word on its own", async () => {
|
||||
const h = talkHarness(() => '판돈 커졌네 ㅋㅋ');
|
||||
for (let i = 0; i < 30; i++) {
|
||||
h.brain.onAction('A', { type: 'call' });
|
||||
h.brain.onAction('A', { type: 'check' });
|
||||
await h.flush();
|
||||
h.advance(30_000);
|
||||
}
|
||||
expect(h.chats).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('the prompt has the facts: who did what, what it means, the pot and stacks', async () => {
|
||||
const h = talkHarness(() => '오 철수 세게 나오네 ㅋㅋ');
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
const p = h.prompts.at(-1)!;
|
||||
expect(p).toContain('철수: 풀 베팅 — 판돈만큼 더 거는 가장 센 베팅');
|
||||
expect(p).toContain('판돈 120');
|
||||
expect(p).toContain('컴퓨터 1(나) 칩 500');
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['오 철수 세게 나오네 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('a line about nothing in this game ("다들 준비됐냐?") is not said: a line for the move is said instead', async () => {
|
||||
const h = talkHarness(() => '흥, 또 시작이네 ㅋㅋ 다들 준비됐냐?');
|
||||
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
|
||||
h.advance(TALK_ROOM_GAP);
|
||||
h.brain.onAction('A', { type: 'die' });
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual([
|
||||
cannedLines(meaningOf('seotda', { type: 'full' }), '컴퓨터 1', false, true)[0]!,
|
||||
cannedLines(meaningOf('seotda', { type: 'die' }), '철수', false, false)[0]!,
|
||||
]);
|
||||
expect(h.chats.some((c) => c.text.includes('준비'))).toBe(false);
|
||||
});
|
||||
|
||||
test('without the model the computers play silently; a notable move gets a word only while the model is up', async () => {
|
||||
const h = talkHarness(() => new Error('down'));
|
||||
for (let i = 0; i < 4; i++) {
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
h.advance(TALK_BOT_GAP);
|
||||
}
|
||||
// The model failed three times and is backing off: no more words on its own (the first ones were built-in lines).
|
||||
const said = h.chats.length;
|
||||
expect(said).toBeLessThanOrEqual(3);
|
||||
for (const c of h.chats) expect(cannedLines(meaningOf('seotda', { type: 'full' }), '철수', false, false)).toContain(c.text);
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
expect(h.chats).toHaveLength(said);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lines that contradict the move (신고: 풀 베팅인데 "쫄았네")', () => {
|
||||
test('풀 베팅 → "쫄았네" is thrown away and a safe line said instead; 다이 → "세게 나오네" likewise', async () => {
|
||||
const h = talkHarness(() => 'ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!');
|
||||
h.brain.onAction('A', { type: 'full' });
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['오 철수, 풀 베팅? 세게 나오네 ㅋㅋ']);
|
||||
const d = talkHarness(() => '철수 오늘 세게 나오네 ㅋㅋ');
|
||||
d.brain.onAction('A', { type: 'die' });
|
||||
await d.flush();
|
||||
expect(d.chats.map((c) => c.text)).toEqual(['철수 이번엔 다이? 다음 판에 보자 ㅋㅋ']);
|
||||
});
|
||||
|
||||
test('my own 풀 베팅 with "무섭다, 포기할까" or a wrong bet name is not said (a line for a raise is)', async () => {
|
||||
for (const bad of ['아 무섭다 그냥 포기할까 ㅋㅋ', '다이할게 판돈 가져가라 ㅋㅋ']) {
|
||||
const h = talkHarness(() => bad);
|
||||
await h.brain.beforeMove('bot:1:x', { type: 'full' }, {});
|
||||
await h.flush();
|
||||
expect(h.chats.map((c) => c.text)).toEqual(['풀 베팅 간다! 따라올 수 있어? ㅋㅋ']);
|
||||
}
|
||||
});
|
||||
|
||||
test('each kind of move has its own lines, and every line fits only its kind (no "쫄" on a raise)', () => {
|
||||
const kinds: Record<string, ActKind> = {
|
||||
half: 'raise', full: 'raise', ddadang: 'raise', quarter: 'raise', 'k.half': 'raise', 'k.full': 'raise', 'k.ddadang': 'raise',
|
||||
'nl.raise': 'raise', 'nl.allIn': 'raise', call: 'call', 'k.call': 'call', 'nl.call': 'call',
|
||||
check: 'check', ping: 'check', 'k.check': 'check', 'k.ping': 'check', 'nl.check': 'check', die: 'fold', 'k.die': 'fold', 'nl.fold': 'fold',
|
||||
};
|
||||
for (const [type, kind] of Object.entries(kinds)) expect([type, meaningOf('seotda', { type }).kind]).toEqual([type, kind]);
|
||||
// A rebuilt game may put the bet in the payload.
|
||||
expect(meaningOf('seotda', { type: 'bet', bet: 'half' }).kind).toBe('raise');
|
||||
expect(meaningOf('seotda', { type: 'bet', kind: 'die' }).kind).toBe('fold');
|
||||
const SCARED = /쫄|겁|무서|소심|도망|엄살|떨/;
|
||||
const BRAVE = /세게|과감|질렀|배짱|화끈|자신|올인|풀\s?베팅/;
|
||||
const metas = [
|
||||
...KNOWN_ACTIONS.map((type) => meaningOf('seotda', { type })),
|
||||
meaningOf('gostop', { type: 'goStop', decision: 'go' }),
|
||||
meaningOf('gostop', { type: 'goStop', decision: 'stop' }),
|
||||
meaningOf('mahjong', { type: 'claim', call: 'ron' }),
|
||||
];
|
||||
let checked = 0;
|
||||
for (const meaning of metas) {
|
||||
for (const smart of [true, false]) {
|
||||
for (const mine of [true, false]) {
|
||||
const lines = cannedLines(meaning, '철수', smart, mine);
|
||||
// Notable moves always have a fitting line (unless deliberately neutral); ordinary moves never get one.
|
||||
if (meaning.kind === 'neutral') expect(lines).toEqual([]);
|
||||
else expect(lines.length).toBeGreaterThan(1);
|
||||
for (const line of lines) {
|
||||
checked++;
|
||||
expect([meaning.ko, line, contradicts(line, meaning, mine)]).toEqual([meaning.ko, line, false]);
|
||||
expect(cleanLine(line, 40)).toBe(line);
|
||||
if (meaning.kind === 'raise' || meaning.kind === 'bold') expect([meaning.ko, line, SCARED.test(line)]).toEqual([meaning.ko, line, false]);
|
||||
if (['fold', 'check', 'safe', 'giveUp', 'call'].includes(meaning.kind)) expect([meaning.ko, line, BRAVE.test(line)]).toEqual([meaning.ko, line, false]);
|
||||
// A 존댓말 computer never talks down.
|
||||
if (smart) expect(line).toMatch(/요|죠/);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(checked).toBeGreaterThan(150);
|
||||
});
|
||||
|
||||
test('every kind of bet, with the model writing the opposite: the line said fits the bet', async () => {
|
||||
const wrong: Record<string, string> = {
|
||||
full: 'ㅋㅋ 풀 베팅이라니, 완전 쫄았네 풉!',
|
||||
half: '겁먹었구나 철수 ㅋㅋ 하프 베팅',
|
||||
ddadang: '따당? 떨고 있네 ㅋㅋ',
|
||||
die: '다이? 와 과감하게 질렀네 ㅋㅋ',
|
||||
check: '체크? 화끈하게 지르네 ㅋㅋ',
|
||||
ping: '삥이라니 배짱 좋네 ㅋㅋ',
|
||||
};
|
||||
for (const [type, bad] of Object.entries(wrong)) {
|
||||
const h = talkHarness(() => bad);
|
||||
h.brain.onAction('A', { type });
|
||||
await h.flush();
|
||||
const meaning = meaningOf('seotda', { type });
|
||||
if (!meaning.notable) {
|
||||
expect(h.chats).toHaveLength(0); // 체크·삥: ordinary, no word at all
|
||||
continue;
|
||||
}
|
||||
expect(h.chats).toHaveLength(1);
|
||||
expect(cannedLines(meaning, '철수', false, false)).toContain(h.chats[0]!.text);
|
||||
}
|
||||
});
|
||||
|
||||
test('rules: who made the move matters; other games are not judged by bet names', () => {
|
||||
const full = meaningOf('seotda', { type: 'full' });
|
||||
const die = meaningOf('seotda', { type: 'die' });
|
||||
expect(contradicts('ㅋㅋ 풀 베팅이라니, 완전 쫄앗네 풉!', full, false)).toBe(true);
|
||||
expect(contradicts('겁먹었냐? ㅋㅋ', full, false)).toBe(true);
|
||||
expect(contradicts('내 풀 베팅에 쫄았지? ㅋㅋ', full, true)).toBe(false); // my big bet, the others scared: fine
|
||||
expect(contradicts('오 세게 나오네 판돈 커졌다', full, false)).toBe(false);
|
||||
expect(contradicts('벌써 다이야? 쫄았구나 ㅋㅋ', die, false)).toBe(false);
|
||||
expect(contradicts('와 과감하게 질렀네', die, false)).toBe(true);
|
||||
expect(contradicts('하프 베팅이라니 대단해', full, false)).toBe(true); // a bet that wasn't made
|
||||
expect(contradicts('하프 받고 풀 베팅 간다', full, true, ['하프 베팅'])).toBe(false); // it was, just before
|
||||
expect(contradicts('여기 두면 아프겠는데? 체크야', meaningOf('omok', { type: 'place' }), true)).toBe(false);
|
||||
expect(meaningOf('poker', { type: 'k.full' }).tone).toBe('strong');
|
||||
expect(meaningOf('gostop', { type: 'goStop', decision: 'go' }).ko).toBe('고');
|
||||
expect(meaningOf('gostop', { type: 'goStop', decision: 'stop' }).tone).toBe('careful');
|
||||
});
|
||||
|
||||
test('table facts read only public numbers (stacks, scores, card counts), never a hand', () => {
|
||||
const names = (id: string) => (id === 'A' ? '철수' : '컴퓨터 1');
|
||||
expect(tableFacts({ pot: 30, seats: [{ id: 'A', stack: 990, folded: true, cards: [{ hidden: true }] }, { id: 'bot:1:x', stack: 980 }], myHand: { name: '38광땡' } }, 'bot:1:x', names)).toEqual([
|
||||
'판돈 30',
|
||||
'철수 칩 990 다이함, 컴퓨터 1(나) 칩 980',
|
||||
]);
|
||||
expect(tableFacts({ seats: [{ id: 'A', cards: 3, score: 10 }] }, 'bot:1:x', names)).toEqual(['철수 10점 카드 3장']);
|
||||
expect(tableFacts({ sheets: { A: { total: 120 } } }, 'bot:1:x', names)).toEqual(['철수 120점']);
|
||||
expect(tableFacts(null, 'bot:1:x', names)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Llm queue (one GPU slot)', () => {
|
||||
test('one request at a time; an answer to a person goes ahead of waiting talk; talk is dropped when busy', async () => {
|
||||
const order: string[] = [];
|
||||
let open = 0;
|
||||
let maxOpen = 0;
|
||||
const fetchFn = (async (_u: string, init: RequestInit) => {
|
||||
const body = JSON.parse(String(init.body)) as { messages: { content: string }[]; options: { stop?: string[] } };
|
||||
open++;
|
||||
maxOpen = Math.max(maxOpen, open);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
order.push(body.messages[0]!.content);
|
||||
open--;
|
||||
return new Response(JSON.stringify({ message: { content: 'ok' } }));
|
||||
}) as unknown as typeof fetch;
|
||||
const llm = new Llm({ url: 'http://x', model: 'm', fetch: fetchFn });
|
||||
const first = llm.chat([{ role: 'user', content: 'first' }]);
|
||||
const normal = llm.chat([{ role: 'user', content: 'normal' }]);
|
||||
const answer = llm.chat([{ role: 'user', content: 'answer' }], { priority: 'high' });
|
||||
expect(await llm.chat([{ role: 'user', content: 'talk' }], { priority: 'low' })).toBeNull();
|
||||
await Promise.all([first, normal, answer]);
|
||||
expect(order).toEqual(['first', 'answer', 'normal']);
|
||||
expect(maxOpen).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,14 +3,23 @@
|
||||
*
|
||||
* - They show what they are doing: "생각 중…" while choosing a move and "입력 중…" while typing, for as long as a
|
||||
* person would take to type that line — then they send it and make the move ("채팅 치고 클릭").
|
||||
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말): a word with their own move, a reaction
|
||||
* to a person's move, answers when people chat, a greeting at the start and a word at the end.
|
||||
* - They talk in character (도발형·허세형·차분형·수다형·소심형, 존댓말/반말). A person who talks to a computer (by
|
||||
* name, by answering what it just said, or as the only computer at the table) always gets an answer within a few
|
||||
* seconds — the model's if it is quick, a built-in one if it is slow, busy or down (a flood is cut off).
|
||||
* - On their own they speak rarely and only about what just happened at this table (a big bet, someone folding,
|
||||
* 고/스톱…; never an ordinary move, never a greeting or small talk), with the move's meaning and the table's public
|
||||
* facts in the prompt. A line that contradicts the move ("풀 베팅이라니 쫄았네") or is about nothing in this game
|
||||
* is replaced with a built-in line made for that kind of move (acts.ts).
|
||||
* - Psychological choices go to the model: in 바퀴벌레 포커 it decides whether to tell the truth or bluff, and says
|
||||
* something to sell it. In 마피아 it says each line of the computer's plan in its own words.
|
||||
* Moves themselves still come from each game's computer strategy (it sees only its own screen). Without a model
|
||||
* (not configured, busy, down) the computers simply play as before, silently, and 마피아 uses its built-in lines.
|
||||
* Talking on their own is a room setting (`chatty`, off by default); 마피아 talks always because the game needs it.
|
||||
*/
|
||||
import { secureRandom } from '@bg/engine';
|
||||
import { botPace, hash01 } from '@bg/games/bots';
|
||||
import { botChatRequired } from '@bg/shared';
|
||||
import { cannedLine, contradicts, meaningOf, tableFacts, type ActMeaning } from './acts';
|
||||
import type { Llm } from './llm';
|
||||
import { cleanLine, decide, temperOf, writeLine, type LineRequest } from './lines';
|
||||
|
||||
@@ -28,32 +37,91 @@ export interface BrainRoom {
|
||||
roomChat(bot: string, text: string): void;
|
||||
setActivity(bot: string, a: BotActivity | null): void;
|
||||
recentChat(): { from: string; text: string }[];
|
||||
/** 똑똑한 편 (존댓말) or 허술한 편 (반말), docs/09 §9.1. */
|
||||
smart(bot: string): boolean;
|
||||
/**
|
||||
* The computers may chat on their own (room setting "컴퓨터 채팅"; always on in 마피아). Off: no small talk,
|
||||
* reactions, answers, greetings or end-of-game words — they just play (still showing "생각 중…").
|
||||
*/
|
||||
chatty(): boolean;
|
||||
now(): number;
|
||||
/** What `viewer` sees of the running game (public facts for the prompt); null outside a game. */
|
||||
view?(viewer: string): unknown;
|
||||
}
|
||||
|
||||
/** A few words for what someone just did (any game). */
|
||||
const ACTION_KO: Record<string, string> = {
|
||||
place: '돌을 놓음', move: '말을 움직임', MOVE: '말을 움직임', placeWall: '벽을 세움', castle: '캐슬링',
|
||||
play: '카드를 냄', discard: '패를 버림', DISCARD: '패를 버림', draw: '패를 가져옴', pass: '넘김', PASS: '넘김',
|
||||
call: '콜', check: '체크', die: '다이(포기)', half: '하프 베팅', quarter: '쿼터 베팅', ddadang: '따당', full: '풀 베팅',
|
||||
roll: '주사위를 굴림', hold: '주사위를 고정함', score: '점수를 적음', guess: '추리함', stop: '멈춤', continue: '계속 추리',
|
||||
offer: '카드를 건넴', peek: '카드를 몰래 봄', claim: '선언함', declare: '선언함', tsumo: '쯔모', ring: '종을 침',
|
||||
flip: '카드를 뒤집음', BUY: '땅을 삼', sell: '땅을 팖', THROW: '윷을 던짐', commit: '타일을 내려놓음', goStop: '고/스톱',
|
||||
respond: '대답함', resign: '기권', concede: '기권', CONCEDE: '기권', giveUp: '포기', choose: '골랐음', vote: '투표',
|
||||
};
|
||||
/** Talking on its own: at most one line per room every 40 s, and per computer every 90 s. */
|
||||
export const TALK_ROOM_GAP = 40_000;
|
||||
export const TALK_BOT_GAP = 90_000;
|
||||
/** A person keeps talking with the computer that answered them this long without naming it again (1 person rooms). */
|
||||
export const CONVERSATION_MS = 60_000;
|
||||
/** A line right after a computer's line is an answer to it. */
|
||||
const REPLY_MS = 20_000;
|
||||
/** Chance a computer reacts to a person's notable move (big bet, folding, 고, …) when it may talk. */
|
||||
const REACT_P = 0.3;
|
||||
/** How long an answer waits for the model before a built-in one is said instead. */
|
||||
export const ANSWER_WAIT_MS = 2500;
|
||||
/** A word about a move is dropped after this long (the game has moved on). */
|
||||
const TALK_WAIT_MS = 4000;
|
||||
/** Answers to one person: at most this many a minute (someone flooding a computer is not answered line by line). */
|
||||
export const ANSWERS_PER_MINUTE = 8;
|
||||
|
||||
/** Built-in answers (the model slow, busy, down, or its line unusable): by what the person said. */
|
||||
const QUICK_ANSWER: { test: RegExp; smart: string[]; casual: string[] }[] = [
|
||||
{ test: /안녕|ㅎㅇ|하이|반가/, smart: ['안녕하세요! 잘 부탁드려요.', '반가워요! 재밌게 해 봐요.'], casual: ['ㅎㅇ! 잘 해 보자 ㅋㅋ', '안녕~ 한 판 붙자!'] },
|
||||
{
|
||||
test: /뒤질|뒤져|죽을|죽여|쫄|겁|덤벼|이길\s?수|못\s?하|약하|ㅗ|ㅄ|\*{2,}/,
|
||||
smart: ['하하, 실력으로 답해 드릴게요.', '말보다 게임으로 보여 드릴게요.'],
|
||||
casual: ['ㅋㅋ 말로 하지 말고 게임으로 해!', '워워~ 판에서 보자 ㅋㅋ'],
|
||||
},
|
||||
{
|
||||
test: /\?|뭐|왜|누가|누구|어때|어떻게|몇|언제|할래|하냐|했냐|맞지|맞아/,
|
||||
smart: ['글쎄요, 두고 보시죠!', '음… 그건 비밀이에요.', '판이 끝나 보면 알겠죠?'],
|
||||
casual: ['ㅋㅋ 글쎄~ 두고 봐', '비밀이지롱~', '끝나 보면 알겠지 ㅋㅋ'],
|
||||
},
|
||||
{ test: /[\s\S]/, smart: ['하하, 그러게요.', '네, 계속 해 봐요!'], casual: ['ㅋㅋ 그치', 'ㅇㅋ 계속 가자!'] },
|
||||
];
|
||||
|
||||
/** Waits for `p` at most `ms` (real time): null after that. */
|
||||
function withDeadline<T>(p: Promise<T | null>, ms: number): Promise<T | null> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const late = new Promise<null>((r) => (timer = setTimeout(() => r(null), ms)));
|
||||
return Promise.race([p.catch(() => null), late]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
/** Words that tie a line to the game (a line on its own must mention the move, a player or one of these). */
|
||||
const GAME_WORDS = /판돈|베팅|칩|점수|\d+점|패|카드|돌|주사위|윷|족보|땅|타일|보석|차례|이번 판|한 판|수(?![가-힣])|여기|두면|둬|둔다|놓/;
|
||||
|
||||
const sleepReal = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
|
||||
|
||||
interface Happening {
|
||||
actor: string;
|
||||
meaning: ActMeaning;
|
||||
}
|
||||
|
||||
export class BotBrain {
|
||||
private lastRoomLine = -Infinity;
|
||||
private lastBotLine = new Map<string, number>();
|
||||
private happened: string[] = [];
|
||||
private happened: Happening[] = [];
|
||||
/** Showing "입력 중…". */
|
||||
private typing = new Set<string>();
|
||||
/** Writing or typing an answer, or typing a line: a new message to it waits in `pending`. */
|
||||
private busy = new Set<string>();
|
||||
/** The latest message to a busy computer, answered as soon as it is free. */
|
||||
private pending = new Map<string, { from: string; text: string; reply: boolean }>();
|
||||
/** Who each person is talking with. */
|
||||
private partner = new Map<string, { bot: string; at: number }>();
|
||||
private lastSpeaker: { bot: string; at: number } | null = null;
|
||||
/** When a person last chatted (a line after it is not an answer to a computer's earlier line). */
|
||||
private lastHumanChat = -Infinity;
|
||||
/** When each person was last answered (for the flood limit). */
|
||||
private answered = new Map<string, number[]>();
|
||||
/** The last built-in answer of each computer (not said twice in a row). */
|
||||
private lastQuick = new Map<string, string>();
|
||||
|
||||
constructor(
|
||||
private room: BrainRoom,
|
||||
readonly llm: Llm | null,
|
||||
private random: () => number = Math.random,
|
||||
private random: () => number = secureRandom,
|
||||
private sleep: (ms: number) => Promise<void> = sleepReal,
|
||||
) {}
|
||||
|
||||
@@ -62,33 +130,60 @@ export class BotBrain {
|
||||
return !!this.llm && this.llm.available() && this.room.playing() && this.room.humans().length > 0;
|
||||
}
|
||||
|
||||
/** How long `bot` takes to type `text` (each computer types at its own speed). */
|
||||
/** Games whose computers talk by their own plan (마피아, 라이어 게임): no small talk or answers from here. */
|
||||
private planned(): boolean {
|
||||
return botChatRequired(this.room.gameId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers to people work in and out of a game (lobby, result screen) while the computers sit in the room, and
|
||||
* without the model too (built-in answers): someone who talks to a computer is never left without a word.
|
||||
*/
|
||||
private canAnswer(): boolean {
|
||||
return this.room.chatty() && !this.planned() && this.room.humans().length > 0 && this.room.bots().length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long `bot` takes to type `text` (each computer types at its own speed): 8~16 characters a second, at least
|
||||
* 0.7 s and at most 3.5 s, so a short answer is up within 1~3 s of the question (the model's time counts toward it).
|
||||
*/
|
||||
typingMs(bot: string, text: string): number {
|
||||
const perChar = (120 + 90 * hash01(bot, 'typing')) * botPace(bot);
|
||||
return Math.round(Math.min(6500, Math.max(900, [...text].length * perChar)));
|
||||
const perChar = (60 + 40 * hash01(bot, 'typing')) * botPace(bot);
|
||||
return Math.round(Math.min(3500, Math.max(700, [...text].length * perChar)));
|
||||
}
|
||||
|
||||
thinking(bot: string, on: boolean): void {
|
||||
if (!this.typing.has(bot)) this.room.setActivity(bot, on ? 'thinking' : null);
|
||||
}
|
||||
|
||||
private showTyping(bot: string, on: boolean): void {
|
||||
if (on) this.typing.add(bot);
|
||||
else this.typing.delete(bot);
|
||||
this.room.setActivity(bot, on ? 'typing' : null);
|
||||
}
|
||||
|
||||
/** "입력 중…" for as long as typing takes, then `send` (skipped if the game ended meanwhile). */
|
||||
async type(bot: string, text: string, send: () => void, needPlaying = true): Promise<void> {
|
||||
this.typing.add(bot);
|
||||
this.room.setActivity(bot, 'typing');
|
||||
async type(bot: string, text: string, send: () => void, needPlaying = true, alreadyMs = 0): Promise<void> {
|
||||
this.busy.add(bot);
|
||||
this.showTyping(bot, true);
|
||||
try {
|
||||
await this.sleep(this.typingMs(bot, text));
|
||||
await this.sleep(Math.max(0, this.typingMs(bot, text) - alreadyMs));
|
||||
} finally {
|
||||
this.typing.delete(bot);
|
||||
this.room.setActivity(bot, null);
|
||||
this.showTyping(bot, false);
|
||||
this.busy.delete(bot);
|
||||
}
|
||||
if (!needPlaying || this.room.playing()) send();
|
||||
if (!needPlaying || this.room.playing()) {
|
||||
send();
|
||||
this.lastSpeaker = { bot, at: this.room.now() };
|
||||
}
|
||||
this.answerPending(bot);
|
||||
}
|
||||
|
||||
private request(bot: string, situation: string, task: string, extra: Partial<LineRequest> = {}): LineRequest {
|
||||
return {
|
||||
bot,
|
||||
name: this.room.nameOf(bot),
|
||||
smart: this.room.smart(bot),
|
||||
game: this.room.gameName(),
|
||||
situation,
|
||||
task,
|
||||
@@ -97,9 +192,10 @@ export class BotBrain {
|
||||
};
|
||||
}
|
||||
|
||||
private canTalk(bot: string, roomGap = 8000, botGap = 20_000): boolean {
|
||||
/** May talk on its own: rare (room and computer gaps) and never while busy. */
|
||||
private canTalk(bot: string): boolean {
|
||||
const now = this.room.now();
|
||||
return now - this.lastRoomLine >= roomGap && now - (this.lastBotLine.get(bot) ?? -Infinity) >= botGap && !this.typing.has(bot);
|
||||
return now - this.lastRoomLine >= TALK_ROOM_GAP && now - (this.lastBotLine.get(bot) ?? -Infinity) >= TALK_BOT_GAP && !this.busy.has(bot);
|
||||
}
|
||||
|
||||
private spoke(bot: string): void {
|
||||
@@ -108,30 +204,63 @@ export class BotBrain {
|
||||
this.lastBotLine.set(bot, now);
|
||||
}
|
||||
|
||||
private say(bot: string, line: string): Promise<void> {
|
||||
this.spoke(bot);
|
||||
return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
}
|
||||
|
||||
private situation(): string {
|
||||
/** What is going on, as facts: the last moves with what they mean, and the table (칩·점수·카드 수). */
|
||||
private situation(bot: string): string {
|
||||
const parts: string[] = [];
|
||||
const last = this.happened.slice(-4);
|
||||
return last.length ? `최근: ${last.join(', ')}` : '게임이 막 시작됐다';
|
||||
if (last.length) {
|
||||
const said = last.map((h, i) => `${this.room.nameOf(h.actor)}${h.actor === bot ? '(나)' : ''}: ${h.meaning.ko}${i === last.length - 1 && h.meaning.mean ? ` — ${h.meaning.mean}` : ''}`);
|
||||
parts.push(`방금 일어난 일(오래된 것부터): ${said.join(' / ')}`);
|
||||
} else parts.push('게임이 막 시작됐다');
|
||||
let view: unknown = null;
|
||||
try {
|
||||
view = this.room.view?.(bot) ?? null;
|
||||
} catch {
|
||||
view = null;
|
||||
}
|
||||
const facts = tableFacts(view, bot, (id) => this.room.nameOf(id));
|
||||
if (facts.length) parts.push(`지금 판: ${facts.join(' / ')}`);
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
/** Someone played: remembered for the computers' sense of the game; now and then a computer reacts to a person. */
|
||||
/** Move names that came up just before (a line may mention those). */
|
||||
private known(): string[] {
|
||||
return this.happened.slice(-3).map((h) => h.meaning.ko);
|
||||
}
|
||||
|
||||
/** A line said on its own must be about this game: the move, a player, or a game word. */
|
||||
private relevant(line: string, meaning: ActMeaning | null, people: string[]): boolean {
|
||||
if (GAME_WORDS.test(line)) return true;
|
||||
if (people.some((p) => p && (line.includes(p) || line.includes(p.replace(/\s/g, ''))))) return true;
|
||||
// "카드를 뒤집음" → 카드, 뒤집; a stem shorter than two letters is not used ("다이" → "다" would match "다들").
|
||||
const stems = (meaning?.ko ?? '').split(' ').map((w) => {
|
||||
const stem = w.replace(/(을|를|이|가|은|는|음|함)$/, '');
|
||||
return stem.length >= 2 ? stem : w;
|
||||
});
|
||||
return stems.some((w) => line.includes(w));
|
||||
}
|
||||
|
||||
/** Someone played: remembered for the computers' sense of the game; a notable move by a person may get a word. */
|
||||
onAction(actor: string, action: unknown): void {
|
||||
const type = String((action as { type?: string } | null)?.type ?? '');
|
||||
if (!type || type === 'chat' || type === 'say' || type === 'reaction' || type === 'ping' || type === 'timeout') return;
|
||||
this.happened.push(`${this.room.nameOf(actor)} ${ACTION_KO[type] ?? '행동함'}`);
|
||||
const meaning = meaningOf(this.room.gameId(), action);
|
||||
this.happened.push({ actor, meaning });
|
||||
if (this.happened.length > 12) this.happened.shift();
|
||||
if (!this.enabled() || this.room.bots().includes(actor) || this.room.gameId() === 'mafia') return;
|
||||
const bots = this.room.bots().filter((b) => this.canTalk(b, 10_000, 30_000));
|
||||
if (!bots.length || this.random() > 0.12) return;
|
||||
if (!meaning.notable || !this.enabled() || !this.room.chatty() || this.room.bots().includes(actor) || this.planned()) return;
|
||||
const bots = this.room.bots().filter((b) => this.canTalk(b));
|
||||
if (!bots.length || this.random() > REACT_P) return;
|
||||
const bot = bots[Math.floor(this.random() * bots.length)]!;
|
||||
this.spoke(bot);
|
||||
const who = this.room.nameOf(actor);
|
||||
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 방금 ${ACTION_KO[type] ?? '수를 뒀다'}. ${who}에게 반응하는 한마디(놀리거나 떠보기).`)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
const known = this.known();
|
||||
const task = `${who}이(가) 방금 "${meaning.ko}"를 했다${meaning.mean ? `(${meaning.mean})` : ''}. 그 뜻에 맞게 ${who}에게 반응하는 한마디(떠보거나 장난스럽게 받아치기).`;
|
||||
void writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS })).then((raw) => {
|
||||
let line = raw;
|
||||
// Contradicting the move, or about nothing in this game: a built-in line made for this kind of move instead.
|
||||
if (line && (contradicts(line, meaning, false, known) || !this.relevant(line, meaning, [who]))) line = null;
|
||||
line ??= cannedLine(meaning, who, this.room.smart(bot), false, this.random);
|
||||
if (line && !this.busy.has(bot) && this.room.playing()) return this.type(bot, line, () => this.room.roomChat(bot, line!));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,18 +273,28 @@ export class BotBrain {
|
||||
let act = action;
|
||||
let line: string | null = null;
|
||||
const a = action as { type?: string; claim?: string; cardId?: string; to?: string };
|
||||
const meaning = meaningOf(this.room.gameId(), action);
|
||||
if (this.room.gameId() === 'cockroach-poker' && (a.type === 'offer' || a.type === 'pass') && a.claim) {
|
||||
const r = await this.cockroachBluff(bot, a, view);
|
||||
if (r) {
|
||||
act = r.action;
|
||||
line = r.say;
|
||||
// Chat off: the model still decides truth or bluff, the computer just hands the card over without a word.
|
||||
line = this.room.chatty() ? r.say : null;
|
||||
}
|
||||
} else if (this.canTalk(bot) && this.random() < temperOf(bot).talk) {
|
||||
const type = String(a.type ?? '');
|
||||
line = await writeLine(this.llm, this.request(bot, this.situation(), `나는 지금 "${ACTION_KO[type] ?? '내 수'}"를 하려 한다. 이 수를 두며 상대에게 던지는 도발이나 심리전 한마디.`));
|
||||
} else if (meaning.notable && this.room.chatty() && !this.planned() && this.canTalk(bot) && this.random() < temperOf(bot).talk) {
|
||||
// Only a notable move of its own (a big bet, 다이, 고…) gets a word; ordinary moves are played in silence.
|
||||
this.spoke(bot);
|
||||
const known = this.known();
|
||||
const others = this.room.humans().map((h) => this.room.nameOf(h));
|
||||
const task = `나는 지금 "${meaning.ko}"를 하려 한다${meaning.mean ? `(${meaning.mean})` : ''}. 이 수에 맞게 상대에게 던지는 도발이나 심리전 한마디.`;
|
||||
line = await writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 36, priority: 'low', timeoutMs: TALK_WAIT_MS }));
|
||||
if (line && (contradicts(line, meaning, true, known) || !this.relevant(line, meaning, others))) line = null;
|
||||
line ??= cannedLine(meaning, this.room.nameOf(bot), this.room.smart(bot), true, this.random);
|
||||
}
|
||||
if (line && this.room.playing()) {
|
||||
await this.say(bot, line);
|
||||
if (line && this.room.playing() && !this.busy.has(bot)) {
|
||||
this.spoke(bot);
|
||||
const said = line;
|
||||
await this.type(bot, said, () => this.room.roomChat(bot, said));
|
||||
await this.sleep(Math.round((300 + 500 * this.random()) * botPace(bot)));
|
||||
}
|
||||
return act;
|
||||
@@ -174,6 +313,7 @@ export class BotBrain {
|
||||
this.llm,
|
||||
bot,
|
||||
this.room.nameOf(bot),
|
||||
this.room.smart(bot),
|
||||
`바퀴벌레 포커. 나는 ${target}에게 카드를 건넨다. 실제 카드는 ${KO[kind] ?? kind}다. ${target}의 앞마당: ${pile}.\n` +
|
||||
`진짜 이름을 말할지(bluff=false) 다른 벌레라고 거짓말할지(bluff=true) 정하고, 건네며 할 한마디(say, 30자 이내, 실제 카드를 밝히지 말 것)를 정해.`,
|
||||
{ type: 'object', properties: { bluff: { type: 'boolean' }, say: { type: 'string' } }, required: ['bluff', 'say'] },
|
||||
@@ -188,45 +328,123 @@ export class BotBrain {
|
||||
return { action: { ...a, claim }, say };
|
||||
}
|
||||
|
||||
/** People chatting: a named computer answers; otherwise sometimes one of them joins in. */
|
||||
onHumanChat(from: string, text: string): void {
|
||||
if (!this.enabled() || this.room.gameId() === 'mafia') return;
|
||||
/**
|
||||
* The computer a person is talking to: named ("컴퓨터 1", "컴1", "1번", or its full name), or answering what a
|
||||
* computer just said (no one else spoke since), or — with one person in the room — the computer they were talking
|
||||
* with a moment ago or the only computer there.
|
||||
*/
|
||||
private addressee(from: string, text: string, prevHumanChat: number): { bot: string; reply: boolean } | undefined {
|
||||
const bots = this.room.bots();
|
||||
const flat = text.replace(/\s/g, '');
|
||||
const named = bots.find((b) => {
|
||||
const n = /^컴퓨터 (\d+)$/.exec(this.room.nameOf(b))?.[1];
|
||||
return n ? new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text) : false;
|
||||
});
|
||||
const bot = named ?? (this.random() < 0.4 ? bots[Math.floor(this.random() * bots.length)] : undefined);
|
||||
if (!bot || this.typing.has(bot)) return;
|
||||
this.spoke(bot);
|
||||
const who = this.room.nameOf(from);
|
||||
void writeLine(this.llm, this.request(bot, this.situation(), `${who}이(가) 채팅으로 "${text.slice(0, 100)}"라고 했다. 같이 게임하는 사람으로서 대답한다. 질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능), 질문이 아니면 맞장구치거나 받아친다.`)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
const name = this.room.nameOf(b);
|
||||
const n = /^컴퓨터 (\d+)$/.exec(name)?.[1];
|
||||
if (n) return new RegExp(`(컴퓨터\\s?${n}|컴${n}|(?<![0-9])${n}번)(?![0-9])`).test(text);
|
||||
return name.length >= 2 && flat.includes(name.replace(/\s/g, ''));
|
||||
});
|
||||
if (named) return { bot: named, reply: false };
|
||||
const now = this.room.now();
|
||||
const alone = this.room.humans().length === 1;
|
||||
const partner = this.partner.get(from);
|
||||
if (alone && partner && now - partner.at <= CONVERSATION_MS && bots.includes(partner.bot)) return { bot: partner.bot, reply: false };
|
||||
const last = this.lastSpeaker;
|
||||
if (last && last.at >= prevHumanChat && now - last.at <= REPLY_MS && bots.includes(last.bot)) return { bot: last.bot, reply: true };
|
||||
if (alone && bots.length === 1) return { bot: bots[0]!, reply: false };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** At most `ANSWERS_PER_MINUTE` answers a minute to one person. */
|
||||
private mayAnswer(from: string): boolean {
|
||||
const now = this.room.now();
|
||||
const recent = (this.answered.get(from) ?? []).filter((t) => now - t < 60_000);
|
||||
this.answered.set(from, recent);
|
||||
return recent.length < ANSWERS_PER_MINUTE;
|
||||
}
|
||||
|
||||
/**
|
||||
* People chatting: a computer spoken to always answers (right after the line it is typing, if any). People
|
||||
* talking among themselves are left alone.
|
||||
*/
|
||||
onHumanChat(from: string, text: string): void {
|
||||
const prev = this.lastHumanChat;
|
||||
this.lastHumanChat = this.room.now();
|
||||
if (!this.canAnswer()) return;
|
||||
const to = this.addressee(from, text, prev);
|
||||
if (!to || !this.mayAnswer(from)) return;
|
||||
const { bot, reply } = to;
|
||||
this.partner.set(from, { bot, at: this.room.now() });
|
||||
// Busy: the newest message waits and is answered right after (a burst of lines gets one answer, not none).
|
||||
if (this.busy.has(bot)) this.pending.set(bot, { from, text, reply });
|
||||
else void this.answer(bot, from, text, reply);
|
||||
}
|
||||
|
||||
private answerPending(bot: string): void {
|
||||
const next = this.pending.get(bot);
|
||||
if (!next) return;
|
||||
this.pending.delete(bot);
|
||||
if (this.canAnswer()) void this.answer(bot, next.from, next.text, next.reply);
|
||||
}
|
||||
|
||||
/** A built-in answer that fits what the person said (a greeting, a jab, a question), not the same twice in a row. */
|
||||
quickAnswer(bot: string, text: string): string {
|
||||
const kind = QUICK_ANSWER.find((q) => q.test.test(text))!;
|
||||
const pool = kind[this.room.smart(bot) ? 'smart' : 'casual'].filter((l) => l !== this.lastQuick.get(bot));
|
||||
const line = pool[Math.floor(this.random() * pool.length) % pool.length]!;
|
||||
this.lastQuick.set(bot, line);
|
||||
return line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a person at once: "입력 중…" shows while the model writes (that time counts as typing), then the line.
|
||||
* The model gets `ANSWER_WAIT_MS`; slow, busy, down or unusable, a built-in answer is said instead.
|
||||
*/
|
||||
private async answer(bot: string, from: string, text: string, reply = false): Promise<void> {
|
||||
this.busy.add(bot);
|
||||
this.showTyping(bot, true);
|
||||
this.answered.set(from, [...(this.answered.get(from) ?? []), this.room.now()]);
|
||||
const t0 = this.room.now();
|
||||
let line: string | null = null;
|
||||
if (this.llm?.available()) {
|
||||
const who = this.room.nameOf(from);
|
||||
const task =
|
||||
`${who}이(가) 나(${this.room.nameOf(bot)})에게 채팅으로 "${text.slice(0, 100)}"라고 했다. ${who}에게 바로 대답한다. ` +
|
||||
'질문이면 그 질문에 직접 답하고(성격대로, 허세·도발·엄살 가능, 판 상황에 근거해서), 질문이 아니면 맞장구치거나 받아친다. 짧게.';
|
||||
try {
|
||||
line = await withDeadline(writeLine(this.llm, this.request(bot, this.situation(bot), task, { maxLen: 34, priority: 'high' })), ANSWER_WAIT_MS);
|
||||
} catch {
|
||||
line = null;
|
||||
}
|
||||
}
|
||||
line ??= this.quickAnswer(bot, text);
|
||||
this.busy.delete(bot);
|
||||
const said = line;
|
||||
// Sent in or out of a game (the person asked); the model's time already counted as typing.
|
||||
await this.type(bot, said, () => this.room.roomChat(bot, said), false, this.room.now() - t0);
|
||||
this.partner.set(from, { bot, at: this.room.now() });
|
||||
// An answer to an unnamed reply does not invite the next line in turn: people talking among themselves after
|
||||
// it are left alone (otherwise the computer would answer every line between two people forever).
|
||||
if (reply && this.lastSpeaker?.bot === bot) this.lastSpeaker = null;
|
||||
}
|
||||
|
||||
onGameStart(): void {
|
||||
this.happened = [];
|
||||
if (!this.enabled() || this.room.gameId() === 'mafia' || this.random() > 0.7) return;
|
||||
const bots = this.room.bots();
|
||||
const bot = bots[Math.floor(this.random() * bots.length)];
|
||||
if (!bot) return;
|
||||
this.spoke(bot);
|
||||
void writeLine(this.llm, this.request(bot, '게임이 막 시작됐다', '시작 인사 겸 가벼운 선전포고 한마디.')).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line));
|
||||
});
|
||||
// A game with computers and people where the model will be used: make sure it is loaded before anyone talks.
|
||||
// No greeting: the computers speak on their own only about what happens in the game.
|
||||
const usesModel = this.room.chatty() || this.room.gameId() === 'cockroach-poker';
|
||||
if (usesModel && this.llm?.available() && this.room.humans().length && this.room.bots().length) void this.llm.warm();
|
||||
}
|
||||
|
||||
/** The game ended: a computer that won gloats a little, or one that lost takes it with a word. */
|
||||
onGameEnd(ranking: string[][]): void {
|
||||
if (!this.llm?.available() || !this.room.humans().length || this.room.gameId() === 'mafia' || this.random() > 0.85) return;
|
||||
if (!this.llm?.available() || !this.room.chatty() || !this.room.humans().length || this.planned() || this.random() > 0.6) return;
|
||||
const bots = this.room.bots();
|
||||
const winner = (ranking[0] ?? []).find((p) => bots.includes(p));
|
||||
const bot = winner ?? bots[Math.floor(this.random() * bots.length)];
|
||||
if (!bot) return;
|
||||
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : '내가 졌다. 아쉬워하며 다음엔 이기겠다는 한마디.';
|
||||
void writeLine(this.llm, this.request(bot, '게임이 끝났다', task)).then((line) => {
|
||||
if (line) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
|
||||
const first = (ranking[0] ?? []).map((p) => this.room.nameOf(p)).join(', ');
|
||||
const task = winner ? '내가 이겼다. 상대를 살짝 놀리며 이긴 소감 한마디(한 판 더 하자고 해도 좋다).' : `내가 졌다(1등: ${first}). 아쉬워하며 다음엔 이기겠다는 한마디.`;
|
||||
void writeLine(this.llm, this.request(bot, `게임이 끝났다. 1등: ${first}`, task, { priority: 'low' })).then((line) => {
|
||||
if (line && !this.busy.has(bot)) return this.type(bot, line, () => this.room.roomChat(bot, line), false);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -240,6 +458,7 @@ export class BotBrain {
|
||||
const line = await writeLine(this.llm, {
|
||||
bot,
|
||||
name: this.room.nameOf(bot),
|
||||
smart: this.room.smart(bot),
|
||||
game: '마피아(낮 토론, 모두가 보는 채팅)',
|
||||
situation: '누가 마피아인지 추리하며 이야기하는 중이다. 너는 자신이 시민 팀이라고 말한다.',
|
||||
task: hint,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* What a computer says, written by the local model (docs/06 §12.1): a character (성격 + 말투) per computer, a prompt
|
||||
* per moment, and a strict clean-up so only one short, kind, Korean chat line ever reaches people.
|
||||
*/
|
||||
import { botPersona, hash01 } from '@bg/games/bots';
|
||||
import { hash01 } from '@bg/games/bots';
|
||||
import { chatProblem } from '@bg/games/mafia';
|
||||
import type { Llm, LlmMessage } from './llm';
|
||||
|
||||
@@ -27,18 +27,22 @@ export function temperOf(bot: string): Temper {
|
||||
return TEMPERS[Math.floor(hash01(bot, 'temper') * TEMPERS.length)]!;
|
||||
}
|
||||
|
||||
export function speechOf(bot: string): string {
|
||||
return botPersona(bot).smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
|
||||
/** `smart` = 똑똑한 편 (the room's `botPersona`). */
|
||||
export function speechOf(smart: boolean): string {
|
||||
return smart ? '존댓말(해요체), 또박또박' : '반말, 짧고 가볍게, ㅋㅋ를 가끔 붙임';
|
||||
}
|
||||
|
||||
export function systemPrompt(bot: string, name: string, maxLen: number): string {
|
||||
export function systemPrompt(bot: string, name: string, maxLen: number, smart: boolean): string {
|
||||
const t = temperOf(bot);
|
||||
return [
|
||||
`너는 온라인 보드게임 사이트 "같이 놀자"에서 사람들과 함께 게임하는 컴퓨터 플레이어 "${name}"이다.`,
|
||||
`성격: ${t.ko} — ${t.desc}`,
|
||||
`말투: ${speechOf(bot)}.`,
|
||||
`말투: ${speechOf(smart)}.`,
|
||||
`규칙: 한국어 채팅 한 줄만 쓴다. ${maxLen}자 이내. 대사만 쓰고 따옴표·설명·괄호·영어·한자는 쓰지 않는다.`,
|
||||
'욕설, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 게임과 상관없는 이야기는 하지 않는다.',
|
||||
'욕설·막말·깔보는 호칭, 비하, 외모·성별·나이 언급, 개인정보, 링크는 절대 쓰지 않는다. 상대가 거친 말을 해도 장난스럽게 받아넘긴다.',
|
||||
'"상황"에 적힌 사실에만 근거해서 말한다. 적히지 않은 점수·패·행동은 지어내지 않고, 게임과 상관없는 혼잣말이나 "다들 준비됐냐" 같은 뻔한 말은 하지 않는다.',
|
||||
'최근 채팅에서 "(나)"가 붙은 줄은 내가 한 말이다. 내가 했던 말의 시작이나 표현을 되풀이하지 않는다.',
|
||||
'누가 한 수의 뜻이 적혀 있으면 그 뜻에 맞게 말한다(센 베팅을 한 사람에게 겁먹었다고 하지 않고, 포기한 사람에게 세게 나왔다고 하지 않는다).',
|
||||
'자신이 AI나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
|
||||
].join('\n');
|
||||
}
|
||||
@@ -46,6 +50,8 @@ export function systemPrompt(bot: string, name: string, maxLen: number): string
|
||||
export interface LineRequest {
|
||||
bot: string;
|
||||
name: string;
|
||||
/** 똑똑한 편 (존댓말) / 허술한 편 (반말). */
|
||||
smart: boolean;
|
||||
game: string;
|
||||
/** What is going on, in plain Korean. */
|
||||
situation: string;
|
||||
@@ -58,10 +64,21 @@ export interface LineRequest {
|
||||
maxLen?: number;
|
||||
/** Extra patterns the line must not contain (e.g. a mafia computer saying it is mafia). */
|
||||
forbid?: RegExp[];
|
||||
/** answer = a person spoke to it (goes ahead of everything); talk = on its own (dropped when the model is busy). */
|
||||
priority?: 'high' | 'normal' | 'low';
|
||||
/** Give up on the model after this long (a word about a move is no use once the game has moved on). */
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
const AI_WORDS = /인공\s*지능|\bAI\b|챗봇|언어\s*모델|어시스턴트|프로그램입니다|GPT|모델로서/i;
|
||||
const FOREIGN = /[一-鿿-ヿ]|[A-Za-z]{4,}/;
|
||||
/**
|
||||
* Rude words the shared kid-safe filter lets through but the model likes to use when it plays "도발형" or is sworn at
|
||||
* ("망할 놈", "닥쳐", "뒤져라", "꼬맹이" — all seen from gemma3:4b in testing).
|
||||
*/
|
||||
const RUDE = /뒤지겠|뒤지게|놈|(이|저|그|미친)\s?년|새끼|지랄|닥치|닥쳐|꺼져|뒤질|뒤져|죽을래|죽여|죽인다|팰\s?거|때려|병신|멍청|바보|어리석|꼬맹|찐따|빌어먹|망할|씹|좆|미친|븅|등신|한심/;
|
||||
/** The model repeating its instructions instead of talking ("철수이(가) 채팅으로 … 라고 했다"). */
|
||||
const ECHO = /이\(가\)|채팅으로|라고 했다|할 말:|상황:|최근 채팅/;
|
||||
|
||||
/** One clean chat line out of whatever the model wrote, or null when nothing usable is left. */
|
||||
export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): string | null {
|
||||
@@ -76,7 +93,7 @@ export function cleanLine(raw: string, maxLen = 40, forbid: RegExp[] = []): stri
|
||||
.replace(/[*_#>]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!line || FOREIGN.test(line) || AI_WORDS.test(line)) return null;
|
||||
if (!line || FOREIGN.test(line) || AI_WORDS.test(line) || RUDE.test(line) || ECHO.test(line)) return null;
|
||||
if ([...line].length > maxLen) {
|
||||
const chars = [...line];
|
||||
const cut = chars.slice(0, maxLen).join('');
|
||||
@@ -95,23 +112,24 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
|
||||
if (!llm || !llm.available()) return null;
|
||||
const maxLen = req.maxLen ?? 40;
|
||||
const parts = [`게임: ${req.game}`, `상황: ${req.situation}`];
|
||||
if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}: ${m.text}`).join('\n')}`);
|
||||
if (req.recent?.length) parts.push(`최근 채팅:\n${req.recent.slice(-8).map((m) => `${m.from}${m.from === req.name ? '(나)' : ''}: ${m.text}`).join('\n')}`);
|
||||
if (req.example) parts.push(`예시(뜻은 같게, 표현은 너답게 새로): ${req.example}`);
|
||||
parts.push(`할 말: ${req.task}`);
|
||||
const messages: LlmMessage[] = [
|
||||
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen) },
|
||||
{ role: 'system', content: systemPrompt(req.bot, req.name, maxLen, req.smart) },
|
||||
{ role: 'user', content: parts.join('\n') },
|
||||
];
|
||||
const raw = await llm.chat(messages, { maxTokens: 70, temperature: 0.95 });
|
||||
// One line of at most ~40 Korean characters is 15~30 tokens; stop at the first newline.
|
||||
const raw = await llm.chat(messages, { maxTokens: 56, temperature: 0.9, stop: ['\n'], priority: req.priority ?? 'normal', ...(req.timeoutMs ? { timeoutMs: req.timeoutMs } : {}) });
|
||||
return raw === null ? null : cleanLine(raw, maxLen, req.forbid);
|
||||
}
|
||||
|
||||
/** Structured choice (JSON schema) — e.g. 바퀴벌레 포커: tell the truth or bluff, and what to say. */
|
||||
export async function decide<T>(llm: Llm | null, bot: string, name: string, prompt: string, schema: object): Promise<T | null> {
|
||||
export async function decide<T>(llm: Llm | null, bot: string, name: string, smart: boolean, prompt: string, schema: object): Promise<T | null> {
|
||||
if (!llm || !llm.available()) return null;
|
||||
const raw = await llm.chat(
|
||||
[
|
||||
{ role: 'system', content: systemPrompt(bot, name, 40) + '\n대답은 요청한 JSON 형식으로만 한다.' },
|
||||
{ role: 'system', content: systemPrompt(bot, name, 40, smart) + '\n대답은 요청한 JSON 형식으로만 한다.' },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
{ maxTokens: 120, temperature: 0.9, format: schema },
|
||||
|
||||
@@ -13,7 +13,10 @@ export interface LlmConfig {
|
||||
/** Ollama base URL, e.g. http://192.168.10.9:11434. */
|
||||
url: string;
|
||||
model: string;
|
||||
/** Requests running at once (one GPU). */
|
||||
/**
|
||||
* Requests sent at once. Default 1: Ollama on the one GPU runs one request at a time (`n_slots = 1`), so a second
|
||||
* one would only wait inside Ollama — where an answer to a person could not get ahead of small talk.
|
||||
*/
|
||||
maxConcurrent?: number;
|
||||
/** Requests allowed to wait; more are refused at once (the caller uses a built-in line). */
|
||||
maxQueue?: number;
|
||||
@@ -39,7 +42,7 @@ export interface LlmStats {
|
||||
|
||||
export class Llm {
|
||||
private running = 0;
|
||||
private waiting: (() => void)[] = [];
|
||||
private waiting: { go: () => void; high: boolean }[] = [];
|
||||
private totalMs = 0;
|
||||
private backoffUntil = 0;
|
||||
private failures = 0;
|
||||
@@ -60,17 +63,31 @@ export class Llm {
|
||||
|
||||
/**
|
||||
* One chat completion. `format` is a JSON schema for structured answers. Returns the text, or null when it could
|
||||
* not be had in time (busy, down, timeout).
|
||||
* not be had in time (busy, down, timeout). `priority`: `high` (answering a person) goes ahead of everything that
|
||||
* waits; `low` (small talk nobody asked for) is dropped at once when the model is busy, so it never delays the rest.
|
||||
* `stop` ends the answer early (one chat line: a newline).
|
||||
*/
|
||||
async chat(messages: LlmMessage[], opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number } = {}): Promise<string | null> {
|
||||
async chat(
|
||||
messages: LlmMessage[],
|
||||
opts: { maxTokens?: number; temperature?: number; format?: object; timeoutMs?: number; priority?: 'high' | 'normal' | 'low'; stop?: string[] } = {},
|
||||
): Promise<string | null> {
|
||||
this.stats.requests++;
|
||||
const full = this.running >= (this.cfg.maxConcurrent ?? 2) && this.waiting.length >= (this.cfg.maxQueue ?? 6);
|
||||
if (!this.available() || full) {
|
||||
const max = this.cfg.maxConcurrent ?? 1;
|
||||
const busy = this.running >= max;
|
||||
const full = busy && this.waiting.length >= (this.cfg.maxQueue ?? 6) && opts.priority !== 'high';
|
||||
if (!this.available() || full || (busy && opts.priority === 'low')) {
|
||||
this.stats.skipped++;
|
||||
return null;
|
||||
}
|
||||
if (this.running >= (this.cfg.maxConcurrent ?? 2)) await new Promise<void>((r) => this.waiting.push(r));
|
||||
this.running++;
|
||||
if (busy) {
|
||||
await new Promise<void>((go) => {
|
||||
const high = opts.priority === 'high';
|
||||
// Answers wait only behind earlier answers.
|
||||
const at = high ? this.waiting.findIndex((w) => !w.high) : -1;
|
||||
if (at >= 0) this.waiting.splice(at, 0, { go, high });
|
||||
else this.waiting.push({ go, high });
|
||||
});
|
||||
} else this.running++; // a waiter is handed the finished request's place (`running` stays)
|
||||
const t0 = this.now();
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? this.cfg.timeoutMs ?? 6000);
|
||||
@@ -83,9 +100,9 @@ export class Llm {
|
||||
model: this.cfg.model,
|
||||
messages,
|
||||
stream: false,
|
||||
keep_alive: this.cfg.keepAlive ?? '30m',
|
||||
keep_alive: this.cfg.keepAlive ?? '2h',
|
||||
...(opts.format ? { format: opts.format } : {}),
|
||||
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80 },
|
||||
options: { temperature: opts.temperature ?? 0.9, num_predict: opts.maxTokens ?? 80, ...(opts.stop ? { stop: opts.stop } : {}) },
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
@@ -110,13 +127,21 @@ export class Llm {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
this.running--;
|
||||
this.waiting.shift()?.();
|
||||
const next = this.waiting.shift();
|
||||
if (next) next.go();
|
||||
else this.running--;
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the model into GPU memory ahead of the first real request (the first load takes ~20 s). */
|
||||
private lastWarm = -Infinity;
|
||||
|
||||
/**
|
||||
* Loads the model into GPU memory ahead of the first real request (a cold load takes ~20 s; Ollama unloads it after
|
||||
* `keepAlive` without use). Cheap when it is already loaded; at most once a minute.
|
||||
*/
|
||||
async warm(): Promise<boolean> {
|
||||
if (this.now() - this.lastWarm < 60_000) return true;
|
||||
this.lastWarm = this.now();
|
||||
const r = await this.chat([{ role: 'user', content: '안녕' }], { maxTokens: 1, timeoutMs: 60_000 });
|
||||
return r !== null;
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -93,12 +93,51 @@ describe('idle guests', () => {
|
||||
});
|
||||
|
||||
describe('leaving the room page', () => {
|
||||
test('detach keeps the seat but the room no longer counts the connection', async () => {
|
||||
test('alone with no game running (뒤로가기 from the lobby): leaving the page leaves the room and it closes at once', async () => {
|
||||
const s = start();
|
||||
const g = await guest(s.base, '혼자');
|
||||
const c = await connect(s, g);
|
||||
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: c.cookie, body: JSON.stringify({ gameId: 'omok' }) });
|
||||
c.send({ t: 'join', code: r.body.code, as: 'player' });
|
||||
await c.waitFor((m) => m.t === 'room');
|
||||
expect(s.rooms.get(r.body.code)).toBeDefined();
|
||||
c.send({ t: 'detach' });
|
||||
for (let i = 0; i < 50 && s.rooms.get(r.body.code); i++) await sleep(10);
|
||||
expect(s.rooms.get(r.body.code)).toBeUndefined();
|
||||
expect(s.rooms.activeRoomFor(g.id)).toBeNull();
|
||||
// The same socket is fine afterwards.
|
||||
c.send({ t: 'ping', ts: 1 });
|
||||
await c.waitFor((m) => m.t === 'pong');
|
||||
});
|
||||
|
||||
test('someone else is in the lobby: leaving the page keeps my seat (I can come back)', async () => {
|
||||
const s = start();
|
||||
const a = await guest(s.base, '방장');
|
||||
const b = await guest(s.base, '친구');
|
||||
const ca = await connect(s, a);
|
||||
const cb = await connect(s, b);
|
||||
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: ca.cookie, body: JSON.stringify({ gameId: 'omok' }) });
|
||||
ca.send({ t: 'join', code: r.body.code, as: 'player' });
|
||||
await ca.waitFor((m) => m.t === 'room');
|
||||
cb.send({ t: 'join', code: r.body.code, as: 'player' });
|
||||
await cb.waitFor((m) => m.t === 'room');
|
||||
const room = s.rooms.get(r.body.code)!;
|
||||
ca.send({ t: 'detach' });
|
||||
for (let i = 0; i < 50 && room.conns.size > 1; i++) await sleep(10);
|
||||
expect(room.conns.size).toBe(1);
|
||||
expect(room.seatOf(a.id)).toBeGreaterThanOrEqual(0);
|
||||
expect(s.rooms.get(r.body.code)).toBe(room);
|
||||
});
|
||||
|
||||
test('detach during a game keeps the seat but the room no longer counts the connection', async () => {
|
||||
const s = start();
|
||||
const g = await guest(s.base, '홈으로');
|
||||
const c = await connect(s, g);
|
||||
const code = await practiceRoom(s, c);
|
||||
const room = s.rooms.get(code)!;
|
||||
c.send({ t: 'start' });
|
||||
for (let i = 0; i < 50 && room.status !== 'playing'; i++) await sleep(10);
|
||||
expect(room.status).toBe('playing');
|
||||
expect(room.conns.size).toBe(1);
|
||||
c.send({ t: 'detach' });
|
||||
for (let i = 0; i < 50 && room.conns.size; i++) await sleep(10);
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { botProfile, nicknameError, normalizeNickname } from '@bg/shared';
|
||||
import type { Audit, Role, Roles } from '../admin/roles';
|
||||
import { GameSettingsSchema, SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
||||
import { LiarTopicInputSchema, type LiarBankStore } from '../admin/liar-bank';
|
||||
import type { Sessions } from '../auth/sessions';
|
||||
import { toPublicUser, type Users } from '../auth/users';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
@@ -19,6 +20,7 @@ export interface AdminDeps {
|
||||
audit: Audit;
|
||||
settings: SettingsStore;
|
||||
games: Record<string, AnyGameDefinition>;
|
||||
liarBank: LiarBankStore;
|
||||
disconnectUser: (userId: string) => void;
|
||||
/** When an idle guest will be deleted; null for members and for guests still online or seated. */
|
||||
guestDeleteAt: (u: { id: string; kind: 'guest' | 'member'; last_seen_at: number }) => number | null;
|
||||
@@ -85,6 +87,57 @@ export function createAdminApp(d: AdminDeps) {
|
||||
return c.json({ effective: d.settings.game(id), raw: {} });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ 라이어 게임 topics and words (docs/14-admin.md §4.1)
|
||||
app.get('/liar/topics', (c) => c.json({ topics: d.liarBank.list() }));
|
||||
|
||||
/** Parses and checks a topic as typed; the error response, or the topic. */
|
||||
const liarInput = async (c: Context<Env>) => {
|
||||
const parsed = LiarTopicInputSchema.safeParse(await body(c));
|
||||
if (!parsed.success) return { error: c.json({ error: `입력 값이 올바르지 않아요: ${parsed.error.issues.map((i) => i.path.join('.') + ' ' + i.message).join(', ')}` }, 400) };
|
||||
const problems = d.liarBank.problems(parsed.data);
|
||||
if (problems.length) return { error: c.json({ error: problems.slice(0, 30).join('\n'), problems }, 400) };
|
||||
return { topic: parsed.data };
|
||||
};
|
||||
|
||||
app.post('/liar/topics', async (c) => {
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
const id = d.liarBank.create(r.topic, actor(c));
|
||||
if (!id) return c.json({ error: '주제는 100개까지 더할 수 있어요.' }, 400);
|
||||
d.audit.log(actor(c), 'liar.topic.create', id, null, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.put('/liar/topics/:id', async (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
const r = await liarInput(c);
|
||||
if (r.error) return r.error;
|
||||
d.liarBank.save(id, r.topic, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.update', id, before, r.topic);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
app.delete('/liar/topics/:id', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before || before.deleted) return c.json({ error: '없는 주제예요.' }, 404);
|
||||
if (d.liarBank.list().filter((t) => !t.deleted).length <= 1) return c.json({ error: '주제가 하나는 있어야 해요.' }, 400);
|
||||
d.liarBank.delete(id, actor(c));
|
||||
d.audit.log(actor(c), 'liar.topic.delete', id, before, null);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post('/liar/topics/:id/reset', (c) => {
|
||||
const id = c.req.param('id');
|
||||
const before = d.liarBank.get(id);
|
||||
if (!before?.builtin) return c.json({ error: '처음부터 있던 주제만 되돌릴 수 있어요.' }, 400);
|
||||
d.liarBank.reset(id);
|
||||
d.audit.log(actor(c), 'liar.topic.reset', id, before, null);
|
||||
return c.json({ topic: d.liarBank.get(id) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ site
|
||||
app.get('/site', (c) => c.json({ site: d.settings.getSite() }));
|
||||
app.put('/site', async (c) => {
|
||||
@@ -93,6 +146,8 @@ export function createAdminApp(d: AdminDeps) {
|
||||
const before = d.settings.getSite();
|
||||
d.settings.setSite(parsed.data, actor(c));
|
||||
d.audit.log(actor(c), 'site.update', null, before, parsed.data);
|
||||
// The game speed and chat sound apply at once: open rooms get them with a fresh room view.
|
||||
if (before.gameSpeed !== parsed.data.gameSpeed || before.chatSound !== parsed.data.chatSound) for (const r of d.rooms.all()) r.broadcastRoom();
|
||||
return c.json({ site: parsed.data });
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { Hono, type Context } from 'hono';
|
||||
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
|
||||
import { z } from 'zod';
|
||||
import { bankTopics, liarBankRef } from '@bg/games/liar';
|
||||
import { nicknameError, normalizeNickname, normalizeRoomCode, formatRoomCode } from '@bg/shared';
|
||||
import type { Config } from '../config';
|
||||
import { authorizeUrl, avatarUrl, exchangeCode, safeNext, type DiscordUser } from '../auth/discord';
|
||||
@@ -16,6 +17,8 @@ import type { SettingsStore } from '../admin/settings';
|
||||
|
||||
export interface HttpDeps {
|
||||
config: Config;
|
||||
/** Web build being served (`/api/version`, docs/07 §11.1); null without a web build. */
|
||||
build?: string | null;
|
||||
users: Users;
|
||||
sessions: Sessions;
|
||||
rooms: RoomManager;
|
||||
@@ -76,6 +79,12 @@ export function createHttpApp(d: HttpDeps) {
|
||||
setCookie(c, SESSION_COOKIE, token, cookieOpts(SESSION_TTL[kind]));
|
||||
};
|
||||
|
||||
// Open pages ask now and then whether the site was updated (docs/07 §11.1).
|
||||
app.get('/api/version', (c) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
return c.json({ build: d.build ?? null });
|
||||
});
|
||||
|
||||
app.get('/healthz', (c) => {
|
||||
const h = d.health();
|
||||
return c.json(h, h.ok ? 200 : 503);
|
||||
@@ -89,9 +98,14 @@ export function createHttpApp(d: HttpDeps) {
|
||||
siteName: site.siteName,
|
||||
announcement: site.announcement,
|
||||
maintenance: site.maintenance,
|
||||
gameSpeed: site.gameSpeed,
|
||||
chatSound: site.chatSound,
|
||||
});
|
||||
});
|
||||
|
||||
// 라이어 게임 topics new games can use (admins may add or delete some): the lobby's 주제 choices.
|
||||
app.get('/api/liar/topics', (c) => c.json({ topics: bankTopics(liarBankRef()).map((t) => ({ id: t.id, ko: t.ko, words: t.words.length })) }));
|
||||
|
||||
app.post('/api/auth/guest', async (c) => {
|
||||
if (!guestLimiter.allow(d.ipOf(c.req.raw))) return c.json({ error: '잠시 후 다시 시도해 주세요.' }, 429);
|
||||
const body = z.object({ nickname: z.string().max(100) }).safeParse(await c.req.json().catch(() => null));
|
||||
|
||||
134
apps/server/src/rooms/apple.room.test.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
/** 사과 게임 through a real Room: a practice race against a computer to the end, the server clock, away players (docs/games/apple.md §8.5, §13). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { findMoves, type AppleState, type AppleView } from '@bg/games/apple';
|
||||
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 AppleView;
|
||||
|
||||
describe('사과 게임 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 화면에 보이는 판으로 합 10을 지우고, 컴퓨터도 자기 판을 풀고, 2분 뒤 서버 시계로 끝나요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'apple') 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 rejects = 0;
|
||||
for (let i = 0; i < 4 * 200 && !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 clears one rectangle every 2 seconds, read from their own screen.
|
||||
const v = lastView(a);
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.cells) {
|
||||
const m = findMoves(v.cells, 1)[0];
|
||||
if (m) room.act('A', ++cs, { type: 'select', ...m });
|
||||
}
|
||||
rejects = a.msgs.filter((m) => m.t === 'reject').length;
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(rejects).toBe(0);
|
||||
const s = room.game!.state as AppleState;
|
||||
expect(s.final!.endReason === 'time' || s.final!.endReason === 'cleared').toBe(true);
|
||||
expect(s.score.A).toBeGreaterThan(20);
|
||||
expect(s.score[bot]).toBeGreaterThan(10);
|
||||
// My view never carried the computer's board.
|
||||
expect(JSON.stringify(lastView(a))).not.toContain(s.boards[bot]!);
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
||||
});
|
||||
|
||||
test('합이 10이 아닌 직사각형은 거절(벌점 없음), 연결이 끊긴 사람은 일찍 시간 초과되지 않아요', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'apple', '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.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as AppleState;
|
||||
expect(s().phase).toBe('playing');
|
||||
// Find a 2-cell rectangle that does not add up to 10.
|
||||
const cells = s().boards.A!;
|
||||
const c = [...Array(16).keys()].find((k) => Number(cells[k]) + Number(cells[k + 1]) !== 10)!;
|
||||
room.act('A', 1, { type: 'select', r0: 0, c0: c, r1: 0, c1: c + 1 });
|
||||
const rej = a.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string };
|
||||
expect(rej.reason).toMatch(/^합이 \d+이에요/);
|
||||
expect(s().score.A).toBe(0);
|
||||
// B drops off: 70 s later (past the 60 s grace) nothing happened to B, the race goes on.
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
});
|
||||
test('제한 시간 무제한: 타이머가 돌지 않고, 끊긴 사람은 유예 뒤 한 번만 여기까지 처리(바쁜 루프 없음), 남은 사람이 여기까지 하면 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'apple', '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: { timeLimitSec: null } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
const s = () => room.game!.state as AppleState;
|
||||
expect(s().phase).toBe('playing');
|
||||
expect(s().endsAt).toBeNull();
|
||||
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().status.B).toBe('done');
|
||||
expect(s().status.A).toBe('playing');
|
||||
// Nothing else is due: no timer fires again for B.
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.summary).toContain('모두 끝냈어요');
|
||||
});
|
||||
});
|
||||
238
apps/server/src/rooms/bot-level.room.test.ts
Normal file
@@ -0,0 +1,238 @@
|
||||
/** Computer levels 1~60, the host's 쉬움/보통/어려움, drift between games and luck shuffles (docs/09 §9.1, docs/04 §5.1). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { seedToHex, type ChaChaSeed } from '@bg/engine';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { BOT_BANDS, ClientMessage, bandOf, botProfile, isBotId, luckLabel, type ServerMessage } from '@bg/shared';
|
||||
import type { LuckJob } from '@bg/games/bots/luck';
|
||||
import { openDb } from '../db';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
import { DRIFT_RANGE, DRIFT_STEP, drift, newBotProfile, profileFromId, repick, rollLevel } from './bot-profile';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn, type RoomSnapshot } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness(luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 60_000, luckSeed });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
const practice = (gameId: string) => {
|
||||
const r = manager.createPractice('A', gameId) as Room;
|
||||
rooms.push(r);
|
||||
r.join(conn('A'), 'player');
|
||||
return r;
|
||||
};
|
||||
return { db, store, clock, manager, conn, practice, users };
|
||||
}
|
||||
|
||||
const botsOf = (room: Room) => room.seatedIds().filter(isBotId);
|
||||
const seq = (...xs: number[]) => {
|
||||
let i = 0;
|
||||
return () => xs[i++ % xs.length]!;
|
||||
};
|
||||
|
||||
describe('levels', () => {
|
||||
test('rolls: 랜덤 1~60, 쉬움 1~20, 보통 21~40, 어려움 41~60, all values reachable', () => {
|
||||
for (const pick of ['random', 'easy', 'normal', 'hard'] as const) {
|
||||
const [lo, hi] = pick === 'random' ? [1, 60] : BOT_BANDS[pick];
|
||||
expect(rollLevel(pick, () => 0)).toBe(lo);
|
||||
expect(rollLevel(pick, () => 0.999999)).toBe(hi);
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const l = rollLevel(pick);
|
||||
expect(l >= lo && l <= hi).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(bandOf(20)).toBe('easy');
|
||||
expect(bandOf(21)).toBe('normal');
|
||||
expect(bandOf(41)).toBe('hard');
|
||||
});
|
||||
|
||||
test('a new computer: any level, its own luck in [-1, 1]; picking a band keeps the luck', () => {
|
||||
const p = newBotProfile(seq(0.5, 0.9));
|
||||
expect(p).toEqual({ pick: 'random', base: 31, level: 31, luck: expect.closeTo(0.8, 9), played: 0 });
|
||||
const q = repick(p, 'easy', () => 0.3);
|
||||
expect(q).toEqual({ pick: 'easy', base: 7, level: 7, luck: p.luck, played: 0 });
|
||||
expect(luckLabel(-1)).toBe('아주 나쁨');
|
||||
expect(luckLabel(0)).toBe('보통');
|
||||
expect(luckLabel(0.7)).toBe('아주 좋음');
|
||||
});
|
||||
|
||||
test('drift: none before the first game, then at most 2 a game, within ±5 of the start and never out of its band', () => {
|
||||
for (const base of [1, 20, 21, 33, 41, 60]) {
|
||||
let p = { ...newBotProfile(), base, level: base };
|
||||
p = drift(p);
|
||||
expect(p.level).toBe(base);
|
||||
const [lo, hi] = BOT_BANDS[bandOf(base)];
|
||||
for (let g = 0; g < 300; g++) {
|
||||
const prev = p.level;
|
||||
p = drift(p);
|
||||
expect(Math.abs(p.level - prev)).toBeLessThanOrEqual(DRIFT_STEP);
|
||||
expect(Math.abs(p.level - base)).toBeLessThanOrEqual(DRIFT_RANGE);
|
||||
expect(p.level >= lo && p.level <= hi).toBe(true);
|
||||
}
|
||||
}
|
||||
// A 60 can become 58 next game, never 41.
|
||||
expect(drift({ ...newBotProfile(), base: 60, level: 60, played: 1 }, () => 0).level).toBe(58);
|
||||
});
|
||||
|
||||
test('computers saved without a level get one from their id (the same every time)', () => {
|
||||
const id = 'bot:1:01J0000000ZZZZZZ0000000000';
|
||||
expect(profileFromId(id)).toEqual(profileFromId(id));
|
||||
expect(profileFromId(id).level).toBe(60);
|
||||
});
|
||||
});
|
||||
|
||||
describe('room', () => {
|
||||
test('protocol accepts botLevel with the four choices only', () => {
|
||||
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'hard' }).success).toBe(true);
|
||||
expect(ClientMessage.safeParse({ t: 'botLevel', userId: 'bot:1:x', pick: 'insane' }).success).toBe(false);
|
||||
});
|
||||
|
||||
test('the host picks a band; everyone sees the pick, nobody sees the level until the game is over', () => {
|
||||
const { practice, conn } = harness();
|
||||
const room = practice('omok');
|
||||
const bot = botsOf(room)[0]!;
|
||||
expect(room.profile(bot).pick).toBe('random');
|
||||
expect(room.roomView().botPicks).toEqual({ [bot]: 'random' });
|
||||
room.join(conn('S'), 'spectator');
|
||||
expect(room.setBotLevel('S', bot, 'hard')).toBe('방장만 난이도를 바꿀 수 있어요.');
|
||||
expect(room.setBotLevel('A', 'bot:9:nope', 'hard')).toBe('없는 컴퓨터예요.');
|
||||
expect(room.setBotLevel('A', bot, 'hard')).toBeNull();
|
||||
expect(room.roomView().botPicks).toEqual({ [bot]: 'hard' });
|
||||
const level = room.profile(bot).level;
|
||||
expect(level >= 41 && level <= 60).toBe(true);
|
||||
expect(JSON.stringify(room.roomView())).not.toContain('"level"');
|
||||
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임 중에는 바꿀 수 없어요.');
|
||||
expect(room.roomView().lastBots).toBeUndefined();
|
||||
room.act('A', 1, { type: 'resign' });
|
||||
expect(room.status).toBe('finished');
|
||||
expect(room.roomView().lastBots).toEqual({ [bot]: { level, luck: room.profile(bot).luck } });
|
||||
expect(room.roomView().lastShuffles).toBe(1);
|
||||
});
|
||||
|
||||
test('every next game the level moves a little around where it started', () => {
|
||||
const { practice } = harness();
|
||||
const room = practice('omok');
|
||||
const bot = botsOf(room)[0]!;
|
||||
room.setBotLevel('A', bot, 'hard');
|
||||
const base = room.profile(bot).base;
|
||||
const seen: number[] = [];
|
||||
for (let g = 0; g < 25; g++) {
|
||||
expect(g === 0 ? room.start('A') : room.rematch('A')).toBeNull();
|
||||
seen.push(room.game!.bots![bot]!.level);
|
||||
room.act('A', g + 1, { type: 'resign' });
|
||||
}
|
||||
expect(seen[0]).toBe(base);
|
||||
for (let i = 1; i < seen.length; i++) expect(Math.abs(seen[i]! - seen[i - 1]!)).toBeLessThanOrEqual(DRIFT_STEP);
|
||||
for (const l of seen) expect(l >= Math.max(41, base - DRIFT_RANGE) && l <= Math.min(60, base + DRIFT_RANGE)).toBe(true);
|
||||
expect(new Set(seen).size).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
test('levels and luck survive a restart; rooms saved before get them from the id', () => {
|
||||
const { practice, store, clock, users } = harness();
|
||||
const room = practice('omok');
|
||||
const bot = botsOf(room)[0]!;
|
||||
room.setBotLevel('A', bot, 'easy');
|
||||
const before = room.profile(bot);
|
||||
const { seq: s, stateJson } = store.openRooms()[0]!;
|
||||
const deps = { store, games: GAMES, users, now: clock.now, botDelay: () => 60_000 };
|
||||
const restored = Room.restore(room.id, room.code, s, JSON.parse(stateJson) as RoomSnapshot, deps);
|
||||
rooms.push(restored);
|
||||
expect(restored.profile(bot)).toEqual(before);
|
||||
const old = JSON.parse(stateJson) as RoomSnapshot;
|
||||
delete old.bots;
|
||||
const legacy = Room.restore(room.id, room.code, s, old, deps);
|
||||
rooms.push(legacy);
|
||||
expect(legacy.profile(bot)).toEqual(profileFromId(bot));
|
||||
});
|
||||
});
|
||||
|
||||
describe('luck shuffles', () => {
|
||||
const seedA = [1, 2, 3, 4, 5, 6, 7, 8] as ChaChaSeed;
|
||||
|
||||
test('a card game with computers waits for the shuffles, then starts with the chosen seed', async () => {
|
||||
const jobs: LuckJob[] = [];
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((r) => (release = r));
|
||||
const { practice } = harness(async (job) => {
|
||||
jobs.push(job);
|
||||
await gate;
|
||||
return { seed: seedA, tried: 4 };
|
||||
});
|
||||
const room = practice('one-card');
|
||||
const bot = botsOf(room)[0]!;
|
||||
room.botProfiles[bot]!.luck = 0.9;
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.status).toBe('lobby');
|
||||
expect(room.roomView().starting).toBe(true);
|
||||
expect(room.start('A')).toBe('게임을 준비하고 있어요.');
|
||||
expect(room.setBotLevel('A', bot, 'easy')).toBe('게임을 준비하고 있어요.');
|
||||
expect(jobs).toHaveLength(1);
|
||||
expect(jobs[0]).toMatchObject({ gameId: 'one-card', players: room.seatedIds(), luck: { [bot]: room.profile(bot).luck }, gameNo: 1 });
|
||||
release();
|
||||
await gate;
|
||||
await Bun.sleep(0);
|
||||
expect(room.status).toBe('playing');
|
||||
expect(room.roomView().starting).toBeUndefined();
|
||||
expect(room.game!.seedHex).toBe(seedToHex(seedA));
|
||||
expect(room.game!.seedHash).toBe(sha256Hex(seedToHex(seedA)));
|
||||
expect(room.game!.shuffles).toBe(4);
|
||||
});
|
||||
|
||||
test('if the seats change while shuffling, nothing starts', async () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((r) => (release = r));
|
||||
const { practice } = harness(async () => {
|
||||
await gate;
|
||||
return { seed: seedA, tried: 2 };
|
||||
});
|
||||
const room = practice('one-card');
|
||||
room.botProfiles[botsOf(room)[0]!]!.luck = -0.9;
|
||||
expect(room.start('A')).toBeNull();
|
||||
room.leave('A');
|
||||
release();
|
||||
await gate;
|
||||
await Bun.sleep(0);
|
||||
expect(room.status).toBe('lobby');
|
||||
expect(room.game).toBeNull();
|
||||
expect(room.starting).toBe(false);
|
||||
});
|
||||
|
||||
test('a failed shuffle job still starts the game with a fresh seed; board games and luck near 0 never ask', async () => {
|
||||
const asked: string[] = [];
|
||||
const { practice } = harness(async (job) => {
|
||||
asked.push(job.gameId);
|
||||
throw new Error('worker down');
|
||||
});
|
||||
const omok = practice('omok');
|
||||
expect(omok.start('A')).toBeNull();
|
||||
expect(omok.status).toBe('playing');
|
||||
const cards = practice('one-card');
|
||||
cards.botProfiles[botsOf(cards)[0]!]!.luck = 1;
|
||||
expect(cards.start('A')).toBeNull();
|
||||
expect(cards.status).toBe('lobby');
|
||||
await Bun.sleep(0);
|
||||
await Bun.sleep(0);
|
||||
expect(cards.status).toBe('playing');
|
||||
expect(cards.game!.shuffles).toBe(1);
|
||||
const plain = practice('one-card');
|
||||
plain.botProfiles[botsOf(plain)[0]!]!.luck = 0.05;
|
||||
expect(plain.start('A')).toBeNull();
|
||||
expect(plain.status).toBe('playing');
|
||||
expect(asked).toEqual(['one-card']);
|
||||
});
|
||||
});
|
||||
62
apps/server/src/rooms/bot-profile.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Each computer's level and luck in a room (docs/09-game-engine.md §9.1, docs/06-lobby-rooms.md §12).
|
||||
* Level 1~60: drawn when the computer is added (any level) or when the host picks a band (쉬움 1~20, 보통 21~40,
|
||||
* 어려움 41~60). After that it moves a little from game to game but stays near where it started.
|
||||
*/
|
||||
import { secureRandom } from '@bg/engine';
|
||||
import { BOT_BANDS, BOT_LEVEL_MAX, bandOf, type BotPick } from '@bg/shared';
|
||||
import { hash01, idLevel } from '@bg/games/bots';
|
||||
|
||||
export interface BotProfile {
|
||||
/** What the host chose: 랜덤 (any level) or a band. */
|
||||
pick: BotPick;
|
||||
/** The level drawn for that choice; the drift stays around it. */
|
||||
base: number;
|
||||
/** The level it plays at now. */
|
||||
level: number;
|
||||
/** -1 (아주 나쁨) … 1 (아주 좋음), drawn once when the computer is added. */
|
||||
luck: number;
|
||||
/** Games it has started with this base. */
|
||||
played: number;
|
||||
}
|
||||
|
||||
/** How far a level may move from where it started, and how much in one game. */
|
||||
export const DRIFT_RANGE = 5;
|
||||
export const DRIFT_STEP = 2;
|
||||
|
||||
const int = (lo: number, hi: number, random: () => number) => lo + Math.floor(random() * (hi - lo + 1));
|
||||
|
||||
export function rollLevel(pick: BotPick, random: () => number = secureRandom): number {
|
||||
const [lo, hi] = pick === 'random' ? [1, BOT_LEVEL_MAX] : BOT_BANDS[pick];
|
||||
return int(lo, hi, random);
|
||||
}
|
||||
|
||||
export function newBotProfile(random: () => number = secureRandom): BotProfile {
|
||||
const base = rollLevel('random', random);
|
||||
return { pick: 'random', base, level: base, luck: random() * 2 - 1, played: 0 };
|
||||
}
|
||||
|
||||
/** The host picked a difficulty: a new level from that range, luck stays. */
|
||||
export function repick(p: BotProfile, pick: BotPick, random: () => number = secureRandom): BotProfile {
|
||||
const base = rollLevel(pick, random);
|
||||
return { ...p, pick, base, level: base, played: 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Before each game after the first: the level moves by at most `DRIFT_STEP`, never more than `DRIFT_RANGE` from where
|
||||
* it started and never out of that band (a 60 can become 58, never 41).
|
||||
*/
|
||||
export function drift(p: BotProfile, random: () => number = secureRandom): BotProfile {
|
||||
if (p.played === 0) return { ...p, played: 1 };
|
||||
const [blo, bhi] = BOT_BANDS[bandOf(p.base)];
|
||||
const lo = Math.max(blo, p.base - DRIFT_RANGE);
|
||||
const hi = Math.min(bhi, p.base + DRIFT_RANGE);
|
||||
const level = Math.min(hi, Math.max(lo, p.level + int(-DRIFT_STEP, DRIFT_STEP, random)));
|
||||
return { ...p, level, played: p.played + 1 };
|
||||
}
|
||||
|
||||
/** Computers saved before rooms kept a profile: level and luck fixed by the id. */
|
||||
export function profileFromId(bot: string): BotProfile {
|
||||
const base = idLevel(bot);
|
||||
return { pick: 'random', base, level: base, luck: hash01(bot, 'luck') * 2 - 1, played: 0 };
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
/** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES } from '@bg/games/bots';
|
||||
import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bots';
|
||||
import { classicDeck, type OneCardState } from '@bg/games/one-card';
|
||||
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
||||
import { botPace, defaultBotDelay, type BotDelayInput } from './bots';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn, type RoomSnapshot } from './room';
|
||||
@@ -88,6 +90,41 @@ describe('bot list', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('game speed scales the thinking time, but not a reaction the game timed itself', () => {
|
||||
const bot = 'bot:1:01J0000000000000000000000';
|
||||
const r = () => 0.5;
|
||||
const input = { choices: 4, withPeople: true, bot, followUp: false };
|
||||
expect(defaultBotDelay(input, r, 3)).toBe(Math.round((2600 * botPace(bot) + 1500) * 3));
|
||||
expect(defaultBotDelay(input, r, 0.25)).toBe(Math.round((2600 * botPace(bot) + 1500) * 0.25));
|
||||
expect(defaultBotDelay({ ...input, reactMs: 800 }, r, 3)).toBe(800);
|
||||
});
|
||||
|
||||
test('the admin game speed reaches the computers (×1.5 slower base) and the room view', () => {
|
||||
let speed = 1 / 16;
|
||||
const db = openDb(':memory:');
|
||||
let now = 1_000_000;
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const settings = { game: () => null, getSite: () => SiteSettingsSchema.parse({ gameSpeed: speed }) } as unknown as SettingsStore;
|
||||
const manager = new RoomManager({ store: new RoomStore(db), games: GAMES, users, now: () => now, settings });
|
||||
const play = () => {
|
||||
const room = manager.createPractice('A', 'omok') as Room;
|
||||
rooms.push(room);
|
||||
room.join({ userId: 'A', send: () => {}, close: () => {} }, 'player');
|
||||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||||
expect(room.roomView().gameSpeed).toBe(speed);
|
||||
return room.bots.dueAt! - now;
|
||||
};
|
||||
// 1/16: at least the shortest thought (0.49 s) × 1.5 × 16, though never past half the 30 s turn timer.
|
||||
const slow = play();
|
||||
expect(slow).toBeGreaterThanOrEqual(11_000);
|
||||
expect(slow).toBeLessThanOrEqual(15_000);
|
||||
speed = 16;
|
||||
// ×16: at most the longest thought (10.4 s) × 1.5 / 16.
|
||||
expect(play()).toBeLessThanOrEqual(1000);
|
||||
});
|
||||
|
||||
test('thinking never takes more than half of the time left on the turn timer', () => {
|
||||
const h = harness(undefined, undefined, () => 60 * 60_000);
|
||||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||||
@@ -338,6 +375,63 @@ describe('playing with bots', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('원카드: computers call and catch on their own reaction clock', () => {
|
||||
test('a computer that played down to one card calls at its reaction time; a person can catch only after 2 s', () => {
|
||||
const h = harness(undefined, undefined, (input) => defaultBotDelay(input, () => 0.5));
|
||||
const room = h.manager.createPractice('A', 'one-card') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = bots(room)[0]!;
|
||||
// Rig: the computer's turn with [♥9, ♣3] on ♥5; the person is next.
|
||||
const s = room.game!.state as OneCardState;
|
||||
const deck = classicDeck(1);
|
||||
const take = (ids: string[]) => ids.map((id) => deck.find((c) => c.id === id)!);
|
||||
s.hands = { A: take(['S4', 'S6', 'D8']), [bot]: take(['H9', 'C3']) };
|
||||
s.discard = take(['H5']);
|
||||
s.drawPile = deck.filter((c) => !['S4', 'S6', 'D8', 'H9', 'C3', 'H5'].includes(c.id));
|
||||
s.current = bot;
|
||||
s.phase = { kind: 'turn' };
|
||||
s.pendingAttack = 0;
|
||||
s.declaredSuit = null;
|
||||
s.oneCardWindow = null;
|
||||
room.bots.cancel();
|
||||
room.scheduleTimer();
|
||||
for (let k = 0; k < 5 && !(room.game!.state as OneCardState).oneCardWindow; k++) {
|
||||
h.clock.advance(Math.max(0, (room.bots.dueAt ?? h.clock.now()) - h.clock.now()));
|
||||
room.bots.fire();
|
||||
}
|
||||
let st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: false });
|
||||
expect(st.current).toBe('A');
|
||||
const opened = st.oneCardWindow!.openedAt!;
|
||||
// Planned exactly at its reaction time (not squeezed by the turn clock, no thinking chat).
|
||||
const at = botReactionAt(room.def, st, bot, room.profile(bot).level) as number;
|
||||
expect(at).toBeGreaterThanOrEqual(opened + 500);
|
||||
expect(room.bots.dueAt).toBe(at);
|
||||
const rejects = () => a.msgs.filter((m) => m.t === 'reject').length;
|
||||
const before = rejects();
|
||||
room.act('A', 101, { type: 'declareOneCard' });
|
||||
expect(rejects()).toBe(before + 1);
|
||||
if (at > opened + 2000) {
|
||||
// Slow this time: the person catches it first and the planned call is dropped.
|
||||
h.clock.advance(opened + 2000 - h.clock.now());
|
||||
room.act('A', 102, { type: 'declareOneCard' });
|
||||
st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toBeNull();
|
||||
expect(st.hands[bot]).toHaveLength(2);
|
||||
expect(room.bots.dueAt).toBeNull();
|
||||
} else {
|
||||
h.clock.advance(at - h.clock.now());
|
||||
room.bots.fire();
|
||||
st = room.game!.state as OneCardState;
|
||||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: true });
|
||||
expect(st.hands[bot]).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('practice rooms close once nobody is there', () => {
|
||||
function finishedPractice() {
|
||||
const h = harness();
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
* After every state change the room calls `schedule()`: if the game waits on a bot, one action is planned after a
|
||||
* short human-like pause and played through the room's normal action path (validated, logged as `act`).
|
||||
*/
|
||||
import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
|
||||
import { isBotId } from '@bg/shared';
|
||||
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, type LiveBotStrategy } from '@bg/games/bots';
|
||||
import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, botReactionAt, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
|
||||
|
||||
import type { BotBrain } from '../ai/brain';
|
||||
|
||||
@@ -23,8 +23,12 @@ export interface BotRoom {
|
||||
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
||||
/** Display name of a player (live bots talk about each other by name). */
|
||||
nameOf?(id: string): string;
|
||||
/** A computer's level now and the level it started with (docs/09 §9.1); absent = fixed by the id. */
|
||||
profile?(bot: string): { level: number; base: number };
|
||||
/** The computers' talk and visible activity with the local model (docs/06 §12.1). */
|
||||
brain?: BotBrain;
|
||||
/** Multiplies the computers' thinking time and live games' look intervals (game speed, docs/14 §5); absent = 1. */
|
||||
timeScale?(): number;
|
||||
}
|
||||
|
||||
/** What a planned computer move looks like, for its thinking time. */
|
||||
@@ -37,23 +41,31 @@ export interface BotDelayInput {
|
||||
bot: string;
|
||||
/** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */
|
||||
followUp: boolean;
|
||||
/** An out-of-turn reaction the game timed itself (원카드 외치기·잡기, `botReactionAt`): wait exactly this long. */
|
||||
reactMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-like thinking time (ms). A forced move still takes a moment to notice (0.7~1.3 s); a real choice takes longer
|
||||
* the more moves there are (1.6~3.9 s), and now and then the computer hesitates (+1~3 s). Each bot scales it by its
|
||||
* own pace, and a follow-up move of the same turn is quicker. When people may act in the same window the computer
|
||||
* waits 1.5 s more so it never beats a person to a reaction just by being fast.
|
||||
* waits 1.5 s more so it never beats a person to a reaction just by being fast. `scale` (game speed, `BOT_SLOWDOWN /
|
||||
* speed`) multiplies the whole thinking time; a reaction the game timed itself (`reactMs`) is never scaled, so who
|
||||
* calls first stays fair.
|
||||
*/
|
||||
export function defaultBotDelay(input: BotDelayInput, random: () => number = Math.random): number {
|
||||
export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom, scale = 1): number {
|
||||
const { choices, withPeople, bot, followUp } = input;
|
||||
if (input.reactMs !== undefined) return Math.max(0, Math.round(input.reactMs));
|
||||
let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400;
|
||||
if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000;
|
||||
ms *= botPace(bot);
|
||||
if (followUp) ms *= 0.5;
|
||||
return Math.round(withPeople ? ms + 1500 : ms);
|
||||
return Math.round((withPeople ? ms + 1500 : ms) * scale);
|
||||
}
|
||||
|
||||
/** At game speed ×1 the computers take this much longer than `defaultBotDelay`'s base times (2026-10-14: a bit slower). */
|
||||
export const BOT_SLOWDOWN = 1.5;
|
||||
|
||||
/** Never use more than this share of the time left on the turn timer for thinking. */
|
||||
export const BOT_DEADLINE_SHARE = 0.5;
|
||||
|
||||
@@ -66,6 +78,8 @@ export class BotDriver {
|
||||
dueAt: number | null = null;
|
||||
/** Bot the planned action is for. */
|
||||
private planned: string | null = null;
|
||||
/** The planned action is that bot's out-of-turn reaction due at this time (not its normal move). */
|
||||
private plannedReact: number | null = null;
|
||||
/** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */
|
||||
private acting: string | null = null;
|
||||
/** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */
|
||||
@@ -78,36 +92,79 @@ export class BotDriver {
|
||||
|
||||
constructor(
|
||||
private room: BotRoom,
|
||||
private random: () => number = Math.random,
|
||||
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random),
|
||||
private random: () => number = secureRandom,
|
||||
private delay: (input: BotDelayInput) => number = (input) => defaultBotDelay(input, random, room.timeScale?.() ?? 1),
|
||||
) {}
|
||||
|
||||
/** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */
|
||||
schedule(): void {
|
||||
if (this.liveStrategy()) return this.scheduleLive();
|
||||
if (this.dueAt !== null || this.busy) return;
|
||||
if (this.busy) return;
|
||||
if (this.dueAt !== null) {
|
||||
// A planned reaction the moment has passed for (someone called first): plan again; anything else stays planned.
|
||||
if (this.plannedReact === null || this.reactionDue()?.bot === this.planned) return;
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
this.plannedReact = null;
|
||||
}
|
||||
const next = this.next();
|
||||
if (!next) return;
|
||||
// People can see it think: "생각 중…" until it moves.
|
||||
if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true);
|
||||
const react = this.reactionDue();
|
||||
if (!next && !react) return;
|
||||
const now = this.room.now();
|
||||
let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting });
|
||||
const deadline = this.room.deadline?.() ?? null;
|
||||
if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE));
|
||||
let ms = Infinity;
|
||||
if (next) {
|
||||
ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting });
|
||||
const deadline = this.room.deadline?.() ?? null;
|
||||
if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE));
|
||||
}
|
||||
// An out-of-turn reaction (원카드!) comes first when it is due earlier; it is not squeezed by the turn clock, so a
|
||||
// slow computer can really be late.
|
||||
if (react) {
|
||||
const rms = this.delay({ choices: 1, withPeople: true, bot: react.bot, followUp: false, reactMs: react.at - now });
|
||||
if (rms <= ms) {
|
||||
this.dueAt = now + rms;
|
||||
this.planned = react.bot;
|
||||
this.plannedReact = react.at;
|
||||
return this.arm();
|
||||
}
|
||||
}
|
||||
// People can see it think: "생각 중…" until it moves.
|
||||
if (this.room.brain?.enabled()) this.room.brain.thinking(next!.bot, true);
|
||||
this.dueAt = now + ms;
|
||||
this.planned = next.bot;
|
||||
this.planned = next!.bot;
|
||||
this.plannedReact = null;
|
||||
this.arm();
|
||||
}
|
||||
|
||||
/** The earliest out-of-turn reaction of a computer that may act now (games with `BOT_REACTIONS`). */
|
||||
private reactionDue(): { bot: string; at: number } | null {
|
||||
const g = this.room.game;
|
||||
if (!g || g.finished || this.room.status !== 'playing') return null;
|
||||
let best: { bot: string; at: number } | null = null;
|
||||
for (const p of g.players) {
|
||||
if (!isBotId(p)) continue;
|
||||
const at = botReactionAt(this.room.def, g.state, p, this.room.profile?.(p).level ?? idLevel(p));
|
||||
if (typeof at === 'number' && (!best || at < best.at)) best = { bot: p, at };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
if (this.timer) clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
if (this.planned) this.room.brain?.thinking(this.planned, false);
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
this.plannedReact = null;
|
||||
this.liveDue.clear();
|
||||
}
|
||||
|
||||
private timeScale(): number {
|
||||
return this.room.timeScale?.() ?? 1;
|
||||
}
|
||||
|
||||
private liveStrategy(): LiveBotStrategy | null {
|
||||
return LIVE_BOT_STRATEGIES[this.room.def.id] ?? null;
|
||||
}
|
||||
@@ -131,7 +188,7 @@ export class BotDriver {
|
||||
}
|
||||
const now = this.room.now();
|
||||
for (const p of g.players) {
|
||||
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p)));
|
||||
if (isBotId(p) && !this.liveDue.has(p)) this.liveDue.set(p, now + Math.round((300 + this.random() * 1200) * botPace(p) * this.timeScale()));
|
||||
}
|
||||
const next = Math.min(...this.liveDue.values());
|
||||
this.dueAt = Number.isFinite(next) ? next : null;
|
||||
@@ -157,19 +214,21 @@ export class BotDriver {
|
||||
let decision: { action: unknown; next: number; hint?: string } = { action: null, next: 3000 };
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot), names, memory });
|
||||
const profile = this.room.profile?.(bot);
|
||||
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, profile?.base), level: profile?.level ?? idLevel(bot), names, memory });
|
||||
} catch (err) {
|
||||
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
|
||||
}
|
||||
const ms = performance.now() - t0;
|
||||
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
|
||||
this.liveDue.set(bot, now + Math.max(100, decision.next));
|
||||
this.liveDue.set(bot, now + Math.max(100, Math.round(decision.next * this.timeScale())));
|
||||
if (decision.action == null) continue;
|
||||
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);
|
||||
@@ -182,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 }));
|
||||
@@ -216,8 +275,11 @@ export class BotDriver {
|
||||
const active = def.activePlayers(g.state);
|
||||
const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]);
|
||||
const withPeople = active.some((p) => !isBotId(p));
|
||||
const timed = new Set(def.timeoutPlayers?.(g.state) ?? active);
|
||||
for (const p of g.players) {
|
||||
if (!isBotId(p) || !waiting.has(p)) continue;
|
||||
// Only there to react out of turn (원카드!): `reactionDue` times that, not the thinking time.
|
||||
if (!timed.has(p) && botReactionAt(def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)) !== null) continue;
|
||||
const choices = botCandidates(def, g.state, p).length;
|
||||
if (choices > 0) return { bot: p, choices, withPeople };
|
||||
}
|
||||
@@ -236,18 +298,21 @@ export class BotDriver {
|
||||
return this.fireLive(live);
|
||||
}
|
||||
const planned = this.planned;
|
||||
const wasReact = this.plannedReact !== null;
|
||||
this.dueAt = null;
|
||||
this.planned = null;
|
||||
const next = this.next();
|
||||
this.plannedReact = null;
|
||||
const react = wasReact ? this.reactionDue() : null;
|
||||
const next = wasReact ? (react && react.bot === planned ? { bot: react.bot } : null) : this.next();
|
||||
const g = this.room.game;
|
||||
if (!next || !g) return;
|
||||
// Another bot's turn came up meanwhile: give it its own thinking time.
|
||||
if (next.bot !== planned) return this.schedule();
|
||||
if (!g) return;
|
||||
// Another bot's turn came up meanwhile (or the reaction is moot): give it its own thinking time.
|
||||
if (!next || next.bot !== planned) return this.schedule();
|
||||
const def = this.room.def;
|
||||
const t0 = performance.now();
|
||||
let action: unknown;
|
||||
try {
|
||||
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random });
|
||||
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: this.room.profile?.(next.bot).level ?? idLevel(next.bot) });
|
||||
} catch (err) {
|
||||
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
|
||||
action = null;
|
||||
@@ -255,7 +320,8 @@ export class BotDriver {
|
||||
const ms = performance.now() - t0;
|
||||
if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) });
|
||||
const brain = this.room.brain;
|
||||
if (brain && action != null && brain.enabled()) {
|
||||
// A reaction (원카드!) is a reflex: no chat before it.
|
||||
if (brain && action != null && brain.enabled() && !wasReact) {
|
||||
// Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move.
|
||||
const bot = next.bot;
|
||||
this.busy = bot;
|
||||
|
||||
89
apps/server/src/rooms/case-file.room.test.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/** 사건 파일 through a real Room: briefing clock, captain passes, report clock, race clock, and views that keep unread texts on the server (docs/games/case-file.md §8.5). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ServerMessage } from '@bg/shared';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { CASES, type CaseFileOptions, type CaseFileState } from '@bg/games/case-file';
|
||||
import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
function harness(players: string[], opts: Partial<CaseFileOptions> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, set: (t: number) => (now = t), advance: (ms: number) => (now += ms) };
|
||||
const games = { 'case-file': GAMES['case-file']! };
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = { gameId: 'case-file', options: games['case-file'].optionsSchema.parse(opts), maxPlayers: players.length, visibility: 'private', allowSpectators: true, chatEnabled: true, chatFilter: true, graceSec: 60 };
|
||||
const room = new Room('room1', '482913', config, players[0]!, deps);
|
||||
store.insertRoom({ id: 'room1', code: '482913', hostId: players[0]!, gameId: 'case-file', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
|
||||
const conns: Record<string, Conn & { msgs: ServerMessage[] }> = {};
|
||||
for (const p of players) {
|
||||
const msgs: ServerMessage[] = [];
|
||||
conns[p] = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(conns[p], 'player');
|
||||
}
|
||||
expect(room.start(players[0]!)).toBeNull();
|
||||
room.clearTimer();
|
||||
const state = () => room.game!.state as CaseFileState;
|
||||
/** Jumps to the current deadline and lets the room fire it. */
|
||||
const expire = () => {
|
||||
clock.set(Math.max(clock.now(), room.effectiveDeadline()!));
|
||||
room.onTimer();
|
||||
room.clearTimer();
|
||||
};
|
||||
let cs = 0;
|
||||
/** Sends an action like the client and fails on a reject. */
|
||||
const act = (p: string, a: unknown) => {
|
||||
const before = conns[p]!.msgs.length;
|
||||
room.act(p, ++cs, a);
|
||||
room.clearTimer();
|
||||
const rej = conns[p]!.msgs.slice(before).find((m) => m.t === 'reject');
|
||||
if (rej) throw new Error(`${p} ${JSON.stringify(a)} rejected: ${JSON.stringify(rej)}`);
|
||||
};
|
||||
return { room, clock, conns, state, expire, act };
|
||||
}
|
||||
|
||||
const allText = (msgs: ServerMessage[]) => JSON.stringify(msgs);
|
||||
|
||||
describe('사건 파일 room flow', () => {
|
||||
test('의뢰 60초 → 수사, 반장 시간 초과는 넘기기만, 보고서 시간 초과 → 채점', () => {
|
||||
const { room, state, expire, conns, act } = harness(['A', 'B'], { turnSeconds: 60, reportSeconds: 180 });
|
||||
expect(state().phase).toBe('briefing');
|
||||
expire();
|
||||
expect(state().phase).toBe('investigate');
|
||||
const cap = state().players[state().decider]!.id;
|
||||
expire();
|
||||
expect(state().players[state().decider]!.id).not.toBe(cap);
|
||||
expect(state().investigations.team!.visited).toHaveLength(0);
|
||||
const now = state().players[state().decider]!.id;
|
||||
act(now, { type: 'pick', lead: 'c1-03' });
|
||||
// The read text went out; texts nobody read did not.
|
||||
const c = CASES.c1;
|
||||
expect(allText(conns.A!.msgs)).toContain(JSON.stringify(c.leads[2]!.text).slice(1, 40));
|
||||
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.leads[10]!.text).slice(1, 40));
|
||||
expect(allText(conns.B!.msgs)).not.toContain(JSON.stringify(c.solution).slice(1, 40));
|
||||
const next = state().players[state().decider]!.id;
|
||||
act(next, { type: 'report' });
|
||||
expect(state().phase).toBe('report');
|
||||
act('A', { type: 'answer', q: 'q1', choice: 0 });
|
||||
expire();
|
||||
expire();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.lastResult!.summary).toContain('범인은 강민재였어요');
|
||||
});
|
||||
|
||||
test('따로 겨루기: 전체 시간이 끝나면 모두 보고서, 끝나면 순위', () => {
|
||||
const { room, state, expire, act } = harness(['A', 'B'], { mode: 'race', raceMinutes: 30, reportSeconds: 180 });
|
||||
expire();
|
||||
expect(state().raceEndsAt).not.toBeNull();
|
||||
act('A', { type: 'pick', lead: 'c1-01' });
|
||||
expire();
|
||||
expect(state().phase).toBe('report');
|
||||
act('B', { type: 'answer', q: 'q1', choice: 0 });
|
||||
act('B', { type: 'submit' });
|
||||
expire();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.lastResult!.ranking).toEqual([['B'], ['A']]);
|
||||
});
|
||||
});
|
||||
91
apps/server/src/rooms/castles-of-burgundy.room.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/** 버건디의 성 through a real Room: a practice game against a computer, played from the person's own screen, with turn clocks (docs/games/castles-of-burgundy.md §8.5). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { CobAction, CobState, CobView } from '@bg/games/castles-of-burgundy';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Room, Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as CobView | null;
|
||||
|
||||
/** What the person presses, read only from their own screen: place > take > anything but ending the turn early. */
|
||||
function personMove(v: CobView): CobAction | null {
|
||||
const my = v.my;
|
||||
if (!my || !my.moves.length) return null;
|
||||
const rank = (a: CobAction) =>
|
||||
a.type === 'useDie' ? (a.act.kind === 'place' ? 0 : a.act.kind === 'take' ? 1 : 3) : a.type === 'endTurn' ? 9 : a.type === 'buy' ? 8 : 2;
|
||||
let best = my.moves.map((a, i) => ({ a, i })).sort((x, y) => rank(x.a) - rank(y.a) || (my.costs[x.i] ?? 0) - (my.costs[y.i] ?? 0) || x.i - y.i)[0]!.a;
|
||||
if (my.needDiscard) {
|
||||
if ((best.type === 'useDie' || best.type === 'bonus') && best.act.kind === 'take') best = { ...best, act: { ...best.act, discard: 0 } };
|
||||
else if ((best.type === 'buy' || best.type === 'depotTake' || best.type === 'soloTrade') && 'tile' in best) best = { ...best, discard: 0 } as CobAction;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
describe('버건디의 성 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 자기 화면만 보고 두고, 가끔 시간을 넘겨도 끝까지 가요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'castles-of-burgundy') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots.length).toBeGreaterThan(0);
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
let lastTurn = -1;
|
||||
let skipTurn = false;
|
||||
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
if (!v || !v.my) continue;
|
||||
if (v.turnSeq !== lastTurn) {
|
||||
lastTurn = v.turnSeq;
|
||||
skipTurn = v.turnSeq % 7 === 3; // now and then the person lets the clock run out
|
||||
}
|
||||
if (skipTurn) continue;
|
||||
const m = personMove(v);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as CobState;
|
||||
expect(s.stage).toBe('finished');
|
||||
expect(s.log.some((e) => e.t === 'end')).toBe(true);
|
||||
expect(mine).toBeGreaterThan(40);
|
||||
const last = lastView(a)!;
|
||||
expect(last.final!.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import { RoomStore } from './store';
|
||||
type Msgs = ServerMessage[];
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -19,7 +19,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'catchmind',
|
||||
options: games.catchmind.defaultOptions,
|
||||
options: { ...games.catchmind.defaultOptions, ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -170,12 +170,29 @@ describe('그림 맞히기 room flow', () => {
|
||||
expect(state().away).toEqual([d]);
|
||||
});
|
||||
|
||||
test('그리기 무제한: 연결된 출제자는 타이머 없음, 연결이 끊기면 10초 뒤 턴 종료', () => {
|
||||
const { room, clock, conns, state, act } = harness(['A', 'B'], { drawSeconds: null, hints: 'basic' });
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
expect(state().turn.endsAt).toBeNull();
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
clock.advance(600_000);
|
||||
expect(state().turn.phase).toBe('drawing');
|
||||
room.disconnect(conns[d]!);
|
||||
room.clearTimer();
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 10_000);
|
||||
clock.advance(10_000);
|
||||
room.onTimer();
|
||||
room.clearTimer();
|
||||
expect(state().turn.endReason).toBe('drawerAway');
|
||||
});
|
||||
|
||||
test('연결된 출제자는 힌트·시간 만료 때만 tick(10초 지나도 끝나지 않음)', () => {
|
||||
const { room, clock, state, act } = harness(['A', 'B']);
|
||||
const d = state().turn.drawer;
|
||||
act(d, { type: 'chooseWord', index: 0 });
|
||||
const t0 = state().turn.startedAt;
|
||||
const ends = state().turn.endsAt;
|
||||
const ends = state().turn.endsAt!;
|
||||
expect(room.effectiveDeadline()).toBe(t0 + (ends - t0) / 2);
|
||||
clock.advance(20_000);
|
||||
room.onTimer();
|
||||
|
||||
113
apps/server/src/rooms/gemblo.room.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
/** 젬블로 through a real Room: practice against computers from the person's own screen, and the turn clock (docs/games/gemblo.md §8.5, §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { GembloAction, GembloState, GembloView } from '@bg/games/gemblo';
|
||||
import { legalPlacements, obstaclePlacements } from '@bg/games/gemblo/board';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as GembloView | null;
|
||||
|
||||
/** What the person does, read only from their own screen: tap the first link point, take the first way it offers. */
|
||||
function personMove(v: GembloView, me: string): GembloAction | null {
|
||||
if (v.turnPlayer !== me || v.phase === 'finished') return null;
|
||||
if (v.phase === 'obstacleDraft') return { type: 'pickObstacle', pieceId: v.obstacle!.pool[0]! };
|
||||
if (v.phase === 'obstaclePlace') {
|
||||
const p = obstaclePlacements(v, v.obstacle!.hands[me]!, v.obstacle!.sectorCount, undefined, 1)[0]!;
|
||||
return { type: 'placeObstacle', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
|
||||
}
|
||||
if (!v.legal) return null;
|
||||
const c = v.colors[v.turn]!;
|
||||
// A link point may be one no block left can cover (only the 1-cell block would fit): try the next point.
|
||||
for (const point of v.legal.bridgePoints) {
|
||||
const p = legalPlacements(v, c, v.allowFlip, { points: [point] })[0];
|
||||
if (p) return { type: 'place', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
|
||||
}
|
||||
throw new Error('my turn without a placement');
|
||||
}
|
||||
|
||||
function drive(h: ReturnType<typeof harness>, room: Room, a: ReturnType<ReturnType<typeof harness>['conn']>, play: boolean) {
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
for (let i = 0; i < 20_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(500);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
const m = play && v ? personMove(v, 'A') : null;
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
return mine;
|
||||
}
|
||||
|
||||
describe('젬블로 room flow', () => {
|
||||
test('컴퓨터 1명과 연습: 사람은 자기 화면(이음점 → 놓는 방법)만 보고 끝까지', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'gemblo') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const mine = drive(h, room, a, true);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as GembloState;
|
||||
expect(s.colors).toHaveLength(4); // 2명 = 2색씩
|
||||
expect(s.placements.filter((p) => p.auto)).toEqual([]);
|
||||
expect(mine).toBeGreaterThan(10);
|
||||
const v = lastView(a)!;
|
||||
expect(v.result!.ranking.flat().sort()).toEqual(['A', ...s.players.filter(isBotId)].sort());
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('5명(장애물 직접 고르기) + 시간 초과만 하는 사람: 자동 배치 두 번 뒤 그 사람 색은 끝나고 게임은 끝까지', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'gemblo', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
for (let i = 0; i < 4; i++) expect(room.addBot('A')).toBeNull();
|
||||
expect(room.configure('A', { options: { ...GAMES.gemblo!.defaultOptions, fivePlayerObstacles: 'draft' } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect((room.game!.state as GembloState).phase).toBe('obstacleDraft');
|
||||
drive(h, room, a, false);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const s = room.game!.state as GembloState;
|
||||
expect(s.placements.filter((p) => p.kind === 'obstacle').length).toBeGreaterThanOrEqual(13);
|
||||
const auto = s.placements.filter((p) => p.auto && p.kind === 'play' && s.colors.find((c) => c.color === p.color)?.owner === 'A');
|
||||
expect(auto).toHaveLength(2);
|
||||
expect(s.out).toEqual([expect.objectContaining({ playerId: 'A', reason: 'timeLoss' })]);
|
||||
expect(lastView(a)!.result!.ranking.at(-1)).toEqual(['A']);
|
||||
});
|
||||
});
|
||||
150
apps/server/src/rooms/hot-streak.room.test.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
/** 핫스트릭 through a real Room: races flip on the server clock only, 빨리 보기 needs everyone, practice games finish (docs/games/hot-streak.md §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { HotStreakAction, HotStreakState, HotStreakView } from '@bg/games/hot-streak';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as HotStreakView);
|
||||
|
||||
/** What the person presses, read only from their own screen. */
|
||||
function personMove(v: HotStreakView, n: number): HotStreakAction | null {
|
||||
const l = v.legal;
|
||||
if (l.draft) {
|
||||
const o = l.draft[n % l.draft.length]!;
|
||||
return { type: 'DRAFT', stack: o.stack, side: n % 3 === 0 ? 'risky' : 'safe' };
|
||||
}
|
||||
if (l.double) return { type: 'DOUBLE', index: 0 };
|
||||
if (l.submit) return { type: 'SUBMIT', cards: l.submit.cards.slice(0, l.submit.count) };
|
||||
if (l.pot) return { type: 'POT_BET', mascot: 'D', last: false, side: 'NO', doubled: l.pot.doubleRequired ? 'mascot' : null };
|
||||
if (l.ready) return { type: 'READY' };
|
||||
return null;
|
||||
}
|
||||
|
||||
function tick(h: ReturnType<typeof harness>, room: Room, ms = 250) {
|
||||
h.clock.advance(ms);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
}
|
||||
|
||||
describe('핫스트릭 room flow', () => {
|
||||
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 남이 넣은 카드는 안 보여요', (nBots) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'hot-streak') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'hot-streak', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let mine = 0;
|
||||
let seen = 0;
|
||||
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
|
||||
tick(h, room);
|
||||
const vs = views(a);
|
||||
for (const v of vs.slice(seen)) {
|
||||
expect(v.me).toBe('A');
|
||||
const st = room.game!.state as HotStreakState;
|
||||
for (const b of bots) for (const c of st.hands[b] ?? []) expect(JSON.stringify(v)).not.toContain(c);
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, mine);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as HotStreakState;
|
||||
expect(s.results).toHaveLength(3);
|
||||
expect(s.timeouts.A).toBe(0);
|
||||
expect(mine).toBeGreaterThan(6);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('경주는 서버 시계로만 넘어가요: 끊긴 사람이 있어도 2초마다 한 장, 모두 [빨리 보기]면 바로 끝', () => {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'hot-streak', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
const c = h.conn('C');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.join(c, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
let cs = 0;
|
||||
const st = () => room.game!.state as HotStreakState;
|
||||
// Everyone plays the betting steps from their own view.
|
||||
for (let i = 0; i < 400 && st().phase !== 'race'; i++) {
|
||||
for (const [p, cn] of [['A', a], ['B', b], ['C', c]] as const) {
|
||||
const v = views(cn).at(-1);
|
||||
const m = v && personMove(v, i);
|
||||
if (m) room.act(p, ++cs, m);
|
||||
}
|
||||
tick(h, room, 100);
|
||||
}
|
||||
expect(st().phase).toBe('race');
|
||||
// C drops: nothing speeds up (the driver's grace is 0 but cards wait for their time).
|
||||
room.disconnect(c);
|
||||
const flipAt = st().race!.nextFlipAt;
|
||||
expect(room.effectiveDeadline()).toBe(flipAt);
|
||||
const before = st().race!.processed;
|
||||
h.clock.advance(flipAt - h.clock.now() - 10);
|
||||
room.onTimer();
|
||||
expect(st().race!.processed).toBe(before);
|
||||
h.clock.advance(10);
|
||||
room.onTimer();
|
||||
expect(st().race!.processed).toBe(before + 1);
|
||||
// Next card two seconds later.
|
||||
expect(room.effectiveDeadline()).toBe(h.clock.now() + 2000);
|
||||
// 빨리 보기: A and B agree, C (offline) has not — still running.
|
||||
room.act('A', ++cs, { type: 'HURRY' });
|
||||
room.act('B', ++cs, { type: 'HURRY' });
|
||||
if (st().phase === 'race') {
|
||||
expect(st().race!.hurry.sort()).toEqual(['A', 'B']);
|
||||
room.join(c, 'player');
|
||||
room.act('C', ++cs, { type: 'HURRY' });
|
||||
}
|
||||
expect(st().phase).toBe('payout');
|
||||
expect(st().race!.over).toBe(true);
|
||||
});
|
||||
});
|
||||
130
apps/server/src/rooms/liar.room.test.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* 라이어 게임 through a real Room with computers: one person and computers play a whole game with the real bot driver
|
||||
* and the room clock. The person's connection never learns the word (when they are the liar) or who the liar is (when
|
||||
* they are a citizen) before the reveal, and the room chat stays closed while the game runs.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { LiarState, LiarView } from '@bg/games/liar';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(person = 'A') {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const logs: string[] = [];
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: '철수', avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0, log: (level, msg) => level !== 'info' && logs.push(msg) });
|
||||
const room = manager.createPractice(person, 'liar') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const conn: Conn & { msgs: ServerMessage[] } = { userId: person, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(conn, 'player');
|
||||
const state = () => room.game!.state as LiarState;
|
||||
const lastView = () => (msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as LiarView;
|
||||
/** Lets the computers act (their own timers) and the room clock run, until `stop` or the end. */
|
||||
const run = (stop: () => boolean = () => false, maxSteps = 4000) => {
|
||||
for (let i = 0; i < maxSteps && !room.game!.finished && !stop(); i++) {
|
||||
const next = Math.min(room.bots.dueAt ?? Infinity, room.effectiveDeadline() ?? Infinity);
|
||||
expect(Number.isFinite(next)).toBe(true);
|
||||
clock.advance(Math.max(0, next - clock.now()));
|
||||
room.bots.fire();
|
||||
room.onTimer();
|
||||
}
|
||||
};
|
||||
return { room, clock, msgs, conn, state, lastView, run, logs };
|
||||
}
|
||||
|
||||
describe('라이어 게임 room flow with computers', () => {
|
||||
test('연습 방은 사람 1 + 컴퓨터 4, 컴퓨터 채팅은 항상 켜짐', () => {
|
||||
const { room } = practice();
|
||||
expect(room.seatedIds().filter(isBotId)).toHaveLength(4);
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.game!.players).toHaveLength(5);
|
||||
});
|
||||
|
||||
test('사람이 차례에 설명하고 토론·투표하면 컴퓨터와 한 판이 끝까지 가요', () => {
|
||||
const { room, state, lastView, msgs, run, logs } = practice();
|
||||
expect(room.start('A')).toBeNull();
|
||||
expect(room.chat('A', '안녕')).toBe('게임 중에는 게임 화면의 채팅을 써 주세요.');
|
||||
const s0 = state();
|
||||
const iAmLiar = s0.liar === 'A';
|
||||
// Nothing the person receives names the liar or (if they are the liar) the word, until the reveal.
|
||||
const leaks = () => {
|
||||
const all = JSON.stringify(msgs.filter((m) => m.t === 'state').map((m) => ({ ...(m as { view: LiarView }).view, final: null, events: [] })));
|
||||
if (iAmLiar) expect(all).not.toContain(`"${s0.word}"`);
|
||||
expect(all).not.toContain('"liar":true');
|
||||
};
|
||||
let cs = 1;
|
||||
let described = 0;
|
||||
// Reveal: the person confirms; the computers confirm on their own.
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'reveal');
|
||||
expect(state().phase.kind).toBe('describe');
|
||||
const speaker = () => GAMES.liar!.view(state(), null).phase.speaker;
|
||||
while (state().phase.kind === 'describe') {
|
||||
if (speaker() === 'A') {
|
||||
room.act('A', cs++, { type: 'describe', text: iAmLiar ? '저는 좋아하는 편이에요' : '음 다들 아실 거예요' });
|
||||
described++;
|
||||
}
|
||||
run(() => state().phase.kind !== 'describe' || speaker() === 'A');
|
||||
}
|
||||
leaks();
|
||||
expect(described).toBe(state().options.rounds);
|
||||
// Every computer described in its turn.
|
||||
for (const d of state().descriptions) if (d.from !== 'A') expect(d.text).not.toBeNull();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
room.act('A', cs++, { type: 'chat', text: '누가 라이어일까요' });
|
||||
room.act('A', cs++, { type: 'ready' });
|
||||
run(() => state().phase.kind !== 'discussion');
|
||||
// The computers talked in the discussion.
|
||||
expect(state().chat.some((m) => isBotId(m.from))).toBe(true);
|
||||
leaks();
|
||||
while (state().phase.kind === 'vote') {
|
||||
const v = lastView();
|
||||
if (v.my!.voteTargets.length && v.my!.vote === null) room.act('A', cs++, { type: 'vote', target: v.my!.voteTargets[0]! });
|
||||
run(() => state().phase.kind !== 'vote' || (state().phase.kind === 'vote' && (state().phase as { round: number }).round !== v.phase.voteRound));
|
||||
}
|
||||
if (state().phase.kind === 'guess' && state().liar === 'A') room.act('A', cs++, { type: 'guess', text: '모르겠어요' });
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const f = state().final!;
|
||||
expect(f.summary).toMatch(/^(라이어|시민) 승리!/);
|
||||
const end = lastView();
|
||||
expect(end.final!.liar).toBe(s0.liar);
|
||||
expect(end.players.find((p) => p.id === s0.liar)!.liar).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('사람이 아무것도 안 해도(시간 초과만) 끝나요', () => {
|
||||
const { room, run, state, logs } = practice();
|
||||
room.start('A');
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
test('모든 시간 무제한: 컴퓨터는 알아서 하고, 연결이 끊긴 사람은 유예 시간 뒤 넘겨져 끝까지 가요', () => {
|
||||
const { room, conn, run, state, logs } = practice();
|
||||
const none = { describeSeconds: null, discussionSeconds: null, voteSeconds: null, guessSeconds: null };
|
||||
expect(room.configure('A', { options: { ...(room.config.options as object), ...none } })).toBeNull();
|
||||
room.start('A');
|
||||
room.disconnect(conn);
|
||||
run();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(state().options.describeSeconds).toBeNull();
|
||||
expect(state().descriptions.filter((d) => d.from === 'A').every((d) => d.text === null)).toBe(true);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
});
|
||||
18
apps/server/src/rooms/luck-worker.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** Worker thread for the computers' luck (docs/04 §5.1): plays out candidate shuffles off the rooms' thread. */
|
||||
import { createSeed, secureRandom } from '@bg/engine';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { chooseLuckySeed, type LuckJob } from '@bg/games/bots/luck';
|
||||
|
||||
declare const self: Worker;
|
||||
|
||||
self.onmessage = (e: MessageEvent<{ id: number; job: LuckJob }>) => {
|
||||
const { id, job } = e.data;
|
||||
try {
|
||||
const def = GAMES[job.gameId];
|
||||
if (!def) throw new Error(`unknown game ${job.gameId}`);
|
||||
const { seed, tried } = chooseLuckySeed(def, job, createSeed, secureRandom);
|
||||
self.postMessage({ id, seed, tried });
|
||||
} catch (err) {
|
||||
self.postMessage({ id, error: String(err) });
|
||||
}
|
||||
};
|
||||
49
apps/server/src/rooms/luck.test.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
/** The luck worker (docs/04 §5.1): real thread, real play-outs. */
|
||||
import { expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { createLuckSeeder } from './luck';
|
||||
|
||||
const job = (gameId: string, luck: number) => ({
|
||||
gameId,
|
||||
players: ['human', 'bot:1:a'],
|
||||
options: GAMES[gameId]?.defaultOptions ?? {},
|
||||
now: Date.now(),
|
||||
gameNo: 1,
|
||||
luck: { 'bot:1:a': luck },
|
||||
levels: { 'bot:1:a': 30 },
|
||||
budgetMs: 1500,
|
||||
});
|
||||
|
||||
test('plays out the shuffles on a worker thread and returns one of them', async () => {
|
||||
const seeder = createLuckSeeder();
|
||||
try {
|
||||
const [lucky, plain] = await Promise.all([seeder.seed(job('one-card', 1)), seeder.seed(job('one-card', 0))]);
|
||||
expect(lucky.seed).toHaveLength(8);
|
||||
expect(lucky.tried).toBe(5);
|
||||
expect(plain.tried).toBe(1);
|
||||
expect(lucky.seed.every((w) => Number.isInteger(w) && w >= 0 && w < 2 ** 32)).toBe(true);
|
||||
} finally {
|
||||
seeder.stop();
|
||||
}
|
||||
}, 20_000);
|
||||
|
||||
test('an unknown game or a slow worker falls back to one fresh seed', async () => {
|
||||
const logs: string[] = [];
|
||||
const seeder = createLuckSeeder({ log: (_l, msg) => logs.push(msg) });
|
||||
try {
|
||||
const r = await seeder.seed(job('nope', 1));
|
||||
expect(r.tried).toBe(1);
|
||||
expect(r.seed).toHaveLength(8);
|
||||
expect(logs).toContain('luck shuffle failed');
|
||||
} finally {
|
||||
seeder.stop();
|
||||
}
|
||||
const slow = createLuckSeeder({ timeoutMs: 1, log: (_l, msg) => logs.push(msg) });
|
||||
try {
|
||||
const r = await slow.seed(job('mahjong', 1));
|
||||
expect(r.tried).toBe(1);
|
||||
expect(logs).toContain('luck shuffle timed out');
|
||||
} finally {
|
||||
slow.stop();
|
||||
}
|
||||
}, 20_000);
|
||||
76
apps/server/src/rooms/luck.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* The rooms' side of the luck worker (docs/04-stability-security.md §5.1). Playing out a few shuffles takes up to a
|
||||
* couple of seconds for the heaviest games (마작), so it runs on its own thread; the rooms keep running meanwhile.
|
||||
* One worker, jobs in order. If the worker fails or takes too long, the game starts with one fresh seed (no luck).
|
||||
*/
|
||||
import { createSeed, type ChaChaSeed } from '@bg/engine';
|
||||
import type { LuckJob } from '@bg/games/bots/luck';
|
||||
|
||||
type Picked = { seed: ChaChaSeed; tried: number };
|
||||
|
||||
export interface LuckSeeder {
|
||||
seed(job: LuckJob): Promise<Picked>;
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
export function createLuckSeeder(opts: { timeoutMs?: number; log?: (level: 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void } = {}): LuckSeeder {
|
||||
const timeoutMs = opts.timeoutMs ?? 8000;
|
||||
let worker: Worker | null = null;
|
||||
let nextId = 1;
|
||||
const pending = new Map<number, { resolve: (p: Picked) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
const fallback = (): Picked => ({ seed: createSeed(), tried: 1 });
|
||||
|
||||
const settle = (id: number, p: Picked) => {
|
||||
const job = pending.get(id);
|
||||
if (!job) return;
|
||||
pending.delete(id);
|
||||
clearTimeout(job.timer);
|
||||
job.resolve(p);
|
||||
};
|
||||
|
||||
const reset = (why: string) => {
|
||||
opts.log?.('error', 'luck worker failed', { why });
|
||||
worker?.terminate();
|
||||
worker = null;
|
||||
for (const id of [...pending.keys()]) settle(id, fallback());
|
||||
};
|
||||
|
||||
const get = (): Worker => {
|
||||
if (worker) return worker;
|
||||
const w = new Worker(new URL('./luck-worker.ts', import.meta.url).href);
|
||||
w.onmessage = (e: MessageEvent<{ id: number; seed?: ChaChaSeed; tried?: number; error?: string }>) => {
|
||||
const { id, seed, tried, error } = e.data;
|
||||
if (error || !seed) {
|
||||
opts.log?.('warn', 'luck shuffle failed', { error });
|
||||
settle(id, fallback());
|
||||
} else settle(id, { seed, tried: tried ?? 1 });
|
||||
};
|
||||
w.onerror = (e) => reset(String((e as ErrorEvent).message ?? e));
|
||||
w.unref();
|
||||
worker = w;
|
||||
return w;
|
||||
};
|
||||
|
||||
return {
|
||||
seed(job) {
|
||||
return new Promise<Picked>((resolve) => {
|
||||
const id = nextId++;
|
||||
const timer = setTimeout(() => {
|
||||
opts.log?.('warn', 'luck shuffle timed out', { game: job.gameId });
|
||||
settle(id, fallback());
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve, timer });
|
||||
try {
|
||||
get().postMessage({ id, job });
|
||||
} catch (err) {
|
||||
reset(String(err));
|
||||
}
|
||||
});
|
||||
},
|
||||
stop() {
|
||||
worker?.terminate();
|
||||
worker = null;
|
||||
for (const id of [...pending.keys()]) settle(id, fallback());
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { openDb } from '../db';
|
||||
import { Room, type Conn, type RoomConfig } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
function harness(players: string[]) {
|
||||
function harness(players: string[], options: Record<string, unknown> = {}) {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
@@ -16,7 +16,7 @@ function harness(players: string[]) {
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'mafia',
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night' },
|
||||
options: { ...games.mafia.defaultOptions, firstPhase: 'night', ...options },
|
||||
maxPlayers: players.length,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
@@ -57,8 +57,10 @@ describe('마피아 room flow', () => {
|
||||
expect(all).not.toContain(`"role":"mafia"`);
|
||||
}
|
||||
// Rate limit (validate gets the server clock), and the system-only phase timer cannot be sent by clients.
|
||||
room.act(mafia, 2, { type: 'chat', channel: 'mafia', text: '또' });
|
||||
expect(conns[mafia]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 2, reason: '조금 천천히 보내 주세요.' });
|
||||
// No pace limit: a long run of lines in the same instant all goes through.
|
||||
for (let i = 0; i < 20; i++) room.act(mafia, 10 + i, { type: 'chat', channel: 'mafia', text: `연달아 ${i}` });
|
||||
expect(lastView(mafia).chat.filter((c) => c.text.startsWith('연달아')).length).toBe(20);
|
||||
expect(conns[mafia]!.msgs.some((m) => m.t === 'reject')).toBe(false);
|
||||
room.act(town[0]!, 3, { type: 'phaseTimeout' });
|
||||
expect(conns[town[0]!]!.msgs.at(-1)).toEqual({ t: 'reject', cs: 3, reason: '잘못된 요청이에요.' });
|
||||
expect(state().phase.kind).toBe('night');
|
||||
@@ -67,4 +69,23 @@ describe('마피아 room flow', () => {
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
expect(state().day).toBe(2);
|
||||
});
|
||||
|
||||
test('밤 시간 무제한: 타이머 없이 모두 밤 마치기를 누를 때까지, 연결이 끊긴 사람은 유예 시간 뒤 넘김', () => {
|
||||
const { room, clock, conns, state } = harness(['A', 'B', 'C', 'D'], { nightSeconds: null });
|
||||
expect(room.start('A')).toBeNull();
|
||||
clock.advance(8_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
let cs = 10;
|
||||
for (const p of ['A', 'B', 'C']) room.act(p, ++cs, { type: 'readyEarly' });
|
||||
clock.advance(3_600_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('night');
|
||||
room.disconnect(conns.D!);
|
||||
expect(room.effectiveDeadline()).toBe(clock.now() + 60_000);
|
||||
clock.advance(60_000);
|
||||
room.onTimer();
|
||||
expect(state().phase.kind).toBe('discussion');
|
||||
});
|
||||
});
|
||||
|
||||
103
apps/server/src/rooms/magical-athlete.room.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
/** 야단법석 달리기 through a real Room: practice games against computers played to the end from the person's own screen (docs/games/magical-athlete.md §10). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { MagicalAthleteAction, MagicalAthleteState, MagicalAthleteView } from '@bg/games/magical-athlete';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as MagicalAthleteView);
|
||||
|
||||
/** What the person presses, read only from their own screen (uses a power whenever one is offered). */
|
||||
function personMove(v: MagicalAthleteView, me: string, n: number): MagicalAthleteAction | null {
|
||||
if (v.phase === 'draft') return v.draft!.picker === me ? { type: 'DRAFT', racer: v.draft!.line[n % v.draft!.line.length]! } : null;
|
||||
if (v.phase === 'select') {
|
||||
if (v.picked[me]) return null;
|
||||
const left = v.teams[me]!.filter((id) => !v.used[me]!.includes(id));
|
||||
return { type: 'SELECT', racers: left.slice(0, v.perRace) };
|
||||
}
|
||||
const pr = v.prompt;
|
||||
if (v.phase !== 'race' || !pr || pr.owner !== me) return null;
|
||||
if (pr.step === 'go') return { type: 'GO', racer: pr.options[0]!.key as never };
|
||||
if (pr.step === 'roll') return n % 4 === 3 && pr.options.some((o) => o.key === 'use') ? { type: 'CHOOSE', key: 'use' } : { type: 'ROLL' };
|
||||
return { type: 'CHOOSE', key: n % 2 === 0 ? pr.options[0]!.key : 'skip' };
|
||||
}
|
||||
|
||||
describe('야단법석 달리기 room flow', () => {
|
||||
test.each([1, 3])('컴퓨터 %i명과 연습: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 출전 선수는 경주 전까지 안 보여요', (nBots) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'magical-athlete') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'magical-athlete', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let seen = 0;
|
||||
let mine = 0;
|
||||
for (let i = 0; i < 40_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const vs = views(a);
|
||||
// A computer's secret pick never reaches my screen before the race starts.
|
||||
for (const v of vs.slice(seen)) {
|
||||
if (v.phase === 'select') for (const b of bots) expect(JSON.stringify(v)).not.toContain(`-${b}-`);
|
||||
expect(v.me).toBe('A');
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, 'A', mine);
|
||||
if (m) {
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as MagicalAthleteState;
|
||||
expect(s.results).toHaveLength(4);
|
||||
expect(s.timeouts.A).toBe(0); // every step of the person was a real press
|
||||
expect(s.perRace).toBe(nBots === 1 ? 2 : 1);
|
||||
for (const p of s.seats) expect(s.used[p]).toHaveLength(4 * s.perRace);
|
||||
const last = views(a).at(-1)!;
|
||||
expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
const total = (p: string) => last.scores[p]!.total;
|
||||
expect(last.result!.ranking[0]!.total).toBe(Math.max(...s.seats.map(total)));
|
||||
expect(mine).toBeGreaterThan(20);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Creates, finds, restores and garbage-collects rooms (docs/06 §11, docs/04 §3). */
|
||||
import { ulid } from 'ulid';
|
||||
import type { AnyGameDefinition } from '@bg/engine';
|
||||
import { secureRandom, type AnyGameDefinition } from '@bg/engine';
|
||||
import { PRACTICE_PLAYERS, botsAllowed, isAllowedRoomCode, isBotId, type PublicUser } from '@bg/shared';
|
||||
import { Room, type RoomConfig, type RoomDeps, type RoomSnapshot } from './room';
|
||||
import type { RoomStore } from './store';
|
||||
@@ -29,6 +29,8 @@ export interface ManagerDeps {
|
||||
ai?: RoomDeps['ai'];
|
||||
aiSleep?: RoomDeps['aiSleep'];
|
||||
aiRandom?: RoomDeps['aiRandom'];
|
||||
/** Shuffles for the computers' luck (docs/04 §5.1); absent = one fresh seed per game. */
|
||||
luckSeed?: RoomDeps['luckSeed'];
|
||||
/** When the user's last socket to the site closed; null while the site is open somewhere (the gateway knows). */
|
||||
offlineSince?: (userId: string) => number | null;
|
||||
}
|
||||
@@ -56,6 +58,7 @@ export class RoomManager {
|
||||
ai: this.deps.ai,
|
||||
aiSleep: this.deps.aiSleep,
|
||||
aiRandom: this.deps.aiRandom,
|
||||
luckSeed: this.deps.luckSeed,
|
||||
onEmpty: (room, why) => {
|
||||
// The last person left on purpose and nobody holds a seat (only computers, or nobody joined): close it now.
|
||||
if (why === 'leave' && this.byCode.get(room.code) === room && !room.hasPeopleSeated()) this.close(room);
|
||||
@@ -80,7 +83,7 @@ export class RoomManager {
|
||||
}
|
||||
|
||||
private newCode(): string {
|
||||
const rand = this.deps.random ?? Math.random;
|
||||
const rand = this.deps.random ?? secureRandom;
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const code = String(Math.floor(rand() * 1_000_000)).padStart(6, '0');
|
||||
if (!isAllowedRoomCode(code) || this.byCode.has(code)) continue;
|
||||
@@ -112,6 +115,7 @@ export class RoomManager {
|
||||
allowSpectators: true,
|
||||
chatEnabled: site?.chatEnabledDefault ?? true,
|
||||
chatFilter: site?.chatFilterDefault ?? true,
|
||||
botChat: false,
|
||||
graceSec: site?.graceSec ?? 60,
|
||||
};
|
||||
const code = this.newCode();
|
||||
|
||||
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
@@ -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');
|
||||
@@ -226,3 +306,167 @@ describe('윷놀이 room rules', () => {
|
||||
expect(st.view.turnSeq).toBe((room.game!.state as any).turnSeq);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Room chat (2026-10-13)', () => {
|
||||
test('no pace limit: any number of lines in the same instant all go through, in order', () => {
|
||||
const { room, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
const lines = Array.from({ length: 30 }, (_, i) => `줄 ${i}`);
|
||||
for (const t of lines) expect(room.chat('A', t)).toBeNull();
|
||||
expect(b.msgs.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(lines);
|
||||
});
|
||||
|
||||
test('lines sent before joining come back marked as replay; live lines are not', () => {
|
||||
const { room, conn } = harness();
|
||||
const a = conn('A');
|
||||
room.join(a, 'player');
|
||||
room.chat('A', '먼저 한 말');
|
||||
const b = conn('B');
|
||||
room.join(b, 'player');
|
||||
room.chat('A', '지금 한 말');
|
||||
const got = b.msgs.filter((m) => m.t === 'chat').map((m) => [(m as { text: string }).text, (m as { replay?: true }).replay ?? false]);
|
||||
expect(got).toEqual([
|
||||
['먼저 한 말', true],
|
||||
['지금 한 말', false],
|
||||
]);
|
||||
expect((a.msgs.find((m) => m.t === 'chat') as { replay?: true }).replay).toBeUndefined();
|
||||
});
|
||||
|
||||
test('typing at a person\'s pace (a line every 0.4 s) never waits', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
room.join(conn('A'), 'player');
|
||||
for (let i = 0; i < 30; i++) {
|
||||
expect(room.chat('A', `줄 ${i}`)).toBeNull();
|
||||
clock.advance(400);
|
||||
}
|
||||
});
|
||||
|
||||
test('"입력 중" reaches the others (not me), repeats within a second are dropped, off always goes', () => {
|
||||
const { room, clock, conn } = harness();
|
||||
const a = conn('A');
|
||||
const b = conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
const typingOf = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m) => m.t === 'typing');
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', true, 'room');
|
||||
expect(typingOf(b)).toEqual([{ t: 'typing', from: 'A', on: true, ch: 'room' }]);
|
||||
expect(typingOf(a)).toHaveLength(0);
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
room.typing('A', false, 'room');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Game chat signal only while a game with its own chat runs (omok has none).
|
||||
room.typing('A', true, 'game');
|
||||
expect(typingOf(b)).toHaveLength(3);
|
||||
// Chat off: nothing.
|
||||
room.configure('A', { chatEnabled: false });
|
||||
clock.advance(1000);
|
||||
room.typing('A', true, 'room');
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
* All mutations run on the single JS thread, so a room never sees concurrent updates.
|
||||
*/
|
||||
import { ulid } from 'ulid';
|
||||
import { SeededRng, createSeed, seedToHex, type AnyGameDefinition, type GameResult, type RngState } from '@bg/engine';
|
||||
import { botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { SeededRng, createSeed, secureRandom, seedToHex, type AnyGameDefinition, type ChaChaSeed, type GameResult, type RngState } from '@bg/engine';
|
||||
import { botChatRequired, clampChatSound, clampGameSpeed, botsAllowed, isBotId, makeBotId, botNumber, maskProfanity, type BotPick, type PublicUser, type RoomView, type ServerMessage, type SeatView } from '@bg/shared';
|
||||
import { botPersona } from '@bg/games/bots';
|
||||
import { luckApplies, shufflesFor, type LuckJob } from '@bg/games/bots/luck';
|
||||
import { sha256Hex } from '../auth/sessions';
|
||||
import { BotDriver, type BotDelayInput } from './bots';
|
||||
import { BOT_SLOWDOWN, BotDriver, type BotDelayInput } from './bots';
|
||||
import { drift, newBotProfile, profileFromId, repick, type BotProfile } from './bot-profile';
|
||||
import { BotBrain, type BotActivity } from '../ai/brain';
|
||||
import type { Llm } from '../ai/llm';
|
||||
import type { LogEntry, RoomStore } from './store';
|
||||
@@ -26,6 +29,8 @@ export interface RoomConfig {
|
||||
allowSpectators: boolean;
|
||||
chatEnabled: boolean;
|
||||
chatFilter: boolean;
|
||||
/** Computers chat on their own (docs/06 §12.1). Off unless the host turns it on; rooms saved before it existed read as off. */
|
||||
botChat?: boolean;
|
||||
/** Seconds a disconnected player keeps their turn timer before auto actions kick in (docs/03 §6.2). */
|
||||
graceSec: number;
|
||||
}
|
||||
@@ -54,6 +59,10 @@ interface GameSlot {
|
||||
finished: boolean;
|
||||
/** After a restore, deadlines are not enforced before this time (docs/04 §3.3). */
|
||||
deadlineFloor: number | null;
|
||||
/** Each computer's level and luck in this game (shown in the fairness check afterwards). */
|
||||
bots?: Record<string, { level: number; luck: number }>;
|
||||
/** Shuffles tried for the computers' luck (docs/04 §5.1); 1 or absent = the first one. */
|
||||
shuffles?: number;
|
||||
}
|
||||
|
||||
/** Shape persisted to room_state.state_json. */
|
||||
@@ -70,6 +79,8 @@ export interface RoomSnapshot {
|
||||
lastResult: GameResult | null;
|
||||
game: GameSlot | null;
|
||||
joinedAt: Record<string, number>;
|
||||
/** Computers' level and luck (absent in rooms saved before 2026-10-11: then fixed by the bot id). */
|
||||
bots?: Record<string, BotProfile>;
|
||||
}
|
||||
|
||||
export interface RoomDeps {
|
||||
@@ -91,12 +102,24 @@ export interface RoomDeps {
|
||||
aiSleep?: (ms: number) => Promise<void>;
|
||||
/** Dice for the computers' talk (whether to speak now); tests may pin it. */
|
||||
aiRandom?: () => number;
|
||||
/**
|
||||
* Tries shuffles for the computers' luck off the main thread (docs/04 §5.1). Absent (tests): every game starts at
|
||||
* once with one fresh seed.
|
||||
*/
|
||||
luckSeed?: (job: LuckJob) => Promise<{ seed: ChaChaSeed; tried: number }>;
|
||||
}
|
||||
|
||||
const CHAT_HISTORY = 30;
|
||||
/** Time the luck worker may spend on more shuffles (the first is always played out), docs/04 §5.1. */
|
||||
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';
|
||||
@@ -117,6 +140,12 @@ export class Room {
|
||||
lastSeed: string | null = null;
|
||||
lastResult: GameResult | null = null;
|
||||
game: GameSlot | null = null;
|
||||
/** Computers' level and luck (docs/09 §9.1), by bot id. */
|
||||
botProfiles: Record<string, BotProfile> = {};
|
||||
/** The computers' shuffles are being tried; the game starts when they're done. */
|
||||
starting = false;
|
||||
/** Shut down or closed: late callbacks (the luck worker) must not touch it. */
|
||||
private closed = false;
|
||||
chatLog: Extract<ServerMessage, { t: 'chat' }>[] = [];
|
||||
lastActiveAt: number;
|
||||
/** When the last connection went away (null while someone is connected). */
|
||||
@@ -127,7 +156,18 @@ export class Room {
|
||||
private flushTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private recentCs = new Map<string, number[]>();
|
||||
private lastChatAt = new Map<string, number>();
|
||||
/** 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;
|
||||
@@ -166,10 +206,13 @@ export class Room {
|
||||
this.broadcastRoom();
|
||||
},
|
||||
recentChat: () => this.chatLog.slice(-8).map((m) => ({ from: m.from?.nickname ?? '누군가', text: m.text })),
|
||||
smart: (bot) => botPersona(bot, this.profile(bot).base).smart,
|
||||
chatty: () => this.botChatOn(),
|
||||
now: this.now,
|
||||
view: (viewer) => (this.game && !this.game.finished ? this.def.view(this.game.state, viewer) : null),
|
||||
},
|
||||
deps.ai ?? null,
|
||||
deps.aiRandom ?? Math.random,
|
||||
deps.aiRandom ?? secureRandom,
|
||||
deps.aiSleep,
|
||||
);
|
||||
this.bots = new BotDriver(
|
||||
@@ -191,13 +234,20 @@ export class Room {
|
||||
},
|
||||
log: deps.log,
|
||||
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
|
||||
profile: (bot) => this.profile(bot),
|
||||
brain: this.brain,
|
||||
timeScale: () => BOT_SLOWDOWN / this.gameSpeed(),
|
||||
},
|
||||
Math.random,
|
||||
secureRandom,
|
||||
deps.botDelay,
|
||||
);
|
||||
}
|
||||
|
||||
/** The computers' own chat: the room setting, or always where the game needs it (마피아). */
|
||||
private botChatOn(): boolean {
|
||||
return botChatRequired(this.config.gameId) || this.config.botChat === true;
|
||||
}
|
||||
|
||||
get def(): AnyGameDefinition {
|
||||
const d = this.deps.games[this.config.gameId];
|
||||
if (!d) throw new Error(`unknown game ${this.config.gameId}`);
|
||||
@@ -289,6 +339,7 @@ export class Room {
|
||||
lastResult: this.lastResult,
|
||||
game: this.game,
|
||||
joinedAt,
|
||||
bots: this.botProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,6 +354,7 @@ export class Room {
|
||||
room.lastSeed = snap.lastSeed;
|
||||
room.lastResult = snap.lastResult;
|
||||
room.game = snap.game;
|
||||
room.botProfiles = snap.bots ?? {};
|
||||
const now = room.now();
|
||||
for (const s of room.seats) {
|
||||
// Computer players have no connection (and so no reconnect grace period).
|
||||
@@ -317,7 +369,7 @@ export class Room {
|
||||
}
|
||||
// 30s to reconnect, plus up to 30s jitter so thousands of restored rooms don't all time out
|
||||
// in the same instant (thundering herd after a restart, docs/04 §3).
|
||||
room.game.deadlineFloor = now + 30_000 + Math.floor(Math.random() * 30_000);
|
||||
room.game.deadlineFloor = now + 30_000 + Math.floor(secureRandom() * 30_000);
|
||||
room.scheduleTimer();
|
||||
}
|
||||
return room;
|
||||
@@ -385,6 +437,7 @@ export class Room {
|
||||
allowSpectators: this.config.allowSpectators,
|
||||
chatEnabled: this.config.chatEnabled,
|
||||
chatFilter: this.config.chatFilter,
|
||||
botChat: this.botChatOn(),
|
||||
seats,
|
||||
spectators: [...this.spectators].map(pub),
|
||||
status: this.status,
|
||||
@@ -396,6 +449,12 @@ export class Room {
|
||||
lastSeed: this.lastSeed,
|
||||
lastGamePk: this.game?.finished ? this.game.gamePk : null,
|
||||
...(this.botActivity.size ? { botActivity: Object.fromEntries(this.botActivity) } : {}),
|
||||
...(this.hasBots() ? { botPicks: Object.fromEntries(this.seatedIds().filter(isBotId).map((b) => [b, this.profile(b).pick])) } : {}),
|
||||
...(this.starting ? { starting: true } : {}),
|
||||
// Levels are revealed only once the game is over (fairness check).
|
||||
...(this.game?.finished && this.game.bots ? { lastBots: this.game.bots, lastShuffles: this.game.shuffles ?? 1 } : {}),
|
||||
gameSpeed: this.gameSpeed(),
|
||||
chatSound: clampChatSound(this.deps.settings?.getSite().chatSound),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -417,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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -429,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;
|
||||
@@ -486,7 +549,7 @@ export class Room {
|
||||
const st = this.stateMessage(u, undefined, true);
|
||||
if (st) conn.send(st);
|
||||
if (this.status === 'finished' && this.lastResult) conn.send({ t: 'result', seq: this.seq, result: this.lastResult });
|
||||
for (const m of this.chatLog) conn.send(m);
|
||||
for (const m of this.chatLog) conn.send({ ...m, replay: true });
|
||||
this.scheduleTimer();
|
||||
return null;
|
||||
}
|
||||
@@ -499,6 +562,9 @@ export class Room {
|
||||
const u = conn.userId;
|
||||
if (this.conns.get(u) !== conn) return;
|
||||
if (this.spectators.has(u)) return this.disconnect(conn);
|
||||
// Alone in the lobby: nobody to come back to, so leaving the page (뒤로가기, 홈) leaves the room and the empty room
|
||||
// closes now instead of lingering (2026-10-14). A game (running, or its result: 다시 보기 comes back) keeps the seat.
|
||||
if (this.status === 'lobby' && this.conns.size === 1 && !this.seatedIds().some((x) => x !== u && !isBotId(x) && !this.leftDuringGame.has(x))) return this.leave(u);
|
||||
this.conns.delete(u);
|
||||
this.detached.set(u, conn);
|
||||
if (this.conns.size === 0) this.becameEmpty('disconnect');
|
||||
@@ -574,9 +640,20 @@ export class Room {
|
||||
// ---------------------------------------------------------------- lobby commands
|
||||
|
||||
private requireLobby(): string | null {
|
||||
if (this.starting) return '게임을 준비하고 있어요.';
|
||||
return this.status === 'lobby' || this.status === 'finished' ? null : '게임 중에는 바꿀 수 없어요.';
|
||||
}
|
||||
|
||||
/** A computer's level and luck; computers saved without one get it from their id. */
|
||||
/** Admin game speed (docs/14 §5), read live so a change reaches running games too. */
|
||||
gameSpeed(): number {
|
||||
return clampGameSpeed(this.deps.settings?.getSite().gameSpeed);
|
||||
}
|
||||
|
||||
profile(bot: string): BotProfile {
|
||||
return (this.botProfiles[bot] ??= profileFromId(bot));
|
||||
}
|
||||
|
||||
seat(userId: string, seat?: number): string | null {
|
||||
const err = this.requireLobby();
|
||||
if (err) return err;
|
||||
@@ -653,7 +730,7 @@ export class Room {
|
||||
else if (next.gameId === this.config.gameId && this.config.maxPlayers === this.playerRange().max) next.maxPlayers = range.max;
|
||||
next.maxPlayers = Math.min(Math.max(next.maxPlayers, range.min), range.max);
|
||||
if (next.maxPlayers < this.seatedIds().length) return `이미 ${this.seatedIds().length}명이 앉아 있어요.`;
|
||||
for (const k of ['visibility', 'allowSpectators', 'chatEnabled', 'chatFilter'] as const) {
|
||||
for (const k of ['visibility', 'allowSpectators', 'chatEnabled', 'chatFilter', 'botChat'] as const) {
|
||||
if (patch[k] !== undefined) (next as unknown as Record<string, unknown>)[k] = patch[k];
|
||||
}
|
||||
// Resize seats, compacting occupied seats to the front if needed.
|
||||
@@ -712,8 +789,10 @@ export class Room {
|
||||
const used = new Set(this.seatedIds().map(botNumber));
|
||||
let n = 1;
|
||||
while (used.has(n)) n++;
|
||||
const id = makeBotId(n, ulid(this.now()));
|
||||
const id = makeBotId(n, ulid(this.now(), secureRandom));
|
||||
this.seats[target] = { userId: id, ready: true };
|
||||
// Any level 1~60 and its own luck, from OS randomness; the host may pick 쉬움/보통/어려움 afterwards.
|
||||
this.botProfiles[id] = newBotProfile();
|
||||
if (this.config.visibility === 'public') this.config = { ...this.config, visibility: 'private' };
|
||||
this.persist({ actorId: userId, kind: 'addBot', data: { seat: target, bot: id } });
|
||||
this.broadcastRoom();
|
||||
@@ -728,18 +807,31 @@ export class Room {
|
||||
if (seat < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
|
||||
this.seats[seat] = null;
|
||||
this.rematchVotes.delete(botId);
|
||||
delete this.botProfiles[botId];
|
||||
this.persist({ actorId: userId, kind: 'removeBot', data: { bot: botId } });
|
||||
this.broadcastRoom();
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Host picks a computer's difficulty: a new level from that range (랜덤 = any), hidden until the game is over. */
|
||||
setBotLevel(userId: string, botId: string, pick: BotPick): string | null {
|
||||
if (userId !== this.hostId) return '방장만 난이도를 바꿀 수 있어요.';
|
||||
const err = this.requireLobby();
|
||||
if (err) return err;
|
||||
if (this.seatOf(botId) < 0 || !isBotId(botId)) return '없는 컴퓨터예요.';
|
||||
this.botProfiles[botId] = repick(this.profile(botId), pick);
|
||||
this.persist({ actorId: userId, kind: 'botLevel', data: { bot: botId, pick } });
|
||||
this.broadcastRoom();
|
||||
return null;
|
||||
}
|
||||
|
||||
chat(userId: string, text: string): string | null {
|
||||
if (!this.config.chatEnabled) return '이 방은 채팅을 쓰지 않아요.';
|
||||
if (!this.isParticipant(userId)) return '방에 들어와야 채팅할 수 있어요.';
|
||||
if (this.gameChatOnly()) return '게임 중에는 게임 화면의 채팅을 써 주세요.';
|
||||
// No pace limit: every line goes out as soon as it is typed (the socket's own flood guard still applies).
|
||||
const now = this.now();
|
||||
if (now - (this.lastChatAt.get(userId) ?? 0) < 500) return '조금 천천히 보내 주세요.';
|
||||
this.lastChatAt.set(userId, now);
|
||||
this.typingAt.delete(userId);
|
||||
const clean = text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
|
||||
if (!clean) return null;
|
||||
const msg: Extract<ServerMessage, { t: 'chat' }> = {
|
||||
@@ -760,6 +852,21 @@ export class Room {
|
||||
return (this.status === 'playing' || this.status === 'paused') && !!this.def.ownChat;
|
||||
}
|
||||
|
||||
/**
|
||||
* "입력 중" for people, like the computers'. Room chat: only while the room chat is open. Game chat: only in games
|
||||
* with their own chat, and the client only sends it from the public channel (마피아 낮, 라이어 토론).
|
||||
*/
|
||||
typing(userId: string, on: boolean, ch: 'room' | 'game'): void {
|
||||
if (!this.isParticipant(userId)) return;
|
||||
if (ch === 'room' ? !this.config.chatEnabled || this.gameChatOnly() : !this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
if (on) {
|
||||
if (now - (this.typingAt.get(userId) ?? -Infinity) < 1000) return;
|
||||
this.typingAt.set(userId, now);
|
||||
} else this.typingAt.delete(userId);
|
||||
for (const [id, c] of this.conns) if (id !== userId) c.send({ t: 'typing', from: userId, on, ch });
|
||||
}
|
||||
|
||||
emote(userId: string, id: string): void {
|
||||
if (!this.isParticipant(userId) || this.gameChatOnly()) return;
|
||||
const now = this.now();
|
||||
@@ -780,17 +887,18 @@ export class Room {
|
||||
if (players.length > range.max) return `최대 ${range.max}명까지 할 수 있어요.`;
|
||||
if (this.hasBots() && !botsAllowed(this.config.gameId)) return '컴퓨터는 이 게임을 할 수 없어요.';
|
||||
if (players.every(isBotId)) return '사람이 한 명은 앉아야 해요.';
|
||||
return this.startGame(players);
|
||||
return this.beginGame(players);
|
||||
}
|
||||
|
||||
rematch(userId: string): string | null {
|
||||
if (this.status !== 'finished') return '게임이 끝난 뒤에 누를 수 있어요.';
|
||||
if (this.starting) return '게임을 준비하고 있어요.';
|
||||
if (this.seatOf(userId) < 0) return '자리에 앉아야 해요.';
|
||||
this.rematchVotes.add(userId);
|
||||
const seated = this.seatedIds();
|
||||
const range = this.playerRange();
|
||||
if (seated.length >= range.min && seated.every((u) => isBotId(u) || this.rematchVotes.has(u))) {
|
||||
return this.startGame(this.orderedPlayers());
|
||||
return this.beginGame(this.orderedPlayers());
|
||||
}
|
||||
this.persist(null);
|
||||
this.broadcastRoom();
|
||||
@@ -804,7 +912,8 @@ export class Room {
|
||||
return h > 0 ? [...ids.slice(h), ...ids.slice(0, h)] : ids;
|
||||
}
|
||||
|
||||
private startGame(players: string[]): string | null {
|
||||
/** The options the game would start with, or why it can't start. */
|
||||
private startOptions(players: string[]): { options: unknown } | string {
|
||||
const def = this.def;
|
||||
const lk = this.locked(def.id);
|
||||
const parsed = def.optionsSchema.safeParse(lk.paths.length ? applyLocks(this.config.options, lk.defaults, lk.paths) : this.config.options);
|
||||
@@ -813,22 +922,76 @@ export class Room {
|
||||
if (countErr) return countErr;
|
||||
const eff = this.deps.settings?.game(def.id);
|
||||
if (eff && !eff.enabled) return '관리자가 이 게임을 잠시 막아 두었어요.';
|
||||
this.config = { ...this.config, options: parsed.data };
|
||||
const seed = createSeed();
|
||||
// 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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a game. With computers in a game of chance, a few shuffles are tried first for their luck (docs/04 §5.1)
|
||||
* on the luck worker; the room shows "섞는 중" and starts when they are done (well under a few seconds). If the
|
||||
* seats changed meanwhile, nothing starts and the host can press start again.
|
||||
*/
|
||||
private beginGame(players: string[]): string | null {
|
||||
const ok = this.startOptions(players);
|
||||
if (typeof ok === 'string') return ok;
|
||||
const bots = players.filter(isBotId);
|
||||
const luckSeed = this.deps.luckSeed;
|
||||
if (!luckSeed || !luckApplies(this.def.id) || shufflesFor(bots.map((b) => this.profile(b).luck)) <= 1) return this.startGame(players, null);
|
||||
const job: LuckJob = {
|
||||
gameId: this.def.id,
|
||||
players,
|
||||
options: ok.options,
|
||||
now: this.now(),
|
||||
gameNo: this.gameNo + 1,
|
||||
luck: Object.fromEntries(bots.map((b) => [b, this.profile(b).luck])),
|
||||
levels: Object.fromEntries(bots.map((b) => [b, this.profile(b).level])),
|
||||
budgetMs: LUCK_BUDGET_MS,
|
||||
};
|
||||
this.starting = true;
|
||||
this.broadcastRoom();
|
||||
const gameNo = this.gameNo;
|
||||
void luckSeed(job)
|
||||
.catch((err) => {
|
||||
this.deps.log?.('warn', 'luck shuffle failed', { room: this.code, err: String(err) });
|
||||
return null;
|
||||
})
|
||||
.then((picked) => {
|
||||
this.starting = false;
|
||||
if (this.closed) return;
|
||||
const same = this.gameNo === gameNo && this.requireLobby() === null && this.orderedPlayers().join() === players.join();
|
||||
const err = same ? this.startGame(players, picked) : null;
|
||||
if (err) this.notice('start-failed', err);
|
||||
if (!same || err) this.broadcastRoom();
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
private startGame(players: string[], picked: { seed: ChaChaSeed; tried: number } | null): string | null {
|
||||
const def = this.def;
|
||||
const ok = this.startOptions(players);
|
||||
if (typeof ok === 'string') return ok;
|
||||
this.config = { ...this.config, options: ok.options };
|
||||
const seed = picked?.seed ?? createSeed();
|
||||
const seedHex = seedToHex(seed);
|
||||
const rng = SeededRng.fromSeed(seed);
|
||||
const now = this.now();
|
||||
const gameNo = this.gameNo + 1;
|
||||
let state: unknown;
|
||||
try {
|
||||
state = def.setup({ players, options: parsed.data, rng, now, gameNo });
|
||||
state = def.setup({ players, options: ok.options, rng, now, gameNo });
|
||||
} catch (err) {
|
||||
this.deps.log?.('error', 'setup failed', { room: this.code, err: String(err) });
|
||||
return '게임을 시작하지 못했어요.';
|
||||
}
|
||||
const gamePk = ulid(now);
|
||||
const seedHash = sha256Hex(seedHex);
|
||||
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: parsed.data, seedHash, startedAt: now });
|
||||
// From the second game on, each computer's level moves a little around where it started (docs/09 §9.1).
|
||||
const bots: Record<string, { level: number; luck: number }> = {};
|
||||
for (const b of players.filter(isBotId)) {
|
||||
const p = (this.botProfiles[b] = drift(this.profile(b)));
|
||||
bots[b] = { level: p.level, luck: p.luck };
|
||||
}
|
||||
this.deps.store.insertGame({ id: gamePk, roomId: this.id, gameNo, gameId: def.id, options: ok.options, seedHash, startedAt: now });
|
||||
this.gameNo = gameNo;
|
||||
this.game = {
|
||||
gameId: def.id,
|
||||
@@ -842,6 +1005,7 @@ export class Room {
|
||||
players,
|
||||
finished: false,
|
||||
deadlineFloor: null,
|
||||
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
|
||||
};
|
||||
this.status = 'playing';
|
||||
this.rematchVotes.clear();
|
||||
@@ -982,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;
|
||||
@@ -993,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;
|
||||
@@ -1037,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;
|
||||
@@ -1073,6 +1290,7 @@ export class Room {
|
||||
|
||||
/** Ends a running game uncounted and sends everyone still in the room away (the manager then closes it). */
|
||||
closeWith(summary: string, notice: string): void {
|
||||
this.closed = true;
|
||||
if (this.game && !this.game.finished) {
|
||||
this.finishGame({ ranking: [this.game.players], summary, reason: 'abandoned' }, true);
|
||||
}
|
||||
@@ -1086,6 +1304,7 @@ export class Room {
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
this.closed = true;
|
||||
this.flushStream();
|
||||
this.clearTimer();
|
||||
for (const c of this.conns.values()) {
|
||||
|
||||
142
apps/server/src/rooms/rummikub.room.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 루미큐브 through a real Room (docs/games/rummikub.md §5.6, §8.2–§8.3): the working table is broadcast to everybody
|
||||
* on every drop, the drag preview goes out as a public `stream` message, and a v1 save is migrated on restore.
|
||||
*/
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { ServerMessage } from '@bg/shared';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { cellsOf, freeSpot, type RummikubState, type RummikubView } from '@bg/games/rummikub';
|
||||
import { openDb } from '../db';
|
||||
import { TokenBucket } from '../ws/rate-limit';
|
||||
import { Room, type Conn, type RoomConfig, type RoomSnapshot } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
type Msgs = ServerMessage[];
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const games = { rummikub: GAMES.rummikub! };
|
||||
const deps = { store, games, users: { publicUser: (id: string) => ({ id, nickname: id, avatar: null, kind: 'guest' as const }) }, now: clock.now };
|
||||
const config: RoomConfig = {
|
||||
gameId: 'rummikub',
|
||||
options: { ...games.rummikub.defaultOptions },
|
||||
maxPlayers: 2,
|
||||
visibility: 'private',
|
||||
allowSpectators: true,
|
||||
chatEnabled: true,
|
||||
chatFilter: true,
|
||||
graceSec: 60,
|
||||
};
|
||||
const room = new Room('room1', '482913', config, 'A', deps);
|
||||
store.insertRoom({ id: 'room1', code: '482913', hostId: 'A', gameId: 'rummikub', status: 'lobby', visibility: 'private', config, stateJson: '{}', now });
|
||||
const conn = (p: string) => {
|
||||
const msgs: Msgs = [];
|
||||
const c: Conn & { msgs: Msgs } = { userId: p, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
const conns: Record<string, Conn & { msgs: Msgs }> = { A: conn('A'), B: conn('B') };
|
||||
room.join(conns.A!, 'player');
|
||||
room.join(conns.B!, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
room.clearTimer();
|
||||
conns.S = conn('S');
|
||||
room.join(conns.S, 'spectator');
|
||||
const state = () => room.game!.state as RummikubState;
|
||||
let cs = 100;
|
||||
const act = (p: string, a: unknown) => {
|
||||
room.act(p, ++cs, a);
|
||||
room.clearTimer();
|
||||
return cs;
|
||||
};
|
||||
return { room, store, deps, clock, conns, state, act };
|
||||
}
|
||||
|
||||
const lastView = (m: Msgs) => (m.filter((x): x is StateMsg => x.t === 'state').at(-1)!.view as RummikubView);
|
||||
|
||||
describe('루미큐브 room flow', () => {
|
||||
test('놓을 때마다 바닥이 모두(상대·관전자)에게 바로 보이고, 받침대의 나머지 타일은 보이지 않음', () => {
|
||||
const { conns, state, act } = harness();
|
||||
const cur = state().current;
|
||||
const other = cur === 'A' ? 'B' : 'A';
|
||||
const [t1, t2, ...rest] = state().racks[cur]! as [string, string, ...string[]];
|
||||
act(cur, { type: 'arrange', cells: [{ id: t1, r: 1, c: 2 }], turn: state().turnNo });
|
||||
for (const who of [other, 'S']) {
|
||||
const v = lastView(conns[who]!.msgs);
|
||||
expect(v.draft!.cells).toEqual([{ id: t1, r: 1, c: 2 }]);
|
||||
expect(v.draftEdits).toBe(1);
|
||||
const json = JSON.stringify(v);
|
||||
for (const id of [t2, ...rest]) expect(json.includes(`"${id}"`)).toBe(false);
|
||||
}
|
||||
// Moving it again: everybody sees the new place.
|
||||
act(cur, { type: 'arrange', cells: [{ id: t1, r: 3, c: 7 }, { id: t2, r: 3, c: 8 }], turn: state().turnNo });
|
||||
expect(lastView(conns[other]!.msgs).draft!.cells).toEqual([
|
||||
{ id: t1, r: 3, c: 7 },
|
||||
{ id: t2, r: 3, c: 8 },
|
||||
]);
|
||||
// 되돌리기: back to the turn start for everybody.
|
||||
act(cur, { type: 'resetDraft' });
|
||||
expect(lastView(conns.S!.msgs).draft!.cells).toEqual([]);
|
||||
});
|
||||
|
||||
test('끄는 중인 타일은 stream 메시지로만 중계되고(전체 view 재전송 없음), 받침대 타일은 뒷면(null)', () => {
|
||||
const { conns, state, act } = harness();
|
||||
const cur = state().current;
|
||||
const other = cur === 'A' ? 'B' : 'A';
|
||||
const [t1, t2] = state().racks[cur]! as [string, string];
|
||||
act(cur, { type: 'arrange', cells: [{ id: t1, r: 0, c: 0 }], turn: state().turnNo });
|
||||
const before = { o: conns[other]!.msgs.length, s: conns.S!.msgs.length, me: conns[cur]!.msgs.length };
|
||||
const mine = act(cur, { type: 'drag', ids: [t1, t2], x: 4.5, y: 2, turn: state().turnNo });
|
||||
for (const [who, n] of [
|
||||
[other, before.o],
|
||||
['S', before.s],
|
||||
] as const) {
|
||||
const got = conns[who]!.msgs.slice(n);
|
||||
expect(got).toEqual([{ t: 'stream', seq: expect.any(Number), events: [{ type: 'drag', player: cur, turn: state().turnNo, tiles: [t1, null], x: 4.5, y: 2 }] }]);
|
||||
}
|
||||
// The sender gets the same stream message with its cs (no `pending` lock, no reject).
|
||||
expect(conns[cur]!.msgs.slice(before.me)).toEqual([{ t: 'stream', seq: expect.any(Number), events: expect.any(Array), cs: mine }]);
|
||||
// A late drag from the other player is dropped silently: no error, nothing relayed.
|
||||
const n = conns[other]!.msgs.length;
|
||||
act(other, { type: 'drag', ids: [], x: 0, y: 0 });
|
||||
expect(conns[other]!.msgs.slice(n).some((m) => m.t === 'reject')).toBe(false);
|
||||
});
|
||||
|
||||
test('drag preview pace (5/s) + drops stay well under the socket token bucket (20/s, burst 40)', () => {
|
||||
const bucket = new TokenBucket(20, 40, 0);
|
||||
let dropped = 0;
|
||||
// 30 seconds of non-stop dragging: a preview every 200 ms and a drop every second.
|
||||
for (let t = 0; t < 30_000; t += 200) {
|
||||
if (!bucket.take(t)) dropped++;
|
||||
if (t % 1000 === 0 && !bucket.take(t)) dropped++;
|
||||
}
|
||||
expect(dropped).toBe(0);
|
||||
});
|
||||
|
||||
test('예전 저장(v1, 칸 위치 없음)을 불러오면 칸 판으로 바뀌고 이어서 둘 수 있음', () => {
|
||||
const { room, store, deps, state, act } = harness();
|
||||
act(state().current, { type: 'draw' });
|
||||
room.clearTimer();
|
||||
const { seq, stateJson } = store.openRooms()[0]!;
|
||||
const snap = JSON.parse(stateJson) as RoomSnapshot;
|
||||
const g = snap.game!.state as Record<string, any>;
|
||||
// What a v1 save looked like: sets without places, a draft of sets with an undo history.
|
||||
g.table = [];
|
||||
g.draft = { sets: [], history: [], edits: 0 };
|
||||
snap.game!.stateVersion = 1;
|
||||
const restored = Room.restore('room1', '482913', seq, snap, deps);
|
||||
restored.clearTimer();
|
||||
const s = restored.game!.state as RummikubState;
|
||||
expect(restored.game!.stateVersion).toBe(2);
|
||||
expect(s.draft).toEqual({ cells: [], edits: 0 });
|
||||
const p = s.current;
|
||||
const id = s.racks[p]![0]!;
|
||||
const spot = freeSpot(cellsOf(s.table), 1)!;
|
||||
restored.act(p, 1, { type: 'arrange', cells: [{ id, ...spot }] });
|
||||
restored.clearTimer();
|
||||
expect((restored.game!.state as RummikubState).draft.cells).toEqual([{ id, ...spot }]);
|
||||
});
|
||||
});
|
||||
115
apps/server/src/rooms/shisen.room.test.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/** 사천성 through a real Room: a practice race against a computer to the end, away players (docs/games/shisen.md §8). */
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { findPair, type ShisenState, type ShisenView } from '@bg/games/shisen';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const store = new RoomStore(openDb(':memory:'));
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { clock, manager, conn };
|
||||
}
|
||||
|
||||
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract<ServerMessage, { t: 'state' }>).view as ShisenView;
|
||||
|
||||
function twoPlayers(timeLimitSec: number | null) {
|
||||
const h = harness();
|
||||
const r = h.manager.create('A', 'shisen', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
const room = r as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
const b = h.conn('B');
|
||||
room.join(a, 'player');
|
||||
room.join(b, 'player');
|
||||
room.ready('B', true);
|
||||
expect(room.configure('A', { options: { size: 'small', hints: true, timeLimitSec } })).toBeNull();
|
||||
expect(room.start('A')).toBeNull();
|
||||
h.clock.advance(3000);
|
||||
room.onTimer();
|
||||
return { h, room, a, b, s: () => room.game!.state as ShisenState };
|
||||
}
|
||||
|
||||
describe('사천성 room flow', () => {
|
||||
test('컴퓨터와 연습: 사람은 2초마다 한 쌍씩 없애다 1분 뒤 포기하고, 컴퓨터는 자기 판을 끝까지 풀어요', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'shisen') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bot = room.game!.players.find(isBotId)!;
|
||||
expect(bot).toBeDefined();
|
||||
let cs = 0;
|
||||
let removed = 0;
|
||||
const s = () => room.game!.state as ShisenState;
|
||||
for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const v = lastView(a);
|
||||
if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') {
|
||||
if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' });
|
||||
else {
|
||||
const p = findPair(v.board.cells, v.board.rows, v.board.cols);
|
||||
if (p) {
|
||||
room.act('A', ++cs, { type: 'pair', a: p[0], b: p[1] });
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0);
|
||||
expect(s().boards.A!.removed).toBe(removed);
|
||||
expect(removed).toBeGreaterThan(20);
|
||||
expect(s().status[bot]).toBe('solved');
|
||||
expect(lastView(a).result!.ranking.map((r) => r.id)).toEqual([bot, 'A']);
|
||||
});
|
||||
|
||||
test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => {
|
||||
const { h, room, b, s } = twoPlayers(300);
|
||||
expect(s().phase).toBe('playing');
|
||||
room.disconnect(b);
|
||||
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
||||
h.clock.advance(70_000);
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('playing');
|
||||
h.clock.advance(s().endsAt! - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.endReason).toBe('time');
|
||||
});
|
||||
|
||||
test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => {
|
||||
const { h, room, b, s } = twoPlayers(null);
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.disconnect(b);
|
||||
const d = room.effectiveDeadline()!;
|
||||
h.clock.advance(d - h.clock.now());
|
||||
room.onTimer();
|
||||
expect(s().status.B).toBe('done');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
room.act('A', 1, { type: 'stop' });
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(s().final!.ranking.map((r) => r.status)).toEqual(['done', 'done']);
|
||||
});
|
||||
});
|
||||
129
apps/server/src/rooms/six-nimmt.room.test.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 젝스님트 through a real Room (docs/games/six-nimmt.md §10): practice games against computers played to the end from
|
||||
* the person's own screen, with the simultaneous secret pick, the row choice, the pro draft and timeouts on the clock.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import type { SixNimmtAction, SixNimmtState, SixNimmtView } from '@bg/games/six-nimmt';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import { Room, type Conn } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function harness() {
|
||||
const db = openDb(':memory:');
|
||||
const store = new RoomStore(db);
|
||||
let now = 1_000_000;
|
||||
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
|
||||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||||
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
|
||||
const conn = (userId: string) => {
|
||||
const msgs: ServerMessage[] = [];
|
||||
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
|
||||
return c;
|
||||
};
|
||||
return { db, clock, manager, conn };
|
||||
}
|
||||
|
||||
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
|
||||
const views = (c: { msgs: ServerMessage[] }) => c.msgs.filter((m): m is StateMsg => m.t === 'state').map((m) => m.view as SixNimmtView);
|
||||
|
||||
/** What the person presses, read only from their own screen (the safest-looking card, or the fewest-bulls row). */
|
||||
function personMove(v: SixNimmtView, me: string, n: number): SixNimmtAction | null {
|
||||
if (v.phase === 'draft') return v.draft!.at === me ? { type: 'DRAFT', card: v.draft!.pool[n % v.draft!.pool.length]! } : null;
|
||||
if (v.phase === 'select') {
|
||||
if (v.players[me]!.picked || !v.my) return null;
|
||||
const hand = [...v.my.hand].sort((a, b) => (a.preview?.takes ?? 0) - (b.preview?.takes ?? 0));
|
||||
return { type: 'SELECT', card: hand[n % 2 === 0 ? 0 : hand.length - 1]!.n };
|
||||
}
|
||||
const pd = v.pending;
|
||||
if (v.phase !== 'choose' || !pd || pd.player !== me) return null;
|
||||
if (pd.kind === 'place') return { type: 'PLACE', row: pd.choices[0]!.row, side: pd.choices[0]!.side };
|
||||
const best = v.rows.reduce((b, r, i) => (r.bulls < v.rows[b]!.bulls ? i : b), 0);
|
||||
return { type: 'TAKE_ROW', row: best };
|
||||
}
|
||||
|
||||
describe('젝스님트 room flow', () => {
|
||||
test.each([
|
||||
[1, {}],
|
||||
[3, { deck: 'pro', endMode: 'rounds', rounds: 2 }],
|
||||
[4, { placement: 'both', lowCard: 'choose', endMode: 'rounds', rounds: 2 }],
|
||||
] as const)('컴퓨터 %i명과 연습 %j: 사람은 자기 화면만 보고 끝까지, 컴퓨터가 고른 카드는 공개 전까지 안 보여요', (nBots, options) => {
|
||||
const h = harness();
|
||||
let room: Room;
|
||||
if (nBots === 1) room = h.manager.createPractice('A', 'six-nimmt') as Room;
|
||||
else {
|
||||
const r = h.manager.create('A', 'six-nimmt', 'private');
|
||||
if (typeof r === 'string') throw new Error(r);
|
||||
room = r;
|
||||
expect(room.configure('A', { options: { ...GAMES['six-nimmt']!.defaultOptions, ...options } })).toBeNull();
|
||||
for (let i = 0; i < nBots; i++) expect(room.addBot('A')).toBeNull();
|
||||
}
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
const bots = room.game!.players.filter(isBotId);
|
||||
expect(bots).toHaveLength(nBots);
|
||||
let cs = 0;
|
||||
let seen = 0;
|
||||
let mine = 0;
|
||||
let chose = 0;
|
||||
for (let i = 0; i < 60_000 && !room.game!.finished; i++) {
|
||||
h.clock.advance(250);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
const vs = views(a);
|
||||
for (const v of vs.slice(seen)) {
|
||||
// A computer's secret pick never reaches my screen before the reveal.
|
||||
for (const b of bots) expect(JSON.stringify(v)).not.toContain(`six-sel:${b}`);
|
||||
expect(v.me).toBe('A');
|
||||
}
|
||||
seen = vs.length;
|
||||
const v = vs.at(-1);
|
||||
const m = v && personMove(v, 'A', mine);
|
||||
if (m) {
|
||||
if (m.type === 'TAKE_ROW' || m.type === 'PLACE') chose++;
|
||||
room.act('A', ++cs, m);
|
||||
mine++;
|
||||
}
|
||||
}
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
|
||||
const s = room.game!.state as SixNimmtState;
|
||||
expect(s.timeouts.A).toBe(0); // every step of the person was a real press
|
||||
const last = views(a).at(-1)!;
|
||||
expect(last.result!.ranking.map((r) => r.player).sort()).toEqual(['A', ...bots].sort());
|
||||
expect(last.result!.ranking[0]!.total).toBe(Math.min(...s.seats.map((p) => s.totals[p]!)));
|
||||
expect(mine).toBeGreaterThanOrEqual(10);
|
||||
if (nBots === 1) expect(chose + mine).toBeGreaterThan(10);
|
||||
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
|
||||
expect(JSON.parse(row.result_json).practice).toBe(true);
|
||||
});
|
||||
|
||||
test('시간 초과: 사람이 아무것도 안 하면 제한 시간마다 자동으로 내고 3번이면 자리 비움', () => {
|
||||
const h = harness();
|
||||
const room = h.manager.createPractice('A', 'six-nimmt') as Room;
|
||||
rooms.push(room);
|
||||
const a = h.conn('A');
|
||||
room.join(a, 'player');
|
||||
expect(room.start('A')).toBeNull();
|
||||
for (let i = 0; i < 2000; i++) {
|
||||
h.clock.advance(500);
|
||||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||||
const d = room.effectiveDeadline();
|
||||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||||
if ((room.game!.state as SixNimmtState).timeouts.A! >= 3) break;
|
||||
}
|
||||
const s = room.game!.state as SixNimmtState;
|
||||
expect(s.timeouts.A).toBeGreaterThanOrEqual(3);
|
||||
expect(views(a).at(-1)!.players.A!.away).toBe(true);
|
||||
});
|
||||
});
|
||||
121
apps/server/src/rooms/solitaire.room.test.ts
Normal file
@@ -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
@@ -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
@@ -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');
|
||||
});
|
||||
});
|
||||
90
apps/server/src/rooms/uno.room.test.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/** 우노 with computers in a real room (docs/games/uno.md §9.1): a person and three computers play to the end. */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||||
import type { UnoState } from '@bg/games/uno';
|
||||
import { openDb } from '../db';
|
||||
import { RoomManager } from './manager';
|
||||
import type { Conn, Room } from './room';
|
||||
import { RoomStore } from './store';
|
||||
|
||||
const rooms: Room[] = [];
|
||||
afterEach(() => {
|
||||
for (const r of rooms.splice(0)) r.clearTimer();
|
||||
});
|
||||
|
||||
function practice(options: Record<string, unknown> = {}) {
|
||||
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 room = manager.createPractice('A', 'uno') as Room;
|
||||
rooms.push(room);
|
||||
const msgs: ServerMessage[] = [];
|
||||
const a: Conn = { userId: 'A', send: (m) => msgs.push(m), close: () => {} };
|
||||
room.join(a, 'player');
|
||||
room.addBot('A');
|
||||
room.addBot('A');
|
||||
room.configure('A', { options: { ...(room.config.options as object), ...options } });
|
||||
expect(room.start('A')).toBeNull();
|
||||
return { room, clock, msgs, a };
|
||||
}
|
||||
|
||||
/** Bots move at once; when the game waits on the person, they play their first legal action (or the clock runs out). */
|
||||
function playToEnd(room: Room, clock: { advance: (ms: number) => void }, humanActs: boolean): number {
|
||||
const def = GAMES.uno!;
|
||||
let cs = 0;
|
||||
let steps = 0;
|
||||
for (; steps < 20_000 && !room.game!.finished; steps++) {
|
||||
if (room.bots.dueAt !== null) {
|
||||
room.bots.fire();
|
||||
continue;
|
||||
}
|
||||
const s = room.game!.state as UnoState;
|
||||
const legal = def.legalActions!(s, 'A');
|
||||
if (humanActs && legal.length && def.activePlayers(s).includes('A')) {
|
||||
room.act('A', ++cs, legal.find((x) => (x as { type: string }).type !== 'catchUno') ?? legal[0]);
|
||||
continue;
|
||||
}
|
||||
clock.advance(61_000);
|
||||
room.onTimer();
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
test('a person and three computers finish a game of 우노 (person plays)', () => {
|
||||
const { room, clock } = practice();
|
||||
expect(room.game!.players.filter(isBotId)).toHaveLength(3);
|
||||
playToEnd(room, clock, true);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
expect(room.status).toBe('finished');
|
||||
});
|
||||
|
||||
test('500 points with house rules: the person only times out, the computers still finish', () => {
|
||||
const { room, clock, msgs } = practice({ scoring: 'to500', stacking: true, drawUntilPlayable: true });
|
||||
playToEnd(room, clock, false);
|
||||
expect(room.game!.finished).toBe(true);
|
||||
const s = room.game!.state as UnoState;
|
||||
expect(s.rounds.length).toBeGreaterThanOrEqual(1);
|
||||
expect(msgs.some((m) => m.t === 'state')).toBe(true);
|
||||
// The person's screen shows card counts only for the computers.
|
||||
const view = JSON.stringify(GAMES.uno!.view(s, 'A'));
|
||||
for (const bot of s.seats.filter(isBotId)) for (const c of s.hands[bot]!) expect(view).not.toContain(`"${c.id}"`);
|
||||
});
|
||||
|
||||
test('무제한 time: no clock while the person is here; a dropped connection is still auto-played after the grace time', () => {
|
||||
const { room, clock, a } = practice({ turnSeconds: null });
|
||||
// Let the computers move until the game waits on the person.
|
||||
for (let i = 0; i < 200 && room.bots.dueAt !== null; i++) room.bots.fire();
|
||||
const s = () => room.game!.state as UnoState;
|
||||
expect(GAMES.uno!.activePlayers(s())).toContain('A');
|
||||
expect(room.effectiveDeadline()).toBeNull();
|
||||
const turn = s().turnNo;
|
||||
room.disconnect(a);
|
||||
const d = room.effectiveDeadline();
|
||||
expect(d).not.toBeNull();
|
||||
clock.advance(d! - clock.advance(0) + 1);
|
||||
room.onTimer();
|
||||
expect(s().turnNo !== turn || s().log.some((e) => e.t === 'timeout' && e.p === 'A')).toBe(true);
|
||||
});
|
||||
@@ -216,6 +216,45 @@ describe('M1 integration scenarios', () => {
|
||||
expect(h.res.status).toBe(200);
|
||||
});
|
||||
|
||||
test('10b. chat has its own budget: a fast run of lines (with 입력 중 signals) all arrives and leaves game moves untouched', async () => {
|
||||
const s = start();
|
||||
const a = await client(s, '빠른손');
|
||||
const code = await createRoom(s, a);
|
||||
await join(a, code);
|
||||
for (let i = 0; i < 60; i++) {
|
||||
a.send({ t: 'typing', on: true, ch: 'room' });
|
||||
a.send({ t: 'chat', text: `줄 ${i}` });
|
||||
a.send({ t: 'typing', on: false, ch: 'room' });
|
||||
}
|
||||
await a.next('chat', (m) => m.text === '줄 59');
|
||||
expect(a.messages.filter((m) => m.t === 'chat').map((m) => (m as { text: string }).text)).toEqual(Array.from({ length: 60 }, (_, i) => `줄 ${i}`));
|
||||
// The general budget is still full: a burst of 30 pings all answered.
|
||||
for (let i = 0; i < 30; i++) a.send({ t: 'ping', ts: i });
|
||||
await sleep(200);
|
||||
expect(a.messages.filter((m) => m.t === 'pong').length).toBe(30);
|
||||
});
|
||||
|
||||
test('10c. admin 채팅 도배 방지 (default off) applies at once to open sockets', async () => {
|
||||
const s = start();
|
||||
expect(s.settings.getSite().chatFloodGuard).toBe(false);
|
||||
const a = await client(s, '매크로');
|
||||
const code = await createRoom(s, a);
|
||||
await join(a, code);
|
||||
const lines = () => a.messages.filter((m) => m.t === 'chat').length;
|
||||
// On: 230 lines at once → only the chat budget (200) gets through.
|
||||
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: true }, 'test');
|
||||
for (let i = 0; i < 230; i++) a.send({ t: 'chat', text: `켜짐 ${i}` });
|
||||
await a.next('chat', (m) => m.text === '켜짐 199');
|
||||
await sleep(200);
|
||||
expect(lines()).toBe(200);
|
||||
// Off again: no limit at all.
|
||||
s.settings.setSite({ ...s.settings.getSite(), chatFloodGuard: false }, 'test');
|
||||
for (let i = 0; i < 300; i++) a.send({ t: 'chat', text: `꺼짐 ${i}` });
|
||||
await a.next('chat', (m) => m.text === '꺼짐 299');
|
||||
expect(lines()).toBe(500);
|
||||
expect(a.closed).toBeFalsy();
|
||||
});
|
||||
|
||||
test('11. malformed / oversized / schema-invalid messages', async () => {
|
||||
const s = start();
|
||||
const a = await client(s, '이상한값');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Wires DB, auth, rooms, HTTP and WebSocket into one Bun server (docs/02 §2). */
|
||||
import { existsSync } from 'node:fs';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join, normalize } from 'node:path';
|
||||
import type { Server } from 'bun';
|
||||
import { GAMES } from '@bg/games';
|
||||
@@ -11,12 +11,14 @@ import { SESSION_COOKIE, Sessions } from './auth/sessions';
|
||||
import { Users, toPublicUser } from './auth/users';
|
||||
import { createHttpApp, type HttpDeps } from './http/app';
|
||||
import { RoomManager } from './rooms/manager';
|
||||
import { createLuckSeeder } from './rooms/luck';
|
||||
import type { BotDelayInput } from './rooms/bots';
|
||||
import { RoomStore } from './rooms/store';
|
||||
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;
|
||||
@@ -38,6 +40,8 @@ export interface StartOptions {
|
||||
botDelay?: (input: BotDelayInput) => number;
|
||||
/** Upper bound for waiting on Bun's server.stop() (tests shorten it). */
|
||||
stopWaitMs?: number;
|
||||
/** Computers' luck on a worker thread (docs/04 §5.1); default on. */
|
||||
luck?: boolean;
|
||||
}
|
||||
|
||||
export function startServer(opts: StartOptions) {
|
||||
@@ -54,16 +58,36 @@ 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();
|
||||
// Computers talk and play like people with a local model on the GPU when AI_URL is set (docs/06 §12.1, docs/11 §8).
|
||||
const ai = config.ai ? new Llm({ url: config.ai.url, model: config.ai.model, log }) : null;
|
||||
if (ai) void ai.warm().then((ok) => log('info', 'ai model', { model: config.ai!.model, ready: ok }));
|
||||
const rooms = new RoomManager({ store, games: GAMES, users: { publicUser }, log, settings, botDelay: opts.botDelay, ai, offlineSince: (id): number | null => gateway.offlineSince(id) });
|
||||
const luck = opts.luck === false ? null : createLuckSeeder({ log });
|
||||
const rooms = new RoomManager({
|
||||
store,
|
||||
games: GAMES,
|
||||
users: { publicUser },
|
||||
log,
|
||||
settings,
|
||||
botDelay: opts.botDelay,
|
||||
ai,
|
||||
luckSeed: luck ? (job) => luck.seed(job) : undefined,
|
||||
offlineSince: (id): number | null => gateway.offlineSince(id),
|
||||
});
|
||||
const restored = rooms.restoreAll();
|
||||
log('info', 'rooms restored', restored);
|
||||
const gateway = new Gateway({ rooms, me: publicUser, log, onClose: (id) => users.touch(id) });
|
||||
const gateway = new Gateway({
|
||||
rooms,
|
||||
me: publicUser,
|
||||
log,
|
||||
onClose: (id) => users.touch(id),
|
||||
build: () => build,
|
||||
chatFloodGuard: () => settings.getSite().chatFloodGuard,
|
||||
});
|
||||
const removeGuest = (id: string) => {
|
||||
rooms.leaveAll(id);
|
||||
gateway.closeUser(id);
|
||||
@@ -85,8 +109,13 @@ export function startServer(opts: StartOptions) {
|
||||
server?.requestIP(req)?.address ||
|
||||
'unknown';
|
||||
|
||||
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
|
||||
const serveStatic = staticDir && existsSync(staticDir);
|
||||
// The web build being served (docs/07 §11.1): pages that were opened with an older one offer to refresh.
|
||||
const build = serveStatic ? webBuildId(staticDir!) : null;
|
||||
const app = createHttpApp({
|
||||
config,
|
||||
build,
|
||||
users,
|
||||
sessions,
|
||||
rooms,
|
||||
@@ -105,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: () => {
|
||||
@@ -121,8 +151,6 @@ export function startServer(opts: StartOptions) {
|
||||
},
|
||||
});
|
||||
|
||||
const staticDir = opts.staticDir === undefined ? join(import.meta.dir, '../../web/dist') : opts.staticDir;
|
||||
const serveStatic = staticDir && existsSync(staticDir);
|
||||
|
||||
const server: Server<WsData> = Bun.serve<WsData>({
|
||||
port: config.port,
|
||||
@@ -171,6 +199,7 @@ export function startServer(opts: StartOptions) {
|
||||
clearInterval(sweeper);
|
||||
gateway.shutdown();
|
||||
rooms.shutdown();
|
||||
luck?.stop();
|
||||
// Bun's stop() promise can stay pending after server-initiated WS closes even though the
|
||||
// listener is already closed, so bound the wait.
|
||||
await Promise.race([server.stop(true), Bun.sleep(opts.stopWaitMs ?? 1000)]);
|
||||
@@ -180,6 +209,15 @@ export function startServer(opts: StartOptions) {
|
||||
return { server, stop, rooms, users, sessions, db, gateway, settings, roles, purgeIdleGuests };
|
||||
}
|
||||
|
||||
/** The build id the web build wrote into its index.html (`<meta name="bg-build">`, vite.config.ts), or null. */
|
||||
export function webBuildId(root: string): string | null {
|
||||
try {
|
||||
return /<meta name="bg-build" content="([0-9a-f]+)"/.exec(readFileSync(join(root, 'index.html'), 'utf8'))?.[1] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function serveFile(root: string, pathname: string): Promise<Response> {
|
||||
const safe = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, '');
|
||||
const candidate = join(root, safe);
|
||||
|
||||
44
apps/server/src/version.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/** "업데이트 내용이 있습니다" (docs/07 §11.1): the server tells which web build it serves. */
|
||||
import { afterEach, expect, test } from 'bun:test';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { webBuildId } from './server';
|
||||
import { Client, api, boot, guest } from './test-utils';
|
||||
|
||||
const running: ReturnType<typeof boot>[] = [];
|
||||
const clients: Client[] = [];
|
||||
afterEach(async () => {
|
||||
for (const c of clients.splice(0)) c.close();
|
||||
for (const s of running.splice(0)) await s.stop();
|
||||
});
|
||||
|
||||
function webDir(html: string): string {
|
||||
const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), 'bg-web-'));
|
||||
writeFileSync(join(dir, 'index.html'), html);
|
||||
return dir;
|
||||
}
|
||||
|
||||
test('the build id comes from the meta tag of the served index.html', () => {
|
||||
expect(webBuildId(webDir('<html><head><meta name="bg-build" content="abc123def456"></head></html>'))).toBe('abc123def456');
|
||||
expect(webBuildId(webDir('<html><head></head></html>'))).toBeNull();
|
||||
expect(webBuildId('/nonexistent/dir')).toBeNull();
|
||||
});
|
||||
|
||||
test('/api/version and the socket welcome carry the build', async () => {
|
||||
const s = boot(undefined, { staticDir: webDir('<html><head><meta name="bg-build" content="0123456789ab"></head></html>') });
|
||||
running.push(s);
|
||||
const r = await api(s.base, '/api/version');
|
||||
expect(r.res.headers.get('cache-control')).toBe('no-store');
|
||||
expect(r.body).toEqual({ build: '0123456789ab' });
|
||||
const g = await guest(s.base, '버전확인');
|
||||
const c = await new Client(s.base, g.cookie, g.id).connect();
|
||||
clients.push(c);
|
||||
expect(c.lastOf('welcome')!.build).toBe('0123456789ab');
|
||||
});
|
||||
|
||||
test('without a web build (dev, tests) there is nothing to compare', async () => {
|
||||
const s = boot();
|
||||
running.push(s);
|
||||
expect((await api(s.base, '/api/version')).body).toEqual({ build: null });
|
||||
});
|
||||
69
apps/server/src/ws/gateway.test.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
|
||||
import type { Server, ServerWebSocket } from 'bun';
|
||||
import type { RoomManager } from '../rooms/manager';
|
||||
import { Gateway, type WsData } from './gateway';
|
||||
|
||||
function socket(gw: Gateway) {
|
||||
let data: WsData | undefined;
|
||||
const server = { upgrade: (_req: Request, o: { data: WsData }) => ((data = o.data), true) } as unknown as Server<WsData>;
|
||||
gw.upgrade(new Request('http://x/ws'), server, 'u1');
|
||||
const sent: string[] = [];
|
||||
let closed: number | null = null;
|
||||
const ws = {
|
||||
data: data!,
|
||||
send: (m: string) => void sent.push(m),
|
||||
close: (code: number) => void (closed = code),
|
||||
getBufferedAmount: () => 0,
|
||||
} as unknown as ServerWebSocket<WsData>;
|
||||
return { ws, sent, closed: () => closed };
|
||||
}
|
||||
|
||||
describe('gateway flood guard (2026-10-14)', () => {
|
||||
let spy: ReturnType<typeof spyOn> | null = null;
|
||||
afterEach(() => spy?.mockRestore());
|
||||
|
||||
const chatLine = JSON.stringify({ t: 'chat', text: '도배' });
|
||||
const gateway = (guard: boolean) => new Gateway({ rooms: {} as RoomManager, me: () => null, now: () => 0, chatFloodGuard: () => guard });
|
||||
|
||||
test('도배 방지 켜짐: a flood is cut off before parsing: at most the raw budget of messages is ever parsed', () => {
|
||||
const gw = gateway(true);
|
||||
const { ws, closed } = socket(gw);
|
||||
// Keep the socket open for the whole flood (strikes would close it): only the parse count is under test.
|
||||
ws.data.strikes = -1e9;
|
||||
spy = spyOn(JSON, 'parse');
|
||||
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, '{not json');
|
||||
// Raw budget = game burst 40 + chat burst 200 (the loop takes a few ms, so barely anything refills).
|
||||
expect(spy.mock.calls.length).toBeLessThanOrEqual(250);
|
||||
expect(closed()).toBeNull();
|
||||
});
|
||||
|
||||
test('도배 방지 켜짐: chat past its budget (200 at once) is dropped and a flood closes the socket', () => {
|
||||
const gw = gateway(true);
|
||||
const { ws, closed } = socket(gw);
|
||||
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, chatLine);
|
||||
expect(closed()).toBe(4429);
|
||||
});
|
||||
|
||||
test('도배 방지 꺼짐 (기본): chat is never limited; other messages keep their budget', () => {
|
||||
const gw = gateway(false);
|
||||
const { ws, closed } = socket(gw);
|
||||
spy = spyOn(JSON, 'parse');
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
gw.handlers.message(ws, chatLine);
|
||||
gw.handlers.message(ws, JSON.stringify({ t: 'typing', on: i % 2 === 0, ch: 'room' }));
|
||||
}
|
||||
expect(spy.mock.calls.length).toBe(2000);
|
||||
expect(ws.data.strikes).toBe(0);
|
||||
expect(closed()).toBeNull();
|
||||
// Junk is still cut off (general budget, then strikes).
|
||||
for (let i = 0; i < 1000 && closed() === null; i++) gw.handlers.message(ws, '{not json');
|
||||
expect(closed()).toBe(4429);
|
||||
});
|
||||
|
||||
test('without the setting wired in, the guard is off', () => {
|
||||
const gw = new Gateway({ rooms: {} as RoomManager, me: () => null });
|
||||
const { ws, closed } = socket(gw);
|
||||
for (let i = 0; i < 1000; i++) gw.handlers.message(ws, chatLine);
|
||||
expect(closed()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,12 @@ import { TokenBucket } from './rate-limit';
|
||||
export interface WsData {
|
||||
userId: string;
|
||||
connId: number;
|
||||
/** Every message, checked before parsing (room for both budgets below), so a flood never costs a JSON parse each.
|
||||
* Only while the chat flood guard is on: with it off chat is unlimited, so the raw count cannot be capped. */
|
||||
rawBucket: TokenBucket;
|
||||
bucket: TokenBucket;
|
||||
/** Chat lines and "입력 중" signals have their own budget, so typing fast never eats into (or waits on) game moves. */
|
||||
chatBucket: TokenBucket;
|
||||
strikes: number;
|
||||
room: string | null;
|
||||
conn: Conn | null;
|
||||
@@ -21,9 +26,31 @@ export interface GatewayDeps {
|
||||
log?: (level: 'info' | 'warn' | 'error', msg: string, extra?: Record<string, unknown>) => void;
|
||||
/** A socket closed (the user may have left the site). */
|
||||
onClose?: (userId: string) => void;
|
||||
/** Web build being served (pages opened with an older one offer to refresh, docs/07 §11.1). */
|
||||
build?: () => string | null;
|
||||
/** Admin setting 채팅 도배 방지 (read per message, so a change applies at once). Off when not given. */
|
||||
chatFloodGuard?: () => boolean;
|
||||
}
|
||||
|
||||
export const MAX_CONNS_PER_USER = 5;
|
||||
|
||||
/**
|
||||
* Chat budget per socket: far above any typing speed (a line costs up to three messages: 입력 중 on, the line, off),
|
||||
* only a script flooding the room is cut off.
|
||||
*/
|
||||
const CHAT_RATE_PER_SEC = 50;
|
||||
const CHAT_BURST = 200;
|
||||
/** Game/other budget per socket. */
|
||||
const RATE_PER_SEC = 20;
|
||||
const BURST = 40;
|
||||
|
||||
/** Room chat, game chat (마피아·라이어 게임·그림 맞히기 `act` with `type: 'chat'`) and the "입력 중" signal. */
|
||||
function isChatMessage(m: unknown): boolean {
|
||||
if (typeof m !== 'object' || m === null) return false;
|
||||
const { t, a } = m as { t?: unknown; a?: unknown };
|
||||
if (t === 'chat' || t === 'typing') return true;
|
||||
return t === 'act' && typeof a === 'object' && a !== null && (a as { type?: unknown }).type === 'chat';
|
||||
}
|
||||
const MAX_BUFFERED = 1024 * 1024;
|
||||
|
||||
export class Gateway {
|
||||
@@ -45,7 +72,16 @@ export class Gateway {
|
||||
upgrade(req: Request, server: Server<WsData>, userId: string): Response | undefined {
|
||||
if (this.closing) return new Response('restarting', { status: 503 });
|
||||
if ((this.byUser.get(userId)?.size ?? 0) >= MAX_CONNS_PER_USER) return new Response('too many connections', { status: 429 });
|
||||
const data: WsData = { userId, connId: this.nextId++, bucket: new TokenBucket(20, 40), strikes: 0, room: null, conn: null };
|
||||
const data: WsData = {
|
||||
userId,
|
||||
connId: this.nextId++,
|
||||
rawBucket: new TokenBucket(RATE_PER_SEC + CHAT_RATE_PER_SEC, BURST + CHAT_BURST),
|
||||
bucket: new TokenBucket(RATE_PER_SEC, BURST),
|
||||
chatBucket: new TokenBucket(CHAT_RATE_PER_SEC, CHAT_BURST),
|
||||
strikes: 0,
|
||||
room: null,
|
||||
conn: null,
|
||||
};
|
||||
if (server.upgrade(req, { data })) return undefined;
|
||||
return new Response('upgrade failed', { status: 400 });
|
||||
}
|
||||
@@ -84,6 +120,7 @@ export class Gateway {
|
||||
serverTime: (this.deps.now ?? Date.now)(),
|
||||
protocol: PROTOCOL,
|
||||
activeRoom: this.deps.rooms.activeRoomFor(ws.data.userId),
|
||||
build: this.deps.build?.() ?? null,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -93,23 +130,32 @@ export class Gateway {
|
||||
ws.close(1009, 'message too big');
|
||||
return;
|
||||
}
|
||||
if (!ws.data.bucket.take()) {
|
||||
const strike = () => {
|
||||
if (++ws.data.strikes > 50) ws.close(4429, 'rate limited');
|
||||
return;
|
||||
}
|
||||
let parsed: ClientMessage;
|
||||
};
|
||||
const guard = this.deps.chatFloodGuard?.() ?? false;
|
||||
if (guard && !ws.data.rawBucket.take()) return strike();
|
||||
let json: unknown;
|
||||
let badJson = false;
|
||||
try {
|
||||
const json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
|
||||
const r = ClientMessage.safeParse(json);
|
||||
if (!r.success) {
|
||||
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
parsed = r.data;
|
||||
json = JSON.parse(typeof raw === 'string' ? raw : raw.toString());
|
||||
} catch {
|
||||
badJson = true;
|
||||
}
|
||||
// Guard off: chat is never limited. Everything else keeps the general budget, and junk is still cut off by strikes.
|
||||
const chat = !badJson && isChatMessage(json);
|
||||
const bucket = chat ? (guard ? ws.data.chatBucket : null) : ws.data.bucket;
|
||||
if (bucket && !bucket.take()) return strike();
|
||||
if (badJson) {
|
||||
this.send(ws, { t: 'error', code: 'bad-json', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
const r = ClientMessage.safeParse(json);
|
||||
if (!r.success) {
|
||||
this.send(ws, { t: 'error', code: 'bad-message', message: '잘못된 요청이에요.' });
|
||||
return;
|
||||
}
|
||||
const parsed: ClientMessage = r.data;
|
||||
try {
|
||||
this.dispatch(ws, parsed);
|
||||
} catch (err) {
|
||||
@@ -193,6 +239,9 @@ export class Gateway {
|
||||
case 'removeBot':
|
||||
e = room.removeBot(u, m.userId);
|
||||
break;
|
||||
case 'botLevel':
|
||||
e = room.setBotLevel(u, m.userId, m.pick);
|
||||
break;
|
||||
case 'act':
|
||||
room.act(u, m.cs, m.a);
|
||||
return;
|
||||
@@ -202,6 +251,9 @@ export class Gateway {
|
||||
case 'emote':
|
||||
room.emote(u, m.id);
|
||||
return;
|
||||
case 'typing':
|
||||
room.typing(u, m.on, m.ch);
|
||||
return;
|
||||
case 'rematch':
|
||||
e = room.rematch(u);
|
||||
break;
|
||||
@@ -211,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
@@ -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
@@ -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('입력 중');
|
||||
});
|
||||
@@ -1,18 +1,31 @@
|
||||
import type { RoomView } from '@bg/shared/lite';
|
||||
import { useRoom } from '../net/socket';
|
||||
|
||||
/**
|
||||
* What the computers are doing right now (docs/06 §12.1): "🤖 컴퓨터 1 생각 중…", "💬 컴퓨터 2 입력 중…".
|
||||
* 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). `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 }: { room: RoomView; only?: 'typing' }) {
|
||||
const entries = Object.entries(room.botActivity ?? {}).filter(([, a]) => !only || a === only);
|
||||
if (!entries.length) return null;
|
||||
const name = (id: string) => room.seats.find((s) => s?.user.id === id)?.user.nickname ?? '컴퓨터';
|
||||
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(([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;
|
||||
return (
|
||||
<div className="bot-activity small" aria-hidden>
|
||||
{entries.map(([id, a]) => (
|
||||
<span key={id} data-activity={a}>
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id)} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
{a === 'typing' ? '💬' : '🤖'} {name(id, '컴퓨터')} {a === 'typing' ? '입력 중' : '생각 중'}
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
{people.map(([id]) => (
|
||||
<span key={id} data-activity="typing" data-person>
|
||||
💬 {name(id, '누군가')} 입력 중
|
||||
<span className="bot-dots" />
|
||||
</span>
|
||||
))}
|
||||
|
||||
29
apps/web/src/components/ChatMessage.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* One chat message, shared by the room chat and the games with their own chat (마피아, 라이어 게임): the name sits on
|
||||
* its own small coloured line above a bubble with the text, so who said it and what they said never run together.
|
||||
* My own messages sit on the right without a name; a run of messages from the same person shows the name once.
|
||||
* Hidden names stay in the DOM for screen readers (`.sr-only`).
|
||||
*/
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
|
||||
/** Hues that stay readable as text on the panel in both themes (lightness comes from `--chat-name-l`). */
|
||||
const HUES = [212, 152, 28, 275, 335, 188, 48, 0, 248, 100];
|
||||
|
||||
export function nameHue(id: string): number {
|
||||
let h = 0;
|
||||
for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
|
||||
return HUES[h % HUES.length]!;
|
||||
}
|
||||
|
||||
export function ChatMessage({ from, name, mine = false, cont = false, className, children }: { from: string; name: string; mine?: boolean; cont?: boolean; className?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={`chat-line${mine ? ' mine' : ''}${cont ? ' cont' : ''}${className ? ` ${className}` : ''}`} style={{ '--name-h': nameHue(from) } as CSSProperties}>
|
||||
<strong className={`chat-name${mine || cont ? ' sr-only' : ''}`}>{mine ? '나' : name}</strong>
|
||||
<span className="chat-text">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Same sender as the message right before, within 2 minutes: the name is not repeated. */
|
||||
type RunKey = { from?: string | null; at: number } | undefined;
|
||||
export const sameRun = (prev: RunKey, cur: RunKey): boolean => !!prev && !!cur?.from && prev.from === cur.from && cur.at - prev.at < 120_000;
|
||||
@@ -3,20 +3,25 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { CHAT_MAX, EMOTE_LABEL, EMOTES, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { create } from 'zustand';
|
||||
import { socket, useRoom } from '../net/socket';
|
||||
import { keepFocus, useTypingSignal } from '../lib/chat-input';
|
||||
import { useStickToBottom } from '../lib/useStickToBottom';
|
||||
import { BotActivity } from './BotActivity';
|
||||
import { ChatMessage, sameRun } from './ChatMessage';
|
||||
|
||||
/** Id of the newest chat line shown in an open chat panel (ids only grow; the list itself keeps the last 100). */
|
||||
export const useChatSeen = create<{ seen: number }>(() => ({ seen: 0 }));
|
||||
|
||||
export function ChatPanel({ room, me, title = true }: { room: RoomView; me: PublicUser; title?: boolean }) {
|
||||
const chat = useRoom((s) => s.chat);
|
||||
const [text, setText] = useState('');
|
||||
const [hidden, setHidden] = useState<Set<string>>(new Set());
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const { ref: listRef, pin } = useStickToBottom<HTMLDivElement>();
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const send = (t: string) => socket.send({ t: 'chat', text: t });
|
||||
const typing = useTypingSignal('room', room.chatEnabled);
|
||||
const lastId = chat.at(-1)?.id ?? 0;
|
||||
useEffect(() => {
|
||||
useChatSeen.setState({ seen: chat.length });
|
||||
listRef.current?.scrollTo({ top: listRef.current.scrollHeight });
|
||||
}, [chat.length]);
|
||||
useChatSeen.setState({ seen: lastId });
|
||||
}, [lastId]);
|
||||
// Enter anywhere (outside inputs) focuses chat — PC shortcut (docs/07 §3.5).
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
@@ -34,26 +39,20 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
{title && <h2 style={{ fontSize: '1.1rem' }}>채팅</h2>}
|
||||
<div ref={listRef} className="chat-list" aria-live="polite">
|
||||
{chat.length === 0 && <p className="muted small">아직 메시지가 없어요. Enter를 누르면 바로 입력할 수 있어요.</p>}
|
||||
{chat
|
||||
.filter((m) => !m.from || !hidden.has(m.from.id))
|
||||
.map((m) => (
|
||||
<div key={m.id} className="chat-line">
|
||||
<strong>{m.from?.nickname ?? '알림'}</strong>
|
||||
{chat.map((m, i) =>
|
||||
m.from ? (
|
||||
<ChatMessage key={m.id} from={m.from.id} name={m.from.nickname} mine={m.from.id === me.id} cont={sameRun(chatKey(chat[i - 1]), chatKey(m))}>
|
||||
{m.text}
|
||||
</ChatMessage>
|
||||
) : (
|
||||
<div key={m.id} className="chat-line sys">
|
||||
<strong className="sr-only">알림</strong>
|
||||
{m.text}
|
||||
{m.from && m.from.id !== me.id && (
|
||||
<button
|
||||
className="muted small"
|
||||
style={{ border: 0, background: 'none', cursor: 'pointer' }}
|
||||
title="이 사람의 채팅 가리기"
|
||||
onClick={() => setHidden(new Set([...hidden, m.from!.id]))}
|
||||
>
|
||||
가리기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<BotActivity room={room} only="typing" />
|
||||
<BotActivity room={room} only="typing" ch="room" />
|
||||
<div className="emote-row">
|
||||
{EMOTES.map((id) => (
|
||||
<button key={id} type="button" onClick={() => socket.send({ t: 'emote', id })}>
|
||||
@@ -67,8 +66,11 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
style={{ flexWrap: 'nowrap' }}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (text.trim()) socket.send({ t: 'chat', text: text.trim().slice(0, CHAT_MAX) });
|
||||
if (text.trim()) send(text.trim().slice(0, CHAT_MAX));
|
||||
setText('');
|
||||
typing.stop();
|
||||
pin();
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
@@ -76,14 +78,20 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
className="input"
|
||||
style={{ flex: 1, minHeight: 44 }}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setText(e.target.value);
|
||||
typing.onText(e.target.value);
|
||||
}}
|
||||
onBlur={typing.stop}
|
||||
onKeyDown={(e) => e.key === 'Escape' && (e.currentTarget as HTMLInputElement).blur()}
|
||||
maxLength={CHAT_MAX}
|
||||
placeholder="메시지 입력 (Enter)"
|
||||
aria-label="메시지"
|
||||
enterKeyHint="send"
|
||||
/>
|
||||
<button className="btn btn-primary btn-sm">보내기</button>
|
||||
<button className="btn btn-primary btn-sm" {...keepFocus}>
|
||||
보내기
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted small">이 방은 채팅을 쓰지 않아요. 반응 버튼은 쓸 수 있어요.</p>
|
||||
@@ -92,6 +100,8 @@ export function ChatPanel({ room, me, title = true }: { room: RoomView; me: Publ
|
||||
);
|
||||
}
|
||||
|
||||
const chatKey = (m: { from?: { id: string } | null; at: number } | undefined) => m && { from: m.from?.id ?? null, at: m.at };
|
||||
|
||||
/** Floating emote bubbles (both layouts). */
|
||||
export function EmoteBubbles({ room }: { room: RoomView }) {
|
||||
const emotes = useRoom((s) => s.emotes);
|
||||
|
||||
66
apps/web/src/components/SettingsPopup.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
/** 화면 설정 (font size, colours, sound, vibration, tap-to-place), shared by the 설정 page and the 설정 popup. */
|
||||
import { Link } from 'react-router';
|
||||
import { useSession } from '../store/session';
|
||||
import { Sheet } from './ui';
|
||||
|
||||
function Seg<T extends string>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="setting-row">
|
||||
<strong>{label}</strong>
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={k} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The setting rows only; the caller adds the heading and the box. Changes apply and save at once. */
|
||||
export function DisplaySettings() {
|
||||
const settings = useSession((s) => s.settings);
|
||||
const updateSettings = useSession((s) => s.updateSettings);
|
||||
return (
|
||||
<>
|
||||
<Seg label="글자 크기" value={settings.fontScale} options={[['normal', '보통'], ['large', '크게'], ['xlarge', '아주 크게']]} onChange={(fontScale) => updateSettings({ fontScale })} />
|
||||
<Seg label="화면 색" value={settings.theme} options={[['auto', '자동'], ['light', '밝게'], ['dark', '어둡게']]} onChange={(theme) => updateSettings({ theme })} />
|
||||
<Seg label="소리" value={settings.sound ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ sound: v === 'on' })} />
|
||||
<label className="stack" style={{ gap: 4 }}>
|
||||
<span style={{ fontWeight: 700 }}>
|
||||
소리 크기 <span className="muted">{settings.volume} (기본 50, 이 기기에만 저장)</span>
|
||||
</span>
|
||||
<input type="range" min={0} max={100} step={5} value={settings.volume} aria-label="소리 크기 (0~100)" style={{ accentColor: 'var(--primary)' }} onChange={(e) => updateSettings({ volume: Number(e.target.value) })} />
|
||||
</label>
|
||||
<Seg label="진동" value={settings.vibrate ? 'on' : 'off'} options={[['on', '켜기'], ['off', '끄기']]} onChange={(v) => updateSettings({ vibrate: v === 'on' })} />
|
||||
<Seg
|
||||
label="돌·카드 놓기"
|
||||
value={settings.tapConfirm ? 'on' : 'off'}
|
||||
options={[['on', '두 번 눌러 놓기'], ['off', '한 번에 놓기']]}
|
||||
onChange={(v) => updateSettings({ tapConfirm: v === 'on' })}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 팝업: opens over the current page so a room stays open underneath (no navigation, no leave).
|
||||
* `account` adds a link to the full 설정 page (nickname, records, logout); rooms leave it out because following it leaves the room.
|
||||
*/
|
||||
export function SettingsPopup({ onClose, account }: { onClose: () => void; account?: boolean }) {
|
||||
return (
|
||||
<Sheet onClose={onClose} label="설정">
|
||||
<h2>화면 설정</h2>
|
||||
<DisplaySettings />
|
||||
{account && (
|
||||
<Link className="btn btn-soft btn-block" to="/me" onClick={onClose}>
|
||||
👤 내 계정 · 기록 보기
|
||||
</Link>
|
||||
)}
|
||||
<button type="button" className="btn btn-secondary btn-block" onClick={onClose}>
|
||||
닫기
|
||||
</button>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 테마 버튼과 로그인/계정 메뉴. */
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
/** PC top menu (docs/07-ui-ux.md §3.2): 로고·메뉴, 오른쪽에 소리 크기·테마 버튼과 로그인/계정 메뉴. */
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, NavLink, useNavigate } from 'react-router';
|
||||
import { api } from '../net/api';
|
||||
import { useSession } from '../store/session';
|
||||
import { Avatar, ConfirmSheet } from './ui';
|
||||
import { VolumeControl } from './VolumeControl';
|
||||
import { SettingsPopup } from './SettingsPopup';
|
||||
|
||||
export function SiteHeader() {
|
||||
const { me, siteName, role } = useSession();
|
||||
@@ -21,7 +23,10 @@ export function SiteHeader() {
|
||||
<NavLink to="/games">게임 목록</NavLink>
|
||||
{role !== 'user' && <NavLink to="/admin">관리자</NavLink>}
|
||||
</nav>
|
||||
<ThemeToggle />
|
||||
<div className="header-tools">
|
||||
<VolumeControl />
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
{me ? (
|
||||
<AccountMenu />
|
||||
) : (
|
||||
@@ -56,14 +61,17 @@ function ThemeToggle() {
|
||||
);
|
||||
}
|
||||
|
||||
/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정] ([관리자 메뉴]) [로그아웃] 메뉴. */
|
||||
/** 로그인한 뒤: 닉네임(디스코드 연결 시 디스코드 이름) → 누르면 [설정](팝업) ([관리자 메뉴]) [로그아웃] 메뉴. */
|
||||
function AccountMenu() {
|
||||
const me = useSession((s) => s.me)!;
|
||||
const role = useSession((s) => s.role);
|
||||
const nav = useNavigate();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [settings, setSettings] = useState(false);
|
||||
const closeSettings = useCallback(() => setSettings(false), []);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const btn = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -79,7 +87,7 @@ function AccountMenu() {
|
||||
|
||||
return (
|
||||
<div className="account-menu" ref={ref}>
|
||||
<button type="button" className="header-user" aria-haspopup="menu" aria-expanded={open} aria-label={`내 계정: ${me.nickname}`} onClick={() => setOpen((o) => !o)}>
|
||||
<button type="button" ref={btn} className="header-user" aria-haspopup="menu" aria-expanded={open} aria-label={`내 계정: ${me.nickname}`} onClick={() => setOpen((o) => !o)}>
|
||||
<Avatar user={me} size={36} />
|
||||
<span className="header-user-name">{me.nickname}</span>
|
||||
<span aria-hidden className="small muted">
|
||||
@@ -88,7 +96,8 @@ function AccountMenu() {
|
||||
</button>
|
||||
{open && (
|
||||
<div className="account-menu-list" role="menu" aria-label="내 계정">
|
||||
<button type="button" role="menuitem" onClick={() => (setOpen(false), nav('/me'))}>
|
||||
{/* A popup, not a page. The menu item is about to go away, so focus the account button first: the popup returns focus there. */}
|
||||
<button type="button" role="menuitem" aria-haspopup="dialog" onClick={() => (btn.current?.focus(), setOpen(false), setSettings(true))}>
|
||||
⚙️ 설정
|
||||
</button>
|
||||
{role !== 'user' && (
|
||||
@@ -101,6 +110,7 @@ function AccountMenu() {
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{settings && <SettingsPopup onClose={closeSettings} account />}
|
||||
{confirm && (
|
||||
<ConfirmSheet
|
||||
title="로그아웃할까요?"
|
||||
|
||||
84
apps/web/src/components/VolumeControl.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Site volume (top right of the site header and the room bar): a speaker button that opens a 0~100 slider.
|
||||
* Default 50 (the sounds play at half their old level). 0 or "소리 끄기" mutes everything. This device only.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { sfx } from '../lib/feedback';
|
||||
import { useSession } from '../store/session';
|
||||
|
||||
export function volumeIcon(sound: boolean, volume: number): string {
|
||||
if (!sound || volume <= 0) return '🔇';
|
||||
return volume < 34 ? '🔈' : volume < 67 ? '🔉' : '🔊';
|
||||
}
|
||||
|
||||
export function VolumeControl({ className = 'theme-toggle', label }: { className?: string; label?: boolean }) {
|
||||
const sound = useSession((s) => s.settings.sound);
|
||||
const volume = useSession((s) => s.settings.volume);
|
||||
const updateSettings = useSession((s) => s.updateSettings);
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: PointerEvent) => !ref.current?.contains(e.target as Node) && setOpen(false);
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && setOpen(false);
|
||||
document.addEventListener('pointerdown', onDown);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open]);
|
||||
const shown = sound ? volume : 0;
|
||||
const icon = volumeIcon(sound, volume);
|
||||
return (
|
||||
<div className="volume-control" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
className={className}
|
||||
aria-label={`소리 크기 ${shown}`}
|
||||
title={`소리 크기 ${shown}`}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
>
|
||||
{label ? (
|
||||
<>
|
||||
<span className="rb-ico">{icon}</span>
|
||||
<span className="rb-lbl">{shown}</span>
|
||||
</>
|
||||
) : (
|
||||
<span aria-hidden>{icon}</span>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="volume-pop" role="dialog" aria-label="소리 크기">
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<strong>소리 크기</strong>
|
||||
<output className="volume-num" aria-live="polite">
|
||||
{shown}
|
||||
</output>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={5}
|
||||
value={shown}
|
||||
aria-label="소리 크기 (0~100)"
|
||||
onChange={(e) => updateSettings({ volume: Number(e.target.value), sound: Number(e.target.value) > 0 })}
|
||||
onPointerUp={() => sfx.good()}
|
||||
onKeyUp={() => sfx.click()}
|
||||
/>
|
||||
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap', gap: 8 }}>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => updateSettings(sound && volume > 0 ? { sound: false } : { sound: true, volume: volume > 0 ? volume : 50 })}>
|
||||
{sound && volume > 0 ? '🔇 끄기' : '🔊 켜기'}
|
||||
</button>
|
||||
<button type="button" className="btn btn-ghost btn-sm" onClick={() => (updateSettings({ sound: true, volume: 50 }), sfx.good())}>
|
||||
기본(50)
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* Hwatu card drawn in SVG (our own simple artwork, no commercial hwatu images — docs/games/seotda.md §12).
|
||||
* Large month number + kind badge so the card is readable without knowing the pictures.
|
||||
* Hwatu card: the real 48-card hwatu artwork from Wikimedia Commons "SVG Hwatu" (Marcus Richert after Louie Mantia Jr.,
|
||||
* CC BY-SA 4.0 — ./hwatu/ATTRIBUTION.txt, docs/games/seotda.md "화투 그림"), bundled from our own origin (no external
|
||||
* URLs). A small month badge stays on top so beginners can read the card at a glance (섯다 instead draws a big outlined
|
||||
* number in the bottom-left corner, which stays visible when cards overlap);
|
||||
* 쌍피 / bonus cards get their value tag (고스톱). The back and the bonus cards are drawn here.
|
||||
*/
|
||||
import type { CSSProperties, ReactNode } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export interface HwatuInfo {
|
||||
id: number;
|
||||
@@ -13,172 +16,216 @@ export interface HwatuInfo {
|
||||
piValue?: number;
|
||||
}
|
||||
|
||||
const MONTH_COLOR = ['#6b7280', '#15803d', '#be185d', '#db2777', '#1f2937', '#7c3aed', '#dc2626', '#b91c1c', '#111827', '#ca8a04', '#c2410c', '#7c2d12', '#1e40af'];
|
||||
const MONTH_NAME = ['보너스', '송학', '매조', '벚꽃', '흑싸리', '난초', '모란', '홍싸리', '공산', '국화', '단풍', '오동', '비'];
|
||||
const KIND_BADGE: Record<HwatuInfo['kind'], string> = { gwang: '光', yeol: '열', tti: '띠', pi: '피', ssangpi: '쌍피', bonus: '+' };
|
||||
const TTI_COLOR = { hong: '#dc2626', cheong: '#2563eb', cho: '#15803d', plain: '#dc2626' };
|
||||
const TTI_TEXT = { hong: '홍단', cheong: '청단', cho: '', plain: '' };
|
||||
/** Attribution of the card artwork (CC BY-SA 4.0 asks for it); shown in the rules of the games that use these cards. */
|
||||
export const HWATU_CREDIT =
|
||||
'화투 그림: Marcus Richert(Louie Mantia, Jr.의 Hanafuda 그림 바탕), Spenĉjo — Wikimedia Commons "SVG Hwatu", CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/). 크기만 줄여 썼어요.';
|
||||
|
||||
/** A small motif per month (flowers/plants), drawn with basic shapes. */
|
||||
function Motif({ month, color }: { month: number; color: string }): ReactNode {
|
||||
const c = color;
|
||||
switch (month) {
|
||||
case 1: // 송학: pine
|
||||
return <path d="M50 52 L28 92 H72 Z M50 72 L22 116 H78 Z" fill={c} opacity="0.85" />;
|
||||
case 2: // 매조: plum blossoms
|
||||
case 3: // 벚꽃
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
{[[34, 70], [62, 62], [50, 92], [70, 100], [30, 108]].map(([x, y], i) => (
|
||||
<circle key={i} cx={x} cy={y} r="10" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 4: // 흑싸리
|
||||
case 7: // 홍싸리
|
||||
return (
|
||||
<g stroke={c} strokeWidth="5" strokeLinecap="round" opacity="0.85">
|
||||
{[30, 45, 60, 75].map((x, i) => (
|
||||
<line key={i} x1={x} y1="52" x2={x - 6} y2={100 + (i % 2) * 14} />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
case 5: // 난초: iris leaves
|
||||
return (
|
||||
<g fill="none" stroke={c} strokeWidth="5" opacity="0.85">
|
||||
<path d="M40 120 Q34 80 44 52" />
|
||||
<path d="M55 120 Q62 84 52 54" />
|
||||
<path d="M70 120 Q76 92 68 64" />
|
||||
</g>
|
||||
);
|
||||
case 6: // 모란: peony
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<circle cx="50" cy="86" r="22" />
|
||||
<circle cx="50" cy="86" r="10" fill="#fde68a" />
|
||||
</g>
|
||||
);
|
||||
case 8: // 공산: hill
|
||||
return <path d="M8 120 Q50 52 92 120 Z" fill={c} opacity="0.85" />;
|
||||
case 9: // 국화
|
||||
return (
|
||||
<g fill={c} opacity="0.9">
|
||||
{Array.from({ length: 10 }, (_, i) => {
|
||||
const a = (i / 10) * Math.PI * 2;
|
||||
return <ellipse key={i} cx={50 + Math.cos(a) * 14} cy={88 + Math.sin(a) * 14} rx="8" ry="4" transform={`rotate(${(a * 180) / Math.PI} ${50 + Math.cos(a) * 14} ${88 + Math.sin(a) * 14})`} />;
|
||||
})}
|
||||
<circle cx="50" cy="88" r="7" fill="#78350f" />
|
||||
</g>
|
||||
);
|
||||
case 10: // 단풍: maple
|
||||
return <path d="M50 58 L58 78 L78 74 L64 90 L74 108 L50 98 L26 108 L36 90 L22 74 L42 78 Z" fill={c} opacity="0.9" />;
|
||||
case 11: // 오동
|
||||
return (
|
||||
<g fill={c} opacity="0.85">
|
||||
<ellipse cx="38" cy="82" rx="16" ry="22" />
|
||||
<ellipse cx="64" cy="94" rx="16" ry="22" />
|
||||
</g>
|
||||
);
|
||||
case 12: // 비: rain lines + umbrella
|
||||
return (
|
||||
<g stroke={c} strokeWidth="3" opacity="0.85">
|
||||
{[20, 35, 50, 65, 80].map((x) => (
|
||||
<line key={x} x1={x} y1="54" x2={x - 8} y2="118" />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
default:
|
||||
return <text x="50" y="98" fontSize="36" textAnchor="middle" fill={c}>★</text>;
|
||||
}
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg' | 'xl';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84, xl: 108 };
|
||||
/** Height / width of the artwork (103.2 × 168.2). */
|
||||
export const HWATU_RATIO = 1.63;
|
||||
|
||||
/**
|
||||
* URL of a card face (ids 0..47). Vite turns this pattern into hashed /assets/ files (cached for good, also by the
|
||||
* service worker); in tests it is just a file URL.
|
||||
*/
|
||||
export const hwatuSrc = (id: number): string => new URL(`./hwatu/${id}.svg`, import.meta.url).href;
|
||||
|
||||
/** Card back: deep red lacquer with a thin gold frame, like a real hwatu back. */
|
||||
export function HwatuBack({ w, h }: { w: number; h: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<defs>
|
||||
<linearGradient id="hwb-g" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor="#c8102e" />
|
||||
<stop offset="1" stopColor="#8a0b1f" />
|
||||
</linearGradient>
|
||||
<pattern id="hwb-p" width="10" height="10" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
|
||||
<rect width="10" height="10" fill="none" />
|
||||
<path d="M0 5h10M5 0v10" stroke="#ffffff" strokeOpacity="0.07" strokeWidth="1.2" />
|
||||
</pattern>
|
||||
</defs>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-g)" stroke="#4a0510" strokeWidth="2" />
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="url(#hwb-p)" />
|
||||
<rect x="8" y="8" width="84" height="147" rx="4" fill="none" stroke="#f6c453" strokeOpacity="0.55" strokeWidth="1.5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export type HwatuSize = 'sm' | 'md' | 'lg';
|
||||
const WIDTH: Record<HwatuSize, number> = { sm: 40, md: 60, lg: 84 };
|
||||
function BonusFace({ w, h, value }: { w: number; h: number; value: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 100 163" width={w} height={h} aria-hidden style={{ display: 'block' }}>
|
||||
<rect x="1" y="1" width="98" height="161" rx="7" fill="#e3262b" />
|
||||
<rect x="7" y="7" width="86" height="149" rx="5" fill="#fffaf0" />
|
||||
<circle cx="50" cy="70" r="27" fill="#f6c453" stroke="#b45309" strokeWidth="3" />
|
||||
<text x="50" y="81" fontSize="30" fontWeight="900" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}
|
||||
</text>
|
||||
<text x="50" y="128" fontSize="20" fontWeight="900" fill="#b91c1c" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
보너스
|
||||
</text>
|
||||
<text x="50" y="148" fontSize="15" fontWeight="800" fill="#7c2d12" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{value}피
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/** Dark outline around white text (8 directions + soft shadow), readable on both the white and black parts of a card. */
|
||||
const cornerOutline = (t: number): string =>
|
||||
[
|
||||
[-t, -t], [0, -t], [t, -t], [-t, 0], [t, 0], [-t, t], [0, t], [t, t],
|
||||
]
|
||||
.map(([x, y]) => `${x}px ${y}px 0 #111827`)
|
||||
.concat('0 1px 3px rgba(0,0,0,0.6)')
|
||||
.join(', ');
|
||||
|
||||
export function HwatuCard({
|
||||
card,
|
||||
size = 'md',
|
||||
width,
|
||||
selected,
|
||||
dimmed,
|
||||
highlight,
|
||||
showMonth = true,
|
||||
monthStyle = 'badge',
|
||||
onClick,
|
||||
disabled,
|
||||
className,
|
||||
style,
|
||||
}: {
|
||||
card: HwatuInfo | null;
|
||||
size?: HwatuSize;
|
||||
/** Exact width in px (overrides `size`). */
|
||||
width?: number;
|
||||
selected?: boolean;
|
||||
dimmed?: boolean;
|
||||
highlight?: boolean;
|
||||
/** Small month number badge (on by default). */
|
||||
showMonth?: boolean;
|
||||
/** 'badge': small dark circle top-right. 'corner': big white outlined number bottom-left (섯다). */
|
||||
monthStyle?: 'badge' | 'corner';
|
||||
onClick?: () => void;
|
||||
/** Keeps the card a (disabled) button while it can't be clicked, so switching on/off doesn't remount it (no replayed deal animation). */
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}) {
|
||||
const w = WIDTH[size];
|
||||
const h = Math.round(w * 1.6);
|
||||
const w = width ?? WIDTH[size];
|
||||
const h = Math.round(w * HWATU_RATIO);
|
||||
const Tag = onClick ? 'button' : 'span';
|
||||
const radius = Math.max(3, Math.round(w * 0.07));
|
||||
const s: CSSProperties = {
|
||||
position: 'relative',
|
||||
width: w,
|
||||
height: h,
|
||||
flex: 'none',
|
||||
display: 'inline-block',
|
||||
padding: 0,
|
||||
border: 0,
|
||||
borderRadius: radius,
|
||||
background: 'none',
|
||||
cursor: onClick ? 'pointer' : 'default',
|
||||
cursor: onClick && !disabled ? 'pointer' : 'default',
|
||||
opacity: dimmed ? 0.45 : 1,
|
||||
transform: selected ? `translateY(${-Math.round(w * 0.2)}px)` : undefined,
|
||||
transition: 'transform 0.12s ease',
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))',
|
||||
boxShadow: selected ? '0 0 0 3px #2563eb' : undefined,
|
||||
filter: highlight ? 'drop-shadow(0 0 6px #f59e0b)' : 'drop-shadow(0 1px 2px rgba(0,0,0,0.35))',
|
||||
verticalAlign: 'bottom',
|
||||
...style,
|
||||
};
|
||||
if (!card) {
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투">
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#991b1b" stroke="#450a0a" strokeWidth="3" />
|
||||
<rect x="10" y="10" width="80" height="140" rx="5" fill="#b91c1c" />
|
||||
</svg>
|
||||
<Tag style={s} onClick={onClick} aria-label="뒤집힌 화투" className={className}>
|
||||
<HwatuBack w={w} h={h} />
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
const color = MONTH_COLOR[card.month] ?? '#374151';
|
||||
const badge = Math.max(12, Math.round(w * 0.24));
|
||||
// 고스톱 passes 쌍피 as kind 'pi' with piValue 2.
|
||||
const tag = card.kind === 'ssangpi' || (card.kind === 'pi' && (card.piValue ?? 1) >= 2) ? '쌍피' : null;
|
||||
return (
|
||||
<Tag style={s} onClick={onClick} aria-label={card.name} aria-pressed={onClick ? !!selected : undefined} title={card.name}>
|
||||
<svg viewBox="0 0 100 160" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="158" rx="8" fill="#fffaf0" stroke={selected ? '#2563eb' : '#1f2937'} strokeWidth={selected ? 6 : 3} />
|
||||
{card.kind === 'bonus' ? (
|
||||
<text x="50" y="102" fontSize="34" fontWeight="900" fill="#b45309" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.piValue ?? 2}피
|
||||
</text>
|
||||
) : (
|
||||
<Motif month={card.month} color={color} />
|
||||
)}
|
||||
{card.kind === 'tti' && (
|
||||
<g>
|
||||
<rect x="58" y="30" width="18" height="90" rx="3" fill={TTI_COLOR[card.tti ?? 'plain']} />
|
||||
{TTI_TEXT[card.tti ?? 'plain'] && (
|
||||
<text x="67" y="62" fontSize="13" fontWeight="800" fill="#fff" textAnchor="middle" style={{ writingMode: 'vertical-rl' } as CSSProperties}>
|
||||
{TTI_TEXT[card.tti ?? 'plain']}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{(card.kind === 'gwang' || card.kind === 'yeol') && (
|
||||
<g>
|
||||
<circle cx="78" cy="120" r="15" fill={card.kind === 'gwang' ? '#dc2626' : '#a16207'} />
|
||||
<text x="78" y="127" fontSize={card.kind === 'gwang' ? 20 : 16} fontWeight="800" fill="#fff" textAnchor="middle">
|
||||
{card.kind === 'gwang' ? '光' : '열'}
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{/* Month number: large and always readable */}
|
||||
<rect x="6" y="6" width="38" height="38" rx="8" fill={color} />
|
||||
<text x="25" y="35" fontSize="28" fontWeight="900" fill="#fff" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{card.month || '+'}
|
||||
</text>
|
||||
<text x="50" y="154" fontSize="13" fontWeight="700" fill="#374151" textAnchor="middle" fontFamily="Pretendard Variable, sans-serif">
|
||||
{MONTH_NAME[card.month]} · {card.kind === 'bonus' ? `${card.piValue ?? 2}피` : card.kind === 'tti' ? (TTI_TEXT[card.tti ?? 'plain'] || '띠') : KIND_BADGE[card.kind] === '光' ? '광' : KIND_BADGE[card.kind] === '열' ? '열끗' : KIND_BADGE[card.kind]}
|
||||
</text>
|
||||
</svg>
|
||||
<Tag
|
||||
style={s}
|
||||
onClick={onClick}
|
||||
disabled={onClick ? disabled : undefined}
|
||||
aria-label={card.name}
|
||||
aria-pressed={onClick && !disabled ? !!selected : undefined}
|
||||
title={card.name}
|
||||
className={className}
|
||||
>
|
||||
{card.kind === 'bonus' || card.id >= 48 ? (
|
||||
<BonusFace w={w} h={h} value={card.piValue ?? 2} />
|
||||
) : (
|
||||
<img src={hwatuSrc(card.id)} alt="" draggable={false} width={w} height={h} decoding="async" style={{ display: 'block', width: w, height: h, borderRadius: radius }} />
|
||||
)}
|
||||
{showMonth && card.month > 0 && monthStyle === 'corner' && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: Math.round(w * 0.08),
|
||||
bottom: Math.round(w * 0.06),
|
||||
color: '#fff',
|
||||
fontSize: Math.max(12, Math.round(8 + w * 0.26)),
|
||||
fontWeight: 900,
|
||||
lineHeight: 1,
|
||||
letterSpacing: '-0.04em',
|
||||
textShadow: cornerOutline(Math.max(1, Math.round(w * 0.025))),
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{card.month}
|
||||
</span>
|
||||
)}
|
||||
{showMonth && card.month > 0 && monthStyle === 'badge' && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: Math.round(w * 0.05),
|
||||
right: Math.round(w * 0.05),
|
||||
minWidth: badge,
|
||||
height: badge,
|
||||
padding: '0 2px',
|
||||
borderRadius: badge,
|
||||
background: 'rgba(17,24,39,0.82)',
|
||||
color: '#fff',
|
||||
fontSize: Math.max(9, Math.round(badge * 0.66)),
|
||||
fontWeight: 800,
|
||||
lineHeight: `${badge}px`,
|
||||
textAlign: 'center',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{card.month}
|
||||
</span>
|
||||
)}
|
||||
{tag && (
|
||||
<span
|
||||
aria-hidden
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: '50%',
|
||||
bottom: Math.round(w * 0.06),
|
||||
transform: 'translateX(-50%)',
|
||||
padding: '0 4px',
|
||||
borderRadius: 4,
|
||||
background: '#f6c453',
|
||||
color: '#7c2d12',
|
||||
fontSize: Math.max(9, Math.round(w * 0.2)),
|
||||
fontWeight: 900,
|
||||
lineHeight: 1.25,
|
||||
whiteSpace: 'nowrap',
|
||||
fontFamily: 'Pretendard Variable, sans-serif',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
)}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
/** Trump card drawn in SVG (no image assets). Big corner index for readability on PC and phones. */
|
||||
/**
|
||||
* Trump card drawn in SVG. Big corner index for readability on PC and phones. Number cards and the back are drawn here;
|
||||
* J/Q/K and the two jokers show real card artwork by Dmitry Fomin (Wikimedia Commons, CC0 — ./court/ATTRIBUTION.txt),
|
||||
* bundled from our own origin as small WebP files that load only when such a card is on screen.
|
||||
*/
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
/** Credit for the court/joker artwork (CC0 needs none, but we say thanks); shown in the rules of the games using these cards. */
|
||||
export const PLAYING_CARD_CREDIT =
|
||||
'트럼프 그림카드(J·Q·K)·조커 그림: Dmitry Fomin — Wikimedia Commons "SVG English pattern playing cards", "Atlas deck joker", CC0 1.0(퍼블릭 도메인). 그림 부분만 잘라 작게 줄여 썼어요.';
|
||||
|
||||
/**
|
||||
* URL of the court/joker picture ("JS".."KC", "X1" black joker, "X2" red joker). Vite turns this pattern into hashed
|
||||
* /assets/ files; in tests it is just a file URL.
|
||||
*/
|
||||
export const courtSrc = (id: string): string => new URL(`./court/${id}.webp`, import.meta.url).href;
|
||||
|
||||
const SUIT_SYMBOL: Record<string, string> = { S: '♠', H: '♥', D: '◆', C: '♣' };
|
||||
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
|
||||
const RANK_LABEL: Record<string, string> = { T: '10', J: 'J', Q: 'Q', K: 'K', A: 'A' };
|
||||
@@ -13,6 +27,8 @@ export interface PlayingCardProps {
|
||||
/** e.g. "AS", "TD", "X1" (joker). null = face down. */
|
||||
card: string | null;
|
||||
size?: CardSize;
|
||||
/** Exact width in px (overrides `size`). */
|
||||
width?: number;
|
||||
selected?: boolean;
|
||||
dimmed?: boolean;
|
||||
highlight?: boolean;
|
||||
@@ -30,8 +46,8 @@ export function cardAria(card: string | null): string {
|
||||
return `${SUIT_KO[card[1]!]} ${FACE_KO[r] ?? RANK_LABEL[r] ?? r}`;
|
||||
}
|
||||
|
||||
export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
|
||||
const w = WIDTH[size];
|
||||
export function PlayingCard({ card, size = 'md', width, selected, dimmed, highlight, onClick, title, style, fourColor }: PlayingCardProps) {
|
||||
const w = width ?? WIDTH[size];
|
||||
const h = Math.round(w * 1.4);
|
||||
const lift = selected ? -Math.round(w * 0.22) : 0;
|
||||
const common: CSSProperties = {
|
||||
@@ -74,28 +90,26 @@ export function PlayingCard({ card, size = 'md', selected, dimmed, highlight, on
|
||||
<Tag style={{ ...common, ...btnReset }} onClick={onClick} aria-label={title ?? cardAria(card)} aria-pressed={onClick ? !!selected : undefined} title={title}>
|
||||
<svg viewBox="0 0 100 140" width={w} height={h} aria-hidden>
|
||||
<rect x="1" y="1" width="98" height="138" rx="9" fill="#fffef9" stroke={selected ? '#2563eb' : '#9ca3af'} strokeWidth={selected ? 5 : 2} />
|
||||
<text x="9" y="33" fontSize="30" fontWeight="800" fill={color} fontFamily="Pretendard Variable, sans-serif">
|
||||
{label}
|
||||
</text>
|
||||
<text x="11" y="60" fontSize="26" fill={color}>
|
||||
{sym}
|
||||
</text>
|
||||
{joker ? (
|
||||
<text x="50" y="98" fontSize="22" fontWeight="800" textAnchor="middle" fill={color}>
|
||||
JOKER
|
||||
</text>
|
||||
<image href={courtSrc(card === 'X1' ? 'X1' : 'X2')} x="22" y="30" width="72" height="104" preserveAspectRatio="xMidYMid meet" />
|
||||
) : 'JQK'.includes(rank) ? (
|
||||
<>
|
||||
<rect x="30" y="44" width="56" height="78" rx="6" fill={color} opacity="0.1" />
|
||||
<text x="58" y="100" fontSize="44" fontWeight="800" textAnchor="middle" fill={color}>
|
||||
{rank}
|
||||
</text>
|
||||
{/* picture frame like a real court card, with a notch at top-left so the big index stays readable */}
|
||||
<image href={courtSrc(rank + suit)} x="10" y="5" width="80" height="130" preserveAspectRatio="xMidYMid slice" />
|
||||
<path d="M10 5H36V65H10Z" fill="#fffef9" />
|
||||
<path d="M36 5H90V135H10V65H36Z" fill="none" stroke={color} strokeOpacity="0.55" strokeWidth="1.2" />
|
||||
</>
|
||||
) : (
|
||||
<text x="60" y="108" fontSize="54" textAnchor="middle" fill={color}>
|
||||
{sym}
|
||||
</text>
|
||||
)}
|
||||
<text x="9" y="33" fontSize="30" fontWeight="800" fill={color} fontFamily="Pretendard Variable, sans-serif">
|
||||
{label}
|
||||
</text>
|
||||
<text x="11" y="60" fontSize="26" fill={color}>
|
||||
{sym}
|
||||
</text>
|
||||
</svg>
|
||||
</Tag>
|
||||
);
|
||||
|
||||
21
apps/web/src/components/cards/court/ATTRIBUTION.txt
Normal file
@@ -0,0 +1,21 @@
|
||||
트럼프 그림카드·조커 그림 출처 (Playing card court and joker artwork)
|
||||
|
||||
JS JH JD JC / QS QH QD QC / KS KH KD KC .webp (J·Q·K 12장, 파일 이름 = 게임 엔진의 카드 id, 랭크+무늬)
|
||||
|
||||
- 원본: Wikimedia Commons "Category:SVG English pattern playing cards"
|
||||
https://commons.wikimedia.org/wiki/Category:SVG_English_pattern_playing_cards
|
||||
File:English pattern jack of spades.svg ~ File:English pattern king of clubs.svg (2026-10-13 받음)
|
||||
- 만든 사람: Dmitry Fomin (Дмитрий Фомин), https://commons.wikimedia.org/wiki/User:Dmitry_Fomin
|
||||
- 라이선스: CC0 1.0 (퍼블릭 도메인 헌정, https://creativecommons.org/publicdomain/zero/1.0/)
|
||||
|
||||
X1.webp (검은 조커), X2.webp (빨간 조커)
|
||||
|
||||
- 원본: Wikimedia Commons
|
||||
https://commons.wikimedia.org/wiki/File:Atlas_deck_joker_black.svg
|
||||
https://commons.wikimedia.org/wiki/File:Atlas_deck_joker_red.svg (2026-10-13 받음)
|
||||
- 만든 사람: Dmitry Fomin (Дмитрий Фомин)
|
||||
- 라이선스: CC0 1.0
|
||||
|
||||
바꾼 점: 원본 SVG(360×540)를 4배로 그린 뒤 그림카드는 파란 테두리 안쪽 그림만, 조커는 광대 그림만 잘라
|
||||
(모서리 글자·러시아어 "ДЖОКЕР" 글자는 뺌) 높이 282px WebP(품질 80)로 줄이고, 흰 바탕을 카드 종이색(#fffef9)으로 칠했다.
|
||||
CC0이라 출처 표시 의무는 없지만 고마움의 뜻으로 적어 둔다. 숫자 카드·뒷면·모서리 글자는 PlayingCard.tsx 가 직접 그린다.
|
||||
BIN
apps/web/src/components/cards/court/JC.webp
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
apps/web/src/components/cards/court/JD.webp
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/src/components/cards/court/JH.webp
Normal file
|
After Width: | Height: | Size: 22 KiB |
BIN
apps/web/src/components/cards/court/JS.webp
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
apps/web/src/components/cards/court/KC.webp
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/src/components/cards/court/KD.webp
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/src/components/cards/court/KH.webp
Normal file
|
After Width: | Height: | Size: 21 KiB |
BIN
apps/web/src/components/cards/court/KS.webp
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
apps/web/src/components/cards/court/QC.webp
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
apps/web/src/components/cards/court/QD.webp
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
apps/web/src/components/cards/court/QH.webp
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
apps/web/src/components/cards/court/QS.webp
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
apps/web/src/components/cards/court/X1.webp
Normal file
|
After Width: | Height: | Size: 6.8 KiB |
BIN
apps/web/src/components/cards/court/X2.webp
Normal file
|
After Width: | Height: | Size: 8.1 KiB |
1
apps/web/src/components/cards/hwatu/0.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/1.svg
Normal file
|
After Width: | Height: | Size: 19 KiB |
1
apps/web/src/components/cards/hwatu/10.svg
Normal file
|
After Width: | Height: | Size: 51 KiB |
1
apps/web/src/components/cards/hwatu/11.svg
Normal file
|
After Width: | Height: | Size: 56 KiB |
1
apps/web/src/components/cards/hwatu/12.svg
Normal file
|
After Width: | Height: | Size: 34 KiB |
1
apps/web/src/components/cards/hwatu/13.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/14.svg
Normal file
|
After Width: | Height: | Size: 26 KiB |
1
apps/web/src/components/cards/hwatu/15.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/16.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/17.svg
Normal file
|
After Width: | Height: | Size: 21 KiB |
1
apps/web/src/components/cards/hwatu/18.svg
Normal file
|
After Width: | Height: | Size: 18 KiB |
1
apps/web/src/components/cards/hwatu/19.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/2.svg
Normal file
|
After Width: | Height: | Size: 12 KiB |
1
apps/web/src/components/cards/hwatu/20.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/21.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/22.svg
Normal file
|
After Width: | Height: | Size: 29 KiB |
1
apps/web/src/components/cards/hwatu/23.svg
Normal file
|
After Width: | Height: | Size: 23 KiB |
1
apps/web/src/components/cards/hwatu/24.svg
Normal file
|
After Width: | Height: | Size: 54 KiB |
1
apps/web/src/components/cards/hwatu/25.svg
Normal file
|
After Width: | Height: | Size: 27 KiB |
1
apps/web/src/components/cards/hwatu/26.svg
Normal file
|
After Width: | Height: | Size: 24 KiB |
1
apps/web/src/components/cards/hwatu/27.svg
Normal file
|
After Width: | Height: | Size: 20 KiB |
1
apps/web/src/components/cards/hwatu/28.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m3.3 3.15c-.17 10.85 1.3 101.25 1.3 101.25l94.7 9.5 1.25-110.75c-32.28.58-64.87-1.85-97.25 0zm46.45 19c18.68-.54 33.23 16.56 33.23 31.59 0 21.84-16.42 34.31-33.38 34.31-14.18 0-32.68-12.1-32.68-32.42 0-16.47 11.61-32.87 32.83-33.48z" fill="#ef1d1e"/><path d="m48.05 21.45c-8.53.4-15.92 3.75-22.15 10.05-6.6 6.67-9.78 14.78-9.55 24.35.37 11.97 5.65 21.23 15.85 27.8 6.37 4.07 13.38 5.7 21.05 4.9 9.1-.97 16.6-4.95 22.5-11.95 5.73-6.77 8.32-14.82 7.75-24.15-.5-8.27-3.9-15.47-10.2-21.6-6.9-6.7-15.32-9.83-25.25-9.4zm.92 1.21c6.93-.28 13.46 1.72 19.58 5.99 6.2 4.33 10.35 10.15 12.45 17.45 2.8 9.93 1.22 19.15-4.75 27.65-2.9 4.13-6.42 7.37-10.55 9.7-3.97 2.23-8.35 3.55-13.15 3.95-8.4.3-15.68-1.82-21.85-6.35-5.63-4.17-9.48-9.43-11.55-15.8-2.87-9.07-2.08-17.63 2.35-25.7h.05l.05-.05c4.57-8.23 11.33-13.5 20.3-15.8 2.4-.6 4.76-.95 7.07-1.04zm-8.22 70.09c-2.53.27-4.43.43-5.7.5-.6 0-1.35.08-2.25.25-.97.17-1.7.28-2.2.35-.17.03-1.22.23-3.15.6-2.37.57-3.83.93-4.4 1.1l-6.5 2.25c-.8.27-1.9.72-3.3 1.35-1.5.67-2.62 1.13-3.35 1.4-2.03.73-3.97 1.77-5.8 3.1l-.82 59.4 95.11 1.07-.89-52.96c-1-.87-2.92-2.22-5.75-4.05-2.03-1.33-4.47-2.8-7.3-4.4-1.93-1.1-4.67-2.38-8.2-3.85-3.03-1.1-5.3-1.93-6.8-2.5-2.13-.77-5.77-1.65-10.9-2.65-.43-.07-2.75-.28-6.95-.65l-2.75-.2c-.47 0-1.13-.03-2-.1l-3.1.05c-1.33-.07-2.33-.08-3-.05z"/><g transform="translate(479.2 -235.55)"><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="#ef1d1e"/><path transform="translate(-848.6,2.2)" d="m397.62 356.15c-.52.06-.91.55-1.17 1.45-.3 1-.3 2.55 0 4.65.03.93.05 1.82.05 2.65-.03.97-.1 1.85-.2 2.65-.73.23-1.38.47-1.95.7-2.07.83-3.1 1.65-3.1 2.45v.25l.15.4h.4c.03 0 1.67-.4 4.9-1.2-.27.9-.85 1.93-1.75 3.1-.83 1.1-1.58 1.97-2.25 2.6-.7.67-1.15 1.12-1.35 1.35-.13.2-.52.55-1.15 1.05-.6.47-1.18.82-1.75 1.05-.6.23-.9.48-.9.75 0 .17.13.35.4.55.27.17.6.25 1 .25.97 0 2.25-.8 3.85-2.4 1.6-1.63 2.65-2.78 3.15-3.45s1.1-1.62 1.8-2.85c.67-1.23 1.15-2.1 1.45-2.6v-.05c.06 0 .11-.02.15-.05-.04.04-.09.07-.15.1.07 1.03.13 2 .2 2.9l-.35 5.5c0 1.33.38 2.27 1.15 2.8.73.5 2.27.78 4.6.85 2.3.13 4.07-.32 5.3-1.35 1.33-1.07 1.93-2.18 1.8-3.35-.07-1.13-.35-1.95-.85-2.45s-.92-.82-1.25-.95c-.4-.07-.78.48-1.15 1.65-.43 1.13-.92 1.82-1.45 2.05-.57.2-1.37.4-2.4.6-1.07.3-1.73.45-2 .45-1 0-1.52-1.07-1.55-3.2.07-2.1.1-3.2.1-3.3 0-.97-.02-1.55-.05-1.75-.13-.3-.37-.6-.7-.9 2.83-1 4.25-1.88 4.25-2.65 0-.53-.2-.87-.6-1-.17-.1-.58-.15-1.25-.15-.6 0-1.22.15-1.85.45-1.1.47-1.9.8-2.4 1-.07-.33-.1-.77-.1-1.3 0-.83.08-1.77.25-2.8 0-.2.02-.42.05-.65.17-1.3.25-2.32.25-3.05s-.02-1.23-.05-1.5c-.23-.87-.67-1.3-1.3-1.3-.08-.01-.16-.01-.23 0zm5.73 1.75c-.6.47-1.38 1.22-2.35 2.25-.97 1.03-1.45 1.9-1.45 2.6 0 .67.02 1.02.05 1.05.07.07.1.12.1.15.13.1.23.15.3.15.33 0 1.27-.55 2.8-1.65 1.63-1.2 2.45-2.05 2.45-2.55 0-.43-.2-.87-.6-1.3-.4-.47-.83-.7-1.3-.7zm-12.5 4.6c-.3 0-.55.18-.75.55-.13.33-.2.65-.2.95 0 .83.17 1.45.5 1.85.3.3.77.48 1.4.55.2.03.43.05.7.05.2-.03.43-.08.7-.15.1-.03.22-.1.35-.2.83-.33 1.25-.75 1.25-1.25 0-.43-.15-.72-.45-.85-.17-.07-.62-.17-1.35-.3-.6-.07-1.02-.3-1.25-.7-.27-.33-.57-.5-.9-.5z" fill="#fff"/><path transform="translate(-848.6,2.2)" d="m399.45 353.05c-4.87 0-9.02 1.72-12.45 5.15-3.4 3.43-5.1 7.58-5.1 12.45s1.7 9.02 5.1 12.45c3.43 3.43 7.58 5.15 12.45 5.15s9.02-1.72 12.45-5.15 5.15-7.58 5.15-12.45-1.72-9.02-5.15-12.45-7.58-5.15-12.45-5.15z" fill="none" stroke="#000"/></g><g transform="translate(-447.2 -373.75)"><path transform="translate(160.15,84.1)" d="m292.05 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m300.35 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
1
apps/web/src/components/cards/hwatu/29.svg
Normal file
|
After Width: | Height: | Size: 28 KiB |
1
apps/web/src/components/cards/hwatu/3.svg
Normal file
|
After Width: | Height: | Size: 10 KiB |
1
apps/web/src/components/cards/hwatu/30.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m41.15 88.75c-1.6.07-3.2.22-4.8.45-3.07.4-5.35.75-6.85 1.05-3.43.7-5.65 1.18-6.65 1.45-1.5.4-3.72 1.13-6.65 2.2-3.9 1.43-6.35 2.42-7.35 2.95-1.63.7-2.83 1.27-3.6 1.7l-1.7 67.5c.46.42 97.25 0 97.25 0l-3.7-59.55c-1.87-1.67-3.3-2.87-4.3-3.6-1.07-.77-2.7-1.82-4.9-3.15-2.3-1.3-4.32-2.38-6.05-3.25-1.27-.6-3.47-1.5-6.6-2.7-1.9-.73-3.6-1.3-5.1-1.7-2.2-.47-3.85-.83-4.95-1.1-2.73-.6-4.8-.98-6.2-1.15l-3.75-.55c-2.5-.23-4-.37-4.5-.4-2.17.1-3.78.07-4.85-.1-.87-.1-2.45-.12-4.75-.05z"/><g transform="translate(-555.75,-373.75)"><path transform="translate(160.15,84.1)" d="m400.6 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m408.9 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
1
apps/web/src/components/cards/hwatu/31.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg width="103.2" height="168.2" preserveAspectRatio="none" version="1.1" viewBox="0 0 103.2 168.2" xmlns="http://www.w3.org/2000/svg"><path d="m13.3 7.2c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="#fff"/><path d="m46.2 81.65c-1.8 0-3.35.07-4.65.2-3.77.33-6.58.62-8.45.85-2.53.27-4.38.53-5.55.8-2.33.5-4.7 1.1-7.1 1.8-2.57.7-4.72 1.4-6.45 2.1-.37.17-2.32 1.1-5.85 2.8-1.93 1.07-3.32 1.97-4.15 2.7l-.6 73.15h97.25l-1.55-67.2c-1.27-1.1-2.14-1.82-2.6-2.15-.1-.07-.2-.11-.3-.18-.36-.28-.5-.48-.9-.77-.53-.4-2.22-1.48-5.05-3.25-1.93-1.2-4.27-2.4-7-3.6-1.33-.6-3.58-1.47-6.75-2.6-1.97-.77-3.3-1.23-4-1.4-2.77-.6-4.85-1.08-6.25-1.45-.4-.13-1.02-.22-1.85-.25-.87-.03-1.48-.1-1.85-.2-.8-.23-1.77-.42-2.9-.55-1.27-.13-2.23-.25-2.9-.35-2.13-.27-4.12-.4-5.95-.4-2.07-.03-3.6-.05-4.6-.05z"/><g transform="translate(-773.5,-373.75)"><path transform="translate(160.15,84.1)" d="m618.35 289.65c-3.33 0-5 1.67-5 5v158.2c0 3.33 1.67 5 5 5h93.2c3.33 0 5-1.67 5-5v-158.2c0-3.33-1.67-5-5-5zm8.3 7.2h76.6c4.67 0 7 2.33 7 7v139.8c0 4.67-2.33 7-7 7h-76.6c-4.67 0-7-2.33-7-7v-139.8c0-4.67 2.33-7 7-7z" fill="#ef1d1e"/><path transform="translate(160.15,84.1)" d="m626.65 296.85c-4.67 0-7 2.33-7 7v139.8c0 4.67 2.33 7 7 7h76.6c4.67 0 7-2.33 7-7v-139.8c0-4.67-2.33-7-7-7z" fill="none" stroke="#000" stroke-width="1.2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
apps/web/src/components/cards/hwatu/32.svg
Normal file
|
After Width: | Height: | Size: 50 KiB |
1
apps/web/src/components/cards/hwatu/33.svg
Normal file
|
After Width: | Height: | Size: 37 KiB |
1
apps/web/src/components/cards/hwatu/34.svg
Normal file
|
After Width: | Height: | Size: 35 KiB |