Prompt specification
Build or customize the Three.js 3D scene "Design a Fair Circular Race" 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: Design a Fair Circular Race
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/design-a-fair-circular-race-x3672
Scene Description Prompt:
Make a low-poly circular-race puzzle where staggered starting positions give each lane equal travel distance. Three.js from cdnjs, one HTML file.
Working Three.js Starter (design-a-fair-circular-race-x3672):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Circle Equal — Low-Poly Race Puzzle</title>
<style>
:root {
--ink: #17252b;
--paper: #f7f3e8;
--panel: rgba(255, 252, 242, 0.91);
--line: rgba(23, 37, 43, 0.13);
--ember: #f2685c;
--sun: #efbd4d;
--mint: #39b9a5;
--sky: #579bd1;
--green: #4f9b72;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9dce1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#stage,
#stage canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#stage canvas {
touch-action: none;
outline: none;
}
.brand {
position: fixed;
z-index: 5;
top: 26px;
left: 28px;
max-width: 430px;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
padding: 6px 9px;
border: 1px solid rgba(23, 37, 43, 0.18);
border-radius: 999px;
background: rgba(255, 252, 242, 0.72);
backdrop-filter: blur(8px);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.15em;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--ember);
box-shadow: 13px 0 0 var(--sun), 26px 0 0 var(--mint), 39px 0 0 var(--sky);
margin-right: 37px;
}
h1 {
margin: 0;
font-size: clamp(38px, 6vw, 78px);
line-height: 0.88;
letter-spacing: -0.065em;
font-weight: 950;
}
.brand p {
width: min(390px, 90vw);
margin: 15px 0 0;
font-size: 13px;
line-height: 1.55;
font-weight: 650;
}
.panel {
position: fixed;
z-index: 10;
top: 24px;
right: 24px;
width: min(350px, calc(100vw - 32px));
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(36, 66, 68, 0.18),
inset 0 0 0 1px rgba(23, 37, 43, 0.04);
backdrop-filter: blur(16px) saturate(1.15);
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.panel-heading h2 {
margin: 0;
font-size: 19px;
letter-spacing: -0.035em;
}
.panel-heading p {
margin: 4px 0 0;
color: rgba(23, 37, 43, 0.62);
font-size: 11px;
font-weight: 650;
}
.status {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 999px;
background: rgba(242, 104, 92, 0.12);
color: #b8473e;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.status::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.status.ready {
color: #25836f;
background: rgba(57, 185, 165, 0.15);
}
.balance {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 10px;
}
.metric {
padding: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.42);
}
.metric-label {
color: rgba(23, 37, 43, 0.52);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.11em;
}
.metric-value {
display: block;
margin-top: 4px;
font-size: 24px;
line-height: 1;
font-weight: 900;
letter-spacing: -0.045em;
}
.metric-value small {
font-size: 11px;
letter-spacing: 0;
}
.rule {
margin: 0 0 10px;
padding: 9px 11px;
border-radius: 11px;
background: rgba(23, 37, 43, 0.055);
color: rgba(23, 37, 43, 0.7);
font-size: 10px;
line-height: 1.45;
font-weight: 700;
}
.lanes {
display: grid;
gap: 7px;
}
.lane {
position: relative;
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
padding: 10px 11px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.42);
color: var(--ink);
cursor: pointer;
text-align: left;
transition: transform 150ms ease, border-color 150ms ease, background 150ms ease;
}
.lane:hover {
transform: translateX(-2px);
background: rgba(255, 255, 255, 0.75);
}
.lane.active {
border-color: var(--lane-color);
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 5px 14px rgba(23, 37, 43, 0.08);
}
.lane-dot {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--lane-color);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--lane-color) 18%, transparent);
}
.lane-name {
display: block;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.lane-detail {
display: block;
margin-top: 2px;
color: rgba(23, 37, 43, 0.55);
font-size: 9px;
font-weight: 700;
}
.lane-arc {
text-align: right;
}
.lane-arc strong {
display: block;
font-size: 14px;
letter-spacing: -0.02em;
}
.lane-arc small {
color: rgba(23, 37, 43, 0.52);
font-size: 9px;
font-weight: 800;
}
.progress {
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 3px;
background: rgba(23, 37, 43, 0.05);
}
.progress > i {
display: block;
width: 0;
height: 100%;
background: var(--lane-color);
transition: width 80ms linear;
}
.hint-box {
display: none;
margin: 9px 0 0;
padding: 10px 11px;
border-left: 3px solid var(--sun);
border-radius: 4px 10px 10px 4px;
background: rgba(239, 189, 77, 0.14);
font-size: 10px;
line-height: 1.5;
font-weight: 700;
}
.hint-box.show {
display: block;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.actions button,
.result button {
min-height: 42px;
border: 0;
border-radius: 12px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.035em;
cursor: pointer;
transition: transform 140ms ease, filter 140ms ease, opacity 140ms ease;
}
.actions button:hover,
.result button:hover {
transform: translateY(-1px);
filter: brightness(0.98);
}
.actions button:active,
.result button:active {
transform: translateY(1px);
}
.secondary {
background: rgba(23, 37, 43, 0.08);
color: var(--ink);
}
.primary {
background: var(--ink);
color: var(--paper);
}
#runButton {
grid-column: 1 / -1;
min-height: 48px;
background: var(--ink);
color: var(--paper);
box-shadow: 0 8px 18px rgba(23, 37, 43, 0.18);
}
#runButton.ready {
background: #25836f;
}
#runButton:disabled {
cursor: wait;
opacity: 0.5;
}
.help {
position: fixed;
z-index: 4;
left: 28px;
bottom: 24px;
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
max-width: calc(100vw - 56px);
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 12px;
background: rgba(255, 252, 242, 0.72);
backdrop-filter: blur(10px);
color: rgba(23, 37, 43, 0.7);
font-size: 10px;
font-weight: 750;
pointer-events: none;
}
.help span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.help b {
color: var(--ink);
font-size: 9px;
letter-spacing: 0.07em;
}
.toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 25px;
max-width: min(480px, calc(100vw - 32px));
padding: 11px 16px;
border-radius: 999px;
background: rgba(23, 37, 43, 0.92);
color: var(--paper);
box-shadow: 0 10px 28px rgba(23, 37, 43, 0.22);
font-size: 11px;
font-weight: 750;
text-align: center;
opacity: 0;
transform: translate(-50%, 12px);
pointer-events: none;
transition: opacity 180ms ease, transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.countdown {
position: fixed;
z-index: 25;
top: 50%;
left: 50%;
color: var(--paper);
font-size: clamp(82px, 16vw, 170px);
line-height: 1;
font-weight: 950;
letter-spacing: -0.08em;
text-shadow: 0 8px 0 rgba(23, 37, 43, 0.18);
transform: translate(-50%, -50%);
pointer-events: none;
}
.countdown.go {
color: #fff1a8;
font-size: clamp(64px, 12vw, 130px);
}
.result {
position: fixed;
z-index: 40;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(28, 48, 52, 0.28);
backdrop-filter: blur(6px);
}
.result-card {
width: min(430px, 100%);
padding: 28px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 25px;
background: var(--paper);
box-shadow: 0 25px 70px rgba(23, 37, 43, 0.25);
text-align: center;
}
.result-card .eyebrow {
margin-bottom: 14px;
background: rgba(23, 37, 43, 0.055);
}
.result-card h2 {
margin: 0;
font-size: clamp(30px, 7vw, 54px);
line-height: 0.95;
letter-spacing: -0.06em;
}
.result-card p {
margin: 14px auto 21px;
max-width: 330px;
color: rgba(23, 37, 43, 0.66);
font-size: 12px;
line-height: 1.6;
font-weight: 650;
}
.result-card button {
width: 100%;
background: var(--ink);
color: var(--paper);
}
[hidden] {
display: none !important;
}
@media (max-width: 760px) {
.brand {
top: 16px;
left: 16px;
}
.brand p {
display: none;
}
h1 {
font-size: 40px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 48vh;
overflow: auto;
padding: 13px;
border-radius: 18px;
}
.lanes {
grid-template-columns: 1fr 1fr;
}
.lane {
grid-template-columns: 9px 1fr;
gap: 7px;
padding: 8px;
}
.lane-arc {
grid-column: 2;
text-align: left;
}
.lane-arc strong,
.lane-arc small {
display: inline;
margin-right: 4px;
}
.help {
display: none;
}
.toast {
bottom: calc(48vh + 24px);
}
}
</style>
</head>
<body>
<main id="stage" aria-label="Interactive low-poly circular race puzzle"></main>
<header class="brand">
<div class="eyebrow">LOW-POLY PUZZLE / 04 LANES</div>
<h1>CIRCLE<br />EQUAL</h1>
<p>
Stagger the starting gates until every lane has the same travel distance.
Different radii. One fair finish.
</p>
</header>
<section class="panel" aria-label="Puzzle controls">
<div class="panel-heading">
<div>
<h2>Arc balance</h2>
<p>Select a lane, then drag its starting gate.</p>
</div>
<div id="status" class="status">UNBALANCED</div>
</div>
<div class="balance">
<div class="metric">
<span class="metric-label">ARC SPREAD</span>
<span class="metric-value"><span id="spreadValue">0.00</span> <small>m</small></span>
</div>
<div class="metric">
<span class="metric-label">COMMON ARC</span>
<span class="metric-value"><span id="meanValue">0.00</span> <small>m</small></span>
</div>
</div>
<p class="rule">
A fair layout needs equal arcs between <b>20–30 m</b>.
Outer lanes require a smaller angular sweep.
</p>
<div id="laneRows" class="lanes"></div>
<div id="hintBox" class="hint-box">
<b>Hint:</b> choose a target such as 25 m for every lane, then set each
angle with <b>arc = radius × angle</b>. The inner lane needs the largest sweep.
</div>
<div class="actions">
<button id="newButton" class="secondary" type="button">NEW LAYOUT</button>
<button id="hintButton" class="secondary" type="button">HINT</button>
<button id="runButton" type="button">TEST THE RACE</button>
</div>
</section>
<div class="help">
<span><b>DRAG</b> colored gates</span>
<span><b>RIGHT-DRAG</b> orbit camera</span>
<span><b>SCROLL</b> zoom</span>
<span><b>← →</b> nudge selected gate</span>
</div>
<div id="toast" class="toast" role="status"></div>
<div id="countdown" class="countdown" hidden></div>
<div id="result" class="result" hidden>
<div class="result-card">
<div class="eyebrow">RACE REPORT</div>
<h2 id="resultTitle">FOUR-WAY TIE</h2>
<p id="resultText"></p>
<button id="resultButton" type="button">ADJUST THE STAGGER</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and puzzle state
// -------------------------------------------------------------------------
const TAU = Math.PI * 2;
const FINISH_ANGLE = 0;
const FAIR_MIN = 20;
const FAIR_MAX = 30;
const FAIR_TOLERANCE = 0.08;
const RUN_SPEED = 5.2;
const lanes = [
{ name: "EMBER", radius: 4.8, color: 0xf2685c, css: "#f2685c" },
{ name: "SUN", radius: 6.4, color: 0xefbd4d, css: "#efbd4d" },
{ name: "MINT", radius: 8.0, color: 0x39b9a5, css: "#39b9a5" },
{ name: "SKY", radius: 9.6, color: 0x579bd1, css: "#579bd1" }
];
const state = {
starts: [0.8, 2.1, 4.2, 5.5],
selected: 0,
mode: "edit",
countdown: 0,
raceElapsed: 0,
raceDuration: 6,
totalDistance: 1,
hintShown: false
};
const stage = document.querySelector("#stage");
const statusElement = document.querySelector("#status");
const spreadElement = document.querySelector("#spreadValue");
const meanElement = document.querySelector("#meanValue");
const laneRowsElement = document.querySelector("#laneRows");
const runButton = document.querySelector("#runButton");
const newButton = document.querySelector("#newButton");
const hintButton = document.querySelector("#hintButton");
const hintBox = document.querySelector("#hintBox");
const toastElement = document.querySelector("#toast");
const countdownElement = document.querySelector("#countdown");
const resultElement = document.querySelector("#result");
const resultTitle = document.querySelector("#resultTitle");
const resultText = document.querySelector("#resultText");
laneRowsElement.innerHTML = lanes.map((lane, index) => `
<button
class="lane ${index === 0 ? "active" : ""}"
style="--lane-color:${lane.css}"
data-lane="${index}"
type="button"
aria-label="Select ${lane.name} lane"
>
<span class="lane-dot"></span>
<span>
<span class="lane-name">${lane.name} / L${index + 1}</span>
<span class="lane-detail">RADIUS ${lane.radius.toFixed(1)} m</span>
</span>
<span class="lane-arc">
<strong data-arc>0.00 m</strong>
<small data-angle>0°</small>
</span>
<span class="progress"><i data-progress></i></span>
</button>
`).join("");
const laneElements = [...laneRowsElement.querySelectorAll(".lane")].map((element) => ({
element,
arc: element.querySelector("[data-arc]"),
angle: element.querySelector("[data-angle]"),
progress: element.querySelector("[data-progress]")
}));
function mod(value, divisor = TAU) {
return ((value % divisor) + divisor) % divisor;
}
function arcLength(laneIndex) {
const lane = lanes[laneIndex];
const sweep = mod(FINISH_ANGLE - state.starts[laneIndex]);
return lane.radius * sweep;
}
function getMetrics() {
const distances = lanes.map((_, index) => arcLength(index));
const mean = distances.reduce((sum, value) => sum + value, 0) / distances.length;
const spread = Math.max(...distances) - Math.min(...distances);
const fairRange = mean >= FAIR_MIN && mean <= FAIR_MAX;
const balanced = spread <= FAIR_TOLERANCE && fairRange;
return { distances, mean, spread, fairRange, balanced };
}
let toastTimer = 0;
function showToast(message, duration = 2300) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastElement.classList.remove("show"), duration);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9dce1);
scene.fog = new THREE.Fog(0xb9dce1, 33, 68);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
150
);
const orbit = {
yaw: 0.34,
pitch: 0.83,
distance: 27,
targetDistance: 27
};
function updateCamera() {
const horizontal = Math.cos(orbit.pitch) * orbit.distance;
camera.position.set(
Math.sin(orbit.yaw) * horizontal,
Math.sin(orbit.pitch) * orbit.distance,
Math.cos(orbit.yaw) * horizontal
);
camera.lookAt(0, 0.25, 0);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xeaf8ff, 0x66855f, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3cf, 3.2);
sun.position.set(-11, 20, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -20;
sun.shadow.camera.right = 20;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 48;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fillLight = new THREE.DirectionalLight(0x9acfe2, 0.8);
fillLight.position.set(13, 8, -12);
scene.add(fillLight);
const world = new THREE.Group();
scene.add(world);
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(33, 33, 0.7, 48),
new THREE.MeshStandardMaterial({
color: 0x8ebc78,
roughness: 1,
flatShading: true
})
);
ground.position.y = -0.48;
ground.receiveShadow = true;
world.add(ground);
const centerIsland = new THREE.Mesh(
new THREE.CylinderGeometry(3.45, 3.7, 0.48, 12),
new THREE.MeshStandardMaterial({
color: 0xd6c998,
roughness: 0.95,
flatShading: true
})
);
centerIsland.position.y = 0.02;
centerIsland.receiveShadow = true;
world.add(centerIsland);
const centerTop = new THREE.Mesh(
new THREE.CylinderGeometry(2.95, 3.15, 0.12, 12),
new THREE.MeshStandardMaterial({
color: 0xeee0b5,
roughness: 0.9,
flatShading: true
})
);
centerTop.position.y = 0.29;
centerTop.receiveShadow = true;
world.add(centerTop);
function createAnnulus(innerRadius, outerRadius, baseColor, segments = 48) {
const positions = [];
const colors = [];
const base = new THREE.Color(baseColor);
for (let segment = 0; segment < segments; segment++) {
const a0 = (segment / segments) * TAU;
const a1 = ((segment + 1) / segments) * TAU;
const shade = 0.84 + (segment % 2) * 0.09;
const color = base.clone().multiplyScalar(shade);
const inner0 = [innerRadius * Math.cos(a0), 0.08, innerRadius * Math.sin(a0)];
const inner1 = [innerRadius * Math.cos(a1), 0.08, innerRadius * Math.sin(a1)];
const outer0 = [outerRadius * Math.cos(a0), 0.08, outerRadius * Math.sin(a0)];
const outer1 = [outerRadius * Math.cos(a1), 0.08, outerRadius * Math.sin(a1)];
positions.push(...inner0, ...outer1, ...outer0);
positions.push(...inner0, ...inner1, ...outer1);
for (let i = 0; i < 6; i++) {
colors.push(color.r, color.g, color.b);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.92,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
}
const trackInner = 3.65;
const trackOuter = 10.3;
lanes.forEach((lane, index) => {
const laneWidth = 1.28;
const mesh = createAnnulus(
lane.radius - laneWidth / 2,
lane.radius + laneWidth / 2,
lane.color
);
world.add(mesh);
const boundary = new THREE.Mesh(
new THREE.TorusGeometry(lane.radius + laneWidth / 2, 0.045, 4, 64),
new THREE.MeshStandardMaterial({
color: 0xf8f2df,
roughness: 0.8,
flatShading: true
})
);
boundary.rotation.x = Math.PI / 2;
boundary.position.y = 0.16;
world.add(boundary);
});
const innerRail = new THREE.Mesh(
new THREE.TorusGeometry(trackInner, 0.09, 5, 64),
new THREE.MeshStandardMaterial({ color: 0xf7efd7, roughness: 0.8 })
);
innerRail.rotation.x = Math.PI / 2;
innerRail.position.y = 0.16;
world.add(innerRail);
// Short outer edge markers.
for (let i = 0; i < 40; i++) {
const angle = (i / 40) * TAU;
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.17, 0.15),
new THREE.MeshStandardMaterial({
color: i % 2 === 0 ? 0xf7efd7 : 0x657c71,
roughness: 0.9
})
);
marker.position.set(
Math.cos(angle) * (trackOuter + 0.22),
0.19,
Math.sin(angle) * (trackOuter + 0.22)
);
marker.rotation.y = -angle;
marker.castShadow = true;
world.add(marker);
}
// Finish stripe.
const finishGroup = new THREE.Group();
finishGroup.rotation.y = -FINISH_ANGLE;
world.add(finishGroup);
for (let i = 0; i < 26; i++) {
const x = trackInner + 0.2 + i * ((trackOuter - trackInner - 0.4) / 26);
const checker = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.07, 0.58),
new THREE.MeshStandardMaterial({
color: i % 2 === 0 ? 0xfffaf0 : 0x25363b,
roughness: 0.75
})
);
checker.position.set(x, 0.16, 0);
checker.receiveShadow = true;
finishGroup.add(checker);
}
function makeTextSprite(lines, accent = "#ffffff", scale = 3.8) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(23,37,43,0.90)";
context.fillRect(8, 8, 496, 144);
context.fillStyle = accent;
context.fillRect(8, 8, 13, 144);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#fffaf0";
lines.forEach((line, index) => {
context.font = index === 0
? "900 60px system-ui, sans-serif"
: "800 25px system-ui, sans-serif";
context.fillText(line, 266, lines.length === 1 ? 80 : index === 0 ? 61 : 112);
});
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale, scale * 0.3125, 1);
return sprite;
}
const finishSign = makeTextSprite(["FINISH"], "#efbd4d", 3.2);
finishSign.position.set(11.55, 1.25, 0);
world.add(finishSign);
const centerSign = makeTextSprite(["EQUAL", "ARC PUZZLE"], "#39b9a5", 3.5);
centerSign.position.set(0, 2.0, 0);
world.add(centerSign);
// -------------------------------------------------------------------------
// Low-poly scenery
// -------------------------------------------------------------------------
let scenerySeed = 8041;
function seededRandom() {
scenerySeed = (scenerySeed * 16807) % 2147483647;
return (scenerySeed - 1) / 2147483646;
}
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.18, 1.0, 5),
new THREE.MeshStandardMaterial({ color: 0x77543a, flatShading: true })
);
trunk.position.y = 0.25;
trunk.castShadow = true;
const crownA = new THREE.Mesh(
new THREE.ConeGeometry(0.8, 1.7, 7),
new THREE.MeshStandardMaterial({ color: 0x4f9367, flatShading: true })
);
crownA.position.y = 1.35;
crownA.castShadow = true;
const crownB = new THREE.Mesh(
new THREE.ConeGeometry(0.58, 1.25, 7),
new THREE.MeshStandardMaterial({ color: 0x65a874, flatShading: true })
);
crownB.position.y = 1.9;
crownB.castShadow = true;
tree.add(trunk, crownA, crownB);
world.add(tree);
}
for (let i = 0; i < 28; i++) {
const angle = (i / 28) * TAU + seededRandom() * 0.13;
const radius = 12.1 + seededRandom() * 6.8;
addTree(
Math.cos(angle) * radius,
Math.sin(angle) * radius,
0.72 + seededRandom() * 0.7
);
}
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * TAU + 0.25;
const radius = 2.35 + seededRandom() * 0.45;
const bush = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.42 + seededRandom() * 0.15, 0),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0x72aa6d : 0x5f9866,
flatShading: true
})
);
bush.position.set(
Math.cos(angle) * radius,
0.52,
Math.sin(angle) * radius
);
bush.castShadow = true;
world.add(bush);
}
for (let i = 0; i < 8; i++) {
const cloud = new THREE.Group();
const angle = (i / 8) * TAU + 0.3;
cloud.position.set(
Math.cos(angle) * (18 + seededRandom() * 6),
11 + seededRandom() * 5,
Math.sin(angle) * (18 + seededRandom() * 6)
);
for (let j = 0; j < 3; j++) {
const puff = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.3 + j * 0.15, 1),
new THREE.MeshStandardMaterial({
color: 0xf5f3e8,
roughness: 1,
flatShading: true
})
);
puff.position.set(j * 1.35, (j % 2) * 0.35, (j % 2) * 0.25);
puff.scale.y = 0.62;
cloud.add(puff);
}
world.add(cloud);
}
// -------------------------------------------------------------------------
// Starting gates, route lines, and runners
// -------------------------------------------------------------------------
const gateObjects = [];
const routeObjects = [];
const runnerObjects = [];
const pickObjects = [];
const invisiblePickMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
function createRunner(color) {
const group = new THREE.Group();
const rig = new THREE.Group();
group.add(rig);
const torsoMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.75,
flatShading: true
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x24373d,
roughness: 0.9,
flatShading: true
});
const skinMaterial = new THREE.MeshStandardMaterial({
color: 0xf1c59e,
roughness: 0.9,
flatShading: true
});
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.3, 0.62, 5),
torsoMaterial
);
torso.position.y = 0.78;
torso.castShadow = true;
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.23, 0),
skinMaterial
);
head.position.y = 1.27;
head.castShadow = true;
const visor = new THREE.Mesh(
new THREE.BoxGeometry(0.29, 0.09, 0.08),
darkMaterial
);
visor.position.set(0, 1.29, 0.2);
const leftArm = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.55, 0.13),
torsoMaterial
);
leftArm.position.set(-0.32, 0.8, 0);
leftArm.rotation.z = -0.18;
const rightArm = leftArm.clone();
rightArm.position.x = 0.32;
rightArm.rotation.z = 0.18;
const leftLeg = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.5, 0.15),
darkMaterial
);
leftLeg.position.set(-0.14, 0.28, 0);
const rightLeg = leftLeg.clone();
rightLeg.position.x = 0.14;
rig.add(torso, head, visor, leftArm, rightArm, leftLeg, rightLeg);
const shadow = new THREE.Mesh(
new THREE.CircleGeometry(0.38, 12),
new THREE.MeshBasicMaterial({
color: 0x1d3030,
transparent: true,
opacity: 0.15,
depthWrite: false
})
);
shadow.rotation.x = -Math.PI / 2;
shadow.position.y = 0.005;
group.add(shadow);
return {
group,
rig,
legs: [leftLeg, rightLeg],
arms: [leftArm, rightArm]
};
}
lanes.forEach((lane, index) => {
const gate = new THREE.Group();
const gateMaterial = new THREE.MeshStandardMaterial({
color: lane.color,
emissive: lane.color,
emissiveIntensity: 0.06,
roughness: 0.55,
flatShading: true
});
const crossbar = new THREE.Mesh(
new THREE.BoxGeometry(1.13, 0.13, 0.14),
gateMaterial
);
crossbar.position.y = 0.77;
crossbar.castShadow = true;
const leftPost = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.78, 0.14),
gateMaterial
);
leftPost.position.set(-0.56, 0.38, 0);
leftPost.castShadow = true;
const rightPost = leftPost.clone();
rightPost.position.x = 0.56;
const flag = new THREE.Mesh(
new THREE.ConeGeometry(0.18, 0.38, 4),
gateMaterial
);
flag.position.set(0, 1.02, 0);
flag.rotation.z = Math.PI;
flag.castShadow = true;
const pick = new THREE.Mesh(
new THREE.BoxGeometry(1.35, 1.2, 0.45),
invisiblePickMaterial
);
pick.position.y = 0.48;
pick.userData.laneIndex = index;
gate.add(crossbar, leftPost, rightPost, flag, pick);
world.add(gate);
pickObjects.push(pick);
const routeMaterial = new THREE.LineDashedMaterial({
color: lane.color,
transparent: true,
opacity: 0.1,
dashSize: 0.28,
gapSize: 0.16,
depthWrite: false
});
const route = new THREE.Line(new THREE.BufferGeometry(), routeMaterial);
world.add(route);
routeObjects.push(route);
const runner = createRunner(lane.color);
world.add(runner.group);
runnerObjects.push(runner);
gateObjects.push({ group: gate, material: gateMaterial });
});
function updateRoute(index) {
const lane = lanes[index];
const start = state.starts[index];
const distance = arcLength(index);
const sweep = distance / lane.radius;
const points = [];
const steps = Math.max(12, Math.ceil(sweep / 0.055));
for (let step = 0; step <= steps; step++) {
const angle = start + sweep * (step / steps);
points.push(new THREE.Vector3(
Math.cos(angle) * lane.radius,
0.23,
Math.sin(angle) * lane.radius
));
}
const oldGeometry = routeObjects[index].geometry;
routeObjects[index].geometry = new THREE.BufferGeometry().setFromPoints(points);
oldGeometry.dispose();
routeObjects[index].computeLineDistances();
}
function positionRunner(index, angle, runPhase = 0, isRunning = false) {
const lane = lanes[index];
const runner = runnerObjects[index];
runner.group.position.set(
Math.cos(angle) * lane.radius,
0.18,
Math.sin(angle) * lane.radius
);
runner.group.rotation.y = -angle;
const selectedScale = state.selected === index ? 1.08 : 1;
runner.group.scale.setScalar(selectedScale);
if (isRunning) {
const stride = Math.sin(runPhase * 12 + index * 1.7);
runner.legs[0].rotation.x = stride * 0.7;
runner.legs[1].rotation.x = -stride * 0.7;
runner.arms[0].rotation.x = -stride * 0.55;
runner.arms[1].rotation.x = stride * 0.55;
runner.rig.position.y = Math.abs(Math.sin(runPhase * 12)) * 0.07;
} else {
runner.legs.forEach((leg) => leg.rotation.x = 0);
runner.arms.forEach((arm) => arm.rotation.x = 0);
runner.rig.position.y = 0;
}
}
function refreshPositions() {
lanes.forEach((lane, index) => {
const start = state.starts[index];
gateObjects[index].group.position.set(
Math.cos(start) * lane.radius,
0.1,
Math.sin(start) * lane.radius
);
gateObjects[index].group.rotation.y = -start;
gateObjects[index].material.emissiveIntensity =
state.selected === index ? 0.38 : 0.05;
routeObjects[index].material.opacity =
state.selected === index ? 0.92 : 0.1;
updateRoute(index);
if (state.mode === "edit" || state.mode === "countdown") {
positionRunner(index, start);
}
});
}
function refreshUI() {
const metrics = getMetrics();
spreadElement.textContent = metrics.spread.toFixed(2);
meanElement.textContent = metrics.mean.toFixed(2);
laneElements.forEach((element, index) => {
const distance = metrics.distances[index];
const sweep = mod(FINISH_ANGLE - state.starts[index]);
const deviation = distance - metrics.mean;
element.arc.textContent = `${distance.toFixed(2)} m`;
element.angle.textContent =
`${(sweep * 180 / Math.PI).toFixed(0)}° · ${deviation >= 0 ? "+" : ""}${deviation.toFixed(2)}`;
element.element.classList.toggle("active", state.selected === index);
});
if (metrics.balanced) {
statusElement.textContent = "LOCKED · FAIR";
statusElement.classList.add("ready");
runButton.classList.add("ready");
runButton.textContent = "RUN THE FAIR RACE";
} else if (metrics.spread <= FAIR_TOLERANCE && !metrics.fairRange) {
statusElement.textContent = "WRONG LENGTH";
statusElement.classList.remove("ready");
runButton.classList.remove("ready");
runButton.textContent = "TEST THE RACE";
} else if (metrics.spread < 1.2) {
statusElement.textContent = "ALMOST FAIR";
statusElement.classList.remove("ready");
runButton.classList.remove("ready");
runButton.textContent = "TEST THE RACE";
} else {
statusElement.textContent = "UNBALANCED";
statusElement.classList.remove("ready");
runButton.classList.remove("ready");
runButton.textContent = "TEST THE RACE";
}
runButton.disabled = state.mode === "countdown" || state.mode === "racing";
}
function selectLane(index) {
state.selected = index;
refreshPositions();
refreshUI();
}
// -------------------------------------------------------------------------
// Pointer and keyboard interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planePoint = new THREE.Vector3();
let dragState = null;
let orbitState = null;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pointerWorldAngle(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (!raycaster.ray.intersectPlane(groundPlane, planePoint)) {
return null;
}
return mod(Math.atan2(planePoint.z, planePoint.x));
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
if (state.mode !== "edit") return;
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickObjects, false);
if (event.button === 2) {
orbitState = {
x: event.clientX,
y: event.clientY
};
renderer.domElement.setPointerCapture(event.pointerId);
return;
}
if (intersections.length) {
const laneIndex = intersections[0].object.userData.laneIndex;
const worldAngle = pointerWorldAngle(event);
if (worldAngle !== null) {
state.selected = laneIndex;
dragState = {
laneIndex,
offset: mod(state.starts[laneIndex] - worldAngle)
};
renderer.domElement.setPointerCapture(event.pointerId);
refreshPositions();
refreshUI();
}
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (orbitState) {
const deltaX = event.clientX - orbitState.x;
const deltaY = event.clientY - orbitState.y;
orbit.yaw -= deltaX * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + deltaY * 0.005,
0.46,
1.34
);
orbitState.x = event.clientX;
orbitState.y = event.clientY;
updateCamera();
return;
}
if (!dragState) return;
const worldAngle = pointerWorldAngle(event);
if (worldAngle === null) return;
state.starts[dragState.laneIndex] = mod(worldAngle + dragState.offset);
refreshPositions();
refreshUI();
});
function endPointer(event) {
if (dragState || orbitState) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
dragState = null;
orbitState = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.targetDistance = THREE.MathUtils.clamp(
orbit.targetDistance + event.deltaY * 0.018,
17,
39
);
},
{ passive: false }
);
laneRowsElement.addEventListener("click", (event) => {
const button = event.target.closest("[data-lane]");
if (!button) return;
selectLane(Number(button.dataset.lane));
});
window.addEventListener("keydown", (event) => {
if (state.mode !== "edit") return;
if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
const direction = event.key === "ArrowLeft" ? -1 : 1;
const amount = event.shiftKey ? 0.08 : 0.025;
state.starts[state.selected] = mod(
state.starts[state.selected] + direction * amount
);
refreshPositions();
refreshUI();
}
if (event.code === "Space") {
event.preventDefault();
startRace();
}
});
// -------------------------------------------------------------------------
// Game actions
// -------------------------------------------------------------------------
function newLayout() {
state.mode = "edit";
state.countdown = 0;
state.raceElapsed = 0;
resultElement.hidden = true;
countdownElement.hidden = true;
for (let i = 0; i < state.starts.length; i++) {
state.starts[i] = mod(Math.random() * TAU);
}
refreshPositions();
refreshUI();
showToast("New layout shuffled. Stagger all four gates.");
}
function toggleHint() {
state.hintShown = !state.hintShown;
hintBox.classList.toggle("show", state.hintShown);
hintButton.textContent = state.hintShown ? "HIDE HINT" : "HINT";
if (state.hintShown) {
showToast("Target idea: make every lane exactly 25.00 m.");
}
}
function startRace() {
if (state.mode === "countdown" || state.mode === "racing") return;
const metrics = getMetrics();
state.mode = "countdown";
state.countdown = 3.25;
state.raceElapsed = 0;
state.totalDistance = Math.max(0.01, ...metrics.distances);
state.raceDuration = Math.max(4, state.totalDistance / RUN_SPEED);
countdownElement.hidden = false;
countdownElement.classList.remove("go");
countdownElement.textContent = "3";
refreshPositions();
refreshUI();
}
function finishRace() {
const metrics = getMetrics();
const ranking = metrics.distances
.map((distance, index) => ({ distance, index }))
.sort((a, b) => a.distance - b.distance);
state.mode = "finished";
countdownElement.hidden = true;
if (metrics.balanced) {
resultTitle.textContent = "FOUR-WAY TIE";
resultTitle.style.color = "#25836f";
resultText.textContent =
`Every racer covered ${metrics.mean.toFixed(2)} m in the same time. ` +
"The staggered starts made the circular track perfectly fair.";
} else if (metrics.spread <= FAIR_TOLERANCE) {
resultTitle.textContent = "EQUAL, BUT TOO SHORT";
resultTitle.style.color = "#c08026";
resultText.textContent =
`The arcs match, but their common length is outside the ${FAIR_MIN}–${FAIR_MAX} m range. ` +
"Move the whole stagger farther around the circle.";
} else {
const winner = ranking[0];
const winnerTime = winner.distance / RUN_SPEED;
const last = ranking[ranking.length - 1];
resultTitle.textContent = `${lanes[winner.index].name} WINS`;
resultTitle.style.color = lanes[winner.index].css;
resultText.textContent =
`${lanes[winner.index].name} reached the line first at ${winnerTime.toFixed(2)} s. ` +
`${lanes[last.index].name} covered ${last.distance.toFixed(2)} m, producing a ` +
`${metrics.spread.toFixed(2)} m spread. Adjust the starting gates and try again.`;
}
resultElement.hidden = false;
refreshUI();
}
newButton.addEventListener("click", newLayout);
hintButton.addEventListener("click", toggleHint);
runButton.addEventListener("click", startRace);
document.querySelector("#resultButton").addEventListener("click", () => {
resultElement.hidden = true;
state.mode = "edit";
refreshPositions();
refreshUI();
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", onResize);
let previousTime = performance.now();
function animate(time) {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
orbit.distance += (orbit.targetDistance - orbit.distance) * 0.08;
updateCamera();
if (state.mode === "countdown") {
const before = Math.ceil(state.countdown);
state.countdown -= delta;
const after = Math.ceil(state.countdown);
if (after !== before && after > 0) {
countdownElement.textContent = String(after);
}
if (state.countdown <= 0) {
state.mode = "racing";
state.raceElapsed = 0;
countdownElement.textContent = "GO";
countdownElement.classList.add("go");
setTimeout(() => {
if (state.mode === "racing" || state.mode === "finished") {
countdownElement.hidden = true;
}
}, 450);
}
}
if (state.mode === "racing") {
state.raceElapsed += delta;
lanes.forEach((lane, index) => {
const distance = arcLength(index);
const traveled = Math.min(distance, state.raceElapsed * RUN_SPEED);
const angle = state.starts[index] + traveled / lane.radius;
positionRunner(index, angle, state.raceElapsed, traveled < distance - 0.001);
const progress = distance > 0
? Math.min(1, traveled / distance)
: 1;
laneElements[index].progress.style.width = `${progress * 100}%`;
});
if (state.raceElapsed >= state.raceDuration) {
finishRace();
}
}
if (state.mode === "edit" || state.mode === "countdown" || state.mode === "finished") {
laneElements.forEach((element) => {
if (state.mode !== "finished") {
element.progress.style.width = "0%";
}
});
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
refreshPositions();
refreshUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```