Prompt specification
Build or customize the Three.js 3D scene "Mountain Courier Strategy Board" 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: Mountain Courier Strategy Board
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/mountain-courier-strategy-board-x3595
Scene Description Prompt:
Please make a voxel Three.js scene in one standalone HTML file using cdnjs. Create an original voxel courier game with roads, hills, and bridges on a bounded map. Calculate route cost from visible rules and preserve a reachable destination.
Working Three.js Starter (mountain-courier-strategy-board-x3595):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bramblebyte — Voxel Courier</title>
<style>
:root {
--ink: #17232b;
--panel: rgba(19, 31, 38, 0.9);
--panel-soft: rgba(28, 45, 52, 0.84);
--line: rgba(255, 255, 255, 0.12);
--text: #f4f1df;
--muted: #aab9b7;
--gold: #ffc857;
--mint: #77e0b4;
--orange: #ff8a4c;
--blue: #67c9e8;
--red: #ff6f61;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #91b7ba;
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;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 10;
}
.panel {
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 18px 50px rgba(13, 23, 28, 0.25),
inset 0 1px 0 rgba(255, 255, 255, 0.06);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.eyebrow {
color: var(--gold);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
#mission {
position: absolute;
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
padding: 18px 18px 16px;
border-radius: 18px;
}
#mission h1 {
margin: 5px 0 2px;
font-size: clamp(1.35rem, 3vw, 2rem);
line-height: 1;
letter-spacing: -0.04em;
}
#mission .subtitle {
color: var(--mint);
font-size: 0.75rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#mission p {
margin: 12px 0 14px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.5;
}
.mission-row {
display: flex;
align-items: center;
gap: 10px;
padding-top: 12px;
border-top: 1px solid var(--line);
color: #d9e2dc;
font-size: 0.76rem;
}
.parcel-icon {
position: relative;
width: 27px;
height: 27px;
flex: 0 0 auto;
border: 2px solid var(--gold);
border-radius: 5px;
background: rgba(255, 200, 87, 0.12);
transform: rotate(-5deg);
}
.parcel-icon::before,
.parcel-icon::after {
content: "";
position: absolute;
background: var(--gold);
}
.parcel-icon::before {
top: -2px;
bottom: -2px;
left: 10px;
width: 2px;
}
.parcel-icon::after {
left: -2px;
right: -2px;
top: 10px;
height: 2px;
}
#rules {
position: absolute;
top: 18px;
right: 18px;
width: 250px;
padding: 16px;
border-radius: 18px;
pointer-events: auto;
}
.rule-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 11px;
}
.reachable {
padding: 4px 7px;
border-radius: 999px;
background: rgba(119, 224, 180, 0.12);
color: var(--mint);
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.rule {
display: grid;
grid-template-columns: 22px 1fr auto;
align-items: center;
gap: 9px;
padding: 8px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.07);
font-size: 0.78rem;
}
.rule:last-of-type {
border-bottom: 0;
}
.swatch {
width: 20px;
height: 20px;
border-radius: 5px;
box-shadow: inset 0 -4px 0 rgba(0, 0, 0, 0.14);
}
.swatch.flat {
background: #455260;
}
.swatch.hill {
background: #756253;
}
.swatch.bridge {
background: #c48b54;
}
.rule strong {
color: var(--gold);
font-size: 1rem;
}
.rule-note {
margin: 10px 0 0;
color: var(--muted);
font-size: 0.68rem;
line-height: 1.45;
}
#rules button {
width: 100%;
margin-top: 12px;
}
#routePanel {
position: absolute;
bottom: 20px;
left: 50%;
width: min(760px, calc(100vw - 32px));
padding: 14px 16px;
border-radius: 19px;
transform: translateX(-50%);
pointer-events: auto;
}
.route-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
}
.route-copy {
min-width: 0;
}
#routeStatus {
overflow: hidden;
color: #e8eee8;
font-size: 0.82rem;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.metrics {
display: flex;
flex: 0 0 auto;
gap: 9px;
}
.metric {
min-width: 76px;
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.045);
text-align: center;
}
.metric span {
display: block;
color: var(--muted);
font-size: 0.58rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 2px;
color: var(--gold);
font-size: 1.12rem;
}
.metric strong.good {
color: var(--mint);
}
.route-actions {
display: flex;
gap: 8px;
margin-top: 12px;
}
button {
min-height: 39px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.07);
color: var(--text);
cursor: pointer;
font-size: 0.75rem;
font-weight: 800;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
border-color: rgba(255, 255, 255, 0.28);
background: rgba(255, 255, 255, 0.13);
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
cursor: not-allowed;
opacity: 0.36;
}
button.primary {
border-color: transparent;
background: var(--gold);
color: #283039;
}
button.primary:hover:not(:disabled) {
background: #ffd77c;
}
#dispatchBtn {
min-width: 130px;
margin-left: auto;
}
#help {
position: absolute;
right: 20px;
bottom: 22px;
padding: 8px 11px;
border-radius: 9px;
background: rgba(19, 31, 38, 0.72);
color: rgba(244, 241, 223, 0.72);
font-size: 0.66rem;
pointer-events: none;
}
#toast {
position: absolute;
top: 50%;
left: 50%;
max-width: min(430px, calc(100vw - 36px));
padding: 12px 17px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 12px;
background: rgba(17, 27, 33, 0.94);
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
color: var(--text);
font-size: 0.78rem;
line-height: 1.4;
opacity: 0;
transform: translate(-50%, -35%);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, -50%);
}
#result {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: rgba(9, 16, 20, 0.32);
opacity: 0;
pointer-events: none;
transition: opacity 220ms ease;
}
#result.show {
opacity: 1;
pointer-events: auto;
}
.result-card {
width: min(370px, calc(100vw - 34px));
padding: 28px;
border-radius: 22px;
background: rgba(19, 31, 38, 0.96);
border: 1px solid rgba(255, 255, 255, 0.17);
box-shadow: 0 30px 90px rgba(0, 0, 0, 0.38);
text-align: center;
transform: translateY(12px) scale(0.98);
transition: transform 220ms ease;
}
#result.show .result-card {
transform: translateY(0) scale(1);
}
#result h2 {
margin: 6px 0 4px;
font-size: 2rem;
letter-spacing: -0.04em;
}
#stars {
margin: 9px 0;
color: var(--gold);
font-size: 2.1rem;
letter-spacing: 0.15em;
}
#resultText {
margin: 0 0 20px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.55;
}
#result button {
width: 100%;
}
@media (max-width: 760px) {
#mission {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 14px;
}
#mission p {
display: none;
}
.mission-row {
padding-top: 9px;
}
#rules {
top: 112px;
right: 10px;
width: 210px;
padding: 12px;
}
.rule {
padding: 5px 0;
}
.rule-note {
display: none;
}
#routePanel {
bottom: 10px;
width: calc(100vw - 20px);
padding: 11px;
}
.route-top {
align-items: flex-start;
gap: 8px;
}
#routeStatus {
max-width: 42vw;
font-size: 0.72rem;
}
.metric {
min-width: 62px;
padding: 6px 7px;
}
.route-actions {
gap: 5px;
}
button {
padding: 0 9px;
font-size: 0.68rem;
}
#dispatchBtn {
min-width: 105px;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel courier map"></canvas>
<div id="ui">
<section id="mission" class="panel">
<div class="eyebrow">Voxel Courier Run</div>
<h1>BRAMBLEBYTE</h1>
<div class="subtitle">The Mosslight Delivery</div>
<p>
Carry the Ember Lens from Orchard Post to Beacon Depot. Plot a
connected road, then send your courier along it.
</p>
<div class="mission-row">
<span class="parcel-icon" aria-hidden="true"></span>
<span>Best safe route: <strong id="parValue">—</strong> energy</span>
</div>
</section>
<aside id="rules" class="panel">
<div class="rule-heading">
<span class="eyebrow">Visible Route Rules</span>
<span class="reachable">Reachable ✓</span>
</div>
<div class="rule">
<span class="swatch flat"></span>
<span>Flat road</span>
<strong>1</strong>
</div>
<div class="rule">
<span class="swatch hill"></span>
<span>Hill road</span>
<strong>3</strong>
</div>
<div class="rule">
<span class="swatch bridge"></span>
<span>Bridge road</span>
<strong>2</strong>
</div>
<p class="rule-note">
Energy is the sum of the costs of every tile after Orchard Post.
The preview and the suggested route use these exact values.
</p>
<button id="suggestBtn" type="button">Suggest a safe route</button>
</aside>
<section id="routePanel" class="panel">
<div class="route-top">
<div class="route-copy">
<div class="eyebrow">Route Planner</div>
<div id="routeStatus">Click a road beside the glowing route tip.</div>
</div>
<div class="metrics">
<div class="metric">
<span>Energy</span>
<strong id="costValue">0</strong>
</div>
<div class="metric">
<span>Tiles</span>
<strong id="tileValue">0</strong>
</div>
</div>
</div>
<div class="route-actions">
<button id="undoBtn" type="button">Undo</button>
<button id="clearBtn" type="button">Clear</button>
<button id="dispatchBtn" class="primary" type="button" disabled>
Dispatch courier
</button>
</div>
</section>
<div id="help">Drag to orbit · Wheel to zoom · Click road tiles</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="result">
<div class="result-card">
<div class="eyebrow">Parcel Delivered</div>
<h2>Beacon reached!</h2>
<div id="stars">★★★</div>
<p id="resultText"></p>
<button id="newRunBtn" class="primary" type="button">Plan another run</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";
// -------------------------------------------------------------------------
// Configuration and route data
// -------------------------------------------------------------------------
const CELL = 1.05;
const GRID = 13;
const START = "2,10";
const GOAL = "10,2";
// road type: flat, hill, bridge, start, goal
const roadData = [
[2, 10, "start"],
[3, 10],
[4, 10],
[5, 10],
[6, 10, "bridge"],
[7, 10],
[8, 10],
[9, 10],
[9, 9],
[9, 8],
[9, 7],
[9, 6],
[9, 5],
[10, 5],
[10, 4],
[10, 3],
[10, 2, "goal"],
[2, 9],
[2, 8, "hill"],
[3, 8, "hill"],
[3, 9],
[4, 8, "hill"],
[5, 8, "hill"],
[5, 7, "hill"],
[5, 6],
[6, 6, "bridge"],
[7, 6],
[8, 6]
];
const costForType = {
flat: 1,
hill: 3,
bridge: 2,
start: 1,
goal: 1
};
const tiles = new Map();
for (const [x, z, explicitType] of roadData) {
const type = explicitType || "flat";
const key = `${x},${z}`;
const top =
type === "hill"
? 0.92
: type === "bridge"
? 0.14
: 0.075;
tiles.set(key, {
key,
x,
z,
type,
cost: costForType[type],
top
});
}
const neighbors = new Map();
for (const [key, tile] of tiles) {
const found = [];
for (const [dx, dz] of [
[1, 0],
[-1, 0],
[0, 1],
[0, -1]
]) {
const nk = `${tile.x + dx},${tile.z + dz}`;
if (tiles.has(nk)) found.push(nk);
}
neighbors.set(key, found);
}
function routeCost(route) {
let total = 0;
for (let i = 1; i < route.length; i++) {
total += tiles.get(route[i]).cost;
}
return total;
}
// Dijkstra uses the same visible costs shown in the rules panel.
function shortestPath(start, goal) {
const distance = new Map();
const previous = new Map();
const remaining = new Set(tiles.keys());
for (const key of tiles.keys()) distance.set(key, Infinity);
distance.set(start, 0);
while (remaining.size) {
let current = null;
let currentDistance = Infinity;
for (const key of remaining) {
const d = distance.get(key);
if (d < currentDistance) {
current = key;
currentDistance = d;
}
}
if (current === null) break;
if (current === goal) break;
remaining.delete(current);
for (const next of neighbors.get(current)) {
if (!remaining.has(next)) continue;
const candidate =
currentDistance + tiles.get(next).cost;
if (candidate < distance.get(next)) {
distance.set(next, candidate);
previous.set(next, current);
}
}
}
if (!Number.isFinite(distance.get(goal))) return null;
const path = [goal];
while (path[0] !== start) {
const p = previous.get(path[0]);
if (!p) return null;
path.unshift(p);
}
return path;
}
// Verify that the destination remains reachable before building the game.
const verifiedPath = shortestPath(START, GOAL);
if (!verifiedPath) {
throw new Error("Beacon Depot is not reachable from Orchard Post.");
}
const parCost = routeCost(verifiedPath);
document.getElementById("parValue").textContent = parCost;
// -------------------------------------------------------------------------
// Renderer, scene, lights, and camera
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x91b7ba);
scene.fog = new THREE.Fog(0x91b7ba, 34, 62);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const cameraState = {
yaw: 0.68,
pitch: 0.72,
zoom: 1.04,
target: new THREE.Vector3(0, 0.2, 0)
};
const hemisphere = new THREE.HemisphereLight(0xc8e9e7, 0x506341, 2.05);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe5b0, 3.2);
sun.position.set(-11, 19, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x8cc9ff, 0.65);
rimLight.position.set(12, 8, -10);
scene.add(rimLight);
function updateCamera() {
const radius = 25;
const { yaw, pitch, target } = cameraState;
camera.position.set(
target.x + Math.sin(yaw) * Math.cos(pitch) * radius,
target.y + Math.sin(pitch) * radius,
target.z + Math.cos(yaw) * Math.cos(pitch) * radius
);
camera.lookAt(target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const verticalSpan = Math.max(13, 19 / aspect);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(width, height);
camera.left = (-verticalSpan * aspect) / 2;
camera.right = (verticalSpan * aspect) / 2;
camera.top = verticalSpan / 2;
camera.bottom = -verticalSpan / 2;
updateCamera();
}
window.addEventListener("resize", resize);
resize();
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function worldX(x) {
return (x - (GRID - 1) / 2) * CELL;
}
function worldZ(z) {
return (z - (GRID - 1) / 2) * CELL;
}
function boxMesh(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabelSprite(text, background, foreground = "#ffffff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 112;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(8, 8, 496, 96, 22);
ctx.fill();
ctx.strokeStyle = "rgba(255,255,255,.22)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = foreground;
ctx.font = "800 34px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 57);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
return sprite;
}
const materials = {
groundA: new THREE.MeshStandardMaterial({ color: 0x7ea663, roughness: 0.98 }),
groundB: new THREE.MeshStandardMaterial({ color: 0x86ad68, roughness: 0.98 }),
groundC: new THREE.MeshStandardMaterial({ color: 0x75965d, roughness: 0.98 }),
hill: new THREE.MeshStandardMaterial({ color: 0x8ca76b, roughness: 1 }),
hillSide: new THREE.MeshStandardMaterial({ color: 0x718b58, roughness: 1 }),
riverbed: new THREE.MeshStandardMaterial({ color: 0x335b5c, roughness: 1 }),
road: new THREE.MeshStandardMaterial({ color: 0x46525d, roughness: 0.93 }),
hillRoad: new THREE.MeshStandardMaterial({ color: 0x776453, roughness: 0.94 }),
bridge: new THREE.MeshStandardMaterial({ color: 0xc18a54, roughness: 0.87 }),
lane: new THREE.MeshStandardMaterial({ color: 0xf0dca6, roughness: 0.8 }),
rail: new THREE.MeshStandardMaterial({ color: 0x9c663d, roughness: 0.85 }),
bark: new THREE.MeshStandardMaterial({ color: 0x704e38, roughness: 1 }),
leafA: new THREE.MeshStandardMaterial({ color: 0x3e7752, roughness: 1 }),
leafB: new THREE.MeshStandardMaterial({ color: 0x56875a, roughness: 1 }),
leafC: new THREE.MeshStandardMaterial({ color: 0x71985e, roughness: 1 }),
stone: new THREE.MeshStandardMaterial({ color: 0x879084, roughness: 1 }),
dark: new THREE.MeshStandardMaterial({ color: 0x273039, roughness: 0.85 }),
orange: new THREE.MeshStandardMaterial({ color: 0xf1783f, roughness: 0.75 }),
cyan: new THREE.MeshStandardMaterial({ color: 0x63d6df, roughness: 0.65 }),
gold: new THREE.MeshStandardMaterial({
color: 0xffc857,
emissive: 0x9d5b08,
emissiveIntensity: 0.3,
roughness: 0.45
})
};
// -------------------------------------------------------------------------
// Island, river, hills, and border
// -------------------------------------------------------------------------
const boardSize = GRID * CELL + 1.0;
boxMesh(
boardSize,
0.38,
boardSize,
new THREE.MeshStandardMaterial({ color: 0x5e654d, roughness: 1 }),
0,
-0.84,
0
);
const naturalHills = new Set([
"3,7",
"4,7",
"4,9",
"5,9",
"1,8",
"2,7",
"6,5"
]);
function terrainTop(x, z) {
const key = `${x},${z}`;
if (tiles.get(key)?.type === "hill") return 0.92;
if (naturalHills.has(key)) return 0.43;
return 0;
}
for (let x = 0; x < GRID; x++) {
for (let z = 0; z < GRID; z++) {
const isRiver = x === 6 && z >= 2 && z <= 10;
if (isRiver) continue;
const key = `${x},${z}`;
const top = terrainTop(x, z);
const height = top + 0.62;
let material = materials.groundA;
if ((x + z) % 3 === 0) material = materials.groundB;
if ((x * 7 + z * 3) % 11 === 0) material = materials.groundC;
if (top > 0.7) material = materials.hillSide;
boxMesh(
CELL * 0.99,
height,
CELL * 0.99,
material,
worldX(x),
top - height / 2,
worldZ(z)
);
}
}
const riverLength = 9 * CELL;
boxMesh(
CELL * 0.99,
0.12,
riverLength,
materials.riverbed,
worldX(6),
-0.58,
worldZ(6)
);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x4ab6c1,
transparent: true,
opacity: 0.82,
roughness: 0.22,
metalness: 0.05
});
boxMesh(
CELL * 0.96,
0.075,
riverLength * 0.99,
waterMaterial,
worldX(6),
-0.29,
worldZ(6)
);
// A low boundary makes the finite map explicit.
const borderOffset = (GRID * CELL) / 2 + 0.18;
const borderLength = GRID * CELL + 0.5;
for (const side of [-1, 1]) {
boxMesh(
borderLength,
0.18,
0.15,
materials.stone,
0,
0.08,
side * borderOffset
);
boxMesh(
0.15,
0.18,
borderLength,
materials.stone,
side * borderOffset,
0.08,
0
);
}
for (const x of [-1, 1]) {
for (const z of [-1, 1]) {
boxMesh(
0.48,
0.48,
0.48,
materials.stone,
x * borderOffset,
0.18,
z * borderOffset
);
}
}
// -------------------------------------------------------------------------
// Roads and bridges
// -------------------------------------------------------------------------
const roadMeshes = [];
for (const tile of tiles.values()) {
let material = materials.road;
if (tile.type === "hill") material = materials.hillRoad;
if (tile.type === "bridge") material = materials.bridge;
if (tile.type === "goal") material = materials.gold;
const road = boxMesh(
CELL * 0.82,
0.11,
CELL * 0.82,
material,
worldX(tile.x),
tile.top + 0.055,
worldZ(tile.z)
);
road.userData.tileKey = tile.key;
roadMeshes.push(road);
if (tile.type !== "bridge") {
boxMesh(
0.075,
0.022,
0.30,
materials.lane,
worldX(tile.x),
tile.top + 0.122,
worldZ(tile.z)
);
} else {
// Side rails and supports make the elevated road read as a bridge.
for (const dz of [-1, 1]) {
boxMesh(
CELL * 0.86,
0.08,
0.075,
materials.rail,
worldX(tile.x),
tile.top + 0.42,
worldZ(tile.z + dz * 0.34)
);
}
for (const dx of [-0.28, 0.28]) {
boxMesh(
0.12,
0.68,
0.12,
materials.rail,
worldX(tile.x + dx),
-0.05,
worldZ(tile.z)
);
}
}
}
// -------------------------------------------------------------------------
// Trees, buildings, and landmarks
// -------------------------------------------------------------------------
function addTree(x, z) {
const top = terrainTop(x, z);
const group = new THREE.Group();
group.position.set(worldX(x), top, worldZ(z));
boxMesh(0.13, 0.42, 0.13, materials.bark, 0, 0.21, 0, group);
boxMesh(0.49, 0.32, 0.49, materials.leafA, 0, 0.57, 0, group);
boxMesh(0.36, 0.31, 0.39, materials.leafB, 0.08, 0.82, -0.03, group);
boxMesh(0.31, 0.24, 0.32, materials.leafC, -0.09, 1.01, 0.02, group);
scene.add(group);
}
let treeCounter = 0;
for (let x = 0; x < GRID; x++) {
for (let z = 0; z < GRID; z++) {
const key = `${x},${z}`;
const isRiver = x === 6 && z >= 2 && z <= 10;
const occupied =
tiles.has(key) ||
key === "1,10" ||
key === "11,2" ||
key === "1,2" ||
key === "11,10";
if (isRiver || occupied) continue;
if ((x * 17 + z * 13 + treeCounter * 5) % 9 < 2) {
addTree(x, z);
treeCounter++;
}
}
}
function addBuilding(x, z, bodyColor, roofColor, glowColor) {
const group = new THREE.Group();
group.position.set(worldX(x), terrainTop(x, z), worldZ(z));
const bodyMaterial = new THREE.MeshStandardMaterial({
color: bodyColor,
roughness: 0.82
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: roofColor,
roughness: 0.8
});
const glowMaterial = new THREE.MeshStandardMaterial({
color: glowColor,
emissive: glowColor,
emissiveIntensity: 0.45,
roughness: 0.4
});
boxMesh(0.72, 0.58, 0.72, bodyMaterial, 0, 0.29, 0, group);
boxMesh(0.83, 0.13, 0.83, roofMaterial, 0, 0.64, 0, group);
boxMesh(0.58, 0.14, 0.58, roofMaterial, 0, 0.76, 0, group);
boxMesh(0.22, 0.23, 0.035, glowMaterial, 0, 0.35, 0.375, group);
boxMesh(0.14, 0.28, 0.15, materials.dark, 0.23, 0.14, 0.39, group);
scene.add(group);
return group;
}
addBuilding(1, 10, 0x486b72, 0x31505a, 0x69e1df);
addBuilding(11, 2, 0x826c55, 0x4b5960, 0xffc857);
addBuilding(1, 2, 0x697b68, 0x4a5b4d, 0xbde08c);
const startLabel = makeLabelSprite("ORCHARD POST", "#203b42", "#8df1cf");
startLabel.position.set(worldX(2), 1.8, worldZ(10));
startLabel.scale.set(2.8, 0.61, 1);
scene.add(startLabel);
const goalLabel = makeLabelSprite("BEACON DEPOT", "#483820", "#ffe093");
goalLabel.position.set(worldX(10), 2.15, worldZ(2));
goalLabel.scale.set(2.9, 0.64, 1);
scene.add(goalLabel);
const goalBeacon = new THREE.Group();
goalBeacon.position.set(worldX(10), 0.16, worldZ(10) - 0.28);
for (const dx of [-0.32, 0.32]) {
for (const dz of [-0.32, 0.32]) {
boxMesh(
0.08,
0.42,
0.08,
materials.gold,
dx,
0.21,
dz,
goalBeacon
);
}
}
const beaconCore = boxMesh(
0.25,
0.25,
0.25,
materials.gold,
0,
0.88,
0,
goalBeacon
);
scene.add(goalBeacon);
// -------------------------------------------------------------------------
// Courier and parcel
// -------------------------------------------------------------------------
const courier = new THREE.Group();
const courierBody = new THREE.Group();
courier.add(courierBody);
boxMesh(0.46, 0.29, 0.38, materials.orange, 0, 0.25, 0, courierBody);
boxMesh(0.29, 0.27, 0.28, materials.dark, 0, 0.53, 0.01, courierBody);
for (const dx of [-0.17, 0.17]) {
boxMesh(0.10, 0.17, 0.42, materials.dark, dx, 0.12, 0, courierBody);
}
const parcel = boxMesh(
0.34,
0.32,
0.34,
materials.cyan,
0,
0.40,
-0.34,
courierBody
);
const parcelBandMaterial = new THREE.MeshStandardMaterial({
color: 0xffdd78,
roughness: 0.55
});
boxMesh(
0.36,
0.055,
0.36,
parcelBandMaterial,
0,
0.40,
-0.34,
courierBody
);
const startTile = tiles.get(START);
courier.position.set(
worldX(startTile.x),
startTile.top + 0.02,
worldZ(startTile.z)
);
scene.add(courier);
// -------------------------------------------------------------------------
// Route preview
// -------------------------------------------------------------------------
const routeMarkerGroup = new THREE.Group();
scene.add(routeMarkerGroup);
const routeMarkerGeometry = new THREE.BoxGeometry(0.19, 0.19, 0.19);
const routeMarkerMaterial = new THREE.MeshStandardMaterial({
color: 0xffd05c,
emissive: 0x9b5a06,
emissiveIntensity: 0.48,
roughness: 0.42
});
let routeMarkers = [];
let routeLine = null;
let route = [START];
let gameState = "ready";
let motion = null;
let toastTimer = null;
function drawRoute() {
for (const child of [...routeMarkerGroup.children]) {
routeMarkerGroup.remove(child);
}
routeMarkers = [];
for (let i = 0; i < route.length; i++) {
const tile = tiles.get(route[i]);
const marker = new THREE.Mesh(
routeMarkerGeometry,
routeMarkerMaterial
);
marker.position.set(
worldX(tile.x),
tile.top + 0.24,
worldZ(tile.z)
);
marker.castShadow = true;
marker.userData.routeIndex = i;
routeMarkerGroup.add(marker);
routeMarkers.push(marker);
}
if (routeLine) {
routeMarkerGroup.remove(routeLine);
routeLine.geometry.dispose();
}
if (route.length > 1) {
const points = route.map((key) => {
const tile = tiles.get(key);
return new THREE.Vector3(
worldX(tile.x),
tile.top + 0.23,
worldZ(tile.z)
);
});
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0xffd05c,
transparent: true,
opacity: 0.95
});
routeLine = new THREE.Line(geometry, material);
routeMarkerGroup.add(routeLine);
}
}
const routeStatus = document.getElementById("routeStatus");
const costValue = document.getElementById("costValue");
const tileValue = document.getElementById("tileValue");
const dispatchBtn = document.getElementById("dispatchBtn");
const undoBtn = document.getElementById("undoBtn");
const clearBtn = document.getElementById("clearBtn");
const suggestBtn = document.getElementById("suggestBtn");
function updateRouteUI() {
const cost = routeCost(route);
const last = route[route.length - 1];
const tileCount = Math.max(0, route.length - 1);
costValue.textContent = cost;
tileValue.textContent = tileCount;
costValue.classList.toggle("good", cost <= parCost);
if (gameState === "delivering") {
routeStatus.textContent = "Courier en route — Ember Lens secured.";
} else if (gameState === "delivered") {
routeStatus.textContent = "Delivered! Beacon Depot has the Ember Lens.";
} else if (last === GOAL) {
routeStatus.textContent =
`Route complete: ${cost} energy. Dispatch the courier.`;
} else {
const tip = tiles.get(last);
routeStatus.textContent =
`Tip at ${tip.x},${tip.z}. Click an adjacent road tile.`;
}
dispatchBtn.disabled = !(last === GOAL && gameState === "ready");
undoBtn.disabled = route.length <= 1 || gameState !== "ready";
clearBtn.disabled = route.length <= 1 || gameState !== "ready";
suggestBtn.disabled = gameState === "delivering";
drawRoute();
}
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 2600);
}
function areAdjacent(a, b) {
const first = tiles.get(a);
const second = tiles.get(b);
return (
Math.abs(first.x - second.x) + Math.abs(first.z - second.z) === 1
);
}
// -------------------------------------------------------------------------
// Dispatch animation and delivery result
// -------------------------------------------------------------------------
const confettiGroup = new THREE.Group();
scene.add(confettiGroup);
const confetti = [];
const confettiGeometry = new THREE.BoxGeometry(0.09, 0.09, 0.09);
const confettiColors = [
0xffc857,
0x77e0b4,
0x67c9e8,
0xff8a4c,
0xf4f1df
];
function spawnConfetti() {
const goal = tiles.get(GOAL);
for (let i = 0; i < 36; i++) {
const material = new THREE.MeshStandardMaterial({
color: confettiColors[i % confettiColors.length],
roughness: 0.7
});
const piece = new THREE.Mesh(confettiGeometry, material);
piece.position.set(
worldX(goal.x) + (Math.random() - 0.5) * 0.55,
1.15 + Math.random() * 0.35,
worldZ(goal.z) + (Math.random() - 0.5) * 0.55
);
piece.rotation.set(
Math.random() * 3,
Math.random() * 3,
Math.random() * 3
);
confettiGroup.add(piece);
confetti.push({
mesh: piece,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.8,
2.2 + Math.random() * 2.4,
(Math.random() - 0.5) * 2.8
),
spin: new THREE.Vector3(
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8,
(Math.random() - 0.5) * 8
)
});
}
}
function clearConfetti() {
for (const item of confetti) {
confettiGroup.remove(item.mesh);
item.mesh.material.dispose();
}
confetti.length = 0;
}
function finishDelivery() {
gameState = "delivered";
parcel.visible = false;
spawnConfetti();
const cost = routeCost(route);
const stars = cost <= parCost ? 3 : cost <= parCost + 3 ? 2 : 1;
document.getElementById("stars").textContent =
"★".repeat(stars) + "☆".repeat(3 - stars);
const comparison =
cost === parCost
? "You matched the best safe route."
: cost < parCost
? "You beat the visible par by " + (parCost - cost) + " energy."
: "You used " + (cost - parCost) + " more energy than par.";
document.getElementById("resultText").textContent =
`${cost} energy · ${route.length - 1} road tiles. ${comparison}`;
document.getElementById("result").classList.add("show");
updateRouteUI();
}
function dispatchCourier() {
if (gameState !== "ready" || route[route.length - 1] !== GOAL) return;
gameState = "delivering";
document.getElementById("result").classList.remove("show");
parcel.visible = true;
const first = tiles.get(route[0]);
courier.position.set(
worldX(first.x),
first.top + 0.02,
worldZ(first.z)
);
moveToRouteIndex(1);
updateRouteUI();
}
function moveToRouteIndex(index) {
if (index >= route.length) {
finishDelivery();
return;
}
const fromTile = tiles.get(route[index - 1]);
const toTile = tiles.get(route[index]);
const from = new THREE.Vector3(
worldX(fromTile.x),
fromTile.top + 0.02,
worldZ(fromTile.z)
);
const to = new THREE.Vector3(
worldX(toTile.x),
toTile.top + 0.02,
worldZ(toTile.z)
);
motion = {
index,
from,
to,
started: performance.now(),
duration: 390
};
}
function resetRun() {
gameState = "ready";
motion = null;
route = [START];
parcel.visible = true;
clearConfetti();
const start = tiles.get(START);
courier.position.set(
worldX(start.x),
start.top + 0.02,
worldZ(start.z)
);
courier.rotation.y = 0;
document.getElementById("result").classList.remove("show");
updateRouteUI();
}
// -------------------------------------------------------------------------
// Route interaction
// -------------------------------------------------------------------------
undoBtn.addEventListener("click", () => {
if (gameState !== "ready" || route.length <= 1) return;
route.pop();
updateRouteUI();
});
clearBtn.addEventListener("click", () => {
if (gameState !== "ready") return;
route = [START];
updateRouteUI();
});
suggestBtn.addEventListener("click", () => {
if (gameState === "delivering") return;
if (gameState === "delivered") resetRun();
const path = shortestPath(START, GOAL);
if (!path) {
showToast("No route currently reaches Beacon Depot.");
return;
}
route = path;
updateRouteUI();
showToast(
`Safe route found: ${routeCost(route)} energy. You can edit it before dispatch.`
);
});
dispatchBtn.addEventListener("click", dispatchCourier);
document.getElementById("newRunBtn").addEventListener("click", resetRun);
// -------------------------------------------------------------------------
// Picking and direct camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickRoad(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(roadMeshes, false);
return hits.length ? hits[0].object.userData.tileKey : null;
}
const drag = {
active: false,
pointerId: null,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false,
button: 0
};
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.pointerId = event.pointerId;
drag.startX = event.clientX;
drag.startY = event.clientY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
drag.moved = false;
drag.button = event.button;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!drag.active || drag.pointerId !== event.pointerId) {
const hovered = pickRoad(event.clientX, event.clientY);
canvas.style.cursor = hovered ? "pointer" : "grab";
return;
}
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
if (
Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
) > 5
) {
drag.moved = true;
canvas.style.cursor = "grabbing";
}
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.34,
1.28
);
drag.lastX = event.clientX;
drag.lastY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!drag.active || drag.pointerId !== event.pointerId) return;
const wasClick = !drag.moved && drag.button === 0;
drag.active = false;
canvas.style.cursor = "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (!wasClick) return;
if (gameState === "delivering") return;
if (gameState === "delivered") {
showToast("Delivery complete. Start another run to keep planning.");
return;
}
const key = pickRoad(event.clientX, event.clientY);
if (!key) return;
const existingIndex = route.indexOf(key);
// Clicking an earlier route tile trims the route back to that point.
if (existingIndex >= 0) {
route = route.slice(0, existingIndex + 1);
updateRouteUI();
return;
}
const tip = route[route.length - 1];
if (areAdjacent(tip, key)) {
route.push(key);
updateRouteUI();
if (key === GOAL) {
showToast(
`Beacon reached in the plan. Route energy: ${routeCost(route)}.`
);
}
} else {
showToast(
"That tile is not beside the glowing route tip. Undo or click an earlier route tile first."
);
}
});
canvas.addEventListener("pointercancel", () => {
drag.active = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.62,
1.8
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let lastTime = performance.now();
function animate(now) {
const dt = Math.min((now - lastTime) / 1000, 0.05);
lastTime = now;
if (motion) {
const t = THREE.MathUtils.clamp(
(now - motion.started) / motion.duration,
0,
1
);
const eased = t * t * (3 - 2 * t);
courier.position.lerpVectors(motion.from, motion.to, eased);
const dx = motion.to.x - motion.from.x;
const dz = motion.to.z - motion.from.z;
if (dx !== 0 || dz !== 0) {
const targetRotation = Math.atan2(dx, dz);
let delta =
targetRotation - courier.rotation.y;
delta = Math.atan2(Math.sin(delta), Math.cos(delta));
courier.rotation.y += delta * 0.22;
}
if (t >= 1) {
const completedIndex = motion.index;
motion = null;
courier.position.copy(motion?.to || courier.position);
if (completedIndex >= route.length - 1) {
finishDelivery();
} else {
moveToRouteIndex(completedIndex + 1);
}
}
}
// Gentle beacon bob.
beaconCore.position.y = 0.88 + Math.sin(now * 0.0032) * 0.07;
beaconCore.rotation.y = now * 0.0012;
// Selected route markers pulse, with the final marker emphasized.
routeMarkers.forEach((marker, index) => {
const isTip = index === routeMarkers.length - 1;
const pulse = 1 + Math.sin(now * 0.006 + index * 0.35) * 0.11;
marker.scale.setScalar((isTip ? 1.35 : 0.88) * pulse);
});
// Confetti physics.
for (const item of confetti) {
item.velocity.y -= 7.5 * dt;
item.mesh.position.addScaledVector(item.velocity, dt);
item.mesh.rotation.x += item.spin.x * dt;
item.mesh.rotation.y += item.spin.y * dt;
item.mesh.rotation.z += item.spin.z * dt;
if (item.mesh.position.y < 0.1) {
item.mesh.position.y = 0.1;
item.velocity.set(0, 0, 0);
}
}
// A restrained follow effect keeps the courier visually central.
if (gameState === "delivering") {
const followX = courier.position.x * 0.08;
const followZ = courier.position.z * 0.08;
cameraState.target.x = THREE.MathUtils.lerp(
cameraState.target.x,
followX,
0.025
);
cameraState.target.z = THREE.MathUtils.lerp(
cameraState.target.z,
followZ,
0.025
);
updateCamera();
}
renderer.render(scene, camera);
}
updateRouteUI();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```