import { playSound } from './audio'; import { checkAll, saveState, type GameState } from './state'; import type { Action, Clue, Hotspot, Interaction, Item, PuzzleDef, Scenario, Scene } from './types'; import type { PuzzleContext } from '../puzzles/registry'; export type MessageKind = 'info' | 'hint' | 'item'; export type Transition = 'fade' | 'zoom-in' | 'zoom-out' | 'turn-left' | 'turn-right' | 'none'; /** * Ce que le moteur attend d'un rendu (aujourd'hui ThreeRenderer). Le moteur * ne dépend d'aucune technologie d'affichage. */ export interface View { showScene(scene: Scene, transition: Transition): void; refresh(): void; showMessage(text: string, kind: MessageKind): void; /** Ajoute au message courant la proposition de noter cet indice. */ offerClue?(clue: Clue): void; /** Annonce d'un objet obtenu. */ itemGained?(item: Item): void; openPuzzle(def: PuzzleDef, ctx: PuzzleContext): void; closePuzzle(): void; showWin(): void; } /** Bandes de navigation auto-générées (largeur en px dans le repère `resolution`). */ const NAV_SIZE = 90; export class Engine { private scenes = new Map(); private items = new Map(); private puzzles = new Map(); private view!: View; private timer: ReturnType | undefined; constructor( public readonly scenario: Scenario, public readonly state: GameState, /** Tests : résolution des mini-jeux sans délai d'animation. */ private readonly options: { instant?: boolean } = {}, ) { scenario.scenes.forEach((s) => this.scenes.set(s.id, s)); scenario.items.forEach((i) => this.items.set(i.id, i)); scenario.puzzles.forEach((p) => this.puzzles.set(p.id, p)); for (const [k, v] of Object.entries(scenario.vars ?? {})) if (state.vars[k] === undefined) state.vars[k] = v; } attach(view: View): void { this.view = view; } start(): void { this.view.showScene(this.currentScene, 'fade'); this.view.refresh(); if (this.state.elapsedMs === 0 && this.scenario.intro) { this.view.showMessage(this.scenario.intro, 'info'); } this.startTimer(); saveState(this.state); } stop(): void { clearInterval(this.timer); } private startTimer(): void { clearInterval(this.timer); this.timer = setInterval(() => { if (this.state.won || (typeof document !== 'undefined' && document.hidden)) return; this.state.elapsedMs += 1000; if (this.state.elapsedMs % 10000 === 0) saveState(this.state); }, 1000); } // --- Lecture ------------------------------------------------------------------ get currentScene(): Scene { const s = this.scenes.get(this.state.scene); if (!s) throw new Error(`Scène introuvable : ${this.state.scene}`); return s; } getItem(id: string): Item | undefined { return this.items.get(id); } getClue(id: string): Clue | undefined { return this.scenario.clues?.find((c) => c.id === id); } /** Note un indice dans le carnet. Renvoie false s'il y était déjà ou n'existe pas. */ noteClue(id: string): boolean { if (!this.getClue(id) || this.state.notebook.includes(id)) return false; this.state.notebook.push(id); playSound('pickup'); saveState(this.state); this.view.refresh(); return true; } /** Zones actives de la scène, y compris les bandes de navigation générées. */ activeHotspots(scene: Scene): Hotspot[] { const [w, h] = this.scenario.resolution; const nav: Hotspot[] = []; if (scene.left) { nav.push({ id: '__left', rect: [0, 0, NAV_SIZE, h], cursor: 'left', label: 'Tourner à gauche', interactions: [{ do: [{ goto: scene.left }] }] }); } if (scene.right) { nav.push({ id: '__right', rect: [w - NAV_SIZE, 0, NAV_SIZE, h], cursor: 'right', label: 'Tourner à droite', interactions: [{ do: [{ goto: scene.right }] }] }); } if (scene.back) { nav.push({ id: '__back', rect: [NAV_SIZE, h - NAV_SIZE, w - 2 * NAV_SIZE, NAV_SIZE], cursor: 'back', label: 'Reculer', interactions: [{ do: [{ goto: scene.back }] }] }); } const own = scene.hotspots.filter((hs) => checkAll(this.state, hs.visibleWhen)); // Les zones du scénario passent au-dessus des bandes de navigation. return [...nav, ...own]; } // --- Interactions ------------------------------------------------------------- /** Clic sur une zone. Renvoie true si une interaction a été exécutée. */ click(hotspot: Hotspot): boolean { const isNav = hotspot.id.startsWith('__'); const match: Interaction | undefined = hotspot.interactions.find((i) => checkAll(this.state, i.when)); if (this.state.selected && !isNav) { const usesSelection = match?.when?.some((c) => c === `selected:${this.state.selected}`); const item = this.getItem(this.state.selected); // Dans tous les cas, l'objet est « rangé » après usage : on le reprend en main si besoin. this.state.selected = null; if (!usesSelection) { this.view.showMessage(`${item?.name ?? 'Cet objet'} ne sert à rien ici.`, 'info'); this.view.refresh(); return false; } } if (!match) return false; this.run(match.do); return true; } /** Clic droit sur une zone : renvoie true si une interaction `rightClick` s'est exécutée. */ rightClick(hotspot: Hotspot): boolean { const match = hotspot.rightClick?.find((i) => checkAll(this.state, i.when)); if (!match) return false; this.state.selected = null; this.run(match.do); return true; } /** Sélectionner un objet puis cliquer sur un autre objet de l'inventaire. */ /** Renvoie true si la combinaison existe. */ combine(a: string, b: string): boolean { const combo = this.scenario.combinations?.find((c) => (c.items[0] === a && c.items[1] === b) || (c.items[0] === b && c.items[1] === a)); this.state.selected = null; if (!combo) { const na = this.getItem(a)?.name ?? a; const nb = this.getItem(b)?.name ?? b; this.view.showMessage(`Combiner « ${na} » et « ${nb} » ne donne rien.`, 'info'); this.view.refresh(); return false; } this.run(combo.do); return true; } goBack(): void { const scene = this.currentScene; if (this.state.selected) { this.state.selected = null; this.view.refresh(); } else if (scene.back) { this.run([{ goto: scene.back }]); } } selectItem(id: string): void { this.state.selected = this.state.selected === id ? null : id; playSound('click'); this.view.refresh(); } nextHint(): void { const idx = this.scenario.hints.findIndex((g) => checkAll(this.state, g.when)); if (idx < 0) { this.view.showMessage('Pas d’indice pour le moment.', 'hint'); return; } const group = this.scenario.hints[idx]; const level = this.state.hintLevels[idx] ?? 0; const shown = Math.min(level, group.hints.length - 1); if (level < group.hints.length) { this.state.hintLevels[idx] = level + 1; this.state.hintsUsed++; saveState(this.state); } const suffix = group.hints.length > 1 ? ` (${shown + 1}/${group.hints.length})` : ''; this.view.showMessage(group.hints[shown] + suffix, 'hint'); this.view.refresh(); } run(actions: Action[]): void { for (const action of actions) this.exec(action); this.runTriggers(); saveState(this.state); this.view.refresh(); } /** Exécute les déclencheurs dont les conditions sont devenues vraies (une fois chacun). */ private runTriggers(): void { for (let pass = 0; pass < 5; pass++) { const ready = (this.scenario.triggers ?? []).filter((t) => !this.state.fired[t.id] && checkAll(this.state, t.when)); if (!ready.length) return; for (const t of ready) { this.state.fired[t.id] = true; for (const a of t.do) this.exec(a); } } } private exec(action: Action): void { if ('goto' in action) { const from = this.currentScene; const to = this.scenes.get(action.goto); if (!to) return console.error(`goto : scène inconnue "${action.goto}"`); this.state.scene = to.id; let t: Transition = 'fade'; if (from.left === to.id) t = 'turn-left'; else if (from.right === to.id) t = 'turn-right'; else if (from.back === to.id) t = 'zoom-out'; else if (to.back === from.id) t = 'zoom-in'; playSound('step'); this.view.showScene(to, t); } else if ('message' in action) { this.view.showMessage(action.message, 'info'); } else if ('setFlag' in action) { this.state.flags[action.setFlag] = true; } else if ('clearFlag' in action) { delete this.state.flags[action.clearFlag]; } else if ('give' in action) { if (!this.state.inventory.includes(action.give)) { this.state.inventory.push(action.give); const item = this.getItem(action.give); if (item) this.view.itemGained?.(item); } playSound('pickup'); } else if ('remove' in action) { this.state.inventory = this.state.inventory.filter((i) => i !== action.remove); if (this.state.selected === action.remove) this.state.selected = null; } else if ('puzzle' in action) { this.openPuzzle(action.puzzle); } else if ('sound' in action) { playSound(action.sound); } else if ('add' in action) { let v = (this.state.vars[action.add] ?? 0) + (action.value ?? 1); if (action.mod) v = ((v % action.mod) + action.mod) % action.mod; this.state.vars[action.add] = v; } else if ('set' in action) { this.state.vars[action.set] = action.value; } else if ('if' in action) { for (const a of checkAll(this.state, action.if) ? action.then : (action.else ?? [])) this.exec(a); } else if ('clue' in action) { const clue = this.getClue(action.clue); if (clue && !this.state.notebook.includes(clue.id)) this.view.offerClue?.(clue); } else if ('win' in action) { this.state.won = true; this.state.selected = null; saveState(this.state); this.view.showWin(); } } private openPuzzle(id: string): void { const def = this.puzzles.get(id); if (!def) return console.error(`Puzzle inconnu "${id}"`); const ctx: PuzzleContext = { def, data: this.state.puzzleData[id], alreadySolved: !!this.state.solved[id], save: (data) => { this.state.puzzleData[id] = data; saveState(this.state); }, solve: () => { if (this.state.solved[id]) return; this.state.solved[id] = true; playSound('success'); const finish = () => { this.view.closePuzzle(); this.run(def.onSolve); }; if (this.options.instant) finish(); else setTimeout(finish, 1100); }, close: () => this.view.closePuzzle(), sound: playSound, }; this.view.openPuzzle(def, ctx); } }