/* explorer.js — The Valley: the landing page. * * Progressive disclosure, in four levels: * 0 the painted valley, its landmarks, and the dragons where riders meet them (faint = rarely met). No routes. * 1 hover or focus a dragon or landmark: a short note (riders who met it, bond chance there). * 2 choose a dragon: every route to every place that dragon can be bonded, drawn at once. Line width = chance you * are still on the route at that point (it narrows at every roll of the dice and every risk); the better route * is solid and opaque, weaker ones fade and turn dashed, then dotted. * 3 click a choice point on the highlighted route: its other options branch off, each with the chance it gives. * Picking one re-plans the route from there. * 4 "Why this route?" in the side panel: intervals, how often the choice stays best, low-bias numbers, risks. * A toggle adds the community's actual traffic underneath. The URL keeps the selection (#valley/blue/meadow-Blue). */ (function () { "use strict"; const S = window.ThreshSolver, V = window.ValleyMap, D = window.DragonArt; if (!S || !V || !D) return; const $ = (q, el = document) => el.querySelector(q); const $$ = (q, el = document) => [...el.querySelectorAll(q)]; const NS = "http://www.w3.org/2000/svg"; const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); const pct = (p) => (p == null || isNaN(p) ? "–" : p === 0 ? "0%" : p < 0.001 ? "<0.1%" : (p * 100).toFixed(p < 0.1 ? 1 : 0) + "%"); const L = V.places, INK = V.INK, PAPER = V.PAPER; const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" }; const COLOURS = ["Red", "Orange", "Brown", "Green", "Blue", "Black"]; const GATE = { x: 500, y: 770, name: "The entrance" }; function el(tag, attrs = {}, parent) { const e = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v); if (parent) parent.appendChild(e); return e; } /* ---------- the cast: where each dragon is met, in what pose ---------- */ const ENC_NAME = { "valley-Red": "The valley Red", "tree-Red": "The Red below the tree", "tree-Greens": "The two Greens", "meadow-Orange": "The meadow Orange", "meadow-Brown": "The meadow Brown", "meadow-Blue": "The meadow Blue", "shadow-Blue": "The Blue at the redwood", "shadow-Black": "The Black (the shadow)", }; const RESCUE = { Orange: "tree-Greens", Brown: "tree-Greens" }; const SPOTS = [ { place: "treeRed", enc: "tree-Red", colour: "Red", pose: "prowling", flip: true, sc: 0.36 }, { place: "greens", enc: "tree-Greens", colour: "Green", pose: "resting", sc: 0.3, dx: -16 }, { place: "greens", enc: "tree-Greens", colour: "Green", pose: "sitting", flip: true, sc: 0.27, dx: 20, dy: -4, twin: true }, { place: "black", enc: "shadow-Black", colour: "Black", pose: "flying", flip: true, sc: 0.38 }, { place: "redwood", enc: "shadow-Blue", colour: "Blue", pose: "coiled", sc: 0.3 }, { place: "valleyRed", enc: "valley-Red", colour: "Red", pose: "roaring", sc: 0.36, dy: -12 }, { place: "meadow:Orange", enc: "meadow-Orange", colour: "Orange", pose: "sitting", flip: true, sc: 0.3 }, { place: "meadow:Brown", enc: "meadow-Brown", colour: "Brown", pose: "resting", sc: 0.32 }, { place: "meadow:Blue", enc: "meadow-Blue", colour: "Blue", pose: "sitting", sc: 0.32 }, ]; const FIRST_POSE = { Red: "roaring", Brown: "sitting", Green: "prowling", Orange: "flying" }; Object.keys(L).filter((k) => k.startsWith("see:")).forEach((k) => { const c = L[k].colour; SPOTS.push({ place: k, first: true, colour: c, pose: FIRST_POSE[c], sc: 0.2, flip: L[k].x > 500 }); }); const LANDMARKS = ["dir:West", "dir:Center", "dir:East", "scream", "bully", "wounded", "fork:Forest", "hour", "tree", "valley", "meadow", "stream"]; const LANDMARK_NAME = { "dir:West": "West, toward the scent", "dir:Center": "Forest centre", "dir:East": "East, toward the roar", "fork:Forest": "The fork" }; /* ---------- state ---------- */ const st = { policy: null, runs: null, counts: {}, colour: null, focus: null, expanded: null, over: {}, objective: "eventually", sample: "all", traffic: false, cache: new Map(), pendingHash: null, info: null, }; const model = () => st.policy.samples[st.sample]; function advisorFor(enc) { const k = `${st.sample}|${st.colour}|${st.objective}|${enc}`; if (!st.cache.has(k)) st.cache.set(k, S.advisor(model(), st.colour, st.objective, { only: [enc] })); return st.cache.get(k); } let encParams = null; const encOutcome = (enc) => { if (!encParams || encParams.sample !== st.sample) encParams = { sample: st.sample, p: S.makeParams(model().model.tables, { alphas: model().model.alphas }) }; return encParams.p.encounter(enc); }; /* ---------- walking one route ---------- */ const encColour = (enc) => (enc === "tree-Greens" ? "Green" : enc.split("-")[1]); function defaultOutcome(s, enc) { const ent = Object.entries(s.probs).sort((a, b) => b[1] - a[1]); if (s.var === "shadow") return enc.startsWith("shadow-") ? "yes" : "no"; if (s.var === "shadowColour" || s.var === "meadow") { const c = encColour(enc); if (s.probs[c] != null) return c; } return ent[0][0]; } function walk(enc) { const adv = advisorFor(enc), over = st.over[enc] || {}, steps = [], h = {}; for (let i = 0; i < 20; i++) { const s = adv.step(h); s.before = { ...h }; steps.push(s); if (s.kind === "end") break; const key = s.var; const ok = s.kind === "decision" ? over[key] && s.options[over[key]] : over[key] && s.probs[over[key]] != null; s.taken = ok ? over[key] : s.kind === "decision" ? s.choice : defaultOutcome(s, enc); s.userSet = !!ok; h[key] = s.taken; } return { enc, adv, steps, value: Object.keys(over).length ? routeValue(adv, over) : adv.value }; } /** * Value of a route when the rider follows their own choices (overrides) and plays the best route everywhere else: * expectimax over the rolls, using the overridden option where one is set. Option values already include the * best play after them, so recursion stops as soon as no override is left to apply. */ function routeValue(adv, over) { const keys = Object.keys(over); const rec = (h) => { const s = adv.step(h); if (s.kind === "end") return { x: 0, o: 0 }; const live = s.risk ? 1 - s.risk.p : 1; if (s.kind === "chance") { return Object.entries(s.probs).reduce((acc, [b, p]) => { if (!p) return acc; const v = rec({ ...h, [s.var]: b }); return { x: acc.x + p * v.x, o: acc.o + p * v.o }; }, { x: 0, o: 0 }); } const o = over[s.var] && s.options[over[s.var]] ? over[s.var] : s.choice; const pending = keys.some((k) => h[k] == null && k !== s.var); if (!pending) { const v = s.options[o]; return { x: live * v.pX, o: live * v.pOther }; } const v = rec({ ...h, [s.var]: o }); return { x: live * v.x, o: live * v.o }; }; return rec({}); } /** The route as points on the map, each with the chance of still being on it, plus where decisions are made. */ function routePoints(route) { const pts = [{ id: "gate", P: GATE, flow: 1 }], marks = [], rolls = []; let flow = 1; const push = (id) => { if (L[id]) pts.push({ id, P: L[id], flow }); }; const last = () => pts[pts.length - 1]; route.steps.forEach((s, i) => { if (s.risk) flow *= 1 - s.risk.p; if (s.kind === "chance") flow *= s.probs[s.taken] || 0; if (s.kind === "end") return; if (s.kind === "decision") marks.push({ i, s, at: last() }); const before = pts.length; const v = s.taken, h = s.before; switch (s.var) { case "company": push("comp:" + v); break; case "direction": push("dir:" + v); break; case "fs": push(`see:${h.direction}:${v}`); break; // the cadet encounter, step by step: you hear the scream, then either investigate (the clearing with your // squadmate and the bullies) or keep walking (the wounded cadet) case "scream": push("scream"); marks[marks.length - 1].at = last(); push(v === "Keep walking" ? "wounded" : "bully"); break; case "clearing": if (v === "Walk away") push("away"); break; case "fate": case "wounded": push("res:" + v); break; case "post": push("fork:" + v); break; case "hour": push("hour"); marks[marks.length - 1].at = last(); push(v === "Tree" ? "tree" : "valley"); break; case "shadow": if (v === "yes") push("stream"); break; case "shadowColour": push(v === "Black" ? "black" : "redwood"); break; case "descend": push(v.startsWith("Quickly") ? "treeRed" : "greens"); break; case "valley": push(v === "Face the Red" ? "valleyRed" : "meadow"); break; case "meadow": push("meadow:" + v); break; default: break; } // a roll is labelled on the segment it leads into (or at the current point when nothing moves) if (s.kind === "chance") rolls.push({ s, at: pts.length > before ? pts.length - 1 : null, P: last().P }); }); return { pts, marks, rolls, endFlow: flow }; } // where each option of a decision leads on the map (for expanded choice points) const optionPlace = (s, v) => ({ company: "comp:" + v, direction: "dir:" + v, post: "fork:" + v, scream: v === "Keep walking" ? "wounded" : "bully", clearing: v === "Walk away" ? "away" : "bully", fate: "res:" + v, wounded: "res:" + v, hour: v === "Tree" ? "tree" : "valley", descend: v.startsWith("Quickly") ? "treeRed" : "greens", valley: v === "Face the Red" ? "valleyRed" : "meadow", }[s.var]); /* ---------- drawing ---------- */ let base = null; // painted valley, cached as markup function paintBase(svg) { if (!base) { const tmp = document.createElementNS(NS, "svg"); V.paintBase(tmp); base = tmp.innerHTML.replace(/vm-/g, "ex-"); } svg.innerHTML = base; } function curve(A, B, bend = 0.08, off = 0) { const dx = B.x - A.x, dy = B.y - A.y, len = Math.hypot(dx, dy) || 1, nx = -dy / len * off, ny = dx / len * off; const a = { x: A.x + nx, y: A.y + ny }, b = { x: B.x + nx, y: B.y + ny }; return `M${a.x} ${a.y} Q${(a.x + b.x) / 2 - dy * bend} ${(a.y + b.y) / 2 + dx * bend} ${b.x} ${b.y}`; } const mid = (A, B, t = 0.5, bend = 0.08) => { const mx = (A.x + B.x) / 2 - (B.y - A.y) * bend, my = (A.y + B.y) / 2 + (B.x - A.x) * bend; return { x: (1 - t) ** 2 * A.x + 2 * (1 - t) * t * mx + t * t * B.x, y: (1 - t) ** 2 * A.y + 2 * (1 - t) * t * my + t * t * B.y }; }; // label text is always dark ink (light dragon colours like Orange are unreadable as text on paper); // the dragon's colour goes on the border instead let pills = []; // every label drawn this render, so overlapping ones can be pushed apart afterwards function pill(g0, x, y, text, { ink = PAPER.ink, edge = null, strong = false, bg = PAPER.halo } = {}) { const w = 10 + text.length * (strong ? 7.2 : 6.4), h = strong ? 20 : 17; const g = el("g", {}, g0); pills.push({ g, x, y, w, h, dy: 0 }); el("rect", { x: x - w / 2, y: y - h / 2, width: w, height: h, rx: h / 2, fill: bg, "fill-opacity": 0.95, stroke: edge || ink, "stroke-opacity": edge ? 0.95 : 0.4, "stroke-width": edge ? 2 : 1 }, g); el("text", { x, y: y + (strong ? 4.5 : 4), "text-anchor": "middle", "font-size": strong ? 12.5 : 11, "font-weight": strong ? 700 : 500, fill: ink, "font-family": "var(--font-data)" }, g).textContent = text; } function drawDragons(g, routesOn) { const maxN = Math.max(1, ...SPOTS.filter((s) => !s.first).map((s) => st.counts[s.place] || 0)); const maxF = Math.max(1, ...SPOTS.filter((s) => s.first).map((s) => st.counts[s.place] || 0)); SPOTS.forEach((sp) => { const P = L[sp.place]; if (!P) return; const n = st.counts[sp.place]; // faint = rarely met, but never so faint it disappears (bonding dragons keep a higher floor) let op = n == null ? 0.85 : (sp.first ? 0.35 : 0.5) + (sp.first ? 0.65 : 0.5) * Math.sqrt(n / (sp.first ? maxF : maxN)); const isTarget = st.colour && !sp.first && (encColour(sp.enc) === st.colour || RESCUE[st.colour] === sp.enc); if (st.colour && !isTarget) op = Math.max(0.3, op * 0.5); // faded, but never lost if (isTarget) op = Math.max(op, 0.9); const w = 200 * sp.sc, hgt = 160 * sp.sc; const x = P.x - w / 2 + (sp.dx || 0), y = P.y - hgt * 0.7 + (sp.dy || 0); const gg = el("g", { class: "ex-dragon", transform: `translate(${x} ${y}) scale(${sp.sc})`, opacity: op.toFixed(2), tabindex: sp.twin ? null : 0, role: sp.twin ? null : "button", "aria-label": sp.first ? `${sp.colour} dragon, first sighting` : `${ENC_NAME[sp.enc]}. Show the routes to it.` }, g); if (isTarget && routesOn) el("ellipse", { cx: 100, cy: 140, rx: 80, ry: 16, fill: INK[sp.colour], "fill-opacity": 0.25 }, gg); // a soft paper-coloured halo keeps dark dragons readable on the dark canopy gg.innerHTML += `${D.svg(sp.pose, { fill: PAPER.halo, eyeFill: PAPER.halo, flip: sp.flip })}`; gg.innerHTML += D.svg(sp.pose, { fill: INK[sp.colour], flip: sp.flip }); el("rect", { x: 0, y: 0, width: 200, height: 160, fill: "transparent" }, gg); if (sp.twin) return; const tipHtml = () => { if (sp.first) return `${sp.colour} dragon
One of the first dragons you can meet here. This is a roll of the dice, not a bonding.${n != null ? `
${n.toLocaleString()} riders met it here` : ""}`; const o = st.policy ? encOutcome(sp.enc) : null; const c = encColour(sp.enc); const bond = o ? (sp.enc === "tree-Greens" ? `Green ${pct(o.Green)}, rescue by Orange ${pct(o.Orange || 0)} or Brown ${pct(o.Brown || 0)}` : pct(o[c])) : "–"; return `${ENC_NAME[sp.enc]}${n != null ? `
${n.toLocaleString()} riders met it here` : ""}
Bond chance when attempted: ${bond}`; }; gg.addEventListener("mouseenter", (e) => showTip(e, tipHtml())); gg.addEventListener("mousemove", (e) => moveTip(e)); gg.addEventListener("mouseleave", hideTip); gg.addEventListener("focus", () => { const r = gg.getBoundingClientRect(); showTip({ clientX: r.right, clientY: r.top }, tipHtml()); }); gg.addEventListener("blur", hideTip); const go = () => { hideTip(); if (sp.first) { st.info = sp; render(); return; } select(encColour(sp.enc) === "Green" && st.colour && RESCUE[st.colour] === sp.enc ? st.colour : encColour(sp.enc), sp.enc); }; gg.addEventListener("click", go); gg.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } }); }); } /* ---------- the people (and the thorn) of the valley ---------- */ const SCENERY = [ { at: "bully", fig: "defender", dx: 6, sc: 0.42, tip: "The bully fight", text: "Your squadmate holds off two cadets who have bullied them since Parapet. Help them, or walk away." }, { at: "bully", fig: "lunging", dx: 30, sc: 0.42, tip: "The bully fight", text: "The bigger cadet swings a sword; the smaller one has a dagger ready to throw." }, { at: "bully", fig: "throwing", dx: 58, sc: 0.42, tip: "The bully fight", text: "Assess first, even the numbers, or put yourself in the middle. Then decide the bullies' fate." }, { at: "wounded", fig: "lying", dx: -72, dy: 4, sc: 0.56, tip: "The wounded cadet", text: "Ignore the scream and you find a badly wounded cadet. Tie a tourniquet, leave them, or take their weapons." }, { at: "hour", fig: "thorns", dx: -66, dy: 6, sc: 0.44, tip: "An hour's walk", text: "No dragon for an hour, and a thorn cuts the back of your hand. Then: climb the tallest tree, or walk on to the valley centre." }, ]; function drawScenery(g, onRoute) { SCENERY.forEach((sc) => { const P = L[sc.at]; if (!P) return; const faded = st.colour && !onRoute.has(sc.at); const x = P.x + (sc.dx || 0) - 50 * sc.sc, y = P.y + (sc.dy || 0) - 136 * sc.sc; const gg = el("g", { class: "ex-scene", transform: `translate(${x} ${y}) scale(${sc.sc})`, opacity: faded ? 0.35 : 0.88 }, g); gg.innerHTML = D.figure(sc.fig, { fill: sc.fig === "thorns" ? "#4a3a22" : PAPER.ink, flip: !!sc.flip }); el("rect", { x: 0, y: 0, width: 100, height: 140, fill: "transparent" }, gg); const html = `${esc(sc.tip)}
${esc(sc.text)}`; gg.addEventListener("mouseenter", (e) => showTip(e, html)); gg.addEventListener("mousemove", (e) => moveTip(e)); gg.addEventListener("mouseleave", hideTip); }); } function drawLandmarks(g, onRoute) { const ids = new Set(LANDMARKS); onRoute.forEach((id) => { if (L[id] && L[id].kind !== "dragon") ids.add(id); }); ids.forEach((id) => { const P = L[id]; if (!P || P.kind === "dragon") return; const strong = onRoute.has(id); el("circle", { cx: P.x, cy: P.y, r: strong ? 6 : 4.5, fill: PAPER.ink, "fill-opacity": strong ? 0.95 : 0.7, stroke: PAPER.halo, "stroke-width": 2 }, g); // small choice points sit close together, so they honour "above" as well as left/right const pos = P.kind === "small" && P.lab === "above" ? "above" : (P.lab || "right") === "left" ? "left" : "right"; const t = el("text", { x: P.x + (pos === "right" ? 10 : pos === "left" ? -10 : 0), y: P.y + (pos === "above" ? -10 : 4), "text-anchor": pos === "right" ? "start" : pos === "left" ? "end" : "middle", "font-family": "var(--font-display)", "font-size": strong ? 14 : 13, fill: PAPER.ink, "fill-opacity": strong ? 1 : 0.8, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g); t.textContent = LANDMARK_NAME[id] || P.name; }); el("text", { x: GATE.x, y: GATE.y + 14, "text-anchor": "middle", "font-size": 11, "letter-spacing": "0.16em", fill: PAPER.ink, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, g).textContent = "ENTER THE VALLEY"; } function drawTraffic(g) { if (!st.runs) return; const edges = new Map(); st.runs.forEach((r) => { const seq = V.path(r); for (let i = 1; i < seq.length; i++) { const k = seq[i - 1] + ">" + seq[i]; edges.set(k, (edges.get(k) || 0) + 1); } }); const max = Math.max(1, ...edges.values()); [...edges.entries()].sort((a, b) => b[1] - a[1]).forEach(([k, n]) => { const [a, b] = k.split(">"); if (!L[a] || !L[b]) return; el("path", { d: curve(L[a], L[b], 0.05), fill: "none", stroke: "#6b4a33", "stroke-opacity": 0.32, "stroke-width": 1.5 + 18 * Math.sqrt(n / max), "stroke-linecap": "round" }, g); }); } function drawRoutes(gRoute, gLab, routes) { const best = Math.max(1e-12, ...routes.map((r) => r.value.x)); const onRoute = new Set(); const tc = INK[st.colour]; // weaker routes first so the best one sits on top [...routes].sort((a, b) => a.value.x - b.value.x).forEach((r) => { const rel = r.value.x / best; const focus = r.enc === st.focus; const dash = rel >= 0.5 ? null : rel >= 0.1 ? "14 9" : "3 9"; const op = (0.3 + 0.65 * rel) * (focus ? 1 : 0.85); const off = (routes.indexOf(r) - (routes.length - 1) / 2) * 7; const { pts, marks } = r.geo; pts.forEach((p) => onRoute.add(p.id)); for (let i = 1; i < pts.length; i++) { const A = pts[i - 1].P, B = pts[i].P, w = 3 + 22 * pts[i].flow; const d = curve(A, B, 0.08, off); if (focus) el("path", { d, fill: "none", stroke: "#fff1c9", "stroke-width": w + 6, "stroke-opacity": 0.55, "stroke-linecap": "round" }, gRoute); el("path", { d, fill: "none", stroke: tc, "stroke-width": w, "stroke-opacity": op, "stroke-linecap": dash ? "butt" : "round", "stroke-dasharray": dash, class: "ex-route" }, gRoute); } // rolls of the dice: the odds where the route narrows (focused route only) if (focus) r.geo.rolls.forEach((ro) => { const p = ro.s.probs[ro.s.taken]; if (p > 0.995) return; // the last roll leads straight into the dragon, whose own label sits there: put the roll under the fork point const at = !ro.at ? { x: ro.P.x + 34, y: ro.P.y - 22 } : ro.at === pts.length - 1 ? { x: pts[ro.at - 1].P.x, y: pts[ro.at - 1].P.y + 24 } : mid(pts[ro.at - 1].P, pts[ro.at].P, 0.38); pill(gLab, at.x, at.y, ro.s.var === "shadow" ? (ro.s.taken === "yes" ? `shadow ${pct(p)}` : `no shadow ${pct(p)}`) : `roll ${pct(p)}`); }); // destination label const end = pts[pts.length - 1]; pill(gLab, end.P.x, end.P.y + 30, `${pct(r.value.x)} per attempt`, { edge: tc, strong: rel === 1 }); // choice points on the focused route if (focus) marks.forEach((m) => { if (!m.at || m.s.var === "encounter") return; const P = m.at.P, open = st.expanded === m.s.var; const g = el("g", { class: "ex-mark", tabindex: 0, role: "button", "aria-label": `${m.s.label}: ${m.s.taken}. Show the other options.`, "aria-expanded": open }, gLab); el("path", { d: `M${P.x} ${P.y - 9} L${P.x + 9} ${P.y} L${P.x} ${P.y + 9} L${P.x - 9} ${P.y} Z`, fill: open ? tc : PAPER.halo, stroke: tc, "stroke-width": 2.5 }, g); el("title", {}, g).textContent = `${m.s.label}: ${m.s.taken} (click for the other options)`; const go = () => { st.expanded = open ? null : m.s.var; render(); }; g.addEventListener("click", go); g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } }); if (open) { const best2 = Math.max(1e-12, ...Object.values(m.s.options).map((v) => v.pX)); Object.entries(m.s.options).forEach(([v, val]) => { const pid = optionPlace(m.s, v); if (!pid || !L[pid] || v === m.s.taken) return; if (L[pid] === P) { // this option stays where you are (e.g. help your squadmate, right here in the clearing) pill(gLab, P.x, P.y - 30, `${v} ${pct(val.pX)}`, { edge: tc }); const hit = pills[pills.length - 1].g; hit.setAttribute("class", "ex-alt"); hit.setAttribute("tabindex", 0); hit.setAttribute("role", "button"); hit.setAttribute("aria-label", `${v}: ${pct(val.pX)}. Take this instead.`); const go = () => choose(m.s.var, v); hit.addEventListener("click", go); hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } }); return; } const B = L[pid], rel2 = val.pX / best2; const p = el("path", { d: curve(P, B, 0.1), fill: "none", stroke: tc, "stroke-width": 2 + 4 * rel2, "stroke-opacity": 0.35 + 0.5 * rel2, "stroke-dasharray": "6 6", "stroke-linecap": "round", class: "ex-alt", tabindex: 0, role: "button", "aria-label": `${v}: ${pct(val.pX)}. Take this instead.` }, gLab); // the option's own place is labelled on the map, so its chance sits just under that place onRoute.add(pid); pill(gLab, B.x, B.y + 17, pct(val.pX)); const pick = () => choose(m.s.var, v); p.addEventListener("click", pick); p.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } }); }); } }); }); return onRoute; } /** Push overlapping labels apart vertically (a few relaxation passes), so no two chances sit on top of each other. */ function spreadPills() { const gap = 3; for (let pass = 0; pass < 30; pass++) { let moved = false; for (let i = 0; i < pills.length; i++) for (let j = i + 1; j < pills.length; j++) { const a = pills[i], b = pills[j]; const ox = Math.min(a.x + a.w / 2, b.x + b.w / 2) - Math.max(a.x - a.w / 2, b.x - b.w / 2); const ay = a.y + a.dy, by = b.y + b.dy; const oy = Math.min(ay + a.h / 2, by + b.h / 2) - Math.max(ay - a.h / 2, by - b.h / 2); if (ox > 0 && oy > -gap) { const push = (oy + gap) / 2, down = by >= ay ? 1 : -1; a.dy -= push * down; b.dy += push * down; moved = true; } } if (!moved) break; } pills.forEach((p) => { if (p.dy) p.g.setAttribute("transform", `translate(0 ${p.dy.toFixed(1)})`); }); } /* ---------- tooltip ---------- */ function showTip(e, html) { const t = $("#ex-tip"); t.innerHTML = html; t.hidden = false; moveTip(e); } function moveTip(e) { const t = $("#ex-tip"), box = $(".ex-map-wrap").getBoundingClientRect(), r = t.getBoundingClientRect(); t.style.left = Math.min(box.width - r.width - 8, Math.max(8, e.clientX - box.left + 14)) + "px"; t.style.top = Math.min(box.height - r.height - 8, Math.max(8, e.clientY - box.top + 14)) + "px"; } const hideTip = () => { const t = $("#ex-tip"); if (t) t.hidden = true; }; /* ---------- panel ---------- */ const mini = (c, pose = "sitting") => ``; const POSE_OF = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" }; const trafficToggle = () => ``; function chooser() { return `
${COLOURS.map((c) => ``).join("")}
`; } function panelIdle() { let info = ""; if (st.info) { const sp = st.info, dir = sp.place.split(":")[1]; const fs = st.policy ? S.makeParams(model().model.tables, { alphas: model().model.alphas }).chance("fs", { direction: dir }) : null; info = `
First sighting · ${dir === "Center" ? "forest centre" : dir.toLowerCase()}

The first dragon is a roll of the dice: nobody bonds here, it decides what you face next.${fs ? ` Going ${dir === "Center" ? "to the forest centre" : dir.toLowerCase()}, riders met: ${Object.entries(fs).sort((a, b) => b[1] - a[1]).filter(([, p]) => p > 0.005).map(([k, p]) => `${k} ${pct(p)}`).join(", ")}.` : ""}

`; } return `Unofficial atlas · built from ${st.runs ? st.runs.length.toLocaleString() : "thousands of"} logged runs

The valley

Every dragon is drawn where riders meet it. The fainter it is, the fewer riders reach it. Choose one to see every way to it, and how likely each is.

${chooser()}${info} ${trafficToggle()}

Prefer the numbers? The Odds has the statistics behind the map.

`; } function panelRoutes(routes) { const best = Math.max(1e-12, ...routes.map((r) => r.value.x)); const T = model().targets[st.colour], b = T[st.objective]; const focus = routes.find((r) => r.enc === st.focus) || routes[0]; const card = (r) => { const rel = r.value.x / best, o = encOutcome(r.enc), c = encColour(r.enc); const n = r.adv.attempts(r.enc); const bond = r.enc === "tree-Greens" && st.colour !== "Green" ? `rescue by ${st.colour}: ${pct(o[st.colour] || 0)}` : `bond chance there: ${pct(o[c])}`; const style = rel >= 0.5 ? "solid" : rel >= 0.1 ? "dashed" : "dotted"; return ``; }; const steps = focus.steps.filter((s) => s.kind === "decision" || s.kind === "chance").map((s) => { if (s.kind === "chance") return `
  • ${esc(s.label)}${esc(String(s.taken))}roll ${pct(s.probs[s.taken])}
  • `; const open = st.expanded === s.var; const opts = open ? `
    ${Object.entries(s.options).sort((a, c) => c[1].pX - a[1].pX).map(([v, val]) => ``).join("")}
    ` : ""; return `
  • ${opts}
  • `; }).join(""); const risks = focus.steps.filter((s) => s.risk && s.risk.p > 0.0005).map((s) => `${s.risk.label.toLowerCase()} ${pct(s.risk.p)}`); const lb = st.policy.samples.lowBias.targets[st.colour].thisAttempt; return `
    ${mini(st.colour, POSE_OF[st.colour])}
    Routes to a

    ${st.colour} dragon

    ${chooser()}
    ${routes.map(card).join("")}

    best route under half as likely under a tenth · line width: chance you are still on the route

    ${esc(ENC_NAME[focus.enc])}: step by step
      ${steps}

    Diamonds on the map are choices: click one to see where the other options lead. Changed your mind?

    Why this route?

    Best route for any ${st.colour}: ${pct(b.pX.mean)} per attempt (95% interval ${pct(b.pX.lo)}–${pct(b.pX.hi)}), about ${isFinite(b.expectedAttempts.mean) ? Math.round(b.expectedAttempts.mean) : "–"} attempts. Riders who logged every run suggest ${pct(lb.pX.mean)}.

    Each roll's odds may depend on your earlier choices, as far as the data support it. Choices marked "no clear winner" in Deep Dive are within the noise.${risks.length ? ` Risks on this route: ${risks.join(", ")}.` : ""}

    The bond chance at each encounter is the community average: the form does not record the answers riders gave there.

    ${trafficToggle()}`; } function bindPanel() { const p = $("#ex-panel"); $$(".ex-dchip", p).forEach((b) => b.addEventListener("click", () => select(b.dataset.c === st.colour ? null : b.dataset.c))); $$(".ex-route-card", p).forEach((b) => b.addEventListener("click", () => { st.focus = b.dataset.enc; st.expanded = null; render(); })); $$(".ex-step", p).forEach((b) => b.addEventListener("click", () => { st.expanded = st.expanded === b.dataset.var ? null : b.dataset.var; render(); })); $$(".ex-opt", p).forEach((b) => b.addEventListener("click", () => choose(b.dataset.var, b.dataset.v))); $$("[data-o]", p).forEach((b) => b.addEventListener("click", () => { st.objective = b.dataset.o; render(); })); $$("[data-s]", p).forEach((b) => b.addEventListener("click", () => { st.sample = b.dataset.s; render(); })); const tr = $("#ex-traffic", p); if (tr) tr.addEventListener("change", () => { st.traffic = tr.checked; render(); }); const cl = $("#ex-clear", p); if (cl) cl.addEventListener("click", () => select(null)); const rr = $("#ex-reset-route", p); if (rr) rr.addEventListener("click", () => { delete st.over[st.focus]; st.expanded = null; render(); }); } /* ---------- actions ---------- */ function select(colour, enc) { st.colour = colour; st.info = null; st.expanded = null; st.focus = colour ? enc || null : null; writeHash(); render(); } function choose(v, val) { const route = walk(st.focus); const order = route.steps.map((s) => s.var); const over = { ...(st.over[st.focus] || {}) }; // keep choices before this one, drop the ones after it const idx = order.indexOf(v); order.slice(idx + 1).forEach((k) => delete over[k]); over[v] = val; st.over[st.focus] = over; render(); } function writeHash() { if (!$("#panel-valley") || $("#panel-valley").hidden) return; const h = "#valley" + (st.colour ? "/" + st.colour.toLowerCase() + (st.focus ? "/" + st.focus : "") : ""); try { history.replaceState(null, "", h); } catch (e) { /* ignore */ } } function fromHash() { const parts = (location.hash || "").replace(/^#/, "").split("/"); if (parts[0] !== "valley") return; const c = parts[1] ? COLOURS.find((x) => x.toLowerCase() === parts[1].toLowerCase()) : null; const enc = parts[2] && c && S.ENCOUNTERS[c].includes(parts[2]) ? parts[2] : null; // plain "#valley" (e.g. the tab itself) keeps whatever the reader was looking at if (!c) { writeHash(); return; } if (!st.policy) { st.pendingHash = { c, enc }; return; } // a link to a dragon opens its most probable route, fresh: no earlier detours, nothing expanded st.colour = c; st.focus = enc; st.expanded = null; st.info = null; delete st.over[enc || ""]; S.ENCOUNTERS[c].forEach((e) => delete st.over[e]); render(); } /* ---------- render ---------- */ function render() { const svg = $("#ex-map"); if (!svg) return; paintBase(svg); el("rect", { x: 0, y: 0, width: 1000, height: 790, fill: "#f6e6c4", "fill-opacity": st.colour ? 0.32 : 0.12 }, svg); const gTraffic = el("g", { filter: "url(#ex-brush)" }, svg); const gRoute = el("g", { filter: "url(#ex-brush)" }, svg); const gLand = el("g", {}, svg), gScene = el("g", {}, svg), gDrag = el("g", {}, svg), gLab = el("g", {}, svg); if (st.traffic) drawTraffic(gTraffic); let routes = [], onRoute = new Set(); if (st.colour && st.policy) { routes = S.ENCOUNTERS[st.colour].map((enc) => { const r = walk(enc); r.geo = routePoints(r); return r; }).sort((a, b) => b.value.x - a.value.x); if (!st.focus || !routes.some((r) => r.enc === st.focus)) st.focus = routes[0].enc; pills = []; onRoute = drawRoutes(gRoute, gLab, routes); spreadPills(); } drawLandmarks(gLand, onRoute); drawScenery(gScene, onRoute); drawDragons(gDrag, !!st.colour); // the paper texture and vignette go on top const fin = document.createElementNS(NS, "svg"); V.finish(fin); svg.insertAdjacentHTML("beforeend", fin.innerHTML.replace(/vm-/g, "ex-")); $("#ex-hint").hidden = !!st.colour || !st.policy; $("#ex-shell").style.setProperty("--vt", st.colour ? `var(${DV[st.colour]})` : "var(--accent)"); // the panel scrolls inside the map's height on wide screens (see .ex-scroll) $("#ex-panel").innerHTML = `
    ${st.colour && st.policy ? panelRoutes(routes) : panelIdle()}
    `; bindPanel(); writeHash(); // on narrow screens the map scrolls sideways: start centred rather than at the far west const wrap = $(".ex-map-wrap"); if (wrap && !wrap.dataset.centred && wrap.scrollWidth > wrap.clientWidth) { wrap.scrollLeft = (wrap.scrollWidth - wrap.clientWidth) / 2; wrap.dataset.centred = "1"; } } function setRuns(state) { st.runs = state.runs; st.counts = {}; state.runs.forEach((r) => V.path(r).forEach((id) => (st.counts[id] = (st.counts[id] || 0) + 1))); render(); } function init() { render(); fetch("data/policy.json").then((r) => r.json()).then((p) => { st.policy = p; if (st.pendingHash) { st.colour = st.pendingHash.c; st.focus = st.pendingHash.enc; st.pendingHash = null; } render(); }).catch(() => { $("#ex-panel").innerHTML = '

    The route model (data/policy.json) could not be loaded.

    '; }); } window.ValleyExplorer = { setRuns, fromHash, state: st, render }; if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init(); })();