M4: 윷놀이 규칙·화면·테스트
- 규칙(packages/games/yut): 29칸 윷판 그래프(모서리·방은 멈췄다 출발할 때만 꺾음, 방에서는 항상 참먹이 쪽), 가락 단위 확률(realistic 0.6 / fair 0.5, 빽도 표시 가락, 낙), 윷·모·잡기 추가 던지기, 모아 둔 결과 자유 순서, 쓸 수 없는 빽도 자동 버림, 빽도는 왔던 길(trail)로, 도 자리 빽도(참먹이/바로 남), pass/reach 날 판정, 업기·잡기(지나가면 안 잡음), 개인전 2~4명(1등 종료/꼴찌까지), 팀전 4·6·8명(청·홍 번갈아, 팀원 순환), 기권(팀은 전원 기권 시 패배), 시간 초과 자동 행동(잡기 > 내기 > 업기 > 뒤처진 말 > 올리기), 3연속 초과 시 자리 비움(5초) - 테스트: 문서 10절 시나리오 + 확률 10만 회(±0.5%p), 무작위 1,000판(불변식·onTimeout 합법·결정성·리플레이), 자동 진행·무작위 기권 60판, apply p99 < 5ms. 서버 방 테스트 2개(팀전 인원 검사, 연결 끊김 자동 진행·재접속 View) - 화면(apps/web/games/yut): SVG 윷판·말(편마다 색+모양), 윷가락 던지기 애니메이션, 결과 칩 → 말 → 한 번 더 눌러 확정, 경로 미리보기와 잡기!/날!/업기 배지, 자동 이동, 칸마다 통통 이동 애니메이션, 진행 기록, 옵션·규칙 설명, 키보드 조작 - 엔진/서버(하위 호환): GameDefinition.playerCountError(옵션별 인원 규칙) 추가, 방 시작 시 검사. 방 인원이 게임 최대였으면 옵션 변경으로 범위가 바뀔 때 새 최대를 따라감(팀전 8자리) - 등록: GAMES, 카탈로그(쉬움·15~25분), 화면 레지스트리, 홈의 "준비 중" 목록에서 윷놀이 제거 - E2E: PC 방장 + 휴대폰 친구, 말 2개로 실제 화면 조작(키보드 2단계 확정)으로 끝까지, 다크 모드 화면 저장 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
833
packages/games/src/yut/index.ts
Normal file
833
packages/games/src/yut/index.ts
Normal file
@@ -0,0 +1,833 @@
|
||||
/** 윷놀이 (docs/games/yut.md). No hidden information; the RNG state is kept by the runner, never in the state. */
|
||||
import { z } from 'zod';
|
||||
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
|
||||
import {
|
||||
GOAL,
|
||||
THROW_KO,
|
||||
THROW_STEPS,
|
||||
advance,
|
||||
defaultPrev,
|
||||
remainingDistance,
|
||||
rollSticks,
|
||||
type NodeId,
|
||||
type Sticks,
|
||||
type Throw,
|
||||
} from './board';
|
||||
|
||||
export * from './board';
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
export const yutOptionsSchema = z.object({
|
||||
mode: z
|
||||
.enum(['individual', 'team'])
|
||||
.default('individual')
|
||||
.meta({ title: '경기 방식', labels: { individual: '개인전(2~4명)', team: '팀전(4·6·8명, 2팀)' } }),
|
||||
pieces: z
|
||||
.union([z.literal(2), z.literal(3), z.literal(4), z.literal(5)])
|
||||
.default(4)
|
||||
.meta({ title: '한 편의 말 수', labels: { 2: '2개', 3: '3개', 4: '4개', 5: '5개' } }),
|
||||
stickModel: z
|
||||
.enum(['realistic', 'fair'])
|
||||
.default('realistic')
|
||||
.meta({ title: '윷가락 확률', labels: { realistic: '실제 윷처럼(개·걸이 잘 나오고 모는 드묾)', fair: '반반(앞뒤가 나올 확률이 같음)' } }),
|
||||
backdo: z.boolean().default(true).meta({ title: '빽도 사용' }),
|
||||
backdoFromDo: z
|
||||
.enum(['chammeogi', 'finish'])
|
||||
.default('chammeogi')
|
||||
.meta({ title: '도 자리 말이 빽도를 받으면', labels: { chammeogi: '참먹이로 감(다음 전진에서 남)', finish: '바로 남' } }),
|
||||
finishRule: z
|
||||
.enum(['pass', 'reach'])
|
||||
.default('pass')
|
||||
.meta({ title: '날(완주) 판정', labels: { pass: '참먹이를 지나야 남', reach: '참먹이에 도착하면 남' } }),
|
||||
nakPercent: z
|
||||
.union([z.literal(0), z.literal(3), z.literal(5), z.literal(10)])
|
||||
.default(0)
|
||||
.meta({ title: '낙(윷가락이 판 밖으로 떨어짐) 확률', labels: { 0: '낙 없음', 3: '3%', 5: '5%', 10: '10%' } }),
|
||||
backdoCaptureBonus: z.boolean().default(true).meta({ title: '빽도로 잡아도 한 번 더 던지기' }),
|
||||
ranking: z
|
||||
.enum(['first', 'all'])
|
||||
.default('first')
|
||||
.meta({ title: '3~4명 개인전에서 1등이 나오면', labels: { first: '바로 끝(나머지는 진행도로 순위)', all: '꼴찌가 정해질 때까지 계속' } }),
|
||||
turnSeconds: z
|
||||
.union([z.literal(15), z.literal(30), z.literal(60), z.literal(null)])
|
||||
.default(30)
|
||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||
});
|
||||
export type YutOptions = z.infer<typeof yutOptionsSchema>;
|
||||
|
||||
export const yutActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('THROW') }),
|
||||
z.object({
|
||||
type: z.literal('MOVE'),
|
||||
throwIndex: z.number().int().min(0).max(999),
|
||||
from: z.union([z.literal('home'), z.number().int().min(0).max(28)]),
|
||||
}),
|
||||
z.object({ type: z.literal('CONCEDE') }),
|
||||
]);
|
||||
/** Client actions plus the system-only timer action (not in the schema). */
|
||||
export type YutAction = z.infer<typeof yutActionSchema> | { type: 'TIMEOUT' };
|
||||
export type YutMoveAction = Extract<YutAction, { type: 'MOVE' }>;
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
/** 개인전: seat index. 팀전: 0 = 청팀, 1 = 홍팀. */
|
||||
export type SideId = number;
|
||||
|
||||
export interface Piece {
|
||||
id: number;
|
||||
status: 'home' | 'board' | 'done';
|
||||
node: NodeId | null;
|
||||
/** True while standing on 참먹이 after a lap (every board piece on 0 is lapped). */
|
||||
lapped: boolean;
|
||||
/** Nodes visited since entering the board, current node last (for 빽도). Shared by a stack. */
|
||||
trail: NodeId[];
|
||||
}
|
||||
|
||||
export interface SideState {
|
||||
id: SideId;
|
||||
members: PlayerId[];
|
||||
pieces: Piece[];
|
||||
finishedRank: number | null;
|
||||
/** Members who conceded; the side is out when all of them did. */
|
||||
conceded: PlayerId[];
|
||||
out: boolean;
|
||||
outSeq: number | null;
|
||||
/** Index into `members` of whoever throws next time this side has the turn. */
|
||||
cursor: number;
|
||||
}
|
||||
|
||||
export interface YutMoveInfo {
|
||||
no: number;
|
||||
side: SideId;
|
||||
player: PlayerId;
|
||||
throw: Throw;
|
||||
from: NodeId | 'home';
|
||||
to: NodeId | typeof GOAL;
|
||||
path: NodeId[];
|
||||
count: number;
|
||||
captured: { side: SideId; count: number }[];
|
||||
stacked: boolean;
|
||||
}
|
||||
|
||||
export interface YutStats {
|
||||
throws: Record<Throw | 'nak', number>;
|
||||
/** Keyed by side id. */
|
||||
captures: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface YutRankEntry {
|
||||
rank: number;
|
||||
players: PlayerId[];
|
||||
side: SideId;
|
||||
finishedPieces: number;
|
||||
remainingDistance: number;
|
||||
}
|
||||
|
||||
export interface YutResult {
|
||||
ranking: YutRankEntry[];
|
||||
winners: PlayerId[];
|
||||
summary: string;
|
||||
reason: 'normal' | 'resign';
|
||||
stats: YutStats;
|
||||
}
|
||||
|
||||
export interface YutState {
|
||||
options: YutOptions;
|
||||
players: PlayerId[];
|
||||
sideOf: Record<PlayerId, SideId>;
|
||||
sides: SideState[];
|
||||
turnSide: SideId;
|
||||
current: PlayerId;
|
||||
phase: 'throw' | 'move' | 'finished';
|
||||
/** Throws still owed this turn (윷/모/잡기 bonus). 1 when the throw phase starts. */
|
||||
throwsOwed: number;
|
||||
/** Results collected this turn, in throw order. */
|
||||
pending: Throw[];
|
||||
lastThrow: { no: number; player: PlayerId; sticks: Sticks | null; result: Throw | 'nak' } | null;
|
||||
lastMove: YutMoveInfo | null;
|
||||
throwNo: number;
|
||||
moveNo: number;
|
||||
/** +1 per applied action (timer key / duplicate guard). */
|
||||
turnSeq: number;
|
||||
deadlineAt: number | null;
|
||||
timeouts: Record<PlayerId, number>;
|
||||
log: GameEvent[];
|
||||
stats: YutStats;
|
||||
nextRank: number;
|
||||
outCount: number;
|
||||
final: YutResult | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- views
|
||||
|
||||
export interface YutLegalMove {
|
||||
throwIndex: number;
|
||||
throw: Throw;
|
||||
from: NodeId | 'home';
|
||||
to: NodeId | typeof GOAL;
|
||||
/** Nodes entered (for the dotted preview). */
|
||||
path: NodeId[];
|
||||
/** Pieces that move together. */
|
||||
count: number;
|
||||
/** Opponent pieces caught. */
|
||||
captures: number;
|
||||
stacks: boolean;
|
||||
finishes: boolean;
|
||||
}
|
||||
|
||||
export interface YutSideView {
|
||||
id: SideId;
|
||||
name: string;
|
||||
members: PlayerId[];
|
||||
conceded: PlayerId[];
|
||||
out: boolean;
|
||||
finishedRank: number | null;
|
||||
home: number;
|
||||
onBoard: number;
|
||||
done: number;
|
||||
remaining: number;
|
||||
}
|
||||
|
||||
export interface YutStackView {
|
||||
node: NodeId;
|
||||
side: SideId;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface YutView {
|
||||
options: YutOptions;
|
||||
team: boolean;
|
||||
me: PlayerId | null;
|
||||
mySide: SideId | null;
|
||||
phase: YutState['phase'];
|
||||
sides: YutSideView[];
|
||||
stacks: YutStackView[];
|
||||
turnSide: SideId;
|
||||
current: PlayerId;
|
||||
throwsOwed: number;
|
||||
pending: Throw[];
|
||||
lastThrow: YutState['lastThrow'];
|
||||
lastMove: YutMoveInfo | null;
|
||||
turnSeq: number;
|
||||
deadlineAt: number | null;
|
||||
away: PlayerId[];
|
||||
/** Only for the player to move (null otherwise). */
|
||||
legalMoves: YutLegalMove[] | null;
|
||||
/** The move a timeout would play (§8.5), for the player to move. */
|
||||
suggested: { throwIndex: number; from: NodeId | 'home' } | null;
|
||||
log: GameEvent[];
|
||||
stats: YutStats;
|
||||
result: YutResult | null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
const TEAM_NAMES = ['청팀', '홍팀'];
|
||||
const SOLO_NAMES = ['빨강', '파랑', '초록', '노랑'];
|
||||
const LOG_MAX = 40;
|
||||
const AWAY_AFTER = 3;
|
||||
const AWAY_MS = 5000;
|
||||
|
||||
export function sideName(o: Pick<YutOptions, 'mode'>, side: SideId): string {
|
||||
return o.mode === 'team' ? TEAM_NAMES[side]! : SOLO_NAMES[side]!;
|
||||
}
|
||||
|
||||
export function playerRange(o: Pick<YutOptions, 'mode'>): { min: number; max: number } {
|
||||
return o.mode === 'team' ? { min: 4, max: 8 } : { min: 2, max: 4 };
|
||||
}
|
||||
|
||||
/** Player-count check that `playersFor` cannot express (팀전은 짝수만). */
|
||||
export function playerCountError(o: Pick<YutOptions, 'mode'>, n: number): string | null {
|
||||
if (o.mode === 'team') return n === 4 || n === 6 || n === 8 ? null : '팀전은 4명, 6명, 8명(짝수)으로만 할 수 있어요.';
|
||||
return n >= 2 && n <= 4 ? null : '개인전은 2~4명이 할 수 있어요.';
|
||||
}
|
||||
|
||||
const sideActive = (x: SideState) => x.finishedRank === null && !x.out;
|
||||
const memberActive = (x: SideState, i: number) => !x.conceded.includes(x.members[i]!);
|
||||
|
||||
/** First active member index at or after `from` (cyclic). */
|
||||
function memberFrom(x: SideState, from: number): number {
|
||||
for (let k = 0; k < x.members.length; k++) {
|
||||
const i = (from + k) % x.members.length;
|
||||
if (memberActive(x, i)) return i;
|
||||
}
|
||||
return from % x.members.length;
|
||||
}
|
||||
|
||||
function pieceDistance(p: Piece, rule: YutOptions['finishRule']): number {
|
||||
if (p.status === 'done') return 0;
|
||||
return remainingDistance(p.status === 'home' ? 'home' : p.node!, rule);
|
||||
}
|
||||
|
||||
function sideDistance(x: SideState, rule: YutOptions['finishRule']): number {
|
||||
return x.pieces.reduce((a, p) => a + pieceDistance(p, rule), 0);
|
||||
}
|
||||
|
||||
const doneCount = (x: SideState) => x.pieces.filter((p) => p.status === 'done').length;
|
||||
|
||||
function pushLog(s: YutState, events: GameEvent[], e: GameEvent): void {
|
||||
events.push(e);
|
||||
s.log.push(e);
|
||||
if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX);
|
||||
}
|
||||
|
||||
interface Plan {
|
||||
throwIndex: number;
|
||||
throw: Throw;
|
||||
from: NodeId | 'home';
|
||||
to: NodeId | typeof GOAL;
|
||||
path: NodeId[];
|
||||
movers: number[];
|
||||
trailAfter: NodeId[];
|
||||
victims: { side: SideId; ids: number[] }[];
|
||||
stackWith: number[];
|
||||
}
|
||||
|
||||
/** Where `from` would go with `pending[throwIndex]`; null if that is not a legal move. */
|
||||
function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId | 'home'): Plan | null {
|
||||
const t = s.pending[throwIndex];
|
||||
const side = s.sides[sideId];
|
||||
if (!t || !side) return null;
|
||||
const o = s.options;
|
||||
let movers: Piece[];
|
||||
let to: NodeId | typeof GOAL;
|
||||
let path: NodeId[];
|
||||
let trailAfter: NodeId[];
|
||||
if (from === 'home') {
|
||||
if (t === 'backdo') return null;
|
||||
const p = side.pieces.find((x) => x.status === 'home');
|
||||
if (!p) return null;
|
||||
movers = [p];
|
||||
const adv = advance('home', THROW_STEPS[t], o.finishRule);
|
||||
({ to, path } = adv);
|
||||
trailAfter = to === GOAL ? [] : [...path];
|
||||
} else {
|
||||
movers = side.pieces.filter((x) => x.status === 'board' && x.node === from);
|
||||
if (movers.length === 0) return null;
|
||||
const trail = movers[0]!.trail;
|
||||
if (t === 'backdo') {
|
||||
if (trail.length >= 2) {
|
||||
to = trail[trail.length - 2]!;
|
||||
trailAfter = trail.slice(0, -1);
|
||||
} else if (from === 1) {
|
||||
to = o.backdoFromDo === 'finish' ? GOAL : 0;
|
||||
trailAfter = to === GOAL ? [] : [0];
|
||||
} else {
|
||||
to = defaultPrev(from);
|
||||
trailAfter = [to];
|
||||
}
|
||||
path = to === GOAL ? [] : [to];
|
||||
} else {
|
||||
const adv = advance(from, THROW_STEPS[t], o.finishRule);
|
||||
({ to, path } = adv);
|
||||
trailAfter = to === GOAL ? [] : [...trail, ...path];
|
||||
}
|
||||
}
|
||||
const victims: Plan['victims'] = [];
|
||||
const stackWith: number[] = [];
|
||||
if (to !== GOAL) {
|
||||
for (const x of s.sides) {
|
||||
const here = x.pieces.filter((p) => p.status === 'board' && p.node === to && !(x.id === sideId && movers.includes(p))).map((p) => p.id);
|
||||
if (here.length === 0) continue;
|
||||
if (x.id === sideId) stackWith.push(...here);
|
||||
else victims.push({ side: x.id, ids: here });
|
||||
}
|
||||
}
|
||||
return { throwIndex, throw: t, from, to, path, movers: movers.map((p) => p.id), trailAfter, victims, stackWith };
|
||||
}
|
||||
|
||||
/** Legal moves of the side to move. Equal results are listed once (first index). Order: index, node, 'home' last. */
|
||||
function legalPlans(s: YutState): Plan[] {
|
||||
if (s.phase !== 'move') return [];
|
||||
const side = s.sides[s.turnSide]!;
|
||||
const sources: (NodeId | 'home')[] = [...new Set(side.pieces.filter((p) => p.status === 'board').map((p) => p.node!))].sort((a, b) => a - b);
|
||||
if (side.pieces.some((p) => p.status === 'home')) sources.push('home');
|
||||
const out: Plan[] = [];
|
||||
const seen = new Set<Throw>();
|
||||
s.pending.forEach((t, i) => {
|
||||
if (seen.has(t)) return;
|
||||
seen.add(t);
|
||||
for (const from of sources) {
|
||||
const p = planMove(s, s.turnSide, i, from);
|
||||
if (p) out.push(p);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
const toLegal = (p: Plan): YutLegalMove => ({
|
||||
throwIndex: p.throwIndex,
|
||||
throw: p.throw,
|
||||
from: p.from,
|
||||
to: p.to,
|
||||
path: p.path,
|
||||
count: p.movers.length,
|
||||
captures: p.victims.reduce((a, v) => a + v.ids.length, 0),
|
||||
stacks: p.stackWith.length > 0,
|
||||
finishes: p.to === GOAL,
|
||||
});
|
||||
|
||||
/** Deterministic auto move (§8.5): capture > finish > stack > most-behind piece with the biggest result > enter > rest. */
|
||||
function chooseAuto(s: YutState, plans: Plan[]): Plan {
|
||||
const rule = s.options.finishRule;
|
||||
const side = s.sides[s.turnSide]!;
|
||||
const byTie = (a: Plan, b: Plan) =>
|
||||
a.throwIndex - b.throwIndex || (a.from === 'home' ? 1 : 0) - (b.from === 'home' ? 1 : 0) || (a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number));
|
||||
const pick = (list: Plan[], cmp: (a: Plan, b: Plan) => number) => [...list].sort((a, b) => cmp(a, b) || byTie(a, b))[0];
|
||||
const caps = plans.filter((p) => p.victims.length > 0);
|
||||
if (caps.length) return pick(caps, (a, b) => toLegal(b).captures - toLegal(a).captures)!;
|
||||
const fin = plans.filter((p) => p.to === GOAL);
|
||||
if (fin.length) return pick(fin, (a, b) => b.movers.length - a.movers.length)!;
|
||||
const stack = plans.filter((p) => p.stackWith.length > 0);
|
||||
if (stack.length) return pick(stack, () => 0)!;
|
||||
const distOf = (p: Plan) => pieceDistance(side.pieces.find((x) => x.id === p.movers[0])!, rule);
|
||||
const fwd = plans.filter((p) => p.from !== 'home' && p.throw !== 'backdo');
|
||||
if (fwd.length) return pick(fwd, (a, b) => distOf(b) - distOf(a) || THROW_STEPS[b.throw] - THROW_STEPS[a.throw])!;
|
||||
const enter = plans.filter((p) => p.from === 'home');
|
||||
if (enter.length) return pick(enter, () => 0)!;
|
||||
return pick(plans, () => 0)!;
|
||||
}
|
||||
|
||||
/** The action a timeout plays now (THROW in the throw phase, §8.5 move otherwise). */
|
||||
export function autoAction(s: YutState): Exclude<YutAction, { type: 'TIMEOUT' }> {
|
||||
if (s.phase !== 'move') return { type: 'THROW' };
|
||||
const plans = legalPlans(s);
|
||||
if (plans.length === 0) return { type: 'THROW' }; // unreachable: stuck results are discarded right away
|
||||
const p = chooseAuto(s, plans);
|
||||
return { type: 'MOVE', throwIndex: p.throwIndex, from: p.from };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- transitions
|
||||
|
||||
function startTurn(s: YutState, sideId: SideId, events: GameEvent[]): void {
|
||||
const side = s.sides[sideId]!;
|
||||
side.cursor = memberFrom(side, side.cursor);
|
||||
s.turnSide = sideId;
|
||||
s.current = side.members[side.cursor]!;
|
||||
s.phase = 'throw';
|
||||
s.throwsOwed = 1;
|
||||
s.pending = [];
|
||||
pushLog(s, events, { type: 'turnChanged', side: sideId, player: s.current });
|
||||
}
|
||||
|
||||
function endTurn(s: YutState, events: GameEvent[]): void {
|
||||
const side = s.sides[s.turnSide]!;
|
||||
side.cursor = memberFrom(side, side.cursor + 1);
|
||||
const n = s.sides.length;
|
||||
for (let k = 1; k <= n; k++) {
|
||||
const next = s.sides[(s.turnSide + k) % n]!;
|
||||
if (sideActive(next)) {
|
||||
startTurn(s, next.id, events);
|
||||
return;
|
||||
}
|
||||
}
|
||||
finishGame(s, events);
|
||||
}
|
||||
|
||||
function gameShouldEnd(s: YutState): boolean {
|
||||
const active = s.sides.filter(sideActive).length;
|
||||
const anyFinished = s.sides.some((x) => x.finishedRank !== null);
|
||||
return active <= 1 || (anyFinished && (s.options.ranking === 'first' || s.options.mode === 'team'));
|
||||
}
|
||||
|
||||
function finishGame(s: YutState, events: GameEvent[]): void {
|
||||
const rule = s.options.finishRule;
|
||||
const entry = (x: SideState): Omit<YutRankEntry, 'rank'> => ({
|
||||
players: [...x.members],
|
||||
side: x.id,
|
||||
finishedPieces: doneCount(x),
|
||||
remainingDistance: sideDistance(x, rule),
|
||||
});
|
||||
const ranked: YutRankEntry[] = [];
|
||||
const push = (group: SideState[]) => {
|
||||
const rank = ranked.length + 1;
|
||||
for (const x of group) ranked.push({ rank, ...entry(x) });
|
||||
};
|
||||
for (const x of s.sides.filter((x) => x.finishedRank !== null).sort((a, b) => a.finishedRank! - b.finishedRank!)) push([x]);
|
||||
const active = s.sides
|
||||
.filter(sideActive)
|
||||
.sort((a, b) => doneCount(b) - doneCount(a) || sideDistance(a, rule) - sideDistance(b, rule));
|
||||
for (let i = 0; i < active.length; ) {
|
||||
const a = active[i]!;
|
||||
const group = active.filter((b, j) => j >= i && doneCount(b) === doneCount(a) && sideDistance(b, rule) === sideDistance(a, rule));
|
||||
push(group);
|
||||
i += group.length;
|
||||
}
|
||||
for (const x of s.sides.filter((x) => x.out).sort((a, b) => b.outSeq! - a.outSeq!)) push([x]);
|
||||
const first = ranked.filter((r) => r.rank === 1);
|
||||
const winners = first.flatMap((r) => r.players);
|
||||
const anyFinished = s.sides.some((x) => x.finishedRank !== null);
|
||||
const o = s.options;
|
||||
const top = first[0]!;
|
||||
let summary: string;
|
||||
if (anyFinished) {
|
||||
summary =
|
||||
o.mode === 'team'
|
||||
? `${sideName(o, top.side)} 승리! (말 ${o.pieces}개 모두 남)`
|
||||
: `${sideName(o, top.side)} 1등! (말 ${o.pieces}개 모두 남)${o.ranking === 'all' && s.sides.length > 2 ? ' · 꼴찌까지 순위가 정해졌어요' : ''}`;
|
||||
} else if (first.length > 1) {
|
||||
summary = '모두 기권해서 게임이 끝났어요';
|
||||
} else {
|
||||
summary =
|
||||
o.mode === 'team'
|
||||
? `${sideName(o, 1 - top.side)} 기권으로 ${sideName(o, top.side)} 승리!`
|
||||
: `다른 사람이 모두 기권해서 ${sideName(o, top.side)} 1등!`;
|
||||
}
|
||||
s.phase = 'finished';
|
||||
s.pending = [];
|
||||
s.throwsOwed = 0;
|
||||
s.deadlineAt = null;
|
||||
s.final = { ranking: ranked, winners, summary, reason: anyFinished ? 'normal' : 'resign', stats: structuredClone(s.stats) };
|
||||
pushLog(s, events, { type: 'gameOver', winners, summary });
|
||||
}
|
||||
|
||||
/** In the move phase: if no pending result can be used, discard them all and end the turn (§5.3-2). */
|
||||
function settleMovePhase(s: YutState, events: GameEvent[]): void {
|
||||
if (s.phase !== 'move') return;
|
||||
if (s.pending.length === 0) {
|
||||
endTurn(s, events);
|
||||
return;
|
||||
}
|
||||
if (legalPlans(s).length > 0) return;
|
||||
pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: [...s.pending] });
|
||||
s.pending = [];
|
||||
endTurn(s, events);
|
||||
}
|
||||
|
||||
function doThrow(s: YutState, rng: Rng, events: GameEvent[]): void {
|
||||
const r = rollSticks(rng, s.options);
|
||||
s.throwNo += 1;
|
||||
s.stats.throws[r.result] += 1;
|
||||
s.lastThrow = { no: s.throwNo, player: s.current, sticks: r.sticks, result: r.result };
|
||||
s.throwsOwed -= 1;
|
||||
if (r.result === 'nak') {
|
||||
pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current });
|
||||
} else {
|
||||
s.pending.push(r.result);
|
||||
if (r.result === 'yut' || r.result === 'mo') s.throwsOwed += 1;
|
||||
pushLog(s, events, { type: 'thrown', side: s.turnSide, player: s.current, sticks: r.sticks, result: r.result });
|
||||
}
|
||||
if (s.throwsOwed > 0) return;
|
||||
s.phase = 'move';
|
||||
settleMovePhase(s, events);
|
||||
}
|
||||
|
||||
function doMove(s: YutState, throwIndex: number, from: NodeId | 'home', events: GameEvent[]): void {
|
||||
const plan = planMove(s, s.turnSide, throwIndex, from);
|
||||
if (!plan) throw new Error(`yut: illegal move ${throwIndex} ${from}`);
|
||||
const side = s.sides[s.turnSide]!;
|
||||
s.pending.splice(throwIndex, 1);
|
||||
const movers = side.pieces.filter((p) => plan.movers.includes(p.id));
|
||||
for (const p of movers) {
|
||||
if (plan.to === GOAL) Object.assign(p, { status: 'done', node: null, lapped: false, trail: [] });
|
||||
else Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] });
|
||||
}
|
||||
for (const p of side.pieces) if (plan.stackWith.includes(p.id)) Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] });
|
||||
let caught = 0;
|
||||
for (const v of plan.victims) {
|
||||
for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] });
|
||||
caught += v.ids.length;
|
||||
}
|
||||
s.moveNo += 1;
|
||||
s.lastMove = {
|
||||
no: s.moveNo,
|
||||
side: side.id,
|
||||
player: s.current,
|
||||
throw: plan.throw,
|
||||
from: plan.from,
|
||||
to: plan.to,
|
||||
path: plan.path,
|
||||
count: movers.length,
|
||||
captured: plan.victims.map((v) => ({ side: v.side, count: v.ids.length })),
|
||||
stacked: plan.stackWith.length > 0,
|
||||
};
|
||||
pushLog(s, events, { type: 'moved', side: side.id, player: s.current, throw: plan.throw, from: plan.from, to: plan.to, path: plan.path, count: movers.length });
|
||||
if (plan.stackWith.length) pushLog(s, events, { type: 'stacked', side: side.id, node: plan.to, count: movers.length + plan.stackWith.length });
|
||||
for (const v of plan.victims) pushLog(s, events, { type: 'captured', side: side.id, victimSide: v.side, count: v.ids.length, node: plan.to });
|
||||
if (caught) s.stats.captures[String(side.id)] = (s.stats.captures[String(side.id)] ?? 0) + 1;
|
||||
if (plan.to === GOAL) {
|
||||
pushLog(s, events, { type: 'finishedPieces', side: side.id, count: movers.length });
|
||||
if (side.pieces.every((p) => p.status === 'done')) {
|
||||
side.finishedRank = s.nextRank++;
|
||||
pushLog(s, events, { type: 'sideFinished', side: side.id, rank: side.finishedRank });
|
||||
if (gameShouldEnd(s)) {
|
||||
finishGame(s, events);
|
||||
return;
|
||||
}
|
||||
// ranking = all: the finished side drops out; leftover results are lost.
|
||||
if (s.pending.length) pushLog(s, events, { type: 'discarded', side: side.id, player: s.current, throws: [...s.pending] });
|
||||
s.pending = [];
|
||||
endTurn(s, events);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (caught && (plan.throw !== 'backdo' || s.options.backdoCaptureBonus)) {
|
||||
s.phase = 'throw';
|
||||
s.throwsOwed = 1;
|
||||
pushLog(s, events, { type: 'bonusThrow', side: side.id, player: s.current });
|
||||
return;
|
||||
}
|
||||
settleMovePhase(s, events);
|
||||
}
|
||||
|
||||
function doConcede(s: YutState, actor: PlayerId, events: GameEvent[]): void {
|
||||
const side = s.sides[s.sideOf[actor]!]!;
|
||||
side.conceded.push(actor);
|
||||
const whole = side.members.every((m) => side.conceded.includes(m));
|
||||
pushLog(s, events, { type: 'conceded', side: side.id, player: actor, sideOut: whole });
|
||||
if (!whole) {
|
||||
// 팀전: a teammate takes over (the turn in progress continues with them).
|
||||
if (s.current === actor) {
|
||||
side.cursor = memberFrom(side, side.cursor + 1);
|
||||
s.current = side.members[side.cursor]!;
|
||||
}
|
||||
return;
|
||||
}
|
||||
side.out = true;
|
||||
side.outSeq = ++s.outCount;
|
||||
for (const p of side.pieces) if (p.status === 'board') Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] });
|
||||
if (gameShouldEnd(s)) {
|
||||
finishGame(s, events);
|
||||
return;
|
||||
}
|
||||
if (s.turnSide === side.id) {
|
||||
s.pending = [];
|
||||
endTurn(s, events);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshDeadline(s: YutState, now: number): void {
|
||||
if (s.phase === 'finished' || s.options.turnSeconds === null) {
|
||||
s.deadlineAt = null;
|
||||
return;
|
||||
}
|
||||
const away = (s.timeouts[s.current] ?? 0) >= AWAY_AFTER;
|
||||
s.deadlineAt = now + (away ? AWAY_MS : s.options.turnSeconds * 1000);
|
||||
}
|
||||
|
||||
function emptyStats(n: number): YutStats {
|
||||
const captures: Record<string, number> = {};
|
||||
for (let i = 0; i < n; i++) captures[String(i)] = 0;
|
||||
return { throws: { do: 0, gae: 0, geol: 0, yut: 0, mo: 0, backdo: 0, nak: 0 }, captures };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definition
|
||||
|
||||
export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
id: 'yut',
|
||||
nameKo: '윷놀이',
|
||||
minPlayers: 2,
|
||||
maxPlayers: 8,
|
||||
stateVersion: 1,
|
||||
defaultOptions: yutOptionsSchema.parse({}),
|
||||
optionsSchema: yutOptionsSchema as unknown as z.ZodType<YutOptions>,
|
||||
actionSchema: yutActionSchema as unknown as z.ZodType<YutAction>,
|
||||
playersFor: playerRange,
|
||||
playerCountError: (o, n) => playerCountError(o, n),
|
||||
|
||||
setup({ players, options, rng, now }) {
|
||||
const err = playerCountError(options, players.length);
|
||||
if (err) throw new Error(`yut: ${err}`);
|
||||
const team = options.mode === 'team';
|
||||
const nSides = team ? 2 : players.length;
|
||||
const sides: SideState[] = Array.from({ length: nSides }, (_, id) => ({
|
||||
id,
|
||||
members: team ? players.filter((_, i) => i % 2 === id) : [players[id]!],
|
||||
pieces: Array.from({ length: options.pieces }, (_, pid) => ({ id: pid, status: 'home' as const, node: null, lapped: false, trail: [] })),
|
||||
finishedRank: null,
|
||||
conceded: [],
|
||||
out: false,
|
||||
outSeq: null,
|
||||
cursor: 0,
|
||||
}));
|
||||
const sideOf: Record<PlayerId, SideId> = {};
|
||||
players.forEach((p, i) => (sideOf[p] = team ? i % 2 : i));
|
||||
const timeouts: Record<PlayerId, number> = {};
|
||||
for (const p of players) timeouts[p] = 0;
|
||||
const s: YutState = {
|
||||
options,
|
||||
players: [...players],
|
||||
sideOf,
|
||||
sides,
|
||||
turnSide: 0,
|
||||
current: players[0]!,
|
||||
phase: 'throw',
|
||||
throwsOwed: 1,
|
||||
pending: [],
|
||||
lastThrow: null,
|
||||
lastMove: null,
|
||||
throwNo: 0,
|
||||
moveNo: 0,
|
||||
turnSeq: 0,
|
||||
deadlineAt: null,
|
||||
timeouts,
|
||||
log: [],
|
||||
stats: emptyStats(nSides),
|
||||
nextRank: 1,
|
||||
outCount: 0,
|
||||
final: null,
|
||||
};
|
||||
startTurn(s, rng.int(nSides), []);
|
||||
refreshDeadline(s, now);
|
||||
return s;
|
||||
},
|
||||
|
||||
validate(s, actor, a) {
|
||||
const sideId = s.sideOf[actor];
|
||||
if (sideId === undefined) return fail('이 게임의 플레이어가 아니에요.');
|
||||
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
|
||||
const side = s.sides[sideId]!;
|
||||
if (a.type === 'CONCEDE') {
|
||||
if (side.conceded.includes(actor)) return fail('이미 기권했어요.');
|
||||
if (side.finishedRank !== null) return fail('이미 말을 모두 냈어요.');
|
||||
return ok;
|
||||
}
|
||||
if (actor !== s.current) return fail('지금은 다른 사람 차례예요.');
|
||||
switch (a.type) {
|
||||
case 'TIMEOUT':
|
||||
return ok;
|
||||
case 'THROW':
|
||||
if (s.phase !== 'throw' || s.throwsOwed <= 0) return fail('지금은 윷을 던질 차례가 아니에요.');
|
||||
return ok;
|
||||
case 'MOVE': {
|
||||
if (s.phase !== 'move') return fail('지금은 말을 움직일 차례가 아니에요. 먼저 윷을 던져 주세요.');
|
||||
const t = s.pending[a.throwIndex];
|
||||
if (!t) return fail('그 윷 결과는 없어요.');
|
||||
if (a.from === 'home') {
|
||||
if (t === 'backdo') return fail('빽도로는 새 말을 올릴 수 없어요.');
|
||||
if (!side.pieces.some((p) => p.status === 'home')) return fail('기다리는 말이 없어요.');
|
||||
} else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from)) {
|
||||
return fail('그 말은 움직일 수 없어요.');
|
||||
}
|
||||
return planMove(s, sideId, a.throwIndex, a.from) ? ok : fail('그 말은 움직일 수 없어요.');
|
||||
}
|
||||
}
|
||||
return fail('알 수 없는 행동이에요.');
|
||||
},
|
||||
|
||||
apply(prev, actor, a, { rng, now }) {
|
||||
const s = structuredClone(prev);
|
||||
const events: GameEvent[] = [];
|
||||
s.turnSeq += 1;
|
||||
const act: Exclude<YutAction, { type: 'TIMEOUT' }> = a.type === 'TIMEOUT' ? autoAction(s) : a;
|
||||
if (a.type === 'TIMEOUT') {
|
||||
s.timeouts[actor] = (s.timeouts[actor] ?? 0) + 1;
|
||||
pushLog(s, events, { type: 'timeout', player: actor });
|
||||
if (s.timeouts[actor] === AWAY_AFTER) pushLog(s, events, { type: 'away', player: actor });
|
||||
} else if (a.type !== 'CONCEDE') s.timeouts[actor] = 0;
|
||||
switch (act.type) {
|
||||
case 'THROW':
|
||||
doThrow(s, rng, events);
|
||||
break;
|
||||
case 'MOVE':
|
||||
doMove(s, act.throwIndex, act.from, events);
|
||||
break;
|
||||
case 'CONCEDE':
|
||||
doConcede(s, actor, events);
|
||||
break;
|
||||
}
|
||||
refreshDeadline(s, now);
|
||||
return { state: s, events };
|
||||
},
|
||||
|
||||
view(s, viewer) {
|
||||
const o = s.options;
|
||||
const mySide = viewer !== null && s.sideOf[viewer] !== undefined ? s.sideOf[viewer]! : null;
|
||||
const stacks: YutStackView[] = [];
|
||||
for (const x of s.sides) {
|
||||
const byNode = new Map<NodeId, number>();
|
||||
for (const p of x.pieces) if (p.status === 'board') byNode.set(p.node!, (byNode.get(p.node!) ?? 0) + 1);
|
||||
for (const [node, count] of byNode) stacks.push({ node, side: x.id, count });
|
||||
}
|
||||
stacks.sort((a, b) => a.node - b.node);
|
||||
const mine = s.phase === 'move' && viewer !== null && viewer === s.current;
|
||||
const plans = mine ? legalPlans(s) : [];
|
||||
const auto = mine && plans.length ? chooseAuto(s, plans) : null;
|
||||
return {
|
||||
options: o,
|
||||
team: o.mode === 'team',
|
||||
me: mySide === null ? null : viewer,
|
||||
mySide,
|
||||
phase: s.phase,
|
||||
sides: s.sides.map((x) => ({
|
||||
id: x.id,
|
||||
name: sideName(o, x.id),
|
||||
members: x.members,
|
||||
conceded: x.conceded,
|
||||
out: x.out,
|
||||
finishedRank: x.finishedRank,
|
||||
home: x.pieces.filter((p) => p.status === 'home').length,
|
||||
onBoard: x.pieces.filter((p) => p.status === 'board').length,
|
||||
done: doneCount(x),
|
||||
remaining: sideDistance(x, o.finishRule),
|
||||
})),
|
||||
stacks,
|
||||
turnSide: s.turnSide,
|
||||
current: s.current,
|
||||
throwsOwed: s.throwsOwed,
|
||||
pending: s.pending,
|
||||
lastThrow: s.lastThrow,
|
||||
lastMove: s.lastMove,
|
||||
turnSeq: s.turnSeq,
|
||||
deadlineAt: s.deadlineAt,
|
||||
away: s.players.filter((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER),
|
||||
legalMoves: mine ? plans.map(toLegal) : null,
|
||||
suggested: auto ? { throwIndex: auto.throwIndex, from: auto.from } : null,
|
||||
log: s.log,
|
||||
stats: s.stats,
|
||||
result: s.final,
|
||||
};
|
||||
},
|
||||
|
||||
activePlayers(s) {
|
||||
return s.phase === 'finished' ? [] : [s.current];
|
||||
},
|
||||
|
||||
deadline(s) {
|
||||
return s.phase === 'finished' ? null : s.deadlineAt;
|
||||
},
|
||||
|
||||
timeoutPlayers(s) {
|
||||
return s.phase === 'finished' ? [] : [s.current];
|
||||
},
|
||||
|
||||
onTimeout() {
|
||||
return { type: 'TIMEOUT' };
|
||||
},
|
||||
|
||||
onLeave(s, player) {
|
||||
const sideId = s.sideOf[player];
|
||||
if (sideId === undefined || s.phase === 'finished') return null;
|
||||
const side = s.sides[sideId]!;
|
||||
if (side.conceded.includes(player) || side.finishedRank !== null) return null;
|
||||
return { type: 'CONCEDE' };
|
||||
},
|
||||
|
||||
result(s): GameResult | null {
|
||||
const f = s.final;
|
||||
if (!f) return null;
|
||||
const groups = new Map<number, PlayerId[]>();
|
||||
for (const r of f.ranking) groups.set(r.rank, [...(groups.get(r.rank) ?? []), ...r.players]);
|
||||
const scores: Record<PlayerId, number> = {};
|
||||
for (const r of f.ranking) for (const p of r.players) scores[p] = r.finishedPieces;
|
||||
return {
|
||||
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ps]) => ps),
|
||||
scores,
|
||||
summary: f.summary,
|
||||
reason: f.reason,
|
||||
};
|
||||
},
|
||||
|
||||
/** Test helper: THROW in the throw phase, every distinct legal MOVE in the move phase (CONCEDE is left out). */
|
||||
legalActions(s, p) {
|
||||
if (s.phase === 'finished' || p !== s.current) return [];
|
||||
if (s.phase === 'throw') return [{ type: 'THROW' }];
|
||||
return legalPlans(s).map((x) => ({ type: 'MOVE' as const, throwIndex: x.throwIndex, from: x.from }));
|
||||
},
|
||||
};
|
||||
|
||||
/** Throw label with its step count, e.g. "걸(3칸)", "빽도(뒤로 1칸)". */
|
||||
export function throwLabel(t: Throw): string {
|
||||
return t === 'backdo' ? `${THROW_KO[t]}(뒤로 1칸)` : `${THROW_KO[t]}(${THROW_STEPS[t]}칸)`;
|
||||
}
|
||||
Reference in New Issue
Block a user