Prompt specification
Build or customize the Three.js 3D scene "Three-Block Exit Lock" 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: Three-Block Exit Lock
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/three-block-exit-lock-x3502
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: three-block exit lock. Create a compact sliding puzzle with differently oriented tracks and one exit piece. Legal moves must follow actual clearances rather than passing blocks through each other.
Working Three.js Starter (three-block-exit-lock-x3502):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three-Block Exit Lock</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 21, 37, 0.86);
--line: rgba(149, 205, 226, 0.2);
--text: #eaf7ff;
--muted: #90aabd;
--cyan: #60ddff;
--mint: #63ffc6;
--amber: #ffbf55;
--coral: #ff617c;
}
* {
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;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 42%, transparent 35%, rgba(2, 7, 15, 0.42) 100%),
linear-gradient(180deg, rgba(2, 8, 16, 0.12), transparent 28%, rgba(2, 8, 16, 0.3));
z-index: 2;
}
.ui {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
}
.panel {
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
#hud {
position: absolute;
top: 22px;
left: 22px;
width: min(360px, calc(100vw - 44px));
padding: 20px 21px 18px;
border-radius: 18px;
pointer-events: auto;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 8px 0 9px;
font-size: clamp(25px, 4vw, 36px);
line-height: 0.98;
letter-spacing: -0.045em;
text-transform: uppercase;
}
h1 span {
display: block;
color: var(--muted);
font-size: 0.54em;
letter-spacing: 0.14em;
margin-bottom: 7px;
}
#description {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.lock-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 16px;
}
.lock-chip {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
color: #7f96a8;
background: rgba(255, 255, 255, 0.025);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
transition: 180ms ease;
}
.lock-chip i {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--chip-color);
box-shadow: 0 0 0 transparent;
transition: 180ms ease;
}
.lock-chip.open {
color: #d9fff1;
border-color: color-mix(in srgb, var(--chip-color), transparent 45%);
background: color-mix(in srgb, var(--chip-color), transparent 91%);
}
.lock-chip.open i {
box-shadow: 0 0 12px var(--chip-color);
}
.mini-help {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
color: #7890a4;
font-size: 10px;
line-height: 1.55;
}
#stats {
position: absolute;
top: 22px;
right: 22px;
min-width: 170px;
padding: 14px 16px;
border-radius: 14px;
pointer-events: auto;
}
.stat-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.stat-row + .stat-row {
margin-top: 8px;
}
.stat-row strong {
color: var(--text);
font-size: 12px;
letter-spacing: 0;
}
#gate-state {
color: var(--amber);
}
#dock {
position: absolute;
left: 50%;
bottom: 22px;
width: min(610px, calc(100vw - 30px));
transform: translateX(-50%);
padding: 13px 14px;
border-radius: 18px;
pointer-events: auto;
}
.dock-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
}
.selected {
min-width: 145px;
}
.selected small {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#selected-name {
font-size: 14px;
font-weight: 800;
letter-spacing: 0.02em;
}
.pad {
display: grid;
grid-template-columns: repeat(3, 42px);
grid-template-rows: repeat(2, 38px);
gap: 5px;
}
.pad button {
grid-row: 2;
grid-column: 2;
}
.pad [data-dir="up"] {
grid-row: 1;
}
.pad [data-dir="left"] {
grid-column: 1;
}
.pad [data-dir="down"] {
grid-column: 2;
}
.pad [data-dir="right"] {
grid-column: 3;
}
.icon-button,
.action-button {
border: 1px solid rgba(255, 255, 255, 0.12);
color: var(--text);
background: rgba(255, 255, 255, 0.055);
cursor: pointer;
transition: 140ms ease;
}
.icon-button {
border-radius: 10px;
font-size: 17px;
}
.icon-button:hover:not(:disabled),
.action-button:hover {
background: rgba(96, 221, 255, 0.14);
border-color: rgba(96, 221, 255, 0.45);
transform: translateY(-1px);
}
button:disabled {
cursor: default;
opacity: 0.25;
}
.dock-actions {
display: flex;
gap: 7px;
}
.action-button {
min-height: 38px;
padding: 0 12px;
border-radius: 10px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#hint {
color: #d8f7ff;
}
#reset-camera {
position: absolute;
right: 22px;
bottom: 22px;
width: 42px;
height: 42px;
border-radius: 12px;
pointer-events: auto;
}
#toast {
position: absolute;
left: 50%;
top: 22px;
max-width: min(520px, calc(100vw - 40px));
padding: 11px 15px;
border: 1px solid rgba(96, 221, 255, 0.25);
border-radius: 999px;
background: rgba(7, 17, 31, 0.9);
color: #dff8ff;
font-size: 11px;
font-weight: 700;
text-align: center;
opacity: 0;
transform: translate(-50%, -12px);
transition: 180ms ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.win {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: rgba(3, 9, 17, 0.58);
backdrop-filter: blur(8px);
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: 220ms ease;
}
.win.show {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
.win-card {
width: min(390px, calc(100vw - 36px));
padding: 28px;
border: 1px solid rgba(99, 255, 198, 0.35);
border-radius: 22px;
background: #091625;
box-shadow: 0 30px 100px rgba(0, 0, 0, 0.5);
text-align: center;
transform: translateY(10px) scale(0.98);
transition: 220ms ease;
}
.win.show .win-card {
transform: none;
}
.win-icon {
color: var(--mint);
font-size: 42px;
line-height: 1;
}
.win h2 {
margin: 12px 0 8px;
font-size: 31px;
letter-spacing: -0.04em;
text-transform: uppercase;
}
.win p {
margin: 0 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.6;
}
#play-again {
width: 100%;
min-height: 45px;
border-radius: 12px;
color: #062119;
background: var(--mint);
border: 0;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
}
@media (max-width: 720px) {
#hud {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 15px 16px;
}
#description,
.mini-help {
display: none;
}
h1 {
font-size: 25px;
margin-bottom: 0;
}
.lock-row {
margin-top: 12px;
}
#stats {
top: auto;
right: 12px;
bottom: 112px;
min-width: 140px;
padding: 10px 12px;
}
#dock {
bottom: 12px;
padding: 10px;
}
.dock-main {
gap: 8px;
}
.selected {
min-width: 104px;
}
#selected-name {
font-size: 12px;
}
.action-button {
padding: 0 9px;
font-size: 9px;
}
#reset-camera {
right: 12px;
bottom: 112px;
display: none;
}
}
@media (max-width: 460px) {
#stats {
display: none;
}
.dock-actions {
flex-direction: column;
}
.action-button {
min-height: 30px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel sliding puzzle"></canvas>
<div class="vignette"></div>
<div class="ui">
<section id="hud" class="panel">
<div class="eyebrow">Voxel clearance puzzle</div>
<h1><span>Three-Block</span>Exit Lock</h1>
<p id="description">
Send the coral exit key through the east gate. Every slide checks the
full swept path, so no block can pass through another.
</p>
<div class="lock-row">
<div class="lock-chip" id="lock-amber" style="--chip-color:#ffbf55">
<i></i><span>AMBER</span>
</div>
<div class="lock-chip" id="lock-blue" style="--chip-color:#60a5ff">
<i></i><span>BLUE</span>
</div>
<div class="lock-chip" id="lock-teal" style="--chip-color:#48dfca">
<i></i><span>TEAL</span>
</div>
</div>
<div class="mini-help">
Click a block, then use the arrow buttons. You can also drag a block
along its rail. Drag empty space to orbit; scroll to zoom.
</div>
</section>
<section id="stats" class="panel">
<div class="stat-row">
<span>Shifts</span>
<strong id="move-count">0</strong>
</div>
<div class="stat-row">
<span>East gate</span>
<strong id="gate-state">Locked</strong>
</div>
<div class="stat-row">
<span>Best route</span>
<strong>10 shifts</strong>
</div>
</section>
<section id="dock" class="panel">
<div class="dock-main">
<div class="selected">
<small>Selected block</small>
<div id="selected-name">Coral Exit</div>
</div>
<div class="pad" aria-label="Movement controls">
<button class="icon-button" data-dir="up" aria-label="Move up">▲</button>
<button class="icon-button" data-dir="left" aria-label="Move left">◀</button>
<button class="icon-button" data-dir="down" aria-label="Move down">▼</button>
<button class="icon-button" data-dir="right" aria-label="Move right">▶</button>
</div>
<div class="dock-actions">
<button id="hint" class="action-button">Hint</button>
<button id="restart" class="action-button">Restart</button>
</div>
</div>
</section>
<button id="reset-camera" class="icon-button" aria-label="Reset camera">
⤾
</button>
<div id="toast" role="status" aria-live="polite"></div>
</div>
<div id="win" class="win">
<div class="win-card">
<div class="win-icon">✦</div>
<h2>Unlocked</h2>
<p>
The exit key cleared the east gate in <strong id="final-moves">0</strong>
shifts. Every block stayed on its own rail.
</p>
<button id="play-again">Run It Again</button>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle state
// -------------------------------------------------------------------------
const GRID = 5;
const HALF = (GRID - 1) / 2;
const FIXED_STUD = { x: 2, z: 4 };
const pieces = [
{
id: "exit",
name: "Coral Exit",
color: 0xff617c,
direction: "x",
length: 2,
anchor: { x: 0, z: 2 },
initial: { x: 0, z: 2 },
moved: false
},
{
id: "amber",
name: "Amber Block",
color: 0xffbf55,
direction: "z",
length: 2,
anchor: { x: 2, z: 2 },
initial: { x: 2, z: 2 },
moved: false
},
{
id: "blue",
name: "Blue Block",
color: 0x60a5ff,
direction: "x",
length: 2,
anchor: { x: 1, z: 0 },
initial: { x: 1, z: 0 },
moved: false
},
{
id: "teal",
name: "Teal Block",
color: 0x48dfca,
direction: "z",
length: 2,
anchor: { x: 4, z: 0 },
initial: { x: 4, z: 0 },
moved: false
}
];
const pieceById = Object.fromEntries(pieces.map((piece) => [piece.id, piece]));
let selectedId = "exit";
let moveCount = 0;
let solved = false;
let toastTimer = 0;
let winTimer = 0;
function offsetsFor(piece) {
const offsets = [];
for (let i = 0; i < piece.length; i++) {
offsets.push(
piece.direction === "x"
? { x: i, z: 0 }
: { x: 0, z: i }
);
}
return offsets;
}
pieces.forEach((piece) => {
piece.offsets = offsetsFor(piece);
});
function currentStates() {
return Object.fromEntries(
pieces.map((piece) => [piece.id, { ...piece.anchor }])
);
}
function cellsFor(piece, anchor) {
return piece.offsets.map((offset) => ({
x: anchor.x + offset.x,
z: anchor.z + offset.z
}));
}
function buildOccupancy(states, excludedId = null) {
const occupancy = new Map();
for (const piece of pieces) {
if (piece.id === excludedId) continue;
const anchor = states[piece.id];
for (const cell of cellsFor(piece, anchor)) {
if (
cell.x >= 0 && cell.x < GRID &&
cell.z >= 0 && cell.z < GRID
) {
occupancy.set(`${cell.x},${cell.z}`, piece.id);
}
}
}
occupancy.set(`${FIXED_STUD.x},${FIXED_STUD.z}`, "stud");
return occupancy;
}
/**
* Checks the complete swept path one grid cell at a time.
* The moving piece is removed from occupancy, while all other pieces and
* the fixed steel stud remain solid.
*/
function canMoveTo(id, target, states = currentStates()) {
const piece = pieceById[id];
const current = states[id];
if (!piece || !target) return false;
if (target.x !== current.x && target.z !== current.z) return false;
const axis = piece.direction;
const start = axis === "x" ? current.x : current.z;
const end = axis === "x" ? target.x : target.z;
if (!Number.isInteger(start) || !Number.isInteger(end)) return false;
if (axis === "x" && target.z !== current.z) return false;
if (axis === "z" && target.x !== current.x) return false;
const step = Math.sign(end - start);
if (step === 0) return true;
const occupancy = buildOccupancy(states, id);
const exiting = id === "exit" && axis === "x" && end === 5;
for (let position = start + step; ; position += step) {
const probe = {
x: axis === "x" ? position : current.x,
z: axis === "z" ? position : current.z
};
for (const cell of cellsFor(piece, probe)) {
const outside = cell.x < 0 || cell.x >= GRID ||
cell.z < 0 || cell.z >= GRID;
if (outside && !exiting) return false;
if (
cell.x >= 0 && cell.x < GRID &&
cell.z >= 0 && cell.z < GRID &&
occupancy.has(`${cell.x},${cell.z}`)
) {
return false;
}
}
if (position === end) break;
}
return true;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.FogExp2(0x07111f, 0.042);
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 100);
const orbit = {
theta: 0.72,
phi: 0.79,
radius: 10.7
};
function updateCamera() {
camera.position.setFromSphericalCoords(
orbit.radius,
orbit.phi,
orbit.theta
);
camera.lookAt(0, 0.15, 0);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb9eaff, 0x132034, 2.05);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(4.5, 9, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x39bfff, 16, 15, 2);
rimLight.position.set(-4, 4, -4);
scene.add(rimLight);
const exitLight = new THREE.PointLight(0xff4569, 8, 8, 2);
exitLight.position.set(-1.8, 1.4, 0);
scene.add(exitLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x07111d,
roughness: 0.94,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.51;
floor.receiveShadow = true;
scene.add(floor);
const boardBase = new THREE.Mesh(
new THREE.BoxGeometry(5.65, 0.42, 5.65),
new THREE.MeshStandardMaterial({
color: 0x12263a,
roughness: 0.72,
metalness: 0.28
})
);
boardBase.position.y = -0.27;
boardBase.castShadow = true;
boardBase.receiveShadow = true;
scene.add(boardBase);
const lowerBase = new THREE.Mesh(
new THREE.BoxGeometry(5.25, 0.22, 5.25),
new THREE.MeshStandardMaterial({
color: 0x0a1727,
roughness: 0.85,
metalness: 0.18
})
);
lowerBase.position.y = -0.57;
lowerBase.castShadow = true;
lowerBase.receiveShadow = true;
scene.add(lowerBase);
const tileGeometry = new THREE.BoxGeometry(0.92, 0.12, 0.92);
const tileMaterials = [
new THREE.MeshStandardMaterial({
color: 0x18334a,
roughness: 0.82,
metalness: 0.14
}),
new THREE.MeshStandardMaterial({
color: 0x163047,
roughness: 0.84,
metalness: 0.12
})
];
for (let z = 0; z < GRID; z++) {
for (let x = 0; x < GRID; x++) {
const tile = new THREE.Mesh(
tileGeometry,
tileMaterials[(x + z) % 2]
);
tile.position.set(x - HALF, 0, z - HALF);
tile.receiveShadow = true;
scene.add(tile);
}
}
const edgeMaterial = new THREE.MeshStandardMaterial({
color: 0x31526b,
roughness: 0.42,
metalness: 0.55
});
const edgeGeometryHorizontal = new THREE.BoxGeometry(5.62, 0.23, 0.09);
const edgeGeometryVertical = new THREE.BoxGeometry(0.09, 0.23, 5.62);
for (const z of [-2.82, 2.82]) {
const edge = new THREE.Mesh(edgeGeometryHorizontal, edgeMaterial);
edge.position.set(0, -0.03, z);
edge.castShadow = true;
scene.add(edge);
}
for (const x of [-2.82, 2.82]) {
const edge = new THREE.Mesh(edgeGeometryVertical, edgeMaterial);
edge.position.set(x, -0.03, 0);
edge.castShadow = true;
scene.add(edge);
}
function addTrack(direction, lane, color, opacity = 0.42) {
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.22,
transparent: true,
opacity,
roughness: 0.45,
metalness: 0.4
});
if (direction === "x") {
for (const offset of [-0.29, 0.29]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(5.04, 0.026, 0.035),
material
);
rail.position.set(0, 0.076, lane - HALF + offset);
scene.add(rail);
}
} else {
for (const offset of [-0.29, 0.29]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.026, 5.04),
material
);
rail.position.set(lane - HALF + offset, 0.076, 0);
scene.add(rail);
}
}
}
addTrack("x", 2, 0xffbf55, 0.48);
addTrack("x", 0, 0x60a5ff, 0.30);
addTrack("z", 2, 0xffbf55, 0.30);
addTrack("z", 4, 0x48dfca, 0.30);
// Fixed steel stud. It is a permanent occupancy cell, not a movable block.
const stud = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.58, 0.58),
new THREE.MeshStandardMaterial({
color: 0x8294a1,
emissive: 0x263b49,
emissiveIntensity: 0.35,
roughness: 0.3,
metalness: 0.82
})
);
stud.position.set(
FIXED_STUD.x - HALF,
0.36,
FIXED_STUD.z - HALF
);
stud.castShadow = true;
stud.receiveShadow = true;
scene.add(stud);
const studTop = new THREE.Mesh(
new THREE.BoxGeometry(0.26, 0.035, 0.26),
new THREE.MeshStandardMaterial({
color: 0xdcecf2,
roughness: 0.3,
metalness: 0.75
})
);
studTop.position.set(stud.position.x, 0.665, stud.position.z);
scene.add(studTop);
function pieceCenter(anchor, piece) {
if (piece.direction === "x") {
return new THREE.Vector3(
anchor.x + 0.5 - HALF,
0.34,
anchor.z - HALF
);
}
return new THREE.Vector3(
anchor.x - HALF,
0.34,
anchor.z + 0.5 - HALF
);
}
function addVoxelArrow(group, direction, material, doubleEnded = false) {
const arrow = new THREE.Group();
const cube = new THREE.BoxGeometry(0.105, 0.075, 0.105);
const addCube = (x, z) => {
const mesh = new THREE.Mesh(cube, material);
mesh.position.set(x, 0.29, z);
mesh.castShadow = true;
arrow.add(mesh);
};
addCube(-0.08, 0);
addCube(0.17, 0);
addCube(0.06, 0.12);
addCube(0.06, -0.12);
if (doubleEnded) {
addCube(-0.17, 0);
addCube(-0.06, 0.12);
addCube(-0.06, -0.12);
}
if (direction === "z") arrow.rotation.y = -Math.PI / 2;
group.add(arrow);
}
const pickables = [];
for (const piece of pieces) {
const group = new THREE.Group();
group.position.copy(pieceCenter(piece.anchor, piece));
const bodyMaterial = new THREE.MeshStandardMaterial({
color: piece.color,
emissive: new THREE.Color(piece.color).multiplyScalar(0.11),
emissiveIntensity: 0.18,
roughness: 0.34,
metalness: 0.24
});
const capMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(piece.color).lerp(new THREE.Color(0xffffff), 0.24),
emissive: new THREE.Color(piece.color).multiplyScalar(0.07),
emissiveIntensity: 0.15,
roughness: 0.28,
metalness: 0.3
});
piece.material = bodyMaterial;
const blockGeometry = new THREE.BoxGeometry(0.78, 0.42, 0.78);
const capGeometry = new THREE.BoxGeometry(0.61, 0.065, 0.61);
piece.offsets.forEach((offset) => {
const localX = piece.direction === "x"
? offset.x - 0.5
: 0;
const localZ = piece.direction === "z"
? offset.z - 0.5
: 0;
const block = new THREE.Mesh(blockGeometry, bodyMaterial);
block.position.set(localX, 0, localZ);
block.castShadow = true;
block.receiveShadow = true;
block.userData.pieceId = piece.id;
group.add(block);
pickables.push(block);
const cap = new THREE.Mesh(capGeometry, capMaterial);
cap.position.set(localX, 0.245, localZ);
cap.castShadow = true;
cap.userData.pieceId = piece.id;
group.add(cap);
pickables.push(cap);
});
const arrowMaterial = new THREE.MeshStandardMaterial({
color: piece.id === "exit" ? 0xfff2e9 : 0xeafaff,
emissive: piece.color,
emissiveIntensity: 0.22,
roughness: 0.35,
metalness: 0.15
});
addVoxelArrow(
group,
piece.direction,
arrowMaterial,
piece.id !== "exit"
);
scene.add(group);
piece.mesh = group;
}
// East gate.
const gateMaterial = new THREE.MeshStandardMaterial({
color: 0xffb454,
emissive: 0xff8d32,
emissiveIntensity: 0.65,
roughness: 0.32,
metalness: 0.55
});
const gate = new THREE.Group();
const postGeometry = new THREE.BoxGeometry(0.18, 0.78, 0.18);
const beamGeometry = new THREE.BoxGeometry(0.18, 0.17, 1.32);
for (const z of [-0.56, 0.56]) {
const post = new THREE.Mesh(postGeometry, gateMaterial);
post.position.set(2.72, 0.38, z);
post.castShadow = true;
gate.add(post);
}
const beam = new THREE.Mesh(beamGeometry, gateMaterial);
beam.position.set(2.72, 0.81, 0);
beam.castShadow = true;
gate.add(beam);
const gatePixelGeometry = new THREE.BoxGeometry(0.08, 0.08, 0.08);
for (const z of [-0.12, 0, 0.12]) {
const pixel = new THREE.Mesh(gatePixelGeometry, gateMaterial);
pixel.position.set(2.84, 0.51, z);
gate.add(pixel);
}
scene.add(gate);
const selectionBox = new THREE.BoxHelper(
pieceById.exit.mesh,
0xffffff
);
selectionBox.visible = false;
selectionBox.material.transparent = true;
selectionBox.material.opacity = 0.8;
scene.add(selectionBox);
// -------------------------------------------------------------------------
// UI and state updates
// -------------------------------------------------------------------------
const moveCountElement = document.querySelector("#move-count");
const gateStateElement = document.querySelector("#gate-state");
const selectedNameElement = document.querySelector("#selected-name");
const toastElement = document.querySelector("#toast");
const winElement = document.querySelector("#win");
const finalMovesElement = document.querySelector("#final-moves");
const moveButtons = [...document.querySelectorAll("[data-dir]")];
function showToast(message, duration = 2200) {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.classList.add("show");
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, duration);
}
function isBusy() {
return pieces.some((piece) => Boolean(piece.animation));
}
function pathIsClear() {
const occupancy = buildOccupancy(currentStates());
for (let x = 2; x < GRID; x++) {
if (occupancy.has(`${x},2`)) return false;
}
return true;
}
function setSelected(id) {
if (!pieceById[id]) return;
selectedId = id;
selectionBox.setFromObject(pieceById[id].mesh);
selectionBox.visible = !solved;
updateHUD();
}
function adjacentTarget(id, direction) {
const piece = pieceById[id];
const target = { ...piece.anchor };
if (piece.direction === "x") {
if (direction === "left") target.x -= 1;
if (direction === "right") {
if (piece.id === "exit" && piece.anchor.x === 3) {
target.x = 5;
} else {
target.x += 1;
}
}
} else {
if (direction === "up") target.z -= 1;
if (direction === "down") target.z += 1;
}
return target;
}
function updateControls() {
const piece = pieceById[selectedId];
const busy = isBusy() || solved;
for (const button of moveButtons) {
const direction = button.dataset.dir;
let allowed = false;
if (piece && !busy) {
if (piece.direction === "x") {
if (direction === "left" || direction === "right") {
allowed = canMoveTo(
piece.id,
adjacentTarget(piece.id, direction)
);
}
} else {
if (direction === "up" || direction === "down") {
allowed = canMoveTo(
piece.id,
adjacentTarget(piece.id, direction)
);
}
}
}
button.disabled = !allowed;
}
}
function updateHUD() {
moveCountElement.textContent = String(moveCount);
const clear = pathIsClear();
gateStateElement.textContent = clear ? "Open" : "Locked";
gateStateElement.style.color = clear ? "#63ffc6" : "#ffbf55";
gateMaterial.color.setHex(clear ? 0x63ffc6 : 0xffb454);
gateMaterial.emissive.setHex(clear ? 0x29e79f : 0xff8d32);
for (const piece of pieces) {
if (piece.id === "exit") continue;
const chip = document.querySelector(`#lock-${piece.id}`);
chip.classList.toggle("open", piece.moved);
}
const piece = pieceById[selectedId];
selectedNameElement.textContent = piece.name;
selectedNameElement.style.color = `#${new THREE.Color(piece.color).getHexString()}`;
updateControls();
}
function animatePiece(piece, targetPosition, duration = 190) {
piece.animation = {
from: piece.mesh.position.clone(),
to: targetPosition.clone(),
start: performance.now(),
duration
};
}
function commitMove(id, target, instant = false) {
if (solved || isBusy()) return false;
const piece = pieceById[id];
const oldAnchor = piece.anchor;
if (
oldAnchor.x === target.x &&
oldAnchor.z === target.z
) {
return false;
}
if (!canMoveTo(id, target)) return false;
const distance =
Math.abs(target.x - oldAnchor.x) +
Math.abs(target.z - oldAnchor.z);
piece.anchor = { x: target.x, z: target.z };
moveCount += distance;
if (piece.id !== "exit") piece.moved = true;
const targetPosition = pieceCenter(piece.anchor, piece);
if (instant) {
piece.mesh.position.copy(targetPosition);
} else {
const duration = piece.id === "exit" && target.x === 5 ? 560 : 190;
animatePiece(piece, targetPosition, duration);
}
if (piece.id === "exit" && target.x === 5) {
solved = true;
selectionBox.visible = false;
clearTimeout(winTimer);
winTimer = setTimeout(showWin, 620);
}
updateHUD();
return true;
}
function performMove(direction) {
if (solved || isBusy()) return;
const target = adjacentTarget(selectedId, direction);
if (!commitMove(selectedId, target)) {
showToast("That rail is blocked by another solid cell.");
}
}
// -------------------------------------------------------------------------
// Hint solver. Breadth-first search over legal one-cell slide states.
// -------------------------------------------------------------------------
function stateKey(states) {
return pieces
.map((piece) => {
const anchor = states[piece.id];
return `${anchor.x},${anchor.z}`;
})
.join("|");
}
function findHint() {
const initial = currentStates();
const queue = [{ states: initial, move: null }];
const visited = new Set([stateKey(initial)]);
while (queue.length) {
const node = queue.shift();
const states = node.states;
if (states.exit.x === 5) return node.move;
for (const piece of pieces) {
const candidates = [];
if (piece.direction === "x") {
const left = { ...states[piece.id], x: states[piece.id].x - 1 };
if (left.x >= 0) candidates.push(left);
if (piece.id === "exit" && states.exit.x === 3) {
candidates.push({ ...states.exit, x: 5 });
} else {
const right = {
...states[piece.id],
x: states[piece.id].x + 1
};
if (right.x <= 3) candidates.push(right);
}
} else {
const up = { ...states[piece.id], z: states[piece.id].z - 1 };
const down = { ...states[piece.id], z: states[piece.id].z + 1 };
if (up.z >= 0) candidates.push(up);
if (down.z <= 3) candidates.push(down);
}
for (const target of candidates) {
if (!canMoveTo(piece.id, target, states)) continue;
const nextStates = {
...states,
[piece.id]: { ...target }
};
const key = stateKey(nextStates);
if (visited.has(key)) continue;
visited.add(key);
queue.push({
states: nextStates,
move: node.move || {
id: piece.id,
from: { ...states[piece.id] },
to: { ...target }
}
});
}
}
}
return null;
}
function showHint() {
if (solved || isBusy()) return;
const move = findHint();
if (!move) {
showToast("No legal route was found.");
return;
}
setSelected(move.id);
const dx = move.to.x - move.from.x;
const dz = move.to.z - move.from.z;
const direction = dx < 0 ? "left" : dx > 0 ? "right" : dz < 0 ? "up" : "down";
const names = {
left: "left",
right: "right",
up: "north",
down: "south"
};
showToast(
`Move ${pieceById[move.id].name} ${names[direction]}.`,
3000
);
}
// -------------------------------------------------------------------------
// Custom camera and piece dragging
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.34);
const planePoint = new THREE.Vector3();
let orbitDrag = null;
let pieceDrag = null;
function updatePointer(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);
}
function pointOnBoard(event) {
updatePointer(event);
return raycaster.ray.intersectPlane(dragPlane, planePoint);
}
function pickPiece(event) {
updatePointer(event);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0].object.userData.pieceId : null;
}
canvas.addEventListener("pointerdown", (event) => {
if (solved) return;
event.preventDefault();
const hitId = pickPiece(event);
if (hitId && event.button === 0 && !isBusy()) {
const piece = pieceById[hitId];
setSelected(hitId);
const point = pointOnBoard(event);
const center = pieceCenter(piece.anchor, piece);
const axis = piece.direction;
const grabOffset = axis === "x"
? point.x - center.x
: point.z - center.z;
pieceDrag = {
id: hitId,
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
axis,
grabOffset,
preview: null,
previewValid: false
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
} else {
orbitDrag = {
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
}
});
canvas.addEventListener("pointermove", (event) => {
if (orbitDrag && orbitDrag.pointerId === event.pointerId) {
const dx = event.clientX - orbitDrag.lastX;
const dy = event.clientY - orbitDrag.lastY;
orbit.theta -= dx * 0.006;
orbit.phi -= dy * 0.005;
orbit.phi = THREE.MathUtils.clamp(orbit.phi, 0.36, 1.35);
orbitDrag.lastX = event.clientX;
orbitDrag.lastY = event.clientY;
updateCamera();
return;
}
if (!pieceDrag || pieceDrag.pointerId !== event.pointerId) return;
const distance = Math.hypot(
event.clientX - pieceDrag.startX,
event.clientY - pieceDrag.startY
);
if (distance > 4) pieceDrag.moved = true;
if (!pieceDrag.moved) return;
const point = pointOnBoard(event);
if (!point) return;
const piece = pieceById[pieceDrag.id];
const raw = pieceDrag.axis === "x"
? point.x - pieceDrag.grabOffset
: point.z - pieceDrag.grabOffset;
let coordinate = Math.round(raw + HALF - 0.5);
if (piece.id === "exit" && coordinate >= 4) coordinate = 5;
coordinate = THREE.MathUtils.clamp(coordinate, 0, piece.id === "exit" ? 5 : 3);
const target = pieceDrag.axis === "x"
? { x: coordinate, z: piece.anchor.z }
: { x: piece.anchor.x, z: coordinate };
if (!canMoveTo(piece.id, target)) return;
pieceDrag.preview = target;
pieceDrag.previewValid = true;
piece.mesh.position.copy(pieceCenter(target, piece));
});
function finishPointer(event) {
if (orbitDrag && orbitDrag.pointerId === event.pointerId) {
orbitDrag = null;
canvas.style.cursor = "default";
}
if (pieceDrag && pieceDrag.pointerId === event.pointerId) {
const drag = pieceDrag;
pieceDrag = null;
if (drag.moved) {
if (drag.previewValid && drag.preview) {
commitMove(drag.id, drag.preview, true);
} else {
const piece = pieceById[drag.id];
animatePiece(piece, pieceCenter(piece.anchor, piece), 150);
}
}
canvas.style.cursor = "default";
}
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", finishPointer);
canvas.addEventListener("pointercancel", finishPointer);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.008,
7.2,
15
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
function resetCamera() {
orbit.theta = 0.72;
orbit.phi = 0.79;
orbit.radius = 10.7;
updateCamera();
}
// -------------------------------------------------------------------------
// Win effects and reset
// -------------------------------------------------------------------------
const particles = [];
const particleGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
const particleMaterials = [
0xff617c,
0xffbf55,
0x60a5ff,
0x48dfca,
0xffffff
].map((color) => new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.45,
roughness: 0.4
}));
function spawnConfetti() {
for (let i = 0; i < 38; i++) {
const mesh = new THREE.Mesh(
particleGeometry,
particleMaterials[i % particleMaterials.length]
);
mesh.position.set(
2.65 + Math.random() * 0.35,
0.8 + Math.random() * 0.8,
(Math.random() - 0.5) * 1.2
);
scene.add(mesh);
particles.push({
mesh,
velocity: new THREE.Vector3(
0.6 + Math.random() * 1.8,
1.3 + Math.random() * 2.2,
(Math.random() - 0.5) * 2.8
),
spin: new THREE.Vector3(
Math.random() * 8,
Math.random() * 8,
Math.random() * 8
),
life: 1.7 + Math.random() * 0.9
});
}
}
function showWin() {
if (!solved) return;
finalMovesElement.textContent = String(moveCount);
winElement.classList.add("show");
spawnConfetti();
}
function clearParticles() {
for (const particle of particles) scene.remove(particle.mesh);
particles.length = 0;
}
function restart() {
clearTimeout(winTimer);
clearParticles();
solved = false;
moveCount = 0;
selectedId = "exit";
for (const piece of pieces) {
piece.anchor = { ...piece.initial };
piece.moved = false;
piece.animation = null;
piece.mesh.position.copy(pieceCenter(piece.anchor, piece));
}
winElement.classList.remove("show");
setSelected("exit");
showToast("Board reset. All three locks must be shifted.");
}
document.querySelector("#hint").addEventListener("click", showHint);
document.querySelector("#restart").addEventListener("click", restart);
document.querySelector("#play-again").addEventListener("click", restart);
document.querySelector("#reset-camera").addEventListener("click", resetCamera);
for (const button of moveButtons) {
button.addEventListener("click", () => {
performMove(button.dataset.dir);
});
}
window.addEventListener("keydown", (event) => {
const key = event.key.toLowerCase();
if (key === "arrowleft") {
event.preventDefault();
performMove("left");
} else if (key === "arrowright") {
event.preventDefault();
performMove("right");
} else if (key === "arrowup") {
event.preventDefault();
performMove("up");
} else if (key === "arrowdown") {
event.preventDefault();
performMove("down");
} else if (key === "h") {
showHint();
} else if (key === "r") {
restart();
} else if (key === "escape") {
selectionBox.visible = false;
}
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousFrame = performance.now();
function frame(now) {
requestAnimationFrame(frame);
const dt = Math.min((now - previousFrame) / 1000, 0.05);
previousFrame = now;
let controlsChanged = false;
for (const piece of pieces) {
if (!piece.animation) continue;
const animation = piece.animation;
const progress = Math.min(
1,
(now - animation.start) / animation.duration
);
const eased = 1 - Math.pow(1 - progress, 3);
piece.mesh.position.lerpVectors(
animation.from,
animation.to,
eased
);
if (progress >= 1) {
piece.mesh.position.copy(animation.to);
piece.animation = null;
controlsChanged = true;
}
}
const selectedPiece = pieceById[selectedId];
for (const piece of pieces) {
const active = piece.id === selectedId && !solved;
const pulse = 0.17 + Math.sin(now * 0.006) * 0.035;
piece.material.emissiveIntensity = active ? pulse + 0.2 : 0.12;
}
if (selectedPiece && !solved) {
selectionBox.setFromObject(selectedPiece.mesh);
selectionBox.material.opacity = 0.62 + Math.sin(now * 0.006) * 0.18;
}
gateMaterial.emissiveIntensity =
0.52 + Math.sin(now * 0.0038) * 0.18;
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
particle.velocity.y -= 3.8 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += particle.spin.x * dt;
particle.mesh.rotation.y += particle.spin.y * dt;
particle.mesh.rotation.z += particle.spin.z * dt;
if (particle.life <= 0) {
scene.remove(particle.mesh);
particles.splice(i, 1);
}
}
if (controlsChanged) updateControls();
renderer.render(scene, camera);
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
setSelected("exit");
showToast("Shift all three locks, then guide the coral key east.", 3500);
requestAnimationFrame(frame);
</script>
</body>
</html>
```