From de80e99c7489fa151f3444add5317eae2937448d Mon Sep 17 00:00:00 2001 From: ekcSchiano Date: Mon, 2 Nov 2026 14:24:47 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ --- README.md | 3 +- apps/atlas/dragons.js | 235 +++++++++++++++++ apps/atlas/explorer.js | 504 ++++++++++++++++++++++++++++++++++++ apps/atlas/index.html | 350 +++++++++++++------------ apps/atlas/planner.js | 295 --------------------- apps/atlas/ui.js | 103 +++++--- apps/atlas/valley.js | 2 +- packages/core/src/solver.js | 24 +- tests/solver.test.js | 12 + 9 files changed, 1009 insertions(+), 519 deletions(-) create mode 100644 apps/atlas/dragons.js create mode 100644 apps/atlas/explorer.js delete mode 100644 apps/atlas/planner.js diff --git a/README.md b/README.md index 2b4435c..d7da78c 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,8 @@ Unofficial fan project. Not affiliated with Dragonkind or the Fourth Wing publis ## 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: src/engine.js coding rules and statistics for the community form src/graph.js the shared route graph: scene graph, decision-variable graph, diff --git a/apps/atlas/dragons.js b/apps/atlas/dragons.js new file mode 100644 index 0000000..6d37509 --- /dev/null +++ b/apps/atlas/dragons.js @@ -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: 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 `${p.d.map((d) => ``).join("")}`; + } + return { svg, poses: Object.keys(POSES) }; +}); diff --git a/apps/atlas/explorer.js b/apps/atlas/explorer.js new file mode 100644 index 0000000..e51fc46 --- /dev/null +++ b/apps/atlas/explorer.js @@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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 `${sp.colour} dragon
One of the first dragons you can meet here. This is a roll of the dice, not a bonding.${n != null ? `
${n.toLocaleString()} riders met it here` : ""}`; + const o = st.policy ? encOutcome(sp.enc) : null; + const c = encColour(sp.enc); + const bond = o ? (sp.enc === "tree-Greens" ? `Green ${pct(o.Green)}, rescue by Orange ${pct(o.Orange || 0)} or Brown ${pct(o.Brown || 0)}` : pct(o[c])) : "–"; + return `${ENC_NAME[sp.enc]}${n != null ? `
${n.toLocaleString()} riders met it here` : ""}
Bond chance when attempted: ${bond}`; + }; + gg.addEventListener("mouseenter", (e) => showTip(e, tipHtml())); + gg.addEventListener("mousemove", (e) => moveTip(e)); + gg.addEventListener("mouseleave", hideTip); + gg.addEventListener("focus", () => { const r = gg.getBoundingClientRect(); showTip({ clientX: r.right, clientY: r.top }, tipHtml()); }); + gg.addEventListener("blur", hideTip); + const go = () => { + hideTip(); + if (sp.first) { st.info = sp; render(); return; } + select(encColour(sp.enc) === "Green" && st.colour && RESCUE[st.colour] === sp.enc ? st.colour : encColour(sp.enc), sp.enc); + }; + gg.addEventListener("click", go); + gg.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } }); + }); + } + + 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") => ``; + const POSE_OF = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" }; + const trafficToggle = () => ``; + function chooser() { + return `
${COLOURS.map((c) => ``).join("")}
`; + } + + function panelIdle() { + let info = ""; + if (st.info) { + const sp = st.info, dir = sp.place.split(":")[1]; + const fs = st.policy ? S.makeParams(model().model.tables, { alphas: model().model.alphas }).chance("fs", { direction: dir }) : null; + info = `
First sighting · ${dir === "Center" ? "forest centre" : dir.toLowerCase()} +

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

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

The valley

