컴퓨터 난이도 1~60단계·방장 선택·판마다 변화·운, 공정성 확인에 표기, 업데이트 알림 팝업
- 난이도 1~60(쉬움 1~20·보통 21~40·어려움 41~60): 넣을 때 랜덤, 방장이 대기실에서 [랜덤][쉬움][보통][어려움] 선택(botLevel) → 범위 안 무작위 - 다음 판마다 -2~+2, 처음 단계 ±5·같은 범위 안(drift); 말투는 처음 단계(>30 존댓말) - humanBest 확률을 단계별로 보간(BOT_PLAY_ANCHORS: 1·10·30·50·60) - 운(-1~+1): 카드·주사위 게임에서 시작 전에 시드 후보 1~5개를 작업 스레드에서 끝까지 둬 보고 운에 맞는 것을 고름(luck.ts, luck-worker.ts). 해시 공개는 그대로 - 결과 화면 공정성 확인에 컴퓨터별 단계·운, 섞어 본 후보 수 - 업데이트 알림: 빌드 ID meta + /api/version + welcome.build → 상단 팝업 [지금 새로고침하기] [✕] - 문서 03·04 §5.1·06 §12·07 §11.1·09 §9.1, 테스트(bot-level.room, luck, version, e2e bots·pwa) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,6 +29,8 @@ 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;
|
||||
now(): number;
|
||||
}
|
||||
|
||||
@@ -90,6 +92,7 @@ export class BotBrain {
|
||||
return {
|
||||
bot,
|
||||
name: this.room.nameOf(bot),
|
||||
smart: this.room.smart(bot),
|
||||
game: this.room.gameName(),
|
||||
situation,
|
||||
task,
|
||||
@@ -175,6 +178,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'] },
|
||||
@@ -243,6 +247,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,16 +27,17 @@ 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나 프로그램이라고 말하지 않는다. 숨겨진 정보(내 패, 내 카드, 내 직업)는 절대 밝히지 않는다.',
|
||||
@@ -46,6 +47,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;
|
||||
@@ -99,7 +102,7 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
|
||||
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 });
|
||||
@@ -107,11 +110,11 @@ export async function writeLine(llm: Llm | null, req: LineRequest): Promise<stri
|
||||
}
|
||||
|
||||
/** 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 },
|
||||
|
||||
@@ -16,6 +16,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 +78,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);
|
||||
|
||||
238
apps/server/src/rooms/bot-level.room.test.ts
Normal file
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
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 };
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
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, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots';
|
||||
|
||||
import type { BotBrain } from '../ai/brain';
|
||||
|
||||
@@ -23,6 +23,8 @@ 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;
|
||||
}
|
||||
@@ -157,7 +159,7 @@ 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 });
|
||||
decision = strategy({ me: bot, view: structuredClone(def.view(g.state, bot)), now, random: this.random, persona: botPersona(bot, this.room.profile?.(bot).base), names, memory });
|
||||
} catch (err) {
|
||||
this.room.log?.('error', 'bot decision failed', { game: def.id, err: String(err) });
|
||||
}
|
||||
@@ -247,7 +249,7 @@ export class BotDriver {
|
||||
const t0 = performance.now();
|
||||
let action: unknown;
|
||||
try {
|
||||
action = decideBotAction(def, g.state, next.bot, { now: this.room.now(), random: this.random, level: botPersona(next.bot).level });
|
||||
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;
|
||||
|
||||
18
apps/server/src/rooms/luck-worker.ts
Normal file
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
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
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());
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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, secureRandom, 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 { 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 { 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';
|
||||
@@ -54,6 +57,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 +77,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,9 +100,16 @@ 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;
|
||||
@@ -117,6 +133,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). */
|
||||
@@ -166,6 +188,7 @@ 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,
|
||||
now: this.now,
|
||||
},
|
||||
deps.ai ?? null,
|
||||
@@ -191,6 +214,7 @@ export class Room {
|
||||
},
|
||||
log: deps.log,
|
||||
nameOf: (id) => this.deps.users.publicUser(id)?.nickname ?? '누군가',
|
||||
profile: (bot) => this.profile(bot),
|
||||
brain: this.brain,
|
||||
},
|
||||
secureRandom,
|
||||
@@ -289,6 +313,7 @@ export class Room {
|
||||
lastResult: this.lastResult,
|
||||
game: this.game,
|
||||
joinedAt,
|
||||
bots: this.botProfiles,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,6 +328,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).
|
||||
@@ -396,6 +422,10 @@ 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 } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -574,9 +604,15 @@ 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. */
|
||||
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;
|
||||
@@ -712,9 +748,10 @@ export class Room {
|
||||
const used = new Set(this.seatedIds().map(botNumber));
|
||||
let n = 1;
|
||||
while (used.has(n)) n++;
|
||||
// The id's random part is the computer's level roll (`botDraw`): uniform OS randomness.
|
||||
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();
|
||||
@@ -729,11 +766,24 @@ 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 '방에 들어와야 채팅할 수 있어요.';
|
||||
@@ -781,17 +831,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();
|
||||
@@ -805,7 +856,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);
|
||||
@@ -814,22 +866,75 @@ 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();
|
||||
return { options: 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,
|
||||
@@ -843,6 +948,7 @@ export class Room {
|
||||
players,
|
||||
finished: false,
|
||||
deadlineFloor: null,
|
||||
...(Object.keys(bots).length ? { bots, shuffles: picked?.tried ?? 1 } : {}),
|
||||
};
|
||||
this.status = 'playing';
|
||||
this.rematchVotes.clear();
|
||||
@@ -1074,6 +1180,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);
|
||||
}
|
||||
@@ -1087,6 +1194,7 @@ export class Room {
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
this.closed = true;
|
||||
this.flushStream();
|
||||
this.clearTimer();
|
||||
for (const c of this.conns.values()) {
|
||||
|
||||
@@ -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,6 +11,7 @@ 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';
|
||||
@@ -38,6 +39,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) {
|
||||
@@ -60,10 +63,21 @@ export function startServer(opts: StartOptions) {
|
||||
// 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 });
|
||||
const removeGuest = (id: string) => {
|
||||
rooms.leaveAll(id);
|
||||
gateway.closeUser(id);
|
||||
@@ -85,8 +99,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,
|
||||
@@ -121,8 +140,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 +188,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 +198,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
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 });
|
||||
});
|
||||
@@ -21,6 +21,8 @@ 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;
|
||||
}
|
||||
|
||||
export const MAX_CONNS_PER_USER = 5;
|
||||
@@ -84,6 +86,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,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -193,6 +196,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;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useToasts, toast } from '../store/toast';
|
||||
import { useRoom } from '../net/socket';
|
||||
import { haptic } from '../lib/feedback';
|
||||
import { useOnline } from '../lib/pwa';
|
||||
import { dismissUpdate, useUpdateAvailable } from '../lib/update';
|
||||
|
||||
const AVATAR_COLORS = ['#2563eb', '#db2777', '#16a34a', '#ea580c', '#7c3aed', '#0891b2', '#ca8a04', '#dc2626'];
|
||||
|
||||
@@ -146,6 +147,23 @@ export function ConnectionBanner() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The site was updated while this page was open (docs/07 §11.1): refresh, or ✕ to close until the next update. */
|
||||
export function UpdateBanner() {
|
||||
const show = useUpdateAvailable();
|
||||
if (!show) return null;
|
||||
return (
|
||||
<div className="update-banner" role="alert">
|
||||
<span className="update-text">업데이트 내용이 있습니다.</span>
|
||||
<button type="button" className="btn btn-primary btn-sm" onClick={() => location.reload()}>
|
||||
지금 새로고침하기
|
||||
</button>
|
||||
<button type="button" className="update-close" onClick={dismissUpdate} aria-label="업데이트 알림 닫기">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CodeLabel({ code }: { code: string }) {
|
||||
return <span style={{ fontVariantNumeric: 'tabular-nums', letterSpacing: '0.08em' }}>{formatRoomCode(code)}</span>;
|
||||
}
|
||||
|
||||
61
apps/web/src/lib/update.ts
Normal file
61
apps/web/src/lib/update.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* "업데이트 내용이 있습니다" (docs/07 §11.1). The page knows its own build (`<meta name="bg-build">`, written by
|
||||
* vite.config.ts); the server tells its build in `welcome` and at `/api/version`. When they differ the page offers a
|
||||
* refresh at the top; ✕ hides it until the next update. Dev builds have no meta and never ask.
|
||||
*/
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
const POLL_MS = 5 * 60_000;
|
||||
|
||||
const mine = typeof document === 'undefined' ? null : (document.querySelector<HTMLMetaElement>('meta[name="bg-build"]')?.content ?? null);
|
||||
/** Build the server has that this page doesn't ('protocol' = the server speaks a newer protocol). */
|
||||
let latest: string | null = null;
|
||||
let dismissed: string | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
const emit = () => listeners.forEach((l) => l());
|
||||
|
||||
/** The server's build (welcome message, `/api/version`). */
|
||||
export function noteServerBuild(build: string | null | undefined): void {
|
||||
if (!mine || !build || build === mine || build === latest) return;
|
||||
latest = build;
|
||||
emit();
|
||||
}
|
||||
|
||||
/** The server speaks a different protocol: this page must be refreshed whatever its build. */
|
||||
export function markOutdated(): void {
|
||||
if (latest) return;
|
||||
latest = 'protocol';
|
||||
emit();
|
||||
}
|
||||
|
||||
export function dismissUpdate(): void {
|
||||
dismissed = latest;
|
||||
emit();
|
||||
}
|
||||
|
||||
async function check(): Promise<void> {
|
||||
try {
|
||||
const res = await fetch('/api/version', { cache: 'no-store' });
|
||||
if (res.ok) noteServerBuild(((await res.json()) as { build?: string | null }).build);
|
||||
} catch {
|
||||
// Offline or restarting: the next check (or the socket's welcome) will tell.
|
||||
}
|
||||
}
|
||||
|
||||
/** Call once at startup: checks now and then, and whenever the tab comes back into view. */
|
||||
export function initUpdateCheck(): void {
|
||||
if (!mine) return;
|
||||
setInterval(() => void check(), POLL_MS);
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') void check();
|
||||
});
|
||||
}
|
||||
|
||||
const subscribe = (l: () => void) => {
|
||||
listeners.add(l);
|
||||
return () => void listeners.delete(l);
|
||||
};
|
||||
|
||||
export function useUpdateAvailable(): boolean {
|
||||
return useSyncExternalStore(subscribe, () => latest !== null && latest !== dismissed, () => false);
|
||||
}
|
||||
@@ -3,12 +3,13 @@ import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter, Route, Routes, useLocation, useNavigate } from 'react-router';
|
||||
import 'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css';
|
||||
import './styles/global.css';
|
||||
import { ConnectionBanner, Toasts } from './components/ui';
|
||||
import { ConnectionBanner, Toasts, UpdateBanner } from './components/ui';
|
||||
import { useSession } from './store/session';
|
||||
import { toast } from './store/toast';
|
||||
import { Home } from './pages/Home';
|
||||
import { SiteHeader } from './components/SiteHeader';
|
||||
import { initPwa } from './lib/pwa';
|
||||
import { initUpdateCheck } from './lib/update';
|
||||
|
||||
const JoinPage = lazy(() => import('./pages/JoinPage'));
|
||||
const RoomPage = lazy(() => import('./pages/RoomPage'));
|
||||
@@ -58,6 +59,7 @@ function Shell() {
|
||||
return (
|
||||
<>
|
||||
<ConnectionBanner />
|
||||
<UpdateBanner />
|
||||
<SiteHeader />
|
||||
<Announcement />
|
||||
<Toasts />
|
||||
@@ -82,6 +84,7 @@ function Shell() {
|
||||
}
|
||||
|
||||
initPwa();
|
||||
initUpdateCheck();
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { create } from 'zustand';
|
||||
import { PROTOCOL, type GameResultView, type PublicUser, type RoomView, type ServerMessage } from '@bg/shared/lite';
|
||||
import { toast } from '../store/toast';
|
||||
import { markOutdated, noteServerBuild } from '../lib/update';
|
||||
|
||||
export type ConnStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'replaced' | 'offline';
|
||||
|
||||
@@ -39,7 +40,6 @@ interface RoomStore {
|
||||
clockOffset: number;
|
||||
joinError: string | null;
|
||||
kicked: boolean;
|
||||
needsRefresh: boolean;
|
||||
}
|
||||
|
||||
export const useRoom = create<RoomStore>(() => ({
|
||||
@@ -58,7 +58,6 @@ export const useRoom = create<RoomStore>(() => ({
|
||||
clockOffset: 0,
|
||||
joinError: null,
|
||||
kicked: false,
|
||||
needsRefresh: false,
|
||||
}));
|
||||
|
||||
const BACKOFF = [500, 1000, 2000, 4000, 8000];
|
||||
@@ -256,7 +255,8 @@ class GameSocket {
|
||||
const st = useRoom.getState();
|
||||
switch (m.t) {
|
||||
case 'welcome': {
|
||||
if (m.protocol !== PROTOCOL) useRoom.setState({ needsRefresh: true });
|
||||
if (m.protocol !== PROTOCOL) markOutdated();
|
||||
else noteServerBuild(m.build);
|
||||
useRoom.setState({ status: 'open', me: m.me });
|
||||
this.offsets = [m.serverTime - Date.now()];
|
||||
useRoom.setState({ clockOffset: this.offsets[0]! });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** 방: 대기실 ↔ 게임 ↔ 결과를 한 주소에서 전환 (docs/06 §5–§9). */
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { botsAllowed, formatRoomCode, isBotId, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { BOT_BANDS, BOT_PICKS, BOT_PICK_LABEL, bandOf, botsAllowed, formatRoomCode, isBotId, luckLabel, type PublicUser, type RoomView } from '@bg/shared/lite';
|
||||
import { Avatar, CodeLabel, ConfirmSheet, CopyButton, ShareButton, Sheet, TopBar } from '../components/ui';
|
||||
import { GuestWarning, NicknameForm } from '../components/NicknameForm';
|
||||
import { GameNotice, gameName } from '../components/GameNotice';
|
||||
@@ -88,7 +88,7 @@ function RoomGone({ message }: { message: string }) {
|
||||
|
||||
function Room({ code, me }: { code: string; me: PublicUser }) {
|
||||
const nav = useNavigate();
|
||||
const { room, game, result, status, joinError, pending, slow, needsRefresh } = useRoom();
|
||||
const { room, game, result, status, joinError, pending, slow } = useRoom();
|
||||
const [ui, setUi] = useState<GameUI | null>(null);
|
||||
const [leaveAsk, setLeaveAsk] = useState(false);
|
||||
const [chatOpen, setChatOpen] = useState(false);
|
||||
@@ -224,14 +224,6 @@ function Room({ code, me }: { code: string; me: PublicUser }) {
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
{needsRefresh && (
|
||||
<div className="card row" style={{ margin: 12, justifyContent: 'space-between' }}>
|
||||
<span>새 버전이 있어요.</span>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => location.reload()}>
|
||||
새로고침
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{inGame && game ? (
|
||||
<GameView room={room} ui={ui} me={me} players={players} pending={pending !== null} slow={slow} />
|
||||
) : (
|
||||
@@ -331,18 +323,38 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
|
||||
<div style={{ display: 'grid', gridTemplateColumns: wide ? `repeat(${room.seats.length > 4 ? 3 : 2}, minmax(0, 1fr))` : '1fr', gap: 10 }}>
|
||||
{room.seats.map((s, i) =>
|
||||
s && isBotId(s.user.id) ? (
|
||||
<div key={i} className="card row" style={{ gap: 12, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={s.user} size={44} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 700 }}>{s.user.nickname}</div>
|
||||
<div className="row small" style={{ gap: 6 }}>
|
||||
<span className="badge">🤖 컴퓨터</span>
|
||||
<div key={i} className="card stack" style={{ gap: 10 }}>
|
||||
<div className="row" style={{ gap: 12, flexWrap: 'nowrap' }}>
|
||||
<Avatar user={s.user} size={44} />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 700 }}>{s.user.nickname}</div>
|
||||
<div className="row small" style={{ gap: 6 }}>
|
||||
<span className="badge">🤖 컴퓨터</span>
|
||||
{!isHost && <span className="badge">난이도 {BOT_PICK_LABEL[room.botPicks?.[s.user.id] ?? 'random']}</span>}
|
||||
</div>
|
||||
</div>
|
||||
{isHost && (
|
||||
<button className="btn btn-ghost" onClick={() => socket.send({ t: 'removeBot', userId: s.user.id })} aria-label={`${s.user.nickname} 빼기`}>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{/* docs/06 §12: 랜덤 = any level 1~60; a band = a random level inside it. The level shows after the game. */}
|
||||
{isHost && (
|
||||
<button className="btn btn-ghost" onClick={() => socket.send({ t: 'removeBot', userId: s.user.id })} aria-label={`${s.user.nickname} 빼기`}>
|
||||
✕
|
||||
</button>
|
||||
<div className="segmented bot-level" role="group" aria-label={`${s.user.nickname} 난이도`}>
|
||||
{BOT_PICKS.map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
aria-pressed={(room.botPicks?.[s.user.id] ?? 'random') === p}
|
||||
disabled={room.starting}
|
||||
title={p === 'random' ? '1~60단계 중 무작위' : `${BOT_BANDS[p][0]}~${BOT_BANDS[p][1]}단계 중 무작위`}
|
||||
onClick={() => socket.send({ t: 'botLevel', userId: s.user.id, pick: p })}
|
||||
>
|
||||
{BOT_PICK_LABEL[p]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : s ? (
|
||||
@@ -428,8 +440,8 @@ function Lobby({ room, ui, me }: { room: RoomView; ui: GameUI; me: PublicUser })
|
||||
<div className="bottom-bar inline-wide">
|
||||
<div className="bottom-bar-inner">
|
||||
{isHost ? (
|
||||
<button className="btn btn-primary" style={{ minHeight: 64, fontSize: '1.2rem' }} disabled={need > 0} onClick={() => (notReady > 0 ? setAskStart(true) : socket.send({ t: 'start' }))}>
|
||||
{need > 0 ? `${need}명 더 필요해요` : '▶ 게임 시작'}
|
||||
<button className="btn btn-primary" style={{ minHeight: 64, fontSize: '1.2rem' }} disabled={need > 0 || room.starting} onClick={() => (notReady > 0 ? setAskStart(true) : socket.send({ t: 'start' }))}>
|
||||
{room.starting ? '🃏 섞는 중…' : need > 0 ? `${need}명 더 필요해요` : '▶ 게임 시작'}
|
||||
</button>
|
||||
) : mySeat >= 0 ? (
|
||||
room.seats[mySeat]!.ready ? (
|
||||
@@ -751,7 +763,7 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView;
|
||||
방 나가기
|
||||
</button>
|
||||
{room.lastSeed && (
|
||||
<FairnessCheck seedHash={room.seedHash} seed={room.lastSeed} />
|
||||
<FairnessCheck seedHash={room.seedHash} seed={room.lastSeed} bots={room.lastBots} shuffles={room.lastShuffles} players={players} />
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
@@ -761,7 +773,19 @@ function ResultPanel({ room, me, players, onLeave, onAgain }: { room: RoomView;
|
||||
* docs/04 §5: the seed's SHA-256 was published when the game started; the seed is revealed at the end.
|
||||
* The browser recomputes the hash itself so players don't have to trust the server's word.
|
||||
*/
|
||||
function FairnessCheck({ seedHash, seed }: { seedHash: string | null; seed: string }) {
|
||||
function FairnessCheck({
|
||||
seedHash,
|
||||
seed,
|
||||
bots,
|
||||
shuffles,
|
||||
players,
|
||||
}: {
|
||||
seedHash: string | null;
|
||||
seed: string;
|
||||
bots?: RoomView['lastBots'];
|
||||
shuffles?: number;
|
||||
players: Record<string, PublicUser>;
|
||||
}) {
|
||||
const [verdict, setVerdict] = useState<null | boolean>(null);
|
||||
const check = async () => {
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed));
|
||||
@@ -771,6 +795,17 @@ function FairnessCheck({ seedHash, seed }: { seedHash: string | null; seed: stri
|
||||
return (
|
||||
<details className="small muted">
|
||||
<summary>공정성 확인</summary>
|
||||
{/* docs/09 §9.1: each computer's level (1~60) and luck in this game; docs/04 §5.1: shuffles tried for luck. */}
|
||||
{bots && Object.keys(bots).length > 0 && (
|
||||
<div className="stack" style={{ gap: 4, margin: '8px 0' }}>
|
||||
{Object.entries(bots).map(([id, b]) => (
|
||||
<p key={id} style={{ margin: 0 }}>
|
||||
🤖 {players[id]?.nickname ?? '컴퓨터'}: 난이도 <strong>{b.level}단계</strong> ({BOT_PICK_LABEL[bandOf(b.level)]}) · 운 {luckLabel(b.luck)}
|
||||
</p>
|
||||
))}
|
||||
{(shuffles ?? 1) > 1 && <p style={{ margin: 0 }}>이번 판은 컴퓨터의 운에 맞춰, 미리 섞어 본 {shuffles}가지 중 하나로 시작했어요. 고른 결과는 시작할 때 아래 값으로 공개했어요.</p>}
|
||||
</div>
|
||||
)}
|
||||
<p>시작할 때 공개한 값(SHA-256): {seedHash ?? '-'}</p>
|
||||
<p>끝나고 공개한 난수 씨앗: {seed}</p>
|
||||
<button type="button" className="btn btn-secondary btn-sm" onClick={check}>
|
||||
|
||||
@@ -307,6 +307,16 @@ label.field {
|
||||
background: var(--primary-soft);
|
||||
font-weight: 700;
|
||||
}
|
||||
/* Computer difficulty in the lobby (docs/06 §12): four even pills. */
|
||||
.segmented.bot-level {
|
||||
flex-wrap: nowrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.segmented.bot-level button {
|
||||
flex: 1;
|
||||
padding: 0 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ---------- top bar ---------- */
|
||||
.topbar {
|
||||
@@ -368,6 +378,54 @@ label.field {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* "업데이트 내용이 있습니다" (docs/07 §11.1): a card at the top, above everything but the connection banner. */
|
||||
.update-banner {
|
||||
position: fixed;
|
||||
top: calc(8px + env(safe-area-inset-top));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 70;
|
||||
width: min(94vw, 480px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
border: 2px solid var(--primary);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 10px 8px 10px 16px;
|
||||
animation: update-in 0.2s ease;
|
||||
}
|
||||
@keyframes update-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translate(-50%, -8px);
|
||||
}
|
||||
}
|
||||
.update-banner .update-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
.update-banner .btn {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.update-close {
|
||||
flex: none;
|
||||
width: var(--tap);
|
||||
height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--text-sub);
|
||||
font-size: 1.2rem;
|
||||
cursor: pointer;
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.update-close:hover {
|
||||
background: var(--surface-2);
|
||||
}
|
||||
|
||||
.toasts {
|
||||
position: fixed;
|
||||
top: calc(var(--site-h) + env(safe-area-inset-top));
|
||||
|
||||
@@ -19,8 +19,28 @@ function serviceWorker(): Plugin {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `<meta name="bg-build" content="…">` into index.html: a hash of the built file names, so it changes whenever
|
||||
* any script or style changes. The server reads it from dist/index.html; an open page compares its own with the
|
||||
* server's and offers to refresh (docs/07 §11.1).
|
||||
*/
|
||||
function buildId(): Plugin {
|
||||
return {
|
||||
name: 'bg-build-id',
|
||||
apply: 'build',
|
||||
transformIndexHtml: {
|
||||
order: 'post',
|
||||
handler(html, ctx) {
|
||||
const files = Object.keys(ctx.bundle ?? {}).filter((f) => !f.endsWith('.html')).sort().join('\n');
|
||||
const build = createHash('sha256').update(files).digest('hex').slice(0, 12);
|
||||
return [{ tag: 'meta', attrs: { name: 'bg-build', content: build }, injectTo: 'head' }];
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), serviceWorker()],
|
||||
plugins: [react(), serviceWorker(), buildId()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
| `host` | `userId` | 방장 넘기기 |
|
||||
| `addBot` | `seat?: number` | 방장: 빈자리에 컴퓨터 넣기(대기실에서만, 06 §12) |
|
||||
| `removeBot` | `userId` | 방장: 컴퓨터 빼기(대기실에서만) |
|
||||
| `botLevel` | `userId`, `pick: "random"\|"easy"\|"normal"\|"hard"` | 방장: 컴퓨터 난이도 고르기(대기실에서만). 고른 범위 안에서 단계(1~60)를 무작위로 다시 정함(09 §9.1) |
|
||||
| `act` | `cs: number`, `a: Action` | 게임 행동. `cs`는 클라이언트 행동 번호(1부터 증가) |
|
||||
| `chat` | `text`(1~200자) | 채팅 |
|
||||
| `emote` | `id` | 빠른 반응(👍, 😂, "잘했어요!" 등 고정 목록) |
|
||||
@@ -42,7 +43,7 @@
|
||||
### 3.2 서버 → 클라이언트
|
||||
| t | 필드 | 설명 |
|
||||
|---|---|---|
|
||||
| `welcome` | `me`, `serverTime`, `protocol`, `activeRoom?` | 연결 직후 |
|
||||
| `welcome` | `me`, `serverTime`, `protocol`, `activeRoom?`, `build?` | 연결 직후. `build`는 서버가 내주는 웹 빌드 ID(다르면 "업데이트 내용이 있습니다", 07 §11.1) |
|
||||
| `room` | `seq`, `room: RoomView` | 대기실/자리/옵션/접속 상태 전체 |
|
||||
| `state` | `seq`, `view`, `events`, `active: userId[]`, `deadline: number\|null`, `cs?` | 게임 상태. `cs`는 이 상태를 만든 행동이 내 것일 때만 포함(= 성공 응답) |
|
||||
| `reject` | `cs`, `reason` | 내 행동 거절(한국어 이유). 화면은 바꾸지 않고 안내만 표시 |
|
||||
|
||||
@@ -34,8 +34,30 @@
|
||||
- 게임마다 "정보 유출 테스트": 무작위 대국을 돌리며 매 순간 플레이어 A의 view(JSON 문자열)에 다른 사람만 알아야 하는 값(카드 ID 등)이 들어 있지 않은지 검사.
|
||||
- 셔플: 게임 시작 시 `crypto.getRandomValues`로 256비트 시드를 만들고, 상태 안의 암호학적 난수 생성기 ChaCha20(RFC 8439)으로 Fisher–Yates 셔플·주사위·뽑기(2026-10-11). 지금까지 나온 카드·주사위를 아무리 봐도 다음 값을 알 수 없다. 그 전에 시작된 게임은 sfc32(128비트) 그대로라 다시 보기가 같다.
|
||||
- **공정성 확인(선택 표시)**: 게임 시작 때 시드의 SHA-256 해시를 모두에게 공개하고, 게임이 끝나면 시드를 공개한다. 결과 화면의 "공정성 확인"을 누르면 같은 시드로 덱을 다시 만들어 실제 배분과 같은지 브라우저가 확인한다.
|
||||
- **컴퓨터의 운(2026-10-11, §5.1)**: 컴퓨터가 있는 연습 게임에서는 시작 전에 시드를 몇 개 만들어 보고 그중 하나를 고른다. 고른 시드의 해시를 시작할 때 공개하는 것은 같으므로, 게임 중에 카드 순서나 난수가 바뀌지 않는다는 보장은 그대로다.
|
||||
- 관전자에게는 공개 정보만. 포커·섯다처럼 관전이 정보 누설 통로가 될 수 있는 게임은 기본적으로 "관전 지연 표시 없음 + 공개 정보만"이고, 같은 사람이 플레이어와 관전자를 동시에 할 수 없다.
|
||||
|
||||
### 5.1 컴퓨터의 운 (2026-10-11)
|
||||
사람처럼 컴퓨터마다 운이 다르다. 운이 좋으면 패가 잘 들어오고, 난이도가 높아도 운이 나쁘면 패가 잘 안 들어와 어려워진다.
|
||||
|
||||
- 운: 컴퓨터를 넣을 때 OS 보안 난수로 -1(아주 나쁨)~+1(아주 좋음)에서 하나 정해지고 그 방에 있는 동안 그대로다(난이도를 바꿔도 유지). 결과 화면 "공정성 확인"에 아주 나쁨(≤-0.6)·나쁨(≤-0.2)·보통·좋음(≥0.2)·아주 좋음(≥0.6)으로 보인다.
|
||||
- 섞기 후보 수: `1 + round(|운| × 4)`. 운이 0 근처(|운|<0.125)면 1개(고르지 않음), ±1이면 5개(`MAX_SHUFFLES`). 컴퓨터가 여럿이면 가장 센 운 기준.
|
||||
- 고르는 법(`chooseLuckySeed`, `packages/games/src/bots/luck.ts`): 후보마다 새 OS 시드로 게임을 한 번 끝까지 둬 본다(모든 자리를 컴퓨터가 둠, 사람 자리는 30단계). 각자의 등수를 0(꼴찌)~1(1등) 점수로 바꾸고, Σ(컴퓨터의 운 × 그 컴퓨터 점수)가 가장 큰 시드를 쓴다. 운이 좋은 컴퓨터는 잘 풀렸던 배분을, 나쁜 컴퓨터는 안 풀렸던 배분을 받는 셈이다. 실제 게임은 사람이 다르게 두므로 결과는 여전히 정해지지 않는다.
|
||||
- 대상: 카드·패·타일·주사위·숨은 역할이 있는 컴퓨터 게임. 오목·오셀로·체스·장기·바둑·쿼리도(섞는 게 선후뿐), 마피아(말하는 컴퓨터, 시뮬레이션 없음)는 운을 쓰지 않는다.
|
||||
- 서버 부담: 시뮬레이션은 방 스레드가 아닌 작업 스레드(`apps/server/src/rooms/luck-worker.ts`) 하나에서 순서대로 한다. 첫 후보 뒤로는 1.5초(`LUCK_BUDGET_MS`)를 넘기면 더 만들지 않고, 8초 안에 답이 없거나 실패하면 새 시드 하나로 시작한다. 그동안 대기실은 "🃏 섞는 중…"이고 설정·자리·난이도를 바꿀 수 없다. 그사이 자리가 바뀌면 시작하지 않는다.
|
||||
- 공개: 결과 화면 "공정성 확인"에 컴퓨터별 난이도·운과 "미리 섞어 본 N가지 중 하나로 시작했어요"를 보인다. 연습 게임은 전적에 들어가지 않는다(06 §12).
|
||||
- 효과(컴퓨터 1:1, 고른 배분으로 수는 새로 골라 끝까지 둠, 컴퓨터의 평균 점수, 0.5 = 반반, 운별 80판):
|
||||
|
||||
| 게임 | 운 +1 | 운 0 | 운 -1 |
|
||||
|---|---|---|---|
|
||||
| 원카드 | 0.63 | 0.60 | 0.41 |
|
||||
| 섯다 | 0.54 | 0.44 | 0.36 |
|
||||
| 포커 | 0.72 | 0.41 | 0.25 |
|
||||
| 요트 | 0.79 | 0.48 | 0.17 |
|
||||
|
||||
사람은 컴퓨터와 다르게 두므로 실제 효과는 이보다 조금 약할 수 있다(특히 주사위 게임은 두는 수에 따라 뒤 주사위가 달라진다).
|
||||
- 테스트: `packages/games/src/bots/luck.test.ts`(후보 수, 대상 게임, 운 좋은 쪽이 더 잘함), `apps/server/src/rooms/luck.test.ts`(실제 작업 스레드, 실패·시간 초과 대비), `apps/server/src/rooms/bot-level.room.test.ts`(섞는 동안 대기, 고른 시드로 시작, 자리 바뀌면 취소).
|
||||
|
||||
## 6. 사행성·법적 주의
|
||||
- 포커·섯다·고스톱 등은 **방 안에서만 쓰는 가상 칩/점수**를 쓴다. 방이 끝나면 사라지고, 계정에 쌓이지 않으며, 사고팔거나 바꿀 수 없다. 결제·유료 아이템·충전도 없다.
|
||||
- 기록에는 "몇 판 이겼는지"만 남기고 칩 잔액은 남기지 않는다.
|
||||
|
||||
@@ -107,6 +107,7 @@ interface Room {
|
||||
## 12. 컴퓨터 상대 (혼자 연습)
|
||||
- 들어가는 곳: 게임 상세와 홈의 [🤖 컴퓨터와 연습하기]. 친구만 방이 열리고, 바로 시작할 수 있을 만큼 컴퓨터가 앉아 있다(예: 오목 1명, 마작 2명, 뱅 3명).
|
||||
- 대기실: 방장은 첫 빈자리의 [🤖 컴퓨터 넣기]로 넣고, 컴퓨터 자리의 [✕]로 뺀다(대기실에서만). 컴퓨터 이름은 "컴퓨터 1", "컴퓨터 2"…, 아바타는 🤖. 늘 준비 완료이고, 방장은 컴퓨터에게 넘어가지 않는다. 사람이 한 명은 앉아야 시작된다.
|
||||
- 난이도(2026-10-11): 컴퓨터를 넣으면 1~60단계 중 아무 단계나 정해진다(랜덤). 방장은 컴퓨터 자리 아래의 [랜덤][쉬움][보통][어려움]으로 바꿀 수 있고(대기실에서만, `botLevel`), 고르면 그 범위(쉬움 1~20, 보통 21~40, 어려움 41~60) 안에서 단계가 다시 무작위로 정해진다. 다른 사람에게는 고른 이름("난이도 쉬움")만 보이고 정확한 단계는 게임이 끝난 뒤 "공정성 확인"에 보인다. 다음 판마다 처음 정한 단계 근처에서 조금씩 바뀐다(한 판에 최대 2단계, 처음 단계 ±5 안, 같은 범위 안). 컴퓨터마다 운도 다르다(04 §5.1). 자세한 것은 09 §9.1.
|
||||
- 컴퓨터가 앉은 방은 연습 방이다: 공개로 바꿀 수 없고, 공개 방 목록·빠른 시작에 나오지 않는다. 결과는 남지만 전적(`user_stats`)에는 넣지 않는다. 화면에 "연습 게임이에요. 기록에는 남지 않아요." 표시.
|
||||
- 컴퓨터가 할 수 있는 게임: 실시간·그림 게임(도블, 할리갈리, 그림 맞히기)을 뺀 전부(`packages/shared/src/bots.ts`의 `BOT_GAMES`). 마피아는 말하는 컴퓨터(2026-10-11, games/mafia.md §13), 연습 방은 6명으로 시작.
|
||||
- 움직임: 서버의 `BotDriver`(`apps/server/src/rooms/bots.ts`)가 게임이 컴퓨터를 기다릴 때(차례, 반응 창, 동시 선택, 다음 판 준비) 사람처럼 생각할 시간을 두고 한 수를 둔다(2026-10-11). 할 게 하나뿐이면 0.7~1.3초, 고를 게 있으면 1.6~3.9초(고를 수가 많을수록 길게), 가끔(12%) 1~3초 더 멈칫한다. 컴퓨터마다 빠르기가 달라서(`botPace`: 0.7배 빠른 편~1.5배 신중한 편, 컴퓨터 id로 고정) 같은 판에서도 반응 속도가 다르다. 같은 컴퓨터가 이어서 두는 동작(요트 굴리기 → 고르기 등)은 절반 시간, 사람도 함께 반응할 수 있는 창(원카드 외치기 등)은 1.5초 더. 차례 시간이 있으면 남은 시간의 절반을 넘기지 않는다. 사람과 같은 행동 경로(검사·기록)를 거치고, 서버가 다시 켜져도 이어서 둔다.
|
||||
@@ -116,7 +117,7 @@ interface Room {
|
||||
### 12.1 사람처럼 노는 컴퓨터 (GPU 로컬 모델, 2026-10-11)
|
||||
- 수 고르기는 게임별 전략(자기 화면만 봄) 그대로다. 그 위에 GPU의 로컬 언어 모델(gemma3:4b, docs/11 §8)이 말과 심리전을 맡는다(`apps/server/src/ai/`).
|
||||
- 성격: 컴퓨터 id로 정해지는 5가지 — 도발형·허세형·차분형·수다형·소심형 — 와 말투(똑똑한 편 존댓말, 허술한 편 반말).
|
||||
- 난이도: 컴퓨터마다 쉬움 35%·보통 40%·어려움 25%로 정해지고(보안 난수), 오목·체스·장기·오델로·바둑에서는 난이도에 따라 가끔 비슷한 다른 수를 두거나 실수한다. 확률과 기준은 09 §9.1.
|
||||
- 난이도: 컴퓨터마다 1~60단계(§12, 보안 난수)이고, 오목·체스·장기·오델로·바둑에서는 단계에 따라 가끔 비슷한 다른 수를 두거나 실수한다. 확률과 기준은 09 §9.1. 카드·주사위 게임은 운(04 §5.1)이 배분에 영향을 준다.
|
||||
- 보이는 행동: 수를 고르는 동안 "🤖 컴퓨터 1 생각 중…", 말할 때는 그 줄을 치는 만큼(글자 수 × 컴퓨터마다 다른 타자 속도, 0.9~6.5초) "💬 입력 중…"이 보인 뒤 채팅이 올라가고, 잠깐 뒤 수를 둔다(상태 줄과 채팅 칸, `RoomView.botActivity`).
|
||||
- 말하는 때: 자기 수와 함께 도발·심리전 한마디(성격별 14~38%, 방 전체 8초·컴퓨터마다 20초 간격), 사람의 수에 가끔 반응(12%), 사람이 이름을 부르거나 말을 걸면 대답(이름 부르면 꼭, 아니면 40%), 시작 인사, 끝나면 이긴 컴퓨터가 놀리거나 진 컴퓨터가 아쉬워함.
|
||||
- 심리전 판단: 바퀴벌레 포커에서 카드를 건넬 때 진짜를 말할지 블러핑할지를 모델이 정하고, 그걸 파는 한마디를 한다(실제 카드 이름이 들어간 말은 버림). 마피아는 컴퓨터가 계획한 대사(의심 지목·반박·반론 등)를 모델이 자기 말로 바꾼다. 모델에게 그 컴퓨터의 직업은 알려 주지 않고, "저 경찰이에요"·"나 마피아" 같은 직업 주장이 나오면 버리고 원래 대사를 쓴다.
|
||||
|
||||
@@ -200,4 +200,10 @@
|
||||
- 앱 안: 인터넷이 끊기면 `ConnectionBanner`가 위쪽 띠로 알린다(방 안에서는 기존 재연결 문구).
|
||||
- 홈 화면에 추가: 홈 아래쪽 카드. `beforeinstallprompt`를 잡아 [추가하기] 버튼을 보이고, iOS(이 이벤트 없음)는 "공유 버튼 → [홈 화면에 추가]" 안내만. 이미 앱으로 열었거나(standalone) [닫기]를 누르면(기기에 기억) 안 보인다.
|
||||
- 서버: `/sw.js`·`/manifest.webmanifest`·`/offline.html`은 index.html과 같이 `no-cache`, manifest는 `application/manifest+json`(Bun 기본). CSP `default-src 'self'`가 워커·매니페스트를 허용해 따로 넣은 것은 없다.
|
||||
- 확인: `apps/web/src/sw.test.ts`(캐시 규칙), `bun e2e/pwa.e2e.ts`(매니페스트·아이콘, 워커 활성화, 오프라인 띠·안내 페이지, 다시 온라인, 설치 카드).
|
||||
- 확인: `apps/web/src/sw.test.ts`(캐시 규칙), `bun e2e/pwa.e2e.ts`(매니페스트·아이콘, 워커 활성화, 오프라인 띠·안내 페이지, 다시 온라인, 설치 카드, 업데이트 팝업).
|
||||
|
||||
### 11.1 업데이트 알림 (2026-10-11)
|
||||
- 사이트가 업데이트되면 열려 있는 페이지 위쪽 가운데에 카드가 뜬다: "업데이트 내용이 있습니다." [지금 새로고침하기] [✕]. ✕를 누르면 닫히고, 그다음 업데이트가 나올 때까지 다시 뜨지 않는다(새로고침하면 새 빌드라 안 뜸). 모든 화면에 보인다(`UpdateBanner`, `apps/web/src/lib/update.ts`).
|
||||
- 빌드 ID: 빌드할 때 Vite 플러그인(`buildId`, vite.config.ts)이 만든 파일 이름들의 해시 12자리를 index.html의 `<meta name="bg-build">`에 넣는다. 스크립트·스타일이 하나라도 바뀌면 달라지고, 서버 코드만 바뀐 배포에는 뜨지 않는다.
|
||||
- 서버는 시작할 때 dist/index.html에서 그 값을 읽어(`webBuildId`) `GET /api/version`(`no-store`)과 소켓 `welcome.build`로 알린다. 페이지는 5분마다, 탭이 다시 보일 때, 소켓이 (다시) 연결될 때 비교한다. 배포로 서버가 다시 켜지면 소켓이 다시 연결되면서 바로 뜬다.
|
||||
- 프로토콜 번호가 다를 때(예전 방 화면의 "새 버전이 있어요")도 같은 카드를 쓴다. 개발 서버에는 빌드 ID가 없어 뜨지 않는다.
|
||||
|
||||
@@ -135,7 +135,7 @@ export interface GameUI<V> {
|
||||
## 9. 컴퓨터 상대 (`packages/games/src/bots/`, 06 §12)
|
||||
- 게임마다 `<게임>/bot.ts`의 전략 하나: `(입력: { me, view, legal, random }) => 행동`. `view`는 `view(state, me)`, `legal`은 `legalActions(state, me)`. 게임 상태는 넘기지 않는다(비공개 정보 차단).
|
||||
- `decideBotAction`이 고른 수를 `validate`로 다시 검사하고, 틀리면 다른 합법 수로 바꾼다. 서버는 그래도 실패하면 게임의 `onTimeout` 행동을 쓴다.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 난이도(§9.1), 똑똑한 편/허술한 편과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 라이브 봇(`LIVE_BOT_STRATEGIES`, 마피아): 모두가 동시에 시계에 맞춰 움직이고 말하는 게임. 전략은 `({ me, view, now, persona, names, memory }) => { action | null, next }`로, 서버가 컴퓨터마다 따로 `next` ms 뒤에 다시 묻는다. `persona`(`bots/persona.ts`)는 똑똑한 편/허술한 편(§9.1)과 빠르기, `memory`는 이번 판에 이미 한 일(서버가 다시 켜지면 비워짐). 테스트 도우미 `bots/live-playout.ts`.
|
||||
- 테스트(`bots/bots.test.ts`): 게임마다 "사람 1명은 시간 초과만, 나머지는 컴퓨터"와 "컴퓨터끼리" 판을 끝까지 돌려, 모든 수가 합법이고 컴퓨터 때문에 멈추지 않으며 한 수가 충분히 빠른지 본다.
|
||||
|
||||
### 9.1 컴퓨터 난이도와 난수 (2026-10-11)
|
||||
@@ -144,29 +144,37 @@ export interface GameUI<V> {
|
||||
|
||||
| 무엇 | 난수 |
|
||||
|---|---|
|
||||
| 카드 섞기·주사위·타일 뽑기 | 판마다 256비트 OS 시드 + ChaCha20(§3) |
|
||||
| 카드 섞기·주사위·타일 뽑기 | 판마다 256비트 OS 시드 + ChaCha20(§3). 컴퓨터가 있으면 운에 맞춰 후보 시드 중 하나(04 §5.1) |
|
||||
| 컴퓨터의 수 고르기, 생각 시간, 채팅 여부, 방 코드, 마감 유예 | `secureRandom()`(`packages/engine/src/rng.ts`, OS 난수 53비트 실수) |
|
||||
| 컴퓨터의 난이도·말투 | 컴퓨터 id `bot:<n>:<ULID>`의 무작위 부분(ULID를 `secureRandom`으로 만듦) 앞 6글자 = 30비트 균등 난수(`botDraw`) |
|
||||
| 컴퓨터의 난이도 단계·운, 다음 판의 단계 변화 | `secureRandom()` (`apps/server/src/rooms/bot-profile.ts`) |
|
||||
|
||||
브라우저의 닉네임 추천과 재연결 대기 시간은 보안과 상관없어 그대로 둔다.
|
||||
|
||||
**난이도 확률.** 컴퓨터를 넣을 때 하나씩 정해지고, 그 컴퓨터는 서버가 다시 켜져도 같은 난이도다(`bots/persona.ts`). 화면에는 보이지 않는다.
|
||||
**난이도 1~60단계.** 1이 가장 약하고 60이 가장 세다.
|
||||
|
||||
| 난이도 | 확률 (`BOT_LEVEL_ODDS`) | 성격·말투 (`smart`) |
|
||||
| 이름 | 단계 | 고르는 법 |
|
||||
|---|---|---|
|
||||
| 쉬움 | 35% (`botDraw` 0~0.35) | 전부 허술한 편, 반말 |
|
||||
| 보통 | 40% (0.35~0.75) | 앞 절반(0.35~0.5) 허술한 편·반말, 뒤 절반(0.5~0.75) 똑똑한 편·존댓말 |
|
||||
| 어려움 | 25% (0.75~1) | 전부 똑똑한 편, 존댓말 |
|
||||
| 랜덤 (처음) | 1~60 | 컴퓨터를 넣을 때 고르게 무작위 |
|
||||
| 쉬움 | 1~20 | 방장이 [쉬움]을 누르면 이 안에서 무작위 |
|
||||
| 보통 | 21~40 | 〃 |
|
||||
| 어려움 | 41~60 | 〃 |
|
||||
|
||||
그래서 똑똑한 편과 허술한 편은 전체에서 반반이다(마피아 §13 그대로).
|
||||
- 방은 컴퓨터마다 `{ pick, base, level, luck, played }`를 저장한다(`RoomSnapshot.bots`, 서버가 다시 켜져도 그대로). `base`는 고를 때 나온 단계, `level`은 지금 단계.
|
||||
- **판마다 조금씩**: 첫 판은 `base` 그대로, 그다음 판부터 시작할 때마다 -2~+2단계 움직인다(`drift`). 단, `base`±5 안, 그리고 `base`가 속한 범위(쉬움/보통/어려움) 안에서만. 그래서 60은 다음 판에 58이 될 수는 있어도 41이 되지는 않는다. 난이도를 다시 고르면 새 `base`에서 다시 시작한다.
|
||||
- **보이는 것**: 대기실에는 방장이 고른 이름(랜덤/쉬움/보통/어려움)만, 게임이 끝나면 결과 화면 "공정성 확인"에 그 판의 단계와 운이 보인다(`RoomView.lastBots`). 게임 중에는 단계를 보내지 않는다.
|
||||
- **말투(`smart`)**: `base`가 30보다 크면 똑똑한 편·존댓말, 아니면 허술한 편·반말. 랜덤으로 넣은 컴퓨터는 반반이고(마피아 §13 그대로), 쉬움은 모두 반말, 어려움은 모두 존댓말이다. 판마다 단계가 움직여도 말투는 바뀌지 않는다.
|
||||
- 저장된 단계가 없는 예전 방의 컴퓨터는 id의 무작위 부분으로 단계를 정한다(`idLevel`).
|
||||
- **운**: 컴퓨터마다 -1~+1. 카드·패·주사위 게임에서 시작 배분에 영향을 준다. 방법과 효과는 04 §5.1.
|
||||
|
||||
**사람처럼 두기(`humanBest`, `bots/policy.ts`).** 오목·체스·장기·오델로·바둑 컴퓨터는 수마다 점수를 매긴 뒤 늘 1등 수만 두지 않는다. 한 수마다 확률(`BOT_PLAY`):
|
||||
**사람처럼 두기(`humanBest`, `bots/policy.ts`).** 오목·체스·장기·오델로·바둑 컴퓨터는 수마다 점수를 매긴 뒤 늘 1등 수만 두지 않는다. 한 수마다 확률(`botPlay(단계)`)은 아래 기준 단계(`BOT_PLAY_ANCHORS`) 사이를 단계에 따라 고르게 이어 붙인 값이다. 각 범위의 가운데(10·30·50)는 예전 쉬움·보통·어려움과 같다.
|
||||
|
||||
| 난이도 | 1등 수 | 비슷한 수 (점수 차 `small`×창 이내, 상위 5개) | 사고 (점수 차 `small`×8 이내, 상위 8개) | 꼭 둬야 할 수를 놓침 |
|
||||
| 단계 | 1등 수 | 비슷한 수 (점수 차 `small`×창 이내, 상위 5개) | 사고 (점수 차 `small`×8 이내, 상위 8개) | 꼭 둬야 할 수를 놓침 |
|
||||
|---|---|---|---|---|
|
||||
| 쉬움 | 약 59% | 35% (창 ×2) | 6% | 12% |
|
||||
| 보통 | 약 78% | 20% (창 ×1) | 2% | 3% |
|
||||
| 어려움 | 약 91.5% | 8% (창 ×0.5) | 0.5% | 0% |
|
||||
| 1 | 약 45% | 45% (창 ×3) | 10% | 20% |
|
||||
| 10 | 약 59% | 35% (창 ×2) | 6% | 12% |
|
||||
| 30 | 약 78% | 20% (창 ×1) | 2% | 3% |
|
||||
| 50 | 약 91.5% | 8% (창 ×0.5) | 0.5% | 0% |
|
||||
| 60 | 약 97% | 3% (창 ×0.25) | 0% | 0% |
|
||||
|
||||
- 범위 안에 고를 다른 수가 없으면 1등 수를 둔다. 아무리 사고여도 `small`×8보다 나쁜 수(퀸을 그냥 주기, 바로 지는 수 등)는 두지 않는다.
|
||||
- "꼭 둬야 할 수"는 점수가 `critical` 이상인 1등 수다. 놓치면 그다음으로 좋아 보이는 수 3개 중 하나를 둔다.
|
||||
@@ -180,6 +188,6 @@ export interface GameUI<V> {
|
||||
| 오델로 | 3 (상대가 둘 곳 2개 더) | 90: 빈 귀 잡기 |
|
||||
| 바둑 | 1.5 (모양 점수) | 24: 돌 3개 이상 따내기·살리기 |
|
||||
|
||||
- 다른 게임(카드·주사위 등)은 패와 주사위가 이미 무작위라 지금처럼 고른다. 생각 시간은 06 §12대로 가끔(12%) 1~3초 더 멈칫한다.
|
||||
- 컴퓨터끼리 대국(무작위 시드, 선후 번갈아): 오목 어려움 대 쉬움 100판 84승 16패, 보통 대 쉬움 60판 42승 18패, 어려움 대 예전(늘 1등 수) 60판 34승 26패. 체스 어려움 대 쉬움 40판 18승 10패 12무.
|
||||
- 테스트: `bots/level.test.ts`(보안 난수 분포, 난이도 확률·말투 짝, `humanBest` 확률), `bots/bots.test.ts`(다섯 게임 모두 쉬움·어려움 컴퓨터끼리 끝까지 둠).
|
||||
- 다른 게임(카드·주사위 등)은 수 고르기는 그대로이고, 대신 컴퓨터의 운이 배분에 영향을 준다(04 §5.1). 생각 시간은 06 §12대로 가끔(12%) 1~3초 더 멈칫한다.
|
||||
- 컴퓨터끼리 대국(무작위 시드, 선후 번갈아, 단계 50·30·10으로 잰 값): 오목 어려움 대 쉬움 100판 84승 16패, 보통 대 쉬움 60판 42승 18패, 어려움 대 예전(늘 1등 수) 60판 34승 26패. 체스 어려움 대 쉬움 40판 18승 10패 12무.
|
||||
- 테스트: `bots/level.test.ts`(보안 난수 분포, id 단계 1~60 고르게·말투 반반, `botPlay` 기준값·단조, `humanBest` 확률), `bots/bots.test.ts`(다섯 게임 모두 1단계·60단계 컴퓨터끼리 끝까지 둠), `apps/server/src/rooms/bot-level.room.test.ts`(범위별 단계, 방장만 고름, 판마다 변화 폭, 끝난 뒤에만 공개, 재시작 뒤 유지).
|
||||
|
||||
@@ -172,6 +172,11 @@ try {
|
||||
await seats.getByText('컴퓨터 3').waitFor();
|
||||
await seats.getByRole('button', { name: '컴퓨터 3 빼기' }).click();
|
||||
await seats.getByText('컴퓨터 3').waitFor({ state: 'detached' });
|
||||
// Difficulty per computer (docs/06 §12): 랜덤 at first, the host picks 쉬움.
|
||||
const level = seats.getByRole('group', { name: '컴퓨터 2 난이도' });
|
||||
if ((await level.getByRole('button', { name: '랜덤' }).getAttribute('aria-pressed')) !== 'true') throw new Error('a new computer is not 랜덤');
|
||||
await level.getByRole('button', { name: '쉬움' }).click();
|
||||
await b.waitForFunction(() => document.querySelector('[aria-label="컴퓨터 2 난이도"] [aria-pressed="true"]')?.textContent === '쉬움');
|
||||
await b.screenshot({ path: join(SHOTS, 'bots-3-lobby-phone.png'), fullPage: true });
|
||||
});
|
||||
|
||||
@@ -249,6 +254,12 @@ try {
|
||||
await b.getByRole('button', { name: '🤖 컴퓨터와 연습하기' }).click();
|
||||
await b.waitForURL(/\/r\/\d{6}$/);
|
||||
await b.getByLabel('자리').getByText('컴퓨터 1').waitFor();
|
||||
await b.getByRole('group', { name: '컴퓨터 1 난이도' }).getByRole('button', { name: '어려움' }).click();
|
||||
await b.waitForFunction(() => document.querySelector('[aria-label="컴퓨터 1 난이도"] [aria-pressed="true"]')?.textContent === '어려움');
|
||||
// The best luck: the server plays out 5 shuffles on its worker before the game (docs/04 §5.1).
|
||||
const room = app.rooms.get(codeOf(b))!;
|
||||
const bot = room.seatedIds().find((u) => u.startsWith('bot:'))!;
|
||||
room.botProfiles[bot]!.luck = 1;
|
||||
await b.getByRole('button', { name: '▶ 게임 시작' }).click();
|
||||
await b.getByRole('button', { name: '🏳 기권' }).click();
|
||||
await b.getByRole('button', { name: '기권하기' }).click();
|
||||
@@ -259,6 +270,12 @@ try {
|
||||
if (ranks.length !== 2 || scores.length !== 2 || !scores.every((t) => /^\d+점$/.test(t))) {
|
||||
throw new Error(`ranks ${JSON.stringify(ranks)} scores ${JSON.stringify(scores)}`);
|
||||
}
|
||||
// Fairness check: the computer's level and luck in this game, and the shuffles tried for its luck.
|
||||
await result.getByText('공정성 확인').click();
|
||||
const fair = await result.locator('details').innerText();
|
||||
if (!/컴퓨터 1: 난이도 (4[1-9]|5\d|60)단계 \(어려움\) · 운 아주 좋음/.test(fair) || !fair.includes('미리 섞어 본 5가지')) throw new Error(`fairness: ${fair}`);
|
||||
await result.getByRole('button', { name: '내 브라우저에서 직접 확인하기' }).click();
|
||||
await result.getByText('✓ 일치해요.').waitFor();
|
||||
await Bun.sleep(400); // let the sheet finish sliding in
|
||||
await b.screenshot({ path: join(SHOTS, 'bots-5-yacht-result-phone.png') });
|
||||
console.log(` yacht result: ${ranks.map((r, i) => `${r} ${scores[i]}`).join(', ')}`);
|
||||
|
||||
@@ -176,6 +176,46 @@ try {
|
||||
assert((await card.count()) === 0, 'dismissed card came back');
|
||||
await ios.close();
|
||||
});
|
||||
|
||||
await step('사이트 업데이트: 상단 팝업 → ✕로 닫으면 다음 업데이트까지 안 보임 → 새로고침', async () => {
|
||||
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR', serviceWorkers: 'block' });
|
||||
const p = await ctx.newPage();
|
||||
const errors: string[] = [];
|
||||
p.on('pageerror', (e) => errors.push(e.message));
|
||||
let served: string | null = null;
|
||||
await p.route('**/api/version', (r) => (served ? r.fulfill({ json: { build: served } }) : r.continue()));
|
||||
const banner = p.getByRole('alert').filter({ hasText: '업데이트 내용이 있습니다.' });
|
||||
const look = () => p.evaluate(() => document.dispatchEvent(new Event('visibilitychange')));
|
||||
await p.goto(ORIGIN);
|
||||
await p.getByText('게임 고르기').waitFor();
|
||||
const mine = await p.locator('meta[name="bg-build"]').getAttribute('content');
|
||||
assert(mine && mine === (await (await fetch(`${ORIGIN}/api/version`)).json()).build, `page build ${mine} ≠ server build`);
|
||||
await look();
|
||||
await p.waitForTimeout(300);
|
||||
assert((await banner.count()) === 0, 'banner without an update');
|
||||
served = 'ffffffffffff';
|
||||
await look();
|
||||
await banner.waitFor();
|
||||
await p.waitForTimeout(400); // slide-in finished
|
||||
await axe(p, 'update banner');
|
||||
await p.screenshot({ path: join(SHOTS, 'pwa-5-update-banner.png') });
|
||||
await banner.getByRole('button', { name: '업데이트 알림 닫기' }).click();
|
||||
await banner.waitFor({ state: 'detached' });
|
||||
await look();
|
||||
await p.waitForTimeout(300);
|
||||
assert((await banner.count()) === 0, 'closed banner came back for the same update');
|
||||
served = 'eeeeeeeeeeee';
|
||||
await look();
|
||||
await banner.waitFor();
|
||||
served = null;
|
||||
await Promise.all([p.waitForEvent('load'), banner.getByRole('button', { name: '지금 새로고침하기' }).click()]);
|
||||
await p.getByText('게임 고르기').waitFor();
|
||||
await look();
|
||||
await p.waitForTimeout(300);
|
||||
assert((await banner.count()) === 0, 'banner after refreshing to the current build');
|
||||
assert(!errors.length, errors.join(' / '));
|
||||
await ctx.close();
|
||||
});
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
console.error(e);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
".": "./src/index.ts",
|
||||
"./rummikub/rules": "./src/rummikub/rules.ts",
|
||||
"./marble/board": "./src/marble/board.ts",
|
||||
"./bots/luck": "./src/bots/luck.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -51,9 +51,9 @@ test('decideBotAction returns null when the bot has nothing to do', () => {
|
||||
|
||||
describe('levels (docs/09 §9.1)', () => {
|
||||
const BOARD = ['omok', 'chess', 'janggi', 'othello', 'baduk'];
|
||||
test.each(BOARD)('%s: easy and hard computers still finish a game against each other', (id) => {
|
||||
test.each(BOARD)('%s: the weakest and strongest computers still finish a game against each other', (id) => {
|
||||
const def = GAMES[id]!;
|
||||
for (const level of ['easy', 'hard'] as const) {
|
||||
for (const level of [1, 60]) {
|
||||
const r = botPlayout(def, { players: seats(2, 0), seed: seedN(7), isBot, maxSteps: 30_000, level });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
|
||||
@@ -32,7 +32,8 @@ import { ninetyNineBot } from '../ninety-nine/bot';
|
||||
import { mafiaBot } from '../mafia/bot';
|
||||
|
||||
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
|
||||
export { BOT_LEVEL_ODDS, botDraw, botPace, botPersona, hash01, levelOf, type BotLevel, type BotPersona } from './persona';
|
||||
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
|
||||
export { botPlay } from './policy';
|
||||
|
||||
/** Strategy per bot-enabled game (must match `BOT_GAMES` in @bg/shared). */
|
||||
export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/** Computer levels and human-like choices (docs/09-game-engine.md §9.1). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, secureRandom, seedN } from '@bg/engine';
|
||||
import { BOT_PLAY, humanBest } from './policy';
|
||||
import { BOT_LEVEL_ODDS, botDraw, botPersona, levelOf, type BotLevel } from './persona';
|
||||
import { BOT_PLAY_ANCHORS, botPlay, humanBest } from './policy';
|
||||
import { botDraw, botPersona, idLevel, type BotLevel } from './persona';
|
||||
|
||||
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
const fakeUlid = (r: () => number) => '01J' + Array.from({ length: 23 }, () => CROCKFORD[Math.floor(r() * 32)]).join('');
|
||||
@@ -21,30 +21,47 @@ describe('secureRandom', () => {
|
||||
});
|
||||
|
||||
describe('bot level', () => {
|
||||
test('the roll comes from the id’s random characters and keeps the level for the same id', () => {
|
||||
test('a computer without a saved level gets one from its id’s random characters, the same every time', () => {
|
||||
const id = `bot:2:${fakeUlid(secureRandom)}`;
|
||||
expect(botPersona(id)).toEqual(botPersona(id));
|
||||
expect(idLevel(id)).toBe(idLevel(id));
|
||||
expect(botDraw('bot:1:01J0000000000000000000000Z')).toBe(0);
|
||||
expect(botDraw('bot:1:01J0000000ZZZZZZ0000000000')).toBeCloseTo(1, 6);
|
||||
expect(idLevel('bot:1:01J0000000000000000000000Z')).toBe(1);
|
||||
expect(idLevel('bot:1:01J0000000ZZZZZZ0000000000')).toBe(60);
|
||||
});
|
||||
|
||||
test('levels come out at the documented odds; 똑똑한 편 is half, every 쉬움 허술, every 어려움 똑똑', () => {
|
||||
test('id levels are uniform over 1~60; 똑똑한 편 (start above 30) is half', () => {
|
||||
const rng = SeededRng.fromSeed(seedN(3));
|
||||
const n = 40_000;
|
||||
const count: Record<BotLevel, number> = { easy: 0, normal: 0, hard: 0 };
|
||||
const n = 60_000;
|
||||
const bands = [0, 0, 0];
|
||||
let smart = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const p = botPersona(`bot:${(i % 7) + 1}:${fakeUlid(() => rng.next())}`);
|
||||
count[p.level]++;
|
||||
if (p.smart) smart++;
|
||||
if (p.level === 'easy') expect(p.smart).toBe(false);
|
||||
if (p.level === 'hard') expect(p.smart).toBe(true);
|
||||
const id = `bot:${(i % 7) + 1}:${fakeUlid(() => rng.next())}`;
|
||||
const level = idLevel(id);
|
||||
expect(level >= 1 && level <= 60).toBe(true);
|
||||
bands[Math.floor((level - 1) / 20)]!++;
|
||||
if (botPersona(id).smart) smart++;
|
||||
}
|
||||
for (const level of ['easy', 'normal', 'hard'] as const) expect(Math.abs(count[level] / n - BOT_LEVEL_ODDS[level])).toBeLessThan(0.015);
|
||||
for (const b of bands) expect(Math.abs(b / n - 1 / 3)).toBeLessThan(0.015);
|
||||
expect(Math.abs(smart / n - 0.5)).toBeLessThan(0.015);
|
||||
expect(levelOf(0.3499)).toBe('easy');
|
||||
expect(levelOf(0.35)).toBe('normal');
|
||||
expect(levelOf(0.75)).toBe('hard');
|
||||
expect(botPersona('bot:1:x', 30).smart).toBe(false);
|
||||
expect(botPersona('bot:1:x', 31).smart).toBe(true);
|
||||
});
|
||||
|
||||
test('play settings move steadily from level 1 to 60 and hit the anchors', () => {
|
||||
for (const [level, play] of BOT_PLAY_ANCHORS) {
|
||||
const p = botPlay(level);
|
||||
for (const k of ['slip', 'window', 'lapse', 'miss'] as const) expect(p[k]).toBeCloseTo(play[k], 9);
|
||||
}
|
||||
for (let l = 2; l <= 60; l++) {
|
||||
const a = botPlay(l - 1);
|
||||
const b = botPlay(l);
|
||||
expect(b.slip).toBeLessThanOrEqual(a.slip);
|
||||
expect(b.lapse).toBeLessThanOrEqual(a.lapse);
|
||||
expect(b.miss).toBeLessThanOrEqual(a.miss);
|
||||
}
|
||||
expect(botPlay(0)).toEqual(botPlay(1));
|
||||
expect(botPlay(99)).toEqual(botPlay(60));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,24 +87,29 @@ describe('humanBest', () => {
|
||||
});
|
||||
|
||||
test('stronger levels play the best move more often and never pick a move far worse than a lapse allows', () => {
|
||||
const easy = share('easy');
|
||||
const normal = share('normal');
|
||||
const hard = share('hard');
|
||||
const weakest = share(1);
|
||||
const easy = share(10);
|
||||
const normal = share(30);
|
||||
const hard = share(50);
|
||||
const strongest = share(60);
|
||||
expect(weakest.best!).toBeLessThan(easy.best!);
|
||||
expect(hard.best!).toBeLessThan(strongest.best!);
|
||||
expect(strongest.best!).toBeGreaterThan(0.96);
|
||||
expect(easy.best!).toBeLessThan(normal.best!);
|
||||
expect(normal.best!).toBeLessThan(hard.best!);
|
||||
expect(hard.best!).toBeGreaterThan(0.9);
|
||||
// "meh" (30 worse = 3 × small) is past every slip window (≤ 2 × small): only a lapse (8 × small) plays it.
|
||||
expect(hard.meh ?? 0).toBeLessThan(0.01);
|
||||
// 100 worse is beyond every window: never played.
|
||||
for (const s of [easy, normal, hard]) expect(s.blunder ?? 0).toBe(0);
|
||||
for (const s of [weakest, easy, normal, hard, strongest]) expect(s.blunder ?? 0).toBe(0);
|
||||
// Close alternative: roughly slip share of the time.
|
||||
expect(Math.abs((normal.close ?? 0) - (BOT_PLAY.normal.slip + BOT_PLAY.normal.lapse / 2))).toBeLessThan(0.03);
|
||||
expect(Math.abs((normal.close ?? 0) - (botPlay(30).slip + botPlay(30).lapse / 2))).toBeLessThan(0.03);
|
||||
});
|
||||
|
||||
test('a must-play move (≥ critical) is missed only at the documented rate', () => {
|
||||
const v = { ...value, best: 5000 };
|
||||
expect(share('hard', moves, v).best).toBe(1);
|
||||
expect(Math.abs(1 - share('normal', moves, v).best! - BOT_PLAY.normal.miss)).toBeLessThan(0.01);
|
||||
expect(Math.abs(1 - share('easy', moves, v).best! - BOT_PLAY.easy.miss)).toBeLessThan(0.015);
|
||||
expect(share(50, moves, v).best).toBe(1);
|
||||
expect(share(60, moves, v).best).toBe(1);
|
||||
for (const level of [1, 10, 30, 41]) expect(Math.abs(1 - share(level, moves, v).best! - botPlay(level).miss)).toBeLessThan(0.015);
|
||||
});
|
||||
});
|
||||
|
||||
81
packages/games/src/bots/luck.test.ts
Normal file
81
packages/games/src/bots/luck.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
/** Computers' luck: choosing the shuffle (docs/04 §5.1, docs/09 §9.1). */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, seedN, type ChaChaSeed } from '@bg/engine';
|
||||
import { GAMES } from '../index';
|
||||
import { BOT_STRATEGIES } from './index';
|
||||
import { chooseLuckySeed, luckApplies, playOutScores, shufflesFor, type LuckJob } from './luck';
|
||||
|
||||
const words = (r: SeededRng) => Array.from({ length: 8 }, () => Math.floor(r.next() * 2 ** 32) >>> 0) as ChaChaSeed;
|
||||
|
||||
function setup(n: number) {
|
||||
const r = SeededRng.fromSeed(seedN(n));
|
||||
return { makeSeed: () => words(r), random: () => r.next() };
|
||||
}
|
||||
|
||||
const job = (gameId: string, luck: Record<string, number>, players = ['human', 'bot:1:a']): LuckJob => ({
|
||||
gameId,
|
||||
players,
|
||||
options: GAMES[gameId]!.defaultOptions,
|
||||
now: 1_700_000_000_000,
|
||||
gameNo: 1,
|
||||
luck,
|
||||
levels: { 'bot:1:a': 30 },
|
||||
budgetMs: 60_000,
|
||||
});
|
||||
|
||||
describe('luck', () => {
|
||||
test('how many shuffles: none near 0, up to 5 at ±1, the strongest luck at the table counts', () => {
|
||||
expect(shufflesFor([])).toBe(1);
|
||||
expect(shufflesFor([0.1, -0.12])).toBe(1);
|
||||
expect(shufflesFor([0.5])).toBe(3);
|
||||
expect(shufflesFor([-1])).toBe(5);
|
||||
expect(shufflesFor([0.2, -0.9])).toBe(5);
|
||||
});
|
||||
|
||||
test('luck is for games with cards, tiles, dice or hidden roles — not for board games', () => {
|
||||
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'mafia', 'dobble']) expect(luckApplies(id)).toBe(false);
|
||||
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor'].includes(g))) {
|
||||
expect(luckApplies(id)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('tries one shuffle without luck or in a board game, more with luck, and keeps one of them', () => {
|
||||
const { makeSeed, random } = setup(1);
|
||||
expect(chooseLuckySeed(GAMES['one-card']!, job('one-card', { 'bot:1:a': 0 }), makeSeed, random).tried).toBe(1);
|
||||
expect(chooseLuckySeed(GAMES.omok!, job('omok', { 'bot:1:a': 1 }), makeSeed, random).tried).toBe(1);
|
||||
const made: string[] = [];
|
||||
const tracked = () => {
|
||||
const s = makeSeed();
|
||||
made.push(s.join(','));
|
||||
return s;
|
||||
};
|
||||
const r = chooseLuckySeed(GAMES['one-card']!, job('one-card', { 'bot:1:a': -1 }), tracked, random);
|
||||
expect(r.tried).toBe(5);
|
||||
expect(made).toHaveLength(5);
|
||||
expect(made).toContain(r.seed.join(','));
|
||||
});
|
||||
|
||||
test('a played-out game gives every player a place score in [0, 1]', () => {
|
||||
const { makeSeed, random } = setup(2);
|
||||
const s = playOutScores(GAMES['one-card']!, { ...job('one-card', {}, ['a', 'b', 'c']), seed: makeSeed(), random });
|
||||
expect(s).not.toBeNull();
|
||||
expect(Object.keys(s!).sort()).toEqual(['a', 'b', 'c']);
|
||||
for (const v of Object.values(s!)) expect(v >= 0 && v <= 1).toBe(true);
|
||||
});
|
||||
|
||||
test('lucky computers do better than unlucky ones (원카드, 1:1)', () => {
|
||||
const { makeSeed, random } = setup(3);
|
||||
const def = GAMES['one-card']!;
|
||||
const mean = (luck: number) => {
|
||||
let sum = 0;
|
||||
const n = 50;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const { seed } = chooseLuckySeed(def, job('one-card', { 'bot:1:a': luck }), makeSeed, random);
|
||||
// The real game: the same deal, but every choice made afresh.
|
||||
sum += playOutScores(def, { ...job('one-card', {}), seed, random })?.['bot:1:a'] ?? 0.5;
|
||||
}
|
||||
return sum / n;
|
||||
};
|
||||
expect(mean(1) - mean(-1)).toBeGreaterThan(0.15);
|
||||
});
|
||||
});
|
||||
123
packages/games/src/bots/luck.ts
Normal file
123
packages/games/src/bots/luck.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Computers' luck (docs/04-stability-security.md §5.1, docs/09-game-engine.md §9.1). Before a game with computers the
|
||||
* server may try a few shuffles (seeds) instead of one: each is played out once to the end by computers in every
|
||||
* seat, and the one that suits the computers' luck best is kept — a lucky computer tends to get the deal it did well
|
||||
* with, an unlucky one the deal it did badly with. The kept seed's hash is published before the first move as always,
|
||||
* so nothing changes during the game. Board games without dice or cards are left alone.
|
||||
*/
|
||||
import { SeededRng, type AnyGameDefinition, type ChaChaSeed, type PlayerId } from '@bg/engine';
|
||||
import { BOT_STRATEGIES, decideBotAction } from './index';
|
||||
import type { BotLevel } from './persona';
|
||||
|
||||
/** Games where everything is in view from the start: a shuffle only decides who goes first, so luck stays out. */
|
||||
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor']);
|
||||
|
||||
export const luckApplies = (gameId: string): boolean => gameId in BOT_STRATEGIES && !NO_LUCK.has(gameId);
|
||||
|
||||
/** Most shuffles tried for the luckiest (or unluckiest) computer, luck ±1. */
|
||||
export const MAX_SHUFFLES = 5;
|
||||
|
||||
/** Shuffles to try: 1 (no choice) for luck near 0, up to `MAX_SHUFFLES` for ±1; the strongest luck at the table counts. */
|
||||
export function shufflesFor(lucks: readonly number[]): number {
|
||||
const m = Math.max(0, ...lucks.map((l) => Math.min(1, Math.abs(l))));
|
||||
return 1 + Math.round(m * (MAX_SHUFFLES - 1));
|
||||
}
|
||||
|
||||
/** Simulated players stand in for people at this level. */
|
||||
const PERSON_LEVEL = 30;
|
||||
|
||||
/**
|
||||
* Plays the game from `seed` to the end with a computer in every seat (`levels[p]`, people as level 30) and returns
|
||||
* each player's place as a score in [0, 1] (1 = first, 0 = last, ties share), or null if it didn't finish.
|
||||
*/
|
||||
export function playOutScores(
|
||||
def: AnyGameDefinition,
|
||||
input: { players: PlayerId[]; options: unknown; seed: ChaChaSeed; now: number; gameNo: number; levels: Record<PlayerId, BotLevel>; random: () => number; maxSteps?: number },
|
||||
): Record<PlayerId, number> | null {
|
||||
const { players, random } = input;
|
||||
const rng = SeededRng.fromSeed(input.seed);
|
||||
let now = input.now;
|
||||
let state = def.setup({ players, options: input.options, rng, now, gameNo: input.gameNo });
|
||||
const maxSteps = input.maxSteps ?? 20_000;
|
||||
for (let step = 0; step < maxSteps; step++) {
|
||||
const result = def.result(state);
|
||||
if (result) {
|
||||
const out: Record<PlayerId, number> = {};
|
||||
let at = 0;
|
||||
for (const group of result.ranking) {
|
||||
const place = at + (group.length - 1) / 2;
|
||||
for (const p of group) out[p] = players.length > 1 ? 1 - place / (players.length - 1) : 1;
|
||||
at += group.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
now += 500;
|
||||
const waiting = [...new Set([...def.activePlayers(state), ...(def.timeoutPlayers?.(state) ?? [])])];
|
||||
let acted = false;
|
||||
for (const p of waiting) {
|
||||
const action = decideBotAction(def, state, p, { now, random, level: input.levels[p] ?? PERSON_LEVEL });
|
||||
if (action === null) continue;
|
||||
state = def.apply(state, p, action, { rng, now }).state;
|
||||
acted = true;
|
||||
break;
|
||||
}
|
||||
if (acted) continue;
|
||||
// Nobody can move: let the clock run out like the room timer would.
|
||||
const timed = def.timeoutPlayers ? def.timeoutPlayers(state) : def.activePlayers(state);
|
||||
const who = timed[0] ?? waiting[0];
|
||||
if (!who) return null;
|
||||
now = Math.max(now, def.deadline?.(state) ?? now);
|
||||
state = def.apply(state, who, def.onTimeout(state, who), { rng, now }).state;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface LuckJob {
|
||||
gameId: string;
|
||||
players: PlayerId[];
|
||||
options: unknown;
|
||||
now: number;
|
||||
gameNo: number;
|
||||
/** Each computer's luck in [-1, 1]; people are not listed. */
|
||||
luck: Record<PlayerId, number>;
|
||||
levels: Record<PlayerId, BotLevel>;
|
||||
/** Stop trying more shuffles after this long (the first one is always played out). */
|
||||
budgetMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the seed for a game: `shufflesFor(luck)` fresh seeds from `makeSeed`, each played out once; keeps the one with
|
||||
* the highest Σ luck × score over the computers. Returns the seed and how many were tried.
|
||||
*/
|
||||
export function chooseLuckySeed(
|
||||
def: AnyGameDefinition,
|
||||
job: LuckJob,
|
||||
makeSeed: () => ChaChaSeed,
|
||||
random: () => number,
|
||||
): { seed: ChaChaSeed; tried: number } {
|
||||
const want = luckApplies(def.id) ? shufflesFor(Object.values(job.luck)) : 1;
|
||||
let best = makeSeed();
|
||||
if (want <= 1) return { seed: best, tried: 1 };
|
||||
const t0 = performance.now();
|
||||
let bestValue = -Infinity;
|
||||
let tried = 0;
|
||||
for (let i = 0; i < want; i++) {
|
||||
if (i > 0 && performance.now() - t0 > job.budgetMs) break;
|
||||
const seed = i === 0 ? best : makeSeed();
|
||||
tried++;
|
||||
let scores: Record<PlayerId, number> | null = null;
|
||||
try {
|
||||
scores = playOutScores(def, { ...job, seed, random });
|
||||
} catch {
|
||||
scores = null;
|
||||
}
|
||||
if (!scores) continue;
|
||||
let value = 0;
|
||||
for (const [bot, luck] of Object.entries(job.luck)) value += luck * (scores[bot] ?? 0.5);
|
||||
if (value > bestValue) {
|
||||
bestValue = value;
|
||||
best = seed;
|
||||
}
|
||||
}
|
||||
return { seed: best, tried };
|
||||
}
|
||||
@@ -18,18 +18,18 @@ export function botPace(bot: string): number {
|
||||
return 0.7 + ((h >>> 0) / 2 ** 32) * 0.8;
|
||||
}
|
||||
|
||||
/** How well a computer plays (docs/09-game-engine.md §9.1). */
|
||||
export type BotLevel = 'easy' | 'normal' | 'hard';
|
||||
|
||||
/** Share of computers at each level: 쉬움 35%, 보통 40%, 어려움 25%. */
|
||||
export const BOT_LEVEL_ODDS: Readonly<Record<BotLevel, number>> = { easy: 0.35, normal: 0.4, hard: 0.25 };
|
||||
/**
|
||||
* How well a computer plays: level 1 (weakest) … 60 (strongest), docs/09-game-engine.md §9.1. 1~20 쉬움, 21~40 보통,
|
||||
* 41~60 어려움. The room keeps each computer's level (it drifts a little between games); see `botPlay`.
|
||||
*/
|
||||
export type BotLevel = number;
|
||||
|
||||
const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
|
||||
/**
|
||||
* The computer's own die roll in [0, 1), read straight from the random part of its id: the server makes bot ids as
|
||||
* `bot:<n>:<ULID>` with OS secure randomness (`secureRandom`), so the first 6 random characters are 30 uniform bits.
|
||||
* Other ids (tests, hand-made) fall back to a hash. Fixed for the id, so the computer keeps its level after a restart.
|
||||
* A fixed roll in [0, 1) for a bot id: the server makes bot ids as `bot:<n>:<ULID>` with OS secure randomness
|
||||
* (`secureRandom`), so the first 6 random characters are 30 uniform bits. Other ids (tests, hand-made) fall back to a
|
||||
* hash. Only used for computers saved before rooms kept a level per computer (and in tests).
|
||||
*/
|
||||
export function botDraw(bot: string): number {
|
||||
const u = bot.split(':')[2] ?? '';
|
||||
@@ -39,17 +39,13 @@ export function botDraw(bot: string): number {
|
||||
return v / 32 ** 6;
|
||||
}
|
||||
|
||||
export function levelOf(draw: number): BotLevel {
|
||||
if (draw < BOT_LEVEL_ODDS.easy) return 'easy';
|
||||
return draw < BOT_LEVEL_ODDS.easy + BOT_LEVEL_ODDS.normal ? 'normal' : 'hard';
|
||||
}
|
||||
/** Level 1~60 from the id alone, for computers without a saved level. */
|
||||
export const idLevel = (bot: string): BotLevel => 1 + Math.floor(botDraw(bot) * 60);
|
||||
|
||||
export interface BotPersona {
|
||||
/** 쉬움 / 보통 / 어려움: how often it slips in board games (`humanBest`). */
|
||||
level: BotLevel;
|
||||
/**
|
||||
* 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): half of the computers each, by the
|
||||
* same roll as the level — every 쉬움 is 허술, every 어려움 똑똑, 보통 split in two.
|
||||
* 똑똑한 편(근거를 보고 추리, 존댓말) / 허술한 편(느낌과 분위기를 따름, 반말): the computer's starting level is
|
||||
* above 30 (the upper half of 보통 and every 어려움) or not, so a random computer is either with even odds.
|
||||
*/
|
||||
smart: boolean;
|
||||
/** Reaction speed multiplier (`botPace`): 0.7 quick … 1.5 slow. */
|
||||
@@ -58,7 +54,7 @@ export interface BotPersona {
|
||||
chatty: number;
|
||||
}
|
||||
|
||||
export function botPersona(bot: string): BotPersona {
|
||||
const draw = botDraw(bot);
|
||||
return { level: levelOf(draw), smart: draw >= 0.5, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
/** `base` = the level the computer started with (the room's), or one from the id. */
|
||||
export function botPersona(bot: string, base: BotLevel = idLevel(bot)): BotPersona {
|
||||
return { smart: base > 30, pace: botPace(bot), chatty: 0.5 + hash01(bot, 'chatty') * 0.5 };
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export function best<A>(xs: readonly A[], score: (a: A) => number, random: () =>
|
||||
return pick(top.length ? top : xs, random);
|
||||
}
|
||||
|
||||
/** How each level slips (docs/09-game-engine.md §9.1). */
|
||||
/** How a level slips (docs/09-game-engine.md §9.1). */
|
||||
export interface BotPlay {
|
||||
/** Chance per move of a small inaccuracy: a move almost as good (within `window` × the game's `small`). */
|
||||
slip: number;
|
||||
@@ -42,11 +42,28 @@ export interface BotPlay {
|
||||
miss: number;
|
||||
}
|
||||
|
||||
export const BOT_PLAY: Readonly<Record<BotLevel, BotPlay>> = {
|
||||
easy: { slip: 0.35, window: 2, lapse: 0.06, miss: 0.12 },
|
||||
normal: { slip: 0.2, window: 1, lapse: 0.02, miss: 0.03 },
|
||||
hard: { slip: 0.08, window: 0.5, lapse: 0.005, miss: 0 },
|
||||
};
|
||||
/**
|
||||
* Anchor levels; levels in between are interpolated. The middle of each band plays like the old three levels:
|
||||
* 10 = 쉬움, 30 = 보통, 50 = 어려움. Level 1 slips the most, level 60 almost never.
|
||||
*/
|
||||
export const BOT_PLAY_ANCHORS: readonly (readonly [number, BotPlay])[] = [
|
||||
[1, { slip: 0.45, window: 3, lapse: 0.1, miss: 0.2 }],
|
||||
[10, { slip: 0.35, window: 2, lapse: 0.06, miss: 0.12 }],
|
||||
[30, { slip: 0.2, window: 1, lapse: 0.02, miss: 0.03 }],
|
||||
[50, { slip: 0.08, window: 0.5, lapse: 0.005, miss: 0 }],
|
||||
[60, { slip: 0.03, window: 0.25, lapse: 0, miss: 0 }],
|
||||
];
|
||||
|
||||
export function botPlay(level: BotLevel): BotPlay {
|
||||
const L = Math.min(Math.max(level, 1), 60);
|
||||
let i = 0;
|
||||
while (i < BOT_PLAY_ANCHORS.length - 2 && L > BOT_PLAY_ANCHORS[i + 1]![0]) i++;
|
||||
const [l0, a] = BOT_PLAY_ANCHORS[i]!;
|
||||
const [l1, b] = BOT_PLAY_ANCHORS[i + 1]!;
|
||||
const t = (L - l0) / (l1 - l0);
|
||||
const mix = (k: keyof BotPlay) => a[k] + (b[k] - a[k]) * t;
|
||||
return { slip: mix('slip'), window: mix('window'), lapse: mix('lapse'), miss: mix('miss') };
|
||||
}
|
||||
|
||||
export const LAPSE_WINDOW = 8;
|
||||
|
||||
@@ -63,12 +80,12 @@ export function humanBest<A>(
|
||||
level: BotLevel | undefined,
|
||||
scale: { small: number; critical: number },
|
||||
): A {
|
||||
if (!level || xs.length < 2) return best(xs, score, random);
|
||||
if (level === undefined || xs.length < 2) return best(xs, score, random);
|
||||
const scored = xs.map((a) => ({ a, s: score(a) }));
|
||||
const topScore = Math.max(...scored.map((x) => x.s));
|
||||
const top = pick(scored.filter((x) => x.s === topScore), random).a;
|
||||
const rest = scored.filter((x) => x.a !== top).sort((x, y) => y.s - x.s);
|
||||
const play = BOT_PLAY[level];
|
||||
const play = botPlay(level);
|
||||
const r = random();
|
||||
if (topScore >= scale.critical) {
|
||||
if (r >= play.miss) return top;
|
||||
|
||||
@@ -88,7 +88,7 @@ describe('whole games', () => {
|
||||
players: seats(7, 0),
|
||||
seed: seedN(s),
|
||||
isBot,
|
||||
personaOf: (p, st): BotPersona => ({ level: 'normal', smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
|
||||
personaOf: (p, st): BotPersona => ({ smart: roleOf(st, p) === 'mafia' ? mafiaSmart : townSmart, pace: botPace(p), chatty: 0.8 }),
|
||||
});
|
||||
if ((r.state as MafiaState).winner === 'town') town++;
|
||||
}
|
||||
@@ -128,8 +128,8 @@ describe('timing and answers', () => {
|
||||
const { st, players } = toPhase('vote');
|
||||
const names = Object.fromEntries(players.map((p, i) => [p, i ? `컴퓨터 ${i + 1}` : '철수']));
|
||||
const bot = players[2]!;
|
||||
const quick = firstAction(st, bot, { level: 'hard', smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { level: 'hard', smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
const quick = firstAction(st, bot, { smart: true, pace: 0.7, chatty: 0.8 }, names, 'vote')!;
|
||||
const slow = firstAction(st, bot, { smart: true, pace: 1.5, chatty: 0.8 }, names, 'vote')!;
|
||||
expect(quick.at).toBeLessThan(slow.at);
|
||||
expect(slow.at).toBeLessThan(st.options.voteSeconds * 1000);
|
||||
});
|
||||
@@ -142,7 +142,7 @@ describe('timing and answers', () => {
|
||||
const memory: Record<string, unknown> = {};
|
||||
let answer: { text: string; at: number } | null = null;
|
||||
for (let t = now + 1000; t < now + 20_000 && !answer; ) {
|
||||
const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { level: 'hard', smart: true, pace: 1, chatty: 0.8 }, names, memory });
|
||||
const d = mafiaBot({ me: bot, view: mafia.view(asked, bot), now: t, random: Math.random, persona: { smart: true, pace: 1, chatty: 0.8 }, names, memory });
|
||||
const a = d.action as { type: string; text?: string } | null;
|
||||
if (a?.type === 'chat' && memory.done && Object.keys(memory.done as object).some((k) => k.includes(':r:'))) answer = { text: a.text!, at: t - now - 1000 };
|
||||
t += Math.max(50, d.next);
|
||||
|
||||
@@ -55,3 +55,30 @@ export const BOT_GAMES: readonly string[] = [
|
||||
export const PRACTICE_PLAYERS: Readonly<Record<string, number>> = { mafia: 6 };
|
||||
|
||||
export const botsAllowed = (gameId: string): boolean => BOT_GAMES.includes(gameId);
|
||||
|
||||
/**
|
||||
* Computer levels 1~60 (docs/09-game-engine.md §9.1): 1~20 쉬움, 21~40 보통, 41~60 어려움. The host can pick a band
|
||||
* for each computer after adding it; the exact level inside the band is drawn at random and stays hidden until the
|
||||
* game is over (fairness check).
|
||||
*/
|
||||
export const BOT_LEVEL_MAX = 60;
|
||||
export type BotBand = 'easy' | 'normal' | 'hard';
|
||||
export type BotPick = 'random' | BotBand;
|
||||
export const BOT_PICKS: readonly BotPick[] = ['random', 'easy', 'normal', 'hard'];
|
||||
export const BOT_BANDS: Readonly<Record<BotBand, readonly [number, number]>> = { easy: [1, 20], normal: [21, 40], hard: [41, 60] };
|
||||
export const BOT_PICK_LABEL: Readonly<Record<BotPick, string>> = { random: '랜덤', easy: '쉬움', normal: '보통', hard: '어려움' };
|
||||
|
||||
export function bandOf(level: number): BotBand {
|
||||
return level <= BOT_BANDS.easy[1] ? 'easy' : level <= BOT_BANDS.normal[1] ? 'normal' : 'hard';
|
||||
}
|
||||
|
||||
/**
|
||||
* Luck in [-1, 1] as people read it. A computer's luck decides how many shuffles the server tries before a game and
|
||||
* whether it keeps the best or the worst one for that computer (docs/04-stability-security.md §5.1).
|
||||
*/
|
||||
export function luckLabel(luck: number): string {
|
||||
if (luck <= -0.6) return '아주 나쁨';
|
||||
if (luck <= -0.2) return '나쁨';
|
||||
if (luck < 0.2) return '보통';
|
||||
return luck < 0.6 ? '좋음' : '아주 좋음';
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ export const ClientMessage = z.discriminatedUnion('t', [
|
||||
z.object({ t: z.literal('host'), userId }),
|
||||
z.object({ t: z.literal('addBot'), seat: z.number().int().min(0).max(31).optional() }),
|
||||
z.object({ t: z.literal('removeBot'), userId }),
|
||||
z.object({ t: z.literal('botLevel'), userId, pick: z.enum(['random', 'easy', 'normal', 'hard']) }),
|
||||
z.object({ t: z.literal('act'), cs: z.number().int().min(1), a: z.unknown() }),
|
||||
z.object({ t: z.literal('chat'), text: z.string().min(1).max(CHAT_MAX) }),
|
||||
z.object({ t: z.literal('emote'), id: z.string().max(20) }),
|
||||
|
||||
@@ -58,6 +58,14 @@ export interface RoomView {
|
||||
lastGamePk: string | null;
|
||||
/** Computers doing something people can see (docs/06 §12.1): "생각 중…" / "입력 중…". */
|
||||
botActivity?: Record<string, 'thinking' | 'typing'>;
|
||||
/** Difficulty the host picked for each computer (랜덤/쉬움/보통/어려움, docs/06 §12). */
|
||||
botPicks?: Record<string, 'random' | 'easy' | 'normal' | 'hard'>;
|
||||
/** Shuffling before the game started (computers' luck, docs/04 §5.1). */
|
||||
starting?: boolean;
|
||||
/** After a game with computers: each computer's level (1~60) and luck in that game, for the fairness check. */
|
||||
lastBots?: Record<string, { level: number; luck: number }>;
|
||||
/** How many shuffles were tried for the computers' luck in that game (1 = the first one, no choice). */
|
||||
lastShuffles?: number;
|
||||
}
|
||||
|
||||
export interface GameResultView {
|
||||
@@ -70,7 +78,7 @@ export interface GameResultView {
|
||||
}
|
||||
|
||||
export type ServerMessage =
|
||||
| { t: 'welcome'; me: PublicUser; serverTime: number; protocol: number; activeRoom: string | null }
|
||||
| { t: 'welcome'; me: PublicUser; serverTime: number; protocol: number; activeRoom: string | null; build?: string | null }
|
||||
| { t: 'room'; seq: number; room: RoomView }
|
||||
| {
|
||||
t: 'state';
|
||||
|
||||
Reference in New Issue
Block a user