Files
threshing-atlas/apps/atlas/planner.js
T
ekcSchianoandClaude Opus 5.5 bdf66afabc Route planner: the solver's options and odds drawn on the valley map
- New "Route Planner" tab: pick a dragon colour, a goal (only this dragon /
  best odds this run) and a data sample. The solver runs in the browser from
  policy.json and walks the valley: every decision shows each option's
  chance of bonding the colour (with the best play afterwards) and of
  reaching an encounter alive; every roll shows its probabilities; deaths
  show where they happen; "stays best in N% of re-runs" and "no clear
  winner" flag noisy recommendations. Click any option on the map or in the
  list to explore another branch.
- solver.js: values now carry P(reaching an encounter alive); advisor.step()
  gives the planner the next decision, roll or outcome at any history.
- valley.js shares its painting with the planner.
- Fix: route-map target chips no longer capture clicks on other chip rows.
- Pages build gets a doctype and charset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ
2026-11-01 22:50:23 +00:00

296 lines
18 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.
/* planner.js — the route planner.
* Pick a dragon colour and an objective; the solver (solver.js, re-run in the browser from data/policy.json)
* walks the valley with you. At every decision it shows each option's chance of bonding that colour if you take it
* and then play the best route afterwards, plus the chance of reaching a bonding encounter alive. At every chance
* event it shows what can happen and how likely it is. Click any option or outcome to explore another branch. */
(function () {
"use strict";
const S = window.ThreshSolver, V = window.ValleyMap;
if (!S || !V) 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 DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const COLOURS = ["Blue", "Black", "Red", "Green", "Orange", "Brown"];
const L = V.places, INK = V.INK, PAPER = V.PAPER;
const GATE = { x: 500, y: 786 };
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;
}
const st = { policy: null, colour: "Blue", objective: "eventually", sample: "all", h: {}, cache: new Map() };
function advisor() {
const k = `${st.sample}|${st.colour}|${st.objective}`;
if (!st.cache.has(k)) st.cache.set(k, S.advisor(st.policy.samples[st.sample], st.colour, st.objective));
return st.cache.get(k);
}
/* ---------- walking the plan ---------- */
// Where each history variable is drawn on the map.
const placeOf = (v, val, h) => {
switch (v) {
case "company": return "comp:" + val;
case "direction": return "dir:" + val;
case "fs": return L[`see:${h.direction}:${val}`] ? `see:${h.direction}:${val}` : null;
case "cadet": return val === "Left them to it" ? "away" : "res:" + val;
case "post": return "fork:" + val;
case "hour": return val === "Tree" ? "tree" : "valley";
case "shadow": return val === "yes" ? "stream" : null;
case "shadowColour": return val === "Black" ? "black" : "redwood";
case "descend": return val.startsWith("Quickly") ? "treeRed" : "greens";
case "valley": return val === "Face the Red" ? "valleyRed" : "meadow";
case "meadow": return "meadow:" + val;
default: return null;
}
};
const HOLD = { cadet: "hour", post: "hour" }; // after these, the run walks on to the hour's walk
/** Default branch at a chance event: the one that can lead to the target colour, else the most likely. */
function defaultOutcome(s) {
const ent = Object.entries(s.probs).sort((a, b) => b[1] - a[1]);
if (s.var === "meadow" || s.var === "shadowColour") { const hit = ent.find(([k]) => k === st.colour); if (hit) return hit[0]; }
if (s.var === "shadow" && (st.colour === "Black" || st.colour === "Blue")) return "yes";
return ent[0][0];
}
/** Walk from the start: user's choices where given, otherwise the recommended choice / default outcome. */
function walk() {
const adv = advisor(), steps = [], h = {};
const tree = st.policy.samples[st.sample].targets[st.colour][st.objective].tree;
for (let i = 0; i < 20; i++) {
const s = adv.step(h);
if (s.kind === "decision") {
// on the recommended route the published tree knows how often this choice stayed best across posterior draws
const node = S.locate(tree, h);
if (node && node.type === "decision" && node.var === s.var && node.choice === s.choice) s.stillBest = node.stillBest;
}
steps.push({ ...s, before: { ...h } });
if (s.kind === "end") break;
const key = s.var === "encounter" ? "encounter" : s.var;
const picked = st.h[key];
const valid = s.kind === "decision" ? picked && s.options[picked] : picked && s.probs[picked] != null;
const val = valid ? picked : s.kind === "decision" ? s.choice : defaultOutcome(s);
steps[steps.length - 1].taken = val;
steps[steps.length - 1].userSet = !!valid;
h[key] = val;
}
return steps;
}
/* ---------- drawing ---------- */
function anchor(steps, i) {
// the place a step starts from: the place of the last earlier step that has one
for (let j = i - 1; j >= 0; j--) {
const s = steps[j];
if (s.kind === "end") continue;
if (HOLD[s.var] && i > j + 1 && steps.slice(j + 1, i).every((x) => !placeOf(x.var, x.taken, x.before))) return "hour";
const p = placeOf(s.var, s.taken, s.before);
if (p) return p;
}
return null;
}
function pill(g, x, y, text, { fill = PAPER.halo, ink = PAPER.ink, strong = false } = {}) {
const w = 8 + text.length * (strong ? 7.4 : 6.6), hgt = strong ? 19 : 16;
el("rect", { x: x - w / 2, y: y - hgt / 2, width: w, height: hgt, rx: hgt / 2, fill, "fill-opacity": 0.94, stroke: ink, "stroke-opacity": 0.35 }, g);
const t = 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);
t.textContent = text;
}
const at = (A, B, bend, t) => {
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 };
};
function drawMap(steps) {
const svg = $("#planner-map");
svg.innerHTML = "";
V.paintBase(svg);
svg.innerHTML = svg.innerHTML.replace(/vm-/g, "pl-"); // own filter ids: the other map's defs may be hidden
// soften the painting so the plan reads on top
el("rect", { x: 0, y: 0, width: 1000, height: 790, fill: "#f6e6c4", "fill-opacity": 0.35 }, svg);
const tc = INK[st.colour];
const gOpt = el("g", {}, svg), gRoute = el("g", { filter: "url(#pl-brush)" }, svg), gLab = el("g", {}, svg), gPlace = el("g", {}, svg);
const used = new Set();
steps.forEach((s, i) => {
if (s.kind === "end") return;
const from = anchor(steps, i);
const A = from ? L[from] : GATE;
if (from) used.add(from);
if (s.var === "encounter") {
const P = L[from];
if (!P) return;
const v = s.options["Attempt the bond"];
pill(gLab, P.x, P.y + 34, s.choice === "Attempt the bond" ? `attempt: ${pct(v.pX)} ${st.colour}` : "die on purpose", { strong: true, ink: s.choice === "Attempt the bond" ? tc : PAPER.death });
return;
}
const entries = s.kind === "decision" ? Object.entries(s.options) : Object.entries(s.probs);
const best = s.kind === "decision" ? Math.max(...entries.map(([, v]) => v.pX)) : null;
entries.forEach(([val, v]) => {
const pid = placeOf(s.var, val, s.before);
if (!pid || !L[pid]) return;
const B = L[pid];
if (pid === from) return;
const taken = val === s.taken;
const d = V.curve(A, B, 0.08);
if (taken) {
el("path", { d, fill: "none", stroke: "#fff1c9", "stroke-width": 14, "stroke-opacity": 0.75, "stroke-linecap": "round" }, gRoute);
el("path", { d, fill: "none", stroke: s.kind === "decision" ? tc : PAPER.ink, "stroke-width": 6, "stroke-opacity": 0.9, "stroke-linecap": "round", "stroke-dasharray": s.kind === "chance" ? "2 9" : null }, gRoute);
} else {
const rel = s.kind === "decision" ? (best > 0 ? v.pX / best : 0) : v;
el("path", { d, fill: "none", stroke: s.kind === "decision" ? tc : PAPER.ink, "stroke-width": 1.5 + 3 * rel, "stroke-opacity": 0.25 + 0.4 * rel, "stroke-linecap": "round", "stroke-dasharray": "5 6" }, gOpt);
}
used.add(pid);
const m = at(A, B, 0.08, s.kind === "decision" ? 0.7 : 0.55);
const label = s.kind === "decision" ? pct(v.pX) : `roll ${pct(v)}`;
pill(gLab, m.x, m.y, label, { strong: taken, ink: s.kind === "decision" ? (taken ? tc : PAPER.ink) : PAPER.ink });
});
if (s.risk && s.risk.p > 0.0005 && from) {
const P = L[from];
el("circle", { cx: P.x + 16, cy: P.y - 15, r: 13, fill: PAPER.death, stroke: PAPER.halo, "stroke-width": 1.5 }, gLab);
const t = el("text", { x: P.x + 16, y: P.y - 11.5, "text-anchor": "middle", "font-size": 9.5, fill: "#fff3e0", "font-family": "var(--font-data)" }, gLab);
t.textContent = pct(s.risk.p);
el("title", {}, t).textContent = `${s.risk.label}: ${pct(s.risk.p)}`;
}
});
// places: only those on the plan or offered as options
Object.entries(L).forEach(([id, P]) => {
if (!used.has(id)) return;
const g = el("g", {}, gPlace);
if (P.kind === "dragon") {
el("circle", { cx: P.x, cy: P.y, r: 15, fill: PAPER.halo, stroke: INK[P.colour], "stroke-width": 2.4 }, g);
el("path", { d: V.WING, fill: INK[P.colour], transform: `translate(${P.x - 12} ${P.y - 7.5}) scale(0.24)` }, g);
} else {
el("circle", { cx: P.x, cy: P.y, r: P.kind === "small" ? 6 : 8, fill: PAPER.ink, stroke: PAPER.halo, "stroke-width": 2.5 }, g);
}
if (!P.first) {
const right = (P.lab || "right") !== "left";
const t = el("text", { x: P.x + (right ? 20 : -20), y: P.y - 8, "text-anchor": right ? "start" : "end", "font-family": "var(--font-display)", "font-size": 13, fill: PAPER.ink, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g);
t.textContent = P.name;
}
});
el("text", { x: GATE.x, y: 778, "text-anchor": "middle", "font-size": 11, "letter-spacing": "0.14em", fill: PAPER.ink, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, svg).textContent = "ENTER THE VALLEY";
V.finish(svg);
svg.innerHTML = svg.innerHTML.replace(/url\(#vm-/g, "url(#pl-");
bindHits(steps); // click targets go on last, after the id rewrite (which would drop listeners)
}
// Invisible, wide click targets over every option trail on the map.
function bindHits(steps) {
const svg = $("#planner-map");
const g = el("g", {}, svg);
steps.forEach((s, i) => {
if (s.kind === "end" || s.var === "encounter") return;
const from = anchor(steps, i), A = from ? L[from] : GATE;
const entries = s.kind === "decision" ? Object.entries(s.options) : Object.entries(s.probs);
entries.forEach(([val, v]) => {
const pid = placeOf(s.var, val, s.before);
if (!pid || !L[pid] || pid === from) return;
const hit = el("path", { d: V.curve(A, L[pid], 0.08), fill: "none", stroke: "#000", "stroke-opacity": 0, "stroke-width": 18, style: "cursor:pointer", tabindex: 0, role: "button",
"aria-label": s.kind === "decision" ? `${s.label}: ${val}, ${st.colour} ${pct(v.pX)}` : `${s.label}: ${val}, ${pct(v)}` }, g);
el("title", {}, hit).textContent = s.kind === "decision"
? `${s.label}: ${val}\n${st.colour}: ${pct(v.pX)} · reach a bonding encounter alive: ${pct(v.pReach)}` : `${s.label}: ${val} (${pct(v)})`;
const go = () => choose(s, val);
hit.addEventListener("click", go);
hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
});
});
}
/* ---------- the step list ---------- */
const NAME = (s, val) => {
if (s.var === "fs" || s.var === "meadow" || s.var === "shadowColour") return `${val} dragon`;
if (s.var === "shadow") return val === "yes" ? "The shadow appears" : "No shadow";
if (s.var === "company") return val === "Alone" ? "Alone" : `With ${val.toLowerCase()}`;
if (s.var === "direction") return val === "Center" ? "Forest centre" : val;
if (s.var === "post") return val === "Forest" ? "Deeper into the forest" : `${val} fork`;
if (s.var === "hour") return val === "Tree" ? "Climb the tallest tree" : "Walk on to the valley centre";
return val;
};
function drawSteps(steps) {
const box = $("#planner-steps");
box.innerHTML = steps.map((s, i) => {
if (s.kind === "end") {
const rows = Object.entries(s.outcomes).sort((a, b) => b[1] - a[1]).map(([k, p]) =>
`<div class="pl-row"><span>${k === "burn" ? "Incinerated" : "Bond " + esc(k)}</span><i style="--w:${100 * p}%;--c:${k === "burn" ? "var(--ember)" : `var(${DV[k]})`}"></i><span class="m"><b>${pct(p)}</b></span></div>`).join("");
return `<li class="pl-step end"><span class="pl-n">${i + 1}</span><div><h4>${s.action === "Die on purpose" ? "Die on purpose and try again" : "The bonding encounter"}</h4>${rows}</div></li>`;
}
const isDec = s.kind === "decision";
const entries = isDec ? Object.entries(s.options).sort((a, b) => b[1].pX - a[1].pX) : Object.entries(s.probs).sort((a, b) => b[1] - a[1]);
const top = isDec ? Math.max(1e-9, entries[0][1].pX) : 1;
const second = isDec && entries[1] ? entries[1][1].pX : null;
const close = isDec && second != null && (entries[0][1].pX - second < 0.002 || (s.stillBest != null && s.stillBest < 0.75));
const sure = isDec && s.stillBest != null ? `<p class="small muted">The recommended option stays best in ${pct(s.stillBest)} of 200 re-runs on the uncertain data.</p>` : "";
const rows = entries.map(([val, v]) => {
const taken = val === s.taken, rec = isDec && val === s.choice;
const w = isDec ? (100 * v.pX) / top : 100 * v;
const meta = `<span class="m">${isDec ? `<b>${pct(v.pX)}</b><small>alive ${pct(v.pReach)}${v.pOther > 0.0005 ? ` · other ${pct(v.pOther)}` : ""}</small>` : `<b>${pct(v)}</b>`}</span>`;
return `<button type="button" class="pl-row${taken ? " taken" : ""}" data-i="${i}" data-v="${esc(val)}" aria-pressed="${taken}">
<span>${esc(NAME(s, val))}${rec ? ' <em class="rec">best</em>' : ""}</span><i style="--w:${w}%;--c:${isDec ? `var(${DV[st.colour]})` : "var(--muted)"}"></i>${meta}</button>`;
}).join("");
const risk = s.risk && s.risk.p > 0.0005 ? `<p class="small pl-risk">${esc(s.risk.label)}: ${pct(s.risk.p)}</p>` : "";
const head = isDec ? (s.var === "encounter" ? `A ${esc(s.encounter.split("-")[1] === "Greens" ? "pair of Greens" : s.encounter.split("-")[1] + " dragon")} waits` : esc(s.label)) : `${esc(s.label)} <span class="muted">· chance</span>`;
return `<li class="pl-step ${isDec ? "dec" : "chance"}${s.userSet ? " user" : ""}"><span class="pl-n">${i + 1}</span><div>${risk}<h4>${head}</h4>
${isDec && close ? '<p class="small pl-close">No clear winner: the top options are within the noise.</p>' : ""}${sure}${rows}</div></li>`;
}).join("");
$$(".pl-row[data-i]", box).forEach((b) => b.addEventListener("click", () => choose(steps[+b.dataset.i], b.dataset.v)));
}
function choose(s, val) {
const key = s.var === "encounter" ? "encounter" : s.var;
// keep earlier choices, change this one, forget everything after it
const order = ["company", "direction", "fs", "cadet", "post", "hour", "shadow", "shadowColour", "descend", "valley", "meadow", "encounter"];
const keep = {};
for (const k of order) { if (k === key) break; if (st.h[k] != null) keep[k] = st.h[k]; }
Object.assign(keep, s.before);
keep[key] = val;
st.h = keep;
render();
}
function headline() {
const T = st.policy.samples[st.sample].targets[st.colour], b = T[st.objective];
const lb = st.policy.samples.lowBias.targets[st.colour].thisAttempt;
const att = b.expectedAttempts.mean;
$("#planner-head").innerHTML = `
<div class="pl-kpi" style="--c: var(${DV[st.colour]})"><span class="lbl">Best route, ${st.colour}</span><b>${pct(b.pX.mean)}</b><span class="small muted">per attempt · 95% ${pct(b.pX.lo)}–${pct(b.pX.hi)}</span></div>
<div class="pl-kpi"><span class="lbl">Attempts, about</span><b>${isFinite(att) ? Math.round(att) : "–"}</b><span class="small muted">if you die on purpose whenever it goes wrong</span></div>
<div class="pl-kpi"><span class="lbl">Ends on another colour</span><b>${pct(b.pOther.mean)}</b><span class="small muted">per attempt, on this route</span></div>
<div class="pl-kpi"><span class="lbl">Low-bias estimate</span><b>${pct(lb.pX.mean)}</b><span class="small muted">riders who logged every run</span></div>`;
}
function render() {
if (!st.policy) return;
$$("#planner-colours .tchip").forEach((b) => b.setAttribute("aria-pressed", b.dataset.c === st.colour));
$$("#planner-obj button").forEach((b) => b.setAttribute("aria-pressed", b.dataset.o === st.objective));
$$("#planner-sample button").forEach((b) => b.setAttribute("aria-pressed", b.dataset.s === st.sample));
$(".planner-shell").style.setProperty("--vt", `var(${DV[st.colour]})`);
headline();
const steps = walk();
drawMap(steps);
drawSteps(steps);
}
function init() {
$("#planner-colours").innerHTML = COLOURS.map((c) => `<button type="button" class="tchip${c === "Blue" || c === "Black" ? " featured" : ""}" data-c="${c}" style="--c: var(${DV[c]})"><span class="sw"></span>${c}</button>`).join("");
$$("#planner-colours .tchip").forEach((b) => b.addEventListener("click", () => { st.colour = b.dataset.c; st.h = {}; render(); }));
$$("#planner-obj button").forEach((b) => b.addEventListener("click", () => { st.objective = b.dataset.o; render(); }));
$$("#planner-sample button").forEach((b) => b.addEventListener("click", () => { st.sample = b.dataset.s; render(); }));
$("#planner-reset").addEventListener("click", () => { st.h = {}; render(); });
fetch("data/policy.json").then((r) => r.json()).then((p) => { st.policy = p; render(); })
.catch(() => { $("#planner-head").innerHTML = '<p class="small muted">The route model (data/policy.json) could not be loaded.</p>'; });
}
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
window.RoutePlanner = { state: st, render };
})();