Prompt specification
Build or customize the Three.js 3D scene "Sample-space event explorer" 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: Sample-space event explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sample-space-event-explorer-x1828
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Let users define events by sum, parity, or matching faces; count satisfying outcomes and compute probabilities from the same stated equally likely sample space.
Working Three.js Starter (sample-space-event-explorer-x1828):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Probability Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: #0b1725;
--panel-2: #101f30;
--line: #20364a;
--text: #edf8ff;
--muted: #8ea8bb;
--cyan: #38d9e8;
--pink: #f26caf;
--green: #68e3a6;
--orange: #ffbd66;
--purple: #aa8cff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
#app {
display: grid;
grid-template-columns: 390px minmax(0, 1fr);
height: 100dvh;
}
.sidebar {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 24px 22px 32px;
background:
linear-gradient(180deg, rgba(15, 31, 47, 0.98), rgba(7, 17, 29, 0.99));
border-right: 1px solid var(--line);
box-shadow: 16px 0 50px rgba(0, 0, 0, 0.24);
scrollbar-width: thin;
scrollbar-color: #29445a transparent;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 18px;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(3, 7px);
grid-template-rows: repeat(3, 7px);
gap: 3px;
transform: rotate(-8deg);
}
.brand-mark i {
display: block;
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 12px rgba(56, 217, 232, 0.38);
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(4),
.brand-mark i:nth-child(8) {
background: var(--pink);
box-shadow: 0 0 12px rgba(242, 106, 175, 0.34);
}
.brand-mark i:nth-child(5) {
background: var(--orange);
}
.brand-kicker,
.section-kicker {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 0;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.intro {
margin: 0 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.sample-space {
position: relative;
overflow: hidden;
margin-bottom: 20px;
padding: 15px;
border: 1px solid #285064;
border-radius: 14px;
background:
linear-gradient(135deg, rgba(56, 217, 232, 0.09), transparent 62%),
#0d1c2a;
}
.sample-space::after {
content: "";
position: absolute;
top: -32px;
right: -25px;
width: 90px;
height: 90px;
border: 1px solid rgba(56, 217, 232, 0.2);
transform: rotate(30deg);
}
.sample-space h2 {
margin: 7px 0 8px;
font-size: 14px;
}
.sample-space p {
margin: 0;
color: #afc4d3;
font-size: 12px;
line-height: 1.55;
}
.sample-space code {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 11px;
}
.sample-space .equally {
display: inline-block;
margin-top: 10px;
padding: 5px 8px;
color: #d9faff;
border: 1px solid rgba(56, 217, 232, 0.28);
border-radius: 999px;
background: rgba(56, 217, 232, 0.08);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.panel-section {
margin-top: 20px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
font-size: 14px;
letter-spacing: -0.01em;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
}
.builder {
padding: 14px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(15, 31, 47, 0.72);
}
.field {
margin-bottom: 11px;
}
.field:last-child {
margin-bottom: 0;
}
.field label,
.field-label {
display: block;
margin-bottom: 6px;
color: #9fb6c7;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
input[type="text"],
input[type="number"],
select {
width: 100%;
height: 38px;
padding: 0 10px;
color: var(--text);
border: 1px solid #294157;
border-radius: 9px;
background: #091522;
}
input[type="number"] {
appearance: textfield;
}
input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
appearance: none;
margin: 0;
}
.field-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.hidden {
display: none !important;
}
.primary-button,
.secondary-button,
.ghost-button,
.icon-button {
border: 0;
border-radius: 10px;
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease;
}
.primary-button {
width: 100%;
height: 42px;
color: #03151b;
background: linear-gradient(100deg, var(--cyan), #74e8d5);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.02em;
}
.primary-button:hover {
transform: translateY(-1px);
filter: brightness(1.05);
}
.event-list {
display: grid;
gap: 9px;
}
.event-card {
position: relative;
padding: 12px 42px 12px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0d1a29;
cursor: pointer;
transition:
border-color 140ms ease,
background 140ms ease,
transform 140ms ease;
}
.event-card:hover {
transform: translateX(2px);
border-color: #36556e;
}
.event-card.active {
border-color: var(--cyan);
background:
linear-gradient(100deg, rgba(56, 217, 232, 0.1), transparent),
#0e1d2c;
box-shadow: inset 3px 0 0 var(--cyan);
}
.event-card.combined-mode {
opacity: 0.72;
}
.event-name {
margin-bottom: 4px;
font-size: 12px;
font-weight: 850;
}
.event-rule {
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.event-prob {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 8px;
}
.event-prob strong {
color: var(--cyan);
font-size: 17px;
}
.event-prob span {
color: var(--muted);
font-size: 10px;
}
.icon-button {
position: absolute;
top: 10px;
right: 10px;
width: 27px;
height: 27px;
color: #7890a3;
background: #132335;
font-size: 16px;
line-height: 1;
}
.icon-button:hover {
color: #fff;
background: #79324c;
}
.empty-state {
padding: 18px;
color: var(--muted);
border: 1px dashed #2b4256;
border-radius: 12px;
text-align: center;
font-size: 12px;
}
.combine-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0b1826;
}
.combine-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.combine-row label {
font-size: 12px;
font-weight: 750;
}
.switch {
position: relative;
width: 38px;
height: 22px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch span {
position: absolute;
inset: 0;
border: 1px solid #344b60;
border-radius: 999px;
background: #142437;
cursor: pointer;
}
.switch span::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 14px;
height: 14px;
border-radius: 50%;
background: #7f96a8;
transition: 150ms ease;
}
.switch input:checked + span {
border-color: var(--purple);
background: rgba(170, 140, 255, 0.18);
}
.switch input:checked + span::after {
transform: translateX(16px);
background: var(--purple);
}
.combine-options {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 11px;
}
.combine-options select {
height: 34px;
font-size: 11px;
}
.result-card {
position: relative;
overflow: hidden;
padding: 16px;
border: 1px solid #31566a;
border-radius: 14px;
background:
radial-gradient(circle at 100% 0, rgba(56, 217, 232, 0.13), transparent 42%),
#0d1c2a;
}
.result-title {
margin-bottom: 12px;
color: #b8cedc;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.result-main {
display: flex;
align-items: flex-end;
gap: 9px;
}
.result-main strong {
color: var(--cyan);
font-size: 42px;
line-height: 0.95;
letter-spacing: -0.05em;
}
.result-main span {
margin-bottom: 3px;
color: var(--muted);
font-size: 11px;
}
.result-fraction {
margin-top: 8px;
color: #e6f8ff;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 12px;
}
.result-description {
min-height: 34px;
margin-top: 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.matching-outcomes {
display: flex;
flex-wrap: wrap;
gap: 5px;
max-height: 102px;
overflow-y: auto;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
}
.outcome-chip {
padding: 4px 6px;
color: #a9f7ff;
border: 1px solid rgba(56, 217, 232, 0.2);
border-radius: 6px;
background: rgba(56, 217, 232, 0.07);
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 9px;
}
.matrix-wrap {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 12px;
background: #0a1623;
}
.matrix {
display: grid;
grid-template-columns: 25px repeat(6, minmax(0, 1fr));
gap: 4px;
padding: 9px;
}
.matrix-axis {
display: grid;
place-items: center;
color: #718a9e;
font-size: 9px;
font-weight: 800;
}
.matrix-axis.col {
padding-bottom: 3px;
}
.matrix-axis.row {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
}
.matrix-cell {
position: relative;
min-width: 0;
aspect-ratio: 1;
padding: 0;
color: #6f899c;
border: 1px solid #1e3346;
border-radius: 7px;
background: #0d1b29;
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 10px;
transition: 120ms ease;
}
.matrix-cell:hover {
z-index: 2;
color: white;
border-color: #547188;
transform: scale(1.05);
}
.matrix-cell.satisfies {
color: #071b22;
border-color: var(--cyan);
background: var(--cyan);
box-shadow: 0 0 12px rgba(56, 217, 232, 0.16);
font-weight: 900;
}
.matrix-cell.selected::after {
content: "";
position: absolute;
inset: -3px;
border: 2px solid var(--orange);
border-radius: 9px;
pointer-events: none;
}
.matrix-legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 9px 11px;
color: var(--muted);
border-top: 1px solid var(--line);
font-size: 9px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--cyan);
}
.legend-dot.selected {
background: transparent;
border: 2px solid var(--orange);
}
.sidebar-note {
margin: 17px 0 0;
color: #668094;
font-size: 10px;
line-height: 1.55;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #10263a 0, #07111d 64%);
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-top {
position: absolute;
top: 22px;
left: 22px;
z-index: 3;
display: flex;
align-items: center;
gap: 9px;
pointer-events: none;
}
.scene-chip {
padding: 8px 11px;
color: #bcd2df;
border: 1px solid rgba(81, 118, 142, 0.3);
border-radius: 999px;
background: rgba(8, 20, 32, 0.68);
backdrop-filter: blur(12px);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.scene-chip .live-dot {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px var(--green);
}
.scene-controls {
position: absolute;
top: 18px;
right: 20px;
z-index: 4;
display: flex;
gap: 8px;
}
.roll-button,
.reset-view-button {
height: 40px;
padding: 0 14px;
border-radius: 10px;
cursor: pointer;
backdrop-filter: blur(12px);
font-size: 11px;
font-weight: 850;
}
.roll-button {
color: #06181e;
border: 0;
background: linear-gradient(100deg, var(--cyan), #77e7d5);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
}
.roll-button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
.reset-view-button {
color: #bfd3df;
border: 1px solid rgba(93, 127, 149, 0.34);
background: rgba(8, 20, 32, 0.68);
}
.reset-view-button:hover {
color: white;
border-color: #6d8ba0;
}
.outcome-hud {
position: absolute;
bottom: 22px;
left: 50%;
z-index: 3;
min-width: 300px;
padding: 12px 16px;
border: 1px solid rgba(93, 127, 149, 0.28);
border-radius: 14px;
background: rgba(7, 17, 29, 0.76);
backdrop-filter: blur(15px);
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.28);
transform: translateX(-50%);
pointer-events: none;
}
.hud-label {
margin-bottom: 6px;
color: #7893a7;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.hud-outcome {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.die-value {
display: grid;
place-items: center;
width: 33px;
height: 33px;
border-radius: 8px;
font-size: 18px;
font-weight: 900;
}
.die-value.a {
color: #bffaff;
border: 1px solid rgba(56, 217, 232, 0.42);
background: rgba(56, 217, 232, 0.13);
}
.die-value.b {
color: #ffd3eb;
border: 1px solid rgba(242, 106, 175, 0.42);
background: rgba(242, 106, 175, 0.13);
}
.hud-times {
color: #678296;
font-size: 13px;
}
.hud-status {
margin-top: 7px;
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.06em;
text-align: center;
text-transform: uppercase;
}
.hud-status.no {
color: #ff8c9f;
}
.camera-hint {
position: absolute;
right: 20px;
bottom: 21px;
z-index: 3;
color: rgba(170, 196, 212, 0.65);
font-size: 9px;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 850px) {
body {
overflow: auto;
}
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100dvh;
}
.stage {
order: -1;
height: 52vh;
min-height: 390px;
}
.sidebar {
overflow: visible;
padding: 22px 18px 35px;
border-top: 1px solid var(--line);
border-right: 0;
}
.scene-top {
top: 14px;
left: 14px;
}
.scene-controls {
top: 12px;
right: 12px;
}
.roll-button,
.reset-view-button {
height: 36px;
padding: 0 10px;
font-size: 10px;
}
.outcome-hud {
bottom: 12px;
min-width: 250px;
padding: 9px 12px;
}
.camera-hint {
display: none;
}
}
@media (max-width: 480px) {
.stage {
height: 45vh;
min-height: 330px;
}
.scene-chip {
display: none;
}
.scene-controls {
left: 12px;
right: auto;
}
.outcome-hud {
min-width: 225px;
}
.brand h1 {
font-size: 22px;
}
}
</style>
</head>
<body>
<div id="app">
<aside class="sidebar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<div class="brand-kicker">Interactive probability lab</div>
<h1>Voxel Outcomes</h1>
</div>
</div>
<p class="intro">
Define events, enumerate every outcome in the same sample space,
and see both the satisfying count and its probability.
</p>
<section class="sample-space" aria-labelledby="sampleTitle">
<div class="section-kicker">Stated sample space</div>
<h2 id="sampleTitle">Two distinguishable voxel dice</h2>
<p>
<code>Ω = {(a, b) | a, b ∈ {1, 2, 3, 4, 5, 6}}</code><br />
There are <strong>36 ordered outcomes</strong>. Dice A and B are
labeled, so (2, 5) and (5, 2) are different outcomes.
</p>
<span class="equally">Each outcome has probability 1 / 36</span>
</section>
<section class="panel-section" aria-labelledby="builderTitle">
<div class="section-heading">
<h2 id="builderTitle">Define an event</h2>
<span>Add one or more rules</span>
</div>
<form id="eventForm" class="builder">
<div class="field">
<label for="eventName">Event name</label>
<input
id="eventName"
type="text"
maxlength="32"
placeholder="Optional: e.g. Lucky total"
autocomplete="off"
/>
</div>
<div class="field">
<label for="eventType">Rule type</label>
<select id="eventType">
<option value="sum">Sum of the two dice</option>
<option value="parity">Parity of the sum</option>
<option value="match">Matching faces</option>
</select>
</div>
<div id="sumFields" class="field">
<div class="field-row">
<div>
<label for="sumComparison">Comparison</label>
<select id="sumComparison">
<option value="eq">Equals</option>
<option value="gte">At least</option>
<option value="lte">At most</option>
</select>
</div>
<div>
<label for="sumTarget">Target sum</label>
<input id="sumTarget" type="number" min="2" max="12" value="7" />
</div>
</div>
</div>
<div id="parityFields" class="field hidden">
<label for="parityValue">Sum parity</label>
<select id="parityValue">
<option value="even">Even</option>
<option value="odd">Odd</option>
</select>
</div>
<div id="matchFields" class="field hidden">
<div class="field-row">
<div>
<label for="matchMode">Match condition</label>
<select id="matchMode">
<option value="any">Any matching face</option>
<option value="exact">Specific matching face</option>
</select>
</div>
<div id="matchTargetField">
<label for="matchTarget">Face</label>
<input id="matchTarget" type="number" min="1" max="6" value="1" />
</div>
</div>
</div>
<button class="primary-button" type="submit">+ Add event rule</button>
</form>
</section>
<section class="panel-section" aria-labelledby="eventsTitle">
<div class="section-heading">
<h2 id="eventsTitle">Your events</h2>
<span id="eventCount">1 rule</span>
</div>
<div id="eventList" class="event-list"></div>
</section>
<section class="panel-section">
<div class="combine-card">
<div class="combine-row">
<label for="combineEnabled">Combine all event rules</label>
<label class="switch">
<input id="combineEnabled" type="checkbox" />
<span aria-hidden="true"></span>
</label>
</div>
<div id="combineOptions" class="combine-options hidden">
<div>
<label class="field-label" for="combineMode">Combination</label>
<select id="combineMode">
<option value="all">All rules · intersection</option>
<option value="any">Any rule · union</option>
</select>
</div>
<div>
<span class="field-label">Denominator</span>
<div style="height:34px;line-height:34px;color:#c9dce7;font-size:12px">
Always 36
</div>
</div>
</div>
</div>
</section>
<section class="panel-section" aria-labelledby="resultTitle">
<div class="result-card">
<div id="resultTitle" class="result-title">Selected event</div>
<div class="result-main">
<strong id="resultCount">0</strong>
<span>of 36 outcomes</span>
</div>
<div id="resultFraction" class="result-fraction">P(E) = 0/36</div>
<div id="resultPercent" class="result-fraction">0.00%</div>
<div id="resultDescription" class="result-description"></div>
<div id="matchingOutcomes" class="matching-outcomes"></div>
</div>
</section>
<section class="panel-section" aria-labelledby="matrixTitle">
<div class="section-heading">
<h2 id="matrixTitle">Ordered outcome matrix</h2>
<span>Click a cell to display it</span>
</div>
<div class="matrix-wrap">
<div id="matrix" class="matrix"></div>
<div class="matrix-legend">
<span class="legend-item">
<i class="legend-dot"></i>
Satisfies selected event
</span>
<span class="legend-item">
<i class="legend-dot selected"></i>
Current dice
</span>
</div>
</div>
</section>
<p class="sidebar-note">
No conditional or reduced sample space is used. Every displayed
probability is the number of satisfying ordered pairs divided by all
36 equally likely ordered pairs.
</p>
</aside>
<main class="stage" id="stage">
<div id="scene"></div>
<div class="scene-top">
<div class="scene-chip">
<span class="live-dot"></span>
Fair model · 36 ordered outcomes
</div>
</div>
<div class="scene-controls">
<button id="rollButton" class="roll-button" type="button">
Roll a fair pair
</button>
<button id="resetViewButton" class="reset-view-button" type="button">
Reset view
</button>
</div>
<div class="outcome-hud">
<div class="hud-label">Current ordered outcome</div>
<div class="hud-outcome">
<div class="die-value a" id="hudA">3</div>
<div class="hud-times">×</div>
<div class="die-value b" id="hudB">4</div>
</div>
<div id="hudStatus" class="hud-status">Satisfies selected event</div>
</div>
<div class="camera-hint">
Drag to orbit · Scroll to zoom · Double-click to reset
</div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Event model and probability calculations
// ------------------------------------------------------------
const SAMPLE_SPACE_SIZE = 36;
const $ = (id) => document.getElementById(id);
const escapeHTML = (value) =>
String(value).replace(
/[&<>'"]/g,
(character) =>
({
"&": "&",
"<": "<",
">": ">",
"'": "'",
'"': """
})[character]
);
let nextEventId = 2;
let activeEventId = 1;
let combineEnabled = false;
let combineMode = "all";
let events = [
{
id: 1,
name: "Seven total",
rule: { type: "sum", comparison: "eq", target: 7 }
}
];
let currentOutcome = { a: 3, b: 4 };
function evaluateRule(rule, a, b) {
const sum = a + b;
if (rule.type === "sum") {
if (rule.comparison === "eq") return sum === rule.target;
if (rule.comparison === "gte") return sum >= rule.target;
if (rule.comparison === "lte") return sum <= rule.target;
}
if (rule.type === "parity") {
return rule.parity === "even" ? sum % 2 === 0 : sum % 2 === 1;
}
if (rule.type === "match") {
if (rule.mode === "exact") {
return a === b && a === rule.target;
}
return a === b;
}
return false;
}
function describeRule(rule) {
if (rule.type === "sum") {
const symbol =
rule.comparison === "eq"
? "="
: rule.comparison === "gte"
? "≥"
: "≤";
return `The sum is ${symbol} ${rule.target}.`;
}
if (rule.type === "parity") {
return `The sum is ${rule.parity}.`;
}
if (rule.mode === "exact") {
return `Both dice show face ${rule.target}.`;
}
return "Both dice show the same face (A = B).";
}
function defaultName(rule) {
if (rule.type === "sum") {
const prefix =
rule.comparison === "eq"
? "Sum"
: rule.comparison === "gte"
? "Sum at least"
: "Sum at most";
return `${prefix} ${rule.target}`;
}
if (rule.type === "parity") return `${rule.parity} sum`;
return rule.mode === "exact"
? `Both show ${rule.target}`
: "Matching faces";
}
function getSelectedEvents() {
if (combineEnabled) return events;
const active = events.find((event) => event.id === activeEventId);
return active ? [active] : [];
}
function getPredicate() {
const selected = getSelectedEvents();
if (!selected.length) return () => false;
if (!combineEnabled) {
return (a, b) => evaluateRule(selected[0].rule, a, b);
}
if (combineMode === "any") {
return (a, b) =>
selected.some((event) => evaluateRule(event.rule, a, b));
}
return (a, b) =>
selected.every((event) => evaluateRule(event.rule, a, b));
}
function gcd(a, b) {
while (b) {
const remainder = a % b;
a = b;
b = remainder;
}
return a;
}
function reducedFraction(numerator, denominator) {
const divisor = gcd(numerator, denominator);
return `${numerator / divisor}/${denominator / divisor}`;
}
function renderEvents() {
const list = $("eventList");
$("eventCount").textContent =
`${events.length} ${events.length === 1 ? "rule" : "rules"}`;
if (!events.length) {
list.innerHTML =
'<div class="empty-state">No event rules yet. Add one above to begin counting.</div>';
return;
}
list.innerHTML = events
.map((event) => {
const count = Array.from({ length: 6 }, (_, i) => i + 1).reduce(
(total, a) =>
total +
Array.from({ length: 6 }, (_, j) => j + 1).filter((b) =>
evaluateRule(event.rule, a, b)
).length,
0
);
const percent = (count / SAMPLE_SPACE_SIZE) * 100;
const active = !combineEnabled && event.id === activeEventId;
return `
<article
class="event-card ${active ? "active" : ""} ${combineEnabled ? "combined-mode" : ""}"
data-event-id="${event.id}"
tabindex="0"
aria-pressed="${active}"
>
<div class="event-name">${escapeHTML(event.name)}</div>
<div class="event-rule">${escapeHTML(describeRule(event.rule))}</div>
<div class="event-prob">
<strong>${percent.toFixed(2)}%</strong>
<span>${count} of 36 outcomes</span>
</div>
<button
class="icon-button"
type="button"
data-remove-id="${event.id}"
aria-label="Remove ${escapeHTML(event.name)}"
>×</button>
</article>
`;
})
.join("");
}
function updateResults() {
const predicate = getPredicate();
const matching = [];
for (let a = 1; a <= 6; a++) {
for (let b = 1; b <= 6; b++) {
if (predicate(a, b)) matching.push({ a, b });
}
}
const count = matching.length;
const percent = (count / SAMPLE_SPACE_SIZE) * 100;
let title = "Selected event";
let description = "Add or select an event rule.";
if (combineEnabled) {
title =
combineMode === "all"
? "Combined event · all rules"
: "Combined event · any rule";
description =
combineMode === "all"
? "An outcome satisfies this event only when it satisfies every rule."
: "An outcome satisfies this event when it satisfies at least one rule.";
} else {
const active = events.find((event) => event.id === activeEventId);
if (active) {
title = active.name;
description = describeRule(active.rule);
}
}
$("resultTitle").textContent = title;
$("resultCount").textContent = count;
$("resultFraction").textContent =
`P(E) = ${count}/36 = ${reducedFraction(count, SAMPLE_SPACE_SIZE)}`;
$("resultPercent").textContent = `${percent.toFixed(2)}%`;
$("resultDescription").textContent = description;
$("matchingOutcomes").innerHTML = matching.length
? matching
.map(
({ a, b }) =>
`<span class="outcome-chip">(${a}, ${b})</span>`
)
.join("")
: '<span class="result-description">No outcomes satisfy this event.</span>';
}
function updateMatrix() {
const predicate = getPredicate();
document.querySelectorAll(".matrix-cell").forEach((cell) => {
const a = Number(cell.dataset.a);
const b = Number(cell.dataset.b);
const satisfies = predicate(a, b);
cell.classList.toggle("satisfies", satisfies);
cell.classList.toggle(
"selected",
a === currentOutcome.a && b === currentOutcome.b
);
cell.title =
`Outcome (${a}, ${b}): ` +
`${satisfies ? "satisfies" : "does not satisfy"} the selected event. ` +
`Each ordered pair has probability 1/36.`;
});
}
function updateHUD() {
$("hudA").textContent = currentOutcome.a;
$("hudB").textContent = currentOutcome.b;
const satisfies = getPredicate()(currentOutcome.a, currentOutcome.b);
const status = $("hudStatus");
status.classList.toggle("no", !satisfies);
status.textContent = satisfies
? "Satisfies selected event"
: "Does not satisfy selected event";
}
function updateAll() {
updateResults();
updateMatrix();
updateHUD();
}
function updateConditionalFields() {
const type = $("eventType").value;
$("sumFields").classList.toggle("hidden", type !== "sum");
$("parityFields").classList.toggle("hidden", type !== "parity");
$("matchFields").classList.toggle("hidden", type !== "match");
$("matchTargetField").classList.toggle(
"hidden",
type !== "match" || $("matchMode").value !== "exact"
);
}
$("eventType").addEventListener("change", updateConditionalFields);
$("matchMode").addEventListener("change", updateConditionalFields);
$("eventForm").querySelector('button[type="submit"]').addEventListener("click", (event) => {
event.preventDefault();
$("eventForm").dispatchEvent(new Event("submit", { cancelable: true }));
});
$("eventForm").addEventListener("submit", (event) => {
event.preventDefault();
const type = $("eventType").value;
let rule;
if (type === "sum") {
const target = Number($("sumTarget").value);
if (!Number.isInteger(target) || target < 2 || target > 12) {
$("sumTarget").focus();
return;
}
rule = {
type,
comparison: $("sumComparison").value,
target
};
} else if (type === "parity") {
rule = { type, parity: $("parityValue").value };
} else {
const mode = $("matchMode").value;
const target = Number($("matchTarget").value);
if (mode === "exact" && (!Number.isInteger(target) || target < 1 || target > 6)) {
$("matchTarget").focus();
return;
}
rule = { type, mode, target };
}
const enteredName = $("eventName").value.trim();
const newEvent = {
id: nextEventId++,
name: enteredName || defaultName(rule),
rule
};
events.push(newEvent);
activeEventId = newEvent.id;
$("eventName").value = "";
renderEvents();
updateAll();
});
$("eventList").addEventListener("click", (event) => {
const removeButton = event.target.closest("[data-remove-id]");
if (removeButton) {
event.stopPropagation();
const id = Number(removeButton.dataset.removeId);
events = events.filter((item) => item.id !== id);
if (activeEventId === id) {
activeEventId = events[0]?.id ?? null;
}
renderEvents();
updateAll();
return;
}
const card = event.target.closest("[data-event-id]");
if (card) {
activeEventId = Number(card.dataset.eventId);
renderEvents();
updateAll();
}
});
$("eventList").addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
event.target.click();
}
});
$("combineEnabled").addEventListener("change", () => {
combineEnabled = $("combineEnabled").checked;
$("combineOptions").classList.toggle("hidden", !combineEnabled);
renderEvents();
updateAll();
});
$("combineMode").addEventListener("change", () => {
combineMode = $("combineMode").value;
updateAll();
});
// ------------------------------------------------------------
// Three.js scene
// ------------------------------------------------------------
const sceneHost = $("scene");
const stage = $("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(sceneHost.clientWidth, sceneHost.clientHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive scene showing two voxel dice"
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 9, 23);
const camera = new THREE.PerspectiveCamera(
38,
sceneHost.clientWidth / sceneHost.clientHeight,
0.1,
60
);
// Custom camera controls implemented here; no addon modules are used.
const cameraState = {
radius: 7.2,
theta: 0.48,
phi: 1.03,
targetRadius: 7.2,
targetTheta: 0.48,
targetPhi: 1.03,
target: new THREE.Vector3(0, 1.15, 0)
};
function resetCamera() {
cameraState.targetRadius = 7.2;
cameraState.targetTheta = 0.48;
cameraState.targetPhi = 1.03;
}
const pointers = new Map();
let lastPinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
lastPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const deltaX = event.clientX - previous.x;
const deltaY = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
cameraState.targetTheta -= deltaX * 0.006;
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi - deltaY * 0.005,
0.48,
1.43
);
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (lastPinchDistance > 0 && distance > 0) {
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius * (lastPinchDistance / distance),
4.6,
12
);
}
lastPinchDistance = distance;
}
});
function removePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) lastPinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius + event.deltaY * 0.005,
4.6,
12
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
$("resetViewButton").addEventListener("click", resetCamera);
// Lighting.
scene.add(new THREE.HemisphereLight(0xbceeff, 0x08111c, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4.5, 8, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x35ddec, 24, 8, 2);
cyanLight.position.set(-3.2, 2.6, 2.4);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xf05ca8, 22, 8, 2);
pinkLight.position.set(3.2, 2.4, -0.8);
scene.add(pinkLight);
// Ground and grid.
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x07131f,
roughness: 0.92,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x1b5265, 0x102b3c);
grid.position.y = 0.008;
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
// Main voxel platform.
const platformBase = new THREE.Mesh(
new THREE.BoxGeometry(6.15, 0.24, 4.75),
new THREE.MeshStandardMaterial({
color: 0x0b1b28,
roughness: 0.72,
metalness: 0.25
})
);
platformBase.position.y = 0.12;
platformBase.receiveShadow = true;
platformBase.castShadow = true;
scene.add(platformBase);
const tileGeometry = new THREE.BoxGeometry(0.58, 0.12, 0.58);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.62,
metalness: 0.2
});
const tileColumns = 9;
const tileRows = 7;
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileColumns * tileRows
);
const tileDummy = new THREE.Object3D();
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let column = 0; column < tileColumns; column++) {
tileDummy.position.set(
(column - (tileColumns - 1) / 2) * 0.64,
0.3,
(row - (tileRows - 1) / 2) * 0.64
);
tileDummy.updateMatrix();
tiles.setMatrixAt(tileIndex, tileDummy.matrix);
const tileColor = new THREE.Color(0x0d2835);
tileColor.offsetHSL(0, 0, ((row + column) % 3) * 0.012);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
tiles.castShadow = true;
tiles.receiveShadow = true;
scene.add(tiles);
function makePedestal(x, color) {
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(1.48, 0.62, 1.48),
new THREE.MeshStandardMaterial({
color: 0x101d2a,
roughness: 0.46,
metalness: 0.42
})
);
pedestal.position.set(x, 0.63, 0);
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
const top = new THREE.Mesh(
new THREE.BoxGeometry(1.62, 0.08, 1.62),
new THREE.MeshStandardMaterial({
color: 0x172c39,
roughness: 0.36,
metalness: 0.5
})
);
top.position.set(x, 0.98, 0);
top.castShadow = true;
scene.add(top);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.94, 0.025, 8, 72),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.78
})
);
ring.position.set(x, 1.035, 0);
ring.rotation.x = Math.PI / 2;
scene.add(ring);
}
makePedestal(-1.2, 0x38d9e8);
makePedestal(1.2, 0xf26caf);
// Deterministic decorative voxel blocks in the background.
let randomSeed = 9173;
function seededRandom() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
const blockCount = 30;
const backgroundBlocks = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.74,
metalness: 0.18
}),
blockCount
);
const blockDummy = new THREE.Object3D();
for (let i = 0; i < blockCount; i++) {
const side = i % 2 === 0 ? -1 : 1;
const x = side * (3.5 + seededRandom() * 4.2);
const z = -3.4 + seededRandom() * 8.5;
const height = 0.25 + seededRandom() * 1.55;
blockDummy.position.set(x, height / 2, z);
blockDummy.scale.set(
0.42 + seededRandom() * 0.68,
height,
0.42 + seededRandom() * 0.68
);
blockDummy.rotation.y = seededRandom() * Math.PI;
blockDummy.updateMatrix();
backgroundBlocks.setMatrixAt(i, blockDummy.matrix);
const color = new THREE.Color(
seededRandom() > 0.78 ? 0x4b2d48 : 0x102b38
);
color.offsetHSL(0, 0, (seededRandom() - 0.5) * 0.08);
backgroundBlocks.setColorAt(i, color);
}
backgroundBlocks.instanceMatrix.needsUpdate = true;
if (backgroundBlocks.instanceColor) {
backgroundBlocks.instanceColor.needsUpdate = true;
}
backgroundBlocks.castShadow = true;
backgroundBlocks.receiveShadow = true;
scene.add(backgroundBlocks);
// Fine background particles.
const particlePositions = new Float32Array(180 * 3);
for (let i = 0; i < 180; i++) {
particlePositions[i * 3] = (seededRandom() - 0.5) * 18;
particlePositions[i * 3 + 1] = 0.5 + seededRandom() * 8;
particlePositions[i * 3 + 2] = (seededRandom() - 0.5) * 14;
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x5aa9c1,
size: 0.025,
transparent: true,
opacity: 0.55,
depthWrite: false
})
);
scene.add(particles);
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 makeTextSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 16, 27, 0.86)";
context.strokeStyle = color;
context.lineWidth = 3;
context.beginPath();
context.roundRect(4, 4, 248, 88, 18);
context.fill();
context.stroke();
context.fillStyle = color;
context.font = "800 38px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 49);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.22, 0.46, 1);
return sprite;
}
function makeDie(baseColor, pipColor, x) {
const group = new THREE.Group();
group.position.set(x, 1.6, 0);
const bodyGeometry = new THREE.BoxGeometry(0.35, 0.35, 0.35);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.28,
metalness: 0.28,
emissive: baseColor,
emissiveIntensity: 0.11
});
const body = new THREE.InstancedMesh(bodyGeometry, bodyMaterial, 27);
const bodyDummy = new THREE.Object3D();
let bodyIndex = 0;
for (let ix = -1; ix <= 1; ix++) {
for (let iy = -1; iy <= 1; iy++) {
for (let iz = -1; iz <= 1; iz++) {
bodyDummy.position.set(ix * 0.38, iy * 0.38, iz * 0.38);
bodyDummy.updateMatrix();
body.setMatrixAt(bodyIndex, bodyDummy.matrix);
const color = new THREE.Color(baseColor);
color.offsetHSL(
0,
0,
-0.08 + ((ix + iy + iz + 3) % 3) * 0.035
);
body.setColorAt(bodyIndex, color);
bodyIndex++;
}
}
}
body.instanceMatrix.needsUpdate = true;
if (body.instanceColor) body.instanceColor.needsUpdate = true;
body.castShadow = true;
body.receiveShadow = true;
body.computeBoundingSphere();
group.add(body);
// Canonical die faces:
// front 1, right 2, back 6, left 5, top 3, bottom 4.
const faceDefinitions = [
{
value: 1,
offset: [0, 0, 0.575],
rotation: [0, 0, 0]
},
{
value: 2,
offset: [0.575, 0, 0],
rotation: [0, Math.PI / 2, 0]
},
{
value: 6,
offset: [0, 0, -0.575],
rotation: [0, Math.PI, 0]
},
{
value: 5,
offset: [-0.575, 0, 0],
rotation: [0, -Math.PI / 2, 0]
},
{
value: 3,
offset: [0, 0.575, 0],
rotation: [-Math.PI / 2, 0, 0]
},
{
value: 4,
offset: [0, -0.575, 0],
rotation: [Math.PI / 2, 0, 0]
}
];
const totalPips = faceDefinitions.reduce(
(sum, face) => sum + pipCoordinates[face.value].length,
0
);
const pipGeometry = new THREE.BoxGeometry(0.105, 0.105, 0.045);
const pipMaterial = new THREE.MeshStandardMaterial({
color: pipColor,
roughness: 0.3,
metalness: 0.05,
emissive: pipColor,
emissiveIntensity: 0.65
});
const pips = new THREE.InstancedMesh(
pipGeometry,
pipMaterial,
totalPips
);
const pipDummy = new THREE.Object3D();
const offsetMatrix = new THREE.Matrix4();
let pipIndex = 0;
for (const face of faceDefinitions) {
for (const [px, py] of pipCoordinates[face.value]) {
pipDummy.position.set(px * 0.19, py * 0.19, 0);
pipDummy.rotation.set(...face.rotation);
pipDummy.updateMatrix();
offsetMatrix.makeTranslation(...face.offset);
const matrix = offsetMatrix.clone().multiply(pipDummy.matrix);
pips.setMatrixAt(pipIndex, matrix);
pipIndex++;
}
}
pips.instanceMatrix.needsUpdate = true;
pips.castShadow = true;
pips.computeBoundingSphere();
group.add(pips);
group.userData.targetQuaternion = new THREE.Quaternion();
group.userData.bounce = 0;
scene.add(group);
return group;
}
const dice = [
makeDie(0x22b9cc, 0xd8fbff, -1.2),
makeDie(0xe65b9e, 0xffd8ee, 1.2)
];
const labelA = makeTextSprite("DIE A", "#54ddea");
labelA.position.set(-1.2, 2.48, 0);
scene.add(labelA);
const labelB = makeTextSprite("DIE B", "#f17ab4");
labelB.position.set(1.2, 2.48, 0);
scene.add(labelB);
const targetFaceQuaternions = {
1: new THREE.Quaternion(),
2: new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, -Math.PI / 2, 0)
),
6: new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, Math.PI, 0)
),
5: new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, Math.PI / 2, 0)
),
3: new THREE.Quaternion().setFromEuler(
new THREE.Euler(Math.PI / 2, 0, 0)
),
4: new THREE.Quaternion().setFromEuler(
new THREE.Euler(-Math.PI / 2, 0, 0)
)
};
function setDieValue(index, value, spinning = false) {
const die = dice[index];
const target = die.userData.targetQuaternion;
target.copy(targetFaceQuaternions[value]);
if (spinning) {
const turns = Math.floor(Math.random() * 4);
const spin = new THREE.Quaternion().setFromAxisAngle(
new THREE.Vector3(0, 1, 0),
turns * Math.PI / 2
);
target.premultiply(spin);
}
die.userData.bounce = 1;
}
function setOutcome(a, b, spinning = false) {
currentOutcome = { a, b };
setDieValue(0, a, spinning);
setDieValue(1, b, spinning);
updateMatrix();
updateHUD();
}
function rollPair() {
// Uniform over the 36 ordered outcomes in the stated sample space.
const a = Math.floor(Math.random() * 6) + 1;
const b = Math.floor(Math.random() * 6) + 1;
setOutcome(a, b, true);
}
$("rollButton").addEventListener("click", rollPair);
document.addEventListener("keydown", (event) => {
const target = event.target;
const isTyping =
target instanceof HTMLInputElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLTextAreaElement;
if (event.code === "Space" && !isTyping) {
event.preventDefault();
rollPair();
}
});
// Build the 6 x 6 ordered outcome matrix.
const matrix = $("matrix");
const corner = document.createElement("div");
corner.className = "matrix-axis";
corner.textContent = "B →";
matrix.appendChild(corner);
for (let b = 1; b <= 6; b++) {
const axis = document.createElement("div");
axis.className = "matrix-axis col";
axis.textContent = b;
matrix.appendChild(axis);
}
for (let a = 1; a <= 6; a++) {
const rowAxis = document.createElement("div");
rowAxis.className = "matrix-axis row";
rowAxis.textContent = `A${a}`;
matrix.appendChild(rowAxis);
for (let b = 1; b <= 6; b++) {
const cell = document.createElement("button");
cell.type = "button";
cell.className = "matrix-cell";
cell.dataset.a = a;
cell.dataset.b = b;
cell.textContent = b;
cell.setAttribute(
"aria-label",
`Display ordered outcome die A ${a}, die B ${b}`
);
cell.addEventListener("click", () => {
setOutcome(a, b);
});
matrix.appendChild(cell);
}
}
// Resize handling.
function resizeRenderer() {
const width = sceneHost.clientWidth;
const height = sceneHost.clientHeight;
renderer.setSize(width, height);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resizeRenderer).observe(sceneHost);
} else {
window.addEventListener("resize", resizeRenderer);
}
// Initial UI and scene state.
updateConditionalFields();
renderEvents();
updateAll();
setOutcome(currentOutcome.a, currentOutcome.b);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
// Smooth custom orbit camera.
const cameraAlpha = 1 - Math.exp(-delta * 9);
cameraState.theta +=
(cameraState.targetTheta - cameraState.theta) * cameraAlpha;
cameraState.phi +=
(cameraState.targetPhi - cameraState.phi) * cameraAlpha;
cameraState.radius +=
(cameraState.targetRadius - cameraState.radius) * cameraAlpha;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
// Smooth dice rotations and bounce.
dice.forEach((die, index) => {
const rotationAlpha = 1 - Math.exp(-delta * 8.5);
die.quaternion.slerp(die.userData.targetQuaternion, rotationAlpha);
const bounce = die.userData.bounce;
die.position.y =
1.6 + Math.sin(elapsed * 14 + index * 1.8) * 0.095 * bounce;
die.userData.bounce *= Math.exp(-delta * 3.1);
});
particles.rotation.y = elapsed * 0.008;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```