Prompt specification
Build or customize the Three.js 3D scene "Reach a Charger Before Returning" 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: Reach a Charger Before Returning
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/reach-a-charger-before-returning-x3538
Scene Description Prompt:
Create a small robot puzzle where a direct round trip exceeds available energy. Require an intermediate recharge and display energy before each move. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (reach-a-charger-before-returning-x3538):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Relay 08 — Robot Energy Puzzle</title>
<style>
:root {
--bg: #08111c;
--panel: #101c2b;
--panel-2: #162437;
--line: #263a50;
--text: #eaf3ff;
--muted: #91a6bc;
--cyan: #4de4d1;
--amber: #ffc85a;
--red: #ff6f72;
}
* {
box-sizing: border-box;
}
html, body {
margin: 0;
width: 100%;
height: 100%;
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;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100%;
height: 100dvh;
}
#scene-wrap {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 45% 35%, #1b3044 0%, #0c1724 52%, #07101a 100%);
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.scene-header {
position: absolute;
top: 24px;
left: 26px;
right: 26px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand {
pointer-events: none;
}
.eyebrow {
margin: 0 0 6px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 42px);
line-height: 1;
letter-spacing: -0.04em;
}
.brand small {
display: block;
margin-top: 9px;
color: var(--muted);
font-size: 12px;
}
.view-button {
pointer-events: auto;
border: 1px solid #38506a;
border-radius: 9px;
padding: 9px 12px;
color: var(--text);
background: rgba(11, 24, 38, 0.8);
backdrop-filter: blur(10px);
cursor: pointer;
font-size: 12px;
font-weight: 700;
}
.view-button:hover {
border-color: var(--cyan);
}
.camera-hint {
position: absolute;
left: 26px;
bottom: 22px;
padding: 9px 12px;
border: 1px solid rgba(76, 104, 135, 0.35);
border-radius: 9px;
color: #a9bed2;
background: rgba(8, 17, 28, 0.72);
font-size: 11px;
pointer-events: none;
backdrop-filter: blur(8px);
}
#toast {
position: absolute;
left: 50%;
bottom: 28px;
max-width: min(520px, calc(100% - 40px));
padding: 12px 17px;
border: 1px solid #37516c;
border-radius: 12px;
color: var(--text);
background: rgba(10, 21, 34, 0.94);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.32);
opacity: 0;
transform: translate(-50%, 12px);
transition: opacity 180ms ease, transform 180ms ease;
pointer-events: none;
text-align: center;
font-size: 13px;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good {
border-color: rgba(77, 228, 209, 0.7);
}
#toast.warn {
border-color: rgba(255, 200, 90, 0.75);
}
#panel {
position: relative;
z-index: 2;
overflow-y: auto;
padding: 24px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(20, 34, 51, 0.96), rgba(12, 23, 36, 0.98));
box-shadow: -16px 0 45px rgba(0, 0, 0, 0.2);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 18px;
}
.panel-heading span:first-child {
font-size: 12px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.status-pill {
border: 1px solid #37516a;
border-radius: 999px;
padding: 5px 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-pill.ready {
border-color: rgba(77, 228, 209, 0.6);
color: var(--cyan);
}
.card {
margin-bottom: 14px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(20, 34, 51, 0.72);
}
.card-title {
margin-bottom: 11px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.energy-top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
}
.energy-number {
font-size: 38px;
font-weight: 850;
line-height: 1;
letter-spacing: -0.05em;
}
.energy-capacity {
color: var(--muted);
font-size: 14px;
font-weight: 700;
}
.energy-bar {
height: 9px;
margin: 14px 0 9px;
overflow: hidden;
border-radius: 999px;
background: #08131f;
box-shadow: inset 0 0 0 1px #2a3b4e;
}
#energy-fill {
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #27bfae, #76f2df);
transition: width 240ms ease, background 240ms ease;
}
#energy-fill.low {
background: linear-gradient(90deg, #d94d55, #ff8580);
}
.microcopy {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.brief-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin: 12px 0;
}
.brief-stat {
padding: 10px;
border: 1px solid #2a4057;
border-radius: 10px;
background: #0d1927;
}
.brief-stat strong {
display: block;
color: var(--amber);
font-size: 21px;
line-height: 1;
}
.brief-stat span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.objective {
display: flex;
align-items: flex-start;
gap: 10px;
margin-top: 12px;
font-size: 13px;
line-height: 1.45;
}
.objective-dot {
flex: 0 0 auto;
width: 9px;
height: 9px;
margin-top: 4px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 14px rgba(255, 200, 90, 0.55);
}
.objective.done .objective-dot {
background: var(--cyan);
box-shadow: 0 0 14px rgba(77, 228, 209, 0.55);
}
.preview-box {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 10px 0 12px;
}
.preview-cell {
padding: 10px;
border: 1px solid #2a4057;
border-radius: 10px;
background: #0b1724;
}
.preview-cell.wide {
grid-column: 1 / -1;
}
.preview-cell span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.preview-cell strong {
display: block;
margin-top: 5px;
font-size: 19px;
}
.action {
width: 100%;
border: 0;
border-radius: 10px;
padding: 12px 14px;
color: #06151a;
background: var(--cyan);
cursor: pointer;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.05em;
text-transform: uppercase;
transition: transform 140ms ease, filter 140ms ease, opacity 140ms ease;
}
.action:hover:not(:disabled) {
transform: translateY(-1px);
filter: brightness(1.08);
}
.action:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.action.secondary {
margin-top: 9px;
border: 1px solid #4a647e;
color: var(--text);
background: #192a3d;
}
.action.pulse {
animation: pulse 1.2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { box-shadow: 0 0 0 rgba(77, 228, 209, 0); }
50% { box-shadow: 0 0 24px rgba(77, 228, 209, 0.28); }
}
.log {
min-height: 92px;
}
.log-row {
display: flex;
justify-content: space-between;
gap: 10px;
padding: 6px 0;
border-bottom: 1px solid rgba(48, 68, 89, 0.45);
color: #b8c8d9;
font-size: 11px;
}
.log-row:last-child {
border-bottom: 0;
}
.log-row.good {
color: var(--cyan);
}
.log-row.warn {
color: var(--amber);
}
.panel-footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-top: 16px;
color: var(--muted);
font-size: 11px;
}
.reset-button {
border: 0;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 11px;
font-weight: 800;
text-decoration: underline;
text-underline-offset: 3px;
}
.reset-button:hover {
color: var(--text);
}
#win-overlay {
position: absolute;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
padding: 20px;
background: rgba(4, 10, 17, 0.78);
opacity: 0;
visibility: hidden;
transition: opacity 220ms ease, visibility 220ms ease;
backdrop-filter: blur(8px);
}
#win-overlay.show {
opacity: 1;
visibility: visible;
}
.win-card {
width: min(410px, 100%);
padding: 28px;
border: 1px solid rgba(77, 228, 209, 0.65);
border-radius: 18px;
background: linear-gradient(145deg, #14273a, #0b1623);
box-shadow: 0 24px 90px rgba(0, 0, 0, 0.5);
text-align: center;
}
.win-icon {
display: grid;
place-items: center;
width: 58px;
height: 58px;
margin: 0 auto 15px;
border-radius: 16px;
color: #071619;
background: var(--cyan);
font-size: 27px;
font-weight: 900;
transform: rotate(-5deg);
}
.win-card h2 {
margin: 0;
font-size: 27px;
letter-spacing: -0.035em;
}
.win-card p {
margin: 11px 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
@media (max-width: 820px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 58dvh 42dvh;
}
#panel {
padding: 16px;
border-top: 1px solid var(--line);
border-left: 0;
}
.scene-header {
top: 16px;
left: 16px;
right: 16px;
}
.camera-hint {
left: 16px;
bottom: 14px;
}
.brand small {
display: none;
}
.card {
padding: 14px;
}
}
</style>
</head>
<body>
<main id="app">
<section id="scene-wrap" aria-label="Interactive low-poly robot puzzle">
<canvas id="scene" tabindex="0" aria-label="Puzzle board. Use arrow keys to select adjacent squares."></canvas>
<div class="scene-header">
<div class="brand">
<p class="eyebrow">Low-poly energy puzzle</p>
<h1>RELAY // 08</h1>
<small>Collect the core. Bring it home. Watch your charge.</small>
</div>
<button class="view-button" id="camera-reset" type="button">Reset view</button>
</div>
<div class="camera-hint">DRAG TO ORBIT · SCROLL TO ZOOM · ARROWS TO SELECT</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="win-overlay" aria-hidden="true">
<div class="win-card">
<div class="win-icon">✓</div>
<p class="eyebrow">Mission complete</p>
<h2>Core delivered</h2>
<p id="win-copy">The relay made the impossible round trip possible.</p>
<button class="action" id="play-again" type="button">Run it again</button>
</div>
</div>
</section>
<aside id="panel">
<div class="panel-heading">
<span>Robot telemetry</span>
<span class="status-pill" id="status-pill">Ready</span>
</div>
<section class="card">
<div class="card-title">Available energy</div>
<div class="energy-top">
<div class="energy-number" id="energy-value">12</div>
<div class="energy-capacity" id="energy-capacity">/ 12</div>
</div>
<div class="energy-bar"><div id="energy-fill"></div></div>
<p class="microcopy" id="energy-note">Initial cell charge. The cyan relay can restore up to 20.</p>
</section>
<section class="card">
<div class="card-title">Mission brief</div>
<div class="brief-grid">
<div class="brief-stat">
<strong id="direct-cost">20</strong>
<span>energy for the direct round trip</span>
</div>
<div class="brief-stat">
<strong id="initial-charge">12</strong>
<span>energy available at launch</span>
</div>
</div>
<div class="objective" id="objective">
<span class="objective-dot"></span>
<span id="objective-text">Reach the amber beacon and collect the power core.</span>
</div>
</section>
<section class="card">
<div class="card-title">Move preview — energy shown before action</div>
<div class="preview-box">
<div class="preview-cell wide">
<span>Energy before this move</span>
<strong id="before-energy">—</strong>
</div>
<div class="preview-cell">
<span>Move cost</span>
<strong id="move-cost">—</strong>
</div>
<div class="preview-cell">
<span>Energy after</span>
<strong id="after-energy">—</strong>
</div>
</div>
<button class="action" id="commit-move" type="button" disabled>Select an adjacent tile</button>
<button class="action secondary" id="recharge" type="button" disabled>Stand on relay to recharge</button>
<p class="microcopy" id="control-note">
Click a glowing adjacent tile or use the arrow keys. Press Enter to commit.
</p>
</section>
<section class="card log">
<div class="card-title">Event log</div>
<div id="log-list"></div>
</section>
<div class="panel-footer">
<span id="move-count">0 moves</span>
<button class="reset-button" id="reset-game" type="button">Reset puzzle</button>
</div>
</aside>
</main>
<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.querySelector("#scene");
const sceneWrap = document.querySelector("#scene-wrap");
const toastElement = document.querySelector("#toast");
const winOverlay = document.querySelector("#win-overlay");
const winCopy = document.querySelector("#win-copy");
const ui = {
energyValue: document.querySelector("#energy-value"),
energyCapacity: document.querySelector("#energy-capacity"),
energyFill: document.querySelector("#energy-fill"),
energyNote: document.querySelector("#energy-note"),
directCost: document.querySelector("#direct-cost"),
initialCharge: document.querySelector("#initial-charge"),
objective: document.querySelector("#objective"),
objectiveText: document.querySelector("#objective-text"),
beforeEnergy: document.querySelector("#before-energy"),
moveCost: document.querySelector("#move-cost"),
afterEnergy: document.querySelector("#after-energy"),
commitMove: document.querySelector("#commit-move"),
recharge: document.querySelector("#recharge"),
controlNote: document.querySelector("#control-note"),
statusPill: document.querySelector("#status-pill"),
moveCount: document.querySelector("#move-count"),
logList: document.querySelector("#log-list")
};
const GRID = 8;
const TILE_SPACING = 1.05;
const INITIAL_ENERGY = 12;
const RELAY_ENERGY = 20;
const MOVE_COST = 1;
const START = { x: 1, z: 6 };
const RELAY = { x: 3, z: 3 };
const GOAL = { x: 6, z: 1 };
const obstacles = new Set([
"0,2", "2,6", "4,6", "0,4", "5,4",
"2,2", "4,1", "6,3", "7,5", "3,6"
]);
const state = {
cell: { ...START },
energy: INITIAL_ENERGY,
maxEnergy: INITIAL_ENERGY,
collected: false,
won: false,
moving: false,
recharging: false,
selected: null,
moves: 0,
log: [],
moveFrom: null,
moveTo: null,
moveStart: 0,
moveTarget: null,
rechargeStart: 0
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1724);
scene.fog = new THREE.Fog(0x0b1724, 24, 42);
const camera = new THREE.OrthographicCamera(-8, 8, 8, -8, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const hemisphere = new THREE.HemisphereLight(0xb8e9ff, 0x172235, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d0, 3.2);
sun.position.set(7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0007;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4de4d1, 1.35);
rimLight.position.set(-7, 5, -8);
scene.add(rimLight);
const tiles = [];
const tileMeshes = [];
const highlightGroup = new THREE.Group();
scene.add(highlightGroup);
let robot;
let robotLeftLeg;
let robotRightLeg;
let robotBackpackCrystal;
let goalCrystal;
let goalCrystalBaseY;
let relayRing;
let relayBeam;
let startRing;
const cameraState = {
yaw: 0.72,
pitch: 0.78,
zoom: 1,
distance: 19,
target: new THREE.Vector3(0, 0.25, 0)
};
function gridKey(x, z) {
return `${x},${z}`;
}
function inBounds(x, z) {
return x >= 0 && x < GRID && z >= 0 && z < GRID;
}
function isObstacle(x, z) {
return obstacles.has(gridKey(x, z));
}
function worldFor(x, z, y = 0) {
return new THREE.Vector3(
(x - (GRID - 1) / 2) * TILE_SPACING,
y,
(z - (GRID - 1) / 2) * TILE_SPACING
);
}
function neighbors(x, z) {
return [
{ x: x + 1, z },
{ x: x - 1, z },
{ x, z: z + 1 },
{ x, z: z - 1 }
].filter(cell => inBounds(cell.x, cell.z) && !isObstacle(cell.x, cell.z));
}
function shortestDistance(from, to) {
const queue = [{ ...from, distance: 0 }];
const seen = new Set([gridKey(from.x, from.z)]);
while (queue.length) {
const current = queue.shift();
if (current.x === to.x && current.z === to.z) {
return current.distance;
}
for (const cell of neighbors(current.x, current.z)) {
const key = gridKey(cell.x, cell.z);
if (!seen.has(key)) {
seen.add(key);
queue.push({ ...cell, distance: current.distance + 1 });
}
}
}
return Infinity;
}
function material(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.05,
flatShading: true,
...extra
});
}
function addMesh(parent, geometry, mat, position, rotation = null) {
const mesh = new THREE.Mesh(geometry, mat);
mesh.position.copy(position);
if (rotation) mesh.rotation.set(rotation.x, rotation.y, rotation.z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function buildBoard() {
const boardWidth = GRID * TILE_SPACING + 0.45;
const baseMat = material(0x16283a);
const trimMat = material(0x28475b, {
emissive: 0x123340,
emissiveIntensity: 0.35
});
addMesh(
scene,
new THREE.BoxGeometry(boardWidth, 0.65, boardWidth),
baseMat,
new THREE.Vector3(0, -0.42, 0)
);
addMesh(
scene,
new THREE.BoxGeometry(boardWidth + 0.08, 0.08, boardWidth + 0.08),
trimMat,
new THREE.Vector3(0, -0.31, 0)
);
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
const checker = (x + z) % 2;
const special = gridKey(x, z);
let color = checker ? 0x426477 : 0x36576a;
if (special === gridKey(START.x, START.z)) color = 0x315b78;
if (special === gridKey(RELAY.x, RELAY.z)) color = 0x285c62;
if (special === gridKey(GOAL.x, GOAL.z)) color = 0x66593c;
const tile = addMesh(
scene,
new THREE.BoxGeometry(0.96, 0.17, 0.96),
material(color),
worldFor(x, z, -0.01)
);
tile.userData.grid = { x, z };
tiles.push(tile);
tileMeshes.push(tile);
}
}
buildObstacles();
buildStartDock();
buildRelay();
buildGoal();
buildRobot();
buildEnvironment();
}
function buildObstacles() {
obstacles.forEach(key => {
const [x, z] = key.split(",").map(Number);
const position = worldFor(x, z, 0);
if ((x + z) % 2 === 0) {
const group = new THREE.Group();
group.position.copy(position);
group.rotation.y = (x * 0.31 + z * 0.17) % 1;
addMesh(
group,
new THREE.BoxGeometry(0.64, 0.58, 0.64),
material(0x8b644e),
new THREE.Vector3(0, 0.34, 0)
);
addMesh(
group,
new THREE.BoxGeometry(0.69, 0.09, 0.69),
material(0xb0835e),
new THREE.Vector3(0, 0.43, 0)
);
addMesh(
group,
new THREE.BoxGeometry(0.09, 0.62, 0.69),
material(0x59453c),
new THREE.Vector3(0, 0.34, 0)
);
scene.add(group);
} else {
const rock = addMesh(
scene,
new THREE.DodecahedronGeometry(0.43, 0),
material(0x65758a),
position.clone().add(new THREE.Vector3(0, 0.38, 0))
);
rock.scale.set(1, 1.15, 0.9);
rock.rotation.set(0.2 * x, x * 0.7, 0.15 * z);
}
});
}
function buildStartDock() {
const group = new THREE.Group();
group.position.copy(worldFor(START.x, START.z, 0));
scene.add(group);
addMesh(
group,
new THREE.CylinderGeometry(0.35, 0.4, 0.13, 6),
material(0x2f91cf, {
emissive: 0x123d5d,
emissiveIntensity: 0.6
}),
new THREE.Vector3(0, 0.12, 0)
);
startRing = addMesh(
group,
new THREE.TorusGeometry(0.3, 0.025, 4, 18),
new THREE.MeshBasicMaterial({ color: 0x62c9ff }),
new THREE.Vector3(0, 0.2, 0),
new THREE.Euler(Math.PI / 2, 0, 0)
);
startRing.castShadow = false;
}
function buildRelay() {
const group = new THREE.Group();
group.position.copy(worldFor(RELAY.x, RELAY.z, 0));
scene.add(group);
addMesh(
group,
new THREE.CylinderGeometry(0.36, 0.42, 0.14, 6),
material(0x2c7f7b, {
emissive: 0x0b3e3d,
emissiveIntensity: 0.8
}),
new THREE.Vector3(0, 0.13, 0)
);
addMesh(
group,
new THREE.CylinderGeometry(0.12, 0.18, 0.62, 6),
material(0x4de4d1, {
emissive: 0x1ba99a,
emissiveIntensity: 0.8
}),
new THREE.Vector3(0, 0.48, 0)
);
relayRing = addMesh(
group,
new THREE.TorusGeometry(0.25, 0.035, 5, 18),
new THREE.MeshBasicMaterial({ color: 0x64ffe7 }),
new THREE.Vector3(0, 0.62, 0),
new THREE.Euler(Math.PI / 2, 0, 0)
);
relayRing.castShadow = false;
relayBeam = addMesh(
group,
new THREE.CylinderGeometry(0.08, 0.18, 0.8, 8, 1, true),
new THREE.MeshBasicMaterial({
color: 0x4de4d1,
transparent: true,
opacity: 0.15,
depthWrite: false,
side: THREE.DoubleSide
}),
new THREE.Vector3(0, 0.55, 0)
);
relayBeam.castShadow = false;
}
function buildGoal() {
const group = new THREE.Group();
group.position.copy(worldFor(GOAL.x, GOAL.z, 0));
scene.add(group);
addMesh(
group,
new THREE.CylinderGeometry(0.34, 0.42, 0.16, 6),
material(0x806a3d, {
emissive: 0x403015,
emissiveIntensity: 0.5
}),
new THREE.Vector3(0, 0.14, 0)
);
addMesh(
group,
new THREE.TorusGeometry(0.29, 0.025, 4, 18),
new THREE.MeshBasicMaterial({ color: 0xffc85a }),
new THREE.Vector3(0, 0.24, 0),
new THREE.Euler(Math.PI / 2, 0, 0)
);
goalCrystal = addMesh(
group,
new THREE.OctahedronGeometry(0.28, 0),
material(0xffc85a, {
emissive: 0xb77710,
emissiveIntensity: 1.05,
metalness: 0.15
}),
new THREE.Vector3(0, 0.92, 0)
);
goalCrystalBaseY = goalCrystal.position.y;
}
function buildRobot() {
robot = new THREE.Group();
robot.position.copy(worldFor(START.x, START.z, 0.12));
robot.rotation.y = 0.38;
scene.add(robot);
const dark = material(0x182b3c);
const shell = material(0xd7e2e8);
const accent = material(0xffc85a, {
emissive: 0x7b4d05,
emissiveIntensity: 0.35
});
addMesh(
robot,
new THREE.BoxGeometry(0.42, 0.4, 0.3),
shell,
new THREE.Vector3(0, 0.53, 0)
);
addMesh(
robot,
new THREE.BoxGeometry(0.34, 0.27, 0.29),
dark,
new THREE.Vector3(0, 0.84, 0.015)
);
addMesh(
robot,
new THREE.BoxGeometry(0.27, 0.115, 0.025),
material(0x0a1521),
new THREE.Vector3(0, 0.85, 0.17)
);
const eyeMat = new THREE.MeshBasicMaterial({ color: 0x5dffea });
addMesh(
robot,
new THREE.BoxGeometry(0.065, 0.055, 0.025),
eyeMat,
new THREE.Vector3(-0.065, 0.86, 0.19)
);
addMesh(
robot,
new THREE.BoxGeometry(0.065, 0.055, 0.025),
eyeMat,
new THREE.Vector3(0.065, 0.86, 0.19)
);
addMesh(
robot,
new THREE.CylinderGeometry(0.018, 0.018, 0.2, 6),
dark,
new THREE.Vector3(0, 1.06, 0)
);
addMesh(
robot,
new THREE.OctahedronGeometry(0.065, 0),
accent,
new THREE.Vector3(0, 1.19, 0)
);
addMesh(
robot,
new THREE.BoxGeometry(0.1, 0.28, 0.12),
dark,
new THREE.Vector3(-0.27, 0.51, 0)
);
addMesh(
robot,
new THREE.BoxGeometry(0.1, 0.28, 0.12),
dark,
new THREE.Vector3(0.27, 0.51, 0)
);
robotLeftLeg = addMesh(
robot,
new THREE.BoxGeometry(0.13, 0.28, 0.15),
dark,
new THREE.Vector3(-0.12, 0.2, 0)
);
robotRightLeg = addMesh(
robot,
new THREE.BoxGeometry(0.13, 0.28, 0.15),
dark,
new THREE.Vector3(0.12, 0.2, 0)
);
addMesh(
robot,
new THREE.BoxGeometry(0.3, 0.24, 0.14),
accent,
new THREE.Vector3(0, 0.57, -0.22)
);
robotBackpackCrystal = addMesh(
robot,
new THREE.OctahedronGeometry(0.13, 0),
material(0xffc85a, {
emissive: 0xa86208,
emissiveIntensity: 1
}),
new THREE.Vector3(0, 0.61, -0.34)
);
robotBackpackCrystal.visible = false;
}
function buildEnvironment() {
const trunkMat = material(0x5c4639);
const leafMat = material(0x2f7568);
const leafMat2 = material(0x3d8a72);
const treePositions = [
[-5.6, -4.7, 0.95], [-5.9, 3.7, 0.72], [5.4, -4.8, 0.82],
[5.8, 3.8, 1.05], [-4.8, 5.4, 0.7], [4.8, 5.4, 0.75]
];
treePositions.forEach(([x, z, scale], index) => {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
scene.add(tree);
addMesh(
tree,
new THREE.CylinderGeometry(0.12, 0.17, 0.8, 6),
trunkMat,
new THREE.Vector3(0, 0.15, 0)
);
addMesh(
tree,
new THREE.ConeGeometry(0.5, 1.2, 6),
index % 2 ? leafMat : leafMat2,
new THREE.Vector3(0, 0.95, 0)
);
addMesh(
tree,
new THREE.ConeGeometry(0.36, 0.9, 6),
index % 2 ? leafMat2 : leafMat,
new THREE.Vector3(0, 1.4, 0)
);
});
const rockMat = material(0x30475b);
[
[-5.1, 0.4], [5.1, 0.1], [-2.7, -5.2], [2.6, 5.1]
].forEach(([x, z]) => {
const rock = addMesh(
scene,
new THREE.DodecahedronGeometry(0.42, 0),
rockMat,
new THREE.Vector3(x, 0.28, z)
);
rock.scale.set(1.2, 0.75, 0.9);
rock.rotation.set(0.3, x, 0.1);
});
}
function clearHighlights() {
while (highlightGroup.children.length) {
const child = highlightGroup.children.pop();
child.geometry?.dispose();
child.material?.dispose();
}
}
function refreshHighlights() {
clearHighlights();
if (state.moving || state.recharging || state.won) return;
for (const cell of neighbors(state.cell.x, state.cell.z)) {
const selected = state.selected &&
state.selected.x === cell.x &&
state.selected.z === cell.z;
const marker = new THREE.Mesh(
new THREE.PlaneGeometry(selected ? 0.79 : 0.7, selected ? 0.79 : 0.7),
new THREE.MeshBasicMaterial({
color: selected ? 0xffc85a : 0x4de4d1,
transparent: true,
opacity: selected ? 0.62 : 0.22,
depthWrite: false,
side: THREE.DoubleSide
})
);
marker.rotation.x = -Math.PI / 2;
marker.position.copy(worldFor(cell.x, cell.z, 0.082));
marker.userData.grid = cell;
highlightGroup.add(marker);
}
}
function selectCell(x, z) {
if (state.moving || state.recharging || state.won) return;
if (!inBounds(x, z) || isObstacle(x, z)) {
showToast("That square is blocked.", "warn");
return;
}
const adjacent = Math.abs(x - state.cell.x) + Math.abs(z - state.cell.z) === 1;
if (!adjacent) {
showToast("Move one square at a time. Select a glowing adjacent tile.", "warn");
return;
}
state.selected = { x, z };
refreshHighlights();
updateUI();
}
function commitMove() {
if (!state.selected || state.moving || state.recharging || state.won) return;
if (state.energy < MOVE_COST) {
showToast("Not enough energy. Stand on the relay or reset the puzzle.", "warn");
return;
}
const target = { ...state.selected };
const before = state.energy;
state.energy -= MOVE_COST;
state.moves += 1;
state.moving = true;
state.moveFrom = robot.position.clone();
state.moveTo = worldFor(target.x, target.z, 0.12);
state.moveTarget = target;
state.moveStart = performance.now();
state.selected = null;
addLog(`Move (${target.x}, ${target.z}): ${before} → ${state.energy}`);
refreshHighlights();
updateUI();
}
function arriveAtCell() {
const target = state.moveTarget;
state.cell = { ...target };
if (
state.cell.x === GOAL.x &&
state.cell.z === GOAL.z &&
!state.collected
) {
state.collected = true;
goalCrystal.visible = false;
robotBackpackCrystal.visible = true;
showToast("Power core collected. Return it to the blue home dock.", "good");
addLog("Core collected at the amber beacon.", "good");
} else if (
state.cell.x === START.x &&
state.cell.z === START.z &&
state.collected
) {
winGame();
} else if (
state.cell.x === RELAY.x &&
state.cell.z === RELAY.z
) {
showToast("Relay reached. Recharge before attempting the return leg.", "good");
addLog("Robot is standing on the cyan relay.", "good");
} else if (state.energy === 0) {
showToast("Energy depleted away from the relay. Reset to try again.", "warn");
addLog("Energy depleted away from the relay.", "warn");
}
updateUI();
}
function recharge() {
if (
state.recharging ||
state.moving ||
state.won ||
state.cell.x !== RELAY.x ||
state.cell.z !== RELAY.z ||
state.energy >= RELAY_ENERGY
) {
return;
}
const before = state.energy;
state.recharging = true;
state.rechargeStart = performance.now();
refreshHighlights();
updateUI();
showToast("Relay charging…", "good");
addLog(`Relay started: ${before} energy before recharge.`, "good");
}
function finishRecharge() {
const before = state.energy;
state.energy = RELAY_ENERGY;
state.maxEnergy = RELAY_ENERGY;
state.recharging = false;
addLog(`Relay complete: ${before} → ${state.energy}.`, "good");
showToast("Fully charged. The remaining route now fits.", "good");
updateUI();
}
function winGame() {
state.won = true;
winCopy.textContent =
`The core is home in ${state.moves} moves. ` +
`The relay supplied ${state.maxEnergy - INITIAL_ENERGY} extra energy and broke the direct-loop deficit.`;
winOverlay.classList.add("show");
winOverlay.setAttribute("aria-hidden", "false");
addLog("Core delivered. Mission complete!", "good");
updateUI();
}
function resetGame() {
state.cell = { ...START };
state.energy = INITIAL_ENERGY;
state.maxEnergy = INITIAL_ENERGY;
state.collected = false;
state.won = false;
state.moving = false;
state.recharging = false;
state.selected = null;
state.moves = 0;
state.log = [];
robot.position.copy(worldFor(START.x, START.z, 0.12));
robot.rotation.set(0, 0.38, 0);
robotBackpackCrystal.visible = false;
goalCrystal.visible = true;
winOverlay.classList.remove("show");
winOverlay.setAttribute("aria-hidden", "true");
addLog(`Direct round trip needs ${shortestDistance(START, GOAL) * 2} energy; launch charge is ${INITIAL_ENERGY}.`, "warn");
refreshHighlights();
updateUI();
showToast("New mission loaded. Find a safe route through the relay.", "good");
}
function addLog(text, tone = "") {
state.log.unshift({ text, tone });
state.log = state.log.slice(0, 7);
renderLog();
}
function renderLog() {
ui.logList.innerHTML = "";
if (!state.log.length) {
const row = document.createElement("div");
row.className = "log-row";
row.innerHTML = `<span>Waiting for robot activity…</span>`;
ui.logList.appendChild(row);
return;
}
state.log.forEach(entry => {
const row = document.createElement("div");
row.className = `log-row ${entry.tone}`;
const text = document.createElement("span");
text.textContent = entry.text;
row.appendChild(text);
ui.logList.appendChild(row);
});
}
function updateUI() {
ui.energyValue.textContent = state.energy;
ui.energyCapacity.textContent = `/ ${state.maxEnergy}`;
ui.energyFill.style.width = `${(state.energy / RELAY_ENERGY) * 100}%`;
ui.energyFill.classList.toggle("low", state.energy <= 3);
ui.energyNote.textContent = state.maxEnergy === INITIAL_ENERGY
? "Initial cell charge. The cyan relay can restore up to 20."
: "Relay output active. Maximum charge is 20 energy.";
ui.moveCount.textContent = `${state.moves} ${state.moves === 1 ? "move" : "moves"}`;
if (state.collected) {
ui.objective.classList.add("done");
ui.objectiveText.textContent = "Return the power core to the blue home dock.";
} else {
ui.objective.classList.remove("done");
ui.objectiveText.textContent = "Reach the amber beacon and collect the power core.";
}
if (state.selected) {
const after = Math.max(0, state.energy - MOVE_COST);
ui.beforeEnergy.textContent = `${state.energy} energy`;
ui.moveCost.textContent = `${MOVE_COST} energy`;
ui.afterEnergy.textContent = `${after} energy`;
ui.commitMove.disabled = state.moving || state.recharging || state.won || state.energy < MOVE_COST;
ui.commitMove.textContent = `Commit move — use ${state.energy} energy`;
} else {
ui.beforeEnergy.textContent = "—";
ui.moveCost.textContent = "—";
ui.afterEnergy.textContent = "—";
ui.commitMove.disabled = true;
ui.commitMove.textContent = state.moving
? "Robot moving…"
: state.recharging
? "Recharging…"
: "Select an adjacent tile";
}
const onRelay = state.cell.x === RELAY.x && state.cell.z === RELAY.z;
const canRecharge = onRelay && !state.recharging && !state.moving && !state.won && state.energy < RELAY_ENERGY;
ui.recharge.disabled = !canRecharge;
ui.recharge.classList.toggle("pulse", canRecharge);
ui.recharge.textContent = state.recharging
? "Relay charging…"
: onRelay
? state.energy >= RELAY_ENERGY
? "Relay fully charged"
: `Recharge to ${RELAY_ENERGY} energy`
: "Stand on relay to recharge";
if (state.won) {
ui.statusPill.textContent = "Complete";
ui.statusPill.classList.add("ready");
ui.controlNote.textContent = "Mission complete. Reset to try a shorter route.";
} else if (state.recharging) {
ui.statusPill.textContent = "Charging";
ui.statusPill.classList.add("ready");
ui.controlNote.textContent = "The relay is restoring the robot to 20 energy.";
} else if (onRelay) {
ui.statusPill.textContent = "On relay";
ui.statusPill.classList.add("ready");
ui.controlNote.textContent = "The relay is beneath the robot. Use the recharge button before leaving.";
} else if (state.energy <= 3) {
ui.statusPill.textContent = "Low charge";
ui.statusPill.classList.remove("ready");
ui.controlNote.textContent = "Low energy. Avoid committing a move that strands the robot away from the relay.";
} else {
ui.statusPill.textContent = state.collected ? "Returning" : "Searching";
ui.statusPill.classList.remove("ready");
ui.controlNote.textContent = "Click a glowing adjacent tile or use the arrow keys. Press Enter to commit.";
}
}
let toastTimer = 0;
function showToast(message, tone = "") {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.className = `show ${tone}`;
toastTimer = window.setTimeout(() => {
toastElement.className = "";
}, 2800);
}
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.distance;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.yaw = 0.72;
cameraState.pitch = 0.78;
cameraState.zoom = 1;
updateCamera();
}
function resize() {
const width = Math.max(1, sceneWrap.clientWidth);
const height = Math.max(1, sceneWrap.clientHeight);
const aspect = width / height;
const halfHeight = Math.max(5.8, 6.6 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickCell(event) {
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 hits = raycaster.intersectObjects(tileMeshes, false);
return hits.length ? hits[0].object.userData.grid : null;
}
const pointerState = {
down: false,
id: null,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
canvas.addEventListener("pointerdown", event => {
pointerState.down = true;
pointerState.id = event.pointerId;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = false;
canvas.setPointerCapture(event.pointerId);
canvas.focus();
});
canvas.addEventListener("pointermove", event => {
if (!pointerState.down || pointerState.id !== event.pointerId) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
if (
Math.abs(event.clientX - pointerState.startX) +
Math.abs(event.clientY - pointerState.startY) > 5
) {
pointerState.moved = true;
}
if (pointerState.moved) {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.42,
1.25
);
updateCamera();
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
});
canvas.addEventListener("pointerup", event => {
if (!pointerState.down || pointerState.id !== event.pointerId) return;
if (!pointerState.moved) {
const cell = pickCell(event);
if (cell) selectCell(cell.x, cell.z);
}
pointerState.down = false;
pointerState.id = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
pointerState.down = false;
pointerState.id = null;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.85
);
updateCamera();
}, { passive: false });
canvas.addEventListener("contextmenu", event => event.preventDefault());
window.addEventListener("keydown", event => {
if (state.won) return;
const directions = {
ArrowUp: { x: 0, z: -1 },
ArrowDown: { x: 0, z: 1 },
ArrowLeft: { x: -1, z: 0 },
ArrowRight: { x: 1, z: 0 }
};
if (directions[event.key]) {
event.preventDefault();
const direction = directions[event.key];
selectCell(state.cell.x + direction.x, state.cell.z + direction.z);
} else if (event.key === "Enter") {
event.preventDefault();
commitMove();
} else if (event.key.toLowerCase() === "r") {
event.preventDefault();
recharge();
}
});
ui.commitMove.addEventListener("click", commitMove);
ui.recharge.addEventListener("click", recharge);
document.querySelector("#reset-game").addEventListener("click", resetGame);
document.querySelector("#play-again").addEventListener("click", resetGame);
document.querySelector("#camera-reset").addEventListener("click", resetCamera);
function easeInOutCubic(value) {
return value < 0.5
? 4 * value * value * value
: 1 - Math.pow(-2 * value + 2, 3) / 2;
}
function shortestAngle(from, to) {
let delta = (to - from + Math.PI) % (Math.PI * 2) - Math.PI;
if (delta < -Math.PI) delta += Math.PI * 2;
return delta;
}
function animate(now) {
requestAnimationFrame(animate);
if (state.moving) {
const duration = 430;
const t = THREE.MathUtils.clamp((now - state.moveStart) / duration, 0, 1);
const eased = easeInOutCubic(t);
robot.position.x = THREE.MathUtils.lerp(state.moveFrom.x, state.moveTo.x, eased);
robot.position.z = THREE.MathUtils.lerp(state.moveFrom.z, state.moveTo.z, eased);
robot.position.y = 0.12 + Math.sin(t * Math.PI) * 0.08;
const dx = state.moveTo.x - state.moveFrom.x;
const dz = state.moveTo.z - state.moveFrom.z;
const targetRotation = Math.atan2(dx, dz);
robot.rotation.y += shortestAngle(robot.rotation.y, targetRotation) * 0.22;
const stride = Math.sin(t * Math.PI * 4) * 0.32;
robotLeftLeg.rotation.x = stride;
robotRightLeg.rotation.x = -stride;
if (t >= 1) {
state.moving = false;
robot.position.copy(state.moveTo);
robotLeftLeg.rotation.x = 0;
robotRightLeg.rotation.x = 0;
arriveAtCell();
refreshHighlights();
}
} else {
robotLeftLeg.rotation.x *= 0.82;
robotRightLeg.rotation.x *= 0.82;
}
if (state.recharging && now - state.rechargeStart >= 950) {
finishRecharge();
}
if (goalCrystal.visible) {
goalCrystal.rotation.y = now * 0.0012;
goalCrystal.position.y = goalCrystalBaseY + Math.sin(now * 0.003) * 0.07;
}
if (relayRing) {
relayRing.rotation.z = now * 0.0018;
relayBeam.material.opacity = 0.12 + Math.sin(now * 0.005) * 0.06;
relayBeam.scale.y = 0.9 + Math.sin(now * 0.003) * 0.12;
}
if (startRing) {
startRing.rotation.z = -now * 0.0008;
const pulse = 1 + Math.sin(now * 0.0025) * 0.08;
startRing.scale.set(pulse, pulse, pulse);
}
if (robotBackpackCrystal.visible) {
robotBackpackCrystal.rotation.y = now * 0.004;
}
renderer.render(scene, camera);
}
buildBoard();
resize();
new ResizeObserver(resize).observe(sceneWrap);
const directCost = shortestDistance(START, GOAL) * 2;
ui.directCost.textContent = directCost;
ui.initialCharge.textContent = INITIAL_ENERGY;
addLog(`Direct round trip needs ${directCost} energy; launch charge is ${INITIAL_ENERGY}.`, "warn");
updateUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```