import type { ZoneDef } from '../core/types'; import { emo, h, type Ctx } from './dom'; import { tallyRead } from '../core/tally'; /** Tamaño de celda del automapa en unidades de mundo (≈ media pantalla). */ export const CELL_W = 13; export const CELL_H = 8; const B32 = '0123456789abcdefghijklmnopqrstuv'; function dims(z: ZoneDef): { nx: number; ny: number } { const b = z.bounds; return { nx: Math.max(1, Math.ceil((b.maxX - b.minX) / CELL_W)), ny: Math.max(1, Math.ceil((b.maxY - b.minY) / CELL_H)) }; } /** Bits → cadena compacta (5 bits por carácter). */ function encode(bits: Uint8Array): string { let s = ''; for (let i = 0; i < bits.length; i += 5) { let v = 0; for (let k = 0; k < 5; k++) if (bits[i + k]) v |= 1 << k; s += B32[v]; } return s.replace(/0+$/, ''); } function decode(s: string, n: number): Uint8Array { const bits = new Uint8Array(n); for (let c = 0; c < s.length; c++) { const v = B32.indexOf(s[c]); for (let k = 0; k < 5; k++) if (v & (1 << k) && c * 5 + k < n) bits[c * 5 + k] = 1; } return bits; } /** Punto de interés guardado en flags `map.poi..` = "x,y,emoji". */ interface Poi { zone: string; id: string; x: number; y: number; emoji: string } /** * Registro del automapa: celdas visitadas por zona en flags `map.`, * puntos de interés (`map.poi.*`) y checkpoints (`map.cp..`). */ export class AutoMap { private cache = new Map(); private lastCell = ''; el: HTMLElement | null = null; constructor(private ctx: Ctx) { const ev = ctx.game.events; ev.on('map:poi', (p) => { if (!p || !p.zone || !p.id) return; ctx.game.state.set(`map.poi.${p.zone}.${p.id}`, `${+p.x.toFixed(2)},${+p.y.toFixed(2)},${p.emoji}`); }); ev.on('checkpoint', ({ zone, spawn }) => ctx.game.state.set(`map.cp.${zone}.${spawn}`, true)); ev.on('zone:loaded', () => { this.lastCell = ''; this.sample(); }); } private bitsFor(z: ZoneDef): Uint8Array { const { nx, ny } = dims(z); const raw = this.ctx.game.state.get(`map.${z.id}`); const key = `${typeof raw === 'string' ? raw : ''}|${nx}x${ny}`; const c = this.cache.get(z.id); if (c && c.key === key) return c.bits; const bits = decode(typeof raw === 'string' ? raw : '', nx * ny); this.cache.set(z.id, { key, bits }); return bits; } /** Marca la celda del héroe (llamar en cada paso; barato si no cambia). */ sample(): void { const g = this.ctx.game; const z = g.zone; const hero = g.hero; if (!z || !hero || g.loading) return; const { nx, ny } = dims(z); const cx = Math.max(0, Math.min(nx - 1, Math.floor((hero.x - z.bounds.minX) / CELL_W))); const cy = Math.max(0, Math.min(ny - 1, Math.floor((hero.y - z.bounds.minY) / CELL_H))); const ck = `${z.id}:${cx}:${cy}`; if (ck === this.lastCell) return; this.lastCell = ck; const bits = this.bitsFor(z); const i = cy * nx + cx; if (bits[i]) return; bits[i] = 1; g.state.set(`map.${z.id}`, encode(bits)); } private pois(): Poi[] { const out: Poi[] = []; const flags = this.ctx.game.state.data.flags; for (const k in flags) { if (!k.startsWith('map.poi.')) continue; const rest = k.slice(8); const dot = rest.indexOf('.'); if (dot < 0) continue; const [x, y, ...e] = String(flags[k]).split(','); out.push({ zone: rest.slice(0, dot), id: rest.slice(dot + 1), x: +x, y: +y, emoji: e.join(',') || '❓' }); } return out; } // ───────── Vista ───────── /** * El mapa es el CONTADOR DEL TESORO: por cada zona, monedas y diamantes recogidos frente a los que hay * (incluidos cofres y tierra cavable). Sirve para saber a dónde volver a por lo que falta. */ show(onClose: () => void): void { this.hide(); const g = this.ctx.game; const el = (this.el = h('div', 'eh-map', null, this.ctx.root)); el.addEventListener('pointerdown', (ev) => { if (ev.target === el) onClose(); }); const box = h('div', 'eh-panel eh-mbox', null, el); h('div', 'eh-title-text eh-ptitle', 'TESORO DEL REINO', box); const close = h('button', 'eh-mclose', '✕', box); close.addEventListener('click', (ev) => { ev.stopPropagation(); onClose(); }); const list = h('div', 'eh-tlist', null, box); let sc = 0, st = 0, sd = 0, sdt = 0; let curEl: HTMLElement | null = null; const bar = (parent: HTMLElement, e: string, got: number, tot: number, cls: string) => { const b = h('div', `eh-tbar ${cls}${tot > 0 && got >= tot ? ' full' : ''}`, null, parent); emo(e, b); const tr = h('span', 'tr', null, b); const fill = h('i', '', null, tr); fill.style.width = `${tot ? Math.round((got / tot) * 100) : 0}%`; h('span', '', tot ? `${got}/${tot}` : '—', b); }; for (const id of g.zoneIds()) { if (id === 'test') continue; const z = g.getZone(id); if (!z) continue; const t = tallyRead(g, id); const cur = g.zone?.id === id; const row = h('div', `eh-trow${cur ? ' cur' : ''}${t ? '' : ' unk'}`, null, list); if (cur) curEl = row; emo(t ? z.emoji : '❔', row); const nm = h('div', 'nm', null, row); h('span', '', t ? z.name : '???', nm); if (cur) h('small', '', 'estás aquí', nm); const bars = h('div', 'eh-tbars', null, row); if (!t) { h('span', '', 'Sin explorar', bars); continue; } sc += t.cg; st += t.ct; sd += t.dg; sdt += t.dt; bar(bars, '🪙', t.cg, t.ct, 'c'); bar(bars, '💎', t.dg, t.dt, 'd'); } const d = g.state.data; const sum = h('div', 'eh-tsum', null, box); const item = (e: string, txt: string) => { const sp = h('span', '', null, sum); emo(e, sp); h('span', '', txt, sp); }; item('🪙', `Recogidas ${sc}/${st}`); item('💎', `Recogidos ${sd}/${sdt}`); item('🎒', `Llevas ${d.coins} 🪙 · ${d.diamonds} 💎`); curEl?.scrollIntoView?.({ block: 'center' }); } hide(): void { this.el?.remove(); this.el = null; } }