Prompt specification
Build or customize the Three.js 3D scene "Miniature Court With Transparent Scoring" 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: Miniature Court With Transparent Scoring
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/miniature-court-with-transparent-scoring-x3651
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Build an original court scene with scripted rallies and a stepwise score controller. Keep the visual rally outcome synchronized with the selected scoring-state transition.
Working Three.js Starter (miniature-court-with-transparent-scoring-x3651):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cube Rally — Voxel Court Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #09111f;
--panel: rgba(12, 22, 39, 0.9);
--line: rgba(167, 201, 255, 0.16);
--text: #edf6ff;
--muted: #90a5bf;
--a: #ff6f61;
--b: #40d9e8;
--accent: #f7e36c;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.brand {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.45);
}
.brand-row {
display: flex;
align-items: center;
gap: 10px;
}
.brand-mark {
width: 18px;
height: 18px;
background: var(--accent);
box-shadow:
6px 0 0 rgba(247, 227, 108, 0.45),
0 6px 0 rgba(247, 227, 108, 0.32),
6px 6px 0 rgba(247, 227, 108, 0.2);
transform: rotate(8deg);
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: 0.22em;
font-weight: 850;
}
.brand p {
margin: 7px 0 0 29px;
color: #a9bbd0;
font-size: 10px;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.hud-score {
position: fixed;
z-index: 5;
top: 22px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: stretch;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(8, 17, 31, 0.8);
box-shadow: 0 14px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px);
pointer-events: none;
}
.hud-team {
min-width: 104px;
padding: 12px 18px;
text-align: center;
}
.hud-team.a {
color: var(--a);
}
.hud-team.b {
color: var(--b);
}
.hud-team span {
display: block;
font-size: 9px;
letter-spacing: 0.2em;
opacity: 0.72;
}
.hud-team strong {
display: block;
margin-top: 2px;
font-size: 30px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.hud-middle {
min-width: 76px;
display: grid;
place-items: center;
padding: 8px 12px;
border-left: 1px solid var(--line);
border-right: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
letter-spacing: 0.15em;
text-align: center;
}
.hud-middle b {
display: block;
margin-bottom: 5px;
color: var(--text);
font-size: 15px;
}
.controller {
position: fixed;
z-index: 10;
top: 22px;
right: 22px;
width: min(348px, calc(100vw - 32px));
max-height: calc(100vh - 44px);
overflow: auto;
padding: 19px;
border: 1px solid var(--line);
border-radius: 20px;
background:
linear-gradient(145deg, rgba(26, 43, 69, 0.34), transparent 45%),
var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.4);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
}
.eyebrow {
margin: 0 0 5px;
color: var(--accent);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.controller h2 {
margin: 0;
font-size: 23px;
letter-spacing: -0.03em;
}
.controller-intro {
margin: 8px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.live-card {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 12px;
padding: 13px;
margin-bottom: 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.035);
}
.live-player {
min-width: 0;
}
.live-player.right {
text-align: right;
}
.live-player small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.16em;
}
.live-player strong {
display: block;
margin-top: 2px;
font-size: 31px;
font-variant-numeric: tabular-nums;
}
.live-player.a strong {
color: var(--a);
}
.live-player.b strong {
color: var(--b);
}
.live-divider {
text-align: center;
color: #647b98;
font-size: 10px;
line-height: 1.6;
}
.live-divider b {
display: block;
color: var(--accent);
font-size: 11px;
}
.section-label {
display: flex;
justify-content: space-between;
align-items: center;
margin: 15px 0 8px;
color: #b7c7da;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.section-label span {
color: #617895;
font-weight: 600;
letter-spacing: 0.08em;
}
.transition-list {
display: grid;
gap: 7px;
}
.transition {
width: 100%;
display: grid;
grid-template-columns: 8px 1fr auto;
gap: 10px;
align-items: center;
padding: 10px 11px;
border: 1px solid transparent;
border-radius: 11px;
color: var(--text);
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
text-align: left;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
.transition:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.07);
transform: translateX(-2px);
}
.transition.selected {
border-color: rgba(247, 227, 108, 0.48);
background: rgba(247, 227, 108, 0.085);
}
.transition:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.transition-dot {
width: 7px;
height: 7px;
border-radius: 2px;
background: #667b96;
}
.transition[data-id="POINT_A"] .transition-dot {
background: var(--a);
}
.transition[data-id="POINT_B"] .transition-dot {
background: var(--b);
}
.transition[data-id="FAULT_A"] .transition-dot {
background: #ff9e64;
}
.transition[data-id="FAULT_B"] .transition-dot {
background: #8e9cff;
}
.transition[data-id="LET"] .transition-dot {
background: var(--accent);
}
.transition b {
display: block;
font-size: 11px;
letter-spacing: 0.04em;
}
.transition small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.transition .arrow {
color: #647b98;
font-size: 15px;
}
.selection-summary {
min-height: 42px;
margin: 11px 0 13px;
padding: 9px 11px;
border-left: 2px solid var(--accent);
border-radius: 0 8px 8px 0;
color: #c8d6e7;
background: rgba(247, 227, 108, 0.055);
font-size: 10px;
line-height: 1.5;
}
.selection-summary b {
color: var(--accent);
}
.primary {
width: 100%;
padding: 12px 15px;
border: 0;
border-radius: 11px;
color: #182033;
background: var(--accent);
box-shadow: 0 8px 24px rgba(247, 227, 108, 0.16);
font-size: 11px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
cursor: pointer;
transition:
filter 150ms ease,
transform 150ms ease;
}
.primary:hover:not(:disabled) {
filter: brightness(1.08);
transform: translateY(-1px);
}
.primary:disabled {
opacity: 0.45;
cursor: not-allowed;
box-shadow: none;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 8px;
}
.secondary {
padding: 9px;
border: 1px solid var(--line);
border-radius: 9px;
color: #c0d0e2;
background: rgba(255, 255, 255, 0.035);
font-size: 10px;
cursor: pointer;
}
.secondary:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.075);
}
.secondary:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.status-row {
display: flex;
justify-content: space-between;
gap: 8px;
margin: 16px 0 8px;
color: var(--muted);
font-size: 9px;
}
.status-row b {
color: var(--accent);
letter-spacing: 0.08em;
}
.beat-track {
display: flex;
gap: 5px;
height: 5px;
}
.beat {
flex: 1;
border-radius: 4px;
background: rgba(255, 255, 255, 0.08);
transition: background 120ms ease;
}
.beat.active {
background: var(--accent);
box-shadow: 0 0 12px rgba(247, 227, 108, 0.4);
}
.log {
display: grid;
gap: 6px;
max-height: 118px;
overflow: auto;
scrollbar-width: thin;
}
.log-entry {
display: grid;
grid-template-columns: 43px 1fr;
gap: 8px;
padding: 8px 9px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
color: #afc0d5;
font-size: 9px;
line-height: 1.4;
}
.log-entry time {
color: #617895;
font-variant-numeric: tabular-nums;
}
.log-entry b {
display: block;
color: #e5effa;
font-size: 10px;
}
.outcome {
position: fixed;
z-index: 8;
top: 43%;
left: 50%;
min-width: 250px;
padding: 18px 25px;
border: 1px solid rgba(247, 227, 108, 0.4);
border-radius: 16px;
background: rgba(8, 17, 31, 0.88);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(14px);
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -35%) scale(0.9);
transition:
opacity 180ms ease,
transform 220ms cubic-bezier(0.2, 0.9, 0.3, 1.25);
}
.outcome.show {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
.outcome strong {
display: block;
color: var(--accent);
font-size: 29px;
letter-spacing: 0.08em;
text-shadow: 0 3px 16px currentColor;
}
.outcome span {
display: block;
margin-top: 6px;
color: #c4d3e4;
font-size: 11px;
}
.camera-help {
position: fixed;
z-index: 4;
left: 26px;
bottom: 22px;
display: flex;
gap: 7px;
flex-wrap: wrap;
pointer-events: none;
}
.camera-help span {
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 7px;
color: #8fa4be;
background: rgba(8, 17, 31, 0.62);
font-size: 9px;
letter-spacing: 0.06em;
backdrop-filter: blur(8px);
}
@media (max-width: 780px) {
.brand {
top: 14px;
left: 15px;
}
.brand p {
display: none;
}
.hud-score {
top: 62px;
}
.hud-team {
min-width: 76px;
padding: 9px 12px;
}
.hud-team strong {
font-size: 24px;
}
.controller {
top: auto;
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
max-height: 46vh;
padding: 15px;
}
.controller h2 {
font-size: 19px;
}
.controller-intro {
display: none;
}
.live-card {
margin-bottom: 10px;
padding: 8px 12px;
}
.live-player strong {
font-size: 24px;
}
.camera-help {
display: none;
}
.outcome {
top: 32%;
min-width: 220px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel rally court"></canvas>
<div class="brand">
<div class="brand-row">
<div class="brand-mark"></div>
<h1>CUBE RALLY</h1>
</div>
<p>Voxel court lab · scripted outcome engine</p>
</div>
<div class="hud-score" aria-live="polite">
<div class="hud-team a">
<span>PLAYER A</span>
<strong id="hudScoreA">0</strong>
</div>
<div class="hud-middle">
<b>FIRST TO 7</b>
<span id="hudServer">A SERVES</span>
</div>
<div class="hud-team b">
<span>PLAYER B</span>
<strong id="hudScoreB">0</strong>
</div>
</div>
<aside class="controller" aria-label="Stepwise scoring controller">
<p class="eyebrow">Scoring controller</p>
<h2>Resolve the rally</h2>
<p class="controller-intro">
Choose the transition before playback. The same transition controls the
ball script, the final impact, the score, and the celebration.
</p>
<div class="live-card">
<div class="live-player a">
<small>PLAYER A</small>
<strong id="scoreA">0</strong>
</div>
<div class="live-divider">
<b id="matchPoint">FIRST TO 7</b>
<span id="server">A SERVES</span>
</div>
<div class="live-player b right">
<small>PLAYER B</small>
<strong id="scoreB">0</strong>
</div>
</div>
<div class="section-label">
Selected transition
<span>step 01</span>
</div>
<div class="transition-list">
<button class="transition selected" data-id="POINT_A" type="button">
<span class="transition-dot"></span>
<span>
<b>RALLY → POINT A</b>
<small>A lands the winning cube</small>
</span>
<span class="arrow">›</span>
</button>
<button class="transition" data-id="POINT_B" type="button">
<span class="transition-dot"></span>
<span>
<b>RALLY → POINT B</b>
<small>B lands the winning cube</small>
</span>
<span class="arrow">›</span>
</button>
<button class="transition" data-id="FAULT_A" type="button">
<span class="transition-dot"></span>
<span>
<b>FAULT A → POINT B</b>
<small>A clips the net; B receives point</small>
</span>
<span class="arrow">›</span>
</button>
<button class="transition" data-id="FAULT_B" type="button">
<span class="transition-dot"></span>
<span>
<b>FAULT B → POINT A</b>
<small>B clips the net; A receives point</small>
</span>
<span class="arrow">›</span>
</button>
<button class="transition" data-id="LET" type="button">
<span class="transition-dot"></span>
<span>
<b>RALLY → LET</b>
<small>Net touch; replay with no point</small>
</span>
<span class="arrow">›</span>
</button>
</div>
<div class="selection-summary" id="selectionSummary">
<b>POINT A</b><br />
A's final shot is scripted into B's court. The point is added at impact.
</div>
<button class="primary" id="applyButton" type="button">Play selected rally</button>
<div class="button-row">
<button class="secondary" id="undoButton" type="button" disabled>Undo last step</button>
<button class="secondary" id="resetButton" type="button">Reset match</button>
</div>
<div class="status-row">
<span>Script status</span>
<b id="statusText">READY</b>
</div>
<div class="beat-track" id="beatTrack" aria-hidden="true"></div>
<div class="section-label">
Resolution log
<span>live</span>
</div>
<div class="log" id="log" aria-live="polite"></div>
</aside>
<div class="outcome" id="outcome" aria-live="assertive">
<strong id="outcomeTitle">POINT A</strong>
<span id="outcomeDetail">A wins the rally</span>
</div>
<div class="camera-help">
<span>DRAG TO ORBIT</span>
<span>WHEEL TO ZOOM</span>
<span>DOUBLE-CLICK TO RESET VIEW</span>
<span>SPACE TO PLAY</span>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1425);
scene.fog = new THREE.Fog(0x0a1425, 34, 68);
const camera = new THREE.PerspectiveCamera(
44,
window.innerWidth / window.innerHeight,
0.1,
120
);
const cameraTarget = new THREE.Vector3(0, 1.1, 0);
const cameraState = {
theta: 0.55,
phi: 0.84,
radius: 32
};
function updateCamera() {
const { theta, phi, radius } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xb9dcff, 0x142137, 2.1);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xfff2d6, 3.4);
keyLight.position.set(12, 24, 16);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -23;
keyLight.shadow.camera.right = 23;
keyLight.shadow.camera.top = 23;
keyLight.shadow.camera.bottom = -23;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 65;
keyLight.shadow.bias = -0.00015;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x60cfff, 1.5);
rimLight.position.set(-15, 10, -18);
scene.add(rimLight);
const celebrationLight = new THREE.PointLight(0xffffff, 0, 14, 2);
celebrationLight.position.set(0, 4, 0);
scene.add(celebrationLight);
// -------------------------------------------------------------------------
// Small helpers
// -------------------------------------------------------------------------
const mat = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04,
...options
});
const materials = {
base: mat(0x111c31),
apron: mat(0x192a43),
line: mat(0xeaf4ff, { roughness: 0.48 }),
dark: mat(0x17253a),
black: mat(0x101722),
post: mat(0x4d6d91),
net: mat(0xb6c9df, { transparent: true, opacity: 0.82 }),
board: mat(0x08111e),
boardFrame: mat(0x304967),
coral: mat(0xff6f61),
cyan: mat(0x40d9e8),
yellow: mat(0xf7e36c, {
emissive: 0x8a6900,
emissiveIntensity: 0.55,
roughness: 0.38
}),
white: mat(0xf4f8ff),
skin: mat(0xe6b58c),
skinDark: mat(0xa56d50),
hair: mat(0x18202d)
};
function addBox(
parent,
width,
height,
depth,
material,
x = 0,
y = 0,
z = 0,
castShadow = true
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function box(
width,
height,
depth,
material,
x = 0,
y = 0,
z = 0,
castShadow = true
) {
return addBox(scene, width, height, depth, material, x, y, z, castShadow);
}
let randomSeed = 90317;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
// -------------------------------------------------------------------------
// Arena and court
// -------------------------------------------------------------------------
box(34, 0.8, 42, materials.base, 0, -0.72, 0, false);
box(21, 0.28, 31, materials.apron, 0, -0.32, 0, false);
const tileGeometry = new THREE.BoxGeometry(1.92, 0.13, 1.92);
const tileMaterial = mat(0xffffff, { roughness: 0.9 });
const tiles = new THREE.InstancedMesh(tileGeometry, tileMaterial, 7 * 12);
const dummy = new THREE.Object3D();
const tileColors = [
new THREE.Color(0x245d6c),
new THREE.Color(0x286979),
new THREE.Color(0x2d7180),
new THREE.Color(0x22566a),
new THREE.Color(0x317b87)
];
let tileIndex = 0;
for (let ix = 0; ix < 7; ix++) {
for (let iz = 0; iz < 12; iz++) {
dummy.position.set(-6 + ix * 2, -0.02, -11 + iz * 2);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
tiles.setColorAt(
tileIndex,
tileColors[Math.floor(random() * tileColors.length)]
);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
// Court markings.
[-5.15, 5.15, -6.25, 6.25].forEach((x) => {
box(0.07, 0.04, 21, materials.line, x, 0.075, 0, false);
});
[-10.4, 10.4, -4.2, 4.2].forEach((z) => {
box(12.5, 0.04, 0.07, materials.line, 0, 0.075, z, false);
});
box(12.5, 0.04, 0.07, materials.line, 0, 0.075, 0, false);
// Net posts and top beam.
box(0.32, 2.55, 0.32, materials.post, -7.05, 1.18, 0);
box(0.32, 2.55, 0.32, materials.post, 7.05, 1.18, 0);
box(14.4, 0.12, 0.12, materials.white, 0, 2.14, 0);
for (let x = -6.7; x <= 6.71; x += 0.67) {
box(0.035, 1.85, 0.035, materials.net, x, 1.08, 0, false);
}
[0.28, 0.68, 1.08, 1.48, 1.88].forEach((y) => {
box(13.45, 0.035, 0.035, materials.net, 0, y, 0, false);
});
// Side bleachers.
for (const side of [-1, 1]) {
for (let row = 0; row < 4; row++) {
box(
1.0,
0.45,
22,
materials.dark,
side * (9.4 + row * 1.05),
0.12 + row * 0.48,
-0.4,
false
);
}
}
// Voxel audience.
const crowdPalette = [
0xef6a5b,
0x3fcbd7,
0xf5d76e,
0x758be7,
0xb16bd3,
0xe7edf7,
0x4db68f
];
for (const side of [-1, 1]) {
for (let row = 0; row < 4; row++) {
for (let seat = 0; seat < 9; seat++) {
const color = crowdPalette[Math.floor(random() * crowdPalette.length)];
const bodyMaterial = mat(color);
const x = side * (9.45 + row * 1.05);
const y = 0.65 + row * 0.48;
const z = -9.2 + seat * 2.25 + (random() - 0.5) * 0.3;
box(0.46, 0.62, 0.43, bodyMaterial, x, y, z, false);
box(
0.34,
0.34,
0.34,
random() > 0.5 ? materials.skin : materials.skinDark,
x,
y + 0.49,
z,
false
);
}
}
}
// Block planters.
for (const side of [-1, 1]) {
for (const z of [-12.8, 12.8]) {
box(1.4, 1.0, 1.4, materials.boardFrame, side * 8.4, 0.4, z);
box(1.05, 1.15, 1.05, mat(0x3c9b72), side * 8.4, 1.45, z);
box(0.55, 0.75, 0.55, mat(0x63c98d), side * 8.4, 2.25, z);
}
}
// Floating arena lights.
for (const x of [-8, 0, 8]) {
box(1.3, 0.22, 1.3, materials.boardFrame, x, 9.4, -9);
box(0.9, 0.08, 0.9, materials.yellow, x, 9.25, -9, false);
}
// -------------------------------------------------------------------------
// Physical voxel scoreboard
// -------------------------------------------------------------------------
const scoreboard = new THREE.Group();
scoreboard.position.z = -14.7;
scene.add(scoreboard);
addBox(
scoreboard,
8.6,
4.1,
0.55,
materials.boardFrame,
0,
5.1,
0
);
addBox(
scoreboard,
8.15,
3.65,
0.12,
materials.board,
0,
5.1,
0.33
);
addBox(scoreboard, 0.45, 3.5, 0.45, materials.post, -2.6, 1.6, 0);
addBox(scoreboard, 0.45, 3.5, 0.45, materials.post, 2.6, 1.6, 0);
function createSevenDigit(x, y, z, color) {
const group = new THREE.Group();
group.position.set(x, y, z);
scoreboard.add(group);
const segmentMaterial = mat(color, {
emissive: color,
emissiveIntensity: 0.22
});
const definitions = {
a: [0, 0.58, 0.5, 0.12],
b: [0.31, 0.29, 0.12, 0.48],
c: [0.31, -0.29, 0.12, 0.48],
d: [0, -0.58, 0.5, 0.12],
e: [-0.31, -0.29, 0.12, 0.48],
f: [-0.31, 0.29, 0.12, 0.48],
g: [0, 0, 0.5, 0.12]
};
const segments = {};
for (const [name, [sx, sy, sw, sh]] of Object.entries(definitions)) {
const mesh = addBox(
group,
sw,
sh,
0.08,
segmentMaterial,
sx,
sy,
0,
false
);
mesh.visible = false;
segments[name] = mesh;
}
return { group, segments };
}
const digitPatterns = {
0: "abcdef",
1: "bc",
2: "abdeg",
3: "abcdg",
4: "bcfg",
5: "acdfg",
6: "acdefg",
7: "abc",
8: "abcdefg",
9: "abcdfg"
};
function setDigit(digit, value) {
const active = digitPatterns[value] ?? "";
for (const [name, mesh] of Object.entries(digit.segments)) {
mesh.visible = active.includes(name);
}
}
const physicalDigits = {
A: [
createSevenDigit(-2.5, 4.9, 0.45, 0xff6f61),
createSevenDigit(-1.35, 4.9, 0.45, 0xff6f61)
],
B: [
createSevenDigit(1.35, 4.9, 0.45, 0x40d9e8),
createSevenDigit(2.5, 4.9, 0.45, 0x40d9e8)
]
};
const pixelLetters = {
A: ["01110", "10001", "10001", "11111", "10001", "10001", "10001"],
B: ["11110", "10001", "10001", "11110", "10001", "10001", "11110"]
};
function addPixelLetter(letter, x, y, z, color) {
const pattern = pixelLetters[letter];
const cell = 0.19;
const material = mat(color, {
emissive: color,
emissiveIntensity: 0.18
});
pattern.forEach((row, rowIndex) => {
[...row].forEach((value, columnIndex) => {
if (value === "1") {
addBox(
scoreboard,
0.145,
0.145,
0.08,
material,
x + (columnIndex - 2) * cell,
y + (3 - rowIndex) * cell,
z,
false
);
}
});
});
}
addPixelLetter("A", -1.92, 6.1, 0.46, 0xff6f61);
addPixelLetter("B", 1.92, 6.1, 0.46, 0x40d9e8);
// -------------------------------------------------------------------------
// Voxel players
// -------------------------------------------------------------------------
function createPlayer(side, bodyMaterial, accentMaterial) {
const root = new THREE.Group();
const baseZ = side === "A" ? 7.35 : -7.35;
const baseX = side === "A" ? 2.3 : -2.3;
root.position.set(baseX, 0, baseZ);
root.rotation.y = side === "A" ? 0 : Math.PI;
scene.add(root);
const torso = addBox(
root,
0.92,
1.12,
0.62,
bodyMaterial,
0,
1.43,
0
);
addBox(root, 0.96, 0.19, 0.66, accentMaterial, 0, 1.91, 0);
addBox(root, 0.98, 0.2, 0.66, accentMaterial, 0, 0.96, 0);
const head = new THREE.Group();
head.position.set(0, 2.18, 0);
root.add(head);
addBox(head, 0.67, 0.67, 0.62, materials.skin, 0, 0, 0);
addBox(head, 0.72, 0.22, 0.66, materials.hair, 0, 0.34, 0.015);
addBox(head, 0.18, 0.22, 0.12, materials.hair, -0.29, 0.12, 0.02);
addBox(head, 0.11, 0.11, 0.07, materials.white, -0.17, 0.04, -0.34);
addBox(head, 0.11, 0.11, 0.07, materials.white, 0.17, 0.04, -0.34);
addBox(head, 0.055, 0.075, 0.04, materials.black, -0.17, 0.025, -0.39);
addBox(head, 0.055, 0.075, 0.04, materials.black, 0.17, 0.025, -0.39);
function createArm(x) {
const pivot = new THREE.Group();
pivot.position.set(x, 1.78, 0);
root.add(pivot);
addBox(pivot, 0.28, 0.75, 0.3, bodyMaterial, 0, -0.35, 0);
addBox(pivot, 0.3, 0.28, 0.32, materials.skin, 0, -0.78, 0);
return pivot;
}
function createLeg(x) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.91, 0);
root.add(pivot);
addBox(pivot, 0.34, 0.76, 0.37, bodyMaterial, 0, -0.37, 0);
addBox(pivot, 0.38, 0.22, 0.55, accentMaterial, 0, -0.78, -0.08);
return pivot;
}
const leftArm = createArm(-0.58);
const rightArm = createArm(0.58);
const leftLeg = createLeg(-0.25);
const rightLeg = createLeg(0.25);
// Voxel racket attached to the right arm.
const racket = new THREE.Group();
racket.position.set(0, -0.9, -0.12);
rightArm.add(racket);
addBox(racket, 0.58, 0.08, 0.1, accentMaterial, 0, 0.28, 0);
addBox(racket, 0.58, 0.08, 0.1, accentMaterial, 0, -0.28, 0);
addBox(racket, 0.08, 0.56, 0.1, accentMaterial, -0.25, 0, 0);
addBox(racket, 0.08, 0.56, 0.1, accentMaterial, 0.25, 0, 0);
addBox(racket, 0.06, 0.25, 0.07, materials.white, 0, 0, 0);
return {
side,
root,
torso,
head,
leftArm,
rightArm,
leftLeg,
rightLeg,
baseX,
baseZ,
accentMaterial
};
}
const playerA = createPlayer("A", materials.coral, materials.yellow);
const playerB = createPlayer("B", materials.cyan, materials.white);
// -------------------------------------------------------------------------
// Ball and trail
// -------------------------------------------------------------------------
const ball = new THREE.Mesh(
new THREE.BoxGeometry(0.27, 0.27, 0.27),
materials.yellow
);
ball.castShadow = true;
ball.visible = false;
scene.add(ball);
const ballLight = new THREE.PointLight(0xffe98b, 1.7, 4, 2);
ball.add(ballLight);
const trailMeshes = [];
const trailGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
for (let i = 0; i < 18; i++) {
const mesh = new THREE.Mesh(
trailGeometry,
new THREE.MeshBasicMaterial({
color: 0xf7e36c,
transparent: true,
opacity: 0.35 * (1 - i / 18),
depthWrite: false
})
);
mesh.visible = false;
trailMeshes.push(mesh);
scene.add(mesh);
}
let trailPoints = [];
// -------------------------------------------------------------------------
// Scoring transitions and deterministic rally scripts
// -------------------------------------------------------------------------
const transitions = {
POINT_A: {
title: "POINT A",
chain: "RALLY → POINT A",
description:
"A's final shot is scripted into B's court. The point is added at impact.",
award: "A",
winner: "A",
loser: "B",
color: 0xff6f61
},
POINT_B: {
title: "POINT B",
chain: "RALLY → POINT B",
description:
"B's final shot is scripted into A's court. The point is added at impact.",
award: "B",
winner: "B",
loser: "A",
color: 0x40d9e8
},
FAULT_A: {
title: "FAULT A",
chain: "FAULT A → POINT B",
description:
"A clips the net on the final hit. The fault awards one point to B.",
award: "B",
winner: "B",
loser: "A",
color: 0xff9e64
},
FAULT_B: {
title: "FAULT B",
chain: "FAULT B → POINT A",
description:
"B clips the net on the final hit. The fault awards one point to A.",
award: "A",
winner: "A",
loser: "B",
color: 0x8e9cff
},
LET: {
title: "LET",
chain: "RALLY → LET",
description:
"The ball touches the net and the rally is replayed. No point is added.",
award: null,
winner: null,
loser: null,
color: 0xf7e36c
}
};
const commonOpening = [
{
t: 0.6,
hitter: "A",
from: [1.5, 1.35, 7.1],
to: [-2.3, 1.25, -5.5],
arc: 1.15
},
{
t: 1.4,
hitter: "B",
from: [-2.3, 1.25, -5.5],
to: [2.2, 1.3, 5.5],
arc: 1.18
},
{
t: 2.2,
hitter: "A",
from: [2.2, 1.3, 5.5],
to: [-1.8, 1.25, -5.6],
arc: 1.16
}
];
const returnToA = {
t: 3.0,
hitter: "B",
from: [-1.8, 1.25, -5.6],
to: [2.3, 1.25, 5.5],
arc: 1.18
};
const aReturns = {
t: 3.8,
hitter: "A",
from: [2.3, 1.25, 5.5],
to: [-2.2, 1.25, -5.6],
arc: 1.16
};
const bReturns = {
t: 4.6,
hitter: "B",
from: [-2.2, 1.25, -5.6],
to: [2.0, 1.25, 5.5],
arc: 1.15
};
function getHits(id) {
let hits;
if (id === "POINT_A") {
hits = [
...commonOpening,
returnToA,
aReturns,
bReturns,
{
t: 5.4,
hitter: "A",
from: [2.0, 1.25, 5.5],
to: [-1.6, 0.16, -6.4],
arc: 0.9,
final: true
}
];
} else if (id === "POINT_B") {
hits = [
...commonOpening,
returnToA,
aReturns,
{
t: 4.6,
hitter: "B",
from: [-2.2, 1.25, -5.6],
to: [1.8, 0.16, 6.4],
arc: 0.9,
final: true
}
];
} else if (id === "FAULT_A") {
hits = [
...commonOpening,
returnToA,
{
t: 4.6,
hitter: "A",
from: [2.3, 1.25, 5.5],
via: [0, 1.45, 0],
to: [0, 0.16, 1.6],
arc: 0.12,
net: true,
final: true
}
];
} else if (id === "FAULT_B") {
hits = [
...commonOpening,
returnToA,
aReturns,
{
t: 4.6,
hitter: "B",
from: [-2.2, 1.25, -5.6],
via: [0, 1.45, 0],
to: [0, 0.16, -1.6],
arc: 0.12,
net: true,
final: true
}
];
} else {
hits = [
...commonOpening,
{
t: 3.0,
hitter: "B",
from: [-1.8, 1.25, -5.6],
via: [0, 1.25, 0],
to: [0, 0.16, -0.7],
arc: 0.1,
net: true,
final: true
}
];
}
for (const hit of hits) {
hit.fromV = new THREE.Vector3(...hit.from);
hit.toV = new THREE.Vector3(...hit.to);
hit.viaV = hit.via ? new THREE.Vector3(...hit.via) : null;
hit.netTriggered = false;
}
return hits;
}
// -------------------------------------------------------------------------
// Match and UI state
// -------------------------------------------------------------------------
const score = { A: 0, B: 0 };
const history = [];
const targetScore = 7;
let selectedId = "POINT_A";
let currentTransition = transitions[selectedId];
let currentHits = [];
let rallyActive = false;
let rallyTime = 0;
let outcomeResolved = false;
let gameOver = false;
let resolveAt = -100;
let outcomeState = null;
let globalTime = 0;
const els = {
scoreA: document.querySelector("#scoreA"),
scoreB: document.querySelector("#scoreB"),
hudScoreA: document.querySelector("#hudScoreA"),
hudScoreB: document.querySelector("#hudScoreB"),
server: document.querySelector("#server"),
hudServer: document.querySelector("#hudServer"),
matchPoint: document.querySelector("#matchPoint"),
status: document.querySelector("#statusText"),
apply: document.querySelector("#applyButton"),
undo: document.querySelector("#undoButton"),
reset: document.querySelector("#resetButton"),
summary: document.querySelector("#selectionSummary"),
log: document.querySelector("#log"),
outcome: document.querySelector("#outcome"),
outcomeTitle: document.querySelector("#outcomeTitle"),
outcomeDetail: document.querySelector("#outcomeDetail"),
beatTrack: document.querySelector("#beatTrack")
};
const transitionButtons = [
...document.querySelectorAll(".transition")
];
function updateScoreDisplay() {
els.scoreA.textContent = score.A;
els.scoreB.textContent = score.B;
els.hudScoreA.textContent = score.A;
els.hudScoreB.textContent = score.B;
const total = score.A + score.B;
const server = total % 2 === 0 ? "A" : "B";
els.server.textContent = `${server} SERVES`;
els.hudServer.textContent = `${server} SERVES`;
if (score.A === targetScore - 1 || score.B === targetScore - 1) {
els.matchPoint.textContent = "MATCH POINT";
} else {
els.matchPoint.textContent = "FIRST TO 7";
}
setDigit(physicalDigits.A[0], Math.floor(score.A / 10));
setDigit(physicalDigits.A[1], score.A % 10);
setDigit(physicalDigits.B[0], Math.floor(score.B / 10));
setDigit(physicalDigits.B[1], score.B % 10);
}
function setBusy(busy) {
transitionButtons.forEach((button) => {
button.disabled = busy;
});
els.apply.disabled = busy || gameOver;
els.undo.disabled = busy || history.length === 0;
els.reset.disabled = busy;
}
function selectTransition(id) {
if (rallyActive || !transitions[id]) return;
selectedId = id;
currentTransition = transitions[id];
transitionButtons.forEach((button) => {
button.classList.toggle("selected", button.dataset.id === id);
});
els.summary.innerHTML = `
<b>${currentTransition.chain}</b><br />
${currentTransition.description}
`;
}
transitionButtons.forEach((button) => {
button.addEventListener("click", () => {
selectTransition(button.dataset.id);
});
});
function addLog(title, detail, color = "#90a5bf") {
const entry = document.createElement("div");
entry.className = "log-entry";
const time = document.createElement("time");
const totalSeconds = Math.floor(globalTime);
const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, "0");
const seconds = String(totalSeconds % 60).padStart(2, "0");
time.textContent = `${minutes}:${seconds}`;
const content = document.createElement("div");
const heading = document.createElement("b");
heading.textContent = title;
heading.style.color = color;
const body = document.createElement("span");
body.textContent = detail;
content.append(heading, body);
entry.append(time, content);
els.log.prepend(entry);
while (els.log.children.length > 6) {
els.log.lastElementChild.remove();
}
}
let outcomeTimeout;
function showOutcome(title, detail, color) {
clearTimeout(outcomeTimeout);
els.outcomeTitle.textContent = title;
els.outcomeTitle.style.color = `#${color.toString(16).padStart(6, "0")}`;
els.outcomeDetail.textContent = detail;
els.outcome.classList.add("show");
outcomeTimeout = setTimeout(() => {
els.outcome.classList.remove("show");
}, 1450);
}
function createBeatTrack() {
els.beatTrack.innerHTML = "";
for (let i = 0; i < 7; i++) {
const beat = document.createElement("span");
beat.className = "beat";
els.beatTrack.append(beat);
}
}
createBeatTrack();
// -------------------------------------------------------------------------
// Effects
// -------------------------------------------------------------------------
const effects = [];
function spawnBurst(position, color, count = 22) {
for (let i = 0; i < count; i++) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 1
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.12, 0.12),
material
);
mesh.position.copy(position);
mesh.rotation.set(random() * 3, random() * 3, random() * 3);
scene.add(mesh);
effects.push({
type: "particle",
mesh,
velocity: new THREE.Vector3(
(random() - 0.5) * 5.5,
2.4 + random() * 4.2,
(random() - 0.5) * 5.5
),
life: 1.25 + random() * 0.65,
maxLife: 1.9
});
}
}
function spawnImpact(position, color) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9
});
for (let i = 0; i < 10; i++) {
const angle = (i / 10) * Math.PI * 2;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.12, 0.12),
material.clone()
);
mesh.position.set(
position.x + Math.cos(angle) * 0.45,
Math.max(0.13, position.y),
position.z + Math.sin(angle) * 0.45
);
scene.add(mesh);
effects.push({
type: "ring",
mesh,
direction: new THREE.Vector3(Math.cos(angle), 0.1, Math.sin(angle)),
life: 0.65,
maxLife: 0.65
});
}
}
function updateEffects(dt) {
for (let i = effects.length - 1; i >= 0; i--) {
const effect = effects[i];
effect.life -= dt;
if (effect.life <= 0) {
scene.remove(effect.mesh);
effect.mesh.geometry.dispose();
effect.mesh.material.dispose();
effects.splice(i, 1);
continue;
}
if (effect.type === "particle") {
effect.velocity.y -= 8.5 * dt;
effect.mesh.position.addScaledVector(effect.velocity, dt);
effect.mesh.rotation.x += dt * 7;
effect.mesh.rotation.y += dt * 9;
effect.mesh.material.opacity =
Math.max(0, effect.life / effect.maxLife);
} else {
effect.mesh.position.addScaledVector(effect.direction, dt * 2.6);
effect.mesh.material.opacity = effect.life / effect.maxLife;
const scale = 1 + (1 - effect.life / effect.maxLife) * 2.4;
effect.mesh.scale.setScalar(scale);
}
}
}
// -------------------------------------------------------------------------
// Rally playback
// -------------------------------------------------------------------------
function sampleHit(hit, u, output) {
if (hit.viaV) {
const split = 0.72;
if (u <= split) {
output.lerpVectors(hit.fromV, hit.viaV, u / split);
output.y += Math.sin(Math.PI * (u / split)) * hit.arc;
} else {
const after = (u - split) / (1 - split);
output.lerpVectors(hit.viaV, hit.toV, after);
output.y += Math.sin(Math.PI * after) * 0.05;
}
} else {
output.lerpVectors(hit.fromV, hit.toV, u);
output.y += Math.sin(Math.PI * u) * hit.arc;
}
return output;
}
const sampledBallPosition = new THREE.Vector3();
function updateRally(dt) {
rallyTime += dt;
const lastHit = currentHits[currentHits.length - 1];
if (rallyTime < lastHit.t) {
let index = 0;
while (
index < currentHits.length - 1 &&
rallyTime > currentHits[index].t
) {
index++;
}
const hit = currentHits[index];
const previousTime = index === 0 ? 0 : currentHits[index - 1].t;
const u = THREE.MathUtils.clamp(
(rallyTime - previousTime) / Math.max(0.001, hit.t - previousTime),
0,
1
);
sampleHit(hit, u, sampledBallPosition);
ball.position.copy(sampledBallPosition);
if (hit.net && hit.viaV && !hit.netTriggered && u >= 0.72) {
hit.netTriggered = true;
spawnImpact(hit.viaV, 0xf7e36c);
}
const activeBeat = Math.min(
els.beatTrack.children.length - 1,
Math.floor((rallyTime / lastHit.t) * els.beatTrack.children.length)
);
[...els.beatTrack.children].forEach((beat, index) => {
beat.classList.toggle("active", index === activeBeat);
});
} else {
if (!outcomeResolved) {
resolveOutcome();
}
const impact = lastHit.toV;
const after = rallyTime - lastHit.t;
const direction = new THREE.Vector3().subVectors(
lastHit.toV,
lastHit.fromV
);
direction.y = 0;
direction.normalize();
ball.position.copy(impact);
ball.position.addScaledVector(direction, Math.min(after, 1.25) * 0.7);
ball.position.y =
impact.y +
Math.abs(Math.sin(after * 8)) *
0.38 *
Math.max(0, 1 - after / 1.25);
}
ball.rotation.x += dt * 5.5;
ball.rotation.y += dt * 7;
trailPoints.unshift(ball.position.clone());
if (trailPoints.length > trailMeshes.length) {
trailPoints.pop();
}
trailMeshes.forEach((mesh, index) => {
const point = trailPoints[index];
mesh.visible = Boolean(point);
if (!point) return;
mesh.position.copy(point);
const scale = 1 - index / trailMeshes.length;
mesh.scale.setScalar(0.5 + scale * 0.65);
});
if (rallyTime > lastHit.t + 1.35) {
finishRally();
}
}
function resolveOutcome() {
outcomeResolved = true;
resolveAt = globalTime;
const before = { ...score };
const transition = currentTransition;
// The score changes in this exact function, at the same instant as the
// impact effect, player reaction, overlay, log, and physical scoreboard.
if (transition.award) {
score[transition.award] += 1;
}
outcomeState = {
winner: transition.winner,
loser: transition.loser
};
updateScoreDisplay();
const finalHit = currentHits[currentHits.length - 1];
const impactColor = transition.winner
? transitions[transition.winner === "A" ? "POINT_A" : "POINT_B"].color
: transition.color;
spawnImpact(finalHit.toV, impactColor);
if (transition.winner) {
const winner = transition.winner === "A" ? playerA : playerB;
const winnerPosition = winner.root.position.clone();
winnerPosition.y = 2.7;
spawnBurst(winnerPosition, impactColor, 34);
celebrationLight.color.setHex(impactColor);
celebrationLight.intensity = 6;
celebrationLight.position.copy(winner.root.position);
celebrationLight.position.y = 3.5;
} else {
celebrationLight.intensity = 0;
}
let detail;
if (transition.award) {
detail =
`${transition.title === "FAULT A" ? "A clips the net" : transition.title === "FAULT B" ? "B clips the net" : `${transition.winner} lands the winning cube`}` +
` · ${score.A}–${score.B}`;
} else {
detail = `Net touch · replay · score remains ${score.A}–${score.B}`;
}
showOutcome(transition.title, detail, impactColor);
addLog(
transition.title,
detail,
`#${impactColor.toString(16).padStart(6, "0")}`
);
history.push({
transitionId: selectedId,
before,
after: { ...score },
award: transition.award
});
gameOver = score.A >= targetScore || score.B >= targetScore;
if (gameOver) {
const matchWinner = score.A > score.B ? "A" : "B";
els.status.textContent = `MATCH ${matchWinner}`;
addLog(
`MATCH ${matchWinner}`,
`${score.A}–${score.B} · complete`,
matchWinner === "A" ? "#ff6f61" : "#40d9e8"
);
}
}
function finishRally() {
rallyActive = false;
[...els.beatTrack.children].forEach((beat) => {
beat.classList.remove("active");
});
if (!gameOver) {
els.status.textContent = "READY";
}
setBusy(false);
els.undo.disabled = history.length === 0;
}
function playSelectedRally() {
if (rallyActive || gameOver) return;
currentTransition = transitions[selectedId];
currentHits = getHits(selectedId);
rallyActive = true;
rallyTime = 0;
outcomeResolved = false;
outcomeState = null;
resolveAt = -100;
ball.visible = true;
ball.position.copy(currentHits[0].fromV);
trailPoints = [];
trailMeshes.forEach((mesh) => {
mesh.visible = false;
});
celebrationLight.intensity = 0;
els.status.textContent = "RALLY LIVE";
els.outcome.classList.remove("show");
setBusy(true);
addLog(
"RALLY STARTED",
currentTransition.chain,
"#f7e36c"
);
}
function undoLastStep() {
if (rallyActive || history.length === 0) return;
const last = history.pop();
score.A = last.before.A;
score.B = last.before.B;
gameOver = false;
updateScoreDisplay();
outcomeState = null;
celebrationLight.intensity = 0;
ball.visible = false;
els.status.textContent = "READY";
els.outcome.classList.remove("show");
addLog("STEP UNDONE", "Score and match state restored", "#90a5bf");
setBusy(false);
}
function resetMatch() {
if (rallyActive) return;
score.A = 0;
score.B = 0;
history.length = 0;
gameOver = false;
rallyActive = false;
outcomeResolved = false;
outcomeState = null;
resolveAt = -100;
ball.visible = false;
trailPoints = [];
trailMeshes.forEach((mesh) => {
mesh.visible = false;
});
celebrationLight.intensity = 0;
els.log.innerHTML = "";
els.outcome.classList.remove("show");
els.status.textContent = "READY";
updateScoreDisplay();
setBusy(false);
addLog("MATCH RESET", "First to seven · ready", "#90a5bf");
}
els.apply.addEventListener("click", playSelectedRally);
els.undo.addEventListener("click", undoLastStep);
els.reset.addEventListener("click", resetMatch);
// -------------------------------------------------------------------------
// Player animation
// -------------------------------------------------------------------------
function animatePlayer(player, dt) {
let swing = 0;
let targetX = player.baseX;
let closestDistance = Infinity;
if (rallyActive) {
for (const hit of currentHits) {
if (hit.hitter !== player.side) continue;
const distance = Math.abs(rallyTime - hit.t);
if (distance < closestDistance) {
closestDistance = distance;
targetX = hit.fromV.x;
}
const delta = rallyTime - hit.t;
if (delta >= -0.28 && delta <= 0.28) {
swing = Math.max(
swing,
Math.sin(((delta + 0.28) / 0.56) * Math.PI)
);
}
}
}
player.root.position.x = THREE.MathUtils.damp(
player.root.position.x,
targetX,
9,
dt
);
const lungeDirection = player.side === "A" ? -1 : 1;
player.root.position.z = player.baseZ + lungeDirection * swing * 0.3;
player.root.position.y = Math.abs(Math.sin(globalTime * 5)) * 0.035;
const walk = Math.sin(globalTime * 7 + (player.side === "A" ? 0 : 1.8));
player.leftLeg.rotation.x = walk * 0.08;
player.rightLeg.rotation.x = -walk * 0.08;
player.leftArm.rotation.set(0, 0, 0);
player.rightArm.rotation.set(0, 0, 0);
player.torso.rotation.set(0, 0, 0);
player.head.rotation.set(0, 0, 0);
player.rightArm.rotation.x = -swing * 1.55;
player.leftArm.rotation.x = swing * 0.45;
const celebrationAge = globalTime - resolveAt;
if (outcomeState && celebrationAge >= 0 && celebrationAge < 3.1) {
if (outcomeState.winner === player.side) {
const bounce = Math.abs(Math.sin(celebrationAge * 7));
player.root.position.y = bounce * 0.2;
player.leftArm.rotation.z = 2.25;
player.rightArm.rotation.z = -2.25;
player.leftLeg.rotation.x = -0.18;
player.rightLeg.rotation.x = 0.18;
} else if (outcomeState.loser === player.side) {
player.torso.rotation.x = 0.23;
player.head.rotation.x = 0.18;
player.root.position.y = -0.06;
}
}
}
// -------------------------------------------------------------------------
// Direct camera controls — no addons
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.42,
1.34
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.025,
20,
48
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraState.theta = 0.55;
cameraState.phi = 0.84;
cameraState.radius = 32;
updateCamera();
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
playSelectedRally();
}
if (event.key === "ArrowLeft") {
cameraState.theta -= 0.1;
updateCamera();
}
if (event.key === "ArrowRight") {
cameraState.theta += 0.1;
updateCamera();
}
if (event.key === "ArrowUp") {
cameraState.phi = Math.max(0.42, cameraState.phi - 0.08);
updateCamera();
}
if (event.key === "ArrowDown") {
cameraState.phi = Math.min(1.34, cameraState.phi + 0.08);
updateCamera();
}
if (event.key === "+" || event.key === "=") {
cameraState.radius = Math.max(20, cameraState.radius - 2);
updateCamera();
}
if (event.key === "-" || event.key === "_") {
cameraState.radius = Math.min(48, cameraState.radius + 2);
updateCamera();
}
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
globalTime += dt;
if (rallyActive) {
updateRally(dt);
}
animatePlayer(playerA, dt);
animatePlayer(playerB, dt);
updateEffects(dt);
celebrationLight.intensity = THREE.MathUtils.damp(
celebrationLight.intensity,
0,
2.2,
dt
);
renderer.render(scene, camera);
});
updateScoreDisplay();
selectTransition(selectedId);
addLog("COURT READY", "Select a transition, then play the rally", "#40d9e8");
</script>
</body>
</html>
```