Files
threshing-atlas/site/atlas/explorer.js
T

923 lines
61 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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.
* "Show the paths of all riders" adds, underneath, the paths every source logged (one layer each: the sheet's form
* posts and bulk logs, runs reported here, the bot, Discord) and the deaths (deliberate and failed), each layer with
* its own switch; the counts come from data/stats.json `paths` (analysis/stats/site_stats.py). 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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[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: "roaring", flip: true, sc: 0.36 },
{ place: "greens", enc: "tree-Greens", colour: "Green", pose: "prowling", sc: 0.3, dx: -16 },
{ place: "greens", enc: "tree-Greens", colour: "Green", pose: "prowling", flip: true, sc: 0.27, dx: 20, dy: -4, twin: true },
{ place: "black", enc: "shadow-Black", colour: "Black", pose: "resting", 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: "flying", flip: true, sc: 0.3 },
{ place: "meadow:Brown", enc: "meadow-Brown", colour: "Brown", pose: "sitting", sc: 0.32 },
{ place: "meadow:Blue", enc: "meadow-Blue", colour: "Blue", pose: "coiled", 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 });
});
// Progressive disclosure: the idle map shows only the key moments. Clicking one reveals the choices made there
// (and the best route to every dragon from it); a picked dragon shows only its path and the choices taken on it.
const KEY = ["dir:West", "dir:Center", "dir:East", "scream", "bully", "wounded", "hour", "tree", "valley", "meadow", "stream"];
const FATES = ["res:Killed the bullies yourself", "res:Squadmate's revenge", "res:Left bullies to the dragons"];
const FORKS = ["fork:West", "fork:Forest", "fork:East"];
const CHILDREN = {
gate: ["comp:Alone", "comp:1 Squadmate", "comp:2 Squadmates"],
bully: ["away"].concat(FATES),
wounded: ["res:Tourniquet", "res:Left injured cadet", "res:Took their weapons"],
...Object.fromEntries(FATES.map((f) => [f, FORKS])),
};
const PARENT = {};
for (const [p, kids] of Object.entries(CHILDREN)) kids.forEach((k) => { if (!PARENT[k]) PARENT[k] = p; });
/** Places drawn on the idle map: the key moments, plus the choices at (and around) the place you picked. */
function visiblePlaces() {
const ids = new Set(KEY);
let p = st.point;
if (p) {
ids.add(p);
(CHILDREN[p] || []).forEach((k) => ids.add(k));
// the way here: each earlier choice point with its alternatives, so you can switch
for (let q = PARENT[p]; q; q = PARENT[q]) { ids.add(q); (CHILDREN[q] || []).forEach((k) => ids.add(k)); }
}
return ids;
}
const LANDMARK_NAME = { gate: "The entrance", "dir:West": "West, toward the scent", "dir:Center": "Forest centre", "dir:East": "East, toward the roar", "fork:Forest": "The fork" };
/* ---------- state ---------- */
const st = {
point: null, // a place picked before any dragon: show the best way from there to every dragon
policy: null, runs: null, counts: {}, colour: null, focus: null, expanded: null, over: {},
objective: "eventually", sample: "all", traffic: false, layers: {}, paths: null, cache: new Map(), pendingHash: null, info: null,
};
const model = () => st.policy.samples[st.sample];
function advisorFor(enc, colour = st.colour) {
const k = `${st.sample}|${colour}|${st.objective}|${enc}`;
if (!st.cache.has(k)) st.cache.set(k, S.advisor(model(), 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);
};
/* ---------- starting from a place ---------- */
// What being at a place means: the choices (and, for the shadow, the roll) that put you there, and the step you
// face next ("at"). Choices before it that are not listed stay free, and the best play is assumed for them.
const INV = "Investigate the scream", HELPC = "Help your squadmate";
const POINTS = {
gate: { force: {}, at: "company" },
"comp:Alone": { force: { company: "Alone" }, at: "direction" },
"comp:1 Squadmate": { force: { company: "1 Squadmate" }, at: "direction" },
"comp:2 Squadmates": { force: { company: "2 Squadmates" }, at: "direction" },
"dir:West": { force: { direction: "West" }, at: "fs" },
"dir:Center": { force: { direction: "Center" }, at: "fs" },
"dir:East": { force: { direction: "East" }, at: "fs" },
scream: { force: {}, at: "scream" },
bully: { force: { scream: INV, clearing: HELPC }, at: "fight", note: "You stepped in to help your squadmate. Each dragon's chance assumes your best first move in the fight (pause to assess) and includes the risk of being killed there; charging straight in kills about a third of riders. Walking away instead leads to the hour's walk." },
wounded: { force: { scream: "Keep walking" }, at: "wounded" },
away: { force: { scream: INV, clearing: "Walk away" }, at: "hour" },
"res:Killed the bullies yourself": { force: { scream: INV, clearing: HELPC, fate: "Killed the bullies yourself" }, at: "post" },
"res:Squadmate's revenge": { force: { scream: INV, clearing: HELPC, fate: "Squadmate's revenge" }, at: "post" },
"res:Left bullies to the dragons": { force: { scream: INV, clearing: HELPC, fate: "Left bullies to the dragons" }, at: "post" },
"res:Tourniquet": { force: { scream: "Keep walking", wounded: "Tourniquet" }, at: "hour" },
"res:Left injured cadet": { force: { scream: "Keep walking", wounded: "Left injured cadet" }, at: "hour" },
"res:Took their weapons": { force: { scream: "Keep walking", wounded: "Took their weapons" }, at: "hour" },
"fork:West": { force: { scream: INV, clearing: HELPC, post: "West" }, at: "hour" },
"fork:Forest": { force: { scream: INV, clearing: HELPC, post: "Forest" }, at: "hour" },
"fork:East": { force: { scream: INV, clearing: HELPC, post: "East" }, at: "hour" },
hour: { force: {}, at: "hour" },
tree: { force: { hour: "Tree" }, at: "shadow" },
valley: { force: { hour: "Valley" }, at: "valley" },
stream: { force: { hour: "Tree", shadow: "yes" }, at: "shadowColour" },
meadow: { force: { hour: "Valley", valley: "Pass the Red (meadow)" }, at: "meadow" },
};
/**
* Chance of bonding the advisor's colour once you are at a place: everything before it that the place implies is
* fixed, earlier rolls are averaged over the ways of getting there, and from there on the best play is used.
* Returns null when the place cannot lead to that dragon.
*/
function valueFrom(adv, pt) {
const rec = (h, reached) => {
const s = adv.step(h);
if (s.kind === "end") return { x: 0, w: reached ? 1 : 0 };
const live = reached && s.risk ? 1 - s.risk.p : 1;
const atPoint = !reached && s.var === pt.at && Object.keys(pt.force).every((k) => h[k] != null || k === pt.at);
const live2 = atPoint && pt.risk && s.risk ? 1 - s.risk.p : live;
if (reached || atPoint) {
if (s.kind === "decision") return { x: live2 * Math.max(...Object.values(s.options).map((v) => v.pX)), w: 1 };
let x = 0;
for (const [b, p] of Object.entries(s.probs)) if (p) x += p * rec({ ...h, [s.var]: b }, true).x;
return { x: live2 * x, w: 1 };
}
const forced = pt.force[s.var];
if (s.kind === "decision") {
const o = forced != null ? forced : s.choice;
if (!s.options[o]) return { x: 0, w: 0 };
const r = rec({ ...h, [s.var]: o }, false);
return { x: r.x, w: r.w * (s.risk ? 1 - s.risk.p : 1) };
}
// a roll before the place: only branches that can still get there count
let xw = 0, w = 0;
for (const [b, p] of Object.entries(s.probs)) {
if (!p || (forced != null && b !== forced)) continue;
const r = rec({ ...h, [s.var]: b }, false);
xw += p * r.w * r.x; w += p * r.w;
}
return { x: w ? xw / w : 0, w: w * (s.risk ? 1 - s.risk.p : 1) };
};
const r = rec({}, false);
return r.w > 1e-9 ? r.x : null;
}
/** For a picked place: per colour, the encounter with the best chance from there, and its route. */
function routesFrom(id) {
const pt = POINTS[id];
return COLOURS.map((c) => {
let best = null;
// the Greens rescue only counts for Orange/Brown when their own meadow is out of reach from here
const encs = S.ENCOUNTERS[c].filter((e) => RESCUE[c] !== e || c === "Green");
for (const pass of [encs, S.ENCOUNTERS[c].filter((e) => !encs.includes(e))]) {
for (const enc of pass) {
const v = valueFrom(advisorFor(enc, c), pt);
if (v != null && v > 0 && (!best || v > best.v)) best = { enc, v };
}
if (best) break;
}
if (!best) return { colour: c, v: null };
const r = walk(best.enc, c, pt.force);
r.geo = routePoints(r);
return { colour: c, enc: best.enc, v: best.v, route: r };
}).sort((a, b) => (b.v || 0) - (a.v || 0));
}
/* ---------- 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, colour = st.colour, over = st.over[colour] || {}) {
const adv = advisorFor(enc, colour), 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;
}
const end = steps[steps.length - 1];
// a route your choices can no longer reach (e.g. you chose the tree, so the meadow is out)
const reachable = end.kind === "end" && end.encounter === enc && end.action !== "Die on purpose";
return { enc, adv, steps, reachable, 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 "leave": case "react": break; // made where you stand (the start, the first dragon)
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 "red": if (!v.startsWith("Jump")) push("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",
fight: "bully", dagger: "bully", leave: null, react: null,
red: v.startsWith("Jump") ? "treeRed" : "greens",
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 += `<g stroke="${PAPER.halo}" stroke-width="9" stroke-linejoin="round" opacity="0.55">${D.svg(sp.pose, { fill: PAPER.halo, eyeFill: PAPER.halo, flip: sp.flip, lines: false })}</g>`;
gg.innerHTML += D.svg(sp.pose, sp.colour === "Black" ? { dark: true, outline: "#3a2a44", flip: sp.flip } : { fill: INK[sp.colour], flip: sp.flip, lineOpacity: 0.5, outline: "#1b0811", outlineOpacity: 0.55, outlineWidth: 1.1 });
el("rect", { x: 0, y: 0, width: 200, height: 160, fill: "transparent" }, gg);
if (sp.twin) return;
const tipHtml = () => {
if (sp.first) return `<b>${sp.colour} dragon</b><br>One of the first dragons you can meet here. This is a roll of the dice, not a bonding.${n != null ? `<br>${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 `<b>${ENC_NAME[sp.enc]}</b>${n != null ? `<br>${n.toLocaleString()} riders met it here` : ""}<br>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: -150, dy: 62, 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: -126, dy: 62, 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: -98, dy: 62, sc: 0.42, tip: "The bully fight", text: "Pause to assess, charge the smaller cadet, or get between your squadmate and the bigger one. After pausing, the smaller cadet's dagger. Then 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 = `<b>${esc(sc.tip)}</b><br>${esc(sc.text)}`;
gg.addEventListener("mouseenter", (e) => showTip(e, html));
gg.addEventListener("mousemove", (e) => moveTip(e));
gg.addEventListener("mouseleave", hideTip);
});
}
function drawLandmarks(g, onRoute) {
// with a dragon picked: only the places on its routes (opened choices add theirs)
const ids = st.colour ? new Set() : visiblePlaces();
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;
// before a dragon is chosen, any place can be a starting point: "from here, how do I reach each dragon?"
if (!st.colour && POINTS[id] && st.policy) {
if (st.point === id) el("circle", { cx: P.x, cy: P.y, r: 11, fill: "none", stroke: PAPER.ink, "stroke-width": 2.5 }, g);
const hit = el("g", { class: "ex-place", tabindex: 0, role: "button", "aria-label": `${t.textContent}: show the best way from here to every dragon` }, g);
el("circle", { cx: P.x, cy: P.y, r: 14, fill: "transparent" }, hit);
hit.appendChild(t);
el("title", {}, hit).textContent = `${t.textContent}: from here to every dragon`;
const go = () => { st.point = st.point === id ? null : id; st.info = null; writeHash(); render(); };
hit.addEventListener("click", go);
hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
}
});
const gt = 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);
gt.textContent = "ENTER THE VALLEY";
if (!st.colour && st.policy) {
// the entrance is a key moment too: who you go in with
const hit = el("g", { class: "ex-place", tabindex: 0, role: "button", "aria-label": "The entrance: who you enter with, and the best way to every dragon" }, g);
el("rect", { x: GATE.x - 70, y: GATE.y - 2, width: 140, height: 22, fill: "transparent" }, hit);
hit.appendChild(gt);
el("title", {}, hit).textContent = "The entrance: who you enter with";
const go = () => { st.point = st.point === "gate" ? null : "gate"; st.info = null; writeHash(); render(); };
hit.addEventListener("click", go);
hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
}
}
// "Show the paths of all riders": one ink per source layer (data/stats.json paths.layers; measures.yaml path_layers),
// and one line style per way the runs ended
const LAYER_INK = { sheet: "#6b4a33", reported: "#7a4f8f", reddit: "#a8792a", bot: "#28588a", discord: "#5865f2" };
const KIND = {
lived: { dash: null, cap: "round", label: "survived" },
chose: { dash: "11 6", cap: "butt", label: "chose to die" },
failed: { dash: "0.1 6", cap: "round", label: "died (failed run)" },
};
const layerOn = (k) => st.layers[k] !== false; // every layer starts on
function drawTraffic(g) {
if (st.paths && st.paths.layers) return drawLayers(g, st.paths.layers);
// older stats.json: how many logged runs went from each place to the next (precomputed in data/stats.json)
if (!st.edges) return;
const max = Math.max(1, ...st.edges.map((e) => e[2]));
st.edges.forEach(([a, b, n]) => {
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);
});
}
/** Every source layer that is switched on, side by side in its own ink: solid for runs that survived, dashed for
* deliberate deaths, dotted for failed runs, and a mark where the deaths happened. */
function drawLayers(g, layers) {
const shown = layers.filter((l) => l.runs && layerOn(l.key) && l.lines);
const all = shown.flatMap((l) => Object.values(l.lines).flatMap((es) => es.map((e) => e[2])));
const max = Math.max(1, ...all);
shown.forEach((l, i) => {
const base = (i - (shown.length - 1) / 2) * 9, ink = LAYER_INK[l.key] || "#6b4a33";
["lived", "chose", "failed"].forEach((k, j) => {
const off = base + (j - 1) * 3, kd = KIND[k];
(l.lines[k] || []).forEach(([a, b, n]) => {
if (!L[a] || !L[b]) return;
const w = 1.2 + 14 * Math.sqrt(n / max);
el("path", { d: curve(L[a], L[b], 0.05, off), fill: "none", stroke: ink, "stroke-opacity": k === "lived" ? 0.36 : 0.6,
"stroke-width": k === "failed" ? Math.max(2.2, w) : w, "stroke-linecap": kd.cap, "stroke-dasharray": kd.dash }, g);
});
});
// where the deaths happened: one mark per place, sized by the deaths there
const ends = {};
["chose", "failed"].forEach((k) => Object.entries((l.ends || {})[k] || {}).forEach(([p, n]) => (ends[p] = (ends[p] || 0) + n)));
const emax = Math.max(1, ...Object.values(ends));
Object.entries(ends).forEach(([p, n]) => {
if (!L[p]) return;
const r = 2.5 + 9 * Math.sqrt(n / emax), x = L[p].x + base, y = L[p].y;
el("path", { d: `M${x - r * 0.6},${y - r * 0.6}L${x + r * 0.6},${y + r * 0.6}M${x + r * 0.6},${y - r * 0.6}L${x - r * 0.6},${y + r * 0.6}`, stroke: ink, "stroke-width": 2, "stroke-opacity": 0.8 }, 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];
const cards = [];
// 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: one diamond per place, even when several choices are made there
// (at the bully fight: help or walk away, your first move, the dagger, then the bullies' fate)
if (focus) {
const groups = [];
marks.forEach((m) => {
if (!m.at || m.s.var === "encounter") return;
const g0 = groups.find((x) => x.at.id === m.at.id);
if (g0) g0.list.push(m); else groups.push({ at: m.at, list: [m] });
});
groups.forEach((grp) => {
const P = grp.at.P, vars = grp.list.map((m) => m.s.var), open = vars.includes(st.expanded);
const label = grp.list.map((m) => `${m.s.label}: ${m.s.taken}`).join("; ");
const g = el("g", { class: "ex-mark", tabindex: 0, role: "button", "aria-label": `${label}. 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);
if (grp.list.length > 1) {
const t = el("text", { x: P.x + 11, y: P.y - 8, "font-size": 10, "font-weight": 700, fill: tc, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3, "font-family": "var(--font-data)" }, g);
t.textContent = grp.list.length;
}
el("title", {}, g).textContent = `${label} (click for the other options)`;
const go = () => { st.expanded = open ? null : vars[0]; render(); };
g.addEventListener("click", go);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
if (!open) return;
const rows = [];
grp.list.forEach((m) => {
const opts = Object.entries(m.s.options);
const best2 = Math.max(1e-12, ...opts.map(([, v]) => v.pX));
// a choice made right here (no other place to point at) is listed in a small card
const here = opts.some(([v]) => { const pid = optionPlace(m.s, v); return !pid || !L[pid] || L[pid] === P; });
if (here) { rows.push(m); return; }
opts.forEach(([v, val]) => {
const pid = optionPlace(m.s, v);
if (!pid || !L[pid] || v === m.s.taken) return;
const B = L[pid], rel2 = val.pX / best2;
const pth = 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);
pth.addEventListener("click", pick);
pth.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } });
});
});
if (rows.length) cards.push({ P, rows, tc });
});
}
});
cards.forEach((c) => drawCard(gLab, c));
return onRoute;
}
// short names for the choice card (the panel keeps the full ones)
const SHORT = {
"Help your squadmate": "Help them", "Walk away": "Walk away",
"Pause to assess": "Pause to assess", "Charge the smaller cadet": "Charge the smaller one",
"Charge between the bigger cadet and your squadmate": "Get between them",
"Engage the smaller cadet": "Engage the smaller one", "Charge the bigger cadet anyway": "Charge the bigger one",
};
const CAPTION = { leave: "Your squadmates", react: "When the first dragon appears", clearing: "Your squadmate vs two bullies", fight: "Your first move", dagger: "The smaller cadet has a dagger" };
/**
* The choices made at one place, in the game's order, as a small card beside it: one row per choice, every
* option with its chance (the one on this route is filled). Clicking an option takes it instead.
*/
function drawCard(g0, { P, rows, tc }) {
const W = 300, pad = 10, gap = 6, rowH = 22, capH = 15;
const lay = rows.map((m) => {
const items = [];
let x = 0, y = 0;
Object.entries(m.s.options).forEach(([v, val]) => {
const text = `${SHORT[v] || v} ${pct(val.pX)}`, w = 14 + text.length * 6.3;
if (x && x + w > W - 2 * pad) { x = 0; y += rowH; }
items.push({ v, val, text, w, x, y }); x += w + gap;
});
return { m, items, h: capH + y + rowH };
});
const H = pad + lay.reduce((a, r) => a + r.h + 6, 0) + pad - 6;
let x0 = P.x + 22, y0 = P.y - H / 2;
if (x0 + W > 992) x0 = P.x - 22 - W;
y0 = Math.max(8, Math.min(782 - H, y0));
const g = el("g", { class: "ex-card-map" }, g0);
el("rect", { x: x0, y: y0, width: W, height: H, rx: 10, fill: PAPER.halo, "fill-opacity": 0.97, stroke: tc, "stroke-width": 2 }, g);
let y = y0 + pad;
lay.forEach(({ m, items, h }) => {
el("text", { x: x0 + pad, y: y + 10, "font-size": 10.5, "font-weight": 700, "letter-spacing": ".06em", fill: PAPER.ink, "fill-opacity": 0.75, "font-family": "var(--font-data)" }, g)
.textContent = (CAPTION[m.s.var] || m.s.label).toUpperCase();
items.forEach((it) => {
const on = it.v === m.s.taken, bx = x0 + pad + it.x, by = y + capH + it.y;
const b = el("g", { class: "ex-alt", tabindex: 0, role: "button", "aria-pressed": on, "aria-label": `${m.s.label}: ${it.v}, ${pct(it.val.pX)}${on ? " (on this route)" : ". Take this instead."}` }, g);
el("rect", { x: bx, y: by, width: it.w, height: 18, rx: 9, fill: on ? tc : PAPER.halo, stroke: tc, "stroke-width": 1.5 }, b);
el("text", { x: bx + it.w / 2, y: by + 13, "text-anchor": "middle", "font-size": 11, "font-weight": on ? 700 : 500, fill: on ? "#fff" : PAPER.ink, "font-family": "var(--font-data)" }, b).textContent = it.text;
el("title", {}, b).textContent = it.v;
if (!on) {
const pick = () => choose(m.s.var, it.v);
b.addEventListener("click", pick);
b.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } });
}
});
y += h + 6;
});
}
/** 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)})`); });
}
/** All six dragons from one place: the way there in ink, then one line per dragon in its colour. */
function drawFrom(gRoute, gLab, list) {
const onRoute = new Set([st.point]);
const ok = list.filter((x) => x.route);
if (!ok.length) return onRoute;
const best = Math.max(1e-12, ...ok.map((x) => x.v));
// the way to the place (from the most likely dragon's route)
const lead = ok[0].route.geo.pts;
const at = lead.findIndex((p) => p.id === st.point);
for (let i = 1; i <= at; i++) {
el("path", { d: curve(lead[i - 1].P, lead[i].P, 0.08), fill: "none", stroke: PAPER.ink, "stroke-width": 4, "stroke-opacity": 0.55, "stroke-dasharray": "2 8", "stroke-linecap": "round" }, gRoute);
onRoute.add(lead[i].id);
}
[...ok].reverse().forEach((x, k) => {
const pts = x.route.geo.pts, i0 = pts.findIndex((p) => p.id === st.point);
if (i0 < 0) return;
const f0 = pts[i0].flow || 1, rel = x.v / best, off = (COLOURS.indexOf(x.colour) - 2.5) * 5;
for (let i = i0 + 1; i < pts.length; i++) {
const w = 2.5 + 12 * Math.min(1, pts[i].flow / f0);
el("path", { d: curve(pts[i - 1].P, pts[i].P, 0.08, off), fill: "none", stroke: INK[x.colour], "stroke-width": w, "stroke-opacity": 0.45 + 0.45 * rel, "stroke-linecap": "round" }, gRoute);
onRoute.add(pts[i].id);
}
const end = pts[pts.length - 1];
pill(gLab, end.P.x, end.P.y + 30, `${x.colour} ${pct(x.v)}`, { edge: INK[x.colour], strong: rel === 1 });
});
return onRoute;
}
/* ---------- 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") => `<svg viewBox="0 0 200 160" aria-hidden="true">${D.svg(pose, { fill: `var(${DV[c]})`, eyeFill: "var(--bg)", dark: c === "Black" })}</svg>`;
const POSE_OF = { Red: "roaring", Orange: "flying", Brown: "sitting", Green: "prowling", Blue: "coiled", Black: "resting" };
const UNROUTED = { "reddit thread": "Reddit result pages", register: "the Dragon Register" };
function trafficToggle() {
const box = `<label class="ex-toggle"><input type="checkbox" id="ex-traffic"${st.traffic ? " checked" : ""}> Show the paths of all riders</label>`;
if (!st.traffic || !st.paths || !st.paths.layers || !st.paths.layers.some((l) => l.lines)) return box;
const rows = st.paths.layers.map((l) => `<label class="ex-layer${l.runs ? "" : " none"}"><input type="checkbox" data-layer="${esc(l.key)}"${l.runs && layerOn(l.key) ? " checked" : ""}${l.runs ? "" : " disabled"}>
<span class="sw" style="--sw: ${LAYER_INK[l.key] || "#6b4a33"}"></span><span>${esc(l.label)}</span><span class="n">${l.runs ? l.runs.toLocaleString() : "none yet"}</span></label>`).join("");
const key = Object.values(KIND).map((kd) => `<span class="ex-kind"><svg viewBox="0 0 34 8" aria-hidden="true"><path d="M3 4H31" stroke="currentColor" stroke-width="2.6" stroke-linecap="${kd.cap}"${kd.dash ? ` stroke-dasharray="${kd.dash === "11 6" ? "8 4" : "0.1 5"}"` : ""}/></svg>${kd.label}</span>`).join("");
const un = Object.entries(st.paths.unrouted || {}).filter(([, n]) => n).map(([s, n]) => `${n.toLocaleString()} from ${esc(UNROUTED[s] || s)}`);
return `${box}<div class="ex-layers" role="group" aria-label="Which riders' paths to show">${rows}
<div class="ex-kinds">${key}</div>
<p class="small muted">Each source in its own colour; line width is how many runs took each step, and ✕ marks where runs died.${un.length ? ` Not drawn (they record the dragon, not the route): ${un.join(", ")}.` : ""}</p></div>`;
}
function chooser() {
return `<div class="ex-choose">${COLOURS.map((c) => `<button type="button" class="ex-dchip" data-c="${c}" aria-pressed="${st.colour === c}" style="--c: var(${DV[c]})">${mini(c, POSE_OF[c])}<span>${c}</span></button>`).join("")}</div>`;
}
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 = `<div class="ex-card"><span class="eyebrow">First sighting · ${dir === "Center" ? "forest centre" : dir.toLowerCase()}</span>
<p class="small">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(", ")}.` : ""}</p></div>`;
}
return `<span class="eyebrow">Unofficial atlas · built from ${st.nRuns ? st.nRuns.toLocaleString() : "thousands of"} logged runs</span>
<h2 id="h-valley">The valley</h2>
<p class="small muted">Every dragon is drawn where riders meet it. The fainter it is, the fewer riders reach it. Choose one to see its best route and the choices on it. Or click a key moment on the map, including the entrance, to see the choices you make there and your best chance at each dragon from it.</p>
${chooser()}${info}
${trafficToggle()}
<p class="small muted">Prefer the numbers? <a href="#odds">The Odds</a> has the statistics behind the map.</p>`;
}
const placeName = (id) => LANDMARK_NAME[id] || (L[id] && L[id].name) || id;
/** The choices made at the picked place, each a further place to start from, and the way back up. */
function choicesHere() {
const kids = (CHILDREN[st.point] || []).filter((k) => POINTS[k]);
const up = PARENT[st.point];
if (!kids.length && !up) return "";
return `<div class="ex-here">${kids.length ? `<span class="eyebrow">Your choices here</span>
<div class="ex-here-row">${kids.map((k) => `<button type="button" class="ex-chip" data-pt="${esc(k)}">${esc((L[k] && L[k].name) || placeName(k))}</button>`).join("")}</div>` : ""}
${up ? `<button type="button" class="linklike" data-pt="${esc(up)}">← Back to ${esc(placeName(up).toLowerCase())}</button>` : ""}</div>`;
}
function panelFrom(list) {
const name = LANDMARK_NAME[st.point] || (L[st.point] && L[st.point].name) || st.point;
const top = Math.max(1e-12, ...list.map((x) => x.v || 0));
const rows = list.map((x) => x.v == null
? `<div class="ex-from-row off" style="--c: var(${DV[x.colour]})">${mini(x.colour, POSE_OF[x.colour])}<span class="nm">${x.colour}</span><small>not reachable from here</small></div>`
: `<button type="button" class="ex-from-row" data-c="${x.colour}" data-enc="${x.enc}" style="--c: var(${DV[x.colour]}); --w: ${(100 * x.v / top).toFixed(1)}%">${mini(x.colour, POSE_OF[x.colour])}
<span class="nm">${x.colour}<small>${esc(ENC_NAME[x.enc])}${RESCUE[x.colour] === x.enc && x.colour !== "Green" ? " (rescue)" : ""}</small></span><b>${pct(x.v)}</b><i></i></button>`).join("");
return `<div class="ex-head"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="5" fill="var(--accent)"/><circle cx="12" cy="12" r="10" fill="none" stroke="var(--accent)" stroke-width="2"/></svg>
<div><span class="eyebrow">Starting from</span><h2 id="h-valley">${esc(name)}</h2></div>
<button type="button" class="ex-close" id="ex-clear-point" aria-label="Back to the whole valley">×</button></div>
${POINTS[st.point].note ? `<p class="small">${esc(POINTS[st.point].note)}</p>` : ""}
<p class="small muted">From here, this is your best chance of bonding each dragon from here on, playing the best route after this point. Earlier rolls are averaged over the ways of getting here. Pick a dragon to follow its route step by step.</p>
${choicesHere()}
<div class="ex-from">${rows}</div>
<div class="seg" role="group" aria-label="Goal"><button type="button" data-o="eventually" aria-pressed="${st.objective === "eventually"}">Only this dragon</button><button type="button" data-o="thisAttempt" aria-pressed="${st.objective === "thisAttempt"}">Best odds this run</button></div>
${trafficToggle()}`;
}
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 `<button type="button" class="ex-route-card${r.enc === focus.enc ? " on" : ""}" data-enc="${r.enc}" aria-pressed="${r.enc === focus.enc}">
<i class="ex-swatch ${style}" style="--c: var(${DV[st.colour]}); opacity:${(0.3 + 0.7 * rel).toFixed(2)}"></i>
<span class="nm">${esc(ENC_NAME[r.enc])}${RESCUE[st.colour] === r.enc && st.colour !== "Green" ? " <em>(rescue)</em>" : ""}</span>
<b>${pct(r.value.x)}</b><small>per attempt · ${bond}${n < 30 ? ` · only ${n} attempts logged` : ""}${r.value.o > 0.005 ? ` · ends on another dragon ${pct(r.value.o)}` : ""}</small></button>`;
};
const steps = focus.steps.filter((s) => s.kind === "decision" || s.kind === "chance").map((s) => {
if (s.kind === "chance") return `<li class="chance"><span>${esc(s.label)}</span><b>${esc(String(s.taken))}</b><small>roll ${pct(s.probs[s.taken])}</small></li>`;
const open = st.expanded === s.var;
const opts = open ? `<div class="ex-opts">${Object.entries(s.options).sort((a, c) => c[1].pX - a[1].pX).map(([v, val]) =>
`<button type="button" class="ex-opt${v === s.taken ? " on" : ""}" data-var="${s.var}" data-v="${esc(v)}"><span>${esc(v)}${v === s.choice ? ' <em class="rec">best</em>' : ""}</span><b>${pct(val.pX)}</b></button>`).join("")}</div>` : "";
return `<li class="dec${open ? " open" : ""}"><button type="button" class="ex-step" data-var="${s.var}" aria-expanded="${open}"><span>${esc(s.label)}</span><b>${esc(String(s.taken))}</b><small>${s.userSet ? "your choice" : "best"} · ${s.var === "encounter" ? pct(s.options[s.taken].pX) : pct(s.options[s.taken].pX)}</small></button>${opts}</li>`;
}).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 `<div class="ex-head" style="--c: var(${DV[st.colour]})">${mini(st.colour, POSE_OF[st.colour])}<div><span class="eyebrow">Routes to a</span><h2 id="h-valley">${st.colour} dragon</h2></div>
<button type="button" class="ex-close" id="ex-clear" aria-label="Back to the whole valley">×</button></div>
${chooser()}
<div class="seg" role="group" aria-label="Goal"><button type="button" data-o="eventually" aria-pressed="${st.objective === "eventually"}" title="Die on purpose and try again whenever it goes wrong; never risk ending on another dragon">Only this dragon</button><button type="button" data-o="thisAttempt" aria-pressed="${st.objective === "thisAttempt"}" title="Best chance on this one run">Best odds this run</button></div>
${st.blocked ? `<p class="small ex-warn">Your choices so far can't reach a ${st.colour} dragon. <button type="button" class="linklike" id="ex-reset-route">Reset your choices</button></p>` : ""}
<div class="ex-routes">${routes.map(card).join("")}</div>
<p class="small muted ex-key"><span class="solid"></span> best route <span class="dashed"></span> under half as likely <span class="dotted"></span> under a tenth · line width: chance you are still on the route</p>
<span class="eyebrow">${esc(ENC_NAME[focus.enc])}: step by step</span>
<ol class="ex-steps">${steps}</ol>
<p class="small muted">Diamonds on the map are choices: click one to see where the other options lead. ${st.blocked ? "" : `Your choices apply to every route to this dragon. Changed your mind? <button type="button" class="linklike" id="ex-reset-route">Reset your choices</button>`}</p>
<details class="ex-why"><summary>Why this route?</summary>
<p class="small">Best route for any ${st.colour}: <b>${pct(b.pX.mean)}</b> 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)}.</p>
<p class="small">Each roll's odds may depend on your earlier choices, as far as the data support it. Choices marked "no clear winner" in <a href="#deep">Deep Dive</a> are within the noise.${risks.length ? ` Risks on this route: ${risks.join(", ")}.` : ""}</p>
<p class="small">The bond chance at each encounter is the community average: the form does not record the answers riders gave there.</p>
<div class="seg" role="group" aria-label="Data"><button type="button" data-s="all" aria-pressed="${st.sample === "all"}">All runs</button><button type="button" data-s="lowBias" aria-pressed="${st.sample === "lowBias"}">Low-bias</button></div>
</details>
${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(); });
$$("[data-layer]", p).forEach((b) => b.addEventListener("change", () => { st.layers[b.dataset.layer] = b.checked; render(); }));
const cl = $("#ex-clear", p); if (cl) cl.addEventListener("click", () => select(null));
$$("[data-pt]", p).forEach((b) => b.addEventListener("click", () => { st.point = b.dataset.pt; writeHash(); render(); }));
const cp = $("#ex-clear-point", p); if (cp) cp.addEventListener("click", () => { st.point = null; writeHash(); render(); });
$$(".ex-from-row[data-c]", p).forEach((b) => b.addEventListener("click", () => {
// follow that dragon's route, keeping this place on it
st.over[b.dataset.c] = { ...POINTS[st.point].force };
select(b.dataset.c, b.dataset.enc);
}));
const rr = $("#ex-reset-route", p); if (rr) rr.addEventListener("click", () => { delete st.over[st.colour]; st.expanded = null; render(); });
}
/* ---------- actions ---------- */
function select(colour, enc) {
st.colour = colour; st.info = null; st.expanded = null;
if (colour) st.point = 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.colour] || {}) };
// keep choices before this one, drop the ones after it
const idx = order.indexOf(v);
order.slice(idx + 1).forEach((k) => delete over[k]);
// the path up to here is the one you are looking at: keep its earlier choices too, so switching to another
// route to this dragon (e.g. the tree instead of the valley) never changes where you have already been
route.steps.slice(0, Math.max(0, idx)).forEach((s) => { if (s.kind === "decision" && over[s.var] == null) over[s.var] = s.taken; });
over[v] = val;
// your choices hold for every route to this dragon: a later choice never sends the route back through another place
st.over[st.colour] = over;
st.expanded = null;
render();
}
function writeHash() {
if (!$("#panel-valley") || $("#panel-valley").hidden) return;
const h = "#valley" + (st.colour ? "/" + st.colour.toLowerCase() + (st.focus ? "/" + st.focus : "")
: st.point ? "/at/" + encodeURIComponent(st.point) : "");
try { history.replaceState(null, "", h); } catch (e) { /* ignore */ }
}
function fromHash() {
const parts = (location.hash || "").replace(/^#/, "").split("/");
if (parts[0] !== "valley") return;
if (parts[1] === "at") {
const id = decodeURIComponent(parts.slice(2).join("/"));
if (POINTS[id]) { st.colour = null; st.focus = null; st.point = id; if (st.policy) render(); }
return;
}
const c = parts[1] ? COLOURS.find((x) => x.toLowerCase() === parts[1].toLowerCase()) : null;
// an encounter that is not one of this colour's is ignored once the route model has loaded (see render)
const enc = parts[2] && c ? 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[c];
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);
// drop the routes your choices rule out; if every one is ruled out, keep them so the panel can say so
const open = routes.filter((r) => r.reachable);
st.blocked = !open.length;
if (open.length) routes = open;
if (!st.focus || !routes.some((r) => r.enc === st.focus)) st.focus = routes[0].enc;
pills = [];
onRoute = drawRoutes(gRoute, gLab, routes);
spreadPills();
} else if (st.point && st.policy && POINTS[st.point]) {
pills = [];
st.fromList = routesFrom(st.point);
onRoute = drawFrom(gRoute, gLab, st.fromList);
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.point || !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 = `<div class="ex-scroll">${st.colour && st.policy ? panelRoutes(routes) : st.point && st.fromList ? panelFrom(st.fromList) : panelIdle()}</div>`;
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"; }
}
/** The runs selected on the page (one preset of data/stats.json): how many reached each place, and each step. */
function setStats(P, paths) {
if (paths) st.paths = paths;
st.nRuns = P.analyse.n;
st.counts = P.valley.counts;
st.edges = P.valley.edges;
render();
}
function init() {
render();
fetch("data/policy.json").then((r) => r.json()).then((p) => {
st.policy = p;
S.useGame(p.samples.all); // the game (and where each colour can be bonded) comes with the route model
if (st.pendingHash) { st.colour = st.pendingHash.c; st.focus = st.pendingHash.enc; st.pendingHash = null; }
render();
}).catch(() => { $("#ex-panel").innerHTML = '<p class="small muted">The route model (data/policy.json) could not be loaded.</p>'; });
}
window.ValleyExplorer = { setStats, fromHash, state: st, render };
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
})();