Prompt specification
Build or customize the Three.js 3D scene "Delivery-and-collection scheduling 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: Delivery-and-collection scheduling game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/delivery-and-collection-scheduling-game-x0524
Scene Description Prompt:
A voxel parcel-locker scheduling game with compartment sizes, occupied slots, arrivals, and pickups. Make one HTML file using Three.js from cdnjs.
Working Three.js Starter (delivery-and-collection-scheduling-game-x0524):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Block Depot — Voxel Parcel Scheduling</title>
<style>
:root {
--bg: #07111e;
--panel: rgba(10, 23, 38, 0.86);
--panel-solid: #0b1a2a;
--line: rgba(142, 190, 214, 0.18);
--text: #e9f5ff;
--muted: #87a0b5;
--cyan: #58f5cf;
--blue: #62a9ff;
--amber: #ffc766;
--red: #ff756f;
--purple: #bd91ff;
--shadow: 0 18px 55px rgba(0, 0, 0, 0.35);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
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;
cursor: grab;
touch-action: none;
}
#scene.dragging { cursor: grabbing; }
.topbar {
position: fixed;
z-index: 10;
top: 16px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 11px 15px 11px 11px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(8, 19, 32, 0.82);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
}
.brand-mark {
width: 38px;
height: 38px;
border-radius: 9px;
background:
linear-gradient(135deg, var(--cyan) 0 48%, transparent 48% 55%, var(--blue) 55% 100%);
box-shadow: inset 0 0 0 1px rgba(255,255,255,.25), 0 0 24px rgba(88,245,207,.18);
position: relative;
}
.brand-mark::after {
content: "";
position: absolute;
width: 10px;
height: 10px;
left: 8px;
top: 8px;
background: #081522;
box-shadow: 14px 14px 0 #081522, 14px 0 0 rgba(8,21,34,.55);
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1;
letter-spacing: .08em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 10px;
letter-spacing: .12em;
text-transform: uppercase;
}
.metrics {
display: flex;
gap: 8px;
pointer-events: auto;
}
.metric {
min-width: 98px;
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(8, 19, 32, 0.82);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
}
.metric-label {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
margin-bottom: 4px;
}
.metric-value {
font: 800 18px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .02em;
}
#clockMetric { border-color: rgba(88,245,207,.25); }
#clockMetric .metric-value { color: var(--cyan); }
#scoreMetric .metric-value { color: var(--amber); }
.panel {
position: fixed;
z-index: 9;
width: 286px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
overflow: hidden;
}
#arrivalPanel {
left: 18px;
top: 100px;
bottom: 104px;
display: flex;
flex-direction: column;
}
#pickupPanel {
right: 18px;
top: 100px;
bottom: 104px;
display: flex;
flex-direction: column;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 15px 15px 12px;
border-bottom: 1px solid var(--line);
}
.panel-head h2 {
margin: 0;
font-size: 12px;
letter-spacing: .12em;
text-transform: uppercase;
}
.count-pill {
padding: 4px 8px;
border-radius: 999px;
background: rgba(98,169,255,.12);
color: var(--blue);
font: 800 10px/1 ui-monospace, monospace;
}
.panel-scroll {
overflow-y: auto;
padding: 10px;
flex: 1;
scrollbar-width: thin;
scrollbar-color: #28435a transparent;
}
.panel-foot {
padding: 10px 14px 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.panel-foot strong { color: #c9dbea; }
.parcel-card,
.pickup-card {
width: 100%;
margin-bottom: 9px;
padding: 12px;
border: 1px solid rgba(135,160,181,.16);
border-radius: 12px;
background: rgba(17, 37, 56, .72);
color: var(--text);
text-align: left;
cursor: pointer;
transition: transform .15s ease, border-color .15s ease, background .15s ease;
}
.parcel-card:hover,
.pickup-card:hover {
transform: translateY(-1px);
border-color: rgba(98,169,255,.42);
background: rgba(23, 48, 71, .88);
}
.parcel-card.selected {
border-color: var(--cyan);
background: rgba(20, 72, 68, .72);
box-shadow: inset 3px 0 0 var(--cyan), 0 0 22px rgba(88,245,207,.08);
}
.pickup-card.ready {
border-color: rgba(255,117,111,.38);
background: rgba(83, 34, 39, .62);
}
.pickup-card.selected {
border-color: var(--amber);
box-shadow: inset 3px 0 0 var(--amber);
}
.card-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.parcel-id {
font: 800 12px/1 ui-monospace, monospace;
letter-spacing: .04em;
}
.customer {
margin-top: 7px;
color: #b8cad8;
font-size: 11px;
}
.size-chip {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 42px;
height: 25px;
padding: 0 7px;
border-radius: 7px;
background: rgba(0,0,0,.22);
border: 1px solid rgba(255,255,255,.1);
font: 800 11px/1 ui-monospace, monospace;
}
.parcel-dot {
width: 13px;
height: 13px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.24);
}
.card-note {
display: flex;
justify-content: space-between;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
letter-spacing: .07em;
text-transform: uppercase;
}
.selected-note { color: var(--cyan); }
.locate-button {
border: 0;
border-radius: 7px;
padding: 6px 8px;
background: var(--amber);
color: #211705;
font-size: 9px;
font-weight: 900;
letter-spacing: .08em;
cursor: pointer;
}
.locate-button:hover { filter: brightness(1.08); }
.empty-state {
min-height: 120px;
display: grid;
place-items: center;
padding: 22px;
color: var(--muted);
text-align: center;
font-size: 11px;
line-height: 1.6;
}
.empty-icon {
width: 34px;
height: 34px;
margin: 0 auto 10px;
border: 2px dashed #345069;
border-radius: 7px;
position: relative;
}
.empty-icon::after {
content: "";
position: absolute;
width: 8px;
height: 8px;
left: 11px;
top: 11px;
background: #345069;
border-radius: 2px;
}
.events {
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid var(--line);
}
.event-item {
display: grid;
grid-template-columns: 38px 1fr;
gap: 7px;
padding: 5px 0;
color: #9eb2c3;
font-size: 10px;
line-height: 1.35;
}
.event-time {
color: #5f7c92;
font-family: ui-monospace, monospace;
}
.event-item.good { color: #a9ead8; }
.event-item.bad { color: #ffaaa5; }
.toolbar {
position: fixed;
z-index: 12;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 7px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(8, 19, 32, .91);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.tool-button {
min-height: 36px;
padding: 0 12px;
border: 1px solid rgba(135,160,181,.18);
border-radius: 10px;
background: rgba(20, 39, 57, .8);
color: #c9dbea;
font-size: 10px;
font-weight: 800;
letter-spacing: .06em;
cursor: pointer;
transition: background .15s, color .15s, transform .15s;
}
.tool-button:hover {
color: white;
background: #19354d;
transform: translateY(-1px);
}
.tool-button.primary {
color: #06251f;
background: var(--cyan);
border-color: var(--cyan);
min-width: 90px;
}
.tool-button.primary:hover { background: #83ffe3; }
.tool-button:disabled {
opacity: .4;
cursor: default;
transform: none;
}
.speed-group {
display: flex;
padding: 3px;
border: 1px solid rgba(135,160,181,.16);
border-radius: 10px;
background: rgba(0,0,0,.16);
}
.speed-button {
border: 0;
border-radius: 7px;
padding: 7px 9px;
background: transparent;
color: var(--muted);
font: 800 10px/1 ui-monospace, monospace;
cursor: pointer;
}
.speed-button.active {
color: #09271f;
background: var(--cyan);
}
.camera-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 78px;
transform: translateX(-50%);
color: rgba(177,200,218,.55);
font-size: 9px;
letter-spacing: .08em;
text-transform: uppercase;
pointer-events: none;
white-space: nowrap;
}
.toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 105px;
max-width: min(460px, 80vw);
transform: translate(-50%, 12px);
padding: 11px 16px;
border: 1px solid rgba(88,245,207,.35);
border-radius: 11px;
background: rgba(7, 26, 34, .96);
color: #d9fff6;
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 700;
opacity: 0;
pointer-events: none;
transition: opacity .2s, transform .2s;
text-align: center;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.bad {
border-color: rgba(255,117,111,.5);
background: rgba(54, 20, 25, .97);
color: #ffd2cf;
}
.toast.warn {
border-color: rgba(255,199,102,.5);
background: rgba(51, 38, 16, .97);
color: #ffe8bd;
}
.modal {
position: fixed;
z-index: 50;
inset: 0;
display: none;
place-items: center;
padding: 22px;
background: rgba(2, 8, 15, .67);
backdrop-filter: blur(10px);
}
.modal.show { display: grid; }
.modal-card {
width: min(620px, 94vw);
padding: 29px;
border: 1px solid rgba(88,245,207,.26);
border-radius: 22px;
background:
radial-gradient(circle at 85% 5%, rgba(98,169,255,.13), transparent 35%),
linear-gradient(145deg, rgba(13,31,48,.98), rgba(7,17,29,.98));
box-shadow: 0 35px 100px rgba(0,0,0,.58);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 900;
letter-spacing: .18em;
text-transform: uppercase;
}
.modal h2 {
margin: 10px 0 12px;
font-size: clamp(28px, 5vw, 43px);
line-height: 1.02;
letter-spacing: -.04em;
}
.modal p {
color: #a9bdcd;
font-size: 13px;
line-height: 1.65;
}
.rules {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 9px;
margin: 20px 0;
}
.rule {
padding: 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(0,0,0,.15);
}
.rule b {
display: block;
margin-bottom: 5px;
color: #eaf7ff;
font-size: 12px;
}
.rule span {
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.modal-actions {
display: flex;
align-items: center;
gap: 10px;
margin-top: 20px;
}
.modal-primary {
min-height: 44px;
padding: 0 22px;
border: 0;
border-radius: 11px;
background: var(--cyan);
color: #06251f;
font-weight: 900;
letter-spacing: .04em;
cursor: pointer;
}
.modal-primary:hover { filter: brightness(1.08); }
.modal-secondary {
min-height: 44px;
padding: 0 15px;
border: 1px solid var(--line);
border-radius: 11px;
background: transparent;
color: #a8bdcd;
cursor: pointer;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 9px;
margin: 20px 0;
}
.summary-stat {
padding: 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(0,0,0,.16);
}
.summary-stat strong {
display: block;
color: var(--cyan);
font: 900 23px/1 ui-monospace, monospace;
}
.summary-stat span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
letter-spacing: .08em;
text-transform: uppercase;
}
@media (max-width: 1000px) {
.panel { width: 244px; }
.metric { min-width: 82px; }
.brand p { display: none; }
}
@media (max-width: 720px) {
.topbar { top: 8px; left: 8px; right: 8px; }
.brand { padding: 8px; }
.brand h1 { font-size: 13px; }
.brand-mark { width: 32px; height: 32px; }
.metrics { gap: 4px; }
.metric { min-width: 61px; padding: 8px; }
.metric-label { font-size: 7px; }
.metric-value { font-size: 13px; }
.metric:nth-child(4) { display: none; }
.panel {
top: auto;
bottom: 78px;
width: calc(50vw - 13px);
height: 220px;
}
#arrivalPanel { left: 8px; }
#pickupPanel { right: 8px; }
.panel-foot { display: none; }
.toolbar { bottom: 8px; max-width: 96vw; flex-wrap: wrap; justify-content: center; }
.tool-button { padding: 0 8px; min-height: 32px; }
.camera-hint { display: none; }
.rules { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>BLOCK DEPOT</h1>
<p>Parcel control · Shift 01</p>
</div>
</div>
<div class="metrics">
<div class="metric" id="clockMetric">
<span class="metric-label">Depot time</span>
<span class="metric-value" id="clockMetricValue">09:00</span>
</div>
<div class="metric">
<span class="metric-label">Handoffs</span>
<span class="metric-value" id="deliveryMetric">0 / 10</span>
</div>
<div class="metric" id="scoreMetric">
<span class="metric-label">Score</span>
<span class="metric-value" id="scoreMetricValue">0000</span>
</div>
<div class="metric">
<span class="metric-label">Occupied slots</span>
<span class="metric-value" id="fillMetric">0 / 0</span>
</div>
</div>
</header>
<aside class="panel" id="arrivalPanel">
<div class="panel-head">
<h2>Incoming Parcels</h2>
<span class="count-pill" id="queueCount">0 / 6</span>
</div>
<div class="panel-scroll" id="arrivalList"></div>
<div class="panel-foot">
<strong>1.</strong> Select a parcel, then click a compatible locker.
<br />
<strong>R</strong> rotates the selected parcel.
</div>
</aside>
<aside class="panel" id="pickupPanel">
<div class="panel-head">
<h2>Pickup Requests</h2>
<span class="count-pill" id="pickupCount">0</span>
</div>
<div class="panel-scroll" id="pickupList"></div>
<div class="panel-foot">
<strong>2.</strong> Open the glowing locker when a customer arrives.
<br />
Reach <strong>10 handoffs</strong> before the shift ends.
</div>
</aside>
<div class="camera-hint">Drag to orbit · Wheel to zoom · Right-drag to pan · R to rotate</div>
<div class="toolbar">
<button class="tool-button primary" id="pauseButton">Pause</button>
<div class="speed-group" aria-label="Game speed">
<button class="speed-button active" data-speed="1">1×</button>
<button class="speed-button" data-speed="2">2×</button>
</div>
<button class="tool-button" id="rotateButton" title="Rotate selected parcel">Rotate · R</button>
<button class="tool-button" id="cameraButton">Reset View</button>
<button class="tool-button" id="guideButton">How to Play</button>
</div>
<div class="toast" id="toast"></div>
<div class="modal" id="modal"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const arrivalList = document.getElementById("arrivalList");
const pickupList = document.getElementById("pickupList");
const queueCount = document.getElementById("queueCount");
const pickupCount = document.getElementById("pickupCount");
const clockMetricValue = document.getElementById("clockMetricValue");
const deliveryMetric = document.getElementById("deliveryMetric");
const scoreMetricValue = document.getElementById("scoreMetricValue");
const fillMetric = document.getElementById("fillMetric");
const pauseButton = document.getElementById("pauseButton");
const rotateButton = document.getElementById("rotateButton");
const toastElement = document.getElementById("toast");
const modal = document.getElementById("modal");
const SHIFT_LENGTH = 240;
const TARGET = 10;
const MAX_QUEUE = 6;
const SLOT = 0.36;
const COLORS = [0x58f5cf, 0x62a9ff, 0xffc766, 0xff756f, 0xbd91ff, 0xf58ecb, 0x9ee36f];
const CUSTOMERS = [
"Mina Chen", "Owen Brooks", "Pixel Arcade", "North Studio", "Rae Patel",
"Cobalt Books", "Luma Market", "Jules Rivera", "Moss Cafe", "Orbit Labs",
"Tess Morgan", "Harbor Deli", "Violet Works", "Keen Supply"
];
const state = {
running: false,
ended: false,
modalMode: null,
modalReturnRunning: false,
elapsed: 0,
speed: 1,
score: 0,
delivered: 0,
misses: 0,
combo: 0,
targetHit: false,
arrivals: [],
requests: [],
parcels: [],
selectedArrivalId: null,
selectedRequestId: null,
nextArrival: 10,
nextId: 101,
events: []
};
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.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111e);
scene.fog = new THREE.Fog(0x07111e, 11, 25);
const camera = new THREE.PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.1, 60);
const cameraState = {
target: new THREE.Vector3(0, 2.1, 0),
yaw: 0.20,
pitch: 0.34,
radius: 11.8
};
scene.add(new THREE.HemisphereLight(0x9ccfff, 0x172030, 1.8));
const keyLight = new THREE.DirectionalLight(0xd8f6ff, 3.2);
keyLight.position.set(4, 8, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x46f5d0, 35, 12, 2);
cyanLight.position.set(-5, 3.8, 3);
scene.add(cyanLight);
const blueLight = new THREE.PointLight(0x4d91ff, 28, 11, 2);
blueLight.position.set(5, 2.2, 2.5);
scene.add(blueLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({ color: 0x091523, roughness: 0.92, metalness: 0.05 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.12;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x21415a, 0x142b3e);
grid.position.y = -0.105;
grid.material.transparent = true;
grid.material.opacity = 0.55;
scene.add(grid);
const wall = new THREE.Mesh(
new THREE.BoxGeometry(14, 8, 0.35),
new THREE.MeshStandardMaterial({ color: 0x0a1725, roughness: 0.82, metalness: 0.12 })
);
wall.position.set(0, 3.4, -1.0);
wall.receiveShadow = true;
scene.add(wall);
const wallInset = new THREE.Mesh(
new THREE.BoxGeometry(8.4, 5.8, 0.08),
new THREE.MeshStandardMaterial({
color: 0x0d2032,
emissive: 0x06121d,
emissiveIntensity: 0.35,
roughness: 0.7,
metalness: 0.25
})
);
wallInset.position.set(0, 2.5, -0.77);
wallInset.receiveShadow = true;
scene.add(wallInset);
function box(parent, width, height, depth, material, x = 0, y = 0, z = 0, shadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTextTexture(lines, options = {}) {
const textureCanvas = document.createElement("canvas");
textureCanvas.width = options.width || 1024;
textureCanvas.height = options.height || 256;
const context = textureCanvas.getContext("2d");
context.clearRect(0, 0, textureCanvas.width, textureCanvas.height);
context.fillStyle = options.background || "rgba(7,18,30,.94)";
context.fillRect(0, 0, textureCanvas.width, textureCanvas.height);
context.strokeStyle = options.border || "#58f5cf";
context.lineWidth = options.borderWidth || 8;
context.strokeRect(8, 8, textureCanvas.width - 16, textureCanvas.height - 16);
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = options.color || "#e9f5ff";
context.font = options.font || "900 80px ui-monospace, monospace";
context.fillText(lines[0], textureCanvas.width / 2, lines[1] ? 92 : 128);
if (lines[1]) {
context.fillStyle = options.secondaryColor || "#79a1bb";
context.font = options.secondaryFont || "700 30px ui-monospace, monospace";
context.fillText(lines[1], textureCanvas.width / 2, 178);
}
const texture = new THREE.CanvasTexture(textureCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(5.8, 0.7),
new THREE.MeshBasicMaterial({
map: makeTextTexture(["BLOCK DEPOT // 24", "PARCEL CONTROL TERMINAL"], {
font: "900 66px ui-monospace, monospace",
secondaryFont: "700 24px ui-monospace, monospace"
}),
transparent: true
})
);
sign.position.set(0, 4.47, -0.68);
scene.add(sign);
const locker = new THREE.Group();
locker.position.z = -0.12;
scene.add(locker);
const frameMaterial = new THREE.MeshStandardMaterial({
color: 0x25445b,
emissive: 0x07141f,
emissiveIntensity: 0.55,
roughness: 0.42,
metalness: 0.65
});
box(locker, 0.14, 4.95, 0.42, frameMaterial, -3.34, 2.18, -0.28);
box(locker, 0.14, 4.95, 0.42, frameMaterial, 3.34, 2.18, -0.28);
box(locker, 6.82, 0.14, 0.42, frameMaterial, 0, 4.52, -0.28);
box(locker, 6.82, 0.14, 0.42, frameMaterial, 0, -0.18, -0.28);
const layout = [
["A1", 2, 2], ["A2", 2, 3], ["A3", 3, 2], ["A4", 3, 3],
["B1", 1, 2], ["B2", 2, 2], ["B3", 3, 2], ["B4", 2, 3],
["C1", 2, 1], ["C2", 1, 3], ["C3", 2, 2], ["C4", 3, 3]
];
const compartments = [];
const hitMeshes = [];
const totalSlots = layout.reduce((sum, item) => sum + item[1] * item[2], 0);
function createCompartment(def, index) {
const [id, width, height] = def;
const column = index % 4;
const row = Math.floor(index / 4);
const group = new THREE.Group();
group.position.set((column - 1.5) * 1.66, 3.55 - row * 1.45, 0);
locker.add(group);
const backMaterial = new THREE.MeshStandardMaterial({
color: 0x0c1a29,
roughness: 0.65,
metalness: 0.32
});
box(group, 1.46, 1.13, 0.18, backMaterial, 0, 0, -0.46);
const localFrameMaterial = new THREE.MeshStandardMaterial({
color: 0x285069,
emissive: 0x07141f,
emissiveIntensity: 0.6,
roughness: 0.38,
metalness: 0.62
});
const frameParts = [
box(group, 1.48, 0.055, 0.07, localFrameMaterial, 0, 0.55, 0.31, false),
box(group, 1.48, 0.055, 0.07, localFrameMaterial, 0, -0.55, 0.31, false),
box(group, 0.055, 1.15, 0.07, localFrameMaterial, -0.715, 0, 0.31, false),
box(group, 0.055, 1.15, 0.07, localFrameMaterial, 0.715, 0, 0.31, false)
];
const cellMaterial = new THREE.MeshStandardMaterial({
color: 0x11293b,
emissive: 0x06131e,
emissiveIntensity: 0.55,
roughness: 0.8,
metalness: 0.12
});
for (let rowIndex = 0; rowIndex < height; rowIndex++) {
for (let columnIndex = 0; columnIndex < width; columnIndex++) {
const x = (columnIndex - (width - 1) / 2) * SLOT;
const y = ((height - 1) / 2 - rowIndex) * SLOT;
box(group, 0.315, 0.315, 0.025, cellMaterial, x, y, -0.345, false);
}
}
const doorPivot = new THREE.Group();
doorPivot.position.set(-0.69, 0, 0.34);
group.add(doorPivot);
const glassMaterial = new THREE.MeshStandardMaterial({
color: 0x80caff,
transparent: true,
opacity: 0.085,
roughness: 0.15,
metalness: 0.05,
side: THREE.DoubleSide,
depthWrite: false
});
const glass = new THREE.Mesh(new THREE.PlaneGeometry(1.36, 1.06), glassMaterial);
glass.position.x = 0.69;
doorPivot.add(glass);
const handleMaterial = new THREE.MeshStandardMaterial({
color: 0x8ba9bd,
roughness: 0.3,
metalness: 0.8
});
box(doorPivot, 0.045, 0.24, 0.045, handleMaterial, 1.20, 0, 0.03, false);
const statusDot = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.075, 0.035),
new THREE.MeshBasicMaterial({ color: 0x58f5cf })
);
statusDot.position.set(0.61, 0.46, 0.37);
group.add(statusDot);
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 640;
labelCanvas.height = 112;
const labelContext = labelCanvas.getContext("2d");
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const label = new THREE.Mesh(
new THREE.PlaneGeometry(1.30, 0.228),
new THREE.MeshBasicMaterial({ map: labelTexture, transparent: true })
);
label.position.set(0, -0.64, 0.34);
group.add(label);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
const hit = new THREE.Mesh(new THREE.BoxGeometry(1.5, 1.18, 0.85), hitMaterial);
hit.position.set(0, 0, -0.02);
group.add(hit);
const compartment = {
id,
width,
height,
group,
frameMaterial,
frameParts,
doorPivot,
statusDot,
labelCanvas,
labelContext,
labelTexture,
occupancy: Array.from({ length: height }, () => Array(width).fill(false)),
occupied: 0,
doorOpenUntil: 0
};
hit.userData.compartment = compartment;
hitMeshes.push(hit);
compartments.push(compartment);
updateCompartmentLabel(compartment);
}
layout.forEach(createCompartment);
function updateCompartmentLabel(compartment) {
const context = compartment.labelContext;
context.clearRect(0, 0, 640, 112);
context.fillStyle = "rgba(6,17,29,.96)";
context.fillRect(0, 0, 640, 112);
context.strokeStyle = "rgba(88,245,207,.35)";
context.lineWidth = 4;
context.strokeRect(3, 3, 634, 106);
context.textBaseline = "middle";
context.textAlign = "left";
context.fillStyle = "#eaf7ff";
context.font = "900 34px ui-monospace, monospace";
context.fillText(compartment.id, 22, 54);
context.fillStyle = "#79a1bb";
context.font = "800 27px ui-monospace, monospace";
context.fillText(`${compartment.width}×${compartment.height}`, 155, 54);
context.textAlign = "right";
context.fillStyle = compartment.occupied ? "#62a9ff" : "#58f5cf";
context.fillText(`${compartment.occupied}/${compartment.width * compartment.height}`, 616, 54);
compartment.labelTexture.needsUpdate = true;
}
function makeVoxelParcel(compartment, arrival, x, y, width, height) {
const group = new THREE.Group();
compartment.group.add(group);
const baseColor = new THREE.Color(arrival.color);
const materials = [];
const parcelBlocks = [];
for (let rowIndex = 0; rowIndex < height; rowIndex++) {
for (let columnIndex = 0; columnIndex < width; columnIndex++) {
const blockX = (x + columnIndex - (compartment.width - 1) / 2) * SLOT;
const blockY = ((compartment.height - 1) / 2 - (y + rowIndex)) * SLOT;
const blockColor = baseColor.clone().offsetHSL(
((rowIndex + columnIndex) % 2) * 0.012,
0,
((rowIndex + columnIndex) % 2) * 0.045
);
const material = new THREE.MeshStandardMaterial({
color: blockColor,
emissive: blockColor,
emissiveIntensity: 0.055,
roughness: 0.58,
metalness: 0.08
});
materials.push(material);
const block = box(group, 0.313, 0.313, 0.26, material, blockX, blockY, -0.13);
parcelBlocks.push(block);
}
}
const centerX = (x + (width - 1) / 2 - (compartment.width - 1) / 2) * SLOT;
const centerY = ((compartment.height - 1) / 2 - (y + (height - 1) / 2)) * SLOT;
const tapeMaterial = new THREE.MeshStandardMaterial({
color: 0xf0dfb2,
roughness: 0.85
});
box(group, width * 0.313 + 0.012, 0.024, 0.065, tapeMaterial, centerX, centerY + 0.169, -0.13, false);
const stickerMaterial = new THREE.MeshStandardMaterial({
color: 0xf4fbff,
roughness: 0.7
});
const firstX = (x - (compartment.width - 1) / 2) * SLOT;
const firstY = ((compartment.height - 1) / 2 - y) * SLOT;
box(group, 0.12, 0.075, 0.018, stickerMaterial, firstX + 0.07, firstY - 0.06, 0.011, false);
return {
id: arrival.id,
code: arrival.code,
customer: arrival.customer,
color: arrival.color,
compartment,
x,
y,
width,
height,
due: state.elapsed + 26 + Math.random() * 30,
requested: false,
group,
materials
};
}
function findSpot(compartment, width, height) {
for (let y = 0; y <= compartment.height - height; y++) {
for (let x = 0; x <= compartment.width - width; x++) {
let clear = true;
for (let rowIndex = 0; rowIndex < height; rowIndex++) {
for (let columnIndex = 0; columnIndex < width; columnIndex++) {
if (compartment.occupancy[y + rowIndex][x + columnIndex]) {
clear = false;
}
}
}
if (clear) return { x, y };
}
}
return null;
}
function arrivalDimensions(arrival) {
return arrival.rotated
? { width: arrival.height, height: arrival.width }
: { width: arrival.width, height: arrival.height };
}
function selectedArrival() {
return state.arrivals.find(arrival => arrival.id === state.selectedArrivalId) || null;
}
function selectedRequest() {
return state.requests.find(request => request.id === state.selectedRequestId) || null;
}
function compartmentHasRequest(compartment) {
return state.requests.find(request => request.compartment === compartment) || null;
}
function spawnArrival(forced = null) {
if (state.arrivals.length >= MAX_QUEUE) {
state.misses++;
state.score = Math.max(0, state.score - 60);
state.combo = 0;
addEvent("Dock full — parcel turned away", "bad");
return;
}
const types = [
{ width: 1, height: 1, weight: 2 },
{ width: 2, height: 1, weight: 3 },
{ width: 1, height: 2, weight: 3 },
{ width: 2, height: 2, weight: 2 },
{ width: 1, height: 3, weight: 1 },
{ width: 3, height: 1, weight: 1 }
];
const totalWeight = types.reduce((sum, type) => sum + type.weight, 0);
let roll = Math.random() * totalWeight;
let type = types[0];
if (forced) {
type = forced;
} else {
for (const candidate of types) {
roll -= candidate.weight;
if (roll <= 0) {
type = candidate;
break;
}
}
}
const id = state.nextId++;
const arrival = {
id,
code: `PX-${String(id).padStart(3, "0")}`,
customer: CUSTOMERS[Math.floor(Math.random() * CUSTOMERS.length)],
width: type.width,
height: type.height,
color: COLORS[Math.floor(Math.random() * COLORS.length)],
rotated: false
};
state.arrivals.push(arrival);
return arrival;
}
function placeArrival(arrival, compartment) {
const dimensions = arrivalDimensions(arrival);
const spot = findSpot(compartment, dimensions.width, dimensions.height);
if (!spot) return false;
for (let rowIndex = 0; rowIndex < dimensions.height; rowIndex++) {
for (let columnIndex = 0; columnIndex < dimensions.width; columnIndex++) {
compartment.occupancy[spot.y + rowIndex][spot.x + columnIndex] = true;
}
}
compartment.occupied += dimensions.width * dimensions.height;
const parcel = makeVoxelParcel(
compartment,
arrival,
spot.x,
spot.y,
dimensions.width,
dimensions.height
);
state.parcels.push(parcel);
state.arrivals = state.arrivals.filter(item => item.id !== arrival.id);
state.selectedArrivalId = null;
compartment.doorOpenUntil = performance.now() + 850;
updateCompartmentLabel(compartment);
addEvent(`${arrival.code} assigned to ${compartment.id}`, "good");
showToast(`${arrival.code} placed in ${compartment.id} · ${dimensions.width}×${dimensions.height}`);
renderUI();
return true;
}
function disposeParcel(parcel) {
compartmentClear(parcel);
parcel.group.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(material => material.dispose());
else object.material.dispose();
}
});
parcel.group.removeFromParent();
}
function compartmentClear(parcel) {
const compartment = parcel.compartment;
for (let rowIndex = 0; rowIndex < parcel.height; rowIndex++) {
for (let columnIndex = 0; columnIndex < parcel.width; columnIndex++) {
compartment.occupancy[parcel.y + rowIndex][parcel.x + columnIndex] = false;
}
}
compartment.occupied = Math.max(0, compartment.occupied - parcel.width * parcel.height);
updateCompartmentLabel(compartment);
}
function collectRequest(request) {
const parcel = state.parcels.find(item => item.id === request.parcelId);
if (!parcel) return;
parcel.compartment.doorOpenUntil = performance.now() + 1000;
disposeParcel(parcel);
state.parcels = state.parcels.filter(item => item.id !== parcel.id);
state.requests = state.requests.filter(item => item.id !== request.id);
state.combo++;
const speedBonus = Math.max(0, 10 - Math.floor((state.elapsed - request.due) / 2)) * 5;
const comboBonus = Math.min(50, (state.combo - 1) * 10);
const earned = 140 + speedBonus + comboBonus;
state.score += earned;
state.delivered++;
if (!state.targetHit && state.delivered >= TARGET) {
state.targetHit = true;
addEvent("Shift target reached — keep going!", "good");
showToast("Target reached! Keep the handoffs flowing.");
}
addEvent(`${request.code} handed off · +${earned}`, "good");
showToast(`Handoff complete · +${earned} points`);
state.selectedRequestId = null;
renderUI();
}
function expireRequest(request) {
const parcel = state.parcels.find(item => item.id === request.parcelId);
if (parcel) {
disposeParcel(parcel);
state.parcels = state.parcels.filter(item => item.id !== parcel.id);
}
state.requests = state.requests.filter(item => item.id !== request.id);
state.misses++;
state.combo = 0;
state.score = Math.max(0, state.score - 120);
addEvent(`${request.code} pickup window expired`, "bad");
showToast(`Missed pickup for ${request.code}`, "bad");
if (state.selectedRequestId === request.id) state.selectedRequestId = null;
renderUI();
}
function selectArrival(id) {
const arrival = state.arrivals.find(item => item.id === id);
if (!arrival) return;
state.selectedArrivalId = id;
state.selectedRequestId = null;
const dimensions = arrivalDimensions(arrival);
showToast(`${arrival.code} selected · needs ${dimensions.width}×${dimensions.height}`);
renderUI();
}
function selectRequest(id) {
const request = state.requests.find(item => item.id === id);
if (!request) return;
state.selectedRequestId = id;
state.selectedArrivalId = null;
request.compartment.doorOpenUntil = performance.now() + 1400;
showToast(`Open locker ${request.compartment.id} for ${request.code}`);
renderUI();
}
function rotateSelected() {
const arrival = selectedArrival();
if (!arrival) {
showToast("Select an incoming parcel before rotating", "warn");
return;
}
arrival.rotated = !arrival.rotated;
const dimensions = arrivalDimensions(arrival);
showToast(`${arrival.code} rotated · ${dimensions.width}×${dimensions.height}`);
renderUI();
}
function handleCompartmentClick(compartment) {
if (state.ended) return;
const request = selectedRequest();
if (request) {
if (request.compartment === compartment) collectRequest(request);
else showToast(`That parcel is in locker ${request.compartment.id}`, "warn");
return;
}
const arrival = selectedArrival();
if (arrival) {
const dimensions = arrivalDimensions(arrival);
if (!placeArrival(arrival, compartment)) {
showToast(
`${arrival.code} does not fit in ${compartment.id} · needs ${dimensions.width}×${dimensions.height}`,
"bad"
);
}
return;
}
const waitingRequest = compartmentHasRequest(compartment);
if (waitingRequest) {
collectRequest(waitingRequest);
} else {
showToast("Select an incoming parcel or a pickup request first", "warn");
}
}
function addEvent(message, tone = "") {
state.events.unshift({ message, tone, time: formatClock(state.elapsed) });
state.events = state.events.slice(0, 5);
}
function formatClock(elapsed) {
const totalMinutes = 9 * 60 + Math.floor(elapsed);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function updateGame(delta) {
state.elapsed += delta;
state.nextArrival -= delta;
if (state.nextArrival <= 0) {
spawnArrival();
state.nextArrival = 10 + Math.random() * 4;
}
for (const parcel of state.parcels) {
if (!parcel.requested && state.elapsed >= parcel.due) {
parcel.requested = true;
state.requests.push({
id: `REQ-${parcel.id}`,
parcelId: parcel.id,
code: parcel.code,
customer: parcel.customer,
compartment: parcel.compartment,
due: parcel.due,
deadline: parcel.due + 20
});
addEvent(`${parcel.code} pickup ready at ${parcel.compartment.id}`, "good");
showToast(`Pickup ready · ${parcel.code} is in ${parcel.compartment.id}`, "warn");
}
}
for (const request of [...state.requests]) {
if (state.elapsed > request.deadline) expireRequest(request);
}
if (state.elapsed >= SHIFT_LENGTH) endShift();
}
function resetGame() {
for (const parcel of state.parcels) disposeParcel(parcel);
compartments.forEach(compartment => {
compartment.occupancy = Array.from({ length: compartment.height }, () => Array(compartment.width).fill(false));
compartment.occupied = 0;
compartment.doorOpenUntil = 0;
updateCompartmentLabel(compartment);
});
Object.assign(state, {
running: false,
ended: false,
elapsed: 0,
speed: 1,
score: 0,
delivered: 0,
misses: 0,
combo: 0,
targetHit: false,
arrivals: [],
requests: [],
parcels: [],
selectedArrivalId: null,
selectedRequestId: null,
nextArrival: 10,
nextId: 101,
events: []
});
document.querySelectorAll(".speed-button").forEach(button => {
button.classList.toggle("active", button.dataset.speed === "1");
});
renderUI();
}
function startShift() {
resetGame();
state.running = true;
state.nextArrival = 9;
spawnArrival({ width: 2, height: 2 });
spawnArrival({ width: 1, height: 2 });
spawnArrival({ width: 2, height: 1 });
addEvent("Morning inbound wave opened", "good");
showToast("Select an incoming parcel to begin");
renderUI();
}
function endShift() {
if (state.ended) return;
state.ended = true;
state.running = false;
state.misses += state.requests.length;
addEvent("Depot shift closed", "");
showModal("end");
renderUI();
}
function renderUI() {
const occupied = compartments.reduce((sum, compartment) => sum + compartment.occupied, 0);
queueCount.textContent = `${state.arrivals.length} / ${MAX_QUEUE}`;
pickupCount.textContent = state.requests.length;
clockMetricValue.textContent = formatClock(state.elapsed);
deliveryMetric.textContent = `${state.delivered} / ${TARGET}`;
scoreMetricValue.textContent = String(state.score).padStart(4, "0");
fillMetric.textContent = `${occupied} / ${totalSlots}`;
pauseButton.textContent = state.running ? "Pause" : "Resume";
pauseButton.disabled = state.ended;
rotateButton.disabled = !selectedArrival();
if (state.arrivals.length === 0) {
arrivalList.innerHTML = `
<div class="empty-state">
<div>
<div class="empty-icon"></div>
No parcels waiting<br />The next inbound wave is on its way.
</div>
</div>`;
} else {
arrivalList.innerHTML = state.arrivals.map(arrival => {
const dimensions = arrivalDimensions(arrival);
const selected = arrival.id === state.selectedArrivalId;
const color = `#${arrival.color.toString(16).padStart(6, "0")}`;
return `
<div class="parcel-card ${selected ? "selected" : ""}" data-arrival="${arrival.id}">
<div class="card-row">
<div style="display:flex;align-items:center;gap:9px">
<span class="parcel-dot" style="background:${color}"></span>
<span class="parcel-id">${arrival.code}</span>
</div>
<span class="size-chip">${dimensions.width}×${dimensions.height}</span>
</div>
<div class="customer">${arrival.customer}</div>
<div class="card-note">
<span>${selected ? "Selected — click a bay" : "Inbound parcel"}</span>
<span class="${selected ? "selected-note" : ""}">${selected ? "Ready" : "Select"}</span>
</div>
</div>`;
}).join("");
}
if (state.requests.length === 0) {
pickupList.innerHTML = `
<div class="empty-state">
<div>
<div class="empty-icon"></div>
No pickups waiting<br />Delivered parcels appear here automatically.
</div>
</div>`;
} else {
pickupList.innerHTML = state.requests.map(request => {
const remaining = Math.max(0, Math.ceil(request.deadline - state.elapsed));
const selected = request.id === state.selectedRequestId;
return `
<div class="pickup-card ready ${selected ? "selected" : ""}" data-request="${request.id}">
<div class="card-row">
<div class="parcel-id">${request.code}</div>
<button class="locate-button" data-locate="${request.id}">LOCATE</button>
</div>
<div class="customer">${request.customer} · Locker ${request.compartment.id}</div>
<div class="card-note">
<span>Pickup ready</span>
<span>${remaining}m grace</span>
</div>
</div>`;
}).join("");
}
const events = state.events.slice(0, 4).map(event => `
<div class="event-item ${event.tone}">
<span class="event-time">${event.time}</span>
<span>${event.message}</span>
</div>`).join("");
const eventHost = document.createElement("div");
eventHost.className = "events";
eventHost.innerHTML = events || `<div class="event-item"><span class="event-time">09:00</span><span>Waiting for the shift to begin.</span></div>`;
const existingEvents = pickupList.parentElement.querySelector(".events");
if (existingEvents) existingEvents.remove();
pickupList.parentElement.appendChild(eventHost);
}
function showToast(message, tone = "") {
toastElement.textContent = message;
toastElement.className = `toast show ${tone}`;
clearTimeout(showToast.timeout);
showToast.timeout = setTimeout(() => {
toastElement.className = "toast";
}, 2500);
}
function showModal(mode) {
state.modalMode = mode;
if (mode === "guide") {
state.modalReturnRunning = state.running;
state.running = false;
} else if (mode === "intro") {
state.running = false;
} else if (mode === "end") {
state.running = false;
}
if (mode === "intro") {
modal.innerHTML = `
<div class="modal-card">
<div class="eyebrow">Shift 01 · Morning dispatch</div>
<h2>Sort the city,<br />one parcel at a time.</h2>
<p>You are the dispatcher at a voxel parcel depot. Fit incoming parcels into the right compartments, then release them when customers arrive.</p>
<div class="rules">
<div class="rule"><b>Select & place</b><span>Choose an incoming parcel, then click a locker whose grid can hold its footprint.</span></div>
<div class="rule"><b>Mind the shape</b><span>Every compartment has a width and height. Press R to rotate a selected parcel.</span></div>
<div class="rule"><b>Release pickups</b><span>When a request appears, locate its locker and click the glowing compartment.</span></div>
<div class="rule"><b>Beat the target</b><span>Complete 10 handoffs in one shift. Do not let the inbound queue reach six.</span></div>
</div>
<div class="modal-actions">
<button class="modal-primary" id="modalPrimary">Begin shift</button>
<span style="color:#6f8ba0;font-size:10px">Drag to orbit · Wheel to zoom</span>
</div>
</div>`;
} else if (mode === "guide") {
modal.innerHTML = `
<div class="modal-card">
<div class="eyebrow">Dispatcher reference</div>
<h2>Keep the grid moving.</h2>
<div class="rules">
<div class="rule"><b>Place parcels</b><span>Select a parcel from the left, then click a compatible 3D locker.</span></div>
<div class="rule"><b>Rotate with R</b><span>Rotation changes width and height. A 2×1 parcel can become 1×2.</span></div>
<div class="rule"><b>Collect pickups</b><span>Use LOCATE, then click the glowing locker. Each request has a 20-minute grace window.</span></div>
<div class="rule"><b>Camera controls</b><span>Drag to orbit, wheel to zoom, right-drag to pan. The game continues while paused.</span></div>
</div>
<div class="modal-actions">
<button class="modal-primary" id="modalPrimary">Back to shift</button>
</div>
</div>`;
} else {
const accuracy = state.delivered + state.misses > 0
? Math.round((state.delivered / (state.delivered + state.misses)) * 100)
: 0;
modal.innerHTML = `
<div class="modal-card">
<div class="eyebrow">${state.delivered >= TARGET ? "Target achieved" : "Shift complete"}</div>
<h2>${state.delivered >= TARGET ? "Depot cleared." : "The dock got busy."}</h2>
<p>${state.delivered >= TARGET
? "You kept the lockers moving and completed the shift target."
: "The shift ended before the handoff target was reached. Try grouping shapes more efficiently."}</p>
<div class="summary-grid">
<div class="summary-stat"><strong>${state.delivered}</strong><span>Handoffs</span></div>
<div class="summary-stat"><strong>${state.score}</strong><span>Final score</span></div>
<div class="summary-stat"><strong>${accuracy}%</strong><span>Service rate</span></div>
</div>
<div class="modal-actions">
<button class="modal-primary" id="modalPrimary">Run another shift</button>
</div>
</div>`;
}
modal.classList.add("show");
document.getElementById("modalPrimary").addEventListener("click", () => {
if (mode === "intro" || mode === "end") {
modal.classList.remove("show");
startShift();
} else {
modal.classList.remove("show");
state.running = state.modalReturnRunning;
state.modalMode = null;
renderUI();
}
});
renderUI();
}
arrivalList.addEventListener("click", event => {
const card = event.target.closest("[data-arrival]");
if (card) selectArrival(Number(card.dataset.arrival));
});
pickupList.addEventListener("click", event => {
const locate = event.target.closest("[data-locate]");
if (locate) {
selectRequest(locate.dataset.locate);
return;
}
const card = event.target.closest("[data-request]");
if (card) selectRequest(card.dataset.request);
});
pauseButton.addEventListener("click", () => {
if (state.ended) return;
state.running = !state.running;
renderUI();
});
rotateButton.addEventListener("click", rotateSelected);
document.getElementById("cameraButton").addEventListener("click", resetCamera);
document.getElementById("guideButton").addEventListener("click", () => showModal("guide"));
document.querySelectorAll(".speed-button").forEach(button => {
button.addEventListener("click", () => {
state.speed = Number(button.dataset.speed);
document.querySelectorAll(".speed-button").forEach(item => {
item.classList.toggle("active", item === button);
});
});
});
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
if (!state.ended && !state.modalMode) {
state.running = !state.running;
renderUI();
}
}
if (event.key.toLowerCase() === "r") rotateSelected();
if (event.key === "Escape") {
state.selectedArrivalId = null;
state.selectedRequestId = null;
if (state.modalMode === "guide") {
modal.classList.remove("show");
state.running = state.modalReturnRunning;
state.modalMode = null;
}
renderUI();
}
if (event.key === "ArrowLeft") cameraState.yaw += 0.08;
if (event.key === "ArrowRight") cameraState.yaw -= 0.08;
if (event.key === "ArrowUp") cameraState.pitch = Math.min(0.9, cameraState.pitch + 0.05);
if (event.key === "ArrowDown") cameraState.pitch = Math.max(0.08, cameraState.pitch - 0.05);
if (event.key === "+" || event.key === "=") cameraState.radius = Math.max(7, cameraState.radius - 0.5);
if (event.key === "-") cameraState.radius = Math.min(17, cameraState.radius + 0.5);
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerState = {
down: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: 0
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraState;
const horizontal = Math.cos(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.set(0, 2.1, 0);
cameraState.yaw = 0.20;
cameraState.pitch = 0.34;
cameraState.radius = 11.8;
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
pointerState.down = true;
pointerState.button = event.button;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = 0;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", event => {
if (!pointerState.down) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved += Math.abs(dx) + Math.abs(dy);
if (pointerState.button === 2) {
const scale = cameraState.radius * 0.0012;
const rightX = Math.cos(cameraState.yaw);
const rightZ = -Math.sin(cameraState.yaw);
cameraState.target.x -= dx * scale * rightX;
cameraState.target.z -= dx * scale * rightZ;
cameraState.target.y += dy * scale;
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -2.2, 2.2);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, 1.2, 3.1);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -1.2, 1.2);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.0045, 0.08, 0.9);
}
});
canvas.addEventListener("pointerup", event => {
if (pointerState.down && pointerState.moved < 6 && pointerState.button === 0) {
const rect = canvas.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 hit = raycaster.intersectObjects(hitMeshes, false)[0];
if (hit) handleCompartmentClick(hit.object.userData.compartment);
}
pointerState.down = false;
canvas.classList.remove("dragging");
});
canvas.addEventListener("pointercancel", () => {
pointerState.down = false;
canvas.classList.remove("dragging");
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.008,
7,
17
);
}, { passive: false });
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
function updateVisuals(now) {
const arrival = selectedArrival();
const request = selectedRequest();
const dimensions = arrival ? arrivalDimensions(arrival) : null;
for (const compartment of compartments) {
const hasRequest = Boolean(compartmentHasRequest(compartment));
const isTarget = request && request.compartment === compartment;
const isValid = arrival && findSpot(compartment, dimensions.width, dimensions.height);
let color = compartment.occupied ? 0x3977a8 : 0x28546b;
let intensity = compartment.occupied ? 0.13 : 0.07;
if (isValid) {
color = 0x58f5cf;
intensity = 0.34;
}
if (hasRequest) {
color = 0xff756f;
intensity = 0.28 + Math.sin(now * 0.008) * 0.12;
}
if (isTarget) {
color = 0xffc766;
intensity = 0.55;
}
compartment.frameMaterial.color.setHex(color);
compartment.frameMaterial.emissive.setHex(color);
compartment.frameMaterial.emissiveIntensity = intensity;
compartment.statusDot.material.color.setHex(color);
const shouldOpen = now < compartment.doorOpenUntil || isTarget;
const targetRotation = shouldOpen ? -1.12 : 0;
compartment.doorPivot.rotation.y = THREE.MathUtils.lerp(
compartment.doorPivot.rotation.y,
targetRotation,
0.12
);
}
for (const parcel of state.parcels) {
const pulse = parcel.requested ? 0.28 + Math.sin(now * 0.009) * 0.15 : 0.055;
for (const material of parcel.materials) {
material.emissiveIntensity = pulse;
}
}
}
renderUI();
showModal("intro");
updateCamera();
let previousTime = performance.now();
let uiAccumulator = 0;
function animate(now) {
requestAnimationFrame(animate);
const rawDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.running && !state.ended) {
updateGame(rawDelta * state.speed);
}
updateVisuals(now);
updateCamera();
uiAccumulator += rawDelta;
if (uiAccumulator > 0.35) {
uiAccumulator = 0;
renderUI();
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```