Prompt specification
Build or customize the Three.js 3D scene "Board-game chance teaching table" 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: Board-game chance teaching table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/board-game-chance-teaching-table-x1827
Scene Description Prompt:
Please use Three.js from cdnjs for a voxel scene based on this idea: board-game chance teaching table. Compose a simple game track and two dice beside the full outcome grid; compare movement frequencies under an explicitly fair independent-dice model. Return one self-contained HTML file.
Working Three.js Starter (board-game-chance-teaching-table-x1827):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chance Lab — Voxel Dice & Movement Table</title>
<style>
:root {
color-scheme: dark;
--ink: #e9f5ff;
--muted: #a8bfce;
--cyan: #55d8ff;
--coral: #ff906b;
--panel: rgba(8, 25, 38, 0.82);
--border: rgba(170, 220, 245, 0.2);
}
* { box-sizing: border-box; }
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07131f;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 10;
}
.panel {
position: absolute;
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.intro {
top: 22px;
left: 22px;
width: 330px;
padding: 18px 19px 16px;
border-radius: 18px;
}
.kicker {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 8px 0 9px;
font-size: clamp(29px, 3vw, 43px);
line-height: 0.98;
letter-spacing: -0.045em;
}
.intro p,
.model p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.hint {
margin-top: 12px !important;
padding-top: 11px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
color: #d4e6f1 !important;
font-size: 12px !important;
}
.model {
top: 22px;
right: 22px;
width: 342px;
padding: 17px 18px;
border-radius: 18px;
}
.model-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.model-title strong {
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.fair-badge {
padding: 4px 8px;
border: 1px solid rgba(85, 216, 255, 0.4);
border-radius: 999px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
}
.formula {
margin: 12px 0 9px;
padding: 10px 12px;
border-radius: 11px;
background: rgba(85, 216, 255, 0.08);
color: #e9fbff;
font: 700 15px/1.35 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.count-row {
display: grid;
grid-template-columns: repeat(11, 1fr);
gap: 3px;
margin: 11px 0 8px;
}
.count-row span {
min-width: 0;
padding: 5px 0;
border-radius: 5px;
background: rgba(255, 255, 255, 0.07);
color: #dff6ff;
text-align: center;
font: 700 11px ui-monospace, monospace;
}
.sum-labels {
display: grid;
grid-template-columns: repeat(11, 1fr);
gap: 3px;
color: #7892a1;
text-align: center;
font: 700 9px ui-monospace, monospace;
}
.controls {
bottom: 22px;
left: 50%;
display: flex;
gap: 9px;
padding: 9px;
border-radius: 16px;
transform: translateX(-50%);
pointer-events: auto;
}
button {
min-width: 106px;
padding: 12px 16px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 11px;
background: rgba(255, 255, 255, 0.075);
color: var(--ink);
font: 750 12px/1 ui-sans-serif, system-ui, sans-serif;
letter-spacing: 0.035em;
cursor: pointer;
transition: transform 150ms ease, background 150ms ease, border-color 150ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
background: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.28);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
button:disabled {
opacity: 0.48;
cursor: wait;
}
button.primary {
border-color: rgba(85, 216, 255, 0.5);
background: linear-gradient(135deg, #1c91b7, #37c7ed);
color: #04131c;
box-shadow: 0 8px 24px rgba(43, 191, 232, 0.22);
}
.readout {
bottom: 22px;
left: 22px;
display: grid;
grid-template-columns: repeat(4, auto);
gap: 17px;
padding: 13px 15px;
border-radius: 14px;
}
.stat span {
display: block;
margin-bottom: 3px;
color: #7e9aaa;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stat strong {
color: #f2fbff;
font: 750 16px ui-monospace, monospace;
}
.legend {
right: 22px;
bottom: 22px;
display: flex;
align-items: center;
gap: 15px;
padding: 12px 14px;
border-radius: 14px;
color: #bdd0dc;
font-size: 11px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 3px;
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.12);
}
.swatch.fair { background: var(--cyan); }
.swatch.sample { background: var(--coral); }
.tooltip {
position: fixed;
z-index: 30;
display: none;
max-width: 270px;
padding: 11px 12px;
border: 1px solid rgba(150, 220, 250, 0.28);
border-radius: 11px;
background: rgba(4, 17, 27, 0.96);
box-shadow: 0 12px 34px rgba(0, 0, 0, 0.38);
color: #dcecf5;
font-size: 12px;
line-height: 1.5;
pointer-events: none;
}
.tooltip strong {
color: white;
font-size: 13px;
}
.tooltip .accent {
color: var(--cyan);
}
@media (max-width: 980px) {
.intro {
width: 280px;
}
.model {
width: 290px;
}
.legend {
display: none;
}
.readout {
grid-template-columns: repeat(2, auto);
}
}
@media (max-width: 700px) {
.intro {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 13px 15px;
}
.intro h1 {
margin: 5px 0;
font-size: 28px;
}
.intro p {
display: none;
}
.hint {
margin-top: 7px !important;
padding-top: 7px;
}
.model {
top: 145px;
right: 10px;
width: 235px;
padding: 12px;
}
.model p,
.formula,
.count-row,
.sum-labels {
display: none;
}
.readout {
left: 10px;
bottom: 78px;
gap: 11px;
padding: 10px 11px;
}
.stat strong {
font-size: 13px;
}
.controls {
bottom: 10px;
width: calc(100% - 20px);
justify-content: center;
gap: 6px;
padding: 7px;
}
button {
min-width: 0;
flex: 1;
padding: 11px 8px;
font-size: 10px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="hud">
<section class="panel intro">
<div class="kicker">Chance Lab · Voxel Table 01</div>
<h1>Fair dice.<br />Visible odds.</h1>
<p>
A 6 × 6 outcome grid, two independent dice, and a twelve-space track.
A roll moves the token by the dice sum.
</p>
<p class="hint">
Hover a grid tile or chart bar for exact probabilities. Drag to orbit,
scroll to zoom, and press <strong>R</strong> to roll.
</p>
</section>
<section class="panel model">
<div class="model-title">
<strong>Explicit model</strong>
<span class="fair-badge">Fair + independent</span>
</div>
<p>
Each die has P(face = k) = 1/6. The dice are independent, so every
ordered pair has probability 1/36.
</p>
<div class="formula">P(S = s) = n<sub>s</sub> / 36</div>
<div class="count-row" aria-label="Number of ordered outcomes for each sum">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
<span>6</span><span>5</span><span>4</span><span>3</span><span>2</span><span>1</span>
</div>
<div class="sum-labels">
<span>2</span><span>3</span><span>4</span><span>5</span><span>6</span>
<span>7</span><span>8</span><span>9</span><span>10</span><span>11</span><span>12</span>
</div>
<p style="margin-top:10px">
Cyan bars are the exact model. Coral bars are the observed frequency in
the rolling sample.
</p>
</section>
<section class="panel controls" aria-label="Scene controls">
<button id="rollButton" class="primary" title="Roll both independent dice">ROLL DICE</button>
<button id="batchButton" title="Add 60 model-consistent rolls to the observed sample">+60 SAMPLE</button>
<button id="resetButton" title="Clear the observed sample">RESET SAMPLE</button>
<button id="viewButton" title="Reset the camera">RESET VIEW</button>
</section>
<section class="panel readout" aria-live="polite">
<div class="stat">
<span>Sample size</span>
<strong id="rollCount">n = 120</strong>
</div>
<div class="stat">
<span>Latest sum</span>
<strong id="latestSum">—</strong>
</div>
<div class="stat">
<span>Model chance</span>
<strong id="latestFair">—</strong>
</div>
<div class="stat">
<span>Observed</span>
<strong id="latestObserved">—</strong>
</div>
</section>
<section class="panel legend" aria-label="Chart legend">
<div class="legend-item"><span class="swatch fair"></span>Fair model</div>
<div class="legend-item"><span class="swatch sample"></span>Rolled sample</div>
<div class="legend-item">Cell color = sum</div>
</section>
</div>
<div id="tooltip" class="tooltip"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const tooltip = document.getElementById("tooltip");
const rollButton = document.getElementById("rollButton");
const batchButton = document.getElementById("batchButton");
const resetButton = document.getElementById("resetButton");
const viewButton = document.getElementById("viewButton");
const rollCountElement = document.getElementById("rollCount");
const latestSumElement = document.getElementById("latestSum");
const latestFairElement = document.getElementById("latestFair");
const latestObservedElement = document.getElementById("latestObserved");
// ---------------------------------------------------------------------
// Renderer, scene, camera, and direct camera controls
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.Fog(0x07131f, 30, 62);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive voxel scene showing an outcome grid, two dice, a game track, and movement-frequency bars"
);
stage.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-12, 12, 9, -9, 0.1, 100);
const cameraState = {
azimuth: 0.58,
elevation: 0.78,
zoom: 1,
target: new THREE.Vector3(0.25, 0, 0.1)
};
function updateCamera() {
const radius = 30;
const horizontal = Math.cos(cameraState.elevation) * radius;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.azimuth) * horizontal,
cameraState.target.y + Math.sin(cameraState.elevation) * radius,
cameraState.target.z + Math.cos(cameraState.azimuth) * horizontal
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const aspect = window.innerWidth / window.innerHeight;
const viewHeight = Math.max(17.5, 22 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
updateCamera();
let pointerState = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointerState = {
id: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
shift: event.shiftKey
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
hideTooltip();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState) {
updateHover(event);
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
if (
Math.abs(event.clientX - pointerState.startX) +
Math.abs(event.clientY - pointerState.startY) >
5
) {
pointerState.moved = true;
}
if (pointerState.shift) {
const scale =
(camera.top - camera.bottom) / camera.zoom / renderer.domElement.clientHeight;
const right = new THREE.Vector3(
Math.cos(cameraState.azimuth),
0,
-Math.sin(cameraState.azimuth)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.azimuth),
0,
-Math.cos(cameraState.azimuth)
);
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -6, 6);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -5, 5);
} else {
cameraState.azimuth -= dx * 0.006;
cameraState.elevation = THREE.MathUtils.clamp(
cameraState.elevation + dy * 0.0045,
0.32,
1.38
);
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerState) return;
const wasClick = !pointerState.moved;
pointerState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
if (wasClick) {
const hit = pick(event);
if (hit?.object.userData.kind === "dice") {
rollDice();
} else {
updateHover(event);
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState = null;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerState) clearHover();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.62,
2.15
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetView);
function resetView() {
cameraState.azimuth = 0.58;
cameraState.elevation = 0.78;
cameraState.zoom = 1;
cameraState.target.set(0.25, 0, 0.1);
updateCamera();
}
viewButton.addEventListener("click", resetView);
window.addEventListener("keydown", (event) => {
if (event.code === "KeyR") {
event.preventDefault();
rollDice();
}
});
// ---------------------------------------------------------------------
// Lighting and voxel construction helpers
// ---------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xbfeaff, 0x17202d, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff3da, 3.4);
keyLight.position.set(8, 17, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 14;
keyLight.shadow.camera.bottom = -14;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55c9ff, 1.15);
rimLight.position.set(-10, 7, -8);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({ color: 0x081521, roughness: 0.95 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.35;
floor.receiveShadow = true;
scene.add(floor);
function material(color, roughness = 0.72, metalness = 0.02) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness
});
}
function box(width, height, depth, mat, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), mat);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
const textTextureCache = new Map();
const badgeTextureCache = new Map();
function makeTextTexture(text, options = {}) {
const {
background = "rgba(6, 22, 34, 0.88)",
foreground = "#eaf8ff",
border = "rgba(130, 210, 240, 0.25)"
} = options;
const key = `${text}|${background}|${foreground}|${border}`;
if (textTextureCache.has(key)) return textTextureCache.get(key);
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 6, 6, 1012, 244, 36);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = border;
ctx.lineWidth = 5;
ctx.stroke();
let fontSize = 86;
ctx.font = `800 ${fontSize}px system-ui, sans-serif`;
while (ctx.measureText(text).width > 925 && fontSize > 30) {
fontSize -= 3;
ctx.font = `800 ${fontSize}px system-ui, sans-serif`;
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = foreground;
ctx.fillText(text, 512, 132);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
textTextureCache.set(key, texture);
return texture;
}
function makeBadgeTexture(text, options = {}) {
const {
background = "rgba(250, 253, 255, 0.9)",
foreground = "#102635"
} = options;
const key = `${text}|${background}|${foreground}`;
if (badgeTextureCache.has(key)) return badgeTextureCache.get(key);
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 256, 256);
roundedRect(ctx, 16, 16, 224, 224, 48);
ctx.fillStyle = background;
ctx.fill();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "800 112px system-ui, sans-serif";
ctx.fillStyle = foreground;
ctx.fillText(text, 128, 133);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
badgeTextureCache.set(key, texture);
return texture;
}
function flatBadge(text, width, height, x, y, z, options = {}) {
const texture = makeBadgeTexture(text, options);
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
mesh.rotation.x = -Math.PI / 2;
mesh.position.set(x, y, z);
mesh.renderOrder = 4;
scene.add(mesh);
return mesh;
}
function textSprite(text, width, height, x, y, z, options = {}) {
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: makeTextTexture(text, options),
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
sprite.position.set(x, y, z);
sprite.scale.set(width, height, 1);
sprite.renderOrder = 50;
scene.add(sprite);
return sprite;
}
// ---------------------------------------------------------------------
// Table and board
// ---------------------------------------------------------------------
const woodMaterial = material(0x594034, 0.86);
const boardMaterial = material(0x102c3b, 0.8);
const edgeMaterial = material(0x1b4658, 0.62);
const darkMaterial = material(0x071a25, 0.72);
box(21, 0.95, 14, woodMaterial, 0, -0.5, 0);
box(20.5, 0.12, 13.5, boardMaterial, 0, 0.035, 0);
box(20.7, 0.08, 0.13, edgeMaterial, 0, 0.06, -6.72);
box(20.7, 0.08, 0.13, edgeMaterial, 0, 0.06, 6.72);
box(0.13, 0.08, 13.5, edgeMaterial, -10.22, 0.06, 0);
box(0.13, 0.08, 13.5, edgeMaterial, 10.22, 0.06, 0);
const legMaterial = material(0x302b29, 0.9);
for (const x of [-9.1, 9.1]) {
for (const z of [-5.7, 5.7]) {
box(0.7, 2.3, 0.7, legMaterial, x, -2.1, z);
}
}
// ---------------------------------------------------------------------
// Full 6 x 6 ordered outcome grid
// ---------------------------------------------------------------------
const fairOutcomeCounts = [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1];
const sumColors = {
2: 0x71dfbd,
3: 0x4fc6a7,
4: 0x66cc83,
5: 0x9fd56b,
6: 0xe8ca59,
7: 0xf3a550,
8: 0xf17d5d,
9: 0xeb5e69,
10: 0xd95089,
11: 0xb667c4,
12: 0x8f78d1
};
const gridCenter = new THREE.Vector3(-2.85, 0, -0.85);
const gridPitch = 0.94;
const gridCellSize = 0.86;
const outcomeCells = [];
const pickables = [];
box(6.35, 0.12, 6.35, edgeMaterial, gridCenter.x, 0.11, gridCenter.z);
for (let row = 0; row < 6; row++) {
for (let col = 0; col < 6; col++) {
const dieA = row + 1;
const dieB = col + 1;
const sum = dieA + dieB;
const x = gridCenter.x + (col - 2.5) * gridPitch;
const z = gridCenter.z + (row - 2.5) * gridPitch;
const cellMaterial = new THREE.MeshStandardMaterial({
color: sumColors[sum],
roughness: 0.66,
metalness: 0.03,
emissive: 0x000000,
emissiveIntensity: 0
});
const cell = box(gridCellSize, 0.14, gridCellSize, cellMaterial, x, 0.19, z);
cell.userData = {
kind: "outcome",
dieA,
dieB,
sum,
probability: fairOutcomeCounts[sum - 2] / 36
};
outcomeCells.push(cell);
pickables.push(cell);
flatBadge(String(sum), 0.36, 0.36, x, 0.267, z, {
background: "rgba(255,255,255,0.82)",
foreground: "#102635"
});
}
}
// Row and column identifiers make all 36 ordered outcomes explicit.
for (let i = 0; i < 6; i++) {
const rowZ = gridCenter.z + (i - 2.5) * gridPitch;
const colX = gridCenter.x + (i - 2.5) * gridPitch;
flatBadge(`A${i + 1}`, 0.44, 0.44, gridCenter.x - 3.35, 0.17, rowZ, {
background: "rgba(5,22,33,0.94)",
foreground: "#9feaff"
});
flatBadge(`B${i + 1}`, 0.44, 0.44, colX, 0.17, gridCenter.z + 3.35, {
background: "rgba(5,22,33,0.94)",
foreground: "#9feaff"
});
}
textSprite("36 ORDERED OUTCOMES", 3.6, 0.54, -2.85, 1.35, -5.45);
textSprite("DIE A ↓", 1.15, 0.34, -6.35, 0.7, -0.85, {
background: "rgba(5,22,33,0.72)",
foreground: "#8de8ff",
border: "rgba(85,216,255,0.22)"
});
textSprite("DIE B →", 1.15, 0.34, -2.85, 0.7, 2.55, {
background: "rgba(5,22,33,0.72)",
foreground: "#8de8ff",
border: "rgba(85,216,255,0.22)"
});
// ---------------------------------------------------------------------
// Twelve-space movement track
// ---------------------------------------------------------------------
const trackPoints = [
new THREE.Vector3(-7.2, 0.23, -4.8),
new THREE.Vector3(-4.9, 0.23, -4.8),
new THREE.Vector3(-2.6, 0.23, -4.8),
new THREE.Vector3(-0.3, 0.23, -4.8),
new THREE.Vector3(1.6, 0.23, -3.1),
new THREE.Vector3(1.6, 0.23, -0.5),
new THREE.Vector3(1.6, 0.23, 2.1),
new THREE.Vector3(-0.2, 0.23, 4.2),
new THREE.Vector3(-2.8, 0.23, 4.2),
new THREE.Vector3(-5.4, 0.23, 4.2),
new THREE.Vector3(-7.2, 0.23, 2.2),
new THREE.Vector3(-7.2, 0.23, -1.1)
];
const trackMaterials = [
material(0x1a6075, 0.65),
material(0x18566d, 0.65),
material(0x1c5368, 0.65),
material(0x1d4e62, 0.65),
material(0x1b5367, 0.65),
material(0x1d5264, 0.65),
material(0x1b4d60, 0.65),
material(0x1d4b5d, 0.65),
material(0x1b5064, 0.65),
material(0x1b4659, 0.65),
material(0x1b5265, 0.65),
material(0x1a4253, 0.65)
];
const startTileMaterial = material(0xe9f5f1, 0.62);
for (let i = 0; i < trackPoints.length; i++) {
const point = trackPoints[i];
const tile = box(
0.84,
0.14,
0.84,
i === 0 ? startTileMaterial : trackMaterials[i],
point.x,
0.15,
point.z
);
tile.userData = { kind: "track", index: i };
pickables.push(tile);
flatBadge(String(i), 0.37, 0.37, point.x, 0.23, point.z, {
background: i === 0 ? "rgba(255,145,98,0.94)" : "rgba(5,22,33,0.9)",
foreground: i === 0 ? "#102635" : "#dff7ff"
});
}
const trackLineMaterial = material(0x2a7890, 0.72);
for (let i = 0; i < trackPoints.length; i++) {
const a = trackPoints[i];
const b = trackPoints[(i + 1) % trackPoints.length];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const middleX = (a.x + b.x) / 2;
const middleZ = (a.z + b.z) / 2;
const segment = box(0.13, 0.035, length, trackLineMaterial, middleX, 0.105, middleZ);
segment.rotation.y = Math.atan2(dx, dz);
}
textSprite("MOVE TOKEN = DICE SUM", 3.15, 0.46, -4.55, 1.1, 5.45);
// Voxel player token.
const token = new THREE.Group();
const tokenMaterial = material(0xff7659, 0.48, 0.05);
const tokenDarkMaterial = material(0xc84238, 0.55);
box(0.62, 0.16, 0.62, tokenDarkMaterial, 0, 0.08, 0, token);
box(0.4, 0.48, 0.4, tokenMaterial, 0, 0.4, 0, token);
box(0.46, 0.36, 0.46, tokenMaterial, 0, 0.8, 0, token);
box(0.18, 0.08, 0.18, tokenDarkMaterial, 0, 1.03, 0, token);
token.position.copy(trackPoints[0]);
scene.add(token);
let tokenIndex = 0;
let tokenQueue = [];
let tokenTween = null;
function moveToken(steps) {
tokenQueue = [];
for (let i = 0; i < steps; i++) {
tokenIndex = (tokenIndex + 1) % trackPoints.length;
tokenQueue.push(tokenIndex);
}
}
// ---------------------------------------------------------------------
// Two voxel dice
// ---------------------------------------------------------------------
const dicePlatformMaterial = material(0x153d50, 0.66);
box(4.55, 0.18, 4.25, dicePlatformMaterial, 5.05, 0.14, -2.55);
const dieBodyMaterial = new THREE.MeshStandardMaterial({
color: 0xf2f3e9,
roughness: 0.42,
metalness: 0.04,
emissive: 0x000000,
emissiveIntensity: 0
});
const pipMaterial = material(0x10202a, 0.44);
const pipGeometry = new THREE.BoxGeometry(0.18, 0.08, 0.18);
const pipCoordinates = {
1: [[0, 0]],
2: [[-1, -1], [1, 1]],
3: [[-1, -1], [0, 0], [1, 1]],
4: [[-1, -1], [-1, 1], [1, -1], [1, 1]],
5: [[-1, -1], [-1, 1], [0, 0], [1, -1], [1, 1]],
6: [[-1, -1], [-1, 0], [-1, 1], [1, -1], [1, 0], [1, 1]]
};
function createDie(x, z, name) {
const group = new THREE.Group();
group.position.set(x, 0.24, z);
const body = box(1.45, 1.45, 1.45, dieBodyMaterial.clone(), 0, 0.78, 0, group);
body.userData = { kind: "dice", name };
const pips = new THREE.Group();
group.add(pips);
scene.add(group);
pickables.push(body);
textSprite(name, 1.15, 0.34, x, 0.75, -4.12, {
background: "rgba(5,22,33,0.76)",
foreground: "#e7f7ff",
border: "rgba(85,216,255,0.2)"
});
return { group, body, pips, baseY: 0.24 };
}
const dieA = createDie(4.02, -2.55, "DIE A");
const dieB = createDie(6.08, -2.55, "DIE B");
function setDieFace(die, face) {
die.pips.clear();
for (const [column, row] of pipCoordinates[face]) {
const pip = new THREE.Mesh(pipGeometry, pipMaterial);
pip.position.set(column * 0.38, 1.53, row * 0.38);
pip.castShadow = true;
die.pips.add(pip);
}
}
textSprite("2 FAIR, INDEPENDENT DICE", 3.6, 0.5, 5.05, 1.45, -4.95);
// ---------------------------------------------------------------------
// Movement-frequency comparison chart
// ---------------------------------------------------------------------
const chartCenterX = 4.8;
const chartBaseY = 0.25;
const chartMaximum = 0.2; // 20% full-scale ceiling
const chartHeight = 3.2; // world units at 20%
const fairBarMaterial = material(0x55d8ff, 0.48, 0.05);
const sampleBarMaterial = material(0xff906b, 0.5, 0.04);
box(9.1, 0.16, 2.75, dicePlatformMaterial, chartCenterX, 0.14, 2.85);
const fairBars = [];
const sampleBars = [];
for (let i = 0; i < 11; i++) {
const sum = i + 2;
const groupX = 0.82 + i * 0.78;
const fairBar = box(0.2, 1, 0.3, fairBarMaterial, groupX - 0.13, chartBaseY, 2.58);
fairBar.scale.y = 0.001;
fairBar.userData = { kind: "bar", source: "fair", sum };
const sampleBar = box(0.2, 1, 0.3, sampleBarMaterial, groupX + 0.13, chartBaseY, 2.98);
sampleBar.scale.y = 0.001;
sampleBar.userData = { kind: "bar", source: "sample", sum };
fairBars.push(fairBar);
sampleBars.push(sampleBar);
pickables.push(fairBar, sampleBar);
flatBadge(String(sum), 0.34, 0.34, groupX, 0.245, 3.48, {
background: "rgba(5,22,33,0.9)",
foreground: "#dff7ff"
});
}
// A fixed 10% reference line keeps the bar scale honest.
box(8.9, 0.025, 0.025, material(0x9dc2d2, 0.5), chartCenterX, chartBaseY + chartHeight / 2, 2.27);
textSprite("10%", 0.66, 0.25, -0.02, chartBaseY + chartHeight / 2, 2.27, {
background: "rgba(5,22,33,0.68)",
foreground: "#b8d4e2",
border: "rgba(255,255,255,0.08)"
});
textSprite("MOVE FREQUENCY: MODEL vs SAMPLE", 4.7, 0.54, chartCenterX, 1.75, 0.95);
textSprite("FAIR MODEL", 1.75, 0.33, 2.0, 0.73, 1.35, {
background: "rgba(5,22,33,0.78)",
foreground: "#55d8ff",
border: "rgba(85,216,255,0.28)"
});
textSprite("ROLLED SAMPLE", 1.9, 0.33, 6.65, 0.73, 1.35, {
background: "rgba(5,22,33,0.78)",
foreground: "#ff906b",
border: "rgba(255,144,107,0.28)"
});
// ---------------------------------------------------------------------
// Fair sampling, statistics, and chart updates
// ---------------------------------------------------------------------
const observedCounts = new Array(13).fill(0);
let totalRolls = 0;
let lastSum = 7;
let busy = false;
let diceAnimation = null;
// Rejection sampling makes each six-sided face exactly equiprobable.
function fairDieFace() {
const limit = 252; // Largest multiple of 6 that fits in one byte.
const bytes = new Uint8Array(1);
do {
crypto.getRandomValues(bytes);
} while (bytes[0] >= limit);
return (bytes[0] % 6) + 1;
}
function probabilityForSum(sum) {
return fairOutcomeCounts[sum - 2] / 36;
}
function updateChart() {
for (let i = 0; i < 11; i++) {
const sum = i + 2;
const fairProbability = probabilityForSum(sum);
const observedProbability = totalRolls ? observedCounts[sum] / totalRolls : 0;
const fairHeight = (fairProbability / chartMaximum) * chartHeight;
const sampleHeight = (observedProbability / chartMaximum) * chartHeight;
fairBars[i].scale.y = Math.max(fairHeight, 0.001);
fairBars[i].position.y = chartBaseY + fairBars[i].scale.y / 2;
sampleBars[i].visible = totalRolls > 0;
sampleBars[i].scale.y = Math.max(sampleHeight, 0.001);
sampleBars[i].position.y = chartBaseY + sampleBars[i].scale.y / 2;
}
}
function updateReadout() {
rollCountElement.textContent = `n = ${totalRolls}`;
latestSumElement.textContent = totalRolls ? String(lastSum) : "—";
if (!totalRolls) {
latestFairElement.textContent = "—";
latestObservedElement.textContent = "—";
return;
}
latestFairElement.textContent = `${(probabilityForSum(lastSum) * 100).toFixed(2)}%`;
latestObservedElement.textContent =
`${((observedCounts[lastSum] / totalRolls) * 100).toFixed(2)}%`;
}
function setBusy(value) {
busy = value;
rollButton.disabled = value;
batchButton.disabled = value;
resetButton.disabled = value;
}
function animateDice(faceA, faceB) {
diceAnimation = {
start: performance.now(),
duration: 900,
faceA,
faceB,
pipsSet: false
};
}
function rollDice() {
if (busy) return;
const faceA = fairDieFace();
const faceB = fairDieFace();
const sum = faceA + faceB;
observedCounts[sum]++;
totalRolls++;
lastSum = sum;
updateChart();
updateReadout();
animateDice(faceA, faceB);
moveToken(sum);
setBusy(true);
window.setTimeout(() => setBusy(false), 1500);
}
function addSixtyRolls() {
if (busy) return;
let finalTokenIndex = tokenIndex;
let faceA = 1;
let faceB = 1;
let sum = 2;
for (let i = 0; i < 60; i++) {
faceA = fairDieFace();
faceB = fairDieFace();
sum = faceA + faceB;
observedCounts[sum]++;
totalRolls++;
lastSum = sum;
finalTokenIndex = (finalTokenIndex + sum) % trackPoints.length;
}
updateChart();
updateReadout();
animateDice(faceA, faceB);
// Summarize the batch by moving to its final track location.
const aggregateSteps = (finalTokenIndex - tokenIndex + trackPoints.length) % trackPoints.length;
moveToken(aggregateSteps);
setBusy(true);
window.setTimeout(() => setBusy(false), 1500);
}
function resetSample() {
if (busy) return;
observedCounts.fill(0);
totalRolls = 0;
lastSum = 7;
tokenIndex = 0;
tokenQueue = [];
tokenTween = null;
token.position.copy(trackPoints[0]);
setDieFace(dieA, 1);
setDieFace(dieB, 1);
updateChart();
updateReadout();
}
rollButton.addEventListener("click", rollDice);
batchButton.addEventListener("click", addSixtyRolls);
resetButton.addEventListener("click", resetSample);
// Start with a visible comparison sample, generated with the same fair model.
for (let i = 0; i < 120; i++) {
const faceA = fairDieFace();
const faceB = fairDieFace();
observedCounts[faceA + faceB]++;
totalRolls++;
lastSum = faceA + faceB;
if (i === 119) {
setDieFace(dieA, faceA);
setDieFace(dieB, faceB);
}
}
updateChart();
updateReadout();
// ---------------------------------------------------------------------
// Hover picking and explanatory tooltip
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredObject = null;
function pick(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0] : null;
}
function clearHover() {
if (hoveredObject?.material?.emissive) {
hoveredObject.material.emissive.setHex(0x000000);
hoveredObject.material.emissiveIntensity = 0;
}
hoveredObject = null;
renderer.domElement.style.cursor = "grab";
hideTooltip();
}
function updateHover(event) {
const hit = pick(event);
const object = hit?.object ?? null;
if (hoveredObject && hoveredObject !== object && hoveredObject.material?.emissive) {
hoveredObject.material.emissive.setHex(0x000000);
hoveredObject.material.emissiveIntensity = 0;
}
hoveredObject = object;
if (!object) {
hideTooltip();
renderer.domElement.style.cursor = "grab";
return;
}
if (object.material?.emissive) {
object.material.emissive.setHex(0xffffff);
object.material.emissiveIntensity = object.userData.kind === "outcome" ? 0.22 : 0.12;
}
const data = object.userData;
renderer.domElement.style.cursor = data.kind === "dice" ? "pointer" : "help";
if (data.kind === "outcome") {
showTooltip(
event,
`<strong>Die A = ${data.dieA} × Die B = ${data.dieB}</strong><br>
Sum = <span class="accent">${data.sum}</span><br>
Fair sum chance: <strong>${(data.probability * 100).toFixed(2)}%</strong><br>
This exact ordered outcome: <strong>2.78%</strong>`
);
} else if (data.kind === "bar") {
const probability = probabilityForSum(data.sum);
const observed = totalRolls ? observedCounts[data.sum] / totalRolls : 0;
showTooltip(
event,
`<strong>Movement size ${data.sum}</strong><br>
Fair model: <span class="accent">${(probability * 100).toFixed(2)}%</span><br>
Rolled sample: <strong>${(observed * 100).toFixed(2)}%</strong><br>
Observed count: ${observedCounts[data.sum]} / ${totalRolls}`
);
} else if (data.kind === "dice") {
showTooltip(
event,
`<strong>${data.name}</strong><br>
Each face has probability 1/6.<br>
Click to roll both dice.`
);
} else if (data.kind === "track") {
showTooltip(
event,
`<strong>Track space ${data.index}</strong><br>
A sum of s advances s spaces around a 12-space loop.`
);
}
}
function showTooltip(event, html) {
tooltip.innerHTML = html;
tooltip.style.display = "block";
const padding = 14;
const width = tooltip.offsetWidth;
const height = tooltip.offsetHeight;
let x = event.clientX + padding;
let y = event.clientY + padding;
if (x + width > window.innerWidth - 8) x = event.clientX - width - padding;
if (y + height > window.innerHeight - 8) y = event.clientY - height - padding;
tooltip.style.left = `${Math.max(8, x)}px`;
tooltip.style.top = `${Math.max(8, y)}px`;
}
function hideTooltip() {
tooltip.style.display = "none";
}
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
function animate(now) {
requestAnimationFrame(animate);
if (diceAnimation) {
const progress = THREE.MathUtils.clamp(
(now - diceAnimation.start) / diceAnimation.duration,
0,
1
);
const arc = Math.sin(progress * Math.PI);
dieA.group.position.y = dieA.baseY + arc * 1.8;
dieB.group.position.y = dieB.baseY + arc * 1.8;
dieA.group.rotation.x = progress * Math.PI * 5;
dieA.group.rotation.z = progress * Math.PI * 3;
dieB.group.rotation.x = progress * Math.PI * 4;
dieB.group.rotation.z = -progress * Math.PI * 5;
if (!diceAnimation.pipsSet && progress >= 0.56) {
setDieFace(dieA, diceAnimation.faceA);
setDieFace(dieB, diceAnimation.faceB);
diceAnimation.pipsSet = true;
}
if (progress >= 1) {
setDieFace(dieA, diceAnimation.faceA);
setDieFace(dieB, diceAnimation.faceB);
dieA.group.position.y = dieA.baseY;
dieB.group.position.y = dieB.baseY;
dieA.group.rotation.set(0, 0, 0);
dieB.group.rotation.set(0, 0, 0);
diceAnimation = null;
}
}
if (!tokenTween && tokenQueue.length) {
const nextIndex = tokenQueue.shift();
tokenTween = {
from: token.position.clone(),
to: trackPoints[nextIndex].clone(),
start: now,
duration: 105
};
}
if (tokenTween) {
const progress = THREE.MathUtils.clamp(
(now - tokenTween.start) / tokenTween.duration,
0,
1
);
const eased = progress * progress * (3 - 2 * progress);
token.position.lerpVectors(tokenTween.from, tokenTween.to, eased);
token.position.y += Math.sin(progress * Math.PI) * 0.28;
if (progress >= 1) {
token.position.copy(tokenTween.to);
tokenTween = null;
}
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```