/** * What to play and animate when the janggi view changes (pure, so it is unit-tested; no DOM or audio here). * Everything is derived from two consecutive views, so the opponent's and the computer's moves get the same * sound and motion as mine, and one change gives exactly one set of cues. */ import type { JanggiMove, JanggiView, Piece } from '@bg/games/janggi'; export type JanggiCue = 'move' | 'capture' | 'pass' | 'janggun' | 'meonggun' | 'bikjang' | 'mate' | 'undo'; /** The parts of the previous view the cues compare against. */ export interface JanggiPrev { count: number; inCheck: JanggiView['inCheck']; bikjang: JanggiView['bikjang']; } type CueView = Pick & { result: { reason: string } | null }; /** Sounds for one change of the move list. Empty when no move was added or taken back. */ export function janggiCues(p: JanggiPrev, v: CueView): JanggiCue[] { if (v.moveCount === p.count) return []; if (v.moveCount < p.count) return ['undo']; const m = v.moves[v.moves.length - 1]; if (!m) return []; const out: JanggiCue[] = [m.kind === 'pass' ? 'pass' : m.captured ? 'capture' : 'move']; // After a ply the mover is never in check, so a side in check now was just checked by that ply. if (v.phase === 'finished' && v.result?.reason === 'checkmate') out.push('mate'); else if (v.inCheck) out.push('janggun'); else if (p.inCheck && v.phase === 'playing') out.push('meonggun'); if (v.bikjang && !p.bikjang) out.push('bikjang'); return out; } const key = (q: { f: number; r: number }) => q.r * 9 + q.f; const same = (a: Piece | null | undefined, b: Piece | null | undefined) => (!a && !b) || (!!a && !!b && a.side === b.side && a.kind === b.kind); export interface JanggiMotion { /** Board index the moved piece now stands on, and where it came from. */ to: number; from: number; /** The piece it took (drawn fading on the same point). */ captured: Piece | null; } /** Motion for one ply forward (`before` = board one ply earlier, null on page load / undo / several plies at once). */ export function janggiMotion(before: readonly (Piece | null)[] | null, board: readonly (Piece | null)[], last: JanggiMove | undefined): JanggiMotion | null { if (!before || !last || last.kind !== 'move') return null; const to = key(last.to); const from = key(last.from); if (!board[to] || board[from]) return null; const prev = before[to]; return { to, from, captured: prev && prev.side !== board[to]!.side ? prev : null }; } /** * Pieces that appeared during 상차림 (a 마·상 arrangement put on the board). Only a pure addition counts, so an undo * or a move is never mistaken for it. */ export function addedPieces(before: readonly (Piece | null)[] | null, board: readonly (Piece | null)[]): number[] { if (!before) return []; const out: number[] = []; for (let i = 0; i < board.length; i++) { if (before[i]) { if (!same(before[i], board[i])) return []; } else if (board[i]) out.push(i); } return out; }