야단법석 달리기(Magical Athlete): 규칙·컴퓨터 상대·화면·도움말·문서·E2E

- 규칙 모듈 packages/games/src/magical-athlete: 선수 24명(능력 처리 순서가 하나로 정해지는 선수만),
  뱀 순서 뽑기(2~3명은 선수 8명·경주마다 둘, 4~6명은 4명·하나), 몰래 동시에 출전 선수 고르기,
  경주 4번(순한 판·거친 판 번갈아, 거친 판은 화살표·돌·별 칸), 1등 3점·2등 1점(갈수록 커지는 점수표 옵션).
  능력 처리 순서 고정: 칸 효과 → 차례인 사람 → 시계 방향, 연쇄는 줄 끝, 선수당 한 차례 5번, 두 번째 도착 즉시 종료,
  경주 차례 상한. 시간 초과는 안전한 기본값(능력 안 씀), 나간 사람 선수는 자동으로 끝까지.
- 컴퓨터: 평가값 뽑기, 칸 수 기대 이득으로 능력 판단, 레벨별 실수.
- 화면: 뱀 모양 경주로 SVG(PC 11칸·휴대폰 8칸 줄), 말 이동 애니메이션, 능력 버튼, 경주 기록, 결과 표,
  도움말·30초 요약. 판이 화면보다 길면 위에서 시작(가운데 정렬이면 위가 잘려 고르기 카드를 못 누름).
- 등록(GAMES, CATALOG, BOT_GAMES, BOT_STRATEGIES, 화면 레지스트리, 아이콘·판 탭), 문서 docs/games/magical-athlete.md.
- 테스트: 규칙·능력·순서 42개(문서 예시 포함), 컴퓨터 10개, 도움말 2개, 방 통합 2개(컴퓨터 1·3명과 끝까지),
  E2E(PC 방장 + 휴대폰, 실제 뽑기·고르기·굴리기·능력으로 네 경주 끝까지).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 03:45:09 +09:00
parent 65c56d3ae7
commit 71381087cc
23 changed files with 4019 additions and 2 deletions

View File

@@ -10,6 +10,7 @@
"./clue/board": "./src/clue/board.ts",
"./bots/luck": "./src/bots/luck.ts",
"./liar/topics": "./src/liar/topics.ts",
"./magical-athlete/racers": "./src/magical-athlete/racers.ts",
"./*": "./src/*/index.ts"
},
"dependencies": {

View File

@@ -36,6 +36,7 @@ import { clueBot } from '../clue/bot';
import { connectFourBot } from '../connect-four/bot';
import { unoBot } from '../uno/bot';
import { liarBot } from '../liar/bot';
import { magicalAthleteBot } from '../magical-athlete/bot';
export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -69,6 +70,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
'connect-four': connectFourBot,
'old-maid': oldMaidBot,
uno: unoBot,
'magical-athlete': magicalAthleteBot,
};
/** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */

View File

@@ -31,6 +31,7 @@ import { clue } from './clue';
import { connectFour } from './connect-four';
import { uno } from './uno';
import { liar } from './liar';
import { magicalAthlete } from './magical-athlete';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -65,4 +66,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[connectFour.id]: connectFour,
[uno.id]: uno,
[liar.id]: liar,
[magicalAthlete.id]: magicalAthlete,
};

View File

