Files
joke-app/packages/games/src/bots/luck.test.ts
EJClaw b02c9870cf 새 게임 젬블로: 육각 보석 블록 땅따먹기(2~6명), 원작 인원별 구역·시작점과 5인 장애물, 변형 규칙을 방 설정으로
- 엔진 packages/games/src/gemblo/(board·options·types·index·bot): 463칸 판(3인 241·4인 295·듀오 157칸), 블록 18개 72칸(방향 74/뒤집기 포함 92개 미리 계산), 같은 색 변 맞댐 금지, 꼭짓점 이음선(한 블록이 사이 두 칸을 덮으면 막힘, 두 블록 틈은 통과), 놓을 곳 없는 색 자동 끝남, 남은 칸 점수·공동 순위
- 방 설정 §2 전부: 자리, 2명 2색/3색/듀오, 3명 1색/2색, 5명 장애물 자동/직접 고르기/없음, 이음선 막힘, 뒤집기(기본 허용), 점수(남은 칸/블로커스 보너스), 팀전(2명씩·3명씩), 금색 방해 블록 0/3/6, 이음점 표시, 시간(한 번당·피셔), 시간 초과 처리(자동 배치/넘김/끝), 연속 자동 한도, 무르기
- 합법 배치: 이음점 × 블록 × 방향 × 맞출 칸, (블록·방향·기준 칸) 도장으로 중복 제거, apply·legalActions 수 ms
- 컴퓨터: 큰 블록 + 내 이음점 늘리기 + 남의 이음점 막기 + 초반 가운데로, 상위 80개만 자세히, humanBest 1~60단계, 한 수 10ms 안팎
- 화면 apps/web/src/games/gemblo/: 납작한 육각 SVG 판(안 쓰는 칸 흐리게, 보석 색 + 색약용 무늬), 마우스 미리보기·휠/R 돌리기·F 뒤집기, 휴대폰 칸 누르기·끌어 옮기기·[놓기], 이음점을 누르면 그 점을 덮는 합법 배치를 차례로, 두 손가락 확대·이동과 [확대]/[전체], 키보드 조작, 5인 장애물 고르기·놓기, 무르기·기권, 끝나면 색별 남은 블록, 소리·애니메이션, 도움말·30초 요약
- 등록: GAMES·BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·GAME_ICON·판·주사위 탭, 운 제외(NO_LUCK), docs/games/README.md, docs/games/gemblo.md(구현 결정 13장)
- 테스트: 규칙 30개(문서 §10 전부, 5인 장애물 시드 100개, 클라이언트 판정 = validate 1만 개, 무작위 대국 11가지 모드), 컴퓨터 4개, 도움말 2개, 방 통합 2개(연습 한 판, 5명 직접 고르기 + 시간 초과만 하는 사람), e2e games.e2e.ts gemblo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:40:45 +09:00

82 lines
3.4 KiB
TypeScript

/** 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', 'connect-four', 'mafia', 'dobble', 'gemblo']) expect(luckApplies(id)).toBe(false);
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four', 'gemblo'].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);
});
});