+

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

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

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

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

    ${st.colour} dragon

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

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

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

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

    +
    Why this route? +

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

    +

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

    +

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

    +
    +
    + ${trafficToggle()}`; + } + + function bindPanel() { + const p = $("#ex-panel"); + $$(".ex-dchip", p).forEach((b) => b.addEventListener("click", () => select(b.dataset.c === st.colour ? null : b.dataset.c))); + $$(".ex-route-card", p).forEach((b) => b.addEventListener("click", () => { st.focus = b.dataset.enc; st.expanded = null; render(); })); + $$(".ex-step", p).forEach((b) => b.addEventListener("click", () => { st.expanded = st.expanded === b.dataset.var ? null : b.dataset.var; render(); })); + $$(".ex-opt", p).forEach((b) => b.addEventListener("click", () => choose(b.dataset.var, b.dataset.v))); + $$("[data-o]", p).forEach((b) => b.addEventListener("click", () => { st.objective = b.dataset.o; render(); })); + $$("[data-s]", p).forEach((b) => b.addEventListener("click", () => { st.sample = b.dataset.s; render(); })); + const tr = $("#ex-traffic", p); if (tr) tr.addEventListener("change", () => { st.traffic = tr.checked; render(); }); + const cl = $("#ex-clear", p); if (cl) cl.addEventListener("click", () => select(null)); + const rr = $("#ex-reset-route", p); if (rr) rr.addEventListener("click", () => { delete st.over[st.focus]; st.expanded = null; render(); }); + } + + /* ---------- actions ---------- */ + function select(colour, enc) { + st.colour = colour; st.info = null; st.expanded = null; + st.focus = colour ? enc || null : null; + writeHash(); + render(); + } + function choose(v, val) { + const route = walk(st.focus); + const order = route.steps.map((s) => s.var); + const over = { ...(st.over[st.focus] || {}) }; + // keep choices before this one, drop the ones after it + const idx = order.indexOf(v); + order.slice(idx + 1).forEach((k) => delete over[k]); + over[v] = val; + st.over[st.focus] = over; + render(); + } + function writeHash() { + if (!$("#panel-valley") || $("#panel-valley").hidden) return; + const h = "#valley" + (st.colour ? "/" + st.colour.toLowerCase() + (st.focus ? "/" + st.focus : "") : ""); + try { history.replaceState(null, "", h); } catch (e) { /* ignore */ } + } + function fromHash() { + const parts = (location.hash || "").replace(/^#/, "").split("/"); + if (parts[0] !== "valley") return; + const c = parts[1] ? COLOURS.find((x) => x.toLowerCase() === parts[1].toLowerCase()) : null; + const enc = parts[2] && c && S.ENCOUNTERS[c].includes(parts[2]) ? parts[2] : null; + 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 = `
    ${st.colour && st.policy ? panelRoutes(routes) : panelIdle()}
    `; + bindPanel(); + writeHash(); + // on narrow screens the map scrolls sideways: start centred rather than at the far west + const wrap = $(".ex-map-wrap"); + if (wrap && !wrap.dataset.centred && wrap.scrollWidth > wrap.clientWidth) { wrap.scrollLeft = (wrap.scrollWidth - wrap.clientWidth) / 2; wrap.dataset.centred = "1"; } + } + + function setRuns(state) { + st.runs = state.runs; + st.counts = {}; + state.runs.forEach((r) => V.path(r).forEach((id) => (st.counts[id] = (st.counts[id] || 0) + 1))); + render(); + } + + function init() { + render(); + fetch("data/policy.json").then((r) => r.json()).then((p) => { + st.policy = p; + if (st.pendingHash) { st.colour = st.pendingHash.c; st.focus = st.pendingHash.enc; st.pendingHash = null; } + render(); + }).catch(() => { $("#ex-panel").innerHTML = '

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

    '; }); + } + window.ValleyExplorer = { setRuns, fromHash, state: st, render }; + if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init(); +})(); diff --git a/apps/atlas/index.html b/apps/atlas/index.html index 14acc93..94c8a70 100644 --- a/apps/atlas/index.html +++ b/apps/atlas/index.html @@ -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); } footer { border-top-color: var(--line); } -/* route planner */ -.planner-controls { align-items: end; } -.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 999px; overflow: hidden; } -.seg button { border: 0; border-radius: 0; background: transparent; padding: 7px 13px; color: var(--muted); font-size: 0.72rem; } +/* the valley explorer (landing page) */ +.explorer { gap: 0; } +.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); + --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); } -.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; } -.pl-kpi { padding: 12px 14px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface); display: grid; gap: 2px; align-content: start; } -.pl-kpi b { font-family: var(--font-display); font-weight: 400; font-size: 1.7rem; color: var(--c, var(--ink)); line-height: 1.1; } -.pl-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr); gap: 16px; align-items: start; } -@media (max-width: 1050px) { .pl-grid { grid-template-columns: minmax(0, 1fr); } } -.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); } -#planner-map { display: block; width: 100%; min-width: 760px; height: auto; background: #d9b07a; } -.pl-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; padding: 10px 14px; border-top: 1px solid var(--line); background: var(--surface); } -.pl-legend b { display: inline-block; width: 22px; height: 6px; border-radius: 3px; vertical-align: 2px; margin-right: 4px; } -.pl-legend .sw-route { background: var(--vt, var(--accent)); box-shadow: 0 0 0 3px #fff1c955; } -.pl-legend .sw-opt { background: repeating-linear-gradient(90deg, var(--vt, var(--accent)) 0 5px, transparent 5px 10px); opacity: 0.7; } -.pl-legend .sw-roll { background: repeating-linear-gradient(90deg, var(--muted) 0 2px, transparent 2px 8px); } -.pl-legend .sw-risk { width: 12px; height: 12px; border-radius: 50%; background: var(--ember); vertical-align: -2px; } -.pl-steps { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; align-content: start; max-height: 920px; overflow: auto; } -.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; } + +/* the odds, per dragon */ +.odds-colours { grid-template-columns: repeat(3, minmax(0, 1fr)); } +@media (max-width: 900px) { .odds-colours { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 560px) { .odds-colours { 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)); } +.odd-colour:hover, .odd-colour:focus-visible { transform: translateY(-2px); box-shadow: 0 0 22px color-mix(in srgb, var(--c) 30%, transparent); } +.odd-art { width: 110px; height: 88px; max-width: none; } +.odd .go { font-family: var(--font-label); letter-spacing: .12em; text-transform: uppercase; font-size: .68rem; color: var(--c); } +.ladder { padding: 16px 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); display: grid; gap: 10px; } +.ladder ol { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; } +.ladder li { display: grid; grid-template-columns: 70px minmax(0, 1fr) 48px; gap: 10px; align-items: center; font-size: var(--step--1); } +.ladder li i { display: block; height: 10px; border-radius: 4px; width: var(--w); background: var(--c); } +.ladder li b { font-family: var(--font-data); text-align: right; } +.combo { grid-template-columns: minmax(0, 1fr); }
    @@ -361,29 +399,38 @@ button.pl-row:hover { background: color-mix(in srgb, var(--ink) 6%, transparent) Unofficial fan atlas for readers of Rebecca Yarros's Fourth Wing · not affiliated with Dragonkind
    -
    +
    +
    +
    +
    +
    Choose a dragon to see the way to it
    + +
    + +
    +
    +
    + - - - - +
    -

    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.

    @@ -659,5 +656,6 @@ adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ) - + + diff --git a/apps/atlas/planner.js b/apps/atlas/planner.js deleted file mode 100644 index 9e904e9..0000000 --- a/apps/atlas/planner.js +++ /dev/null @@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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]) => - `
    ${k === "burn" ? "Incinerated" : "Bond " + esc(k)}${pct(p)}
    `).join(""); - return `
  • ${i + 1}

    ${s.action === "Die on purpose" ? "Die on purpose and try again" : "The bonding encounter"}

    ${rows}
  • `; - } - 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 ? `

    The recommended option stays best in ${pct(s.stillBest)} of 200 re-runs on the uncertain data.

    ` : ""; - 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 = `${isDec ? `${pct(v.pX)}alive ${pct(v.pReach)}${v.pOther > 0.0005 ? ` · other ${pct(v.pOther)}` : ""}` : `${pct(v)}`}`; - return ``; - }).join(""); - const risk = s.risk && s.risk.p > 0.0005 ? `

    ${esc(s.risk.label)}: ${pct(s.risk.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)} · chance`; - return `
  • ${i + 1}
    ${risk}

    ${head}

    - ${isDec && close ? '

    No clear winner: the top options are within the noise.

    ' : ""}${sure}${rows}
  • `; - }).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 = ` -
    Best route, ${st.colour}${pct(b.pX.mean)}per attempt · 95% ${pct(b.pX.lo)}–${pct(b.pX.hi)}
    -
    Attempts, about${isFinite(att) ? Math.round(att) : "–"}if you die on purpose whenever it goes wrong
    -
    Ends on another colour${pct(b.pOther.mean)}per attempt, on this route
    -
    Low-bias estimate${pct(lb.pX.mean)}riders who logged every run
    `; - } - - 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) => ``).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 = '

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

    '; }); - } - if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init(); - window.RoutePlanner = { state: st, render }; -})(); diff --git a/apps/atlas/ui.js b/apps/atlas/ui.js index 3de65ea..effef3d 100644 --- a/apps/atlas/ui.js +++ b/apps/atlas/ui.js @@ -26,9 +26,12 @@ function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); } // ------------------------------------------------------------ tabs - const TABS = ["overview", "planner", "valley", "flow", "rare", "dragons", "deep", "share"]; - function showTab(name, focus) { - if (!TABS.includes(name)) name = "overview"; + const TABS = ["valley", "odds", "dragons", "deep", "data"]; + // old links (#overview, #flow, #planner ...) still land somewhere sensible + 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) => { const on = t === name; $("#tab-" + t).setAttribute("aria-selected", on); @@ -37,8 +40,9 @@ }); if (focus) $("#tab-" + name).focus(); try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ } - try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } - if (name === "flow" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize")); + if (!keepHash) { try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } } + 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) => { const b = $("#tab-" + t); @@ -56,14 +60,15 @@ const a = e.target.closest('a[href^="#"]'); if (!a) return; 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 panel = target && target.closest(".tabpanel"); 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); }); - const initial = (location.hash || "").slice(1); - showTab(TABS.includes(initial) ? initial : "overview"); + // #valley/blue/meadow-Blue keeps its sub-path (the explorer reads it) + window.addEventListener("hashchange", () => { const t = tabOf(location.hash); if (t) showTab(t, false, t === "valley"); }); + const initial = tabOf(location.hash); + showTab(initial || "valley", false, initial === "valley"); // ------------------------------------------------------------ hero art (original, generic silhouettes) function drawHero() { @@ -117,59 +122,79 @@ } 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 = '

    The route model could not be loaded.

    '; 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 ? `` : ""; + $("#odds-colours").innerHTML = cols.map(({ c, p, pAll, lo, hi }) => { + const e = enc(c); + return `${art(c)} + 1 in ${oneIn(p)}runs end bonded to ${/^[AEIOU]/.test(c) ? "an" : "a"} ${c}, on the best route + ${dots(Math.round(p * 1000), 1000, cssVar(DV[c]))} + ${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. + See the route →`; + }).join(""); + $("#combo").innerHTML = `
    Easiest to hardest, in attempts on the best route
      ${cols.map(({ c, p }) => + `
    1. ${c}${oneIn(p)}
    2. `).join("")}
    +

    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.

    `; + const meadowAlpha = all.model.alphas.meadow, shadowAlpha = all.model.alphas.shadow; + const t2 = $("#truth-history"); + if (t2) t2.innerHTML = `

    Earlier choices barely change who waits

    ${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.

    `; + 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 = `

    The right answer can still burn

    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.

    `; + } + } + function renderOverview(state) { const r = state.res; const reach = r.factors.reach_hour.overall; - const cb = r.chance.blue_meadow, cs = r.chance.shadow; - const bulkB = stratum(cb, "Bulk"), bulkS = stratum(cs, "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 cb = r.chance.blue_meadow; + const bulkB = stratum(cb, "Bulk"); const tag = (txt) => `${txt}`; + const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0); 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: 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: 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 }, + { 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 }, ]; - const dead = Object.entries(r.meta.outcomes).filter(([k]) => k.startsWith("Incinerated") || k.startsWith("Died")).reduce((a, [, v]) => a + v, 0); - 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 }); - $("#odds").innerHTML = cards.map((c) => `
    ${esc(c.big)}${esc(c.what)}${c.scale ? "" : dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}
    `).join(""); - const pBlueRun = blueSeen.p * encB.p, pBlackRun = shadowP * encK.p; - $("#combo").innerHTML = ` -
    ≈ 1 in ${oneIn(pBlueRun)}
    valley runs ends bonded to a Blue
    ${tag(`A Blue has to show up (about ${pct(blueSeen.p)}) and then accept you (about ${pct(encB.p)}).`)}
    -
    ${shadow.k === 0 ? "<" : "≈"} 1 in ${oneIn(pBlackRun)}
    tree climbs ends bonded to a Black
    ${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)}).`)}
    `; + $("#odds").innerHTML = cards.map((c) => `
    ${esc(c.big)}${esc(c.what)}${dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}
    `).join(""); + getPolicy().then(renderColourOdds); // journey const fr = r.factors.reach_hour.rows; const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l); const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates"); 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 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: "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 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: "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: "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 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 }, ]; $("#journey").innerHTML = stops.map((s, i) => `
    ${["I", "II", "III", "IV", "V", "VI", "VII"][i]}${esc(s.t)}${esc(s.d)}${s.v ? `${esc(s.v)}` : ""}
    `).join(""); const chase = stratum(cb, "Form: chasing Blue"); $("#truths").innerHTML = ` -

    Lucky runs get shared

    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.

    -

    No secret route to the Blue, so far

    ${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.

    -

    The right answer can still burn

    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.

    `; +

    Lucky runs get shared

    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.

    +
    +
    `; + $("#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.`; } @@ -186,7 +211,7 @@ window.AtlasUI = { render(state) { renderOverview(state); - if (window.ValleyMap) window.ValleyMap.render(state); + if (window.ValleyExplorer) window.ValleyExplorer.setRuns(state); }, showTab, }; diff --git a/apps/atlas/valley.js b/apps/atlas/valley.js index 68237e2..781c8ac 100644 --- a/apps/atlas/valley.js +++ b/apps/atlas/valley.js @@ -241,7 +241,7 @@ const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour"; function render(state) { - if (!state || !state.res) return; + if (!state || !state.res || !$("#valley")) return; lastState = state; renderTargets(); const svg = $("#valley"); diff --git a/packages/core/src/solver.js b/packages/core/src/solver.js index 71feb04..e342a57 100644 --- a/packages/core/src/solver.js +++ b/packages/core/src/solver.js @@ -282,7 +282,9 @@ * 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). */ - 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 memo = 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 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; const d = params.encounter(ctx); 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 * 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 params = makeParams(m.tables, { mode: "mean", alphas: m.alphas }); const sol = objective === "eventually" - ? (() => { const r = solveRatio(params, X, { support: m.support }); return solve(params, X, { support: m.support, lam: r.lam, record: true }); })() - : solve(params, X, { support: m.support, 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, 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 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 }); @@ -653,7 +655,9 @@ return { kind: "end", encounter: enc, action: h.encounter, outcomes: h.encounter === "Die on purpose" ? { burn: 1 } : params.encounter(enc) }; } 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) { const nd = nextDecision(h); 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}` }; } - 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 }; }); diff --git a/tests/solver.test.js b/tests/solver.test.js index de5702b..98df096 100644 --- a/tests/solver.test.js +++ b/tests/solver.test.js @@ -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); }); +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", () => { 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" });