@@ -0,0 +1,134 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN, type PlayerId, type Rng } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { randomPolicy } from '../bots/policy';
import { magicalAthlete as def, type MagicalAthleteState, type RaceState, type RacerId } from './index';
import { Runner } from './race';
const isBot = (p: string) => p.startsWith('bot');
function dice(...faces: number[]): Rng {
const q = [...faces];
return { next: () => 0, int: () => q.shift()! - 1, shuffle: <T,>(a: readonly T[]) => [...a] };
}
/** 'bot' owns the first racer and is about to act with it; the rest belong to B, C, … */
function race(specs: { id: RacerId; pos?: number; owner?: PlayerId }[], opts: Record<string, unknown> = {}): MagicalAthleteState {
const owners = specs.map((sp, i) => sp.owner ?? (i === 0 ? 'bot' : String.fromCharCode(65 + i)));
const players = [...new Set(owners)];
const s = def.setup({ players, options: def.optionsSchema.parse({ twoRacers: 'off', ...opts }), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
s.phase = 'race';
s.draft = null;
s.raceNo = 4;
const r: RaceState = {
no: 4,
side: 'mild',
racers: specs.map((sp, i) => ({ id: sp.id, owner: owners[i]!, pos: sp.pos ?? 0, status: 'run', tripped: false, place: null })),
seat: 0,
pending: [],
cur: null,
step: 'roll',
roll: null,
turnStartPos: 0,
skipperNext: false,
cancelMain: false,
turns: 0,
fired: {},
loserPts: 0,
sisyphusPts: 0,
finishers: [],
capped: false,
bonus: {},
log: [],
logSeq: 0,
};
s.race = r;
new Runner(s, dice(), []).startRacerTurn(specs[0]!.id);
return s;
}
const decide = (s: MagicalAthleteState, level?: number) => decideBotAction(def, s, 'bot', { now: 1, random: () => 0.5, ...(level ? { level } : {}) });
const roll = (s: MagicalAthleteState, face: number) => def.apply(s, 'bot', { type: 'ROLL' }, { rng: dice(face), now: 1 }).state;
describe('magical-athlete bot', () => {
test('뽑기: 평가값이 가장 높은 선수', () => {
const s = def.setup({ players: ['bot', 'B', 'C', 'D'], options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
s.draftStart = 0;
s.draft = { round: 1, rounds: 2, line: ['coach', 'legs', 'banana', 'hugebaby', 'gunk', 'alchemist', 'inchworm', 'lackey'], order: [0, 1, 2, 3, 3, 2, 1, 0], at: 0 };
expect(decide(s)).toEqual({ type: 'DRAFT', racer: 'legs' });
});
test('출전: 같은 점수표면 강한 선수부터, 갈수록 커지면 첫 경주에는 약한 선수', () => {
for (const [scoring, want] of [
['flat', 'flipflop'],
['rising', 'coach'],
] as const) {
const s = def.setup({ players: ['bot', 'B', 'C', 'D'], options: def.optionsSchema.parse({ scoring }), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
Object.assign(s, { phase: 'select', draft: null });
s.teams.bot = ['coach', 'flipflop', 'banana', 'gunk'];
expect(decide(s)).toEqual({ type: 'SELECT', racers: [want] });
}
});
test('롱다리: 보통은 5칸, 깐깐이 앞에서 넘치면 굴려요', () => {
expect(decide(race([{ id: 'legs', pos: 3 }, { id: 'banana', pos: 10 }]))).toEqual({ type: 'CHOOSE', key: 'use' });
expect(decide(race([{ id: 'legs', pos: 26 }, { id: 'stickler', pos: 10 }]))).toEqual({ type: 'ROLL' });
expect(decide(race([{ id: 'legs', pos: 25 }, { id: 'stickler', pos: 10 }]))).toEqual({ type: 'CHOOSE', key: 'use' });
});
test('마술사: 낮은 눈은 다시, 높은 눈은 그대로', () => {
const s = race([{ id: 'magician' }, { id: 'banana', pos: 10 }]);
expect(decide(roll(s, 1))).toEqual({ type: 'CHOOSE', key: 'use' });
expect(decide(roll(s, 6))).toEqual({ type: 'CHOOSE', key: 'skip' });
});
test('연금술사·로켓 박사', () => {
expect(decide(roll(race([{ id: 'alchemist' }, { id: 'banana', pos: 10 }]), 1))).toEqual({ type: 'CHOOSE', key: 'use' });
expect(decide(roll(race([{ id: 'rocket' }, { id: 'banana', pos: 10 }]), 6))).toEqual({ type: 'CHOOSE', key: 'use' });
expect(decide(roll(race([{ id: 'rocket' }, { id: 'banana', pos: 10 }]), 1))).toEqual({ type: 'CHOOSE', key: 'skip' });
// 두 배면 결승선: 넘어져도 상관없어요.
expect(decide(roll(race([{ id: 'rocket', pos: 25 }, { id: 'banana', pos: 10 }]), 3))).toEqual({ type: 'CHOOSE', key: 'use' });
});
test('최면술사는 앞선 상대를, 자리바꿈이는 멀리 앞선 상대와', () => {
expect(decide(race([{ id: 'hypnotist', pos: 2 }, { id: 'banana', pos: 4 }, { id: 'legs', pos: 20 }]))).toEqual({ type: 'CHOOSE', key: 'racer:legs' });
expect(decide(race([{ id: 'flipflop', pos: 2 }, { id: 'banana', pos: 4 }, { id: 'legs', pos: 20 }]))).toEqual({ type: 'CHOOSE', key: 'racer:legs' });
expect(decide(race([{ id: 'flipflop', pos: 10 }, { id: 'banana', pos: 11 }, { id: 'legs', pos: 2 }]))).toEqual({ type: 'CHOOSE', key: 'skip' });
// 같은 편 선수는 끌어오지 않아요(뒤에 있으면 끌어와요).
expect(decide(race([{ id: 'hypnotist', pos: 12 }, { id: 'legs', pos: 2, owner: 'bot' }, { id: 'banana', pos: 11 }]))).toEqual({ type: 'CHOOSE', key: 'racer:legs' });
});
test('컴퓨터끼리 무작위 상대보다 자주 이겨요', () => {
let wins = 0;
const games = 30;
for (let g = 1; g <= games; g++) {
const rng = SeededRng.fromSeed(seedN(g));
const chooser = SeededRng.fromSeed(seedN(g + 300));
const random = () => chooser.next();
const players = g % 2 ? ['bot', 'r1', 'r2', 'r3'] : ['r1', 'r2', 'bot', 'r3'];
let s = def.setup({ players, options: def.defaultOptions, rng, now: 0 });
for (let i = 0; i < 4000 && !def.result(s); i++) {
const ps = def.activePlayers(s);
const p = ps[0]!;
const a = p === 'bot' ? decideBotAction(def, s, p, { now: 1, random }) : randomPolicy({ me: p, view: null, legal: def.legalActions!(s, p), random });
s = def.apply(s, p, a as never, { rng, now: 1 }).state;
}
if (def.result(s)!.ranking[0]!.includes('bot')) wins++;
}
// 1/4 by chance; the race is mostly dice, so "clearly better" is a modest bar.
expect(wins).toBeGreaterThanOrEqual(10);
});
for (const n of [2, 3, 6]) {
test(`${n}명, 사람 한 명은 시간 초과만: 컴퓨터가 끝까지`, () => {
const players = Array.from({ length: n }, (_, i) => (i === 0 ? 'human' : `bot:${i}`));
for (let g = 1; g <= 2; g++) {
const r = botPlayout(def, { players, seed: seedN(g), isBot, level: g === 1 ? 1 : 60 });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(100);
}
});
}
});

View File

@@ -0,0 +1,112 @@
/**
* 야단법석 달리기 computer player (docs/games/magical-athlete.md §9.1). Only reads its own view:
* - 선수 뽑기: 선수 평가값(racers.ts `rating`)이 높은 선수.
* - 출전 선수: 점수표가 갈수록 커지면 앞 경주에는 약한 선수, 큰 경주에 강한 선수. 아니면 강한 선수부터.
* - 선택형 능력: 칸 수로 따진 기대 이득(결승선을 넘으면 큰 값, 깐깐이가 있으면 넘치는 수는 0)으로 판단.
* Level (1~60) changes how often it slips to a slightly worse choice (`humanBest`).
*/
import type { BotStrategy } from '../bots/types';
import { humanBest, pick, playable } from '../bots/policy';
import { RACERS, type RacerId } from './racers';
import { BLIMP_TURN, FINISH, type MagicalAthleteAction } from './rules';
import type { MaRacerView, MagicalAthleteView } from './index';
type Act = MagicalAthleteAction;
const SCALE = { small: 1, critical: 50 };
const FINISH_VALUE = 60;
const TRIP_COST = 3.5;
/** Spaces gained by moving `amount` from `pos` (finishing is worth much more; 깐깐이 blocks an overshoot). */
function gain(v: MagicalAthleteView, x: MaRacerView, amount: number): number {
const stickler = v.race!.racers.some((y) => y.id === 'stickler' && y.status === 'run' && y.id !== x.id);
if (x.pos + amount >= FINISH) {
if (stickler && x.pos + amount > FINISH) return 0;
return FINISH_VALUE;
}
return Math.max(0, amount);
}
/** Main-move modifiers the racer will get (토끼·비행선·코치·끈적이). */
function mods(v: MagicalAthleteView, x: MaRacerView): number {
let m = 0;
if (x.id === 'hare') m += 2;
if (x.id === 'blimp') m += x.pos < BLIMP_TURN ? 3 : -1;
const run = v.race!.racers.filter((y) => y.status === 'run');
const coach = run.find((y) => y.id === 'coach');
if (coach && (coach.id === x.id || coach.pos === x.pos)) m += 1;
if (run.some((y) => y.id === 'gunk' && y.id !== x.id)) m -= 1;
return m;
}
const avgRoll = (f: (d: number) => number) => [1, 2, 3, 4, 5, 6].reduce((t, d) => t + f(d), 0) / 6;
export const magicalAthleteBot: BotStrategy<MagicalAthleteView, Act> = ({ me, view: v, legal, random, level }) => {
const acts = playable(legal);
const choose = (score: (a: Act) => number) => humanBest(acts, (a) => score(a) + random() * 1e-3, random, level, SCALE);
if (v.phase === 'draft') {
const mine = v.teams[me] ?? [];
return choose((a) => {
if (a.type !== 'DRAFT') return -99;
let s = RACERS[a.racer].rating;
// 꼼지락이 goes well with racers whose powers keep happening (끈적이·코치·비행선 work every main move).
if (mine.includes('scoocher') && ['gunk', 'coach', 'blimp', 'hare'].includes(a.racer)) s += 1;
return s;
});
}
if (v.phase === 'select') {
const g = v.medals.map((m) => m.gold);
const now = g[v.raceNo - 1] ?? 3;
const later = g.slice(v.raceNo);
const avgLater = later.length ? later.reduce((t, x) => t + x, 0) / later.length : now;
// Rising points: save the strong racers while this race is worth less than the ones to come.
const sign = now < avgLater - 0.01 ? -1 : 1;
return choose((a) => (a.type === 'SELECT' ? sign * a.racers.reduce((t, id) => t + RACERS[id].rating, 0) : -99));
}
const r = v.race;
const pr = v.prompt;
if (!r || !pr) return pick(acts, random);
const find = (id: RacerId | null) => r.racers.find((y) => y.id === id) ?? null;
if (pr.step === 'go') {
// The racer with a turn-start choice first (최면술사 etc. pull before the teammate moves), else the one behind.
return choose((a) => {
if (a.type !== 'GO') return -99;
const x = find(a.racer)!;
return (RACERS[a.racer].hook === 'choiceStart' ? 5 : 0) - x.pos / 10;
});
}
const x = find(pr.racer)!;
const m = mods(v, x);
const d = r.roll?.value ?? 0;
const opp = (y: MaRacerView) => y.owner !== me;
switch (pr.step) {
case 'roll':
return choose((a) => (a.type === 'ROLL' ? avgRoll((k) => gain(v, x, k + m)) : a.type === 'CHOOSE' ? gain(v, x, 5 + m) : -99));
case 'reroll':
return choose((a) => (a.type !== 'CHOOSE' ? -99 : a.key === 'use' ? avgRoll((k) => gain(v, x, k + m)) + 0.3 : gain(v, x, d + m)));
case 'boost':
return choose((a) => {
if (a.type !== 'CHOOSE') return -99;
if (a.key === 'skip') return gain(v, x, d + m);
if (x.id === 'alchemist') return gain(v, x, 4 + m);
const g2 = gain(v, x, d * 2 + m);
return g2 >= FINISH_VALUE ? g2 : g2 - TRIP_COST;
});
case 'start':
return choose((a) => {
if (a.type !== 'CHOOSE' || a.key === 'skip') return 0;
if (a.key.startsWith('space:')) return Number(a.key.slice(6)) - x.pos - 0.5;
const y = find(a.key.slice(6) as RacerId)!;
const delta = y.pos - x.pos;
if (x.id === 'hypnotist') return opp(y) ? delta + (delta > 0 && y.pos === Math.max(...r.racers.filter((z) => z.status === 'run').map((z) => z.pos)) ? 2 : 0) : -delta;
// 자리바꿈이: I gain `delta`, the other loses it; I skip my main move (about 3.5 spaces).
return delta + (opp(y) ? delta * 0.5 : -delta) - 3.5;
});
}
return pick(acts, random);
};

View File

@@ -0,0 +1,556 @@
/**
* 야단법석 달리기 (docs/games/magical-athlete.md). 선수 뽑기(뱀 순서) → 경주 4번(몰래 동시에 출전 선수 고르기) → 1·2등 메달 점수.
* Hidden info: the racer deck (only its size is public) and each player's pick for the coming race until everyone picked.
*/
import type { ZodType } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
import { RACERS, RACER_IDS, type RacerId } from './racers';
import { Runner, autoSelect, startRace, unused } from './race';
import {
AWAY_AFTER,
AWAY_MS,
FINISH,
LEFT_MS,
RACES,
WILD_SPACES,
magicalAthleteActionSchema,
magicalAthleteOptionsSchema,
medalPoints,
perRaceFor,
sideOf,
type LogLine,
type MagicalAthleteAction,
type MagicalAthleteOptions,
type MagicalAthleteState,
type RaceResult,
type RacerStatus,
type Score,
type SpaceEffect,
type Step,
type TrackSide,
} from './rules';
export * from './rules';
export * from './racers';
export { ga, eun } from './race';
// ---------------------------------------------------------------- view types
export interface MaPromptOption {
key: string;
label: string;
}
export interface MaPrompt {
step: Step;
owner: PlayerId;
racer: RacerId | null;
/** `go`: racers (GO); `roll`: `roll` (+ `use` for 롱다리); others: CHOOSE keys. */
options: MaPromptOption[];
/** What a timeout does, in words. */
timeoutText: string;
}
export interface MaRacerView {
id: RacerId;
owner: PlayerId;
pos: number;
status: RacerStatus;
tripped: boolean;
place: number | null;
}
export interface MaRaceView {
no: number;
side: TrackSide;
racers: MaRacerView[];
current: PlayerId | null;
cur: RacerId | null;
step: Step | null;
roll: { value: number | null; rerolls: number } | null;
finishers: RacerId[];
over: boolean;
log: LogLine[];
}
export interface MaRankRow {
rank: number;
player: PlayerId;
total: number;
gold: number;
silver: number;
bonus: number;
left: boolean;
}
export interface MaResult {
ranking: MaRankRow[];
winners: PlayerId[];
summary: string;
reason: GameResult['reason'];
}
export interface MagicalAthleteView {
options: MagicalAthleteOptions;
me: PlayerId | null;
seats: PlayerId[];
phase: MagicalAthleteState['phase'];
perRace: 1 | 2;
raceNo: number;
races: number;
/** Medal points of each race (index = race − 1). */
medals: { gold: number; silver: number }[];
draft: { round: number; rounds: number; line: RacerId[]; picker: PlayerId; next: PlayerId[] } | null;
deckCount: number;
teams: Record<PlayerId, RacerId[]>;
used: Record<PlayerId, RacerId[]>;
/** Select phase: who has picked (not what). */
picked: Record<PlayerId, boolean>;
/** My own secret pick for the coming race. */
mySelection: { key: string; racers: RacerId[] } | null;
firstPlayer: PlayerId;
race: MaRaceView | null;
prompt: MaPrompt | null;
results: RaceResult[];
scores: Record<PlayerId, Score & { total: number }>;
/** Special spaces of each side (the wild side only has some). */
spaces: Record<TrackSide, { pos: number; effect: SpaceEffect }[]>;
finish: number;
left: PlayerId[];
away: PlayerId[];
rollSeq: number;
turnSeq: number;
deadlineAt: number | null;
result: MaResult | null;
}
// ---------------------------------------------------------------- helpers
type S = MagicalAthleteState;
type A = MagicalAthleteAction;
const isIn = (s: S, p: PlayerId) => !s.left.includes(p);
const total = (sc: Score) => sc.medal + sc.bonus;
const selKey = (s: S, p: PlayerId, racers: RacerId[]) => `ma-sel-r${s.raceNo}-${p}-${racers.join('+')}`;
/** Player who must act in the race (owner of the racer whose turn it is). */
function raceActor(s: S): PlayerId | null {
const r = s.race;
if (!r || s.phase !== 'race') return null;
if (r.step === 'go' || !r.cur) return s.seats[r.seat]!;
return r.racers.find((x) => x.id === r.cur)!.owner;
}
function activeOf(s: S): PlayerId[] {
switch (s.phase) {
case 'draft':
return [s.seats[s.draft!.order[s.draft!.at]!]!];
case 'select':
return s.seats.filter((p) => s.selections[p] === null);
case 'race': {
const a = raceActor(s);
return a ? [a] : [];
}
default:
return [];
}
}
function refreshDeadline(s: S, now: number): void {
const act = activeOf(s);
if (!act.length) {
s.deadlineAt = null;
return;
}
if (act.some((p) => !isIn(s, p))) s.deadlineAt = now + LEFT_MS;
else if (act.every((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER)) s.deadlineAt = now + AWAY_MS;
else s.deadlineAt = s.options.turnSeconds === null ? null : now + s.options.turnSeconds * 1000;
}
function startDraftRound(s: S, round: number): void {
const n = s.seats.length;
const start = (s.draftStart + round - 1) % n;
const fwd = Array.from({ length: n }, (_, k) => (start + k) % n);
const line = s.deck.splice(0, n * 2);
s.draft = { round, rounds: s.draft?.rounds ?? (s.perRace === 2 ? 4 : 2), line, order: [...fwd, ...[...fwd].reverse()], at: 0 };
s.turnSeq++;
}
function draftPick(s: S, p: PlayerId, racer: RacerId, rng: Rng, ev: GameEvent[]): void {
const d = s.draft!;
d.line = d.line.filter((id) => id !== racer);
s.teams[p]!.push(racer);
d.at++;
s.turnSeq++;
ev.push({ type: 'drafted', player: p, racer });
if (d.at < d.order.length) return;
if (d.round < d.rounds) return startDraftRound(s, d.round + 1);
s.draft = null;
s.phase = 'select';
for (const q of s.seats) s.selections[q] = null;
autoSelect(s);
if (s.seats.every((q) => s.selections[q] !== null)) startRace(s, rng, ev);
}
function finishGame(s: S, ev: GameEvent[]): void {
s.phase = 'finished';
s.deadlineAt = null;
if (s.race) {
s.race.cur = null;
s.race.pending = [];
}
ev.push({ type: 'gameOver' });
}
/** Racer-turn prompt for the view, the bot and validation. */
export function promptOf(s: S): MaPrompt | null {
const r = s.race;
if (s.phase !== 'race' || !r) return null;
const owner = raceActor(s)!;
if (r.step === 'go') {
return {
step: 'go',
owner,
racer: null,
options: r.pending.map((id) => ({ key: id, label: `${RACERS[id].emoji} ${RACERS[id].name} 먼저` })),
timeoutText: '뒤에 있는 선수부터 움직여요',
};
}
const id = r.cur!;
const name = RACERS[id].name;
const run = new Runner(s, { next: () => 0, int: () => 0, shuffle: (a) => [...a] } as Rng, []);
switch (r.step) {
case 'start': {
const keys = run.startOptions(run.get(id)!);
const verb = id === 'hypnotist' ? '내 칸으로 끌어오기' : id === 'flipflop' ? '자리 바꾸기' : '';
const options = keys.map((k) => {
if (k.startsWith('racer:')) {
const t = k.slice(6) as RacerId;
const tx = run.get(t)!;
return { key: k, label: `${RACERS[t].emoji} ${RACERS[t].name}(${tx.pos}칸) ${verb}` };
}
return { key: k, label: `${k.slice(6)}칸으로 끼어들기` };
});
return { step: 'start', owner, racer: id, options: [...options, { key: 'skip', label: '능력 안 쓰고 주사위 굴리기' }], timeoutText: '능력을 쓰지 않아요' };
}
case 'roll':
return {
step: 'roll',
owner,
racer: id,
options: [{ key: 'roll', label: '🎲 주사위 굴리기' }, ...(id === 'legs' ? [{ key: 'use', label: '🦵 굴리지 않고 5칸 가기' }] : [])],
timeoutText: '주사위를 굴려요',
};
case 'reroll':
return {
step: 'reroll',
owner,
racer: id,
options: [
{ key: 'use', label: `🎩 다시 굴리기 (${2 - (r.roll?.rerolls ?? 0)}번 남음)` },
{ key: 'skip', label: `${r.roll?.value}(으)로 가기` },
],
timeoutText: '나온 눈 그대로 가요',
};
case 'boost': {
const d = r.roll?.value ?? 0;
const use = id === 'alchemist' ? `⚗️ ${d} 대신 4칸 가기` : `🚀 두 배로 ${d * 2}칸 가기(간 뒤 넘어짐)`;
return { step: 'boost', owner, racer: id, options: [{ key: 'use', label: use }, { key: 'skip', label: `${d}(으)로 가기` }], timeoutText: `${name} 능력을 쓰지 않아요` };
}
}
return null;
}
/** What the server plays for `p` on a timeout (안전한 기본값: 선택형 능력은 쓰지 않음). */
export function defaultAction(s: S, p: PlayerId): Exclude<A, { type: 'TIMEOUT' }> | null {
switch (s.phase) {
case 'draft': {
const line = [...s.draft!.line].sort((a, b) => RACERS[b].rating - RACERS[a].rating || s.draft!.line.indexOf(a) - s.draft!.line.indexOf(b));
return { type: 'DRAFT', racer: line[0]! };
}
case 'select':
return { type: 'SELECT', racers: unused(s, p).slice(0, s.perRace) };
case 'race': {
const r = s.race!;
if (r.step === 'go') {
const behind = [...r.pending].sort((a, b) => r.racers.find((x) => x.id === a)!.pos - r.racers.find((x) => x.id === b)!.pos);
return { type: 'GO', racer: behind[0]! };
}
if (r.step === 'roll') return { type: 'ROLL' };
return { type: 'CHOOSE', key: 'skip' };
}
}
return null;
}
function perform(s: S, p: PlayerId, a: Exclude<A, { type: 'TIMEOUT' }>, rng: Rng, ev: GameEvent[]): void {
switch (a.type) {
case 'DRAFT':
return draftPick(s, p, a.racer, rng, ev);
case 'SELECT':
s.selections[p] = [...a.racers];
ev.push({ type: 'picked', player: p });
if (s.seats.every((q) => s.selections[q] !== null)) startRace(s, rng, ev);
return;
case 'LEAVE':
s.left.push(p);
ev.push({ type: 'left', player: p });
if (s.seats.filter((q) => isIn(s, q)).length < 2) return finishGame(s, ev);
if (s.phase === 'select') {
autoSelect(s);
if (s.seats.every((q) => s.selections[q] !== null)) startRace(s, rng, ev);
}
return;
}
const run = new Runner(s, rng, ev);
const r = s.race!;
switch (a.type) {
case 'GO':
return run.startRacerTurn(a.racer);
case 'ROLL':
return run.roll();
case 'CHOOSE':
if (r.step === 'start') return run.chooseStart(a.key);
if (r.step === 'roll') return run.legs();
if (r.step === 'reroll') return run.reroll(a.key === 'use');
if (r.step === 'boost') return run.boost(a.key === 'use');
}
}
// ---------------------------------------------------------------- result
function rankRows(s: S): MaRankRow[] {
const rows = s.seats.map((p) => {
const sc = s.scores[p]!;
return { player: p, total: total(sc), gold: sc.gold, silver: sc.silver, bonus: sc.bonus, left: !isIn(s, p) };
});
rows.sort((a, b) => Number(a.left) - Number(b.left) || b.total - a.total);
const out: MaRankRow[] = [];
rows.forEach((r, i) => {
const prev = out[i - 1];
const tied = prev && prev.left === r.left && prev.total === r.total;
out.push({ ...r, rank: tied ? prev.rank : i + 1 });
});
return out;
}
function buildResult(s: S): MaResult {
const ranking = rankRows(s);
const winners = ranking.filter((r) => r.rank === 1).map((r) => r.player);
const top = ranking[0]!;
const early = s.raceNo <= RACES && s.left.length > 0;
let summary =
winners.length > 1
? `공동 1위 ${winners.length}명, ${top.total}점`
: `1위 ${top.total}점 (금메달 ${top.gold}개)${ranking[1] ? ` · 2위 ${ranking[1].total}점` : ''}`;
if (early) summary = `다른 사람이 모두 나갔어요. ${summary}`;
return { ranking, winners, summary, reason: early ? 'resign' : 'normal' };
}
// ---------------------------------------------------------------- definition
export const magicalAthlete: GameDefinition<MagicalAthleteState, MagicalAthleteAction, MagicalAthleteView, MagicalAthleteOptions> = {
id: 'magical-athlete',
nameKo: '야단법석 달리기',
minPlayers: 2,
maxPlayers: 6,
stateVersion: 1,
defaultOptions: magicalAthleteOptionsSchema.parse({}),
optionsSchema: magicalAthleteOptionsSchema as unknown as ZodType<MagicalAthleteOptions>,
actionSchema: magicalAthleteActionSchema as unknown as ZodType<MagicalAthleteAction>,
setup({ players, options, rng, now }) {
if (players.length < 2 || players.length > 6) throw new Error('magical-athlete: 2~6명이 할 수 있어요.');
const n = players.length;
const s: S = {
options,
seats: [...players],
perRace: perRaceFor(options.twoRacers, n),
phase: 'draft',
deck: rng.shuffle(RACER_IDS),
draft: null,
draftStart: rng.int(n),
teams: Object.fromEntries(players.map((p) => [p, []])),
used: Object.fromEntries(players.map((p) => [p, []])),
selections: Object.fromEntries(players.map((p) => [p, null])),
raceNo: 1,
firstSeat: rng.int(n),
race: null,
results: [],
scores: Object.fromEntries(players.map((p) => [p, { gold: 0, silver: 0, medal: 0, bonus: 0 }])),
left: [],
timeouts: Object.fromEntries(players.map((p) => [p, 0])),
rollSeq: 0,
turnSeq: 0,
deadlineAt: null,
};
startDraftRound(s, 1);
refreshDeadline(s, now);
return s;
},
validate(s, actor, a) {
if (!s.teams[actor]) return fail('이 게임의 참가자가 아니에요.');
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
if (!isIn(s, actor)) return fail('이미 나간 자리예요.');
if (a.type === 'LEAVE') return ok;
if (a.type === 'TIMEOUT') return activeOf(s).includes(actor) ? ok : fail('지금은 시간 초과를 처리할 수 없어요.');
if (!activeOf(s).includes(actor)) return fail('지금은 내 차례가 아니에요.');
switch (a.type) {
case 'DRAFT':
if (s.phase !== 'draft') return fail('지금은 선수를 뽑을 때가 아니에요.');
return s.draft!.line.includes(a.racer) ? ok : fail('펼쳐진 선수 중에서 골라 주세요.');
case 'SELECT': {
if (s.phase !== 'select') return fail('지금은 출전 선수를 고를 때가 아니에요.');
if (a.racers.length !== s.perRace) return fail(`선수 ${s.perRace}명을 골라 주세요.`);
if (new Set(a.racers).size !== a.racers.length) return fail('같은 선수를 두 번 고를 수 없어요.');
const left = unused(s, actor);
return a.racers.every((id) => left.includes(id)) ? ok : fail('아직 달리지 않은 내 선수만 고를 수 있어요.');
}
}
if (s.phase !== 'race') return fail('지금은 경주 중이 아니에요.');
const pr = promptOf(s)!;
switch (a.type) {
case 'GO':
return pr.step === 'go' && pr.options.some((o) => o.key === a.racer) ? ok : fail('먼저 움직일 내 선수를 골라 주세요.');
case 'ROLL':
return pr.step === 'roll' ? ok : fail('지금은 주사위를 굴릴 때가 아니에요.');
case 'CHOOSE':
if (pr.step === 'go' || (pr.step === 'roll' && a.key !== 'use')) return fail('그건 지금 고를 수 없어요.');
return pr.options.some((o) => o.key === a.key) ? ok : fail('그건 지금 고를 수 없어요.');
}
return fail('알 수 없는 행동이에요.');
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const ev: GameEvent[] = [];
const seq = s.turnSeq;
const phase = s.phase;
if (a.type === 'TIMEOUT') {
s.timeouts[actor] = (s.timeouts[actor] ?? 0) + 1;
ev.push({ type: 'timeout', player: actor });
if (s.timeouts[actor] === AWAY_AFTER) ev.push({ type: 'away', player: actor });
const d = defaultAction(s, actor);
if (d) perform(s, actor, d, rng, ev);
} else {
if (a.type !== 'LEAVE') s.timeouts[actor] = 0;
perform(s, actor, a, rng, ev);
}
if (s.phase === 'finished') s.deadlineAt = null;
else if (s.turnSeq !== seq || s.phase !== phase || a.type === 'LEAVE') refreshDeadline(s, now);
return { state: s, events: ev };
},
view(s, viewer) {
const me = viewer !== null && s.teams[viewer] ? viewer : null;
const r = s.race;
const done = s.phase === 'finished';
const scores: MagicalAthleteView['scores'] = {};
for (const p of s.seats) scores[p] = { ...s.scores[p]!, total: total(s.scores[p]!) };
const d = s.draft;
const sel = me && s.phase === 'select' ? s.selections[me] : null;
return {
options: s.options,
me,
seats: [...s.seats],
phase: s.phase,
perRace: s.perRace,
raceNo: Math.min(s.raceNo, RACES),
races: RACES,
medals: Array.from({ length: RACES }, (_, i) => medalPoints(s.options.scoring, i + 1)),
draft: d ? { round: d.round, rounds: d.rounds, line: [...d.line], picker: s.seats[d.order[d.at]!]!, next: d.order.slice(d.at + 1).map((i) => s.seats[i]!) } : null,
deckCount: s.deck.length,
teams: Object.fromEntries(s.seats.map((p) => [p, [...s.teams[p]!]])),
used: Object.fromEntries(s.seats.map((p) => [p, [...s.used[p]!]])),
picked: Object.fromEntries(s.seats.map((p) => [p, s.phase === 'select' && s.selections[p] !== null])),
mySelection: sel ? { key: selKey(s, me!, sel), racers: [...sel] } : null,
firstPlayer: s.seats[s.firstSeat]!,
race: r
? {
no: r.no,
side: r.side,
racers: r.racers.map((x) => ({ id: x.id, owner: x.owner, pos: x.pos, status: x.status, tripped: x.tripped, place: x.place })),
current: s.phase === 'race' ? raceActor(s) : null,
cur: s.phase === 'race' ? r.cur : null,
step: s.phase === 'race' ? r.step : null,
roll: r.roll,
finishers: [...r.finishers],
over: s.phase !== 'race',
log: r.log.slice(-60),
}
: null,
prompt: promptOf(s),
results: structuredClone(s.results),
scores,
spaces: { mild: [], wild: Object.entries(WILD_SPACES).map(([pos, effect]) => ({ pos: Number(pos), effect: { ...effect } })) },
finish: FINISH,
left: [...s.left],
away: s.seats.filter((p) => isIn(s, p) && (s.timeouts[p] ?? 0) >= AWAY_AFTER),
rollSeq: s.rollSeq,
turnSeq: s.turnSeq,
deadlineAt: s.deadlineAt,
result: done ? buildResult(s) : null,
};
},
activePlayers: activeOf,
deadline(s) {
return s.phase === 'finished' ? null : s.deadlineAt;
},
onTimeout() {
return { type: 'TIMEOUT' };
},
onLeave(s, player) {
if (s.phase === 'finished' || !s.teams[player] || !isIn(s, player)) return null;
return { type: 'LEAVE' };
},
result(s): GameResult | null {
if (s.phase !== 'finished') return null;
const r = buildResult(s);
const groups = new Map<number, PlayerId[]>();
for (const row of r.ranking) groups.set(row.rank, [...(groups.get(row.rank) ?? []), row.player]);
const scores: Record<PlayerId, number> = {};
for (const row of r.ranking) scores[row.player] = row.total;
return {
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ps]) => ps),
scores,
scoreText: Object.fromEntries(Object.entries(scores).map(([p, n]) => [p, `${n}점`])),
summary: r.summary,
reason: r.reason,
};
},
/** Test helper: every choice the actor has (LEAVE left out). */
legalActions(s, player) {
if (!activeOf(s).includes(player) || !isIn(s, player)) return [];
if (s.phase === 'draft') return s.draft!.line.map((racer) => ({ type: 'DRAFT' as const, racer }));
if (s.phase === 'select') {
const left = unused(s, player);
if (s.perRace === 1) return left.map((id) => ({ type: 'SELECT' as const, racers: [id] }));
const out: A[] = [];
for (let i = 0; i < left.length; i++) for (let j = i + 1; j < left.length; j++) out.push({ type: 'SELECT', racers: [left[i]!, left[j]!] });
return out;
}
const pr = promptOf(s);
if (!pr) return [];
if (pr.step === 'go') return pr.options.map((o) => ({ type: 'GO' as const, racer: o.key as RacerId }));
if (pr.step === 'roll') return pr.options.map((o) => (o.key === 'roll' ? ({ type: 'ROLL' } as const) : ({ type: 'CHOOSE', key: o.key } as const)));
return pr.options.map((o) => ({ type: 'CHOOSE' as const, key: o.key }));
},
/** Test helper: my secret race pick (and the deck order, which nobody may see). */
secretsOf(s, player) {
const out: string[] = [];
if (s.deck.length) out.push(`ma-deck:${s.deck.join(',')}`);
const sel = s.phase === 'select' ? s.selections[player] : null;
if (sel) out.push(selKey(s, player, sel));
return out;
},
};
export { sideOf };

View File

@@ -0,0 +1,629 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN, type PlayerId, type Rng } from '@bg/engine';
import {
FINISH,
POWER_CAP,
RACERS,
RACER_IDS,
defaultAction,
magicalAthlete as def,
promptOf,
type MagicalAthleteAction,
type MagicalAthleteState,
type RaceState,
type RacerId,
} from './index';
import { Runner } from './race';
// ---------------------------------------------------------------- helpers
/** Rng that returns the scripted die faces (1~6) in order. */
function dice(...faces: number[]): Rng {
const q = [...faces];
return {
next: () => 0,
int: (n: number) => {
const f = q.shift();
if (f === undefined) throw new Error('no more scripted dice');
if (n !== 6) throw new Error(`unexpected int(${n})`);
return f - 1;
},
shuffle: <T,>(a: readonly T[]) => [...a],
};
}
interface Spec {
id: RacerId;
pos?: number;
owner?: PlayerId;
tripped?: boolean;
}
/**
* A race already running: racers in the given order (by default each with its own player P0, P1, … in seat order),
* the first one about to start its turn (call `begin`). Side 'mild' unless asked.
*/
function scenario(specs: Spec[], opts: { side?: 'mild' | 'wild'; players?: PlayerId[] } = {}): MagicalAthleteState {
const owners = specs.map((sp, i) => sp.owner ?? `P${i}`);
const players = opts.players ?? [...new Set(owners)];
const s = def.setup({ players, options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
s.phase = 'race';
s.draft = null;
// The last race, so a race that ends here ends the game (no next pick needed).
s.raceNo = 4;
for (const p of players) {
s.teams[p] = specs.filter((_, i) => owners[i] === p).map((sp) => sp.id);
s.used[p] = [...s.teams[p]!];
}
const race: RaceState = {
no: 4,
side: opts.side ?? 'mild',
racers: specs.map((sp, i) => ({ id: sp.id, owner: owners[i]!, pos: sp.pos ?? 0, status: 'run', tripped: sp.tripped ?? false, place: null })),
seat: players.indexOf(owners[0]!),
pending: [],
cur: null,
step: 'roll',
roll: null,
turnStartPos: 0,
skipperNext: false,
cancelMain: false,
turns: 0,
fired: {},
loserPts: 0,
sisyphusPts: 0,
finishers: [],
capped: false,
bonus: {},
log: [],
logSeq: 0,
};
s.race = race;
return s;
}
/** Starts `id`'s turn as the engine would (turn-start powers included). */
function begin(s: MagicalAthleteState, id: RacerId, rng: Rng = dice()): MagicalAthleteState {
const run = new Runner(s, rng, []);
const x = run.get(id)!;
s.race!.seat = s.seats.indexOf(x.owner);
run.startRacerTurn(id);
return s;
}
function act(s: MagicalAthleteState, a: MagicalAthleteAction, rng: Rng = dice()): MagicalAthleteState {
const actor = def.activePlayers(s)[0]!;
const v = def.validate(s, actor, a);
if (!v.ok) throw new Error(`rejected ${JSON.stringify(a)}: ${v.reason}`);
return def.apply(s, actor, a, { rng, now: 1 }).state;
}
const pos = (s: MagicalAthleteState, id: RacerId) => s.race!.racers.find((x) => x.id === id)!.pos;
const racer = (s: MagicalAthleteState, id: RacerId) => s.race!.racers.find((x) => x.id === id)!;
/** Racers whose power lines were logged, in order. */
const powers = (s: MagicalAthleteState) => s.race!.log.filter((l) => l.kind === 'power').map((l) => l.racer);
const cur = (s: MagicalAthleteState) => s.race!.cur;
/** `id` rolls `face` on its turn (no prompts expected). */
function rollTurn(specs: Spec[], face: number[], opts: { side?: 'mild' | 'wild' } = {}) {
let s = begin(scenario(specs, opts), specs[0]!.id);
s = act(s, { type: 'ROLL' }, dice(...face));
return s;
}
// ---------------------------------------------------------------- data
describe('선수 데이터', () => {
test('24명, 이름·설명·평가값이 모두 있어요', () => {
expect(RACER_IDS).toHaveLength(24);
for (const id of RACER_IDS) {
const r = RACERS[id];
expect(r.id).toBe(id);
expect(r.name.length).toBeGreaterThan(1);
expect(r.text.length).toBeGreaterThan(8);
expect(r.text.length).toBeLessThanOrEqual(60);
expect(r.rating >= 1 && r.rating <= 10).toBe(true);
}
expect(new Set(RACER_IDS.map((id) => RACERS[id].name)).size).toBe(24);
});
});
// ---------------------------------------------------------------- one test per racer
describe('선수 능력', () => {
test('연금술사: 1·2가 나오면 4칸을 고를 수 있어요', () => {
let s = begin(scenario([{ id: 'alchemist' }, { id: 'banana', pos: 20 }]), 'alchemist');
s = act(s, { type: 'ROLL' }, dice(2));
expect(s.race!.step).toBe('boost');
expect(promptOf(s)!.options.map((o) => o.key)).toEqual(['use', 'skip']);
const used = act(s, { type: 'CHOOSE', key: 'use' });
expect(pos(used, 'alchemist')).toBe(4);
const kept = act(s, { type: 'CHOOSE', key: 'skip' });
expect(pos(kept, 'alchemist')).toBe(2);
// 3 이상은 묻지 않아요.
expect(pos(rollTurn([{ id: 'alchemist' }, { id: 'banana', pos: 20 }], [5]), 'alchemist')).toBe(5);
});
test('바나나: 앞질러 간 선수는 넘어지고, 다음 차례에는 일어나기만 해요', () => {
let s = rollTurn([{ id: 'legs' }, { id: 'banana', pos: 2 }], [4]);
expect(pos(s, 'legs')).toBe(4);
expect(racer(s, 'legs').tripped).toBe(true);
expect(powers(s)).toEqual(['banana']);
// 바나나 차례 → 롱다리 차례: 일어나기만.
s = act(s, { type: 'ROLL' }, dice(1));
expect(cur(s)).toBe('banana');
expect(s.race!.step).toBe('roll');
s = act(s, { type: 'ROLL' }, dice(1));
expect(pos(s, 'legs')).toBe(4);
expect(racer(s, 'legs').tripped).toBe(false);
// 같은 칸에서 출발하면 "앞질렀다"가 아니에요.
const same = rollTurn([{ id: 'legs', pos: 2 }, { id: 'banana', pos: 2 }], [3]);
expect(racer(same, 'legs').tripped).toBe(false);
});
test('비행선: 15칸 전 +3, 15칸부터 −1', () => {
expect(pos(rollTurn([{ id: 'blimp' }, { id: 'banana', pos: 29 }], [2]), 'blimp')).toBe(5);
expect(pos(rollTurn([{ id: 'blimp', pos: 15 }, { id: 'banana', pos: 29 }], [2]), 'blimp')).toBe(16);
});
test('켄타우로스: 앞지른 선수를 2칸 뒤로 밀어요', () => {
const s = rollTurn([{ id: 'centaur' }, { id: 'hare', pos: 3 }, { id: 'coach', pos: 1 }], [4]);
expect(pos(s, 'centaur')).toBe(4);
expect(pos(s, 'hare')).toBe(1);
expect(pos(s, 'coach')).toBe(0);
});
test('코치: 코치 자신과 같은 칸의 선수는 +1', () => {
expect(pos(rollTurn([{ id: 'coach' }, { id: 'banana', pos: 20 }], [3]), 'coach')).toBe(4);
expect(pos(rollTurn([{ id: 'legs', pos: 5 }, { id: 'coach', pos: 5 }], [3]), 'legs')).toBe(9);
expect(pos(rollTurn([{ id: 'legs', pos: 4 }, { id: 'coach', pos: 5 }], [3]), 'legs')).toBe(7);
});
test('자리바꿈이: 주사위 대신 다른 선수와 자리를 바꿔요(넘어져 있으면 못 해요)', () => {
let s = begin(scenario([{ id: 'flipflop', pos: 2 }, { id: 'legs', pos: 12 }, { id: 'banana', pos: 2 }]), 'flipflop');
expect(s.race!.step).toBe('start');
const keys = promptOf(s)!.options.map((o) => o.key);
expect(keys).toEqual(['racer:legs', 'skip']);
s = act(s, { type: 'CHOOSE', key: 'racer:legs' });
expect(pos(s, 'flipflop')).toBe(12);
expect(pos(s, 'legs')).toBe(2);
expect(cur(s)).toBe('legs');
const tripped = begin(scenario([{ id: 'flipflop', pos: 2, tripped: true }, { id: 'legs', pos: 12 }]), 'flipflop');
expect(cur(tripped)).toBe('legs');
expect(pos(tripped, 'flipflop')).toBe(2);
});
test('끈적이: 다른 선수만 −1', () => {
expect(pos(rollTurn([{ id: 'legs' }, { id: 'gunk', pos: 20 }], [3]), 'legs')).toBe(2);
expect(pos(rollTurn([{ id: 'gunk' }, { id: 'legs', pos: 20 }], [3]), 'gunk')).toBe(3);
// 1에서 −1이면 0칸.
expect(pos(rollTurn([{ id: 'legs', pos: 3 }, { id: 'gunk', pos: 20 }], [1]), 'legs')).toBe(3);
});
test('토끼: +2, 차례 시작에 혼자 1등이면 쉬어요', () => {
expect(pos(rollTurn([{ id: 'hare' }, { id: 'banana', pos: 20 }], [3]), 'hare')).toBe(5);
const s = begin(scenario([{ id: 'hare', pos: 10 }, { id: 'legs', pos: 4 }]), 'hare');
expect(cur(s)).toBe('legs');
expect(pos(s, 'hare')).toBe(10);
// 함께 1등이면 쉬지 않아요.
const tie = begin(scenario([{ id: 'hare', pos: 10 }, { id: 'legs', pos: 10 }]), 'hare');
expect(cur(tie)).toBe('hare');
});
test('야유꾼: 다른 선수가 1칸 이하로 움직이고 차례를 마치면 2칸', () => {
const s = rollTurn([{ id: 'legs', pos: 3 }, { id: 'gunk', pos: 20 }, { id: 'heckler', pos: 6 }], [2]);
expect(pos(s, 'legs')).toBe(4);
expect(pos(s, 'heckler')).toBe(8);
const far = rollTurn([{ id: 'legs', pos: 3 }, { id: 'heckler', pos: 6 }], [2]);
expect(pos(far, 'heckler')).toBe(6);
});
test('왕아기: 다른 선수는 왕아기 칸에 못 멈추고 한 칸 뒤에 서요', () => {
expect(pos(rollTurn([{ id: 'legs', pos: 2 }, { id: 'hugebaby', pos: 5 }], [3]), 'legs')).toBe(4);
// 바로 뒤에서 1이면 그대로.
expect(pos(rollTurn([{ id: 'legs', pos: 4 }, { id: 'hugebaby', pos: 5 }], [1]), 'legs')).toBe(4);
// 지나치는 건 괜찮아요.
expect(pos(rollTurn([{ id: 'legs', pos: 2 }, { id: 'hugebaby', pos: 5 }], [4]), 'legs')).toBe(6);
// 출발점은 함께 있어도 돼요(켄타우로스가 밀어도 0칸).
expect(pos(rollTurn([{ id: 'centaur' }, { id: 'legs', pos: 1 }, { id: 'hugebaby', pos: 0 }], [3]), 'legs')).toBe(0);
});
test('최면술사: 다른 선수 하나를 내 칸으로 끌어와요', () => {
let s = begin(scenario([{ id: 'hypnotist', pos: 2 }, { id: 'legs', pos: 15 }, { id: 'banana', pos: 2 }]), 'hypnotist');
expect(promptOf(s)!.options.map((o) => o.key)).toEqual(['racer:legs', 'skip']);
s = act(s, { type: 'CHOOSE', key: 'racer:legs' });
expect(pos(s, 'legs')).toBe(2);
expect(s.race!.step).toBe('roll');
expect(cur(s)).toBe('hypnotist');
});
test('자벌레: 다른 선수가 1을 굴리면 그 선수는 못 가고 자벌레가 1칸', () => {
const s = rollTurn([{ id: 'legs', pos: 3 }, { id: 'inchworm', pos: 5 }], [1]);
expect(pos(s, 'legs')).toBe(3);
expect(pos(s, 'inchworm')).toBe(6);
// 자기가 1을 굴리면 그냥 1칸.
expect(pos(rollTurn([{ id: 'inchworm', pos: 5 }, { id: 'legs', pos: 3 }], [1]), 'inchworm')).toBe(6);
});
test('심부름꾼: 다른 선수가 6을 굴리면 먼저 2칸', () => {
const s = rollTurn([{ id: 'legs' }, { id: 'lackey', pos: 3 }], [6]);
expect(pos(s, 'lackey')).toBe(5);
expect(pos(s, 'legs')).toBe(6);
const moves = s.race!.log.filter((l) => l.kind === 'move').map((l) => l.racer);
expect(moves).toEqual(['lackey', 'legs']);
});
test('폴짝개구리: 선수가 있는 칸은 세지 않아요', () => {
expect(pos(rollTurn([{ id: 'leaptoad' }, { id: 'legs', pos: 1 }, { id: 'coach', pos: 2 }], [2]), 'leaptoad')).toBe(4);
expect(pos(rollTurn([{ id: 'leaptoad' }, { id: 'legs', pos: 3 }], [2]), 'leaptoad')).toBe(2);
});
test('롱다리: 굴리지 않고 5칸을 고를 수 있어요', () => {
let s = begin(scenario([{ id: 'legs', pos: 1 }, { id: 'banana', pos: 20 }]), 'legs');
expect(promptOf(s)!.options.map((o) => o.key)).toEqual(['roll', 'use']);
s = act(s, { type: 'CHOOSE', key: 'use' });
expect(pos(s, 'legs')).toBe(6);
expect(s.race!.log.some((l) => l.kind === 'roll')).toBe(false);
// 다른 선수는 5칸을 고를 수 없어요.
const o = begin(scenario([{ id: 'banana' }, { id: 'legs', pos: 20 }]), 'banana');
expect(def.validate(o, 'P0', { type: 'CHOOSE', key: 'use' }).ok).toBe(false);
});
test('귀여운 꼴찌: 차례 시작에 혼자 꼴찌면 1점, 한 경주 3점까지', () => {
let s = begin(scenario([{ id: 'loser' }, { id: 'legs', pos: 5 }]), 'loser');
expect(s.scores.P0!.bonus).toBe(1);
s.race!.loserPts = 3;
s.race!.step = 'roll';
s = begin(s, 'loser');
expect(s.scores.P0!.bonus).toBe(1);
const tie = begin(scenario([{ id: 'loser' }, { id: 'legs' }]), 'loser');
expect(tie.scores.P0!.bonus).toBe(0);
});
test('마술사: 두 번까지 다시 굴리고, 마지막 눈으로 가요', () => {
let s = begin(scenario([{ id: 'magician' }, { id: 'banana', pos: 20 }]), 'magician');
s = act(s, { type: 'ROLL' }, dice(1));
expect(s.race!.step).toBe('reroll');
s = act(s, { type: 'CHOOSE', key: 'use' }, dice(2));
expect(s.race!.step).toBe('reroll');
s = act(s, { type: 'CHOOSE', key: 'use' }, dice(3));
expect(pos(s, 'magician')).toBe(3);
expect(cur(s)).toBe('banana');
let k = begin(scenario([{ id: 'magician' }, { id: 'banana', pos: 20 }]), 'magician');
k = act(k, { type: 'ROLL' }, dice(5));
k = act(k, { type: 'CHOOSE', key: 'skip' });
expect(pos(k, 'magician')).toBe(5);
});
test('먹보: 딱 한 선수만 있는 칸에 멈추면 그 선수는 탈락', () => {
const s = rollTurn([{ id: 'mouth' }, { id: 'legs', pos: 4 }], [4]);
expect(racer(s, 'legs').status).toBe('out');
const two = rollTurn([{ id: 'mouth' }, { id: 'legs', pos: 4 }, { id: 'coach', pos: 4 }], [4]);
expect(racer(two, 'legs').status).toBe('run');
expect(racer(two, 'coach').status).toBe('run');
});
test('로켓 박사: 두 배로 가고 넘어져요', () => {
let s = begin(scenario([{ id: 'rocket' }, { id: 'banana', pos: 20 }]), 'rocket');
s = act(s, { type: 'ROLL' }, dice(3));
expect(s.race!.step).toBe('boost');
s = act(s, { type: 'CHOOSE', key: 'use' });
expect(pos(s, 'rocket')).toBe(6);
expect(racer(s, 'rocket').tripped).toBe(true);
});
test('꼼지락이: 다른 선수의 능력이 일어날 때마다 1칸', () => {
const s = rollTurn([{ id: 'legs' }, { id: 'gunk', pos: 20 }, { id: 'scoocher', pos: 10 }], [3]);
expect(pos(s, 'scoocher')).toBe(11);
expect(powers(s)).toEqual(['gunk', 'scoocher']);
});
test('시시포스: 경주 시작에 4점, 6이면 출발점으로 가고 1점을 잃어요', async () => {
const { startRace } = await import('./race');
const s0 = def.setup({ players: ['A', 'B'], options: def.optionsSchema.parse({ twoRacers: 'off' }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
s0.phase = 'select';
s0.draft = null;
s0.teams = { A: ['sisyphus', 'legs', 'coach', 'gunk'], B: ['banana', 'hare', 'blimp', 'mouth'] };
s0.selections = { A: ['sisyphus'], B: ['banana'] };
s0.firstSeat = 0;
startRace(s0, dice(), []);
expect(s0.scores.A!.bonus).toBe(4);
s0.race!.racers[0]!.pos = 9;
const s = act(s0, { type: 'ROLL' }, dice(6));
expect(pos(s, 'sisyphus')).toBe(0);
expect(s.scores.A!.bonus).toBe(3);
});
test('새치기: 누가 1을 굴리면 다음 차례는 새치기', () => {
// P0 legs, P1 banana, P2 skipper: P0 rolls 1 → next is P2 (skipper), then P0 again (clockwise from P2).
let s = rollTurn([{ id: 'legs' }, { id: 'banana', pos: 10 }, { id: 'skipper', pos: 3 }], [1]);
expect(cur(s)).toBe('skipper');
s = act(s, { type: 'ROLL' }, dice(2));
expect(cur(s)).toBe('legs');
});
test('깐깐이: 다른 선수는 딱 맞는 수로만 결승선을 넘어요', () => {
const over = rollTurn([{ id: 'legs', pos: 27 }, { id: 'stickler', pos: 5 }], [5]);
expect(pos(over, 'legs')).toBe(27);
const exact = rollTurn([{ id: 'legs', pos: 27 }, { id: 'stickler', pos: 5 }], [3]);
expect(racer(exact, 'legs').status).toBe('done');
// 깐깐이 자신은 넘쳐도 돼요.
const self = rollTurn([{ id: 'stickler', pos: 27 }, { id: 'legs', pos: 5 }], [6]);
expect(racer(self, 'stickler').status).toBe('done');
});
test('끼어들기: 선수가 딱 둘 있는 칸으로 옮겨 갈 수 있어요', () => {
let s = begin(
scenario([{ id: 'thirdwheel', pos: 1 }, { id: 'legs', pos: 9 }, { id: 'coach', pos: 9 }, { id: 'hare', pos: 6 }, { id: 'blimp', pos: 6 }, { id: 'banana', pos: 6 }]),
'thirdwheel',
);
expect(promptOf(s)!.options.map((o) => o.key)).toEqual(['space:9', 'skip']);
s = act(s, { type: 'CHOOSE', key: 'space:9' });
expect(pos(s, 'thirdwheel')).toBe(9);
expect(s.race!.step).toBe('roll');
});
});
// ---------------------------------------------------------------- resolution order
describe('능력 처리 순서 (§5.4)', () => {
test('같은 일로 발동한 능력은 지금 차례 사람부터 시계 방향, 연쇄는 줄 끝에', () => {
// P0 legs rolls 1: P1 skipper and P2 inchworm react (P1 first), then scoocher (P3) reacts to each in turn.
const s = rollTurn([{ id: 'legs' }, { id: 'skipper', pos: 20 }, { id: 'inchworm', pos: 3 }, { id: 'scoocher', pos: 10 }], [1]);
expect(powers(s)).toEqual(['skipper', 'inchworm', 'scoocher', 'scoocher']);
expect(pos(s, 'scoocher')).toBe(12);
// Same racers, seats swapped: inchworm now acts first.
const t = rollTurn([{ id: 'legs' }, { id: 'inchworm', pos: 3 }, { id: 'skipper', pos: 20 }, { id: 'scoocher', pos: 10 }], [1]);
expect(powers(t)).toEqual(['inchworm', 'skipper', 'scoocher', 'scoocher']);
});
test('문서 §5.6 예시: 비행선 +3·끈적이 −1, 바나나를 앞질러 넘어지고, 꼼지락이는 능력 셋을 보고 3칸', () => {
const s = rollTurn(
[
{ id: 'blimp', pos: 10, owner: 'A' },
{ id: 'gunk', pos: 2, owner: 'B' },
{ id: 'banana', pos: 14, owner: 'B' },
{ id: 'scoocher', pos: 20, owner: 'B' },
],
[4],
);
expect(pos(s, 'blimp')).toBe(16);
expect(racer(s, 'blimp').tripped).toBe(true);
expect(pos(s, 'scoocher')).toBe(23);
expect(powers(s)).toEqual(['blimp', 'gunk', 'scoocher', 'scoocher', 'banana', 'scoocher']);
});
test('경주로 칸 효과가 선수 능력보다 먼저예요', () => {
// 거친 판 5칸 = 앞 화살표 +3. 롱다리가 바나나(4칸)를 지나 5칸에 멈추면: 화살표로 8칸 → 그다음 바나나로 넘어짐.
const s = rollTurn([{ id: 'legs' }, { id: 'banana', pos: 4 }], [5], { side: 'wild' });
const order = s.race!.log.filter((l) => l.kind === 'space' || l.kind === 'power').map((l) => l.kind);
expect(order).toEqual(['space', 'power']);
expect(pos(s, 'legs')).toBe(8);
expect(racer(s, 'legs').tripped).toBe(true);
});
test('거친 판: 돌은 넘어짐, 별은 1점, 뒤 화살표', () => {
const r7 = rollTurn([{ id: 'legs', pos: 4 }, { id: 'banana', pos: 20 }], [3], { side: 'wild' });
expect(pos(r7, 'legs')).toBe(7);
expect(racer(r7, 'legs').tripped).toBe(true);
const star = rollTurn([{ id: 'legs' }, { id: 'banana', pos: 20 }], [3], { side: 'wild' });
expect(star.scores.P0!.bonus).toBe(1);
const back = rollTurn([{ id: 'legs', pos: 9 }, { id: 'banana', pos: 20 }], [3], { side: 'wild' });
expect(pos(back, 'legs')).toBe(9);
});
test('꼼지락이와 왕아기가 끝없이 이어지지 않아요', () => {
// 꼼지락이는 왕아기 바로 뒤: 끈적이 −1 → 꼼지락이 1칸 시도 → 왕아기에 막힘(움직이지 않으면 능력이 "일어나지" 않음).
const s = rollTurn([{ id: 'legs' }, { id: 'gunk', pos: 20 }, { id: 'scoocher', pos: 9 }, { id: 'hugebaby', pos: 10 }], [3]);
expect(pos(s, 'scoocher')).toBe(9);
expect(cur(s)).toBe('gunk');
});
test(`한 선수의 능력은 한 차례에 ${POWER_CAP}번까지만`, () => {
// 같은 선수의 능력을 열 번 일으켜도 꼼지락이는 상한만큼만 반응해요.
const s = scenario([{ id: 'legs' }, { id: 'scoocher', pos: 2 }]);
const run = new Runner(begin(s, 'legs'), dice(), []);
for (let i = 0; i < 10; i++) run.fire('legs', '시험');
run.drain();
expect(pos(s, 'scoocher')).toBe(2 + POWER_CAP);
});
test('두 번째 선수가 결승선을 넘는 순간 경주가 끝나고 남은 능력은 버려요', () => {
const s = scenario([{ id: 'legs', pos: 27 }, { id: 'banana', pos: 29 }, { id: 'scoocher', pos: 29 }, { id: 'gunk', pos: 1 }]);
s.race!.finishers = ['hare' as RacerId];
s.race!.racers.push({ id: 'hare', owner: 'P0', pos: FINISH, status: 'done', tripped: false, place: 1 });
const t = act(begin(s, 'legs'), { type: 'ROLL' }, dice(4));
// gunk −1 → 꼼지락이 1칸 = 결승(2등) → 경주 끝, 롱다리는 움직이지 않아요.
expect(t.results).toHaveLength(1);
expect(t.results[0]!.silver).toBe('scoocher');
expect(t.results[0]!.field.find((x) => x.id === 'legs')!.pos).toBe(27);
expect(t.phase).toBe('finished');
});
});
// ---------------------------------------------------------------- flow
describe('진행', () => {
test('뱀 순서로 뽑기: 2명이면 선수 둘씩(8명), 4명이면 4명씩', () => {
for (const [n, per, each] of [
[2, 2, 8],
[3, 2, 8],
[4, 1, 4],
[6, 1, 4],
] as const) {
const players = Array.from({ length: n }, (_, i) => `p${i}`);
let s = def.setup({ players, options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(n)), now: 0 });
expect(s.perRace).toBe(per);
const order: PlayerId[] = [];
while (s.phase === 'draft') {
const p = def.activePlayers(s)[0]!;
order.push(p);
s = def.apply(s, p, defaultAction(s, p)!, { rng: SeededRng.fromSeed(seedN(9)), now: 1 }).state;
}
for (const p of players) expect(s.teams[p]).toHaveLength(each);
// First round: 1→n then n→1.
expect(order.slice(0, 2 * n)).toEqual([...order.slice(0, n), ...order.slice(0, n).reverse()]);
// The next round starts with the next player.
expect(players.indexOf(order[2 * n]!)).toBe((players.indexOf(order[0]!) + 1) % n);
const all = players.flatMap((p) => s.teams[p]!);
expect(new Set(all).size).toBe(all.length);
}
});
test('출전 선수는 몰래 골라요: 다른 사람 화면에는 골랐는지만 보여요', () => {
let s = def.setup({ players: ['A', 'B', 'C', 'D'], options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(3)), now: 0 });
while (s.phase === 'draft') {
const p = def.activePlayers(s)[0]!;
s = def.apply(s, p, defaultAction(s, p)!, { rng: SeededRng.fromSeed(seedN(9)), now: 1 }).state;
}
expect(s.phase).toBe('select');
const pick = s.teams.A![2]!;
s = def.apply(s, 'A', { type: 'SELECT', racers: [pick] }, { rng: SeededRng.fromSeed(seedN(9)), now: 1 }).state;
expect(def.view(s, 'A').mySelection!.racers).toEqual([pick]);
const vb = def.view(s, 'B');
expect(vb.picked.A).toBe(true);
expect(vb.mySelection).toBeNull();
const secret = def.secretsOf!(s, 'A');
expect(secret.length).toBeGreaterThan(0);
for (const sec of secret) expect(JSON.stringify(vb)).not.toContain(sec);
expect(def.validate(s, 'B', { type: 'SELECT', racers: [pick] }).ok).toBe(false);
});
test('시간 초과는 안전한 기본값: 능력을 쓰지 않고, 굴릴 차례면 굴려요', () => {
const s = begin(scenario([{ id: 'hypnotist', pos: 2 }, { id: 'legs', pos: 15 }]), 'hypnotist');
const t = def.apply(s, 'P0', { type: 'TIMEOUT' }, { rng: dice(3), now: 1 }).state;
expect(pos(t, 'legs')).toBe(15);
expect(pos(t, 'hypnotist')).toBe(2);
expect(t.race!.step).toBe('roll');
const u = def.apply(t, 'P0', { type: 'TIMEOUT' }, { rng: dice(3), now: 2 }).state;
expect(pos(u, 'hypnotist')).toBe(5);
});
test('나간 사람의 선수도 자동으로 끝까지 달리고, 결과에서는 맨 뒤예요', () => {
let s = def.setup({ players: ['A', 'B', 'C'], options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(4)), now: 0 });
const rng = SeededRng.fromSeed(seedN(5));
s = def.apply(s, 'C', def.onLeave!(s, 'C')!, { rng, now: 1 }).state;
expect(s.left).toEqual(['C']);
let now = 2;
for (let i = 0; i < 3000 && !def.result(s); i++) {
const p = def.activePlayers(s)[0]!;
now += 1000;
s = def.apply(s, p, { type: 'TIMEOUT' }, { rng, now }).state;
}
const r = def.result(s)!;
expect(r).not.toBeNull();
expect(r.ranking.at(-1)).toContain('C');
// Everyone else leaving ends the game.
let t = def.setup({ players: ['A', 'B'], options: def.defaultOptions, rng: SeededRng.fromSeed(seedN(4)), now: 0 });
t = def.apply(t, 'B', { type: 'LEAVE' }, { rng, now: 1 }).state;
expect(def.result(t)!.reason).toBe('resign');
expect(def.result(t)!.ranking[0]).toEqual(['A']);
});
test('점수표: 1등 3점, 2등 1점(갈수록 커지는 점수표도 있어요)', async () => {
const { medalPoints } = await import('./rules');
expect([1, 2, 3, 4].map((n) => medalPoints('flat', n))).toEqual(Array(4).fill({ gold: 3, silver: 1 }));
expect([1, 2, 3, 4].map((n) => medalPoints('rising', n).gold)).toEqual([3, 4, 5, 6]);
});
});
// ---------------------------------------------------------------- random games
function invariant(st: unknown) {
const s = st as MagicalAthleteState;
const all = s.seats.flatMap((p) => s.teams[p]!);
if (new Set(all).size !== all.length) throw new Error('racer on two teams');
for (const p of s.seats) {
if (s.used[p]!.some((id) => !s.teams[p]!.includes(id))) throw new Error('raced a racer not on the team');
if (s.used[p]!.length > s.perRace * 4) throw new Error('too many races');
}
const r = s.race;
if (r) {
for (const x of r.racers) if (x.pos < 0 || x.pos > FINISH) throw new Error(`bad position ${x.pos}`);
if (r.finishers.length > 2) throw new Error('more than two finishers');
if (r.racers.length !== s.seats.length * s.perRace) throw new Error('field size');
}
const golds = s.seats.reduce((n, p) => n + s.scores[p]!.gold, 0);
const silvers = s.seats.reduce((n, p) => n + s.scores[p]!.silver, 0);
if (golds !== s.results.filter((x) => x.gold).length || silvers !== s.results.filter((x) => x.silver).length) throw new Error('medal count');
for (const p of s.seats) if (s.scores[p]!.bonus < 0) throw new Error('negative bonus');
}
describe('무작위 대국', () => {
const optionsFor = (i: number) =>
def.optionsSchema.parse({
twoRacers: i % 7 === 0 ? 'off' : 'auto',
track: (['alternate', 'mild', 'wild'] as const)[i % 3],
scoring: i % 2 ? 'flat' : 'rising',
});
const ENGINE = playoutSeeds(200);
test(`엔진 공통 무작위 대국 ${ENGINE}판: 끝나고, 비공개 정보가 새지 않아요`, () => {
for (let i = 1; i <= ENGINE; i++) {
const n = 2 + (i % 5);
const r = randomPlayout(def, { players: Array.from({ length: n }, (_, k) => `p${k}`), options: optionsFor(i), seed: seedN(i), maxSteps: 6000, invariant, maxApplyMs: 30 });
expect(r.finished).toBe(true);
expect((r.finalState as MagicalAthleteState).results).toHaveLength(4);
}
}, 60_000);
const FAST = playoutSeeds(1000);
test(`빠른 무작위 대국 ${FAST}판: 보존 규칙, 경주 4번, 경주마다 차례 수 상한 안에서 끝나요`, () => {
let capped = 0;
for (let i = 1; i <= FAST; i++) {
const n = 2 + (i % 5);
const rng = SeededRng.fromSeed(seedN(5000 + i));
const chooser = SeededRng.fromSeed(seedN(9000 + i));
let s = def.setup({ players: Array.from({ length: n }, (_, k) => `p${k}`), options: optionsFor(i), rng, now: 0 });
let steps = 0;
while (!def.result(s)) {
if (++steps > 4000) throw new Error(`seed ${i}: game did not finish`);
const actives = def.activePlayers(s);
const p = actives[chooser.int(actives.length)]!;
const legal = def.legalActions!(s, p);
const a = legal[chooser.int(legal.length)]!;
expect(def.validate(s, p, a).ok).toBe(true);
s = def.apply(s, p, a, { rng, now: steps }).state;
invariant(s);
}
expect(s.results).toHaveLength(4);
capped += s.results.filter((x) => x.capped).length;
// Every racer raced exactly once.
for (const p of s.seats) expect(s.used[p]).toHaveLength(s.perRace * 4);
}
expect(capped).toBeLessThanOrEqual(Math.ceil(FAST / 50));
}, 120_000);
test('같은 시드면 같은 결과(결정성)', () => {
for (let i = 1; i <= 5; i++) {
const a = randomPlayout(def, { players: ['a', 'b', 'c'], seed: seedN(100 + i), maxApplyMs: 30 });
const b = randomPlayout(def, { players: ['a', 'b', 'c'], seed: seedN(100 + i), maxApplyMs: 30 });
expect(JSON.stringify(a.finalState)).toBe(JSON.stringify(b.finalState));
}
});
test('시간 초과만으로도 끝나요(무한 경주 없음)', () => {
for (let i = 1; i <= 20; i++) {
const n = 2 + (i % 5);
const rng = SeededRng.fromSeed(seedN(i));
let s = def.setup({ players: Array.from({ length: n }, (_, k) => `p${k}`), options: def.defaultOptions, rng, now: 0 });
let steps = 0;
while (!def.result(s) && steps < 5000) {
const p = def.activePlayers(s)[0]!;
s = def.apply(s, p, { type: 'TIMEOUT' }, { rng, now: steps }).state;
steps++;
}
expect(def.result(s)).not.toBeNull();
}
});
test('경주가 길어지면 상한에서 자리 순서로 끝나요', () => {
// 차례 수를 상한 바로 앞으로 맞춰 상한 처리를 확인해요.
const s = begin(scenario([{ id: 'legs', pos: 20 }, { id: 'banana', pos: 10 }, { id: 'coach', pos: 3 }]), 'legs');
s.race!.turns = s.race!.racers.length * 40;
const t = act(s, { type: 'ROLL' }, dice(1));
expect(t.results).toHaveLength(1);
expect(t.results[0]!.capped).toBe(true);
expect(t.results[0]!.gold).toBe('legs');
expect(t.results[0]!.silver).toBe('banana');
});
});

View File

@@ -0,0 +1,791 @@
/**
* 야단법석 달리기 경주 엔진 (docs/games/magical-athlete.md §5.2–§5.5). Works on a state `apply` already cloned.
*
* 능력 처리 순서 (하나로 고정, 테스트로 확인):
* 1. 일어난 일(이동·굴림 등) 하나가 끝나면, 그 일로 발동하는 능력을 모아 정해진 순서로 줄(queue) 끝에 세운다:
* 경주로 칸 효과 → 지금 차례인 사람의 선수 → 시계 방향으로 다른 사람의 선수 (한 사람의 두 선수는 출전 순서대로).
* 2. 줄 앞에서부터 하나씩 처리한다. 처리하면서 또 발동한 능력은 같은 규칙으로 줄 끝에 붙는다(먼저 일어난 일이 먼저).
* 3. 한 선수의 능력은 한 차례(선수 한 명의 차례)에 POWER_CAP 번까지만 일어난다. 왕아기·깐깐이처럼 "규칙"인 능력은
* 그 뒤에도 지켜지지만 꼼지락이를 더 움직이지는 않는다. 줄은 CHAIN_CAP 개까지만 처리한다.
* 4. 두 번째 선수가 결승선을 넘는 순간 경주가 끝나고 줄에 남은 능력은 버린다.
*/
import type { GameEvent, PlayerId, Rng } from '@bg/engine';
import { RACERS, type RacerId } from './racers';
import {
BLIMP_TURN,
CHAIN_CAP,
FINISH,
LOSER_CAP,
POWER_CAP,
RACES,
SISYPHUS_START,
TURNS_PER_RACER_CAP,
medalPoints,
sideOf,
spaceAt,
type LogLine,
type MagicalAthleteState,
type RaceResult,
type RaceState,
type RacerState,
} from './rules';
type Origin = 'track' | RacerId;
interface Task {
origin: Origin;
run: () => void;
}
const LOG_KEEP = 160;
const nm = (id: RacerId) => RACERS[id].name;
/** Korean subject particle for a racer name (이/가). */
export function ga(id: RacerId): string {
const name = nm(id);
const last = name.charCodeAt(name.length - 1);
const batchim = last >= 0xac00 && last <= 0xd7a3 && (last - 0xac00) % 28 !== 0;
return `${name}${batchim ? '이' : '가'}`;
}
export function eun(id: RacerId): string {
const name = nm(id);
const last = name.charCodeAt(name.length - 1);
const batchim = last >= 0xac00 && last <= 0xd7a3 && (last - 0xac00) % 28 !== 0;
return `${name}${batchim ? '은' : '는'}`;
}
/** One apply call's view of the running race: queue of reactions, rng and the events list. */
export class Runner {
private queue: Task[] = [];
private chain = 0;
constructor(
readonly s: MagicalAthleteState,
readonly rng: Rng,
readonly ev: GameEvent[],
) {}
get r(): RaceState {
return this.s.race!;
}
// ------------------------------------------------------------ lookups
get(id: RacerId): RacerState | undefined {
return this.r.racers.find((x) => x.id === id);
}
running(): RacerState[] {
return this.r.racers.filter((x) => x.status === 'run');
}
/** The racer is in this race and still on the track (powers only work on the track). */
has(id: RacerId): RacerState | null {
const x = this.get(id);
return x && x.status === 'run' ? x : null;
}
cur(): RacerState | null {
return this.r.cur ? (this.get(this.r.cur) ?? null) : null;
}
over(): boolean {
return this.r.finishers.length >= 2 || this.running().length === 0;
}
/** Resolution order key: track first, then the current player's racers, then the others clockwise. */
private orderKey(o: Origin): number {
if (o === 'track') return -1;
const i = this.r.racers.findIndex((x) => x.id === o);
const x = this.r.racers[i];
if (!x) return 1e9;
const n = this.s.seats.length;
const seat = this.s.seats.indexOf(x.owner);
return ((seat - this.r.seat + n) % n) * 100 + i;
}
// ------------------------------------------------------------ log & powers
log(kind: LogLine['kind'], text: string, racer?: RacerId): void {
const r = this.r;
r.logSeq++;
r.log.push({ n: r.logSeq, kind, text, ...(racer ? { racer } : {}) });
if (r.log.length > LOG_KEEP) r.log.splice(0, r.log.length - LOG_KEEP);
this.ev.push({ type: 'log', n: r.logSeq, kind, text, ...(racer ? { racer } : {}) });
}
/**
* A racer's power happens: logged, and 꼼지락이 reacts. Returns false once the racer's power hit POWER_CAP this
* racer-turn (the caller then skips an optional effect; rule powers pass `force` and still apply silently).
*/
fire(id: RacerId, text: string, force = false): boolean {
const r = this.r;
const n = r.fired[id] ?? 0;
if (n >= POWER_CAP) {
if (force) this.log('power', text, id);
return false;
}
r.fired[id] = n + 1;
this.log('power', text, id);
const sc = this.has('scoocher');
if (sc && id !== 'scoocher') {
this.enqueue([
{
origin: 'scoocher',
run: () => {
const me = this.has('scoocher');
if (me && this.fire('scoocher', `꼼지락이가 ${nm(id)}의 능력을 보고 1칸 가요.`)) this.moveBy(me, 1);
},
},
]);
}
return true;
}
enqueue(tasks: Task[]): void {
const sorted = tasks.map((t, i) => ({ t, i, k: this.orderKey(t.origin) })).sort((a, b) => a.k - b.k || a.i - b.i);
for (const x of sorted) this.queue.push(x.t);
}
/** Handles queued reactions first-in first-out until none are left or the race is over. */
drain(): void {
while (this.queue.length && !this.over()) {
if (++this.chain > CHAIN_CAP) {
this.queue = [];
this.log('info', '능력이 너무 많이 이어져서 여기서 멈춰요.');
break;
}
this.queue.shift()!.run();
}
if (this.over()) this.queue = [];
}
// ------------------------------------------------------------ movement
private occupied(pos: number, except: RacerState): boolean {
return this.r.racers.some((y) => y !== except && y.status === 'run' && y.pos === pos);
}
/** 왕아기: nobody else stops on its space (except the start); they stop one space back. */
private babyAdjust(x: RacerState, target: number, floor: number): number {
const baby = this.has('hugebaby');
if (!baby || x === baby || target === 0 || baby.pos !== target) return target;
const t = Math.max(floor, target - 1);
if (t !== x.pos) this.fire('hugebaby', `왕아기가 버티고 있어서 ${eun(x.id)} 한 칸 뒤에 멈춰요.`, true);
return t;
}
moveBy(x: RacerState, n: number): void {
if (x.status !== 'run' || n === 0) return;
if (n > 0) this.forward(x, n);
else this.backward(x, -n);
}
private forward(x: RacerState, n: number): void {
const from = x.pos;
let target = from + n;
if (x.id === 'leaptoad') {
let p = from;
let counted = 0;
let skipped = 0;
while (counted < n) {
p++;
if (p < FINISH && this.occupied(p, x)) skipped++;
else counted++;
}
if (skipped > 0) {
this.fire('leaptoad', `폴짝개구리가 선수가 있는 칸 ${skipped}칸을 건너뛰어요.`, true);
target = p;
}
}
if (target > FINISH && x.id !== 'stickler' && this.has('stickler')) {
this.fire('stickler', `깐깐이 때문에 ${eun(x.id)} 결승선까지 딱 ${FINISH - from}칸이 아니라서 못 가요.`, true);
return;
}
if (target < FINISH) target = this.babyAdjust(x, target, from);
if (target <= from) return;
const passed = this.running()
.filter((y) => y !== x && y.pos > from && y.pos < target)
.sort((a, b) => a.pos - b.pos);
x.pos = Math.min(target, FINISH);
this.log('move', `${ga(x.id)} ${target - from}칸 가서 ${x.pos >= FINISH ? '결승선' : `${x.pos}칸`}에 왔어요.`, x.id);
if (target >= FINISH) this.finish(x);
const tasks: Task[] = [];
if (x.status === 'run') this.stopTasks(x, tasks);
if (x.id === 'centaur') {
for (const y of passed)
tasks.push({
origin: 'centaur',
run: () => {
if (y.status === 'run' && this.has('centaur') && this.fire('centaur', `켄타우로스가 앞지른 ${eun(y.id)} 2칸 뒤로 밀려나요.`)) this.moveBy(y, -2);
},
});
}
if (x.id !== 'banana' && passed.some((y) => y.id === 'banana')) {
tasks.push({
origin: 'banana',
run: () => {
if (x.status === 'run' && this.has('banana') && this.fire('banana', `${ga(x.id)} 바나나를 앞지르다 미끄러져 넘어졌어요.`)) this.trip(x);
},
});
}
this.enqueue(tasks);
}
private backward(x: RacerState, n: number): void {
const from = x.pos;
let target = Math.max(0, from - n);
target = this.babyAdjust(x, target, 0);
if (target === from) return;
x.pos = target;
this.log('move', `${ga(x.id)} ${from - target}칸 뒤로 가서 ${target === 0 ? '출발점' : `${target}칸`}에 왔어요.`, x.id);
const tasks: Task[] = [];
this.stopTasks(x, tasks);
this.enqueue(tasks);
}
/** Puts a racer on a space without moving through the ones between (no passing). */
warp(x: RacerState, to: number, text: string): void {
if (x.status !== 'run') return;
const target = this.babyAdjust(x, to, 0);
x.pos = target;
this.log('move', `${text} (${target === 0 ? '출발점' : `${target}칸`})`, x.id);
const tasks: Task[] = [];
this.stopTasks(x, tasks);
this.enqueue(tasks);
}
/** Swap two racers' spaces (자리바꿈이); both have stopped on their new spaces. */
swap(a: RacerState, b: RacerState): void {
const pa = a.pos;
a.pos = b.pos;
b.pos = pa;
this.log('move', `${ga(a.id)} ${nm(b.id)}와 자리를 바꿨어요. (${a.pos}칸 ↔ ${b.pos}칸)`, a.id);
const tasks: Task[] = [];
this.stopTasks(a, tasks);
this.stopTasks(b, tasks);
this.enqueue(tasks);
}
/** What happens when `x` stops where it is: the track space (거친 판), then 먹보 if it is 먹보. */
private stopTasks(x: RacerState, tasks: Task[]): void {
const at = x.pos;
const sp = spaceAt(this.r.side, at);
if (sp && at > 0) {
tasks.push({
origin: 'track',
run: () => {
if (x.status !== 'run' || x.pos !== at) return;
if (sp.kind === 'arrow') {
this.log('space', `${ga(x.id)} ${sp.by > 0 ? '앞' : '뒤'} 화살표 칸에 멈춰 ${Math.abs(sp.by)}칸 ${sp.by > 0 ? '앞으로' : '뒤로'} 가요.`, x.id);
this.moveBy(x, sp.by);
} else if (sp.kind === 'rock') {
this.log('space', `${ga(x.id)} 돌 칸에 걸려 넘어졌어요.`, x.id);
x.tripped = true;
} else {
this.log('space', `${ga(x.id)} 별 칸에 멈춰 1점을 받아요.`, x.id);
this.addBonus(x.owner, 1);
}
},
});
}
if (x.id === 'mouth' && at > 0) {
tasks.push({
origin: 'mouth',
run: () => {
if (x.status !== 'run' || x.pos !== at) return;
const others = this.running().filter((y) => y !== x && y.pos === at);
if (others.length === 1 && this.fire('mouth', `먹보가 같은 칸의 ${nm(others[0]!.id)}를 꿀꺽! ${eun(others[0]!.id)} 탈락이에요.`)) {
others[0]!.status = 'out';
others[0]!.tripped = false;
}
},
});
}
}
trip(x: RacerState): void {
if (x.status === 'run') x.tripped = true;
}
addBonus(owner: PlayerId, n: number): void {
const sc = this.s.scores[owner]!;
const before = sc.bonus;
sc.bonus = Math.max(0, sc.bonus + n);
const r = this.r;
r.bonus[owner] = (r.bonus[owner] ?? 0) + (sc.bonus - before);
}
private finish(x: RacerState): void {
x.status = 'done';
x.tripped = false;
x.pos = FINISH;
this.r.finishers.push(x.id);
x.place = this.r.finishers.length;
this.log('finish', `${ga(x.id)} ${x.place}등으로 결승선을 넘었어요!`, x.id);
this.ev.push({ type: 'finished', racer: x.id, place: x.place });
}
// ------------------------------------------------------------ turn flow
/** Begins `seat`'s turn (or only Skipper's turn after a 1). */
beginPlayerTurn(seat: number, only?: RacerId): void {
const r = this.r;
r.seat = seat;
const owner = this.s.seats[seat]!;
r.pending = only ? [only] : this.running().filter((x) => x.owner === owner).map((x) => x.id);
r.cur = null;
if (r.pending.length >= 2) {
r.step = 'go';
this.s.turnSeq++;
return;
}
this.startRacerTurn(r.pending[0]!);
}
startRacerTurn(id: RacerId): void {
const r = this.r;
r.pending = r.pending.filter((p) => p !== id);
r.cur = id;
const x = this.get(id)!;
r.turnStartPos = x.pos;
r.turns++;
r.fired = {};
r.roll = null;
r.cancelMain = false;
this.chain = 0;
this.s.turnSeq++;
this.log('turn', `${nm(id)} 차례예요.`, id);
if (id === 'loser' && r.loserPts < LOSER_CAP && this.aloneLast(x)) {
if (this.fire('loser', '귀여운 꼴찌가 혼자 꼴찌라서 1점을 받아요.')) {
r.loserPts++;
this.addBonus(x.owner, 1);
}
}
this.drain();
if (this.over()) return this.endRace();
if (x.status !== 'run') return this.endRacerTurn();
if (this.startOptions(x).length > 0) {
r.step = 'start';
return;
}
this.afterStart();
}
aloneLast(x: RacerState): boolean {
const run = this.running();
return run.length >= 2 && run.every((y) => y === x || y.pos > x.pos);
}
aloneLead(x: RacerState): boolean {
const run = this.running();
return run.length >= 2 && run.every((y) => y === x || y.pos < x.pos);
}
/** Turn-start choices (최면술사·끼어들기·자리바꿈이), as `CHOOSE` keys; empty = nothing to choose. */
startOptions(x: RacerState): string[] {
const others = this.running().filter((y) => y !== x && y.pos !== x.pos);
if (x.id === 'hypnotist') return others.map((y) => `racer:${y.id}`);
if (x.id === 'flipflop') return x.tripped ? [] : others.map((y) => `racer:${y.id}`);
if (x.id === 'thirdwheel') {
const count = new Map<number, RacerState[]>();
for (const y of this.running()) if (y !== x) count.set(y.pos, [...(count.get(y.pos) ?? []), y]);
return [...count.entries()]
.filter(([pos, ys]) => pos !== x.pos && ys.length === 2 && !ys.some((y) => y.id === 'hugebaby'))
.map(([pos]) => pos)
.sort((a, b) => a - b)
.map((pos) => `space:${pos}`);
}
return [];
}
/** The turn-start choice: `skip` or one of `startOptions`. */
chooseStart(key: string): void {
const x = this.cur()!;
const r = this.r;
if (key !== 'skip') {
if (x.id === 'hypnotist') {
const y = this.has(key.slice(6) as RacerId)!;
if (this.fire('hypnotist', `최면술사가 ${nm(y.id)}를 자기 칸으로 끌어와요.`)) this.warp(y, x.pos, `${ga(y.id)} 최면에 걸려 끌려왔어요.`);
} else if (x.id === 'thirdwheel') {
const pos = Number(key.slice(6));
if (this.fire('thirdwheel', `끼어들기가 선수 둘이 있는 ${pos}칸으로 끼어들어요.`)) this.warp(x, pos, '끼어들기가 옮겨 갔어요.');
} else if (x.id === 'flipflop') {
const y = this.has(key.slice(6) as RacerId)!;
if (this.fire('flipflop', `자리바꿈이가 주사위 대신 ${nm(y.id)}와 자리를 바꿔요.`)) {
this.swap(x, y);
r.cancelMain = true;
}
}
this.drain();
if (this.over()) return this.endRace();
if (x.status !== 'run' || r.cancelMain) return this.endRacerTurn();
}
this.afterStart();
}
private afterStart(): void {
const x = this.cur()!;
const r = this.r;
if (x.tripped) {
x.tripped = false;
this.log('info', `${ga(x.id)} 넘어져 있어서 일어나기만 해요.`, x.id);
return this.endRacerTurn();
}
if (x.id === 'hare' && this.aloneLead(x)) {
this.fire('hare', '토끼가 혼자 1등이라 낮잠을 자요. 이번 차례는 쉬어요.', true);
this.drain();
if (this.over()) return this.endRace();
return this.endRacerTurn();
}
r.step = 'roll';
}
roll(): void {
const r = this.r;
const value = 1 + this.rng.int(6);
r.roll = { value, rerolls: 0 };
this.s.rollSeq++;
this.log('roll', `${ga(r.cur!)} 주사위를 굴려 ${value}이(가) 나왔어요.`, r.cur!);
this.ev.push({ type: 'rolled', racer: r.cur, value });
if (r.cur === 'magician') {
r.step = 'reroll';
this.s.turnSeq++;
return;
}
this.afterDie();
}
/** 마술사: `use` rolls again (twice at most). */
reroll(use: boolean): void {
const r = this.r;
if (use && r.roll && r.roll.rerolls < 2) {
const value = 1 + this.rng.int(6);
r.roll = { value, rerolls: r.roll.rerolls + 1 };
this.s.rollSeq++;
this.fire('magician', `마술사가 주사위를 다시 굴려 ${value}이(가) 나왔어요.`);
this.ev.push({ type: 'rolled', racer: r.cur, value });
this.drain();
if (this.over()) return this.endRace();
if (r.roll.rerolls < 2 && this.cur()?.status === 'run') {
this.s.turnSeq++;
return;
}
}
this.afterDie();
}
/** Powers that react to the die face (§5.4: 시시포스 → 심부름꾼·자벌레·새치기 in seat order), then the main move. */
private afterDie(): void {
const r = this.r;
const d = r.roll!.value!;
const curId = r.cur!;
const tasks: Task[] = [];
if (curId === 'sisyphus' && d === 6)
tasks.push({
origin: 'sisyphus',
run: () => {
const me = this.has('sisyphus');
if (!me || !this.fire('sisyphus', '시시포스가 6을 굴려 바위와 함께 출발점으로 굴러떨어져요.', true)) return;
r.cancelMain = true;
if (r.sisyphusPts > 0) {
r.sisyphusPts--;
this.addBonus(me.owner, -1);
this.log('info', '시시포스가 1점을 잃었어요.', 'sisyphus');
}
this.warp(me, 0, '시시포스가 출발점으로 돌아갔어요.');
},
});
for (const y of this.running()) {
if (y.id === curId) {
if (y.id === 'skipper' && d === 1) tasks.push(this.skipperTask());
continue;
}
if (y.id === 'lackey' && d === 6)
tasks.push({
origin: 'lackey',
run: () => {
const me = this.has('lackey');
if (me && this.fire('lackey', `심부름꾼이 6을 보고 먼저 2칸 가요.`)) this.moveBy(me, 2);
},
});
if (y.id === 'inchworm' && d === 1)
tasks.push({
origin: 'inchworm',
run: () => {
const me = this.has('inchworm');
if (me && this.fire('inchworm', `자벌레가 1을 보고 ${ga(curId)} 가는 대신 1칸 가요.`)) {
r.cancelMain = true;
this.moveBy(me, 1);
}
},
});
if (y.id === 'skipper' && d === 1) tasks.push(this.skipperTask());
}
this.enqueue(tasks);
this.drain();
if (this.over()) return this.endRace();
const x = this.cur()!;
if (x.status !== 'run' || r.cancelMain) return this.endRacerTurn();
if ((x.id === 'alchemist' && d <= 2) || x.id === 'rocket') {
r.step = 'boost';
this.s.turnSeq++;
return;
}
this.mainMove(d, false);
}
private skipperTask(): Task {
return {
origin: 'skipper',
run: () => {
if (this.has('skipper') && !this.r.skipperNext && this.fire('skipper', '1이 나와서 다음 차례는 새치기가 가져가요.')) this.r.skipperNext = true;
},
};
}
/** 롱다리: 5 spaces instead of rolling. */
legs(): void {
const r = this.r;
r.roll = { value: null, rerolls: 0 };
this.fire('legs', '롱다리가 주사위 대신 성큼성큼 5칸 가요.');
this.drain();
if (this.over()) return this.endRace();
this.mainMove(5, false);
}
/** 연금술사 (1·2 → 4) / 로켓 박사 (두 배, 간 뒤 넘어짐). */
boost(use: boolean): void {
const r = this.r;
const d = r.roll!.value!;
const x = this.cur()!;
if (!use) return this.mainMove(d, false);
if (x.id === 'alchemist') {
this.fire('alchemist', `연금술사가 ${d}을(를) 4로 바꿔요.`);
this.drain();
if (this.over()) return this.endRace();
return this.mainMove(4, false);
}
this.fire('rocket', `로켓 박사가 ${d}의 두 배, ${d * 2}로 날아가요!`);
this.drain();
if (this.over()) return this.endRace();
this.mainMove(d * 2, true);
}
/** Main move with every modifier (토끼·비행선·코치·끈적이), then the end of the racer's turn. */
mainMove(base: number, rocket: boolean): void {
const x = this.cur()!;
if (x.status !== 'run') return this.endRacerTurn();
let amount = base;
if (x.id === 'hare') {
amount += 2;
this.fire('hare', '토끼는 주사위 이동 +2예요.', true);
}
if (x.id === 'blimp') {
const up = x.pos < BLIMP_TURN;
amount += up ? 3 : -1;
this.fire('blimp', up ? '비행선이 바람을 타고 +3이에요.' : '비행선이 바람이 빠져 −1이에요.', true);
}
const coach = this.has('coach');
if (coach && (coach === x || coach.pos === x.pos)) {
amount += 1;
this.fire('coach', coach === x ? '코치는 주사위 이동 +1이에요.' : `코치가 같은 칸의 ${nm(x.id)}를 응원해서 +1이에요.`, true);
}
const gunk = this.has('gunk');
if (gunk && gunk !== x) {
amount -= 1;
this.fire('gunk', `끈적이 때문에 ${eun(x.id)} 주사위 이동 −1이에요.`, true);
}
amount = Math.max(0, amount);
this.drain();
if (this.over()) return this.endRace();
if (x.status !== 'run') return this.endRacerTurn();
if (amount === 0) this.log('move', `${ga(x.id)} 이번에는 한 칸도 못 갔어요.`, x.id);
this.moveBy(x, amount);
this.drain();
if (this.over()) return this.endRace();
if (rocket && x.status === 'run') {
x.tripped = true;
this.log('info', '로켓 박사가 착지하다 넘어졌어요.', 'rocket');
}
this.endRacerTurn();
}
/** 야유꾼, then the next racer / player (or the end of the race). */
endRacerTurn(): void {
const r = this.r;
const x = this.cur();
if (x && x.status === 'run' && x.id !== 'heckler' && this.has('heckler') && Math.abs(x.pos - r.turnStartPos) <= 1) {
this.enqueue([
{
origin: 'heckler',
run: () => {
const me = this.has('heckler');
if (me && this.fire('heckler', `${ga(x.id)} 거의 못 갔어요. 야유꾼이 신나서 2칸 가요.`)) this.moveBy(me, 2);
},
},
]);
this.drain();
}
if (this.over()) return this.endRace();
this.nextTurn();
}
private nextTurn(): void {
const r = this.r;
r.cur = null;
r.roll = null;
if (r.turns >= r.racers.length * TURNS_PER_RACER_CAP) {
r.capped = true;
this.log('info', '경주가 너무 길어져서 지금 자리로 순위를 정해요.');
return this.endRace();
}
r.pending = r.pending.filter((id) => this.has(id));
if (r.pending.length >= 2) {
r.step = 'go';
this.s.turnSeq++;
return;
}
if (r.pending.length === 1) return this.startRacerTurn(r.pending[0]!);
if (r.skipperNext) {
r.skipperNext = false;
const sk = this.has('skipper');
if (sk) return this.beginPlayerTurn(this.s.seats.indexOf(sk.owner), 'skipper');
}
const n = this.s.seats.length;
for (let k = 1; k <= n; k++) {
const seat = (r.seat + k) % n;
const owner = this.s.seats[seat]!;
if (this.running().some((y) => y.owner === owner)) return this.beginPlayerTurn(seat);
}
this.endRace();
}
// ------------------------------------------------------------ race end
endRace(): void {
const s = this.s;
const r = this.r;
if (s.phase !== 'race' || !(this.over() || r.capped)) return;
this.queue = [];
// Places for the racers still on the track (only used for the next first player and a capped race).
const rest = r.racers
.map((x, i) => ({ x, i }))
.filter(({ x }) => x.status === 'run')
.sort((a, b) => b.x.pos - a.x.pos || a.i - b.i);
if (r.capped) {
for (const { x } of rest) {
if (r.finishers.length >= 2) break;
r.finishers.push(x.id);
x.place = r.finishers.length;
x.status = 'done';
this.log('finish', `${ga(x.id)} 자리 순서로 ${x.place}등이 됐어요.`, x.id);
}
}
const pts = medalPoints(s.options.scoring, r.no);
const points: Record<PlayerId, number> = Object.fromEntries(s.seats.map((p) => [p, r.bonus[p] ?? 0]));
const gold = r.finishers[0] ?? null;
const silver = r.finishers[1] ?? null;
if (gold) {
const o = this.get(gold)!.owner;
s.scores[o]!.gold++;
s.scores[o]!.medal += pts.gold;
points[o]! += pts.gold;
}
if (silver) {
const o = this.get(silver)!.owner;
s.scores[o]!.silver++;
s.scores[o]!.medal += pts.silver;
points[o]! += pts.silver;
}
const result: RaceResult = {
no: r.no,
side: r.side,
field: r.racers.map((x) => ({ id: x.id, owner: x.owner, place: x.place, status: x.status, pos: x.pos })),
gold,
silver,
points,
capped: r.capped,
};
s.results.push(result);
this.log('info', `${r.no}번째 경주 끝! 금메달 ${gold ? nm(gold) : '없음'}, 은메달 ${silver ? nm(silver) : '없음'}.`);
this.ev.push({ type: 'raceEnd', no: r.no, gold, silver });
// Next race: the owner of the racer furthest behind goes first (원작). Out of the race counts as furthest behind.
const notIn = r.racers.filter((x) => !r.finishers.includes(x.id));
const outs = notIn.filter((x) => x.status === 'out');
const last = outs[0] ?? notIn.sort((a, b) => a.pos - b.pos)[0] ?? this.get(r.finishers[r.finishers.length - 1]!);
if (last) s.firstSeat = s.seats.indexOf(last.owner);
r.cur = null;
r.pending = [];
r.roll = null;
s.raceNo++;
s.turnSeq++;
if (s.raceNo > RACES) {
s.phase = 'finished';
this.ev.push({ type: 'gameOver' });
return;
}
s.phase = 'select';
for (const p of s.seats) s.selections[p] = null;
autoSelect(s);
if (s.seats.every((p) => s.selections[p] !== null)) startRace(s, this.rng, this.ev);
}
}
// ---------------------------------------------------------------- race setup
/** Racers a player has not raced yet. */
export const unused = (s: MagicalAthleteState, p: PlayerId): RacerId[] => s.teams[p]!.filter((id) => !s.used[p]!.includes(id));
/** Fills in forced choices (only `perRace` racers left) and the picks of players who left. */
export function autoSelect(s: MagicalAthleteState): void {
for (const p of s.seats) {
if (s.selections[p] !== null) continue;
const left = unused(s, p);
if (left.length <= s.perRace || s.left.includes(p)) s.selections[p] = left.slice(0, s.perRace);
}
}
export function startRace(s: MagicalAthleteState, rng: Rng, ev: GameEvent[]): void {
const n = s.seats.length;
const racers: RacerState[] = [];
for (let k = 0; k < n; k++) {
const p = s.seats[(s.firstSeat + k) % n]!;
const sel = s.selections[p] ?? [];
for (const id of sel) {
racers.push({ id, owner: p, pos: 0, status: 'run', tripped: false, place: null });
s.used[p]!.push(id);
}
}
s.phase = 'race';
s.race = {
no: s.raceNo,
side: sideOf(s.options.track, s.raceNo),
racers,
seat: s.firstSeat,
pending: [],
cur: null,
step: 'roll',
roll: null,
turnStartPos: 0,
skipperNext: false,
cancelMain: false,
turns: 0,
fired: {},
loserPts: 0,
sisyphusPts: 0,
finishers: [],
capped: false,
bonus: {},
log: [],
logSeq: 0,
};
const run = new Runner(s, rng, ev);
run.log('info', `${s.raceNo}번째 경주 출발! ${s.race.side === 'wild' ? '거친 판(화살표·돌·별 칸)' : '순한 판'}이에요.`);
ev.push({ type: 'raceStart', no: s.raceNo, field: racers.map((x) => x.id) });
const sis = racers.find((x) => x.id === 'sisyphus');
if (sis) {
s.race.sisyphusPts = SISYPHUS_START;
run.addBonus(sis.owner, SISYPHUS_START);
run.log('info', `시시포스가 ${SISYPHUS_START}점을 안고 출발해요.`, 'sisyphus');
}
run.beginPlayerTurn(s.firstSeat);
}

View File

@@ -0,0 +1,85 @@
/**
* 야단법석 달리기 선수 24명 (docs/games/magical-athlete.md §5.3). 원작 Magical Athlete(2025)의 선수 가운데 능력이
* 분명하고 서로 섞여도 처리 순서가 하나로 정해지는 선수만 골랐다. 이름은 한국판 이름을 확인하지 못해 쉬운 우리말로 지었다.
*
* `hook` 은 능력이 끼어드는 때(엔진 race.ts 가 이 값으로 처리 위치를 찾는다):
* - turnStart: 내 차례 시작 / choiceStart: 내 차례 시작에 고를 수 있음 / mainMove: 굴리기 대신(고를 수 있음)
* - afterRoll: 내가 굴린 뒤 고를 수 있음 / anyRoll: 누군가 굴린 눈을 보고 / modifier: 주사위 이동 칸 수를 바꿈
* - onMove: 움직일 때(내가 또는 남이) / onStop: 멈췄을 때 / turnEnd: 남의 차례가 끝날 때 / onPower: 남의 능력이 일어날 때
* - raceStart: 경주 시작
*/
export const RACER_IDS = [
'alchemist',
'banana',
'blimp',
'centaur',
'coach',
'flipflop',
'gunk',
'hare',
'heckler',
'hugebaby',
'hypnotist',
'inchworm',
'lackey',
'leaptoad',
'legs',
'loser',
'magician',
'mouth',
'rocket',
'scoocher',
'sisyphus',
'skipper',
'stickler',
'thirdwheel',
] as const;
export type RacerId = (typeof RACER_IDS)[number];
export type RacerHook = 'turnStart' | 'choiceStart' | 'mainMove' | 'afterRoll' | 'anyRoll' | 'modifier' | 'onMove' | 'onStop' | 'turnEnd' | 'onPower' | 'raceStart';
export interface RacerDef {
id: RacerId;
/** Korean display name. */
name: string;
/** Original English name (docs only). */
original: string;
emoji: string;
/** One-line ability, plain Korean (~해요). */
text: string;
hook: RacerHook;
/** True when the owner chooses whether to use it (원작 "~할 수 있다"). */
optional: boolean;
/** Computer's draft value 1~10 (bot.ts). */
rating: number;
}
export const RACERS: Record<RacerId, RacerDef> = {
alchemist: { id: 'alchemist', name: '연금술사', original: 'Alchemist', emoji: '⚗️', text: '주사위가 1이나 2면 4칸 갈 수 있어요.', hook: 'afterRoll', optional: true, rating: 5 },
banana: { id: 'banana', name: '바나나', original: 'Banana', emoji: '🍌', text: '나를 앞질러 간 선수는 넘어져요(다음 주사위 이동을 쉬어요).', hook: 'onMove', optional: false, rating: 5 },
blimp: { id: 'blimp', name: '비행선', original: 'Blimp', emoji: '🎈', text: '15칸 전에는 주사위 이동 +3, 15칸부터는 −1이에요.', hook: 'modifier', optional: false, rating: 6 },
centaur: { id: 'centaur', name: '켄타우로스', original: 'Centaur', emoji: '🏇', text: '내가 앞지른 선수는 2칸 뒤로 밀려나요.', hook: 'onMove', optional: false, rating: 5 },
coach: { id: 'coach', name: '코치', original: 'Coach', emoji: '📣', text: '나와 내 칸에 있는 선수는 주사위 이동 +1이에요.', hook: 'modifier', optional: false, rating: 4 },
flipflop: { id: 'flipflop', name: '자리바꿈이', original: 'Flip Flop', emoji: '🔄', text: '차례 시작에 주사위 대신 다른 선수와 자리를 바꿀 수 있어요.', hook: 'choiceStart', optional: true, rating: 8 },
gunk: { id: 'gunk', name: '끈적이', original: 'Gunk', emoji: '🟢', text: '다른 선수는 모두 주사위 이동 −1이에요.', hook: 'modifier', optional: false, rating: 6 },
hare: { id: 'hare', name: '토끼', original: 'Hare', emoji: '🐇', text: '주사위 이동 +2. 차례 시작에 혼자 1등이면 그 차례는 쉬어요.', hook: 'modifier', optional: false, rating: 5 },
heckler: { id: 'heckler', name: '야유꾼', original: 'Heckler', emoji: '📢', text: '다른 선수가 차례를 마칠 때 시작 칸에서 1칸 이하로 움직였으면 내가 2칸 가요.', hook: 'turnEnd', optional: false, rating: 6 },
hugebaby: { id: 'hugebaby', name: '왕아기', original: 'Huge Baby', emoji: '👶', text: '다른 선수는 내 칸에 멈출 수 없어요. 한 칸 뒤에 멈춰요(출발점 빼고).', hook: 'onStop', optional: false, rating: 4 },
hypnotist: { id: 'hypnotist', name: '최면술사', original: 'Hypnotist', emoji: '🌀', text: '차례 시작에 다른 선수 하나를 내 칸으로 끌어올 수 있어요.', hook: 'choiceStart', optional: true, rating: 7 },
inchworm: { id: 'inchworm', name: '자벌레', original: 'Inchworm', emoji: '🐛', text: '다른 선수가 1을 굴리면 그 선수는 못 가고 내가 1칸 가요.', hook: 'anyRoll', optional: false, rating: 5 },
lackey: { id: 'lackey', name: '심부름꾼', original: 'Lackey', emoji: '🛎️', text: '다른 선수가 6을 굴리면 그 선수가 가기 전에 내가 2칸 가요.', hook: 'anyRoll', optional: false, rating: 5 },
leaptoad: { id: 'leaptoad', name: '폴짝개구리', original: 'Leaptoad', emoji: '🐸', text: '갈 때 선수가 있는 칸은 세지 않고 건너뛰어요.', hook: 'onMove', optional: false, rating: 6 },
legs: { id: 'legs', name: '롱다리', original: 'Legs', emoji: '🦵', text: '주사위를 굴리는 대신 5칸 갈 수 있어요.', hook: 'mainMove', optional: true, rating: 8 },
loser: { id: 'loser', name: '귀여운 꼴찌', original: 'Lovable Loser', emoji: '🥺', text: '차례 시작에 혼자 꼴찌면 1점을 받아요(한 경주에 3점까지).', hook: 'turnStart', optional: false, rating: 5 },
magician: { id: 'magician', name: '마술사', original: 'Magician', emoji: '🎩', text: '주사위를 두 번까지 다시 굴릴 수 있어요.', hook: 'afterRoll', optional: true, rating: 6 },
mouth: { id: 'mouth', name: '먹보', original: 'M.O.U.T.H.', emoji: '👄', text: '다른 선수가 딱 하나 있는 칸에 멈추면 그 선수는 탈락해요.', hook: 'onStop', optional: false, rating: 6 },
rocket: { id: 'rocket', name: '로켓 박사', original: 'Rocket Scientist', emoji: '🚀', text: '굴린 눈을 두 배로 갈 수 있어요. 대신 간 뒤에 넘어져요.', hook: 'afterRoll', optional: true, rating: 6 },
scoocher: { id: 'scoocher', name: '꼼지락이', original: 'Scoocher', emoji: '🐌', text: '다른 선수의 능력이 일어날 때마다 1칸 가요.', hook: 'onPower', optional: false, rating: 8 },
sisyphus: { id: 'sisyphus', name: '시시포스', original: 'Sisyphus', emoji: '🪨', text: '경주 시작에 4점을 받아요. 6을 굴리면 출발점으로 돌아가고 1점을 잃어요.', hook: 'raceStart', optional: false, rating: 6 },
skipper: { id: 'skipper', name: '새치기', original: 'Skipper', emoji: '⏭️', text: '누구든 1을 굴리면 다음 차례는 내 차례예요.', hook: 'anyRoll', optional: false, rating: 5 },
stickler: { id: 'stickler', name: '깐깐이', original: 'Stickler', emoji: '📏', text: '다른 선수는 딱 맞는 칸 수로만 결승선을 넘어요. 넘치면 못 가요.', hook: 'onMove', optional: false, rating: 5 },
thirdwheel: { id: 'thirdwheel', name: '끼어들기', original: 'Third Wheel', emoji: '🚲', text: '차례 시작에 선수가 딱 둘 있는 칸으로 옮겨 갈 수 있어요.', hook: 'choiceStart', optional: true, rating: 6 },
};
export const racerName = (id: RacerId): string => RACERS[id].name;

View File

@@ -0,0 +1,218 @@
/**
* 야단법석 달리기 규칙 상수·옵션·상태 타입 (docs/games/magical-athlete.md §2–§5, §8).
*/
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
import { RACER_IDS, type RacerId } from './racers';
// ---------------------------------------------------------------- options & actions
const lit = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const magicalAthleteOptionsSchema = z.object({
twoRacers: z
.enum(['auto', 'off'])
.default('auto')
.meta({ title: '2~3명일 때 선수 둘씩', labels: { auto: '켜기(원작: 2~3명이면 경주마다 선수 둘씩)', off: '끄기(언제나 한 명씩)' } }),
track: z
.enum(['alternate', 'mild', 'wild'])
.default('alternate')
.meta({ title: '경주로', labels: { alternate: '순한 판·거친 판 번갈아(원작)', mild: '모두 순한 판', wild: '모두 거친 판' } }),
scoring: z
.enum(['flat', 'rising'])
.default('flat')
.meta({ title: '점수표', labels: { flat: '경주마다 1등 3점·2등 1점', rising: '갈수록 커져요(1등 3·4·5·6점, 2등 1·1·2·2점)' } }),
turnSeconds: lit(20, 30, 60, null)
.default(30)
.meta({ title: '고르기·굴리기 제한 시간', labels: { 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }),
});
export type MagicalAthleteOptions = z.infer<typeof magicalAthleteOptionsSchema>;
const racerId = z.enum(RACER_IDS);
export const magicalAthleteActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('DRAFT'), racer: racerId }),
z.object({ type: z.literal('SELECT'), racers: z.array(racerId).min(1).max(2) }),
z.object({ type: z.literal('GO'), racer: racerId }),
z.object({ type: z.literal('ROLL') }),
z.object({ type: z.literal('CHOOSE'), key: z.string().max(40) }),
z.object({ type: z.literal('LEAVE') }),
]);
export type MagicalAthleteClientAction = z.infer<typeof magicalAthleteActionSchema>;
/** Client actions plus the system-only timer action (docs/09 §2). */
export type MagicalAthleteAction = MagicalAthleteClientAction | { type: 'TIMEOUT' };
// ---------------------------------------------------------------- track
/** Spaces 0 (start) … 29; a racer reaching 30 or beyond has crossed the finish line (원작: 30칸). */
export const FINISH = 30;
/** Blimp: +3 before this space, −1 from it. */
export const BLIMP_TURN = 15;
export type SpaceEffect = { kind: 'arrow'; by: number } | { kind: 'rock' } | { kind: 'star' };
export type TrackSide = 'mild' | 'wild';
/**
* 거친 판 특수 칸(원작: 화살표·돌·별; 칸 배치는 우리 판). An arrow never leads onto another arrow, so arrows can't loop.
*/
export const WILD_SPACES: Readonly<Record<number, SpaceEffect>> = {
3: { kind: 'star' },
5: { kind: 'arrow', by: 3 },
7: { kind: 'rock' },
10: { kind: 'star' },
12: { kind: 'arrow', by: -3 },
14: { kind: 'arrow', by: 2 },
17: { kind: 'rock' },
19: { kind: 'star' },
21: { kind: 'arrow', by: -3 },
23: { kind: 'arrow', by: 3 },
25: { kind: 'rock' },
27: { kind: 'star' },
28: { kind: 'arrow', by: -4 },
};
export const spaceAt = (side: TrackSide, pos: number): SpaceEffect | null => (side === 'wild' ? (WILD_SPACES[pos] ?? null) : null);
// ---------------------------------------------------------------- constants
export const RACES = 4;
/** Consecutive automatic actions before a player is shown as "자리 비움". */
export const AWAY_AFTER = 3;
export const AWAY_MS = 5000;
/** Deadline for a player who left (their racers keep running on automatic choices). */
export const LEFT_MS = 1200;
/** A racer's power works at most this many times in one racer-turn (stops endless chains, §5.4). */
export const POWER_CAP = 5;
/** Queued reactions handled per racer-turn at most (safety net, §5.4). */
export const CHAIN_CAP = 200;
/** A race stops after this many racer-turns per racer in it; the rest are placed by position (§5.5). */
export const TURNS_PER_RACER_CAP = 40;
export const LOSER_CAP = 3;
export const SISYPHUS_START = 4;
export function medalPoints(scoring: MagicalAthleteOptions['scoring'], raceNo: number): { gold: number; silver: number } {
if (scoring === 'rising') return { gold: [3, 4, 5, 6][raceNo - 1] ?? 6, silver: [1, 1, 2, 2][raceNo - 1] ?? 2 };
return { gold: 3, silver: 1 };
}
export const sideOf = (track: MagicalAthleteOptions['track'], raceNo: number): TrackSide =>
track === 'mild' ? 'mild' : track === 'wild' ? 'wild' : raceNo % 2 === 1 ? 'mild' : 'wild';
/** Racers per player per race: two for 2~3 players unless turned off (원작 2~3인 규칙). */
export const perRaceFor = (opt: MagicalAthleteOptions['twoRacers'], players: number): 1 | 2 => (opt === 'auto' && players <= 3 ? 2 : 1);
// ---------------------------------------------------------------- state
export type RacerStatus = 'run' | 'done' | 'out';
export interface RacerState {
id: RacerId;
owner: PlayerId;
pos: number;
status: RacerStatus;
tripped: boolean;
/** 1 = gold, 2 = silver, … (also given by position when a race is stopped by the cap). */
place: number | null;
}
export type Step = 'go' | 'start' | 'roll' | 'reroll' | 'boost';
export interface LogLine {
n: number;
kind: 'turn' | 'roll' | 'move' | 'power' | 'space' | 'finish' | 'info';
text: string;
racer?: RacerId;
}
export interface RaceState {
no: number;
side: TrackSide;
/** Field in turn order (seat order from the first player; a player's two racers in pick order). */
racers: RacerState[];
/** Seat index of the player whose turn it is. */
seat: number;
/** This player's racers still to move this turn. */
pending: RacerId[];
/** Racer taking its turn now (null while the player picks which racer goes first). */
cur: RacerId | null;
step: Step;
/** Die of the current turn (null = Legs moved 5); rerolls used (Magician). */
roll: { value: number | null; rerolls: number } | null;
turnStartPos: number;
/** Skipper takes the next turn (someone rolled a 1). */
skipperNext: boolean;
/** Main move cancelled this turn (Inchworm / Sisyphus). */
cancelMain: boolean;
/** Racer-turns played. */
turns: number;
/** Times each racer's power worked in the current racer-turn. */
fired: Partial<Record<RacerId, number>>;
/** Points Lovable Loser took this race / Sisyphus still holds. */
loserPts: number;
sisyphusPts: number;
finishers: RacerId[];
/** True when the race was ended by the turn cap. */
capped: boolean;
/** Extra points won in this race per player (stars, Lovable Loser, Sisyphus). */
bonus: Record<PlayerId, number>;
log: LogLine[];
logSeq: number;
}
export interface RaceResult {
no: number;
side: TrackSide;
field: { id: RacerId; owner: PlayerId; place: number | null; status: RacerStatus; pos: number }[];
gold: RacerId | null;
silver: RacerId | null;
/** Points per player from this race (medals + stars/powers). */
points: Record<PlayerId, number>;
capped: boolean;
}
export interface Score {
gold: number;
silver: number;
/** Medal points (gold/silver, by the score table). */
medal: number;
/** Extra points: stars on the wild track, Lovable Loser, Sisyphus. */
bonus: number;
}
export interface DraftState {
round: number;
rounds: number;
/** Face-up racers to pick from. */
line: RacerId[];
/** Seat indexes picking this round, in order (snake: 1→n, n→1). */
order: number[];
at: number;
}
export interface MagicalAthleteState {
options: MagicalAthleteOptions;
seats: PlayerId[];
perRace: 1 | 2;
phase: 'draft' | 'select' | 'race' | 'finished';
/** Hidden draw pile of racers (index 0 = top). */
deck: RacerId[];
draft: DraftState | null;
/** First picker of draft round 1 (seat index). */
draftStart: number;
teams: Record<PlayerId, RacerId[]>;
used: Record<PlayerId, RacerId[]>;
/** Secret picks for the coming race (null = not chosen yet). */
selections: Record<PlayerId, RacerId[] | null>;
raceNo: number;
/** Seat that starts the coming/current race. */
firstSeat: number;
race: RaceState | null;
results: RaceResult[];
scores: Record<PlayerId, Score>;
left: PlayerId[];
timeouts: Record<PlayerId, number>;
rollSeq: number;
turnSeq: number;
deadlineAt: number | null;
}

View File

@@ -57,6 +57,7 @@ export const BOT_GAMES: readonly string[] = [
'connect-four',
'uno',
'liar',
'magical-athlete',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -39,6 +39,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
{ id: 'connect-four', nameKo: '커넥트 포', minPlayers: 2, maxPlayers: 2, minutes: '3~10', level: '쉬움', blurb: '열을 골라 돌을 떨어뜨려 네 개를 먼저 한 줄로! · 사목', available: true },
{ id: 'magical-athlete', nameKo: '야단법석 달리기', minPlayers: 2, maxPlayers: 6, minutes: '20~30', level: '쉬움', blurb: '엉뚱한 능력 선수를 뽑아 주사위 경주 4번! 1·2등만 점수', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },
{ id: 'clue', nameKo: '클루', minPlayers: 3, maxPlayers: 6, minutes: '30~50', level: '보통', blurb: '저택 살인 사건! 질문과 소거법으로 범인·흉기·장소를 맞혀요', available: true },
{ id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true },