Files
joke-app/apps/server/src/rooms/bot-level.room.test.ts
EJClaw 84d64b27f2 컴퓨터 난이도 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>
2026-10-11 17:46:13 +09:00

239 lines
10 KiB
TypeScript

/** 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']);
});
});