1145 lines
44 KiB
TypeScript
1145 lines
44 KiB
TypeScript
/** 윷놀이 (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,
|
|
isFork,
|
|
remainingDistance,
|
|
rollSticks,
|
|
type NodeId,
|
|
type Sticks,
|
|
type Throw,
|
|
} from './board';
|
|
import { AUGS, AUG_IDS } from './augments';
|
|
import {
|
|
augActivePlayers,
|
|
augApply,
|
|
augAutoAction,
|
|
augLegalActions,
|
|
augMoves,
|
|
augSetup,
|
|
augValidate,
|
|
augView,
|
|
type AugState,
|
|
type PieceKind,
|
|
type YutAugView,
|
|
} from './aug';
|
|
|
|
export * from './board';
|
|
export type { AugFx, AugObj, AugOwnedView, AugSideView, AugSpecialMove, AugUseOption, PieceKind, YutAugView } from './aug';
|
|
export { PIECE_KO } from './aug';
|
|
|
|
// ---------------------------------------------------------------- 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: '1번(출발)으로 감(다음 전진에서 남)', finish: '바로 남' } }),
|
|
finishRule: z
|
|
.enum(['pass', 'reach'])
|
|
.default('pass')
|
|
.meta({ title: '날(완주) 판정', labels: { pass: '1번(출발)을 지나야 남', reach: '1번(출발)에 도착하면 남' } }),
|
|
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: '꼴찌가 정해질 때까지 계속' } }),
|
|
// ---- 지역 룰 (docs/games/yut.md §7). Defaults keep the original rules.
|
|
backdoNoPiece: z
|
|
.enum(['discard', 'rethrow', 'enter'])
|
|
.default('discard')
|
|
.meta({
|
|
title: '판에 내 말이 없을 때 빽도가 나오면',
|
|
labels: { discard: '쓸 곳이 없어 버림', rethrow: '다시 던짐', enter: '새 말이 1번(출발) 바로 앞 칸으로 감' },
|
|
}),
|
|
nakRule: z
|
|
.enum(['keep', 'lose'])
|
|
.default('keep')
|
|
.meta({ title: '낙이 나오면', labels: { keep: '그 던지기만 무효(모아 둔 결과는 남음)', lose: '차례가 끝남(모아 둔 결과도 버림)' } }),
|
|
useOrder: z
|
|
.enum(['free', 'thrown'])
|
|
.default('free')
|
|
.meta({ title: '모아 둔 결과를 쓰는 순서', labels: { free: '원하는 순서로', thrown: '던진 순서대로' } }),
|
|
stacking: z
|
|
.enum(['always', 'choose'])
|
|
.default('always')
|
|
.meta({ title: '내 말이 있는 자리에 멈추면', labels: { always: '무조건 업음', choose: '업을지 따로 둘지 고름' } }),
|
|
forkRule: z
|
|
.enum(['shortcut', 'choose'])
|
|
.default('shortcut')
|
|
.meta({ title: '모서리·방에 멈췄다가 출발할 때', labels: { shortcut: '늘 지름길(방에서는 1번 쪽)', choose: '갈 길을 고름' } }),
|
|
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: '무제한' } }),
|
|
// ---- 증강 윷놀이 (docs/games/yut-augmented.md). 개인전 only.
|
|
augmented: z.boolean().default(false).meta({ title: '증강 윷놀이' }),
|
|
augChaos: z.boolean().default(false).meta({ title: '증강: 혼돈 모드(한 번에 2개씩 고름)' }),
|
|
augRounds: z
|
|
.enum(['standard', 'quick', 'many'])
|
|
.default('standard')
|
|
.meta({ title: '증강: 고르는 라운드', labels: { standard: '1·6·12라운드', quick: '1·4·8라운드', many: '1·3·5·7·9라운드' } }),
|
|
augOffers: z
|
|
.union([z.literal(2), z.literal(3), z.literal(4)])
|
|
.default(3)
|
|
.meta({ title: '증강: 후보 수', labels: { 2: '2개', 3: '3개', 4: '4개' } }),
|
|
// This site's own augments start switched off (the room can switch them on).
|
|
augOff: z
|
|
.array(z.enum(AUG_IDS).meta({ labels: Object.fromEntries(AUG_IDS.map((id) => [id, AUGS[id].name])) }))
|
|
.max(AUG_IDS.length)
|
|
.default(() => AUG_IDS.filter((id) => AUGS[id].custom))
|
|
.meta({ title: '증강: 나오지 않게 뺀 증강' }),
|
|
});
|
|
export type YutOptions = z.infer<typeof yutOptionsSchema>;
|
|
|
|
const THROW_IDS = ['do', 'gae', 'geol', 'yut', 'mo', 'backdo'] as const;
|
|
const NODE_NO = z.number().int().min(0).max(28);
|
|
const PIECE_NO = z.number().int().min(0).max(39);
|
|
|
|
export const yutActionSchema = z.discriminatedUnion('type', [
|
|
/** `pick`: 개돼지 (증강) chooses 도 or 개. */
|
|
z.object({ type: z.literal('THROW'), pick: z.enum(['do', 'gae']).optional() }),
|
|
z.object({
|
|
type: z.literal('MOVE'),
|
|
throwIndex: z.number().int().min(0).max(999),
|
|
from: z.union([z.literal('home'), NODE_NO]),
|
|
/**
|
|
* Which stack on `from` (any piece id in it) when one node holds several own stacks (`stacking = choose`, 증강 special
|
|
* pieces), or which waiting piece (증강 special pieces).
|
|
*/
|
|
piece: PIECE_NO.optional(),
|
|
/** Take the other road at the starting fork (`forkRule = choose`). */
|
|
alt: z.boolean().optional(),
|
|
/** false = do not stack on own pieces there (`stacking = choose`). */
|
|
stack: z.boolean().optional(),
|
|
}),
|
|
z.object({ type: z.literal('CONCEDE') }),
|
|
// ---- 증강
|
|
z.object({ type: z.literal('AUG_PICK'), aug: z.enum(AUG_IDS), target: z.enum(AUG_IDS).optional() }),
|
|
z.object({ type: z.literal('AUG_ANSWER'), choice: z.union([z.number().int().min(0).max(99999), z.array(z.number().int().min(0).max(7)).max(8)]) }),
|
|
z.object({
|
|
type: z.literal('AUG_USE'),
|
|
uid: z.number().int().min(0).max(99999),
|
|
piece: PIECE_NO.optional(),
|
|
node: NODE_NO.optional(),
|
|
node2: NODE_NO.optional(),
|
|
target: z.number().int().min(0).max(7).optional(),
|
|
/** Another player's stack (any piece id in it): 얼음!, 뒤로 돌아, 자리 바꾸기. */
|
|
targetPiece: PIECE_NO.optional(),
|
|
result: z.enum(THROW_IDS).optional(),
|
|
angle: z.number().int().min(0).max(359).optional(),
|
|
power: z.number().int().min(1).max(100).optional(),
|
|
}),
|
|
z.object({ type: z.literal('SPECIAL'), piece: PIECE_NO, to: z.union([z.literal('goal'), NODE_NO]) }),
|
|
]);
|
|
/** 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[];
|
|
/**
|
|
* Stack key when own pieces share a node without being stacked (`stacking = choose`): the lowest piece id of
|
|
* that stack. Absent = the node's ordinary stack. Pieces on one node with the same key move together.
|
|
*/
|
|
group?: number;
|
|
/** 증강: special piece kind (absent = ordinary piece). */
|
|
kind?: PieceKind;
|
|
/** 증강: survives one catch. */
|
|
shield?: boolean;
|
|
/** 증강: can't move before this round (잠깐!, 영역 전개). */
|
|
frozenUntil?: number;
|
|
}
|
|
|
|
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;
|
|
/** Took the other road at the fork (`forkRule = choose`). */
|
|
alt?: boolean;
|
|
/** Stopped on own pieces without stacking (`stacking = choose`). */
|
|
apart?: 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;
|
|
/** 증강: why this rank (전원 완주, an augment, 탈락 …). */
|
|
reason?: string;
|
|
}
|
|
|
|
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;
|
|
/** 증강 adds `aug` (everyone picks an augment) and `prompt` (someone answers an augment's question). */
|
|
phase: 'throw' | 'move' | 'finished' | 'aug' | 'prompt';
|
|
/** Throws still owed this turn (윷/모/잡기 bonus). 1 when the throw phase starts. */
|
|
throwsOwed: number;
|
|
/** Results collected this turn, in throw order. */
|
|
pending: Throw[];
|
|
/** `sticks` has 4 entries in plain games (증강 may use 2~7); `results`: 이도류 gives two; `note`: which augment decided it. */
|
|
lastThrow: { no: number; player: PlayerId; sticks: Sticks | boolean[] | null; result: Throw | 'nak'; results?: Throw[]; note?: string } | 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;
|
|
/** 증강 윷놀이 only. */
|
|
aug?: AugState;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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;
|
|
/** 증강 카니발리즘: own pieces caught there. */
|
|
ownCaptures?: number;
|
|
stacks: boolean;
|
|
finishes: boolean;
|
|
/** Action fields that pick this variant (see the MOVE schema); absent for the ordinary move. */
|
|
piece?: number;
|
|
alt?: boolean;
|
|
stack?: false;
|
|
}
|
|
|
|
export interface YutSideView {
|
|
id: SideId;
|
|
name: string;
|
|
members: PlayerId[];
|
|
conceded: PlayerId[];
|
|
out: boolean;
|
|
finishedRank: number | null;
|
|
home: number;
|
|
onBoard: number;
|
|
done: number;
|
|
remaining: number;
|
|
/** 증강: pieces of this side (augments change it). */
|
|
total?: number;
|
|
}
|
|
|
|
export interface YutStackView {
|
|
node: NodeId;
|
|
side: SideId;
|
|
count: number;
|
|
/** Lowest piece id of the stack, only when one node holds several stacks of this side apart (`stacking = choose`). */
|
|
piece?: number;
|
|
/** 증강 */
|
|
kind?: PieceKind;
|
|
shield?: boolean;
|
|
frozen?: boolean;
|
|
}
|
|
|
|
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: Omit<YutMoveAction, 'type'> | null;
|
|
log: GameEvent[];
|
|
stats: YutStats;
|
|
result: YutResult | null;
|
|
/** 증강 윷놀이 only. */
|
|
aug?: YutAugView;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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'> & { augmented?: boolean }, n: number): string | null {
|
|
if (o.mode === 'team' && o.augmented) return '증강 윷놀이는 개인전(2~4명)으로만 할 수 있어요.';
|
|
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);
|
|
}
|
|
|
|
/** Pieces of one stack share node and key; `group` is only set while own stacks share a node apart (`stacking = choose`). */
|
|
const groupKey = (p: Piece) => p.group ?? -1;
|
|
|
|
function clearPiece(p: Piece, status: 'home' | 'done'): void {
|
|
Object.assign(p, { status, node: null, lapped: false, trail: [] });
|
|
delete p.group;
|
|
}
|
|
|
|
/** Own stacks on the board, by node then lowest piece id; `ids` ascending. */
|
|
function stacksOf(x: SideState): { node: NodeId; ids: number[] }[] {
|
|
const byKey = new Map<string, { node: NodeId; ids: number[] }>();
|
|
for (const p of [...x.pieces].sort((a, b) => a.id - b.id)) {
|
|
if (p.status !== 'board') continue;
|
|
const k = `${p.node}:${groupKey(p)}`;
|
|
const g = byKey.get(k);
|
|
if (g) g.ids.push(p.id);
|
|
else byKey.set(k, { node: p.node!, ids: [p.id] });
|
|
}
|
|
return [...byKey.values()].sort((a, b) => a.node - b.node || a.ids[0]! - b.ids[0]!);
|
|
}
|
|
|
|
/** A 빽도 that could never be used this turn: no own piece on the board and no forward result to bring one on. */
|
|
function backdoUseless(s: YutState): boolean {
|
|
const side = s.sides[s.turnSide]!;
|
|
return !side.pieces.some((p) => p.status === 'board') && !s.pending.some((t) => t !== 'backdo');
|
|
}
|
|
|
|
/** Variant fields of a MOVE (see the action schema). */
|
|
type MoveSel = Pick<YutMoveAction, 'piece' | 'alt' | 'stack'>;
|
|
|
|
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[];
|
|
/** Action selector for the stack on `from` (only when that node holds several own stacks). */
|
|
piece?: number;
|
|
alt: boolean;
|
|
/** Stops on own pieces but stays apart. */
|
|
apart: boolean;
|
|
}
|
|
|
|
/** 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', sel: MoveSel = {}): Plan | null {
|
|
const t = s.pending[throwIndex];
|
|
const side = s.sides[sideId];
|
|
if (!t || !side) return null;
|
|
const o = s.options;
|
|
const alt = sel.alt === true;
|
|
if (alt && (o.forkRule !== 'choose' || from === 'home' || !isFork(from) || t === 'backdo')) return null;
|
|
let movers: Piece[];
|
|
let to: NodeId | typeof GOAL;
|
|
let path: NodeId[];
|
|
let trailAfter: NodeId[];
|
|
if (from === 'home') {
|
|
const p = side.pieces.find((x) => x.status === 'home');
|
|
if (!p) return null;
|
|
movers = [p];
|
|
if (t === 'backdo') {
|
|
// 지역 룰: with no own piece on the board, a 빽도 puts a new piece one step behind 참먹이 (날윷).
|
|
if (o.backdoNoPiece !== 'enter' || side.pieces.some((x) => x.status === 'board')) return null;
|
|
to = 19;
|
|
path = [19];
|
|
trailAfter = [19];
|
|
} else {
|
|
const adv = advance('home', THROW_STEPS[t], o.finishRule);
|
|
({ to, path } = adv);
|
|
trailAfter = to === GOAL ? [] : [...path];
|
|
}
|
|
} else {
|
|
const here = side.pieces.filter((x) => x.status === 'board' && x.node === from);
|
|
if (here.length === 0) return null;
|
|
const lead = sel.piece === undefined ? here.reduce((a, b) => (b.id < a.id ? b : a)) : here.find((x) => x.id === sel.piece);
|
|
if (!lead) return null;
|
|
movers = here.filter((x) => groupKey(x) === groupKey(lead));
|
|
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, alt);
|
|
({ 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 });
|
|
}
|
|
}
|
|
const apart = sel.stack === false;
|
|
if (apart && (o.stacking !== 'choose' || stackWith.length === 0)) return null;
|
|
return {
|
|
throwIndex,
|
|
throw: t,
|
|
from,
|
|
to,
|
|
path,
|
|
movers: movers.map((p) => p.id),
|
|
trailAfter,
|
|
victims,
|
|
stackWith: apart ? [] : stackWith,
|
|
...(sel.piece !== undefined ? { piece: sel.piece } : {}),
|
|
alt,
|
|
apart,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Legal moves of the side to move. Equal results are listed once (first index; with `useOrder = thrown` only the
|
|
* first result). Order: index, stack (node, then lowest id), 'home' last; per source the ordinary move first, then
|
|
* "apart", the other road, other road + apart.
|
|
*/
|
|
function legalPlans(s: YutState): Plan[] {
|
|
if (s.phase !== 'move') return [];
|
|
const o = s.options;
|
|
const side = s.sides[s.turnSide]!;
|
|
const stacks = stacksOf(side);
|
|
const sources: { from: NodeId | 'home'; piece?: number }[] = stacks.map((g) =>
|
|
stacks.filter((h) => h.node === g.node).length > 1 ? { from: g.node, piece: g.ids[0]! } : { from: g.node },
|
|
);
|
|
if (side.pieces.some((p) => p.status === 'home')) sources.push({ from: 'home' });
|
|
const out: Plan[] = [];
|
|
const seen = new Set<Throw>();
|
|
const indices = o.useOrder === 'thrown' ? s.pending.slice(0, 1) : s.pending;
|
|
indices.forEach((t, i) => {
|
|
if (seen.has(t)) return;
|
|
seen.add(t);
|
|
for (const src of sources) {
|
|
const roads = o.forkRule === 'choose' && src.from !== 'home' && isFork(src.from) && t !== 'backdo' ? [false, true] : [false];
|
|
for (const alt of roads) {
|
|
const sel: MoveSel = { ...(src.piece !== undefined ? { piece: src.piece } : {}), ...(alt ? { alt } : {}) };
|
|
const p = planMove(s, s.turnSide, i, src.from, sel);
|
|
if (!p) continue;
|
|
out.push(p);
|
|
if (o.stacking === 'choose' && p.stackWith.length) out.push(planMove(s, s.turnSide, i, src.from, { ...sel, stack: false })!);
|
|
}
|
|
}
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/** The MOVE action that plays `p`. */
|
|
function planAction(p: Plan): YutMoveAction {
|
|
return {
|
|
type: 'MOVE',
|
|
throwIndex: p.throwIndex,
|
|
from: p.from,
|
|
...(p.piece !== undefined ? { piece: p.piece } : {}),
|
|
...(p.alt ? { alt: true } : {}),
|
|
...(p.apart ? { stack: false } : {}),
|
|
};
|
|
}
|
|
|
|
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,
|
|
...(p.piece !== undefined ? { piece: p.piece } : {}),
|
|
...(p.alt ? { alt: true } : {}),
|
|
...(p.apart ? { stack: false as const } : {}),
|
|
});
|
|
|
|
/** 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 flag = (x: boolean) => (x ? 1 : 0);
|
|
const byTie = (a: Plan, b: Plan) =>
|
|
a.throwIndex - b.throwIndex ||
|
|
flag(a.from === 'home') - flag(b.from === 'home') ||
|
|
(a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number)) ||
|
|
(a.piece ?? -1) - (b.piece ?? -1) ||
|
|
flag(a.alt) - flag(b.alt) ||
|
|
flag(a.apart) - flag(b.apart);
|
|
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
|
|
return planAction(chooseAuto(s, plans));
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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).
|
|
* With `useOrder = thrown` only the first result counts: an unusable first result is dropped and the next one is tried.
|
|
*/
|
|
function settleMovePhase(s: YutState, events: GameEvent[]): void {
|
|
if (s.phase !== 'move') return;
|
|
if (s.options.useOrder === 'thrown') {
|
|
while (s.pending.length && legalPlans(s).length === 0) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: s.pending.splice(0, 1) });
|
|
}
|
|
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' && s.options.nakRule === 'lose') {
|
|
// 지역 룰: a 낙 ends the turn and every unused result of this turn is lost.
|
|
pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current, endsTurn: true });
|
|
if (s.pending.length) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: [...s.pending] });
|
|
s.pending = [];
|
|
s.throwsOwed = 0;
|
|
endTurn(s, events);
|
|
return;
|
|
}
|
|
if (r.result === 'nak') {
|
|
pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current });
|
|
} else if (r.result === 'backdo' && s.options.backdoNoPiece === 'rethrow' && backdoUseless(s)) {
|
|
// 지역 룰: a 빽도 that could not be used is not kept; throw again.
|
|
pushLog(s, events, { type: 'thrown', side: s.turnSide, player: s.current, sticks: r.sticks, result: r.result });
|
|
pushLog(s, events, { type: 'backdoRethrow', side: s.turnSide, player: s.current });
|
|
s.throwsOwed += 1;
|
|
} 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, a: YutMoveAction, events: GameEvent[]): void {
|
|
const plan = planMove(s, s.turnSide, a.throwIndex, a.from, a);
|
|
if (!plan) throw new Error(`yut: illegal move ${a.throwIndex} ${a.from}`);
|
|
const side = s.sides[s.turnSide]!;
|
|
s.pending.splice(a.throwIndex, 1);
|
|
const movers = side.pieces.filter((p) => plan.movers.includes(p.id));
|
|
const lead = Math.min(...plan.movers);
|
|
for (const p of movers) {
|
|
if (plan.to === GOAL) clearPiece(p, 'done');
|
|
else {
|
|
Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] });
|
|
// Standing apart next to own pieces keeps a key of its own; otherwise it is the node's ordinary stack.
|
|
if (plan.apart) p.group = lead;
|
|
else delete p.group;
|
|
}
|
|
}
|
|
for (const p of side.pieces) {
|
|
if (!plan.stackWith.includes(p.id)) continue;
|
|
Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] });
|
|
delete p.group;
|
|
}
|
|
let caught = 0;
|
|
for (const v of plan.victims) {
|
|
for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) clearPiece(p, 'home');
|
|
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,
|
|
...(plan.alt ? { alt: true } : {}),
|
|
...(plan.apart ? { apart: true } : {}),
|
|
};
|
|
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,
|
|
...(plan.alt ? { alt: true } : {}),
|
|
...(plan.apart ? { apart: true } : {}),
|
|
});
|
|
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') clearPiece(p, 'home');
|
|
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;
|
|
}
|
|
if (s.phase === 'aug') {
|
|
// everyone picks at once: a longer, shared clock (reading three cards takes a while)
|
|
s.deadlineAt = now + Math.max(30, s.options.turnSeconds * 2) * 1000;
|
|
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,
|
|
};
|
|
if (options.augmented) {
|
|
s.turnSide = rng.int(nSides);
|
|
s.current = s.sides[s.turnSide]!.members[0]!;
|
|
augSetup(s, rng, []);
|
|
} else 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 (s.aug) return augValidate(s, actor, a);
|
|
if (a.type === 'AUG_PICK' || a.type === 'AUG_ANSWER' || a.type === 'AUG_USE' || a.type === 'SPECIAL') return fail('증강 윷놀이에서만 쓸 수 있어요.');
|
|
if (a.type === 'THROW' && a.pick) return fail('이 방은 결과를 고를 수 없어요.');
|
|
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('그 윷 결과는 없어요.');
|
|
const o = s.options;
|
|
if (a.from === 'home' && a.piece !== undefined) return fail('그 말은 움직일 수 없어요.');
|
|
if (o.useOrder === 'thrown' && a.throwIndex !== 0) return fail('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.');
|
|
if (a.from === 'home') {
|
|
if (!side.pieces.some((p) => p.status === 'home')) return fail('기다리는 말이 없어요.');
|
|
if (t === 'backdo') {
|
|
if (o.backdoNoPiece !== 'enter') return fail('빽도로는 새 말을 올릴 수 없어요.');
|
|
if (side.pieces.some((p) => p.status === 'board')) return fail('판에 내 말이 있으면 빽도는 판 위의 말에 써야 해요.');
|
|
}
|
|
} else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from && (a.piece === undefined || p.id === a.piece))) {
|
|
return fail('그 말은 움직일 수 없어요.');
|
|
}
|
|
if (a.alt) {
|
|
if (o.forkRule !== 'choose') return fail('이 방은 갈 길을 고르지 않아요. 모서리·방에 멈췄던 말은 늘 지름길로 가요.');
|
|
if (a.from === 'home' || !isFork(a.from) || t === 'backdo') return fail('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.');
|
|
}
|
|
if (a.stack === false) {
|
|
if (o.stacking !== 'choose') return fail('이 방은 내 말이 있는 자리에 멈추면 무조건 업어요.');
|
|
const plain = planMove(s, sideId, a.throwIndex, a.from, { ...a, stack: undefined });
|
|
if (plain && plain.stackWith.length === 0) return fail('그 자리에는 업을 내 말이 없어요.');
|
|
}
|
|
return planMove(s, sideId, a.throwIndex, a.from, a) ? 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' ? (s.aug ? augAutoAction(s, actor) : 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;
|
|
if (s.aug) {
|
|
augApply(s, actor, act, rng, events);
|
|
refreshDeadline(s, now);
|
|
return { state: s, events };
|
|
}
|
|
switch (act.type) {
|
|
case 'THROW':
|
|
doThrow(s, rng, events);
|
|
break;
|
|
case 'MOVE':
|
|
doMove(s, act, events);
|
|
break;
|
|
case 'CONCEDE':
|
|
doConcede(s, actor, events);
|
|
break;
|
|
default:
|
|
throw new Error(`yut: ${act.type} needs 증강 윷놀이`);
|
|
}
|
|
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 own = stacksOf(x);
|
|
for (const g of own) {
|
|
const apart = own.filter((h) => h.node === g.node).length > 1;
|
|
stacks.push({ node: g.node, side: x.id, count: g.ids.length, ...(apart ? { piece: g.ids[0]! } : {}) });
|
|
}
|
|
}
|
|
stacks.sort((a, b) => a.node - b.node || (a.piece ?? -1) - (b.piece ?? -1));
|
|
const mine = s.phase === 'move' && viewer !== null && viewer === s.current;
|
|
const plans = mine && !s.aug ? legalPlans(s) : [];
|
|
const auto = mine && plans.length ? chooseAuto(s, plans) : null;
|
|
const am = s.aug ? augMoves(s, viewer) : null;
|
|
const base: YutView = {
|
|
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: am ? am.legal : mine ? plans.map(toLegal) : null,
|
|
suggested: am ? am.suggested : auto ? (({ type: _t, ...rest }) => rest)(planAction(auto)) : null,
|
|
log: s.log,
|
|
stats: s.stats,
|
|
result: s.final,
|
|
};
|
|
return s.aug ? augView(s, viewer, base) : base;
|
|
},
|
|
|
|
activePlayers(s) {
|
|
if (s.aug) return augActivePlayers(s);
|
|
return s.phase === 'finished' ? [] : [s.current];
|
|
},
|
|
|
|
deadline(s) {
|
|
return s.phase === 'finished' ? null : s.deadlineAt;
|
|
},
|
|
|
|
timeoutPlayers(s) {
|
|
if (s.aug) return augActivePlayers(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,
|
|
scoreText: Object.fromEntries(
|
|
f.ranking.flatMap((r) => r.players.map((p) => [p, r.reason && s.aug ? `난 말 ${r.finishedPieces}개 · ${r.reason}` : `난 말 ${r.finishedPieces}개`])),
|
|
),
|
|
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.aug) return augLegalActions(s, p);
|
|
if (s.phase === 'finished' || p !== s.current) return [];
|
|
if (s.phase === 'throw') return [{ type: 'THROW' }];
|
|
return legalPlans(s).map(planAction);
|
|
},
|
|
};
|
|
|
|
/** 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]}칸)`;
|
|
}
|