import type { Dir, MoveDir, RelDir, Role } from '@two-keys/shared'; import type { LabyrinthGame } from '../content/schemas'; import { OK, fail, type ActionResult, type Ctx } from './types'; export interface Point { x: number; y: number; } /** You may step from (x, y) in `dir`, never back the other way. */ export interface Gate extends Point { dir: Dir; } export const DELTAS: Record = { n: { x: 0, y: -1 }, e: { x: 1, y: 0 }, s: { x: 0, y: 1 }, w: { x: -1, y: 0 }, }; export const OPPOSITE: Record = { n: 's', e: 'w', s: 'n', w: 'e' }; export const REL_DIRS: readonly RelDir[] = ['f', 'r', 'b', 'l']; const CLOCKWISE: readonly Dir[] = ['n', 'e', 's', 'w']; /** Forward / right / back / left from the way you face → a compass direction. */ export function toAbsolute(facing: Dir, rel: RelDir): Dir { return CLOCKWISE[(CLOCKWISE.indexOf(facing) + REL_DIRS.indexOf(rel)) % 4]; } export const cellAt = (grid: string[], x: number, y: number): string => grid[y]?.[x] ?? '#'; export const isWall = (grid: string[], x: number, y: number): boolean => cellAt(grid, x, y) === '#'; /** True if a one-way gate stops a step from (x, y) in `dir`. */ export function gateBlocks(gates: readonly Gate[], x: number, y: number, dir: Dir): boolean { const d = DELTAS[dir]; return gates.some((g) => g.x === x + d.x && g.y === y + d.y && g.dir === OPPOSITE[dir]); } export function findCells(grid: string[], char: string): Point[] { const found: Point[] = []; grid.forEach((row, y) => [...row].forEach((c, x) => c === char && found.push({ x, y }))); return found; } const key = (p: Point) => `${p.x},${p.y}`; /** Every cell reachable from S without ever stepping on a trap. */ export function safeReachable(grid: string[], gates: readonly Gate[] = []): Set { const [start] = findCells(grid, 'S'); const seen = new Set(); if (!start) return seen; const queue: Point[] = [start]; seen.add(key(start)); while (queue.length > 0) { const p = queue.shift()!; for (const dir of CLOCKWISE) { const next = { x: p.x + DELTAS[dir].x, y: p.y + DELTAS[dir].y }; const c = cellAt(grid, next.x, next.y); if (c === '#' || c === 'T' || seen.has(key(next)) || gateBlocks(gates, p.x, p.y, dir)) continue; seen.add(key(next)); queue.push(next); } } return seen; } export const isReachable = (reach: Set, p: Point) => reach.has(key(p)); /** * Plays the maze out as a graph of (cell, lanterns held). Returns whether a trap-free run can * finish, and any cell where the Explorer could end up with no way left to finish (one-way * gates make that possible). Falling into a trap counts as a way out: it leads back to S. */ export function analyseMaze( grid: string[], gates: readonly Gate[], lanterns: readonly Point[], ): { winnable: boolean; stuck: Point[] } { const [start] = findCells(grid, 'S'); if (!start) return { winnable: false, stuck: [] }; const full = (1 << lanterns.length) - 1; const id = (p: Point, mask: number, safe: boolean) => `${p.x},${p.y},${mask},${safe ? 1 : 0}`; const pickUp = (p: Point, mask: number) => { const i = lanterns.findIndex((l) => l.x === p.x && l.y === p.y); return i >= 0 ? mask | (1 << i) : mask; }; // `safe` tracks whether the run so far is trap-free. type Node = { p: Point; mask: number; safe: boolean }; const first: Node = { p: start, mask: 0, safe: true }; const seen = new Map([[id(start, 0, true), first]]); const reverse = new Map(); const queue: Node[] = [first]; const goals: string[] = []; while (queue.length > 0) { const node = queue.shift()!; const from = id(node.p, node.mask, node.safe); if (cellAt(grid, node.p.x, node.p.y) === 'E' && node.mask === full) { goals.push(from); continue; } for (const dir of CLOCKWISE) { const step = { x: node.p.x + DELTAS[dir].x, y: node.p.y + DELTAS[dir].y }; const c = cellAt(grid, step.x, step.y); if (c === '#' || gateBlocks(gates, node.p.x, node.p.y, dir)) continue; const next: Node = c === 'T' ? { p: start, mask: node.mask, safe: false } : { p: step, mask: pickUp(step, node.mask), safe: node.safe }; const to = id(next.p, next.mask, next.safe); reverse.set(to, [...(reverse.get(to) ?? []), from]); if (!seen.has(to)) { seen.set(to, next); queue.push(next); } } } const canFinish = new Set(goals); const back = [...goals]; while (back.length > 0) { for (const from of reverse.get(back.pop()!) ?? []) { if (!canFinish.has(from)) { canFinish.add(from); back.push(from); } } } const stuck = new Map(); for (const [nodeId, node] of seen) if (!canFinish.has(nodeId)) stuck.set(key(node.p), node.p); return { winnable: goals.some((g) => g.endsWith(',1')), stuck: [...stuck.values()] }; } export interface LabyrinthState { x: number; y: number; /** The way the Explorer faces: the direction of their last step. */ facing?: Dir; collected: boolean[]; moves: number; falls: number; message: string; } export function initLabyrinth(game: LabyrinthGame): LabyrinthState { const [start] = findCells(game.grid, 'S'); return { ...start, facing: game.explorer.startFacing, collected: game.lanterns.map(() => false), moves: 0, falls: 0, message: '', }; } export const facingOf = (game: LabyrinthGame, s: LabyrinthState): Dir => s.facing ?? game.explorer.startFacing; export function moveExplorer(game: LabyrinthGame, ctx: Ctx, role: Role, move: MoveDir): ActionResult { const s = ctx.room.engine as LabyrinthState; if (role !== 'B') return fail('wrong_role', 'Only the Explorer can move.'); const relative = game.explorer.compass === 'relative'; const isRel = (REL_DIRS as readonly string[]).includes(move); if (relative !== isRel) return fail('bad_dir', relative ? 'You have no compass in here.' : "You can't move like that here."); const dir = isRel ? toAbsolute(facingOf(game, s), move as RelDir) : (move as Dir); const d = DELTAS[dir]; const next = { x: s.x + d.x, y: s.y + d.y }; if (isWall(game.grid, next.x, next.y)) return fail('wall', "Solid stone. You can't go that way."); if (gateBlocks(game.oneWay, s.x, s.y, dir)) return fail('gate', "The gate won't open from this side."); const flavour = game.explorerView.flavour; const throughGate = game.oneWay.some((g) => g.x === s.x && g.y === s.y && g.dir === dir); s.moves++; s.x = next.x; s.y = next.y; s.facing = dir; s.message = throughGate ? (flavour.gate ?? "A gate swings shut behind you. It won't open from this side.") : ''; const cell = cellAt(game.grid, next.x, next.y); if (cell === 'T') { const [start] = findCells(game.grid, 'S'); s.x = start.x; s.y = start.y; s.facing = game.explorer.startFacing; s.falls++; s.message = flavour.trap; ctx.addPenalty(game.scoring.trapPenaltySeconds); ctx.toast('A', 'Your Explorer fell into a trap and is back at the entrance.'); } else if (cell === 'K') { const i = game.lanterns.findIndex((l) => l.x === next.x && l.y === next.y); if (i >= 0 && !s.collected[i]) { s.collected[i] = true; ctx.addKey(game.lanterns[i].name); s.message = flavour.lantern.replace('{name}', game.lanterns[i].name); } } else if (cell === 'E') { if (s.collected.every(Boolean)) { s.message = flavour.exitOpen; ctx.finish(true, game.successEnding); } else { s.message = flavour.exitLocked; } } return OK; }