Prompt specification
Build or customize the Three.js 3D scene "Energy-budget delivery toy game" 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: Energy-budget delivery toy game
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/energy-budget-delivery-toy-game-x0400
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: energy-budget delivery toy game. Create a small map where wind-up cars deliver blocks to destinations; users choose winding levels and routes under a stated simplified distance budget, with no hidden refueling. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (energy-budget-delivery-toy-game-x0400):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Wind & Deliver — Distance Budget Toy Game</title>
<style>
:root {
--ink: #17343a;
--muted: #5e7478;
--paper: rgba(255, 252, 242, 0.92);
--line: rgba(23, 52, 58, 0.14);
--teal: #159f91;
--teal-dark: #08756d;
--orange: #ef7c57;
--danger: #c84d4d;
--shadow: 0 18px 45px rgba(38, 66, 65, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce9e5;
color: var(--ink);
font-family: Inter, ui-rounded, "SF Pro Rounded", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel,
button,
.clickable {
pointer-events: auto;
}
.topbar {
position: absolute;
top: 16px;
left: 18px;
right: 18px;
display: flex;
align-items: stretch;
gap: 12px;
pointer-events: none;
}
.brand,
.budget-card,
.top-actions {
pointer-events: auto;
background: var(--paper);
border: 1px solid rgba(255,255,255,0.75);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.brand {
min-width: 220px;
padding: 14px 18px;
border-radius: 18px;
}
.eyebrow {
color: var(--teal-dark);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.brand h1 {
margin: 3px 0 1px;
font-size: 24px;
line-height: 1;
letter-spacing: -0.04em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
}
.budget-card {
flex: 1;
max-width: 570px;
padding: 12px 16px;
border-radius: 18px;
}
.budget-top {
display: flex;
justify-content: space-between;
gap: 14px;
align-items: center;
}
.budget-number {
font-size: 25px;
line-height: 1;
font-weight: 900;
letter-spacing: -0.04em;
white-space: nowrap;
}
.budget-number small {
color: var(--muted);
font-size: 12px;
font-weight: 750;
letter-spacing: 0;
}
.rule {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.budget-bar {
height: 7px;
margin-top: 9px;
overflow: hidden;
border-radius: 99px;
background: #dfe7df;
}
#budgetFill {
height: 100%;
width: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #159f91, #62c8a7);
transition: width 0.35s ease, background 0.25s ease;
}
.top-actions {
margin-left: auto;
padding: 8px;
border-radius: 18px;
display: flex;
gap: 7px;
align-items: center;
}
.quiet-button,
.primary-button,
.small-button {
border: 0;
border-radius: 11px;
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease, background 0.15s ease;
}
.quiet-button {
padding: 10px 12px;
background: #edf1e9;
color: var(--ink);
font-size: 12px;
font-weight: 800;
}
.quiet-button:hover,
.small-button:hover {
transform: translateY(-1px);
background: #e2e9df;
}
.side-panel {
position: absolute;
top: 108px;
bottom: 18px;
overflow: auto;
padding: 16px;
border-radius: 20px;
background: var(--paper);
border: 1px solid rgba(255,255,255,0.75);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
scrollbar-width: thin;
}
#ordersPanel {
left: 18px;
width: 278px;
}
#controlPanel {
right: 18px;
width: 350px;
}
.section {
margin-bottom: 18px;
}
.section:last-child { margin-bottom: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title span:last-child {
letter-spacing: 0;
text-transform: none;
font-weight: 750;
}
.order-list,
.car-list,
.destination-list {
display: grid;
gap: 7px;
}
.order {
width: 100%;
padding: 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,0.58);
color: var(--ink);
text-align: left;
cursor: pointer;
transition: 0.15s ease;
}
.order:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(21,159,145,0.42);
background: white;
}
.order.selected {
border-color: var(--teal);
background: white;
box-shadow: 0 5px 16px rgba(21,159,145,0.12);
}
.order:disabled { cursor: default; }
.order-main {
display: flex;
align-items: center;
gap: 9px;
font-size: 12px;
font-weight: 850;
}
.swatch {
flex: 0 0 auto;
width: 18px;
height: 18px;
border-radius: 6px;
background: var(--swatch);
box-shadow: inset 0 -3px 0 rgba(0,0,0,0.12);
}
.order-meta {
margin: 5px 0 0 27px;
color: var(--muted);
font-size: 10px;
}
.status-pill {
margin-left: auto;
padding: 3px 6px;
border-radius: 99px;
background: #eef1ea;
color: var(--muted);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status-pill.done {
color: #17775f;
background: #d9f3e7;
}
.status-pill.transit {
color: #a65b19;
background: #ffecd2;
}
.car-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.car-chip,
.destination-chip {
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,0.62);
color: var(--ink);
cursor: pointer;
transition: 0.15s ease;
}
.car-chip {
padding: 9px;
text-align: left;
}
.car-chip:hover:not(:disabled),
.destination-chip:hover:not(:disabled) {
transform: translateY(-1px);
background: white;
}
.car-chip.selected {
border-color: var(--teal);
background: #eefaf5;
}
.car-chip:disabled,
.destination-chip:disabled {
opacity: 0.4;
cursor: default;
}
.car-name {
display: flex;
align-items: center;
gap: 7px;
font-size: 11px;
font-weight: 850;
}
.car-dot {
width: 12px;
height: 12px;
border-radius: 4px;
background: var(--swatch);
}
.car-spec {
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.wind-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
}
.wind-button {
padding: 9px 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,0.62);
color: var(--ink);
cursor: pointer;
transition: 0.15s ease;
}
.wind-button strong {
display: block;
font-size: 15px;
}
.wind-button span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
}
.wind-button.selected {
border-color: var(--teal);
background: var(--teal);
color: white;
box-shadow: 0 6px 16px rgba(21,159,145,0.24);
}
.wind-button.selected span { color: rgba(255,255,255,0.8); }
.destination-chip {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
font-size: 10px;
font-weight: 800;
}
.destination-chip .swatch {
width: 14px;
height: 14px;
border-radius: 50%;
}
.destination-chip.active {
border-color: var(--teal);
background: white;
}
.route-box {
padding: 12px;
border-radius: 14px;
background: #eef2ea;
border: 1px solid var(--line);
}
.route-path {
min-height: 32px;
margin-bottom: 9px;
color: var(--ink);
font-size: 10px;
font-weight: 800;
line-height: 1.55;
}
.route-numbers {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.metric {
padding: 8px;
border-radius: 10px;
background: rgba(255,255,255,0.72);
}
.metric label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric strong {
font-size: 16px;
}
.metric small {
color: var(--muted);
font-size: 9px;
}
.route-status {
margin-top: 9px;
padding: 8px 9px;
border-radius: 10px;
font-size: 10px;
font-weight: 800;
line-height: 1.35;
background: #fff3d6;
color: #8b5a18;
}
.route-status.ready {
background: #d9f3e7;
color: #176c56;
}
.route-status.bad {
background: #fde3df;
color: #9c3e3e;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 10px;
}
.small-button {
flex: 1;
padding: 9px 8px;
background: #e8eee5;
color: var(--ink);
font-size: 9px;
font-weight: 850;
}
.primary-button {
width: 100%;
margin-top: 9px;
padding: 12px;
background: var(--teal);
color: white;
font-size: 12px;
font-weight: 900;
box-shadow: 0 8px 20px rgba(21,159,145,0.23);
}
.primary-button:hover:not(:disabled) {
transform: translateY(-1px);
background: #108f83;
}
.primary-button:disabled {
cursor: not-allowed;
opacity: 0.42;
box-shadow: none;
}
.microcopy {
margin: 8px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.map-tip {
position: absolute;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
padding: 9px 14px;
border-radius: 99px;
background: rgba(23,52,58,0.82);
color: white;
box-shadow: 0 10px 30px rgba(23,52,58,0.18);
font-size: 10px;
font-weight: 750;
text-align: center;
backdrop-filter: blur(8px);
}
#toast {
position: absolute;
left: 50%;
top: 94px;
transform: translate(-50%, -10px);
max-width: min(460px, calc(100vw - 40px));
padding: 11px 16px;
border-radius: 12px;
background: #17343a;
color: white;
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 750;
text-align: center;
opacity: 0;
transition: 0.22s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error { background: #a84141; }
#toast.success { background: #147762; }
#win {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
background: rgba(25,55,56,0.24);
backdrop-filter: blur(7px);
}
#win.show { display: flex; }
.win-card {
width: min(390px, calc(100vw - 40px));
padding: 30px;
border-radius: 24px;
background: #fffdf4;
box-shadow: 0 30px 80px rgba(19,50,52,0.28);
text-align: center;
}
.win-medal {
width: 68px;
height: 68px;
margin: 0 auto 14px;
display: grid;
place-items: center;
border-radius: 22px;
background: #d9f3e7;
color: #138269;
font-size: 34px;
}
.win-card h2 {
margin: 5px 0 8px;
font-size: 29px;
letter-spacing: -0.04em;
}
.win-card p {
margin: 0 0 20px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
@media (max-width: 920px) {
.brand { min-width: 185px; }
.brand h1 { font-size: 20px; }
.rule { display: none; }
#ordersPanel { width: 240px; }
#controlPanel { width: 320px; }
}
@media (max-width: 700px) {
.topbar {
top: 8px;
left: 8px;
right: 8px;
gap: 7px;
}
.brand { min-width: 0; flex: 1; padding: 11px 12px; }
.brand h1 { font-size: 17px; }
.brand p { display: none; }
.budget-card { flex: 0 0 128px; padding: 10px; }
.budget-number { font-size: 20px; }
.top-actions { padding: 5px; }
.top-actions .quiet-button { padding: 8px; font-size: 0; }
.top-actions .quiet-button::first-letter { font-size: 13px; }
#ordersPanel {
top: 78px;
left: 8px;
right: 8px;
width: auto;
bottom: auto;
max-height: 165px;
padding: 11px;
}
#controlPanel {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
max-height: 48vh;
padding: 12px;
}
.map-tip { display: none; }
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="ui">
<div class="topbar">
<div class="brand">
<div class="eyebrow">A tiny delivery table</div>
<h1>Wind & Deliver</h1>
<p>Plan a route. Wind the toy. Respect the budget.</p>
</div>
<div class="budget-card">
<div class="budget-top">
<div>
<div class="eyebrow">Town distance budget</div>
<div class="budget-number"><span id="budgetRemaining">80</span> <small>wu remaining</small></div>
</div>
<div class="rule">
Each road edge is 5 wu. A route spends exactly its displayed distance.<br>
Wind level sets a hard trip limit of 6 × level wu. No refueling or hidden fees.
</div>
</div>
<div class="budget-bar"><div id="budgetFill"></div></div>
</div>
<div class="top-actions">
<button class="quiet-button" id="helpButton" title="How to play">?</button>
<button class="quiet-button" id="restartButton">↻ Restart</button>
</div>
</div>
<aside id="ordersPanel" class="side-panel">
<div class="section">
<div class="section-title"><span>Delivery orders</span><span id="orderProgress">0 / 5</span></div>
<div id="orders" class="order-list"></div>
</div>
<div class="section">
<div class="section-title"><span>Choose a car</span><span>One block each</span></div>
<div id="cars" class="car-list"></div>
</div>
<div class="section">
<div class="section-title"><span>Map notes</span><span>Drag to orbit</span></div>
<div class="microcopy">
Click the matching colored destination, then click cream junction pins to add or remove route bends.
The shortest road link is used between pinned stops. Scroll to zoom.
</div>
</div>
</aside>
<aside id="controlPanel" class="side-panel">
<div class="section">
<div class="section-title"><span>Selected delivery</span><span id="selectedJobName">—</span></div>
<div id="selectedJobCard" class="route-box"></div>
</div>
<div class="section">
<div class="section-title"><span>Winding level</span><span>Trip reach = 6 × level</span></div>
<div id="windButtons" class="wind-grid"></div>
</div>
<div class="section">
<div class="section-title"><span>Destination</span><span>Colored buildings</span></div>
<div id="destinations" class="destination-list"></div>
</div>
<div class="section">
<div class="section-title"><span>Route plan</span><span id="routeBadge">No route</span></div>
<div class="route-box">
<div id="routePath" class="route-path">Choose a delivery and destination.</div>
<div class="route-numbers">
<div class="metric">
<label>Route cost</label>
<strong id="routeCost">0</strong> <small>wu</small>
</div>
<div class="metric">
<label>Winding limit</label>
<strong id="windLimit">18</strong> <small>wu</small>
</div>
</div>
<div id="routeStatus" class="route-status">Choose a route.</div>
</div>
<div class="button-row">
<button id="shortestButton" class="small-button">Use shortest route</button>
<button id="clearRouteButton" class="small-button">Clear route</button>
</div>
<button id="dispatchButton" class="primary-button" disabled>Dispatch</button>
<p class="microcopy">
Distance uses graph edges only: 5 wu per road segment. The depot apron is one zero-cost staging node.
Delivered cars stay at their destination.
</p>
</div>
</aside>
<div id="toast"></div>
<div class="map-tip">Drag the map to orbit · Scroll to zoom · Click cream pins to bend the route</div>
<div id="win">
<div class="win-card">
<div class="win-medal">★</div>
<div class="eyebrow">Every block delivered</div>
<h2>Perfectly wound.</h2>
<p id="winText">The whole town received its blocks without exceeding the distance budget.</p>
<button class="primary-button" id="playAgainButton">Play again</button>
</div>
</div>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
const $ = s => document.querySelector(s);
const $$ = s => [...document.querySelectorAll(s)];
const EDGE = 5;
const TOWN_BUDGET = 80;
const BASE_WIND_REACH = 6;
const TOTAL_JOBS = 5;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9e5);
scene.fog = new THREE.Fog(0xdce9e5, 42, 78);
const renderer = new THREE.WebGLRenderer({ antialias: true });
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.08;
$('#scene').appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-20, 20, 12, -12, 0.1, 140);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let cameraTheta = 0.72;
let cameraPhi = 0.87;
let cameraZoom = 1;
function updateCamera() {
const radius = 42;
camera.position.set(
cameraTarget.x + radius * Math.sin(cameraPhi) * Math.cos(cameraTheta),
radius * Math.cos(cameraPhi),
cameraTarget.z + radius * Math.sin(cameraPhi) * Math.sin(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xf7fff8, 0x6e8d83, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4dd, 3.0);
sun.position.set(-15, 27, 13);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9d8ff, 0.75);
fill.position.set(18, 10, -20);
scene.add(fill);
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.02,
flatShading: true,
...options
});
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeLabel(text, color = "#17343a") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(ctx, 8, 10, 496, 108, 26);
ctx.fillStyle = "rgba(255,253,244,0.96)";
ctx.fill();
ctx.strokeStyle = "rgba(23,52,58,0.15)";
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "800 42px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(3.65, 0.91, 1);
return sprite;
}
const nodes = [];
const adjacency = Array.from({ length: 16 }, () => []);
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const id = row * 4 + col;
nodes.push(new THREE.Vector3(-7.5 + col * EDGE, 0, -7.5 + row * EDGE));
}
}
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const id = row * 4 + col;
if (col < 3) {
adjacency[id].push(id + 1);
adjacency[id + 1].push(id);
}
if (row < 3) {
adjacency[id].push(id + 4);
adjacency[id + 4].push(id);
}
}
}
const nodeName = id => id === 0 ? "Depot" : `J${String(id).padStart(2, "0")}`;
const destinations = [
{ id: "mint", name: "Mint Garden", node: 4, color: 0x50c69a, css: "#50c69a", offset: [-1.25, -1.25] },
{ id: "blue", name: "Blue Studio", node: 2, color: 0x4f83f7, css: "#4f83f7", offset: [1.25, -1.25] },
{ id: "gold", name: "Gold Market", node: 6, color: 0xf0bd4d, css: "#f0bd4d", offset: [1.25, 1.25] },
{ id: "coral", name: "Coral Workshop", node: 13, color: 0xef795f, css: "#ef795f", offset: [1.25, 1.25] },
{ id: "violet", name: "Violet Arcade", node: 9, color: 0x9b72e8, css: "#9b72e8", offset: [-1.25, -1.25] }
];
const jobs = destinations.map((d, i) => ({
...d,
destId: d.id,
title: ["Garden Cubes", "Studio Blocks", "Market Crates", "Workshop Parts", "Arcade Tiles"][i],
done: false,
inTransit: false
}));
const carDefinitions = [
{ name: "Pip", color: 0xef795f, css: "#ef795f" },
{ name: "Mox", color: 0x4f83f7, css: "#4f83f7" },
{ name: "Bibi", color: 0x50c69a, css: "#50c69a" },
{ name: "Tally", color: 0xf0bd4d, css: "#f0bd4d" },
{ name: "Otto", color: 0x9b72e8, css: "#9b72e8" }
];
const world = new THREE.Group();
scene.add(world);
const board = new THREE.Mesh(
new THREE.BoxGeometry(26, 0.7, 26),
standard(0xa8c99f)
);
board.position.y = -0.46;
board.receiveShadow = true;
world.add(board);
const underlay = new THREE.Mesh(
new THREE.PlaneGeometry(160, 160),
standard(0xcfe0d9)
);
underlay.rotation.x = -Math.PI / 2;
underlay.position.y = -0.83;
underlay.receiveShadow = true;
world.add(underlay);
const roadMaterial = standard(0x455b5d);
const roadStripeMaterial = standard(0xd9d8bc);
function addRoadSegment(a, b) {
const pa = nodes[a];
const pb = nodes[b];
const midpoint = pa.clone().add(pb).multiplyScalar(0.5);
const dx = pb.x - pa.x;
const dz = pb.z - pa.z;
const horizontal = Math.abs(dx) > 0;
const road = new THREE.Mesh(
new THREE.BoxGeometry(horizontal ? EDGE + 1.35 : 1.55, 0.12, horizontal ? 1.55 : EDGE + 1.35),
roadMaterial
);
road.position.set(midpoint.x, 0.015, midpoint.z);
road.receiveShadow = true;
world.add(road);
for (let t = -1.6; t <= 1.6; t += 1.05) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(horizontal ? 0.48 : 0.08, 0.035, horizontal ? 0.08 : 0.48),
roadStripeMaterial
);
dash.position.set(
midpoint.x + (horizontal ? t : 0),
0.095,
midpoint.z + (horizontal ? 0 : t)
);
world.add(dash);
}
}
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const id = row * 4 + col;
if (col < 3) addRoadSegment(id, id + 1);
if (row < 3) addRoadSegment(id, id + 4);
}
}
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.10, 0.14, 0.75, 6),
standard(0x8f6a47)
);
trunk.position.y = 0.35;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.57, 1.35, 7),
standard(new THREE.Color().setHSL(0.34 + Math.random() * 0.05, 0.30, 0.36 + Math.random() * 0.07))
);
crown.position.y = 1.2;
crown.castShadow = true;
group.add(crown);
group.scale.setScalar(scale);
world.add(group);
}
[
[-11.2,-9.7], [-8.9,-10.6], [-5.8,-10.5], [-2.4,-10.6], [1,-10.6], [4.2,-10.6], [7.5,-10.6], [10.9,-9.5],
[-11.3,-6.2], [-11.4,-2.7], [-11.2,2], [-11.4,6.3], [-10.8,9.8],
[11.2,-6.2], [11.4,-2.4], [11.2,2], [11.5,6.1], [10.8,9.9],
[-8.2,10.6], [-5.1,10.7], [-1.2,10.6], [2,10.6], [5.5,10.6], [8.8,10.4]
].forEach(([x,z], i) => addTree(x, z, 0.72 + (i % 3) * 0.12));
function addHill(x, z, color) {
const hill = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.8, 0),
standard(color)
);
hill.scale.set(1.4, 0.55, 1.0);
hill.position.set(x, 0.18, z);
hill.castShadow = true;
world.add(hill);
}
addHill(-5.3, -4.8, 0x86b789);
addHill(5.2, 0, 0x91bd82);
addHill(-5.2, 5.1, 0x7cae82);
addHill(5.3, 5.2, 0x8dbb83);
const clickTargets = [];
const destinationMeshes = [];
const destinationNodeRings = new Map();
function addBuilding(destination) {
const base = nodes[destination.node];
const bx = base.x + destination.offset[0];
const bz = base.z + destination.offset[1];
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(1.06, 1.14, 0.18, 12),
standard(destination.color)
);
pad.position.set(bx, 0.07, bz);
pad.receiveShadow = true;
pad.userData = { kind: "destination", destId: destination.id };
world.add(pad);
clickTargets.push(pad);
destinationMeshes.push(pad);
const foundation = new THREE.Mesh(
new THREE.BoxGeometry(1.55, 0.25, 1.55),
standard(0xe7dfc9)
);
foundation.position.set(bx, 0.23, bz);
foundation.receiveShadow = true;
world.add(foundation);
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 1.25, 1.25),
standard(0xfff8e8)
);
body.position.set(bx, 0.95, bz);
body.castShadow = true;
world.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1.04, 0.78, 4),
standard(destination.color)
);
roof.position.set(bx, 1.93, bz);
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
world.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.65, 0.08),
standard(destination.color)
);
door.position.set(bx, 0.72, bz + 0.67);
world.add(door);
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.33, 0.33, 0.07),
standard(0x9ed2db, { metalness: 0.05 })
);
windowMesh.position.set(bx + 0.34, 1.13, bz + 0.67);
world.add(windowMesh);
const label = makeLabel(destination.name, destination.css);
label.position.set(bx, 2.75, bz);
world.add(label);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.72, 0.095, 8, 28),
standard(destination.color, { emissive: destination.color, emissiveIntensity: 0.18 })
);
ring.rotation.x = Math.PI / 2;
ring.position.set(base.x, 0.18, base.z);
world.add(ring);
destinationNodeRings.set(destination.id, ring);
}
destinations.forEach(addBuilding);
const depot = new THREE.Group();
depot.position.set(-8.75, 0, -8.75);
world.add(depot);
const depotBody = new THREE.Mesh(
new THREE.BoxGeometry(1.55, 1.25, 1.4),
standard(0xf8f0dc)
);
depotBody.position.y = 0.7;
depotBody.castShadow = true;
depot.add(depotBody);
const depotRoof = new THREE.Mesh(
new THREE.ConeGeometry(1.18, 0.8, 4),
standard(0x245d62)
);
depotRoof.position.y = 1.7;
depotRoof.rotation.y = Math.PI / 4;
depotRoof.castShadow = true;
depot.add(depotRoof);
const depotLabel = makeLabel("TOY DEPOT", "#245d62");
depotLabel.position.set(-8.75, 2.55, -8.75);
world.add(depotLabel);
const junctionMarkers = [];
const destinationNodeIds = new Set(destinations.map(d => d.node));
for (let id = 1; id < nodes.length; id++) {
if (destinationNodeIds.has(id)) continue;
const marker = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.31, 0.16, 8),
standard(0xfff1c9)
);
marker.position.set(nodes[id].x, 0.16, nodes[id].z);
marker.userData = { kind: "junction", nodeId: id };
world.add(marker);
clickTargets.push(marker);
junctionMarkers.push(marker);
}
const routeGroup = new THREE.Group();
world.add(routeGroup);
const routeMaterial = standard(0x20bba6, {
emissive: 0x0b6f67,
emissiveIntensity: 0.2,
roughness: 0.5
});
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(1.05, 0.09, 8, 36),
standard(0x20bba6, { emissive: 0x20bba6, emissiveIntensity: 0.25 })
);
targetRing.rotation.x = Math.PI / 2;
targetRing.visible = false;
world.add(targetRing);
function createCar(definition, index) {
const group = new THREE.Group();
const bodyMat = standard(definition.color);
const darkMat = standard(0x294247);
const creamMat = standard(0xfff2d0);
const glassMat = standard(0x8dcbd0, { metalness: 0.06, roughness: 0.38 });
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.18, 0.46, 1.75),
bodyMat
);
body.position.y = 0.45;
body.castShadow = true;
group.add(body);
const hood = new THREE.Mesh(
new THREE.BoxGeometry(1.08, 0.2, 0.48),
bodyMat
);
hood.position.set(0, 0.73, 0.55);
hood.castShadow = true;
group.add(hood);
const cabin = new THREE.Mesh(
new THREE.BoxGeometry(0.83, 0.48, 0.75),
glassMat
);
cabin.position.set(0, 0.88, -0.18);
cabin.castShadow = true;
group.add(cabin);
const bumper = new THREE.Mesh(
new THREE.BoxGeometry(0.94, 0.14, 0.13),
creamMat
);
bumper.position.set(0, 0.38, 0.92);
group.add(bumper);
const wheelPivots = [];
for (const x of [-0.61, 0.61]) {
for (const z of [-0.55, 0.55]) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.26, z);
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.25, 0.25, 0.18, 10),
darkMat
);
wheel.rotation.z = Math.PI / 2;
wheel.castShadow = true;
pivot.add(wheel);
group.add(pivot);
wheelPivots.push(pivot);
}
}
const key = new THREE.Group();
key.position.set(0, 0.76, -1.0);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.07, 0.38, 8),
creamMat
);
stem.rotation.x = Math.PI / 2;
stem.position.z = -0.12;
key.add(stem);
for (const x of [-0.23, 0.23]) {
const loop = new THREE.Mesh(
new THREE.TorusGeometry(0.2, 0.055, 6, 12),
creamMat
);
loop.position.set(x, 0, -0.32);
key.add(loop);
}
group.add(key);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.86, 0.07, 8, 28),
standard(0xffffff, { emissive: 0xffffff, emissiveIntensity: 0.28 })
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.position.y = 0.08;
selectionRing.visible = false;
group.add(selectionRing);
const home = new THREE.Vector3(-10.25 + index * 1.12, 0, -9.85);
group.position.copy(home);
group.scale.setScalar(0.88);
world.add(group);
return {
...definition,
id: index,
group,
key,
wheelPivots,
selectionRing,
home,
done: false,
inTransit: false
};
}
const cars = carDefinitions.map(createCar);
function createCargo(job, index) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.56, 0.56, 0.56),
standard(job.color)
);
mesh.castShadow = true;
const home = new THREE.Vector3(-9.8 + index * 0.62, 0.32, -9.05);
mesh.position.copy(home);
world.add(mesh);
job.token = mesh;
job.tokenHome = home;
}
jobs.forEach(createCargo);
const state = {
budget: TOWN_BUDGET,
level: 3,
selectedJob: null,
selectedCar: null,
target: null,
waypoints: [],
route: null,
animation: null,
lastReadiness: null
};
function shortestPath(start, end) {
const distances = Array(nodes.length).fill(Infinity);
const previous = Array(nodes.length).fill(null);
const visited = new Set();
distances[start] = 0;
while (visited.size < nodes.length) {
let current = -1;
for (let i = 0; i < nodes.length; i++) {
if (!visited.has(i) && (current === -1 || distances[i] < distances[current])) {
current = i;
}
}
if (current === -1 || current === end) break;
visited.add(current);
for (const neighbor of adjacency[current]) {
const nextDistance = distances[current] + EDGE;
if (nextDistance < distances[neighbor]) {
distances[neighbor] = nextDistance;
previous[neighbor] = current;
}
}
}
const path = [];
let cursor = end;
while (cursor !== null) {
path.unshift(cursor);
if (cursor === start) break;
cursor = previous[cursor];
}
return path[0] === start ? path : [start, end];
}
function computeRoute() {
const destination = destinations.find(entry => entry.id === state.target);
if (!destination) {
state.route = null;
return;
}
const stops = [0, ...state.waypoints, destination.node];
const pathIds = [0];
for (let i = 0; i < stops.length - 1; i++) {
const leg = shortestPath(stops[i], stops[i + 1]);
for (let j = 1; j < leg.length; j++) pathIds.push(leg[j]);
}
const points = pathIds.map(id => new THREE.Vector3(nodes[id].x, 0.12, nodes[id].z));
const distance = Math.max(0, pathIds.length - 1) * EDGE;
state.route = {
pathIds,
points,
distance,
label: pathIds.map(nodeName).join(" → ")
};
}
function clearRouteGeometry() {
while (routeGroup.children.length) {
const child = routeGroup.children.pop();
child.geometry?.dispose();
}
}
function updateRouteGeometry() {
clearRouteGeometry();
if (!state.route) {
targetRing.visible = false;
return;
}
const points = state.route.points;
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const direction = b.clone().sub(a);
const length = direction.length();
const segment = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.095, length, 8),
routeMaterial
);
segment.position.copy(a).add(b).multiplyScalar(0.5);
segment.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
routeGroup.add(segment);
}
for (const point of points) {
const dot = new THREE.Mesh(
new THREE.SphereGeometry(0.17, 8, 6),
routeMaterial
);
dot.position.copy(point).setY(0.17);
routeGroup.add(dot);
}
const destination = destinations.find(d => d.id === state.target);
if (destination) {
targetRing.visible = true;
targetRing.position.set(nodes[destination.node].x, 0.24, nodes[destination.node].z);
targetRing.material.color.setHex(destination.color);
targetRing.material.emissive.setHex(destination.color);
}
for (const marker of junctionMarkers) {
const selected = state.waypoints.includes(marker.userData.nodeId);
marker.material.color.setHex(selected ? 0xf05d9d : 0xfff1c9);
marker.material.emissive.setHex(selected ? 0x6c123f : 0x000000);
marker.material.emissiveIntensity = selected ? 0.28 : 0;
marker.scale.setScalar(selected ? 1.28 : 1);
}
}
function tripLimit() {
return BASE_WIND_REACH * state.level;
}
function readiness() {
if (state.animation) {
return { ok: false, text: "The car is on the road.", tone: "" };
}
if (!state.selectedJob || !state.selectedCar) {
return { ok: false, text: "Choose a delivery and an unused car.", tone: "" };
}
if (!state.target || !state.route) {
return { ok: false, text: "Choose the matching colored destination.", tone: "" };
}
if (state.target !== state.selectedJob.destId) {
return { ok: false, text: "That destination does not match this block.", tone: "bad" };
}
if (state.route.distance > tripLimit()) {
return {
ok: false,
text: `Too far for wind ${state.level}: route is ${state.route.distance} wu, limit is ${tripLimit()} wu.`,
tone: "bad"
};
}
if (state.route.distance > state.budget) {
return {
ok: false,
text: `Town budget is short by ${state.route.distance - state.budget} wu.`,
tone: "bad"
};
}
return {
ok: true,
text: `Ready: ${state.route.distance} wu will be spent. No other cost is added.`,
tone: "ready"
};
}
function renderBudget() {
$('#budgetRemaining').textContent = state.budget;
$('#budgetFill').style.width = `${Math.max(0, state.budget / TOWN_BUDGET * 100)}%`;
$('#budgetFill').style.background = state.budget < 15
? "linear-gradient(90deg,#e46c54,#f1a45e)"
: "linear-gradient(90deg,#159f91,#62c8a7)";
}
function renderOrders() {
const complete = jobs.filter(j => j.done).length;
$('#orderProgress').textContent = `${complete} / ${TOTAL_JOBS}`;
$('#orders').innerHTML = jobs.map(job => {
const status = job.done ? "Delivered" : job.inTransit ? "On road" : `${shortestPath(0, job.node).length - 1} edges away`;
const statusClass = job.done ? "done" : job.inTransit ? "transit" : "";
return `
<button class="order ${state.selectedJob?.id === job.id ? "selected" : ""}"
data-job="${job.id}" ${job.done || job.inTransit || state.animation ? "disabled" : ""}>
<div class="order-main">
<span class="swatch" style="--swatch:${job.css}"></span>
<span>${job.title}</span>
<span class="status-pill ${statusClass}">${status}</span>
</div>
<div class="order-meta">Deliver to ${job.name}</div>
</button>`;
}).join("");
}
function renderCars() {
$('#cars').innerHTML = cars.map(car => `
<button class="car-chip ${state.selectedCar?.id === car.id ? "selected" : ""}"
data-car="${car.id}" ${car.done || car.inTransit || state.animation ? "disabled" : ""}>
<div class="car-name"><span class="car-dot" style="--swatch:${car.css}"></span>${car.name}</div>
<div class="car-spec">${car.done ? "Delivered" : car.inTransit ? "On road" : "Ready to wind"}</div>
</button>
`).join("");
}
function renderDestinations() {
$('#destinations').innerHTML = destinations.map(dest => {
const matching = state.selectedJob?.destId === dest.id;
return `
<button class="destination-chip ${state.target === dest.id ? "active" : ""}"
data-destination="${dest.id}" ${!matching || state.animation ? "disabled" : ""}>
<span class="swatch" style="--swatch:${dest.css}"></span>
${dest.name}
</button>`;
}).join("");
}
function renderWind() {
$('#windButtons').innerHTML = [1,2,3,4].map(level => `
<button class="wind-button ${state.level === level ? "selected" : ""}"
data-level="${level}" ${state.animation ? "disabled" : ""}>
<strong>${level}</strong><span>${BASE_WIND_REACH * level} wu</span>
</button>
`).join("");
}
function renderRoutePanel() {
const job = state.selectedJob;
const car = state.selectedCar;
const route = state.route;
const result = readiness();
state.lastReadiness = result;
if (job) {
$('#selectedJobName').textContent = job.title;
$('#selectedJobCard').innerHTML = `
<div class="order-main">
<span class="swatch" style="--swatch:${job.css}"></span>
<span>${job.title} → ${job.name}</span>
</div>
<div class="order-meta">${car ? `Using ${car.name}` : "Choose a car"}</div>`;
} else {
$('#selectedJobName').textContent = "—";
$('#selectedJobCard').innerHTML = `<div class="microcopy" style="margin:0">All available deliveries are shown in the order list.</div>`;
}
$('#routePath').textContent = route ? route.label : "Choose a delivery and destination.";
$('#routeCost').textContent = route ? route.distance : 0;
$('#windLimit').textContent = tripLimit();
$('#routeBadge').textContent = route ? `${route.distance} wu route` : "No route";
$('#routeStatus').textContent = result.text;
$('#routeStatus').className = `route-status ${result.tone || ""}`;
const button = $('#dispatchButton');
button.disabled = !result.ok;
button.textContent = result.ok
? `Dispatch ${state.selectedCar?.name || "car"} • spend ${route.distance} wu`
: "Dispatch unavailable";
cars.forEach(car => {
car.selectionRing.visible = car === state.selectedCar && !car.done && !car.inTransit;
});
}
function refresh() {
computeRoute();
updateRouteGeometry();
renderBudget();
renderOrders();
renderCars();
renderDestinations();
renderWind();
renderRoutePanel();
}
function attachSelectedCargo() {
if (!state.selectedJob || !state.selectedCar) return;
const token = state.selectedJob.token;
state.selectedCar.group.add(token);
token.position.set(0, 1.39, -0.12);
token.rotation.set(0, 0.4, 0);
token.scale.setScalar(1);
}
function detachCargoToDepot(job) {
if (!job || job.done) return;
world.add(job.token);
job.token.position.copy(job.tokenHome);
job.token.rotation.set(0, 0.25, 0);
}
function selectJob(id) {
if (state.animation) return;
const nextJob = jobs.find(j => j.id === id);
if (!nextJob || nextJob.done) return;
if (state.selectedJob && state.selectedJob !== nextJob) {
detachCargoToDepot(state.selectedJob);
}
state.selectedJob = nextJob;
state.target = nextJob.destId;
state.waypoints = [];
if (!state.selectedCar || state.selectedCar.done || state.selectedCar.inTransit) {
state.selectedCar = cars.find(c => !c.done && !c.inTransit) || null;
}
attachSelectedCargo();
refresh();
}
function selectCar(id) {
if (state.animation) return;
const nextCar = cars.find(c => c.id === Number(id));
if (!nextCar || nextCar.done || nextCar.inTransit) return;
if (state.selectedCar && state.selectedCar !== nextCar) {
detachCargoToDepot(state.selectedJob);
}
state.selectedCar = nextCar;
attachSelectedCargo();
refresh();
}
function selectDestination(id) {
if (state.animation) return;
const destination = destinations.find(d => d.id === id);
if (!destination) return;
if (!state.selectedJob || destination.id !== state.selectedJob.destId) {
showToast("Choose the destination matching the selected block.", "error");
return;
}
state.target = destination.id;
refresh();
}
function toggleWaypoint(id) {
if (state.animation) return;
if (state.waypoints.includes(id)) {
state.waypoints = state.waypoints.filter(v => v !== id);
} else {
state.waypoints.push(id);
}
refresh();
}
function showToast(message, tone = "") {
const toast = $('#toast');
toast.textContent = message;
toast.className = `show ${tone}`;
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => {
toast.className = tone;
}, 2600);
}
function dispatch() {
const result = readiness();
if (!result.ok || !state.route) return;
const car = state.selectedCar;
const job = state.selectedJob;
const route = state.route;
state.budget -= route.distance;
car.inTransit = true;
job.inTransit = true;
const motionPoints = [car.group.position.clone(), ...route.points.map(p => p.clone())];
const segments = [];
for (let i = 0; i < motionPoints.length - 1; i++) {
const from = motionPoints[i];
const to = motionPoints[i + 1];
const length = from.distanceTo(to);
if (length > 0.001) segments.push({ from, to, length });
}
state.animation = {
car,
job,
route,
segments,
segmentIndex: 0,
segmentProgress: 0,
speed: 4.2 + state.level * 1.45
};
showToast(`${car.name} is carrying ${job.title} to ${job.name}.`, "success");
refresh();
}
function finishDelivery(animation) {
const { car, job, route } = animation;
car.inTransit = false;
job.inTransit = false;
job.done = true;
car.done = true;
const destination = destinations.find(d => d.id === job.destId);
world.add(job.token);
job.token.position.set(
nodes[destination.node].x + destination.offset[0],
0.48,
nodes[destination.node].z + destination.offset[1]
);
job.token.rotation.set(0, 0.55, 0);
state.animation = null;
state.route = null;
state.target = null;
state.waypoints = [];
if (jobs.every(j => j.done)) {
state.selectedJob = null;
state.selectedCar = null;
refresh();
$('#winText').textContent =
`All five blocks arrived using ${TOWN_BUDGET - state.budget} of ${TOWN_BUDGET} wu, leaving ${state.budget} wu unused.`;
$('#win').classList.add("show");
} else {
const nextJob = jobs.find(j => !j.done);
const nextCar = cars.find(c => !c.done && !c.inTransit);
state.selectedCar = nextCar;
selectJob(nextJob.id);
}
showToast(`${job.title} delivered to ${destination.name}.`, "success");
}
function tickAnimation(dt) {
const animation = state.animation;
if (!animation) return;
let travel = animation.speed * dt;
while (travel > 0 && animation.segmentIndex < animation.segments.length) {
const segment = animation.segments[animation.segmentIndex];
const remaining = segment.length * (1 - animation.segmentProgress);
const step = Math.min(travel, remaining);
animation.segmentProgress += step / segment.length;
travel -= step;
const direction = segment.to.clone().sub(segment.from);
animation.car.group.rotation.y = Math.atan2(direction.x, direction.z);
animation.car.group.position.lerpVectors(segment.from, segment.to, animation.segmentProgress);
animation.car.group.position.y = 0.03 + Math.sin(animation.segmentProgress * Math.PI * 8) * 0.018;
animation.car.wheelPivots.forEach(w => w.rotation.x += step * 2.4);
animation.car.key.rotation.z -= step * 3.2;
if (animation.segmentProgress >= 0.99999) {
animation.segmentIndex++;
animation.segmentProgress = 0;
}
}
if (animation.segmentIndex >= animation.segments.length) {
finishDelivery(animation);
}
}
function resetGame() {
state.budget = TOWN_BUDGET;
state.level = 3;
state.selectedJob = null;
state.selectedCar = null;
state.target = null;
state.waypoints = [];
state.route = null;
state.animation = null;
jobs.forEach(job => {
job.done = false;
job.inTransit = false;
world.add(job.token);
job.token.position.copy(job.tokenHome);
job.token.rotation.set(0, 0.25, 0);
});
cars.forEach(car => {
car.done = false;
car.inTransit = false;
car.group.position.copy(car.home);
car.group.rotation.set(0, 0, 0);
car.key.rotation.set(0, 0, 0);
car.wheelPivots.forEach(w => w.rotation.set(0, 0, 0));
});
$('#win').classList.remove("show");
state.selectedCar = cars[0];
selectJob(jobs[0].id);
showToast("New delivery day. The town has 80 wu to work with.", "success");
}
$('#orders').addEventListener("click", event => {
const button = event.target.closest("[data-job]");
if (button) selectJob(button.dataset.job);
});
$('#cars').addEventListener("click", event => {
const button = event.target.closest("[data-car]");
if (button) selectCar(button.dataset.car);
});
$('#destinations').addEventListener("click", event => {
const button = event.target.closest("[data-destination]");
if (button) selectDestination(button.dataset.destination);
});
$('#windButtons').addEventListener("click", event => {
const button = event.target.closest("[data-level]");
if (!button || state.animation) return;
state.level = Number(button.dataset.level);
refresh();
});
$('#shortestButton').addEventListener("click", () => {
if (state.animation) return;
state.waypoints = [];
refresh();
showToast("Route pins cleared. The shortest road route is shown.");
});
$('#clearRouteButton').addEventListener("click", () => {
if (state.animation) return;
state.waypoints = [];
state.target = state.selectedJob ? state.selectedJob.destId : null;
refresh();
});
$('#dispatchButton').addEventListener("click", dispatch);
$('#restartButton').addEventListener("click", resetGame);
$('#playAgainButton').addEventListener("click", resetGame);
$('#helpButton').addEventListener("click", () => {
showToast("80 wu total · 5 wu per road edge · winding level gives 6 × level wu · no refueling or hidden costs.");
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerStart = null;
let pointerMoved = false;
renderer.domElement.addEventListener("pointerdown", event => {
pointerStart = { x: event.clientX, y: event.clientY };
pointerMoved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerStart) return;
const dx = event.clientX - pointerStart.x;
const dy = event.clientY - pointerStart.y;
if (Math.hypot(dx, dy) > 4) pointerMoved = true;
if (pointerMoved) {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.004, 0.45, 1.23);
updateCamera();
}
pointerStart.x = event.clientX;
pointerStart.y = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerMoved) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(clickTargets, false);
if (hits.length) {
const data = hits[0].object.userData;
if (data.kind === "destination") selectDestination(data.destId);
if (data.kind === "junction") toggleWaypoint(data.nodeId);
}
}
pointerStart = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerStart = null;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom - event.deltaY * 0.001, 0.65, 1.85);
updateCamera();
}, { passive: false });
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewSize = aspect < 1 ? 30 : 24;
camera.left = -viewSize * aspect / 2;
camera.right = viewSize * aspect / 2;
camera.top = viewSize / 2;
camera.bottom = -viewSize / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
tickAnimation(dt);
renderer.render(scene, camera);
}
animate();
state.selectedCar = cars[0];
selectJob(jobs[0].id);
showToast("Choose an order, set the winding, and dispatch. Cream pins bend the route.");
</script>
</body>
</html>
```