컴퓨터 난이도 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:
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()) {
|
||||
|
||||
Reference in New Issue
Block a user