The Valley as the landing page: dragons first, routes on demand

- New tab order: The Valley, The Odds, The Dragons, Deep Dive, Data & Methods
  (Route Flow and Blue & Black fold into Deep Dive; methods into Data &
  Methods; old #links redirect).
- explorer.js replaces the trails map and the route planner, with progressive
  disclosure: the painted valley shows landmarks and the dragons where riders
  meet them (faint = rarely met), no routes and no deaths; hover for a note;
  choose a dragon to draw every route to every place it can be bonded, with
  width = chance of still being on the route, and solid / dashed / dotted and
  opacity for how a route compares with the best; click a choice point to
  branch off and re-plan; "Why this route?" holds intervals and risks; a
  toggle shows the community's actual traffic; #valley/blue/meadow-Blue links.
- dragons.js: original dragon silhouettes in six poses, built from simple
  parts.
- Solver: route to one specific encounter (only: [...]); ENCOUNTERS per
  colour, including the Greens rescue for Orange and Brown.
- The Odds rewritten for all six dragons, ranked easiest to hardest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ
This commit is contained in:
ekcSchiano
2026-11-02 14:24:47 +00:00
co-authored by Claude Opus 5.5
parent bdf66afabc
commit de80e99c74
9 changed files with 1009 additions and 519 deletions
+2 -1
View File
@@ -8,7 +8,8 @@ Unofficial fan project. Not affiliated with Dragonkind or the Fourth Wing publis
## Layout ## Layout
``` ```
apps/atlas/ the web page: valley map, route flow, charts, Dragon Register, Reddit post generator apps/atlas/ the web page. The Valley (explorer.js: the map, the dragons, routes on demand; dragons.js:
original silhouettes), The Odds, The Dragons, Deep Dive, Data & Methods
packages/core/ @threshing-atlas/core, no dependencies, runs in Node and the browser: packages/core/ @threshing-atlas/core, no dependencies, runs in Node and the browser:
src/engine.js coding rules and statistics for the community form src/engine.js coding rules and statistics for the community form
src/graph.js the shared route graph: scene graph, decision-variable graph, src/graph.js the shared route graph: scene graph, decision-variable graph,
+235
View File
@@ -0,0 +1,235 @@
/* dragons.js — original dragon silhouettes for the valley map.
* Each pose is built from simple parts (tapered tubes, a scalloped wing membrane, a head with horns, spines,
* a spaded tail), so every dragon is drawn the same way but stands differently. Drawn facing right in a
* 200 x 160 box; flip with scale(-1, 1). Works in the browser (window.DragonArt) and in Node. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonArt = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const f = (n) => Math.round(n * 10) / 10;
const lerp = (a, b, t) => a + (b - a) * t;
/** Points along a cubic Bezier given as [p0, c1, c2, p1] (each [x, y]). */
function bez(P, n = 28) {
const out = [];
for (let i = 0; i <= n; i++) {
const t = i / n, u = 1 - t;
out.push([
u * u * u * P[0][0] + 3 * u * u * t * P[1][0] + 3 * u * t * t * P[2][0] + t * t * t * P[3][0],
u * u * u * P[0][1] + 3 * u * u * t * P[1][1] + 3 * u * t * t * P[2][1] + t * t * t * P[3][1],
]);
}
return out;
}
/** A tube along a Bezier whose half-width goes from r0 to r1 (r can also be a function of t). */
function tube(P, r0, r1, n = 28) {
const pts = bez(P, n), L = [], R = [];
pts.forEach((p, i) => {
const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const t = i / n, r = typeof r0 === "function" ? r0(t) : lerp(r0, r1, t);
L.push([p[0] - dy * r, p[1] + dx * r]);
R.push([p[0] + dy * r, p[1] - dx * r]);
});
const ring = L.concat(R.reverse());
return "M" + ring.map((p) => `${f(p[0])} ${f(p[1])}`).join(" L") + " Z";
}
const poly = (pts) => "M" + pts.map((p) => `${f(p[0])} ${f(p[1])}`).join(" L") + " Z";
const ell = (cx, cy, rx, ry, rot = 0) => {
const pts = [];
for (let i = 0; i < 36; i++) {
const a = (i / 36) * Math.PI * 2, x = rx * Math.cos(a), y = ry * Math.sin(a), c = Math.cos(rot), s = Math.sin(rot);
pts.push([cx + x * c - y * s, cy + x * s + y * c]);
}
return poly(pts);
};
/**
* Wing membrane: a leading-edge bone shoulder -> wrist -> tip, finger tips along the trailing edge, and
* scalloped membrane between them, back to the root on the body.
*/
function wing({ shoulder, wrist, tip, fingers, root, bow = 0.28, bone = 4 }) {
const d = [tube([shoulder, [lerp(shoulder[0], wrist[0], 0.4), lerp(shoulder[1], wrist[1], 0.4) - 6], [lerp(shoulder[0], wrist[0], 0.8), lerp(shoulder[1], wrist[1], 0.8)], wrist], bone, bone * 0.8),
tube([wrist, [lerp(wrist[0], tip[0], 0.3), lerp(wrist[1], tip[1], 0.3)], [lerp(wrist[0], tip[0], 0.7), lerp(wrist[1], tip[1], 0.7)], tip], bone * 0.8, 0.8)];
const edge = [tip].concat(fingers, [root]);
let m = `M${f(shoulder[0])} ${f(shoulder[1])} L${f(wrist[0])} ${f(wrist[1])} L${f(tip[0])} ${f(tip[1])}`;
for (let i = 1; i < edge.length; i++) {
const a = edge[i - 1], b = edge[i];
// scallop: control point pulled toward the wrist
const mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;
const cx = lerp(mx, wrist[0], bow), cy = lerp(my, wrist[1], bow);
m += ` Q${f(cx)} ${f(cy)} ${f(b[0])} ${f(b[1])}`;
}
m += ` L${f(shoulder[0])} ${f(shoulder[1])} Z`;
d.push(m);
// finger bones from the wrist (thin, add texture at the edge)
fingers.forEach((p) => d.push(tube([wrist, [lerp(wrist[0], p[0], 0.33), lerp(wrist[1], p[1], 0.33)], [lerp(wrist[0], p[0], 0.66), lerp(wrist[1], p[1], 0.66)], p], 1.6, 0.6, 10)));
return d;
}
/** Head pointing along `ang` (radians, 0 = right) from the neck end, with horns and an open or closed jaw. */
function head({ at, ang = 0, size = 1, open = 0, horns = 2 }) {
const c = Math.cos(ang), s = Math.sin(ang);
const T = (x, y) => [at[0] + (x * c - y * s) * size, at[1] + (x * s + y * c) * size];
const d = [];
// skull and upper snout
d.push(poly([T(-8, 2), T(-6, -9), T(4, -12), T(14, -8), T(26, -5), T(31, -2), T(30, 1), T(18, 2 + open * 0.3), T(8, 6)]));
// jaw (drops when open)
d.push(poly([T(-6, 3), T(10, 4), T(28, 3 + open), T(26, 6 + open), T(12, 10 + open * 0.4), T(-4, 9)]));
// horns sweeping back
for (let i = 0; i < horns; i++) {
const y0 = -9 + i * 4, len = 18 - i * 6;
d.push(tube([T(2 - i * 3, y0), T(-6 - i * 2, y0 - 6), T(-14 - i * 3, y0 - 8 - i), T(-12 - len * 0.6 - i * 3, y0 - 14 + i * 3)], 2.6 * size - i * 0.4, 0.4, 10));
}
// brow spike and cheek frill
d.push(poly([T(-4, 4), T(-14, 8), T(-5, 8)]));
return { d, eye: T(8, -5), eyeR: 1.9 * size };
}
/** Small triangular spines along a list of points (pointing away from `side` normal). */
function spines(pts, size, side = -1, every = 2) {
const d = [];
for (let i = 1; i < pts.length - 1; i += every) {
const a = pts[i - 1], b = pts[i + 1], p = pts[i];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const nx = -dy * side, ny = dx * side, k = typeof size === "function" ? size(i / pts.length) : size;
d.push(poly([[p[0] - dx * k * 0.6, p[1] - dy * k * 0.6], [p[0] + nx * k * 1.5 - dx * k * 0.5, p[1] + ny * k * 1.5 - dy * k * 0.5], [p[0] + dx * k * 0.6, p[1] + dy * k * 0.6]]));
}
return d;
}
/** Tail as a tapering tube ending in a spade. */
function tail(P, r0) {
const d = [tube(P, (t) => Math.max(0.9, r0 * (1 - t) ** 1.1), null, 36)];
const pts = bez(P, 36), a = pts[pts.length - 3], b = pts[pts.length - 1];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const nx = -dy, ny = dx, k = Math.max(4, r0 * 0.9);
d.push(poly([[b[0] - dx * k * 0.6, b[1] - dy * k * 0.6], [b[0] + nx * k, b[1] + ny * k], [b[0] + dx * k * 1.6, b[1] + dy * k * 1.6], [b[0] - nx * k, b[1] - ny * k]]));
return { d, pts };
}
/** Leg: hip -> knee -> foot with three claws. */
function leg(hip, knee, foot, r, toe = 1) {
const d = [tube([hip, [lerp(hip[0], knee[0], 0.6), lerp(hip[1], knee[1], 0.6)], knee, [lerp(knee[0], foot[0], 0.5), lerp(knee[1], foot[1], 0.5)]], r, r * 0.6, 14),
tube([[lerp(knee[0], foot[0], 0.4), lerp(knee[1], foot[1], 0.4)], [lerp(knee[0], foot[0], 0.6), lerp(knee[1], foot[1], 0.6)], [lerp(knee[0], foot[0], 0.85), lerp(knee[1], foot[1], 0.85)], foot], r * 0.6, r * 0.45, 10)];
for (let i = -1; i <= 1; i++) d.push(poly([[foot[0] - 2, foot[1] - 2], [foot[0] + toe * (6 + i * 1.5), foot[1] + 1 + i * 2.2], [foot[0] + 1, foot[1] + 2.5]]));
return d;
}
/* ---------- poses ---------- */
const POSES = {
// seated and watchful, one wing raised, tail curled round the feet
sitting() {
const d = [];
d.push(...wing({ shoulder: [88, 74], wrist: [62, 18], tip: [24, 30], fingers: [[14, 66], [30, 98], [56, 116]], root: [76, 112], bow: 0.3 }));
d.push(ell(92, 104, 26, 36, -0.25));
d.push(tube([[90, 80], [96, 58], [110, 42], [116, 34]], 13, 7));
const t = tail([[76, 132], [56, 150], [110, 158], [168, 150]], 9);
d.push(...t.d);
d.push(...leg([84, 120], [70, 136], [86, 152], 12, 1));
d.push(...leg([102, 104], [110, 124], [114, 150], 7, 1));
const h = head({ at: [114, 34], ang: -0.05, size: 1.05 });
d.push(...h.d);
d.push(...spines(bez([[86, 84], [84, 62], [100, 44], [110, 36]], 10), 4, -1, 2));
d.push(...spines(t.pts.slice(0, 26), (u) => 4 * (1 - u), 1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// low and stalking, head forward, wings folded
prowling() {
const d = [];
d.push(...wing({ shoulder: [92, 92], wrist: [70, 64], tip: [118, 52], fingers: [[136, 70], [130, 90]], root: [104, 100], bow: 0.25, bone: 3.4 }));
d.push(ell(96, 108, 38, 18, 0.05));
d.push(tube([[124, 104], [140, 98], [152, 92], [162, 94]], 11, 7));
const t = tail([[62, 108], [36, 106], [22, 128], [6, 120]], 11);
d.push(...t.d);
d.push(...leg([72, 112], [60, 128], [70, 146], 11));
d.push(...leg([84, 116], [94, 130], [92, 146], 8));
d.push(...leg([118, 112], [126, 128], [124, 146], 8));
d.push(...leg([128, 110], [140, 126], [146, 146], 7));
const h = head({ at: [160, 94], ang: 0.12, size: 1 });
d.push(...h.d);
d.push(...spines(bez([[66, 92], [90, 84], [130, 86], [156, 88]], 14), 3.6, -1, 2));
d.push(...spines(t.pts.slice(0, 26), (u) => 3.6 * (1 - u), -1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// in flight, both wings spread
flying() {
const d = [];
d.push(...wing({ shoulder: [96, 84], wrist: [70, 36], tip: [40, 6], fingers: [[30, 40], [44, 66], [70, 80]], root: [92, 94], bow: 0.32 }));
d.push(...wing({ shoulder: [110, 84], wrist: [140, 30], tip: [190, 14], fingers: [[178, 52], [160, 76], [134, 90]], root: [114, 96], bow: 0.32 }));
d.push(ell(104, 96, 30, 13, 0.2));
d.push(tube([[128, 92], [142, 86], [150, 76], [158, 72]], 9, 6));
const t = tail([[78, 92], [54, 98], [40, 120], [12, 116]], 8);
d.push(...t.d);
d.push(...leg([94, 102], [96, 116], [108, 124], 6));
d.push(...leg([116, 102], [122, 114], [132, 118], 5));
const h = head({ at: [156, 72], ang: -0.2, size: 0.9, open: 2 });
d.push(...h.d);
return { d, eye: h.eye, eyeR: h.eyeR };
},
// reared up and roaring, wings half open
roaring() {
const d = [];
d.push(...wing({ shoulder: [94, 68], wrist: [52, 40], tip: [30, 2], fingers: [[16, 46], [34, 78], [66, 96]], root: [90, 98], bow: 0.3 }));
d.push(ell(98, 100, 22, 40, 0.2));
d.push(tube([[104, 70], [112, 50], [126, 34], [136, 24]], 13, 7));
const t = tail([[86, 136], [60, 156], [30, 150], [14, 132]], 10);
d.push(...t.d);
d.push(...leg([90, 124], [104, 138], [96, 154], 12));
d.push(...leg([108, 86], [124, 92], [132, 82], 6, 1));
d.push(...leg([102, 92], [116, 104], [126, 98], 6, 1));
const h = head({ at: [134, 24], ang: -0.55, size: 1.05, open: 7 });
d.push(...h.d);
d.push(...spines(bez([[94, 86], [100, 60], [116, 40], [130, 28]], 10), 4, -1, 2));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// coiled, as if wrapped around something, head lifted
coiled() {
const d = [];
const t = tail([[100, 120], [30, 150], [20, 80], [80, 74]], 15);
d.push(...t.d);
d.push(tube([[100, 120], [150, 130], [170, 96], [140, 70]], 16, 12));
d.push(tube([[140, 70], [124, 52], [128, 34], [146, 26]], 12, 7));
d.push(...wing({ shoulder: [134, 76], wrist: [106, 36], tip: [72, 26], fingers: [[64, 52], [80, 70], [104, 82]], root: [124, 90], bow: 0.28, bone: 3.4 }));
d.push(...leg([150, 116], [164, 126], [170, 142], 8));
d.push(...leg([116, 124], [114, 138], [122, 150], 8));
const h = head({ at: [144, 26], ang: 0.1, size: 1 });
d.push(...h.d);
d.push(...spines(t.pts, (u) => 3.5 * (1 - u * 0.7), -1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// lying down at rest, head up
resting() {
const d = [];
d.push(...wing({ shoulder: [90, 108], wrist: [66, 84], tip: [112, 70], fingers: [[134, 88], [124, 108]], root: [100, 118], bow: 0.25, bone: 3.2 }));
d.push(ell(92, 126, 42, 18, 0));
d.push(tube([[124, 120], [140, 112], [146, 92], [158, 82]], 12, 7));
const t = tail([[54, 130], [24, 140], [20, 152], [70, 152]], 11);
d.push(...t.d);
d.push(...leg([120, 132], [132, 142], [150, 146], 8));
d.push(...leg([70, 134], [82, 144], [96, 148], 10));
const h = head({ at: [156, 84], ang: 0.05, size: 1 });
d.push(...h.d);
d.push(...spines(bez([[60, 112], [90, 104], [130, 106], [152, 88]], 14), 3.4, -1, 2));
return { d, eye: h.eye, eyeR: h.eyeR };
},
};
const cache = {};
/** SVG markup for one dragon: <g> with the silhouette in `fill` and a small eye in `eyeFill`. */
function svg(pose, { fill = "#2a2230", eyeFill = "#f6e6c4", flip = false } = {}) {
if (!cache[pose]) cache[pose] = POSES[pose]();
const p = cache[pose];
const tf = flip ? ' transform="translate(200 0) scale(-1 1)"' : "";
// one path per part: parts wind in different directions, so a single combined path would punch holes
return `<g${tf}><g fill="${fill}">${p.d.map((d) => `<path d="${d}"/>`).join("")}</g><circle cx="${f(p.eye[0])}" cy="${f(p.eye[1])}" r="${p.eyeR}" fill="${eyeFill}"/></g>`;
}
return { svg, poses: Object.keys(POSES) };
});
+504
View File
@@ -0,0 +1,504 @@
/* 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) => ({ "&": "&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: "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;
case "cadet":
push("scream");
if (v === "Left them to it") push("away");
else { push(["Tourniquet", "Left injured cadet", "Took their weapons"].includes(v) ? "wounded" : "bully"); 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,
cadet: v === "Left them to it" ? "away" : "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 };
};
function pill(g, x, y, text, { ink = PAPER.ink, strong = false, bg = PAPER.halo } = {}) {
const w = 10 + text.length * (strong ? 7.2 : 6.4), h = strong ? 20 : 17;
el("rect", { x: x - w / 2, y: y - h / 2, width: w, height: h, rx: h / 2, fill: bg, "fill-opacity": 0.95, stroke: ink, "stroke-opacity": 0.4 }, 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];
let op = n == null ? 0.85 : 0.22 + 0.78 * 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 *= 0.35;
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);
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 `<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(); } });
});
}
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);
const right = (P.lab || "right") !== "left";
const t = el("text", { x: P.x + (right ? 10 : -10), y: P.y + 4, "text-anchor": right ? "start" : "end", "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" ? `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`, { ink: 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;
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);
const m2 = mid(P, B, 0.72, 0.1);
pill(gLab, m2.x, m2.y, `${v.length > 18 ? v.slice(0, 17) + "…" : v} ${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;
}
/* ---------- 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)" })}</svg>`;
const POSE_OF = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" };
const trafficToggle = () => `<label class="ex-toggle"><input type="checkbox" id="ex-traffic"${st.traffic ? " checked" : ""}> Show where riders actually went</label>`;
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.runs ? st.runs.length.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 every way to it, and how likely each is.</p>
${chooser()}${info}
${trafficToggle()}
<p class="small muted">Prefer the numbers? <a href="#odds">The Odds</a> has the statistics behind the map.</p>`;
}
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>
<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. Changed your mind? <button type="button" class="linklike" id="ex-reset-route">Reset this route</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(); });
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;
if (!st.policy) { st.pendingHash = { c, enc }; return; }
if (c !== st.colour || (enc && enc !== st.focus)) { st.colour = c; st.focus = enc; st.expanded = null; 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), 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;
onRoute = drawRoutes(gRoute, gLab, routes);
}
drawLandmarks(gLand, 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 = `<div class="ex-scroll">${st.colour && st.policy ? panelRoutes(routes) : 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"; }
}
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 = '<p class="small muted">The route model (data/policy.json) could not be loaded.</p>'; });
}
window.ValleyExplorer = { setRuns, fromHash, state: st, render };
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
})();
+174 -176
View File
@@ -312,41 +312,79 @@ td { border-bottom-color: color-mix(in srgb, var(--line) 70%, transparent); }
.journey { background: color-mix(in srgb, var(--surface) 85%, #000); } .journey { background: color-mix(in srgb, var(--surface) 85%, #000); }
footer { border-top-color: var(--line); } footer { border-top-color: var(--line); }
/* route planner */ /* the valley explorer (landing page) */
.planner-controls { align-items: end; } .explorer { gap: 0; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 999px; overflow: hidden; } .ex-shell { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 360px); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--surface);
.seg button { border: 0; border-radius: 0; background: transparent; padding: 7px 13px; color: var(--muted); font-size: 0.72rem; } --frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 55%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 35%, transparent), 0 0 36px color-mix(in srgb, var(--frame) 14%, transparent); transition: box-shadow .3s; }
@media (max-width: 980px) { .ex-shell { grid-template-columns: minmax(0, 1fr); } }
.ex-map-wrap { position: relative; overflow-x: auto; background: #d9b07a; }
#ex-map { display: block; width: 100%; min-width: 720px; height: auto; }
#ex-map text { font-family: var(--font-body); }
.ex-dragon { cursor: pointer; transition: opacity .25s; }
.ex-dragon:focus-visible, .ex-mark:focus-visible, .ex-alt:focus-visible { outline: none; filter: drop-shadow(0 0 4px #fff); }
.ex-mark, .ex-alt { cursor: pointer; }
.ex-hint { position: absolute; left: 50%; bottom: 46px; transform: translateX(-50%); padding: 8px 16px; border-radius: 999px; background: color-mix(in srgb, #1d0a12 78%, transparent); color: #f6e6c4; font-family: var(--font-label); letter-spacing: .14em; text-transform: uppercase; font-size: .72rem; pointer-events: none; white-space: nowrap; }
.ex-tip { position: absolute; z-index: 3; max-width: 260px; padding: 8px 10px; border-radius: 8px; background: #fbf0d6; color: #3b2416; font-size: 13px; line-height: 1.35; box-shadow: 0 4px 18px #0006; pointer-events: none; }
.ex-panel { position: relative; border-left: 1px solid var(--line); }
.ex-scroll { position: absolute; inset: 0; overflow: auto; display: grid; gap: 12px; align-content: start; padding: 18px; }
@media (max-width: 980px) { .ex-panel { border-left: 0; border-top: 1px solid var(--line); } .ex-scroll { position: static; } }
.ex-panel h2 { font-family: var(--font-display); font-weight: 400; font-size: 1.6rem; margin: 0; }
.ex-choose { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.ex-dchip { display: grid; justify-items: center; gap: 2px; padding: 6px 4px 8px; border-radius: 10px; border: 1px solid color-mix(in srgb, var(--c) 45%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); color: var(--ink); font-size: .68rem; }
.ex-dchip svg { width: 58px; height: 46px; }
.ex-dchip[aria-pressed="true"] { background: color-mix(in srgb, var(--c) 22%, var(--raised)); box-shadow: 0 0 14px color-mix(in srgb, var(--c) 35%, transparent), inset 0 0 0 1px var(--c); }
.ex-card { padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--raised); }
.ex-toggle { display: flex; gap: 8px; align-items: center; font-size: var(--step--1); color: var(--muted); }
.ex-head { display: grid; grid-template-columns: 64px minmax(0, 1fr) auto; gap: 10px; align-items: center; }
.ex-head svg { width: 64px; height: 52px; }
.ex-head h2 { color: var(--c); }
.ex-close { width: 32px; height: 32px; border-radius: 50%; padding: 0; font-size: 1.1rem; line-height: 1; }
.ex-routes { display: grid; gap: 8px; }
.ex-route-card { display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; gap: 2px 10px; align-items: center; text-align: left; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--raised); color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-route-card.on { border-color: color-mix(in srgb, var(--accent) 60%, var(--line)); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent); }
.ex-route-card .nm { font-family: var(--font-display); font-size: 1rem; }
.ex-route-card .nm em { font-style: normal; color: var(--muted); font-size: .8rem; }
.ex-route-card b { font-family: var(--font-display); font-weight: 400; font-size: 1.35rem; }
.ex-route-card small { grid-column: 2 / 4; color: var(--muted); }
.ex-swatch { grid-row: 1 / 3; width: 30px; height: 0; border-top: 6px solid var(--c); }
.ex-swatch.dashed { border-top-style: dashed; } .ex-swatch.dotted { border-top-style: dotted; }
.ex-key { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
.ex-key span { display: inline-block; width: 22px; border-top: 4px solid var(--muted); }
.ex-key .dashed { border-top-style: dashed; } .ex-key .dotted { border-top-style: dotted; }
.ex-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
.ex-steps li { border-radius: 8px; }
.ex-steps li.chance { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 8px; padding: 6px 10px; border: 1px dashed var(--line); font-size: var(--step--1); }
.ex-steps li.chance small { grid-column: 1 / 3; color: var(--muted); font-family: var(--font-data); }
.ex-step { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 8px; width: 100%; text-align: left; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--raised); color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-step small { grid-column: 1 / 3; color: var(--muted); font-family: var(--font-data); }
.ex-steps li.open .ex-step { border-color: var(--accent); }
.ex-opts { display: grid; gap: 2px; padding: 6px 0 4px 10px; }
.ex-opt { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; text-align: left; padding: 4px 8px; border: 0; border-radius: 6px; background: transparent; color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-opt:hover { background: color-mix(in srgb, var(--ink) 7%, transparent); }
.ex-opt.on { background: color-mix(in srgb, var(--accent) 16%, transparent); }
.ex-opt b { font-family: var(--font-data); }
.ex-opt .rec { font-style: normal; font-size: 9.5px; font-family: var(--font-label); letter-spacing: .1em; text-transform: uppercase; color: var(--bg); background: var(--accent); border-radius: 999px; padding: 1px 6px; margin-left: 4px; }
.ex-why summary { cursor: pointer; font-family: var(--font-label); letter-spacing: .12em; text-transform: uppercase; font-size: .72rem; color: var(--accent); }
.ex-why { display: grid; gap: 6px; }
.linklike { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; font: inherit; text-transform: none; letter-spacing: normal; cursor: pointer; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 999px; overflow: hidden; width: fit-content; }
.seg button { border: 0; border-radius: 0; background: transparent; padding: 7px 13px; color: var(--muted); font-size: 0.7rem; }
.seg button[aria-pressed="true"] { background: color-mix(in srgb, var(--accent) 22%, var(--raised)); color: var(--ink); } .seg button[aria-pressed="true"] { background: color-mix(in srgb, var(--accent) 22%, var(--raised)); color: var(--ink); }
.pl-head { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 10px; }
.pl-close { color: var(--warn); margin: 0 0 4px; } /* the odds, per dragon */
.pl-kpi { padding: 12px 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); display: grid; gap: 2px; align-content: start; } .odds-colours { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.pl-kpi b { font-family: var(--font-display); font-weight: 400; font-size: 1.7rem; color: var(--c, var(--ink)); line-height: 1.1; } @media (max-width: 900px) { .odds-colours { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.pl-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr); gap: 16px; align-items: start; } @media (max-width: 560px) { .odds-colours { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 1050px) { .pl-grid { grid-template-columns: minmax(0, 1fr); } } .odd-colour { color: inherit; text-decoration: none; transition: transform .15s, box-shadow .15s; border-color: color-mix(in srgb, var(--c) 45%, var(--line)); }
.planner-shell { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--map-ground); --frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent), 0 0 30px color-mix(in srgb, var(--frame) 15%, transparent); } .odd-colour:hover, .odd-colour:focus-visible { transform: translateY(-2px); box-shadow: 0 0 22px color-mix(in srgb, var(--c) 30%, transparent); }
#planner-map { display: block; width: 100%; min-width: 760px; height: auto; background: #d9b07a; } .odd-art { width: 110px; height: 88px; max-width: none; }
.pl-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; padding: 10px 14px; border-top: 1px solid var(--line); background: var(--surface); } .odd .go { font-family: var(--font-label); letter-spacing: .12em; text-transform: uppercase; font-size: .68rem; color: var(--c); }
.pl-legend b { display: inline-block; width: 22px; height: 6px; border-radius: 3px; vertical-align: 2px; margin-right: 4px; } .ladder { padding: 16px 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); display: grid; gap: 10px; }
.pl-legend .sw-route { background: var(--vt, var(--accent)); box-shadow: 0 0 0 3px #fff1c955; } .ladder ol { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.pl-legend .sw-opt { background: repeating-linear-gradient(90deg, var(--vt, var(--accent)) 0 5px, transparent 5px 10px); opacity: 0.7; } .ladder li { display: grid; grid-template-columns: 70px minmax(0, 1fr) 48px; gap: 10px; align-items: center; font-size: var(--step--1); }
.pl-legend .sw-roll { background: repeating-linear-gradient(90deg, var(--muted) 0 2px, transparent 2px 8px); } .ladder li i { display: block; height: 10px; border-radius: 4px; width: var(--w); background: var(--c); }
.pl-legend .sw-risk { width: 12px; height: 12px; border-radius: 50%; background: var(--ember); vertical-align: -2px; } .ladder li b { font-family: var(--font-data); text-align: right; }
.pl-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; align-content: start; max-height: 920px; overflow: auto; } .combo { grid-template-columns: minmax(0, 1fr); }
.pl-step { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); }
.pl-step.chance { background: color-mix(in srgb, var(--surface) 82%, #000); border-style: dashed; }
.pl-step.end { border-color: color-mix(in srgb, var(--vt, var(--accent)) 50%, var(--line)); }
.pl-n { font-family: var(--font-display); color: var(--accent); font-size: 1.1rem; }
.pl-step h4 { font-family: var(--font-display); font-weight: 400; font-size: 1.02rem; margin: 0 0 6px; }
.pl-row { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(36px, 1fr) minmax(64px, auto); gap: 8px; align-items: center; width: 100%; text-align: left; background: transparent; border: 0; border-radius: 6px; padding: 4px 6px; color: var(--ink); font-family: var(--font-body); font-size: var(--step--1); text-transform: none; letter-spacing: normal; }
button.pl-row { cursor: pointer; }
button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent); }
.pl-row.taken { background: color-mix(in srgb, var(--accent) 14%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 45%, transparent); }
.pl-row i { display: block; height: 8px; border-radius: 3px; background: var(--c); width: var(--w); min-width: 2px; }
.pl-row .m { text-align: right; display: grid; }
.pl-row .m b { font-family: var(--font-data); font-weight: 600; }
.pl-row .m small { color: var(--muted); font-family: var(--font-data); font-size: 10.5px; white-space: nowrap; }
.pl-row .rec { font-style: normal; font-size: 9.5px; font-family: var(--font-label); letter-spacing: 0.1em; text-transform: uppercase; color: var(--bg); background: var(--accent); border-radius: 999px; padding: 1px 6px; margin-left: 4px; vertical-align: 1px; }
.pl-risk { color: var(--ember); margin: 0 0 4px; }
</style> </style>
<header class="hero"> <header class="hero">
@@ -361,29 +399,38 @@ button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent)
<span class="unofficial">Unofficial fan atlas for readers of Rebecca Yarros's <i>Fourth Wing</i> · not affiliated with Dragonkind</span> <span class="unofficial">Unofficial fan atlas for readers of Rebecca Yarros's <i>Fourth Wing</i> · not affiliated with Dragonkind</span>
</div> </div>
<nav class="tabs" role="tablist" aria-label="Atlas pages"> <nav class="tabs" role="tablist" aria-label="Atlas pages">
<button class="tab" role="tab" id="tab-overview" aria-controls="panel-overview" aria-selected="true">The Threshing</button> <button class="tab" role="tab" id="tab-valley" aria-controls="panel-valley" aria-selected="true">The Valley</button>
<button class="tab" role="tab" id="tab-planner" aria-controls="panel-planner" aria-selected="false">Route Planner</button> <button class="tab" role="tab" id="tab-odds" aria-controls="panel-odds" aria-selected="false">The Odds</button>
<button class="tab" role="tab" id="tab-valley" aria-controls="panel-valley" aria-selected="false">Valley Map</button>
<button class="tab" role="tab" id="tab-flow" aria-controls="panel-flow" aria-selected="false">Route Flow</button>
<button class="tab" role="tab" id="tab-rare" aria-controls="panel-rare" aria-selected="false">Blue &amp; Black</button>
<button class="tab" role="tab" id="tab-dragons" aria-controls="panel-dragons" aria-selected="false">The Dragons</button> <button class="tab" role="tab" id="tab-dragons" aria-controls="panel-dragons" aria-selected="false">The Dragons</button>
<button class="tab" role="tab" id="tab-deep" aria-controls="panel-deep" aria-selected="false">Deep Dive</button> <button class="tab" role="tab" id="tab-deep" aria-controls="panel-deep" aria-selected="false">Deep Dive</button>
<button class="tab" role="tab" id="tab-share" aria-controls="panel-share" aria-selected="false">Data &amp; Share</button> <button class="tab" role="tab" id="tab-data" aria-controls="panel-data" aria-selected="false">Data &amp; Methods</button>
</nav> </nav>
</div> </div>
</header> </header>
<div class="wrap"> <div class="wrap">
<main> <main>
<div class="tabpanel" id="panel-overview" role="tabpanel" aria-labelledby="tab-overview"> <div class="tabpanel" id="panel-valley" role="tabpanel" aria-labelledby="tab-valley">
<section id="valley-sec" aria-labelledby="h-valley" class="explorer">
<div class="ex-shell deco" id="ex-shell">
<div class="ex-map-wrap"><svg id="ex-map" viewBox="0 0 1000 790" role="application" aria-label="Map of the threshing valley. Choose a dragon to see the routes to it."></svg>
<div class="ex-hint" id="ex-hint">Choose a dragon to see the way to it</div>
<div class="ex-tip" id="ex-tip" hidden></div>
</div>
<aside class="ex-panel" id="ex-panel" aria-live="polite"></aside>
</div>
</section>
</div>
<div class="tabpanel" id="panel-odds" role="tabpanel" aria-labelledby="tab-odds" hidden>
<section id="overview" aria-labelledby="h-odds"> <section id="overview" aria-labelledby="h-odds">
<div class="section-head"> <div class="section-head">
<span class="eyebrow">Before you walk into the valley</span> <span class="eyebrow">Before you walk into the valley</span>
<h2 id="h-odds">Your odds, honestly</h2> <h2 id="h-odds">Your odds, honestly</h2>
<p class="muted small">Each grid of dots is 100 runs. These numbers lean on the riders who logged <i>every</i> run, including the dull ones, because people mostly share their lucky runs.</p> <p class="muted small">For each dragon: the chance a run ends bonded to it if you take the best route and die on purpose whenever it goes wrong. Each grid is 100 runs. The numbers lean on riders who logged <i>every</i> run, because people mostly share their lucky ones.</p>
</div> </div>
<div class="odds" id="odds"></div> <div class="odds odds-colours" id="odds-colours"></div>
<div class="combo" id="combo"></div> <div class="combo" id="combo"></div>
<div class="odds" id="odds"></div>
</section> </section>
<section aria-labelledby="h-journey"> <section aria-labelledby="h-journey">
<div class="section-head"> <div class="section-head">
@@ -394,119 +441,9 @@ button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent)
<p class="lore">In the books, first-years who survive to Threshing walk into a valley of unbonded dragons, and the dragons do the choosing. The Dragonkind site recreates that: every choice can end with you incinerated, and the author has said there is a 10% chance of that no matter what you pick.</p> <p class="lore">In the books, first-years who survive to Threshing walk into a valley of unbonded dragons, and the dragons do the choosing. The Dragonkind site recreates that: every choice can end with you incinerated, and the author has said there is a 10% chance of that no matter what you pick.</p>
</section> </section>
<section aria-labelledby="h-truths"> <section aria-labelledby="h-truths">
<div class="section-head"><span class="eyebrow">What 2,500 runs say</span><h2 id="h-truths">Three things worth knowing</h2></div> <div class="section-head"><span class="eyebrow" id="h-truths-kicker">What the runs say</span><h2 id="h-truths">Three things worth knowing</h2></div>
<div class="truths" id="truths"></div> <div class="truths" id="truths"></div>
<div class="cta"><button type="button" class="primary" data-go="valley">Walk the valley map</button><button type="button" data-go="rare">Chasing a Blue or Black?</button><button type="button" data-go="dragons">Meet the bonded dragons</button></div> <div class="cta"><button type="button" class="primary" data-go="valley">Walk the valley map</button><button type="button" data-go="deep">Dig into the statistics</button><button type="button" data-go="dragons">Meet the bonded dragons</button></div>
</section>
</div>
<div class="tabpanel" id="panel-planner" role="tabpanel" aria-labelledby="tab-planner" hidden>
<section id="planner-sec" aria-labelledby="h-planner">
<div class="section-head">
<span class="eyebrow">Interactive · the best route for each dragon, worked out from every logged run</span>
<h2 id="h-planner">Plan your run</h2>
<p class="muted small">Pick the dragon you want. The planner walks the valley with you: at every choice it shows each option's chance of bonding that dragon if you take it and then play the best route afterwards. At every roll of the dice it shows what can happen. Click any option, on the map or in the list, to see where another choice leads.</p>
</div>
<div class="controls planner-controls">
<div class="target-group"><span class="lbl small muted">I want</span><div class="targets" id="planner-colours"></div></div>
<div class="target-group"><span class="lbl small muted">Goal</span>
<div class="seg" id="planner-obj" role="group" aria-label="Goal">
<button type="button" data-o="eventually" aria-pressed="true" title="You will die on purpose and try again whenever the run goes wrong, so never risk ending on another dragon">Only this dragon, ever</button>
<button type="button" data-o="thisAttempt" aria-pressed="false" title="Maximise the chance on this one run, even if that risks a different dragon">Best odds this run</button>
</div></div>
<div class="target-group"><span class="lbl small muted">Data</span>
<div class="seg" id="planner-sample" role="group" aria-label="Data">
<button type="button" data-s="all" aria-pressed="true" title="Every logged run">All runs</button>
<button type="button" data-s="lowBias" aria-pressed="false" title="Only riders who logged every run, and riders not chasing a rare dragon (less selective reporting)">Low-bias</button>
</div></div>
<button type="button" id="planner-reset">Start again</button>
</div>
<div class="pl-head" id="planner-head"></div>
<div class="pl-grid">
<div class="planner-shell deco">
<div class="valley-wrap"><svg id="planner-map" viewBox="0 0 1000 790" role="img" aria-label="Valley map with the recommended route and the chance attached to every option"></svg></div>
<div class="legend small pl-legend"><span><b class="sw-route"></b> recommended route</span><span><b class="sw-opt"></b> other options, with the chance of your dragon if you take them</span><span><b class="sw-roll"></b> a roll of the dice</span><span><b class="sw-risk"></b> chance of being killed there</span></div>
</div>
<ol class="pl-steps" id="planner-steps" aria-label="Your run, step by step"></ol>
</div>
<p class="small muted">How this is worked out: every choice the community form records is a decision; which dragon appears, whether the shadow shows and who dies are rolls. Each roll's odds are allowed to depend on earlier choices, as much as the data support and no more (see Methods and <code>docs/POLICY.md</code>). "Alive" is the chance of reaching a bonding encounter at all. The bond chance inside each encounter is the community average, because the form does not record the answers given there.</p>
</section>
</div>
<div class="tabpanel" id="panel-valley" role="tabpanel" aria-labelledby="tab-valley" hidden>
<section id="valley-sec" aria-labelledby="h-valley">
<div class="section-head">
<span class="eyebrow">Interactive · drawn from the in-game descriptions, not an official map</span>
<h2 id="h-valley">The valley</h2>
<p class="muted small">Trails are as thick as the number of riders who walked them. Their colour shows how often walking that way ended with the dragon you pick below. Tap a place for what happened there.</p>
</div>
<div class="controls"><div class="target-group"><span class="lbl small muted">Colour the trails by</span><div class="targets" id="valley-targets"></div></div></div>
<div class="valley-shell deco">
<div class="valley-wrap"><svg id="valley" viewBox="0 0 1000 780" role="img" aria-label="Illustrated map of the threshing valley with trails"></svg></div>
<div class="valley-foot"><div class="loc-card" id="loc-card"></div><div class="legend" id="valley-legend"></div></div>
</div>
</section>
</div>
<div class="tabpanel" id="panel-flow" role="tabpanel" aria-labelledby="tab-flow" hidden>
<section id="map-sec" aria-labelledby="h-map">
<div class="section-head">
<span class="eyebrow">Interactive</span>
<h2 id="h-map">Route map</h2>
<p class="muted small">Pick an outcome. Click any box to keep only the runs that passed through it, and click more boxes to narrow further. Hover or tap a box or band for its numbers.</p>
</div>
<div class="controls" id="map-controls">
<div class="target-group">
<span class="lbl small muted">Rare dragons</span>
<div class="targets" id="targets-rare"></div>
</div>
<div class="target-group">
<span class="lbl small muted">Other outcomes</span>
<div class="targets" id="targets-other"></div>
</div>
</div>
<div class="controls">
<div class="ctl"><span class="lbl">Band width shows</span>
<div class="seg" id="width-mode"><button type="button" data-v="traffic" aria-pressed="true">How many runs</button><button type="button" data-v="prob" aria-pressed="false">Chance of outcome</button></div></div>
<div class="ctl"><label for="minn">Grey out steps with fewer runs than</label><input id="minn" type="number" min="1" max="200" value="10"></div>
<div class="ctl"><label for="f-source">Data source</label>
<select id="f-source"><option value="all">All rows</option><option value="form">Form submissions only</option><option value="bulk">Bulk logs only (imports)</option></select></div>
<div class="ctl"><label for="f-goal">Players chasing</label>
<select id="f-goal"><option value="all">Any goal</option><option value="exclude_rare">Not chasing Blue/Black</option><option value="only_rare">Chasing Blue/Black</option></select></div>
<label class="check" for="f-flag"><input id="f-flag" type="checkbox"> Drop rows with data-quality flags</label>
</div>
<div class="map-shell deco">
<div class="map-top">
<div class="cond-chips" id="cond-chips"><span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span></div>
<div class="btnrow"><button type="button" id="btn-best">Show top routes for this outcome</button><button type="button" id="btn-clear">Clear selection</button></div>
</div>
<div class="map-scroll"><svg id="map" role="img" aria-label="Route map"></svg></div>
<div class="map-foot">
<div class="sel-summary" id="sel-summary"></div>
<div class="legend" id="legend"></div>
</div>
</div>
<div id="best-routes"></div>
</section>
</div>
<div class="tabpanel" id="panel-rare" role="tabpanel" aria-labelledby="tab-rare" hidden>
<section id="rare" aria-labelledby="h-rare">
<div class="section-head">
<span class="eyebrow">Blue &amp; Black</span>
<h2 id="h-rare">The rare dragons</h2>
<p class="muted small">Two separate rolls. The meadow Blue can join the Orange and Brown after you turn down the valley Red. The tree's shadow option leads to a Blue and then a Black.</p>
</div>
<div class="grid2">
<div class="panel"><h3>Does the Blue show up in the meadow?</h3><p class="small muted">Share of meadow visits where a Blue was attempted, by who logged the run. The game cannot know which dragon a player is chasing, so gaps between these bars come from how people report, not from the game.</p><div class="chart" id="ch-blue-strata"></div></div>
<div class="panel"><h3>Does the shadow show up at the tree?</h3><p class="small muted">Share of tree climbs where the shadow option led to a Blue and/or Black.</p><div class="chart" id="ch-shadow-strata"></div></div>
</div>
<div class="grid2">
<div class="panel"><h3>What changes the Blue's appearance, once reporting bias is held fixed?</h3><p class="small muted">Adjusted odds ratios from one logistic model: route choices plus data source and chase goal. Bars that cross 1 mean no detectable effect.</p><div class="chart" id="ch-model-blue"></div><p class="small muted" id="model-blue-note"></p></div>
<div class="panel"><h3>What changes the shadow's appearance?</h3><p class="small muted">Same approach for the shadow. With so few shadows, intervals are wide.</p><div class="chart" id="ch-model-shadow"></div><p class="small muted" id="model-shadow-note"></p></div>
</div>
<div class="grid2">
<div class="panel"><h3>Day by day (form submissions)</h3><p class="small muted">Bulk imports carry no dates, so they are left out here. Dots are sized by the number of runs, and whiskers show 95% intervals.</p><div class="chart" id="ch-daily"></div></div>
<div class="panel"><h3>Bonding once you reach them</h3><div class="chart" id="ch-rare-bond"></div>
<details class="fold"><summary>Step-by-step survival inside the encounter (from the community PDF)</summary><div id="pdf-steps"></div></details>
</div>
</div>
</section> </section>
</div> </div>
<div class="tabpanel" id="panel-dragons" role="tabpanel" aria-labelledby="tab-dragons" hidden> <div class="tabpanel" id="panel-dragons" role="tabpanel" aria-labelledby="tab-dragons" hidden>
@@ -548,6 +485,66 @@ button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent)
</section> </section>
</div> </div>
<div class="tabpanel" id="panel-deep" role="tabpanel" aria-labelledby="tab-deep" hidden> <div class="tabpanel" id="panel-deep" role="tabpanel" aria-labelledby="tab-deep" hidden>
<section id="map-sec" aria-labelledby="h-map">
<div class="section-head">
<span class="eyebrow">Interactive</span>
<h2 id="h-map">Route map</h2>
<p class="muted small">Pick an outcome. Click any box to keep only the runs that passed through it, and click more boxes to narrow further. Hover or tap a box or band for its numbers.</p>
</div>
<div class="controls" id="map-controls">
<div class="target-group">
<span class="lbl small muted">Rare dragons</span>
<div class="targets" id="targets-rare"></div>
</div>
<div class="target-group">
<span class="lbl small muted">Other outcomes</span>
<div class="targets" id="targets-other"></div>
</div>
</div>
<div class="controls">
<div class="ctl"><span class="lbl">Band width shows</span>
<div class="seg" id="width-mode"><button type="button" data-v="traffic" aria-pressed="true">How many runs</button><button type="button" data-v="prob" aria-pressed="false">Chance of outcome</button></div></div>
<div class="ctl"><label for="minn">Grey out steps with fewer runs than</label><input id="minn" type="number" min="1" max="200" value="10"></div>
<div class="ctl"><label for="f-source">Data source</label>
<select id="f-source"><option value="all">All rows</option><option value="form">Form submissions only</option><option value="bulk">Bulk logs only (imports)</option></select></div>
<div class="ctl"><label for="f-goal">Players chasing</label>
<select id="f-goal"><option value="all">Any goal</option><option value="exclude_rare">Not chasing Blue/Black</option><option value="only_rare">Chasing Blue/Black</option></select></div>
<label class="check" for="f-flag"><input id="f-flag" type="checkbox"> Drop rows with data-quality flags</label>
</div>
<div class="map-shell deco">
<div class="map-top">
<div class="cond-chips" id="cond-chips"><span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span></div>
<div class="btnrow"><button type="button" id="btn-best">Show top routes for this outcome</button><button type="button" id="btn-clear">Clear selection</button></div>
</div>
<div class="map-scroll"><svg id="map" role="img" aria-label="Route map"></svg></div>
<div class="map-foot">
<div class="sel-summary" id="sel-summary"></div>
<div class="legend" id="legend"></div>
</div>
</div>
<div id="best-routes"></div>
</section>
<section id="rare" aria-labelledby="h-rare">
<div class="section-head">
<span class="eyebrow">Blue &amp; Black</span>
<h2 id="h-rare">The rare dragons</h2>
<p class="muted small">Two separate rolls. The meadow Blue can join the Orange and Brown after you turn down the valley Red. The tree's shadow option leads to a Blue and then a Black.</p>
</div>
<div class="grid2">
<div class="panel"><h3>Does the Blue show up in the meadow?</h3><p class="small muted">Share of meadow visits where a Blue was attempted, by who logged the run. The game cannot know which dragon a player is chasing, so gaps between these bars come from how people report, not from the game.</p><div class="chart" id="ch-blue-strata"></div></div>
<div class="panel"><h3>Does the shadow show up at the tree?</h3><p class="small muted">Share of tree climbs where the shadow option led to a Blue and/or Black.</p><div class="chart" id="ch-shadow-strata"></div></div>
</div>
<div class="grid2">
<div class="panel"><h3>What changes the Blue's appearance, once reporting bias is held fixed?</h3><p class="small muted">Adjusted odds ratios from one logistic model: route choices plus data source and chase goal. Bars that cross 1 mean no detectable effect.</p><div class="chart" id="ch-model-blue"></div><p class="small muted" id="model-blue-note"></p></div>
<div class="panel"><h3>What changes the shadow's appearance?</h3><p class="small muted">Same approach for the shadow. With so few shadows, intervals are wide.</p><div class="chart" id="ch-model-shadow"></div><p class="small muted" id="model-shadow-note"></p></div>
</div>
<div class="grid2">
<div class="panel"><h3>Day by day (form submissions)</h3><p class="small muted">Bulk imports carry no dates, so they are left out here. Dots are sized by the number of runs, and whiskers show 95% intervals.</p><div class="chart" id="ch-daily"></div></div>
<div class="panel"><h3>Bonding once you reach them</h3><div class="chart" id="ch-rare-bond"></div>
<details class="fold"><summary>Step-by-step survival inside the encounter (from the community PDF)</summary><div id="pdf-steps"></div></details>
</div>
</div>
</section>
<section id="findings" aria-labelledby="h-findings"> <section id="findings" aria-labelledby="h-findings">
<div class="section-head"> <div class="section-head">
<span class="eyebrow">What the data supports</span> <span class="eyebrow">What the data supports</span>
@@ -581,6 +578,26 @@ button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent)
</div> </div>
<div class="grid3" id="quality-panels"></div> <div class="grid3" id="quality-panels"></div>
</section> </section>
</div>
<div class="tabpanel" id="panel-data" role="tabpanel" aria-labelledby="tab-data" hidden>
<section id="data-sec" aria-labelledby="h-data">
<div class="section-head"><span class="eyebrow">Where the numbers come from</span><h2 id="h-data">Data</h2></div>
<div class="data-status" id="data-status"><span class="loading">Loading data…</span></div>
<div class="btnrow"><label class="filebtn" for="upload">Load a newer route export…<input id="upload" type="file" accept=".xlsx,.csv" hidden></label><button id="btn-reset-data" type="button" hidden>Back to bundled data</button></div>
</section>
<section id="share" aria-labelledby="h-share">
<div class="section-head"><span class="eyebrow">Open by design</span><h2 id="h-share">Share &amp; reproduce</h2>
<p class="muted small">Everything on this page is recomputed in your browser from the raw form export. To update it, download the latest responses sheet (File → Download → Microsoft Excel) and load it with "Load a newer export" at the top. Column order does not matter, because questions are matched by their wording.</p></div>
<div class="grid2">
<div class="panel"><h3>Copy the outputs</h3>
<div class="btnrow"><button type="button" id="cp-reddit" class="primary">Copy Reddit post (Markdown)</button><button type="button" id="cp-csv">Copy coded runs (CSV)</button><button type="button" id="cp-json">Copy all results (JSON)</button></div>
<p class="small muted">The Reddit post is written from the current numbers and filters.</p></div>
<div class="panel"><h3>Read the code</h3>
<div class="btnrow"><button type="button" data-src="engine.js">engine.js (all rules and statistics)</button><button type="button" data-src="app.js">app.js (this page)</button><button type="button" data-src="python/clean.py">clean.py</button><button type="button" data-src="python/analyze.py">analyze.py</button><button type="button" data-src="python/stats_core.py">stats_core.py</button><button type="button" data-src="register.js">register.js</button><button type="button" data-src="README.md">README</button></div>
<p class="small muted">The Python files are an independent second implementation. The test scripts confirm that both produce identical coded runs and identical odds ratios, p-values and model estimates.</p>
<pre id="srcview" hidden></pre></div>
</div>
</section>
<section id="methods" aria-labelledby="h-methods" class="method"> <section id="methods" aria-labelledby="h-methods" class="method">
<div class="section-head"><span class="eyebrow">How every number is made</span><h2 id="h-methods">Methods</h2></div> <div class="section-head"><span class="eyebrow">How every number is made</span><h2 id="h-methods">Methods</h2></div>
<div class="grid2"> <div class="grid2">
@@ -629,26 +646,6 @@ adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ)</div>
</div> </div>
</section> </section>
</div> </div>
<div class="tabpanel" id="panel-share" role="tabpanel" aria-labelledby="tab-share" hidden>
<section id="data-sec" aria-labelledby="h-data">
<div class="section-head"><span class="eyebrow">Where the numbers come from</span><h2 id="h-data">Data</h2></div>
<div class="data-status" id="data-status"><span class="loading">Loading data…</span></div>
<div class="btnrow"><label class="filebtn" for="upload">Load a newer route export…<input id="upload" type="file" accept=".xlsx,.csv" hidden></label><button id="btn-reset-data" type="button" hidden>Back to bundled data</button></div>
</section>
<section id="share" aria-labelledby="h-share">
<div class="section-head"><span class="eyebrow">Open by design</span><h2 id="h-share">Share &amp; reproduce</h2>
<p class="muted small">Everything on this page is recomputed in your browser from the raw form export. To update it, download the latest responses sheet (File → Download → Microsoft Excel) and load it with "Load a newer export" at the top. Column order does not matter, because questions are matched by their wording.</p></div>
<div class="grid2">
<div class="panel"><h3>Copy the outputs</h3>
<div class="btnrow"><button type="button" id="cp-reddit" class="primary">Copy Reddit post (Markdown)</button><button type="button" id="cp-csv">Copy coded runs (CSV)</button><button type="button" id="cp-json">Copy all results (JSON)</button></div>
<p class="small muted">The Reddit post is written from the current numbers and filters.</p></div>
<div class="panel"><h3>Read the code</h3>
<div class="btnrow"><button type="button" data-src="engine.js">engine.js (all rules and statistics)</button><button type="button" data-src="app.js">app.js (this page)</button><button type="button" data-src="python/clean.py">clean.py</button><button type="button" data-src="python/analyze.py">analyze.py</button><button type="button" data-src="python/stats_core.py">stats_core.py</button><button type="button" data-src="register.js">register.js</button><button type="button" data-src="README.md">README</button></div>
<p class="small muted">The Python files are an independent second implementation. The test scripts confirm that both produce identical coded runs and identical odds ratios, p-values and model estimates.</p>
<pre id="srcview" hidden></pre></div>
</div>
</section>
</div>
</main> </main>
</div> </div>
<footer><div class="wrap"><p>Data: the community "Threshing Routes" Google Form and spreadsheet compiled by u/ClumsyBadger, with percentages in the route PDF by u/ClumsyBadger, u/Old_Regular3018 and u/Smart_Trifle_2099. This is an unofficial fan analysis, not affiliated with the Dragonkind site or its authors. A 10% "chaos" chance of incineration on any choice has been described by the author, so no route guarantees a bond.</p></div></footer> <footer><div class="wrap"><p>Data: the community "Threshing Routes" Google Form and spreadsheet compiled by u/ClumsyBadger, with percentages in the route PDF by u/ClumsyBadger, u/Old_Regular3018 and u/Smart_Trifle_2099. This is an unofficial fan analysis, not affiliated with the Dragonkind site or its authors. A 10% "chaos" chance of incineration on any choice has been described by the author, so no route guarantees a bond.</p></div></footer>
@@ -659,5 +656,6 @@ adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ)</div>
<script src="register.js"></script> <script src="register.js"></script>
<script src="app.js"></script> <script src="app.js"></script>
<script src="valley.js"></script> <script src="valley.js"></script>
<script src="planner.js"></script> <script src="dragons.js"></script>
<script src="explorer.js"></script>
<script src="ui.js"></script> <script src="ui.js"></script>
-295
View File
@@ -1,295 +0,0 @@
/* 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 };
})();
+64 -39
View File
@@ -26,9 +26,12 @@
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); } function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ tabs // ------------------------------------------------------------ tabs
const TABS = ["overview", "planner", "valley", "flow", "rare", "dragons", "deep", "share"]; const TABS = ["valley", "odds", "dragons", "deep", "data"];
function showTab(name, focus) { // old links (#overview, #flow, #planner ...) still land somewhere sensible
if (!TABS.includes(name)) name = "overview"; const ALIAS = { overview: "odds", planner: "valley", flow: "deep", rare: "deep", share: "data" };
const tabOf = (hash) => { const t = (hash || "").replace(/^#/, "").split("/")[0]; return TABS.includes(t) ? t : ALIAS[t] || null; };
function showTab(name, focus, keepHash) {
if (!TABS.includes(name)) name = ALIAS[name] || "valley";
TABS.forEach((t) => { TABS.forEach((t) => {
const on = t === name; const on = t === name;
$("#tab-" + t).setAttribute("aria-selected", on); $("#tab-" + t).setAttribute("aria-selected", on);
@@ -37,8 +40,9 @@
}); });
if (focus) $("#tab-" + name).focus(); if (focus) $("#tab-" + name).focus();
try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ } try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ }
try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } if (!keepHash) { try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } }
if (name === "flow" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize")); if (name === "valley" && window.ValleyExplorer) window.ValleyExplorer.fromHash();
if (name === "deep" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize"));
} }
TABS.forEach((t, i) => { TABS.forEach((t, i) => {
const b = $("#tab-" + t); const b = $("#tab-" + t);
@@ -56,14 +60,15 @@
const a = e.target.closest('a[href^="#"]'); const a = e.target.closest('a[href^="#"]');
if (!a) return; if (!a) return;
const id = a.getAttribute("href").slice(1); const id = a.getAttribute("href").slice(1);
if (TABS.includes(id)) { e.preventDefault(); showTab(id); return; } if (tabOf(id)) { e.preventDefault(); showTab(tabOf(id)); return; }
const target = document.getElementById(id); const target = document.getElementById(id);
const panel = target && target.closest(".tabpanel"); const panel = target && target.closest(".tabpanel");
if (panel && panel.hidden) { e.preventDefault(); showTab(panel.id.replace("panel-", "")); target.scrollIntoView({ behavior: "smooth" }); } if (panel && panel.hidden) { e.preventDefault(); showTab(panel.id.replace("panel-", "")); target.scrollIntoView({ behavior: "smooth" }); }
}); });
window.addEventListener("hashchange", () => { const h = location.hash.slice(1); if (TABS.includes(h)) showTab(h); }); // #valley/blue/meadow-Blue keeps its sub-path (the explorer reads it)
const initial = (location.hash || "").slice(1); window.addEventListener("hashchange", () => { const t = tabOf(location.hash); if (t) showTab(t, false, t === "valley"); });
showTab(TABS.includes(initial) ? initial : "overview"); const initial = tabOf(location.hash);
showTab(initial || "valley", false, initial === "valley");
// ------------------------------------------------------------ hero art (original, generic silhouettes) // ------------------------------------------------------------ hero art (original, generic silhouettes)
function drawHero() { function drawHero() {
@@ -117,59 +122,79 @@
} }
return svg.outerHTML; return svg.outerHTML;
} }
// The odds for all six dragons come from the route model (data/policy.json); fetched once.
let policyP = null;
const getPolicy = () => policyP || (policyP = fetch("data/policy.json").then((r) => r.json()).catch(() => null));
const ENC_OF = { Red: "valley-Red", Orange: "meadow-Orange", Brown: "meadow-Brown", Green: "tree-Greens", Blue: "meadow-Blue", Black: "shadow-Black" };
const ENC_LABEL = { "valley-Red": "the valley Red", "meadow-Orange": "the meadow Orange", "meadow-Brown": "the meadow Brown", "tree-Greens": "the two Greens", "meadow-Blue": "the meadow Blue", "shadow-Black": "the Black, after the shadow" };
const POSE = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" };
function renderColourOdds(policy) {
if (!policy) { $("#odds-colours").innerHTML = '<p class="small muted">The route model could not be loaded.</p>'; return; }
const lb = policy.samples.lowBias, all = policy.samples.all;
const cols = ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
.map((c) => ({ c, p: lb.targets[c].eventually.pX.mean, pAll: all.targets[c].eventually.pX.mean, lo: lb.targets[c].eventually.pX.lo, hi: lb.targets[c].eventually.pX.hi }))
.sort((a, b) => b.p - a.p);
const enc = (c) => { const e = (all.model.tables.encounter || {})[ENC_OF[c]] || { outcomes: {} }; const n = Object.values(e.outcomes).reduce((a, b) => a + b, 0); return { k: e.outcomes[c] || 0, n }; };
const art = (c) => window.DragonArt ? `<svg class="odd-art" viewBox="0 0 200 160" aria-hidden="true">${window.DragonArt.svg(POSE[c], { fill: `var(${DV[c]})`, eyeFill: "var(--bg)" })}</svg>` : "";
$("#odds-colours").innerHTML = cols.map(({ c, p, pAll, lo, hi }) => {
const e = enc(c);
return `<a class="odd odd-colour" href="#valley/${c.toLowerCase()}" style="--c: var(${DV[c]})">${art(c)}
<span class="big">1 in ${oneIn(p)}</span><span class="what">runs end bonded to ${/^[AEIOU]/.test(c) ? "an" : "a"} ${c}, on the best route</span>
${dots(Math.round(p * 1000), 1000, cssVar(DV[c]))}
<span class="how">${pct(p, p < 0.1 ? 1 : 0)} per attempt (95% ${pct(lo, 1)}–${pct(hi, 1)}), from riders who logged every run${Math.abs(pAll - p) / p > 0.25 ? `; all form posts suggest ${pct(pAll, 1)}` : ""}. At ${ENC_LABEL[ENC_OF[c]]}, ${e.k} of ${e.n} genuine attempts bonded.</span>
<span class="go">See the route →</span></a>`;
}).join("");
$("#combo").innerHTML = `<div class="ladder"><span class="eyebrow">Easiest to hardest, in attempts on the best route</span><ol>${cols.map(({ c, p }) =>
`<li style="--c: var(${DV[c]}); --w: ${Math.min(100, (100 * Math.log(1 / p + 1)) / Math.log(1 / cols[cols.length - 1].p + 1)).toFixed(1)}%"><span>${c}</span><i></i><b>${oneIn(p)}</b></li>`).join("")}</ol>
<p class="small muted">If you die on purpose whenever a run goes wrong and keep trying, this is about how many attempts each dragon takes. Each attempt costs a cooldown.</p></div>`;
const meadowAlpha = all.model.alphas.meadow, shadowAlpha = all.model.alphas.shadow;
const t2 = $("#truth-history");
if (t2) t2.innerHTML = `<h3>Earlier choices barely change who waits</h3><p class="small">${meadowAlpha >= 10000 ? "Which dragon waits in the meadow shows no link to anything you chose before." : "Which dragon waits in the meadow depends only a little on earlier choices."} ${shadowAlpha >= 500 ? "The shadow at the tree depends on them only weakly." : "The shadow at the tree shows some dependence on earlier choices, but the evidence is thin."} The model lets every roll depend on your history, and measured how much it does. Choices the form doesn't record (what you answered inside an encounter) might still matter.</p>`;
const t3 = $("#truth-burn");
if (t3) {
const rates = cols.map(({ c }) => ({ c, ...enc(c) })).filter((x) => x.n >= 20).map((x) => ({ ...x, p: x.k / x.n })).sort((a, b) => a.p - b.p);
t3.innerHTML = `<h3>The right answer can still burn</h3><p class="small">Even with the community's best answers, bond chances at the encounter run from ${pct(rates[0].p)} (${esc(ENC_LABEL[ENC_OF[rates[0].c]])}) to ${pct(rates[rates.length - 1].p)} (${esc(ENC_LABEL[ENC_OF[rates[rates.length - 1].c]])}). One death with the "right" answer doesn't mean the answer was wrong.</p>`;
}
}
function renderOverview(state) { function renderOverview(state) {
const r = state.res; const r = state.res;
const reach = r.factors.reach_hour.overall; const reach = r.factors.reach_hour.overall;
const cb = r.chance.blue_meadow, cs = r.chance.shadow; const cb = r.chance.blue_meadow;
const bulkB = stratum(cb, "Bulk"), bulkS = stratum(cs, "Bulk"); const bulkB = stratum(cb, "Bulk");
const blueSeen = bulkB && bulkB.n >= 30 ? bulkB : cb.overall;
const shadow = bulkS && bulkS.n >= 30 ? bulkS : cs.overall;
const encB = r.encounters.find((e) => e.context === "Blue (meadow)").overall;
const encK = r.encounters.find((e) => e.context === "Black (shadow)").overall;
const shadowP = shadow.k === 0 ? shadow.hi : shadow.p;
const tag = (txt) => `<span class="how">${txt}</span>`; const tag = (txt) => `<span class="how">${txt}</span>`;
const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0);
const cards = [ const cards = [
{ c: "--accent", big: pct(reach.p), what: "reach the hour alive", how: `${reach.k.toLocaleString()} of ${reach.n.toLocaleString()} logged runs made it past the cadets to the tree-or-valley choice.`, w: reach }, { c: "--accent", big: pct(reach.p), what: "reach the hour alive", how: `${reach.k.toLocaleString()} of ${reach.n.toLocaleString()} logged runs made it past the cadets to the tree-or-valley choice.`, w: reach },
{ c: DV.Blue, big: `1 in ${oneIn(blueSeen.p)}`, what: "meadow visits has a Blue", how: blueSeen === bulkB ? `From riders who logged every run (${blueSeen.k}/${blueSeen.n}). The spreadsheet's headline says ${pct(cb.overall.p)}, inflated by lucky runs being shared more.` : `${blueSeen.k}/${blueSeen.n} meadow visits.`, w: blueSeen }, { c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / r.n)} of logged runs ended in fire or worse. Most were riders dying on purpose to try again.`, w: { k: dead, n: r.n }, death: true },
{ c: DV.Blue, big: pct(encB.p), what: "of Blue attempts end in a bond", how: `${encB.k} of ${encB.n}. Riders who reached a Blue were usually burned, even with the community's best answers.`, w: encB },
{ c: DV.Black, big: shadow.k === 0 ? `< ${pct(shadow.hi, 0)}` : `1 in ${oneIn(shadow.p)}`, what: "of tree climbs show the shadow", how: shadow === bulkS ? `Riders who logged every climb saw it ${shadow.k} times in ${shadow.n}. Form posts show more (${pct(cs.overall.p, 1)}), again because lucky runs get shared.` : `${shadow.k}/${shadow.n} tree climbs.`, w: shadow, scale: 1000 },
{ c: DV.Black, big: pct(encK.p), what: "of riders who meet the Black bond it", how: `${encK.k} of ${encK.n}. Getting there is the hard part.`, w: encK },
]; ];
const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0); $("#odds").innerHTML = cards.map((c) => `<div class="odd${c.death ? " death deco" : ""}" style="--c: var(${c.c})"><span class="big">${esc(c.big)}</span><span class="what">${esc(c.what)}</span>${dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
cards.push({ c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / r.n)} of logged runs ended in fire or worse. Most were riders dying on purpose to try again.`, w: { k: dead, n: r.n }, death: true }); getPolicy().then(renderColourOdds);
$("#odds").innerHTML = cards.map((c) => `<div class="odd${c.death ? " death deco" : ""}" style="--c: var(${c.c})"><span class="big">${esc(c.big)}</span><span class="what">${esc(c.what)}</span>${c.scale ? "" : dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
const pBlueRun = blueSeen.p * encB.p, pBlackRun = shadowP * encK.p;
$("#combo").innerHTML = `
<div class="odd" style="--c: var(${DV.Blue})"><span class="big">≈ 1 in ${oneIn(pBlueRun)}</span><div><div class="what">valley runs ends bonded to a Blue</div>${tag(`A Blue has to show up (about ${pct(blueSeen.p)}) and then accept you (about ${pct(encB.p)}).`)}</div></div>
<div class="odd" style="--c: var(${DV.Black})"><span class="big">${shadow.k === 0 ? "<" : "≈"} 1 in ${oneIn(pBlackRun)}</span><div><div class="what">tree climbs ends bonded to a Black</div>${tag(`The shadow has to appear (${shadow.k === 0 ? "under " + pct(shadow.hi, 1) : "about " + pct(shadow.p, 1)}) and the Black has to accept you (about ${pct(encK.p)}).`)}</div></div>`;
// journey // journey
const fr = r.factors.reach_hour.rows; const fr = r.factors.reach_hour.rows;
const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l); const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l);
const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates"); const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates");
const helpK = lvl("resolution", "DIED in combat"); const helpK = lvl("resolution", "DIED in combat");
const mb = r.models.blue_meadow;
const routeSig = mb ? mb.terms.filter((t) => ["direction", "first_sighting", "resolution", "company"].includes(t.factor) && t.p < 0.05 && !/Unsure|Unknown|Multiple/.test(t.level)) : [];
const fork = r.factors.shadow.rows.find((x) => x.factor === "post_path" && x.level === "Forest");
const rest = r.factors.shadow.rows.filter((x) => x.factor === "post_path" && x.level !== "Forest");
const restK = rest.reduce((a, x) => a + x.k, 0), restN = rest.reduce((a, x) => a + x.n, 0);
const greens = r.green_rescue; const greens = r.green_rescue;
const stops = [ const stops = [
{ t: "Choose company", d: "Go in alone, or with one or two squadmates.", v: alone && two ? `Alone, ${pct(alone.p)} reached the hour. With two squadmates, ${pct(two.p)} did.` : "" }, { t: "Choose company", d: "Go in alone, or with one or two squadmates.", v: alone && two ? `Alone, ${pct(alone.p)} reached the hour. With two squadmates, ${pct(two.p)} did.` : "" },
{ t: "Pick a direction", d: "East toward the roar, west toward the scent, or the forest centre.", v: routeSig.some((x) => x.factor === "direction") ? "Direction shows some link to the Blue." : "No sign that direction changes your Blue odds." }, { t: "Pick a direction", d: "East toward the roar, west toward the scent, or the forest centre.", v: "Direction decides which first dragon can find you." },
{ t: "The first dragon", d: "A dragon finds you. Which colour is the game's roll, not yours.", v: "Keep your eyes down. This one is about surviving, not bonding.", roll: true }, { t: "The first dragon", d: "A dragon finds you. Which colour is the game's roll, not yours.", v: "Keep your eyes down. This one is about surviving, not bonding.", roll: true },
{ t: "The scream", d: "Help the squadmate fighting two cadets, walk away, or ignore it and find a wounded cadet.", v: helpK ? `${helpK.n} logged runs died in the fight.` : "" }, { t: "The scream", d: "Help the squadmate fighting two cadets, walk away, or ignore it and find a wounded cadet.", v: helpK ? `${helpK.n} logged runs died in the fight.` : "" },
{ t: "Fork in the road", d: "After the fight: west, deeper into the forest, or east.", v: fork && restN ? `Shadows came from "deeper" ${pct(fork.p, 1)} of the time, vs ${pct(restK / restN, 1)} otherwise. A lead, not proof.` : "" }, { t: "Fork in the road", d: "After the fight: west, deeper into the forest, or east.", v: "Only the bully path has a fork." },
{ t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds Reds, Greens and the rare shadow. The valley holds Red, Orange, Brown and the meadow Blue." }, { t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds a Red, two Greens and the rare shadow. The valley holds a Red, then the meadow's Orange, Brown and sometimes a Blue." },
{ t: "The bonding", d: "Who is waiting is partly luck. Then every answer is a test.", v: greens.green_encounters ? `At the two Greens, ${pct((greens.rescued_orange + greens.rescued_brown) / greens.green_encounters)} were rescued by an Orange or Brown.` : "", roll: true }, { t: "The bonding", d: "Who is waiting is partly luck. Then every answer is a test.", v: greens.green_encounters ? `At the two Greens, ${pct((greens.rescued_orange + greens.rescued_brown) / greens.green_encounters)} were rescued by an Orange or Brown.` : "", roll: true },
]; ];
$("#journey").innerHTML = stops.map((s, i) => `<div class="stop${s.roll ? " roll" : ""}"><span class="n">${["I", "II", "III", "IV", "V", "VI", "VII"][i]}</span><span class="t">${esc(s.t)}</span><span class="d">${esc(s.d)}</span>${s.v ? `<span class="verdict">${esc(s.v)}</span>` : ""}</div>`).join(""); $("#journey").innerHTML = stops.map((s, i) => `<div class="stop${s.roll ? " roll" : ""}"><span class="n">${["I", "II", "III", "IV", "V", "VI", "VII"][i]}</span><span class="t">${esc(s.t)}</span><span class="d">${esc(s.d)}</span>${s.v ? `<span class="verdict">${esc(s.v)}</span>` : ""}</div>`).join("");
const chase = stratum(cb, "Form: chasing Blue"); const chase = stratum(cb, "Form: chasing Blue");
$("#truths").innerHTML = ` $("#truths").innerHTML = `
<div class="truth"><h3>Lucky runs get shared</h3><p class="small">Riders hunting a rare dragon logged a Blue in ${pct(chase ? chase.p : null)} of their meadow visits. Riders who logged every run saw it in ${pct(bulkB ? bulkB.p : null)}. The game can't know what you're chasing, so the difference is who chose to write in.</p></div> <div class="truth"><h3>Lucky runs get shared</h3><p class="small">Riders hunting a rare dragon logged a Blue in ${pct(chase ? chase.p : null)} of their meadow visits. Riders who logged every run saw it in ${pct(bulkB ? bulkB.p : null)}. The game can't know what you're chasing, so the difference is who chose to write in. The odds above lean on the riders who logged every run.</p></div>
<div class="truth"><h3>No secret route to the Blue, so far</h3><p class="small">${routeSig.length ? `A few recorded choices showed a link: ${esc(routeSig.map((t) => t.term).join(", "))}.` : "Once that reporting bias is accounted for, none of the recorded choices (direction, first dragon, the cadets, company) changed how often the Blue appeared."} Choices the form doesn't record might still matter.</p></div> <div class="truth" id="truth-history"></div>
<div class="truth"><h3>The right answer can still burn</h3><p class="small">Only ${pct(encB.p)} of Blue attempts bonded, about what the community's step-by-step odds predict. One death with the "right" answer doesn't mean the answer was wrong. Try again in four hours.</p></div>`; <div class="truth" id="truth-burn"></div>`;
$("#h-truths-kicker").textContent = `What ${r.n.toLocaleString()} runs say`;
$("#hero-tagline").textContent = `Every path through the valley, mapped from ${r.n.toLocaleString()} runs riders logged.`; $("#hero-tagline").textContent = `Every path through the valley, mapped from ${r.n.toLocaleString()} runs riders logged.`;
} }
@@ -186,7 +211,7 @@
window.AtlasUI = { window.AtlasUI = {
render(state) { render(state) {
renderOverview(state); renderOverview(state);
if (window.ValleyMap) window.ValleyMap.render(state); if (window.ValleyExplorer) window.ValleyExplorer.setRuns(state);
}, },
showTab, showTab,
}; };
+1 -1
View File
@@ -241,7 +241,7 @@
const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour"; const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour";
function render(state) { function render(state) {
if (!state || !state.res) return; if (!state || !state.res || !$("#valley")) return;
lastState = state; lastState = state;
renderTargets(); renderTargets();
const svg = $("#valley"); const svg = $("#valley");
+17 -7
View File
@@ -282,7 +282,9 @@
* Returns the value at the root and a decide(name, h) function giving the best option at any history. * Returns the value at the root and a decide(name, h) function giving the best option at any history.
* `support` lists the options allowed at each decision (options without enough data are left out). * `support` lists the options allowed at each decision (options without enough data are left out).
*/ */
function solve(params, X, { lam = 0, support = DECISIONS, record = false } = {}) { function solve(params, X, { lam = 0, support = DECISIONS, record = false, only = null } = {}) {
// only: bond only at these encounters (e.g. ["meadow-Blue"]); everywhere else the rider dies on purpose
const encOptions = (ctx) => (only && !only.includes(ctx) ? ["Die on purpose"] : support.encounter);
const score = (v) => (1 - lam) * v.x - lam * v.o + 1e-9 * v.x - 1e-12 * v.o; const score = (v) => (1 - lam) * v.x - lam * v.o + 1e-9 * v.x - 1e-12 * v.o;
const memo = new Map(); const memo = new Map();
const choices = new Map(); const choices = new Map();
@@ -306,7 +308,7 @@
const mix = (dist, f) => Object.entries(dist).reduce((acc, [k, p]) => (p ? add(acc, f(k), p) : acc), ZERO); const mix = (dist, f) => Object.entries(dist).reduce((acc, [k, p]) => (p ? add(acc, f(k), p) : acc), ZERO);
const die = () => ZERO; const die = () => ZERO;
const encounter = (h, ctx) => best("encounter", { ...h, enc: ctx }, support.encounter, (o) => { const encounter = (h, ctx) => best("encounter", { ...h, enc: ctx }, encOptions(ctx), (o) => {
if (o === "Die on purpose") return REACHED; if (o === "Die on purpose") return REACHED;
const d = params.encounter(ctx); const d = params.encounter(ctx);
let x = 0, oth = 0; let x = 0, oth = 0;
@@ -601,12 +603,12 @@
* It re-solves the model locally (a few milliseconds), so it can advise from ANY history, including histories * It re-solves the model locally (a few milliseconds), so it can advise from ANY history, including histories
* that already left the recommended route. * that already left the recommended route.
*/ */
function advisor(sample, X, objective = "eventually") { function advisor(sample, X, objective = "eventually", { only = null } = {}) {
const m = sample.model; const m = sample.model;
const params = makeParams(m.tables, { mode: "mean", alphas: m.alphas }); const params = makeParams(m.tables, { mode: "mean", alphas: m.alphas });
const sol = objective === "eventually" const sol = objective === "eventually"
? (() => { const r = solveRatio(params, X, { support: m.support }); return solve(params, X, { support: m.support, lam: r.lam, record: true }); })() ? (() => { const r = solveRatio(params, X, { support: m.support, only }); return solve(params, X, { support: m.support, lam: r.lam, record: true, only }); })()
: solve(params, X, { support: m.support, record: true }); : solve(params, X, { support: m.support, record: true, only });
const opts = (name, key) => Object.fromEntries(Object.entries(sol.optionValues(name, key) || {}).map(([o, v]) => [o, { pX: v.x, pOther: v.o, pReach: v.r }])); const opts = (name, key) => Object.fromEntries(Object.entries(sol.optionValues(name, key) || {}).map(([o, v]) => [o, { pX: v.x, pOther: v.o, pReach: v.r }]));
const dec = (name, key, extra = {}) => ({ kind: "decision", var: name, label: LABEL[name], choice: sol.decide(name, key), options: opts(name, key), ...extra }); const dec = (name, key, extra = {}) => ({ kind: "decision", var: name, label: LABEL[name], choice: sol.decide(name, key), options: opts(name, key), ...extra });
const cha = (name, key, extra = {}) => ({ kind: "chance", var: name, label: LABEL[name], probs: params.chance(name, key), ...extra }); const cha = (name, key, extra = {}) => ({ kind: "chance", var: name, label: LABEL[name], probs: params.chance(name, key), ...extra });
@@ -653,7 +655,9 @@
return { kind: "end", encounter: enc, action: h.encounter, outcomes: h.encounter === "Die on purpose" ? { burn: 1 } : params.encounter(enc) }; return { kind: "end", encounter: enc, action: h.encounter, outcomes: h.encounter === "Die on purpose" ? { burn: 1 } : params.encounter(enc) };
} }
return { return {
colour: X, objective, value: sol.value, step, colour: X, objective, only, value: sol.value, step,
/** attempts recorded at an encounter (genuine attempts only), to show how much data a bond chance rests on */
attempts: (ctx) => Object.values(((m.tables.encounter || {})[ctx] || { outcomes: {} }).outcomes).reduce((a, b) => a + b, 0),
next(h) { next(h) {
const nd = nextDecision(h); const nd = nextDecision(h);
if (!nd) return null; if (!nd) return null;
@@ -690,5 +694,11 @@
reason: idx < 0 && rec.decision !== "encounter" ? "the recommended choice is not on this screen; use the bot's own rules" : `${rec.label}: ${rec.choice}` }; reason: idx < 0 && rec.decision !== "encounter" ? "the recommended choice is not on this screen; use the bot's own rules" : `${rec.label}: ${rec.choice}` };
} }
return { COLOURS, DECISIONS, CHANCE, prepareRun, countTables, makeParams, fitAlpha, solverHistory, nextDecision, advisor, solve, solveRatio, evaluate, buildPolicy, locate, recommendOption, genuineAttempt }; /** Where each colour can be bonded (encounter contexts). The Greens can also end in an Orange or Brown rescue. */
const ENCOUNTERS = {
Red: ["valley-Red", "tree-Red"], Orange: ["meadow-Orange", "tree-Greens"], Brown: ["meadow-Brown", "tree-Greens"],
Green: ["tree-Greens"], Blue: ["meadow-Blue", "shadow-Blue"], Black: ["shadow-Black"],
};
return { ENCOUNTERS, COLOURS, DECISIONS, CHANCE, prepareRun, countTables, makeParams, fitAlpha, solverHistory, nextDecision, advisor, solve, solveRatio, evaluate, buildPolicy, locate, recommendOption, genuineAttempt };
}); });
+12
View File
@@ -88,6 +88,18 @@ test("advisor matches the solver's own decisions on the recommended route", () =
assert.strictEqual(adv.next({}).choice, policy.targets.Blue.eventually.tree.choice); assert.strictEqual(adv.next({}).choice, policy.targets.Blue.eventually.tree.choice);
}); });
test("routing to one encounter: Blue only at the meadow equals the Blue policy; only at the tree Greens gives 0", () => {
const meadow = S.advisor(policy, "Blue", "thisAttempt", { only: ["meadow-Blue"] });
const all = S.advisor(policy, "Blue", "thisAttempt");
assert.ok(Math.abs(meadow.value.x - all.value.x) < 1e-6);
const greens = S.advisor(policy, "Blue", "thisAttempt", { only: ["tree-Greens"] });
assert.ok(greens.value.x < 1e-9);
// Brown via the Greens rescue is possible in this world
const rescue = S.advisor(policy, "Brown", "thisAttempt", { only: ["tree-Greens"] });
assert.ok(rescue.value.x > 0.05, rescue.value.x);
assert.ok(meadow.attempts("meadow-Blue") > 100);
});
test("solverHistory converts form variables", () => { test("solverHistory converts form variables", () => {
const h = S.solverHistory({ company: "Alone", direction: "Center", first_sighting: "Red", resolution: "Tourniquet", hour: "Tree", branch: "Descend slowly: two Greens" }); const h = S.solverHistory({ company: "Alone", direction: "Center", first_sighting: "Red", resolution: "Tourniquet", hour: "Tree", branch: "Descend slowly: two Greens" });
assert.deepStrictEqual(h, { company: "Alone", direction: "Center", fs: "Red", cadet: "Tourniquet", post: "(no fork)", hour: "Tree", descend: "Slowly (two Greens)", shadow: "no" }); assert.deepStrictEqual(h, { company: "Alone", direction: "Center", fs: "Red", cadet: "Tourniquet", post: "(no fork)", hour: "Tree", descend: "Slowly (two Greens)", shadow: "no" });