Prompt specification
Build or customize the Three.js 3D scene "Expected-value design playground" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Expected-value design playground
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/expected-value-design-playground-x1792
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows expected value across weighted outcomes. Let users adjust a small outcome distribution while probabilities remain normalized; calculate mean payout and simulate bounded trials without promoting real gambling or financial decisions. Low-poly.
Working Three.js Starter (expected-value-design-playground-x1792):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark" />
<title>Weighted Outcomes Lab</title>
<style>
:root {
--bg: #071116;
--bg-soft: #0c1b21;
--panel: rgba(15, 32, 39, 0.88);
--panel-solid: #102229;
--border: rgba(181, 226, 224, 0.14);
--border-strong: rgba(181, 226, 224, 0.28);
--text: #edf7f5;
--muted: #9bb4b6;
--accent: #63d8c5;
--accent-warm: #f4cc69;
--danger: #f38f83;
--blue: #8fa8ff;
--shadow: 0 22px 70px rgba(0, 0, 0, 0.28);
}
* {
box-sizing: border-box;
}
html {
min-width: 320px;
background: var(--bg);
}
body {
min-height: 100vh;
margin: 0;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 14% 4%, rgba(48, 137, 133, 0.18), transparent 31rem),
radial-gradient(circle at 92% 18%, rgba(91, 102, 181, 0.15), transparent 28rem),
linear-gradient(180deg, #081419 0%, #061015 100%);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
width: min(1420px, calc(100% - 32px));
margin: 0 auto;
padding: 30px 0 40px;
}
.header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 28px;
margin-bottom: 24px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin: 0 0 10px;
color: var(--accent);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 26px;
height: 2px;
content: "";
background: var(--accent);
box-shadow: 0 0 12px rgba(99, 216, 197, 0.55);
}
h1,
h2,
h3,
p {
margin-top: 0;
}
h1 {
max-width: 780px;
margin-bottom: 10px;
font-size: clamp(2rem, 5vw, 4.35rem);
font-weight: 760;
letter-spacing: -0.055em;
line-height: 0.98;
}
.header-copy {
max-width: 690px;
margin-bottom: 0;
color: var(--muted);
font-size: clamp(0.95rem, 1.5vw, 1.08rem);
line-height: 1.65;
}
.safety-badge {
flex: 0 0 auto;
max-width: 265px;
padding: 13px 15px;
border: 1px solid var(--border-strong);
border-radius: 14px;
color: #c6dcda;
background: rgba(13, 30, 36, 0.65);
font-size: 0.78rem;
line-height: 1.5;
}
.safety-badge strong {
display: block;
margin-bottom: 2px;
color: var(--text);
font-size: 0.72rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.layout {
display: grid;
grid-template-columns: minmax(0, 1.62fr) minmax(330px, 0.78fr);
gap: 18px;
align-items: start;
}
.visual-column,
.controls-column {
display: grid;
gap: 18px;
min-width: 0;
}
.card {
overflow: hidden;
border: 1px solid var(--border);
border-radius: 22px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.card-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
padding: 21px 22px 0;
}
.card-header h2,
.card-header h3 {
margin-bottom: 5px;
font-size: 1rem;
letter-spacing: -0.015em;
}
.card-header p {
margin-bottom: 0;
color: var(--muted);
font-size: 0.79rem;
line-height: 1.5;
}
.mini-pill {
flex: 0 0 auto;
padding: 6px 9px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--muted);
font-size: 0.67rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.stage {
position: relative;
height: 535px;
overflow: hidden;
isolation: isolate;
background:
radial-gradient(circle at 50% 40%, rgba(69, 140, 137, 0.12), transparent 45%),
linear-gradient(180deg, rgba(4, 15, 19, 0.08), rgba(4, 15, 19, 0.55));
}
.stage canvas {
position: absolute;
inset: 0;
z-index: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
.stage canvas:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -4px;
}
.stage canvas.dragging {
cursor: grabbing;
}
.labels {
position: absolute;
inset: 0;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.scene-label {
position: absolute;
min-width: 92px;
padding: 7px 9px;
transform: translate(-50%, -100%);
border: 1px solid rgba(190, 229, 226, 0.17);
border-radius: 10px;
color: var(--text);
background: rgba(7, 18, 23, 0.83);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.26);
text-align: center;
backdrop-filter: blur(8px);
}
.scene-label::after {
position: absolute;
bottom: -6px;
left: 50%;
width: 10px;
height: 10px;
transform: translateX(-50%) rotate(45deg);
border-right: 1px solid rgba(190, 229, 226, 0.17);
border-bottom: 1px solid rgba(190, 229, 226, 0.17);
content: "";
background: rgba(7, 18, 23, 0.83);
}
.label-name {
display: block;
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.025em;
}
.label-prob {
display: block;
margin-top: 2px;
color: var(--accent);
font-size: 0.8rem;
font-weight: 800;
}
.label-pay {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 0.61rem;
}
.scene-label.ev-label {
min-width: 112px;
border-color: rgba(244, 204, 105, 0.35);
}
.scene-label.ev-label .label-prob {
color: var(--accent-warm);
}
.stage-note {
position: absolute;
right: 16px;
bottom: 14px;
z-index: 3;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 9px;
color: var(--muted);
background: rgba(7, 18, 23, 0.7);
font-size: 0.67rem;
pointer-events: none;
}
.stage-key {
position: absolute;
top: 16px;
left: 16px;
z-index: 3;
display: flex;
flex-wrap: wrap;
gap: 7px;
pointer-events: none;
}
.stage-key span {
padding: 6px 9px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--muted);
background: rgba(7, 18, 23, 0.65);
font-size: 0.65rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.card-body {
padding: 18px 22px 22px;
}
.outcome-list {
display: grid;
gap: 10px;
}
.outcome-row {
--outcome-color: var(--accent);
padding: 12px;
border: 1px solid rgba(181, 226, 224, 0.09);
border-radius: 14px;
background: rgba(3, 12, 16, 0.2);
}
.outcome-row-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.outcome-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.78rem;
font-weight: 800;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--outcome-color);
box-shadow: 0 0 11px color-mix(in srgb, var(--outcome-color), transparent 45%);
transform: rotate(45deg);
}
.probability {
color: var(--outcome-color);
font-size: 0.75rem;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.input-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 9px;
}
.field label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 5px;
color: var(--muted);
font-size: 0.67rem;
font-weight: 700;
letter-spacing: 0.035em;
text-transform: uppercase;
}
input[type="number"] {
width: 100%;
min-width: 0;
padding: 8px 9px;
border: 1px solid var(--border);
border-radius: 9px;
outline: none;
color: var(--text);
background: rgba(5, 15, 19, 0.75);
font-size: 0.78rem;
font-variant-numeric: tabular-nums;
}
input[type="number"]:focus,
input[type="range"]:focus-visible {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(99, 216, 197, 0.1);
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0;
accent-color: var(--outcome-color);
cursor: pointer;
}
.weight-range {
display: block;
}
.helper {
margin: 12px 0 0;
color: var(--muted);
font-size: 0.7rem;
line-height: 1.5;
}
.button-row {
display: flex;
gap: 9px;
margin-top: 14px;
}
button {
min-height: 40px;
padding: 9px 13px;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
font-size: 0.76rem;
font-weight: 800;
cursor: pointer;
transition:
transform 150ms ease,
border-color 150ms ease,
background 150ms ease;
}
button:hover {
border-color: rgba(181, 226, 224, 0.45);
background: rgba(255, 255, 255, 0.075);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
button.primary {
flex: 1;
border-color: transparent;
color: #09201d;
background: var(--accent);
}
button.primary:hover {
background: #83e4d4;
}
button.primary:disabled {
opacity: 0.55;
cursor: wait;
transform: none;
}
.normalization {
margin-top: 14px;
}
.normalization-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.67rem;
}
.probability-strip {
display: flex;
height: 8px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.05);
}
.probability-strip span {
height: 100%;
background: var(--strip-color);
transition: width 280ms ease;
}
.expectation-card {
position: relative;
overflow: hidden;
}
.expectation-card::after {
position: absolute;
top: -80px;
right: -75px;
width: 190px;
height: 190px;
border-radius: 50%;
content: "";
background: rgba(244, 204, 105, 0.08);
filter: blur(2px);
}
.expectation-main {
position: relative;
z-index: 1;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 20px;
padding: 22px;
}
.metric-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric-value {
margin: 0;
font-size: clamp(2rem, 5vw, 3.35rem);
font-weight: 780;
letter-spacing: -0.055em;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric-unit {
margin-left: 5px;
color: var(--muted);
font-size: 0.82rem;
font-weight: 700;
letter-spacing: 0;
}
.formula-box {
position: relative;
z-index: 1;
padding: 13px 22px 20px;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.65;
}
.formula-box strong {
color: var(--text);
}
.formula-terms {
display: block;
margin-top: 4px;
color: #bdd0d0;
font-variant-numeric: tabular-nums;
}
.trial-control {
margin-bottom: 14px;
}
.trial-value {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 9px;
}
.trial-value label {
color: var(--muted);
font-size: 0.72rem;
font-weight: 700;
}
.trial-value input {
width: 86px;
}
.trial-range {
accent-color: var(--accent);
}
.run-status {
min-height: 18px;
margin: 10px 0 0;
color: var(--muted);
font-size: 0.69rem;
line-height: 1.45;
}
.run-results {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 13px;
}
.result-box {
padding: 11px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(3, 12, 16, 0.24);
}
.result-box span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 0.63rem;
line-height: 1.3;
text-transform: uppercase;
}
.result-box strong {
font-size: 0.93rem;
font-variant-numeric: tabular-nums;
}
.observed-list {
display: grid;
gap: 8px;
margin-top: 15px;
}
.observed-row {
display: grid;
grid-template-columns: 15px 1fr 48px 48px;
gap: 8px;
align-items: center;
color: var(--muted);
font-size: 0.68rem;
font-variant-numeric: tabular-nums;
}
.observed-row .swatch {
width: 8px;
height: 8px;
}
.observed-row strong {
color: var(--text);
font-weight: 700;
text-align: right;
}
.chart-card {
min-width: 0;
}
.chart-header-meta {
display: flex;
flex-wrap: wrap;
gap: 12px;
color: var(--muted);
font-size: 0.67rem;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-line {
width: 19px;
height: 2px;
background: var(--accent);
}
.legend-line.dashed {
height: 0;
border-top: 2px dashed var(--accent-warm);
background: transparent;
}
.chart-wrap {
position: relative;
min-height: 245px;
padding: 12px 16px 14px;
}
#runChart {
display: block;
width: 100%;
height: 245px;
overflow: visible;
}
.chart-empty {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 30px;
color: var(--muted);
text-align: center;
font-size: 0.8rem;
line-height: 1.6;
pointer-events: none;
}
.chart-empty.hidden {
display: none;
}
.footer {
margin: 20px 2px 0;
color: #789395;
font-size: 0.7rem;
line-height: 1.6;
text-align: center;
}
@media (max-width: 1040px) {
.layout {
grid-template-columns: 1fr;
}
.controls-column {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
.controls-column .simulation-card {
grid-column: 1 / -1;
}
}
@media (max-width: 680px) {
.app {
width: min(100% - 20px, 1420px);
padding-top: 20px;
}
.header {
display: block;
}
.safety-badge {
max-width: none;
margin-top: 16px;
}
.stage {
height: 425px;
}
.controls-column {
grid-template-columns: 1fr;
}
.controls-column .simulation-card {
grid-column: auto;
}
.card-header,
.card-body {
padding-left: 16px;
padding-right: 16px;
}
.expectation-main {
padding: 20px 16px;
}
.formula-box {
padding-left: 16px;
padding-right: 16px;
}
.scene-label {
min-width: 76px;
padding: 6px 7px;
}
.label-name {
font-size: 0.61rem;
}
.label-prob {
font-size: 0.72rem;
}
.label-pay {
font-size: 0.54rem;
}
.stage-note {
right: 10px;
bottom: 9px;
}
.chart-header-meta {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.001ms !important;
animation-duration: 0.001ms !important;
}
}
</style>
</head>
<body>
<main class="app">
<header class="header">
<div>
<p class="eyebrow">Probability sandbox</p>
<h1>Weighted outcomes,<br />made visible.</h1>
<p class="header-copy">
Adjust outcome weights and fixed illustrative payouts. The model keeps
probabilities normalized, while a bounded simulation shows how a sample
average can differ from the theoretical mean.
</p>
</div>
<div class="safety-badge">
<strong>Educational use only</strong>
Abstract points, no deposits or real-money stakes. Results are for
learning about probability, not financial decisions.
</div>
</header>
<main class="layout">
<section class="visual-column">
<section class="card">
<div class="card-header">
<div>
<h2>Outcome landscape</h2>
<p>Column height represents normalized probability.</p>
</div>
<span class="mini-pill">Low-poly model</span>
</div>
<div id="stage" class="stage">
<div id="labels" class="labels" aria-hidden="true"></div>
<div class="stage-key" aria-hidden="true">
<span>Probability → height</span>
<span>Total = 100%</span>
</div>
<div class="stage-note" aria-hidden="true">
Drag to orbit · scroll to zoom
</div>
</div>
</section>
<section class="card chart-card">
<div class="card-header">
<div>
<h2>Running sample mean</h2>
<p>The cumulative average after each illustrative trial.</p>
</div>
<div class="chart-header-meta" aria-hidden="true">
<span class="legend-item">
<i class="legend-line"></i>
Sample mean
</span>
<span class="legend-item">
<i class="legend-line dashed"></i>
Model mean
</span>
</div>
</div>
<div class="chart-wrap">
<svg
id="runChart"
viewBox="0 0 900 245"
preserveAspectRatio="none"
role="img"
aria-label="Chart comparing the running sample mean with the model mean"
></svg>
<div id="chartEmpty" class="chart-empty">
Run a bounded simulation to build the running-mean chart.
</div>
</div>
</section>
</section>
<aside class="controls-column">
<section class="card">
<div class="card-header">
<div>
<h2>Distribution</h2>
<p>Edit payouts and relative weights.</p>
</div>
<span class="mini-pill">Auto-normalized</span>
</div>
<div class="card-body">
<div id="outcomeList" class="outcome-list"></div>
<div class="normalization">
<div class="normalization-label">
<span>Normalized probability</span>
<span id="probabilityTotal">100.0%</span>
</div>
<div id="probabilityStrip" class="probability-strip"></div>
</div>
<p class="helper">
Weights are divided by their total. At least one weight must remain
positive so the probabilities stay defined.
</p>
<div class="button-row">
<button id="resetButton" type="button">Restore defaults</button>
</div>
</div>
</section>
<section class="card expectation-card">
<div class="expectation-main">
<div>
<span class="metric-label">Mean payout / expected value</span>
<p class="metric-value">
<span id="expectedValue">0</span>
<span class="metric-unit">points</span>
</p>
</div>
</div>
<div class="formula-box">
<strong>EV = Σ (normalized probability × fixed payout)</strong>
<span id="formulaTerms" class="formula-terms"></span>
</div>
</section>
<section class="card simulation-card">
<div class="card-header">
<div>
<h2>Bounded simulation</h2>
<p>Independent draws with replacement, capped at 2,000 trials.</p>
</div>
</div>
<div class="card-body">
<div class="trial-control">
<div class="trial-value">
<label for="trialCount">Trials in one run</label>
<input
id="trialCount"
type="number"
min="1"
max="2000"
step="1"
value="500"
/>
</div>
<input
id="trialRange"
class="trial-range"
type="range"
min="1"
max="2000"
step="1"
value="500"
aria-label="Number of trials"
/>
</div>
<button id="simulateButton" class="primary" type="button">
Run illustrative trials
</button>
<p id="runStatus" class="run-status" aria-live="polite">
No simulation run yet.
</p>
<div class="run-results">
<div class="result-box">
<span>Observed mean</span>
<strong id="observedMean">—</strong>
</div>
<div class="result-box">
<span>Difference from model</span>
<strong id="observedDifference">—</strong>
</div>
</div>
<div id="observedList" class="observed-list"></div>
</div>
</section>
</aside>
</main>
<footer class="footer">
This visualization uses abstract outcome points and does not model financial
markets, wagering, rewards, or expected financial returns. Simulations are
illustrative and can vary from the theoretical mean.
</footer>
</main>
<noscript>
<p style="padding: 24px; text-align: center">
JavaScript is required to calculate and visualize the outcome distribution.
</p>
</noscript>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Model state
// ------------------------------------------------------------
const DEFAULTS = [
{ name: "Outcome A", color: 0x63d8c5, css: "#63d8c5", payout: 2, weight: 60 },
{ name: "Outcome B", color: 0xf4cc69, css: "#f4cc69", payout: 5, weight: 25 },
{ name: "Outcome C", color: 0xf38f83, css: "#f38f83", payout: 12, weight: 11 },
{ name: "Outcome D", color: 0x8fa8ff, css: "#8fa8ff", payout: 25, weight: 4 }
];
const state = {
outcomes: DEFAULTS.map((outcome) => ({ ...outcome })),
probabilities: [],
expectedValue: 0
};
const outcomeList = document.getElementById("outcomeList");
const probabilityStrip = document.getElementById("probabilityStrip");
const probabilityTotal = document.getElementById("probabilityTotal");
const expectedValue = document.getElementById("expectedValue");
const formulaTerms = document.getElementById("formulaTerms");
const trialCount = document.getElementById("trialCount");
const trialRange = document.getElementById("trialRange");
const simulateButton = document.getElementById("simulateButton");
const runStatus = document.getElementById("runStatus");
const observedMean = document.getElementById("observedMean");
const observedDifference = document.getElementById("observedDifference");
const observedList = document.getElementById("observedList");
const runChart = document.getElementById("runChart");
const chartEmpty = document.getElementById("chartEmpty");
const formatNumber = (value, maximumFractionDigits = 2) =>
Number(value).toLocaleString(undefined, {
maximumFractionDigits
});
const formatPercent = (value) =>
`${(value * 100).toFixed(1).replace(/\.0$/, "")}%`;
// ------------------------------------------------------------
// Build accessible HTML controls
// ------------------------------------------------------------
function buildControls() {
outcomeList.innerHTML = "";
state.outcomes.forEach((outcome, index) => {
const row = document.createElement("div");
row.className = "outcome-row";
row.style.setProperty("--outcome-color", outcome.css);
row.innerHTML = `
<div class="outcome-row-top">
<span class="outcome-name">
<i class="swatch" aria-hidden="true"></i>
${outcome.name}
</span>
<span class="probability" data-probability="${index}">0%</span>
</div>
<div class="input-grid">
<div class="field">
<label for="payout-${index}">Payout points</label>
<input
id="payout-${index}"
class="payout-input"
data-index="${index}"
type="number"
min="0"
max="9999"
step="0.5"
value="${outcome.payout}"
/>
</div>
<div class="field">
<label for="weight-${index}">Relative weight</label>
<input
id="weight-${index}"
class="weight-number"
data-index="${index}"
type="number"
min="0"
max="100"
step="1"
value="${outcome.weight}"
/>
</div>
</div>
<input
class="weight-range"
data-index="${index}"
type="range"
min="0"
max="100"
step="1"
value="${outcome.weight}"
aria-label="${outcome.name} relative weight"
/>
`;
outcomeList.appendChild(row);
});
outcomeList.querySelectorAll(".payout-input").forEach((input) => {
input.addEventListener("input", () => {
const index = Number(input.dataset.index);
const value = Number(input.value);
state.outcomes[index].payout = Number.isFinite(value)
? Math.min(9999, Math.max(0, value))
: 0;
updateModel();
clearSimulation("Distribution changed. Run again for a new sample.");
});
});
outcomeList.querySelectorAll(".weight-number, .weight-range").forEach((input) => {
input.addEventListener("input", () => {
const index = Number(input.dataset.index);
setWeight(index, input.value);
updateModel();
clearSimulation("Distribution changed. Run again for a new sample.");
});
});
}
function setWeight(index, rawValue) {
let value = Number(rawValue);
value = Number.isFinite(value) ? Math.min(100, Math.max(0, value)) : 0;
state.outcomes[index].weight = value;
// Avoid an undefined distribution if every weight is set to zero.
const total = state.outcomes.reduce((sum, outcome) => sum + outcome.weight, 0);
if (total <= 0) {
state.outcomes[index].weight = 1;
}
}
function syncControls() {
outcomeList.querySelectorAll(".outcome-row").forEach((row, index) => {
const outcome = state.outcomes[index];
const probability = state.probabilities[index];
row.querySelector(".payout-input").value = outcome.payout;
row.querySelector(".weight-number").value = outcome.weight;
row.querySelector(".weight-range").value = outcome.weight;
row.querySelector("[data-probability]").textContent =
formatPercent(probability);
});
probabilityStrip.innerHTML = state.outcomes
.map(
(outcome, index) =>
`<span
style="
width: ${state.probabilities[index] * 100}%;
flex-basis: ${state.probabilities[index] * 100}%;
--strip-color: ${outcome.css};
"
title="${outcome.name}: ${formatPercent(state.probabilities[index])}"
></span>`
)
.join("");
const exactTotal = state.probabilities.reduce((sum, value) => sum + value, 0);
probabilityTotal.textContent = `${(exactTotal * 100).toFixed(1)}%`;
}
function updateModel() {
const totalWeight = state.outcomes.reduce(
(sum, outcome) => sum + outcome.weight,
0
);
const safeTotal = totalWeight > 0 ? totalWeight : 1;
state.probabilities = state.outcomes.map(
(outcome) => outcome.weight / safeTotal
);
state.expectedValue = state.outcomes.reduce(
(sum, outcome, index) =>
sum + state.probabilities[index] * outcome.payout,
0
);
expectedValue.textContent = formatNumber(state.expectedValue);
formulaTerms.textContent = state.outcomes
.map(
(outcome, index) =>
`${formatPercent(state.probabilities[index])} × ${formatNumber(outcome.payout)}`
)
.join(" + ");
syncControls();
updateSceneTargets();
}
// ------------------------------------------------------------
// Three.js scene — core module only
// ------------------------------------------------------------
const stage = document.getElementById("stage");
const labelLayer = document.getElementById("labels");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("role", "img");
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly chart of four weighted outcomes"
);
renderer.domElement.tabIndex = 0;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x071116, 13, 24);
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 100);
const cameraState = {
yaw: 0.34,
pitch: 0.77,
radius: 12.4,
target: new THREE.Vector3(0, 1.45, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
const horizontal = radius * Math.sin(pitch);
camera.position.set(
target.x + horizontal * Math.sin(yaw),
target.y + radius * Math.cos(pitch),
target.z + horizontal * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xd9ffff, 0x14242a, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3d3, 3.2);
keyLight.position.set(4, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x67d9d0, 18, 18, 2);
rimLight.position.set(-5, 4, 2);
scene.add(rimLight);
const world = new THREE.Group();
scene.add(world);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x14282e,
roughness: 0.86,
metalness: 0.08,
flatShading: true
});
const floor = new THREE.Mesh(
new THREE.CylinderGeometry(5.5, 5.8, 0.25, 24),
floorMaterial
);
floor.position.y = -0.18;
floor.receiveShadow = true;
world.add(floor);
const plinth = new THREE.Mesh(
new THREE.CylinderGeometry(4.9, 5.05, 0.16, 20),
new THREE.MeshStandardMaterial({
color: 0x1c353b,
roughness: 0.78,
metalness: 0.1,
flatShading: true
})
);
plinth.position.y = 0;
plinth.receiveShadow = true;
world.add(plinth);
[2.1, 3.65, 4.65].forEach((radius, index) => {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(radius, 0.012, 3, 40),
new THREE.MeshBasicMaterial({
color: index === 1 ? 0x4b7778 : 0x31575a,
transparent: true,
opacity: index === 1 ? 0.42 : 0.28
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.095;
world.add(ring);
});
const decorativeShapes = [];
for (let index = 0; index < 12; index += 1) {
const angle = (index / 12) * Math.PI * 2 + 0.18;
const radius = 4.65 + (index % 3) * 0.16;
const size = 0.08 + (index % 4) * 0.025;
const shape = new THREE.Mesh(
new THREE.TetrahedronGeometry(size, 0),
new THREE.MeshStandardMaterial({
color: index % 3 === 0 ? 0x4d7777 : 0x2b4b50,
roughness: 0.72,
metalness: 0.12,
flatShading: true
})
);
shape.position.set(
Math.cos(angle) * radius,
0.16 + (index % 2) * 0.05,
Math.sin(angle) * radius
);
shape.rotation.set(index * 0.4, index * 0.7, index * 0.2);
world.add(shape);
decorativeShapes.push(shape);
}
const pillarGeometry = new THREE.CylinderGeometry(0.52, 0.69, 1, 6);
const pillarEdgeGeometry = new THREE.EdgesGeometry(pillarGeometry);
const outcomeObjects = [];
const positions = [
[-3.35, 0.12],
[-1.12, -0.08],
[1.12, 0.08],
[3.35, -0.12]
];
function createOutcomeObjects() {
state.outcomes.forEach((outcome, index) => {
const group = new THREE.Group();
group.position.set(positions[index][0], 0, positions[index][1]);
world.add(group);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.8, 0.86, 0.18, 6),
new THREE.MeshStandardMaterial({
color: 0x203b40,
roughness: 0.78,
metalness: 0.14,
flatShading: true
})
);
base.position.y = 0.08;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const accentRing = new THREE.Mesh(
new THREE.TorusGeometry(0.73, 0.025, 4, 24),
new THREE.MeshStandardMaterial({
color: outcome.color,
emissive: outcome.color,
emissiveIntensity: 0.22,
roughness: 0.5,
metalness: 0.2
})
);
accentRing.rotation.x = Math.PI / 2;
accentRing.position.y = 0.19;
group.add(accentRing);
const pillarMaterial = new THREE.MeshStandardMaterial({
color: outcome.color,
emissive: outcome.color,
emissiveIntensity: 0.1,
roughness: 0.48,
metalness: 0.16,
flatShading: true,
transparent: true,
opacity: 1
});
const pillar = new THREE.Mesh(pillarGeometry, pillarMaterial);
pillar.castShadow = true;
pillar.receiveShadow = true;
group.add(pillar);
const edges = new THREE.LineSegments(
pillarEdgeGeometry,
new THREE.LineBasicMaterial({
color: 0x0a1b20,
transparent: true,
opacity: 0.52
})
);
pillar.add(edges);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.25, 0),
new THREE.MeshStandardMaterial({
color: outcome.color,
emissive: outcome.color,
emissiveIntensity: 0.25,
roughness: 0.38,
metalness: 0.2,
flatShading: true,
transparent: true,
opacity: 1
})
);
cap.castShadow = true;
group.add(cap);
const label = document.createElement("div");
label.className = "scene-label";
labelLayer.appendChild(label);
outcomeObjects.push({
group,
pillar,
cap,
label,
currentHeight: 0.08,
targetHeight: 0.08
});
});
}
createOutcomeObjects();
const beacon = new THREE.Group();
beacon.position.set(0, 0.95, -2.8);
world.add(beacon);
const beaconCore = new THREE.Mesh(
new THREE.OctahedronGeometry(0.33, 0),
new THREE.MeshStandardMaterial({
color: 0xf4dfa0,
emissive: 0xf4cc69,
emissiveIntensity: 0.3,
roughness: 0.4,
metalness: 0.2,
flatShading: true
})
);
beaconCore.castShadow = true;
beacon.add(beaconCore);
const beaconRing = new THREE.Mesh(
new THREE.TorusGeometry(0.55, 0.022, 4, 28),
new THREE.MeshBasicMaterial({
color: 0xf4cc69,
transparent: true,
opacity: 0.72
})
);
beaconRing.rotation.x = Math.PI / 2.6;
beacon.add(beaconRing);
const evLabel = document.createElement("div");
evLabel.className = "scene-label ev-label";
evLabel.innerHTML = `
<span class="label-name">Model mean</span>
<span class="label-prob">—</span>
<span class="label-pay">expected value</span>
`;
labelLayer.appendChild(evLabel);
function updateSceneTargets() {
outcomeObjects.forEach((object, index) => {
const probability = state.probabilities[index] || 0;
object.targetHeight = 0.08 + probability * 4.35;
object.pillar.material.opacity = 0.42 + probability * 0.58;
object.cap.material.opacity = 0.48 + probability * 0.52;
object.pillar.material.emissiveIntensity = 0.06 + probability * 0.18;
object.cap.material.emissiveIntensity = 0.12 + probability * 0.25;
});
}
// ------------------------------------------------------------
// Direct camera controls — no Three.js addons
// ------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= deltaX * 0.007;
cameraState.pitch = Math.min(
1.28,
Math.max(0.35, cameraState.pitch + deltaY * 0.005)
);
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = Math.min(
17,
Math.max(8.5, cameraState.radius + event.deltaY * 0.008)
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraState.yaw = 0.34;
cameraState.pitch = 0.77;
cameraState.radius = 12.4;
updateCamera();
});
renderer.domElement.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
cameraState.yaw += 0.1;
break;
case "ArrowRight":
cameraState.yaw -= 0.1;
break;
case "ArrowUp":
cameraState.pitch = Math.min(1.28, cameraState.pitch + 0.08);
break;
case "ArrowDown":
cameraState.pitch = Math.max(0.35, cameraState.pitch - 0.08);
break;
case "+":
case "=":
cameraState.radius = Math.max(8.5, cameraState.radius - 0.5);
break;
case "-":
cameraState.radius = Math.min(17, cameraState.radius + 0.5);
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
function resizeRenderer() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resizeRenderer).observe(stage);
} else {
window.addEventListener("resize", resizeRenderer);
}
resizeRenderer();
// ------------------------------------------------------------
// Simulation and chart
// ------------------------------------------------------------
function clearSimulation(message = "No simulation run yet.") {
runStatus.textContent = message;
observedMean.textContent = "—";
observedDifference.textContent = "—";
observedList.innerHTML = "";
runChart.innerHTML = "";
chartEmpty.classList.remove("hidden");
}
function drawChart(runningMean, trialTotal) {
const width = 900;
const height = 245;
const padding = { left: 52, right: 20, top: 18, bottom: 34 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const maximum =
Math.max(
1,
state.expectedValue,
...state.outcomes.map((outcome) => outcome.payout),
...runningMean
) * 1.12;
const x = (index) =>
padding.left +
(trialTotal <= 1 ? 0 : (index / (trialTotal - 1)) * plotWidth);
const y = (value) => padding.top + plotHeight - (value / maximum) * plotHeight;
const grid = [];
for (let index = 0; index <= 4; index += 1) {
const value = (maximum / 4) * index;
const gridY = y(value);
grid.push(`
<line
x1="${padding.left}"
y1="${gridY}"
x2="${width - padding.right}"
y2="${gridY}"
stroke="rgba(181,226,224,0.10)"
stroke-width="1"
/>
<text
x="${padding.left - 9}"
y="${gridY + 4}"
fill="#789395"
font-size="11"
text-anchor="end"
>${formatNumber(value, 1)}</text>
`);
}
const pathData = runningMean
.map((value, index) => `${index === 0 ? "M" : "L"} ${x(index)} ${y(value)}`)
.join(" ");
const xTicks = [0, Math.floor(trialTotal / 2), trialTotal - 1]
.map((index, tickIndex, array) => {
const uniqueIndex = array.indexOf(index);
if (uniqueIndex !== tickIndex) return "";
return `
<text
x="${x(index)}"
y="${height - 9}"
fill="#789395"
font-size="11"
text-anchor="${tickIndex === 0 ? "start" : tickIndex === array.length - 1 ? "end" : "middle"}"
>${index + 1}</text>
`;
})
.join("");
const modelY = y(state.expectedValue);
const lastX = x(runningMean.length - 1);
const lastY = y(runningMean[runningMean.length - 1]);
runChart.innerHTML = `
<defs>
<linearGradient id="areaGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#63d8c5" stop-opacity="0.22" />
<stop offset="100%" stop-color="#63d8c5" stop-opacity="0" />
</linearGradient>
</defs>
${grid.join("")}
<line
x1="${padding.left}"
y1="${modelY}"
x2="${width - padding.right}"
y2="${modelY}"
stroke="#f4cc69"
stroke-width="1.5"
stroke-dasharray="7 6"
opacity="0.9"
/>
<path
d="${pathData} L ${lastX} ${padding.top + plotHeight} L ${x(0)} ${padding.top + plotHeight} Z"
fill="url(#areaGradient)"
/>
<path
d="${pathData}"
fill="none"
stroke="#63d8c5"
stroke-width="2.4"
stroke-linejoin="round"
stroke-linecap="round"
vector-effect="non-scaling-stroke"
/>
<circle cx="${lastX}" cy="${lastY}" r="4" fill="#63d8c5" />
<text
x="${padding.left}"
y="${height - 9}"
fill="#789395"
font-size="11"
text-anchor="start"
>1</text>
${xTicks}
<text
x="${width - padding.right}"
y="${height - 9}"
fill="#789395"
font-size="11"
text-anchor="end"
>${trialTotal} trials</text>
`;
chartEmpty.classList.add("hidden");
}
function runSimulation() {
const trialTotal = Math.min(
2000,
Math.max(1, Math.floor(Number(trialCount.value) || 1))
);
trialCount.value = trialTotal;
trialRange.value = trialTotal;
simulateButton.disabled = true;
runStatus.textContent = `Running ${formatNumber(trialTotal)} illustrative trials…`;
const counts = new Array(state.outcomes.length).fill(0);
const runningMean = [];
let payoutTotal = 0;
for (let trial = 0; trial < trialTotal; trial += 1) {
const draw = Math.random();
let cumulative = 0;
let selectedIndex = state.outcomes.length - 1;
for (let index = 0; index < state.outcomes.length; index += 1) {
cumulative += state.probabilities[index];
if (draw < cumulative) {
selectedIndex = index;
break;
}
}
counts[selectedIndex] += 1;
payoutTotal += state.outcomes[selectedIndex].payout;
runningMean.push(payoutTotal / (trial + 1));
}
const sampleMean = payoutTotal / trialTotal;
const difference = sampleMean - state.expectedValue;
observedMean.textContent = `${formatNumber(sampleMean)} pts`;
observedDifference.textContent = `${difference >= 0 ? "+" : ""}${formatNumber(difference)} pts`;
observedList.innerHTML = state.outcomes
.map((outcome, index) => {
const modelProbability = formatPercent(state.probabilities[index]);
const observedProbability = formatPercent(counts[index] / trialTotal);
return `
<div class="observed-row" style="--outcome-color: ${outcome.css}">
<i class="swatch" aria-hidden="true"></i>
<span>${outcome.name}</span>
<strong title="Model probability">${modelProbability}</strong>
<strong title="Observed probability">${observedProbability}</strong>
</div>
`;
})
.join("");
runStatus.textContent =
`${formatNumber(trialTotal)} trials complete. ` +
`Observed frequencies may differ from the model because of sampling variation.`;
drawChart(runningMean, trialTotal);
simulateButton.disabled = false;
}
trialCount.addEventListener("input", () => {
let value = Number(trialCount.value);
value = Number.isFinite(value) ? Math.min(2000, Math.max(1, value)) : 1;
trialRange.value = value;
});
trialCount.addEventListener("change", () => {
let value = Math.floor(Number(trialCount.value) || 1);
value = Math.min(2000, Math.max(1, value));
trialCount.value = value;
trialRange.value = value;
});
trialRange.addEventListener("input", () => {
trialCount.value = trialRange.value;
});
simulateButton.addEventListener("click", runSimulation);
document.getElementById("resetButton").addEventListener("click", () => {
state.outcomes = DEFAULTS.map((outcome) => ({ ...outcome }));
updateModel();
clearSimulation("Defaults restored. Run again for a new sample.");
});
// ------------------------------------------------------------
// Render loop and projected HTML labels
// ------------------------------------------------------------
const projected = new THREE.Vector3();
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
function positionLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.visibility = visible ? "visible" : "hidden";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * stage.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * stage.clientHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function animate() {
requestAnimationFrame(animate);
outcomeObjects.forEach((object, index) => {
const difference = object.targetHeight - object.currentHeight;
object.currentHeight += difference * (reducedMotion ? 1 : 0.11);
const height = object.currentHeight;
object.pillar.scale.y = height;
object.pillar.position.y = 0.17 + height / 2;
object.cap.position.y = 0.17 + height + 0.14;
if (!reducedMotion) {
object.cap.rotation.y += 0.006;
object.cap.rotation.x = Math.sin(performance.now() * 0.001 + index) * 0.12;
}
const probability = state.probabilities[index] || 0;
const outcome = state.outcomes[index];
object.label.innerHTML = `
<span class="label-name">${outcome.name}</span>
<span class="label-prob">${formatPercent(probability)}</span>
<span class="label-pay">${formatNumber(outcome.payout)} points</span>
`;
});
if (!reducedMotion) {
decorativeShapes.forEach((shape, index) => {
shape.rotation.y += 0.0015 * (index % 2 === 0 ? 1 : -1);
shape.position.y += Math.sin(performance.now() * 0.001 + index) * 0.00008;
});
beacon.rotation.y += 0.008;
beaconRing.rotation.z += 0.004;
const beaconScale = 1 + Math.sin(performance.now() * 0.002) * 0.045;
beaconCore.scale.setScalar(beaconScale);
}
evLabel.querySelector(".label-prob").textContent =
`${formatNumber(state.expectedValue)} pts`;
renderer.render(scene, camera);
world.updateMatrixWorld(true);
outcomeObjects.forEach((object) => {
const anchor = object.cap.getWorldPosition(new THREE.Vector3());
anchor.y += 0.34;
positionLabel(object.label, anchor);
});
const beaconAnchor = beacon.getWorldPosition(new THREE.Vector3());
beaconAnchor.y += 0.72;
positionLabel(evLabel, beaconAnchor);
}
// ------------------------------------------------------------
// Initialize
// ------------------------------------------------------------
buildControls();
updateModel();
clearSimulation();
animate();
</script>
</body>
</html>
```