Prompt specification
Build or customize the Three.js 3D scene "Shortest Sliding Solution Explorer" 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: Shortest Sliding Solution Explorer
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/shortest-sliding-solution-explorer-x3504
Scene Description Prompt:
Shortest sliding solution explorer. Create a bounded sliding-block puzzle with undo, reset, and a move counter. Compare a player's route with a computed solution under exactly the same legal-move rules. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (shortest-sliding-solution-explorer-x3504):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shortest Sliding Solution Explorer</title>
<style>
:root {
--bg: #e9ede7;
--panel: #f8f8f3;
--panel-2: #eef2eb;
--ink: #17221d;
--muted: #67716b;
--line: #d7ddd6;
--accent: #d8ff64;
--accent-dark: #45621e;
--good: #21865a;
--warn: #b56b24;
--shadow: 0 18px 48px rgba(28, 43, 34, 0.09);
}
* {
box-sizing: border-box;
}
html {
color-scheme: light;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--ink);
background:
radial-gradient(circle at 12% 8%, rgba(216, 255, 100, 0.22), transparent 28rem),
radial-gradient(circle at 95% 85%, rgba(112, 172, 255, 0.12), transparent 32rem),
var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
border: 1px solid var(--line);
color: var(--ink);
background: #fff;
border-radius: 11px;
padding: 9px 13px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: #b8c2b9;
background: #f4f7f1;
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
button:focus-visible,
select:focus-visible,
canvas:focus-visible {
outline: 3px solid rgba(89, 131, 42, 0.34);
outline-offset: 3px;
}
.app {
width: min(1480px, calc(100% - 32px));
margin: 0 auto;
padding: 28px 0 38px;
}
.header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
margin-bottom: 22px;
}
.eyebrow,
.panel-kicker,
.route-label {
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h1 {
max-width: 850px;
margin: 6px 0 8px;
font-size: clamp(2rem, 4.6vw, 4rem);
line-height: 0.98;
letter-spacing: -0.055em;
}
.intro {
max-width: 780px;
margin: 0;
color: var(--muted);
line-height: 1.55;
}
.header-side {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 12px;
flex: 0 0 auto;
}
.solver-badge,
.route-badge {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 7px 11px;
border: 1px solid #cad2c8;
border-radius: 999px;
background: rgba(255, 255, 255, 0.72);
color: var(--muted);
font-size: 0.78rem;
font-weight: 800;
white-space: nowrap;
}
.solver-badge::before,
.route-badge::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: #9ca69f;
content: "";
}
.route-badge.good {
color: var(--good);
border-color: rgba(33, 134, 90, 0.25);
background: rgba(33, 134, 90, 0.08);
}
.route-badge.good::before {
background: var(--good);
}
.route-badge.warn {
color: var(--warn);
border-color: rgba(181, 107, 36, 0.24);
background: rgba(181, 107, 36, 0.08);
}
.route-badge.warn::before {
background: var(--warn);
}
.workspace {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
}
.panel {
min-width: 0;
overflow: hidden;
border: 1px solid rgba(190, 200, 191, 0.82);
border-radius: 22px;
background: rgba(248, 248, 243, 0.92);
box-shadow: var(--shadow);
}
.panel-inner {
padding: 20px;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 4px 0 0;
font-size: clamp(1.2rem, 2.2vw, 1.75rem);
letter-spacing: -0.035em;
}
.rule-chip {
padding: 7px 10px;
border-radius: 9px;
background: var(--panel-2);
color: var(--muted);
font-size: 0.75rem;
font-weight: 700;
text-align: right;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 9px;
margin-bottom: 12px;
}
.stat {
min-width: 0;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.72);
}
.stat-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 0.69rem;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.stat-value {
display: block;
overflow: hidden;
font-size: 1.22rem;
font-weight: 850;
letter-spacing: -0.03em;
text-overflow: ellipsis;
white-space: nowrap;
}
.board-shell {
position: relative;
width: 100%;
height: clamp(340px, 39vw, 535px);
overflow: hidden;
border: 1px solid #d3dbd2;
border-radius: 17px;
background: #dce3dc;
isolation: isolate;
}
.scene-canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.scene-canvas:active {
cursor: grabbing;
}
.board-loading {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
place-items: center;
color: var(--muted);
font-weight: 700;
pointer-events: none;
}
.board-hint {
position: absolute;
right: 10px;
bottom: 10px;
z-index: 2;
padding: 6px 9px;
border: 1px solid rgba(160, 174, 162, 0.7);
border-radius: 999px;
background: rgba(244, 248, 242, 0.78);
color: #657067;
font-size: 0.67rem;
font-weight: 700;
pointer-events: none;
backdrop-filter: blur(7px);
}
.player-tools,
.playback-tools {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-top: 13px;
}
.selected-label {
min-width: 120px;
margin-left: 3px;
color: var(--muted);
font-size: 0.79rem;
font-weight: 700;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 31px);
grid-template-rows: repeat(3, 31px);
gap: 3px;
margin-left: auto;
}
.dpad button {
display: grid;
place-items: center;
width: 31px;
height: 31px;
padding: 0;
border-radius: 8px;
font-size: 1rem;
line-height: 1;
}
.dpad .up {
grid-column: 2;
grid-row: 1;
}
.dpad .left {
grid-column: 1;
grid-row: 2;
}
.dpad .right {
grid-column: 3;
grid-row: 2;
}
.dpad .down {
grid-column: 2;
grid-row: 3;
}
.hint {
margin: 12px 2px 0;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.5;
}
.solution-stats {
grid-template-columns: 1.15fr 0.85fr 1fr;
}
.playback-tools select {
height: 38px;
padding: 0 28px 0 10px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: #fff;
font-weight: 700;
}
.playback-tools .primary {
min-width: 82px;
border-color: #b7d26f;
background: var(--accent);
}
.auto-button {
margin-left: auto;
}
.route-compare {
display: grid;
gap: 12px;
margin-top: 18px;
padding: 18px 20px;
border: 1px solid rgba(190, 200, 191, 0.82);
border-radius: 19px;
background: rgba(248, 248, 243, 0.8);
box-shadow: 0 10px 30px rgba(28, 43, 34, 0.05);
}
.route-row {
display: grid;
grid-template-columns: 145px minmax(0, 1fr);
align-items: center;
gap: 14px;
min-width: 0;
}
.route-scroll {
display: flex;
gap: 6px;
min-width: 0;
overflow-x: auto;
padding: 4px 2px 8px;
scrollbar-width: thin;
}
.move-chip {
display: inline-flex;
flex: 0 0 auto;
align-items: center;
gap: 5px;
min-width: 46px;
height: 32px;
padding: 5px 8px;
border: 1px solid #d2d9d1;
border-radius: 9px;
background: #fff;
color: #526058;
font-size: 0.78rem;
font-weight: 800;
}
.move-chip b {
color: var(--ink);
font-size: 0.9rem;
}
.move-chip.match {
border-color: #9dca69;
background: rgba(216, 255, 100, 0.32);
}
.move-chip.current {
border-color: #497e60;
color: #fff;
background: #497e60;
}
.move-chip.current b {
color: #fff;
}
.empty-route {
padding: 7px 2px;
color: #929b95;
font-size: 0.8rem;
}
.footer {
display: flex;
justify-content: space-between;
gap: 18px;
margin-top: 15px;
padding: 0 3px;
color: #7a847e;
font-size: 0.72rem;
line-height: 1.5;
}
.toast {
position: fixed;
left: 50%;
bottom: 24px;
z-index: 20;
max-width: min(90vw, 480px);
padding: 11px 15px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 999px;
color: #fff;
background: rgba(23, 34, 29, 0.92);
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.2);
font-size: 0.82rem;
font-weight: 700;
opacity: 0;
transform: translate(-50%, 14px);
transition:
opacity 180ms ease,
transform 180ms ease;
pointer-events: none;
}
.toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 920px) {
.workspace {
grid-template-columns: 1fr;
}
.header {
align-items: flex-start;
}
.board-shell {
height: min(76vw, 540px);
}
}
@media (max-width: 620px) {
.app {
width: min(100% - 18px, 1480px);
padding-top: 18px;
}
.header {
flex-direction: column;
gap: 14px;
}
.header-side {
align-items: flex-start;
}
.panel-inner {
padding: 13px;
}
.panel-head {
align-items: flex-start;
}
.rule-chip {
max-width: 135px;
}
.board-shell {
height: 92vw;
max-height: 500px;
}
.route-row {
grid-template-columns: 1fr;
gap: 4px;
}
.footer {
flex-direction: column;
}
.auto-button {
width: 100%;
margin-left: 0;
}
}
</style>
</head>
<body>
<div class="app">
<header class="header">
<div>
<div class="eyebrow">Puzzle laboratory / 8 puzzle</div>
<h1>Shortest sliding solution explorer</h1>
<p class="intro">
Find your own route through the bounded 3×3 arena, then compare it
with an exact shortest solution computed from the same legal-move
rules.
</p>
</div>
<div class="header-side">
<div id="solverBadge" class="solver-badge">Building state graph…</div>
<button id="resetAllButton" type="button">↺ Reset all</button>
</div>
</header>
<main class="workspace">
<section class="panel" aria-labelledby="playerTitle">
<div class="panel-inner">
<div class="panel-head">
<div>
<div class="panel-kicker">01 / Your route</div>
<h2 id="playerTitle">Make your move</h2>
</div>
<div id="routeBadge" class="route-badge">Ready</div>
</div>
<div class="stats">
<div class="stat">
<span class="stat-label">Moves</span>
<span id="playerMoves" class="stat-value">0</span>
</div>
<div class="stat">
<span class="stat-label">Shortest</span>
<span id="optimalMoves" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Gap</span>
<span id="moveGap" class="stat-value">—</span>
</div>
</div>
<div id="playerBoard" class="board-shell">
<div class="board-loading">Preparing arena…</div>
<div class="board-hint">Drag to orbit · scroll to zoom</div>
</div>
<div class="player-tools">
<button id="undoButton" type="button" disabled>↶ Undo</button>
<button id="resetButton" type="button">↺ Reset</button>
<span id="selectedTile" class="selected-label">No tile selected</span>
<div class="dpad" aria-label="Move selected tile">
<button class="up" data-direction="up" type="button" disabled aria-label="Move up">↑</button>
<button class="left" data-direction="left" type="button" disabled aria-label="Move left">←</button>
<button class="right" data-direction="right" type="button" disabled aria-label="Move right">→</button>
<button class="down" data-direction="down" type="button" disabled aria-label="Move down">↓</button>
</div>
</div>
<p class="hint">
Select a numbered tile, then press an arrow or click the empty
square. The move counter counts successful slides; undo does not.
</p>
</div>
</section>
<section class="panel" aria-labelledby="solutionTitle">
<div class="panel-inner">
<div class="panel-head">
<div>
<div class="panel-kicker">02 / Computed route</div>
<h2 id="solutionTitle">The shortest path</h2>
</div>
<div class="rule-chip">BFS exact shortest<br />1 tile → blank</div>
</div>
<div class="stats solution-stats">
<div class="stat">
<span class="stat-label">Playback</span>
<span id="solutionStep" class="stat-value">0 / —</span>
</div>
<div class="stat">
<span class="stat-label">Search</span>
<span class="stat-value">BFS</span>
</div>
<div class="stat">
<span class="stat-label">Verified</span>
<span class="stat-value">Exact</span>
</div>
</div>
<div id="solutionBoard" class="board-shell">
<div class="board-loading">Preparing solution…</div>
<div class="board-hint">Drag to orbit · scroll to zoom</div>
</div>
<div class="playback-tools">
<button id="solutionPrevButton" type="button" disabled aria-label="Previous solution move">−</button>
<button id="solutionPlayButton" class="primary" type="button">▶ Play</button>
<button id="solutionNextButton" type="button" aria-label="Next solution move">+</button>
<button id="solutionResetButton" type="button">Reset</button>
<select id="solutionSpeed" aria-label="Solution playback speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
<option value="2">2×</option>
</select>
<button id="autoSolveButton" class="auto-button" type="button">
Try shortest on your board
</button>
</div>
<p class="hint">
This route is generated by breadth-first search. Player input and
the solver call the same legal-move function, so neither route can
use a hidden rule.
</p>
</div>
</section>
</main>
<section class="route-compare" aria-label="Route comparison">
<div class="route-row">
<div class="route-label">Your route</div>
<div id="playerRoute" class="route-scroll"></div>
</div>
<div class="route-row">
<div class="route-label">Shortest route</div>
<div id="optimalRoute" class="route-scroll"></div>
</div>
</section>
<footer class="footer">
<span>
Deterministic 3×3 puzzle · computed from a 37-move legal scramble ·
no path data is hard-coded.
</span>
<span>
Three.js core only · custom orbit controls · low-poly geometry
</span>
</footer>
</div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Shared puzzle model and exact legal-move rule
// -------------------------------------------------------------------------
const SIZE = 3;
const CELL_COUNT = SIZE * SIZE;
const GOAL = [1, 2, 3, 4, 5, 6, 7, 8, 0];
const REDUCED_MOTION =
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const TILE_DELTA = {
up: [-1, 0],
down: [1, 0],
left: [0, -1],
right: [0, 1]
};
const OPPOSITE = {
up: "down",
down: "up",
left: "right",
right: "left"
};
const ARROW = {
up: "↑",
down: "↓",
left: "←",
right: "→"
};
const TILE_COLORS = {
1: 0xff6b5f,
2: 0xffa64d,
3: 0xf4d35e,
4: 0x54c78b,
5: 0x39b8c4,
6: 0x5b8def,
7: 0x9b7cf6,
8: 0xe978b5
};
function rowOf(index) {
return Math.floor(index / SIZE);
}
function colOf(index) {
return index % SIZE;
}
function legalMoves(state) {
const blank = state.indexOf(0);
const row = rowOf(blank);
const col = colOf(blank);
const moves = [];
// The direction names the tile's movement, not the blank's movement.
for (const [name, [dr, dc]] of Object.entries(TILE_DELTA)) {
const nr = row + dr;
const nc = col + dc;
if (nr < 0 || nr >= SIZE || nc < 0 || nc >= SIZE) continue;
const from = nr * SIZE + nc;
const tile = state[from];
if (tile === 0) continue;
moves.push({
tile,
from,
to: blank,
dir: OPPOSITE[name]
});
}
return moves;
}
function applyMove(state, move) {
const next = state.slice();
next[move.from] = 0;
next[move.to] = move.tile;
return next;
}
function moveBlank(state, direction) {
const blank = state.indexOf(0);
const [dr, dc] = TILE_DELTA[direction];
const nr = rowOf(blank) + dr;
const nc = colOf(blank) + dc;
if (nr < 0 || nr >= SIZE || nc < 0 || nc >= SIZE) {
return state.slice();
}
const target = nr * SIZE + nc;
const next = state.slice();
next[blank] = next[target];
next[target] = 0;
return next;
}
function makeScrambledState() {
let state = GOAL.slice();
// A legal perimeter cycle, repeated to mix the outer ring.
const perimeterCycle = ["L", "L", "U", "L", "L", "D", "D", "R"];
const sequence = [];
for (let repeat = 0; repeat < 3; repeat++) {
sequence.push(...perimeterCycle);
}
// A legal center excursion.
sequence.push("L", "L", "U", "L", "D", "U", "R", "D", "L", "U", "R", "D", "R");
for (const direction of sequence) {
const map = { L: "left", R: "right", U: "up", D: "down" };
state = moveBlank(state, map[direction]);
}
return state;
}
const INITIAL = makeScrambledState();
function solvePuzzle(start) {
const startKey = start.join("");
const goalKey = GOAL.join("");
const queue = [start.slice()];
const parents = new Map([[startKey, null]]);
let foundKey = null;
for (let head = 0; head < queue.length; head++) {
const state = queue[head];
const key = state.join("");
if (key === goalKey) {
foundKey = key;
break;
}
for (const move of legalMoves(state)) {
const next = applyMove(state, move);
const nextKey = next.join("");
if (parents.has(nextKey)) continue;
parents.set(nextKey, {
previous: key,
move: { ...move }
});
queue.push(next);
}
}
if (!foundKey) {
throw new Error("No solution exists for the generated puzzle.");
}
const states = [foundKey];
const moves = [];
let key = foundKey;
while (parents.get(key)) {
const record = parents.get(key);
moves.push({ ...record.move });
key = record.previous;
states.push(key);
}
moves.reverse();
states.reverse();
return {
moves,
states,
stateIndex: new Map(states.map((stateKey, index) => [stateKey, index]))
};
}
// -------------------------------------------------------------------------
// Three.js board view
// -------------------------------------------------------------------------
class BoardView {
constructor(container, initialState, options = {}) {
this.container = container;
this.options = options;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xdce3dc);
this.scene.fog = new THREE.Fog(0xdce3dc, 12, 22);
this.renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.08;
this.renderer.domElement.className = "scene-canvas";
this.renderer.domElement.tabIndex = 0;
this.renderer.domElement.setAttribute(
"aria-label",
options.interactive
? "Interactive three-dimensional sliding puzzle board"
: "Three-dimensional shortest solution board"
);
container.querySelector(".board-loading")?.remove();
container.prepend(this.renderer.domElement);
this.camera = new THREE.PerspectiveCamera(36, 1, 0.1, 100);
this.cameraState = {
yaw: 0.62,
pitch: 0.72,
distance: 7.5
};
this.raycaster = new THREE.Raycaster();
this.pointer = new THREE.Vector2();
this.tileMeshes = [];
this.floorTiles = [];
this.tileGroups = new Map();
this.visualPositions = new Map();
this.animations = new Map();
this.createLighting();
this.createArena();
this.createTiles(initialState);
this.updateCamera();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(container);
this.resize();
this.installControls();
}
createLighting() {
const hemi = new THREE.HemisphereLight(0xf7fff4, 0x849188, 2.25);
this.scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4dd, 3.1);
sun.position.set(4.5, 8, 5.5);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -5;
sun.shadow.camera.right = 5;
sun.shadow.camera.top = 5;
sun.shadow.camera.bottom = -5;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 20;
sun.shadow.bias = -0.00035;
this.scene.add(sun);
const rim = new THREE.DirectionalLight(0xb9d9ff, 1.15);
rim.position.set(-5, 4, -4);
this.scene.add(rim);
}
createArena() {
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0xd5ddd5,
roughness: 0.98,
flatShading: true
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.34;
ground.receiveShadow = true;
this.scene.add(ground);
const base = new THREE.Mesh(
new THREE.BoxGeometry(3.45, 0.18, 3.45),
new THREE.MeshStandardMaterial({
color: 0xaab7ac,
roughness: 0.86,
flatShading: true
})
);
base.position.y = -0.08;
base.castShadow = true;
base.receiveShadow = true;
this.scene.add(base);
for (let index = 0; index < CELL_COUNT; index++) {
const row = rowOf(index);
const col = colOf(index);
const checker = (row + col) % 2;
const color = new THREE.Color(
checker === 0 ? 0xe6ebe4 : 0xd8dfd7
);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.93,
flatShading: true
});
const tile = new THREE.Mesh(
new THREE.BoxGeometry(0.94, 0.075, 0.94),
material
);
tile.position.set(col - 1, 0.045, row - 1);
tile.receiveShadow = true;
tile.userData.index = index;
tile.userData.baseColor = color.clone();
this.floorTiles.push(tile);
this.scene.add(tile);
}
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x76857b,
roughness: 0.72,
metalness: 0.04,
flatShading: true
});
const railLength = 3.55;
const railThickness = 0.12;
const railHeight = 0.32;
for (const side of [-1, 1]) {
const xRail = new THREE.Mesh(
new THREE.BoxGeometry(railThickness, railHeight, railLength),
railMaterial
);
xRail.position.set(side * 1.69, 0.11, 0);
xRail.castShadow = true;
this.scene.add(xRail);
const zRail = new THREE.Mesh(
new THREE.BoxGeometry(railLength, railHeight, railThickness),
railMaterial
);
zRail.position.set(0, 0.11, side * 1.69);
zRail.castShadow = true;
this.scene.add(zRail);
}
const postGeometry = new THREE.CylinderGeometry(
0.105,
0.13,
0.42,
6
);
for (const x of [-1, 1]) {
for (const z of [-1, 1]) {
const post = new THREE.Mesh(postGeometry, railMaterial);
post.position.set(x * 1.69, 0.17, z * 1.69);
post.castShadow = true;
this.scene.add(post);
}
}
}
createTiles(state) {
for (let tile = 1; tile <= 8; tile++) {
const index = state.indexOf(tile);
const group = new THREE.Group();
const color = new THREE.Color(TILE_COLORS[tile]);
const baseMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.64,
metalness: 0.025,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.82, 0.38, 0.82),
baseMaterial
);
block.castShadow = true;
block.receiveShadow = true;
block.userData.tile = tile;
group.add(block);
this.tileMeshes.push(block);
const topColor = color.clone().lerp(new THREE.Color(0xffffff), 0.2);
const top = new THREE.Mesh(
new THREE.BoxGeometry(0.68, 0.035, 0.68),
new THREE.MeshStandardMaterial({
color: topColor,
roughness: 0.58,
flatShading: true
})
);
top.position.y = 0.207;
top.castShadow = true;
group.add(top);
const numberTexture = this.makeNumberTexture(tile);
const number = new THREE.Mesh(
new THREE.PlaneGeometry(0.48, 0.48),
new THREE.MeshBasicMaterial({
map: numberTexture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
number.rotation.x = -Math.PI / 2;
number.position.y = 0.231;
group.add(number);
group.position.copy(this.worldPosition(index));
this.tileGroups.set(tile, group);
this.visualPositions.set(tile, index);
this.scene.add(group);
}
this.setBlank(state.indexOf(0));
}
makeNumberTexture(number) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 256, 256);
context.fillStyle = "rgba(255,255,255,0.94)";
context.font = "900 145px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(String(number), 128, 139);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = this.renderer.capabilities.getMaxAnisotropy();
return texture;
}
worldPosition(index) {
return new THREE.Vector3(
colOf(index) - 1,
0.29,
rowOf(index) - 1
);
}
setBlank(blankIndex) {
this.floorTiles.forEach((tile, index) => {
tile.material.color.copy(
index === blankIndex
? new THREE.Color(0xaebbb0)
: tile.userData.baseColor
);
});
}
setSelected(tile) {
for (const [number, group] of this.tileGroups) {
const material = group.children[0].material;
material.emissive.set(number === tile ? 0xffffff : 0x000000);
material.emissiveIntensity = number === tile ? 0.2 : 0;
}
}
moveTile(tile, from, to, duration = 190) {
const group = this.tileGroups.get(tile);
if (!group) return Promise.resolve();
const previousAnimation = this.animations.get(tile);
if (previousAnimation) previousAnimation.resolve();
const start = group.position.clone();
const end = this.worldPosition(to);
const actualDuration = REDUCED_MOTION ? 1 : duration;
this.visualPositions.set(tile, to);
return new Promise((resolve) => {
this.animations.set(tile, {
group,
start,
end,
started: performance.now(),
duration: actualDuration,
resolve
});
});
}
snapTo(state) {
for (const animation of this.animations.values()) {
animation.resolve();
}
this.animations.clear();
for (const [tile, group] of this.tileGroups) {
const index = state.indexOf(tile);
group.position.copy(this.worldPosition(index));
this.visualPositions.set(tile, index);
}
this.setBlank(state.indexOf(0));
}
resize() {
const width = Math.max(1, this.container.clientWidth);
const height = Math.max(1, this.container.clientHeight);
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
updateCamera() {
const { yaw, pitch, distance } = this.cameraState;
const horizontal = Math.cos(pitch) * distance;
this.camera.position.set(
Math.sin(yaw) * horizontal,
Math.sin(pitch) * distance,
Math.cos(yaw) * horizontal
);
this.camera.lookAt(0, 0.02, 0);
}
installControls() {
const canvas = this.renderer.domElement;
let active = false;
let moved = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("pointerdown", (event) => {
active = true;
moved = false;
lastX = event.clientX;
lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!active) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 3) moved = true;
if (!moved) return;
this.cameraState.yaw -= dx * 0.008;
this.cameraState.pitch = THREE.MathUtils.clamp(
this.cameraState.pitch + dy * 0.006,
0.38,
1.24
);
this.updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!active) return;
active = false;
if (!moved) this.pick(event);
});
canvas.addEventListener("pointercancel", () => {
active = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
this.cameraState.distance = THREE.MathUtils.clamp(
this.cameraState.distance + event.deltaY * 0.006,
5.4,
10.5
);
this.updateCamera();
},
{ passive: false }
);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
}
pick(event) {
const rect = this.renderer.domElement.getBoundingClientRect();
this.pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
this.pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
this.raycaster.setFromCamera(this.pointer, this.camera);
const tileHits = this.raycaster.intersectObjects(this.tileMeshes, false);
if (tileHits.length) {
this.options.onTile?.(tileHits[0].object.userData.tile);
return;
}
const floorHits = this.raycaster.intersectObjects(this.floorTiles, false);
if (floorHits.length) {
this.options.onCell?.(floorHits[0].object.userData.index);
}
}
render(now) {
for (const [tile, animation] of this.animations) {
const elapsed = now - animation.started;
const t = Math.min(1, elapsed / animation.duration);
const eased = 1 - Math.pow(1 - t, 3);
animation.group.position.lerpVectors(
animation.start,
animation.end,
eased
);
animation.group.position.y += Math.sin(t * Math.PI) * 0.065;
if (t >= 1) {
animation.group.position.copy(animation.end);
this.animations.delete(tile);
animation.resolve();
}
}
this.renderer.render(this.scene, this.camera);
}
}
// -------------------------------------------------------------------------
// Application state
// -------------------------------------------------------------------------
const playerBoardElement = document.querySelector("#playerBoard");
const solutionBoardElement = document.querySelector("#solutionBoard");
let playerView;
let solutionView;
let solution;
let playerState = INITIAL.slice();
let playerHistory = [];
let selectedTile = null;
let playerBusy = false;
let autoRunning = false;
let autoToken = 0;
let solutionState = INITIAL.slice();
let solutionIndex = 0;
let solutionBusy = false;
let solutionPlaying = false;
let solutionTimer = null;
playerView = new BoardView(playerBoardElement, INITIAL, {
interactive: true,
onTile: (tile) => selectTile(tile),
onCell: (index) => handlePlayerCell(index)
});
solutionView = new BoardView(solutionBoardElement, INITIAL);
// Let the board render once before the shortest-path search runs.
await new Promise((resolve) => setTimeout(resolve, 35));
try {
solution = solvePuzzle(INITIAL);
} catch (error) {
document.querySelector("#solverBadge").textContent = "Solver error";
throw error;
}
document.querySelector("#solverBadge").textContent =
`BFS exact · ${solution.moves.length} moves`;
document.querySelector("#optimalMoves").textContent = solution.moves.length;
document.querySelector("#solutionStep").textContent =
`0 / ${solution.moves.length}`;
buildOptimalRoute();
updatePlayerUI();
updateSolutionUI();
// -------------------------------------------------------------------------
// Player controls
// -------------------------------------------------------------------------
function selectTile(tile) {
if (autoRunning) return;
selectedTile = tile;
playerView.setSelected(tile);
updatePlayerUI();
playerView.renderer.domElement.focus({ preventScroll: true });
}
function handlePlayerCell(index) {
if (autoRunning || playerBusy) return;
const tile = playerState[index];
if (tile !== 0) {
selectTile(tile);
return;
}
if (selectedTile === null) return;
const move = legalMoves(playerState).find(
(candidate) =>
candidate.tile === selectedTile && candidate.to === index
);
if (move) performPlayerMove(move);
}
function moveSelected(direction) {
if (autoRunning || playerBusy) return;
if (selectedTile === null) {
showToast("Select a numbered tile first.");
return;
}
const move = legalMoves(playerState).find(
(candidate) =>
candidate.tile === selectedTile && candidate.dir === direction
);
if (!move) {
showToast("That slide would leave the arena or overlap another tile.");
return;
}
performPlayerMove(move);
}
async function performPlayerMove(move) {
if (playerBusy || autoRunning) return;
playerBusy = true;
playerState = applyMove(playerState, move);
playerHistory.push({ ...move });
playerView.setBlank(playerState.indexOf(0));
updatePlayerUI();
await playerView.moveTile(move.tile, move.from, move.to, 180);
playerBusy = false;
updatePlayerUI();
}
function undoPlayer() {
if (playerBusy || playerHistory.length === 0) return;
cancelAutoSolve();
playerBusy = true;
const last = playerHistory.pop();
const inverse = {
tile: last.tile,
from: last.to,
to: last.from,
dir: OPPOSITE[last.dir]
};
playerState = applyMove(playerState, inverse);
playerView.setBlank(playerState.indexOf(0));
updatePlayerUI();
playerView.moveTile(last.tile, last.to, last.from, 170).then(() => {
playerBusy = false;
updatePlayerUI();
});
}
function resetPlayer(cancelAuto = true) {
if (cancelAuto) cancelAutoSolve();
playerState = INITIAL.slice();
playerHistory = [];
selectedTile = null;
playerBusy = false;
playerView.snapTo(INITIAL);
playerView.setSelected(null);
updatePlayerUI();
}
function cancelAutoSolve() {
autoToken++;
autoRunning = false;
document.querySelector("#autoSolveButton").disabled = false;
document.querySelector("#autoSolveButton").textContent =
"Try shortest on your board";
}
async function autoSolvePlayer() {
if (autoRunning) return;
cancelAutoSolve();
const token = autoToken;
autoRunning = true;
resetPlayer(false);
playerHistory = [];
const button = document.querySelector("#autoSolveButton");
button.disabled = true;
button.textContent = "Following shortest route…";
for (const move of solution.moves) {
if (token !== autoToken) return;
playerState = applyMove(playerState, move);
playerHistory.push({ ...move });
playerView.setBlank(playerState.indexOf(0));
updatePlayerUI();
await playerView.moveTile(move.tile, move.from, move.to, 145);
await new Promise((resolve) => setTimeout(resolve, 95));
}
if (token !== autoToken) return;
autoRunning = false;
button.disabled = false;
button.textContent = "Try shortest on your board";
updatePlayerUI();
showToast("Optimal route completed with no extra moves.");
}
function updatePlayerUI() {
const stateKey = playerState.join("");
const goalKey = GOAL.join("");
const optimalIndex = solution.stateIndex.get(stateKey);
const atGoal = stateKey === goalKey;
const optimalLength = solution.moves.length;
document.querySelector("#playerMoves").textContent = playerHistory.length;
document.querySelector("#undoButton").disabled =
playerHistory.length === 0 || playerBusy || autoRunning;
document.querySelectorAll(".dpad button").forEach((button) => {
button.disabled = selectedTile === null || playerBusy || autoRunning;
});
document.querySelector("#selectedTile").textContent =
selectedTile === null
? "No tile selected"
: `Tile ${selectedTile} selected`;
const badge = document.querySelector("#routeBadge");
badge.classList.remove("good", "warn");
if (atGoal && playerHistory.length === optimalLength) {
badge.textContent = "Optimal solve";
badge.classList.add("good");
} else if (atGoal) {
badge.textContent = `Solved · +${playerHistory.length - optimalLength}`;
badge.classList.add("warn");
} else if (optimalIndex !== undefined) {
badge.textContent = `On shortest path · ${optimalIndex}/${optimalLength}`;
badge.classList.add("good");
} else {
badge.textContent = "Exploring an alternate route";
badge.classList.add("warn");
}
document.querySelector("#moveGap").textContent = atGoal
? playerHistory.length === optimalLength
? "0"
: `+${playerHistory.length - optimalLength}`
: "—";
updatePlayerRoute();
}
function updatePlayerRoute() {
const container = document.querySelector("#playerRoute");
if (playerHistory.length === 0) {
container.innerHTML = `<span class="empty-route">No slides yet</span>`;
return;
}
let matchingPrefix = 0;
while (
matchingPrefix < playerHistory.length &&
matchingPrefix < solution.moves.length &&
playerHistory[matchingPrefix].tile === solution.moves[matchingPrefix].tile &&
playerHistory[matchingPrefix].dir === solution.moves[matchingPrefix].dir
) {
matchingPrefix++;
}
container.innerHTML = playerHistory
.map(
(move, index) => `
<span class="move-chip ${index < matchingPrefix ? "match" : ""}">
<b>${move.tile}</b>${ARROW[move.dir]}
</span>
`
)
.join("");
}
function buildOptimalRoute() {
const container = document.querySelector("#optimalRoute");
container.innerHTML = solution.moves
.map(
(move, index) => `
<span class="move-chip" data-solution-index="${index}">
<b>${move.tile}</b>${ARROW[move.dir]}
</span>
`
)
.join("");
}
// -------------------------------------------------------------------------
// Computed solution playback
// -------------------------------------------------------------------------
function playbackDelay() {
const speed = Number(document.querySelector("#solutionSpeed").value);
return REDUCED_MOTION ? 10 : 560 / speed;
}
function tileAnimationDuration() {
const speed = Number(document.querySelector("#solutionSpeed").value);
return REDUCED_MOTION ? 1 : 330 / speed;
}
async function solutionStep() {
if (solutionBusy || solutionIndex >= solution.moves.length) return;
solutionBusy = true;
const move = solution.moves[solutionIndex];
solutionState = applyMove(solutionState, move);
solutionView.setBlank(solutionState.indexOf(0));
await solutionView.moveTile(
move.tile,
move.from,
move.to,
tileAnimationDuration()
);
solutionIndex++;
solutionBusy = false;
updateSolutionUI();
}
async function solutionPrevious() {
if (solutionBusy || solutionIndex === 0) return;
pauseSolution();
solutionBusy = true;
const previous = solution.moves[solutionIndex - 1];
const inverse = {
tile: previous.tile,
from: previous.to,
to: previous.from,
dir: OPPOSITE[previous.dir]
};
solutionState = applyMove(solutionState, inverse);
solutionView.setBlank(solutionState.indexOf(0));
await solutionView.moveTile(
previous.tile,
previous.to,
previous.from,
tileAnimationDuration()
);
solutionIndex--;
solutionBusy = false;
updateSolutionUI();
}
function resetSolution() {
pauseSolution();
solutionState = INITIAL.slice();
solutionIndex = 0;
solutionBusy = false;
solutionView.snapTo(INITIAL);
updateSolutionUI();
}
function scheduleSolutionStep() {
clearTimeout(solutionTimer);
solutionTimer = setTimeout(async () => {
if (!solutionPlaying) return;
await solutionStep();
if (solutionPlaying) {
if (solutionIndex >= solution.moves.length) {
solutionPlaying = false;
updateSolutionUI();
} else {
scheduleSolutionStep();
}
}
}, playbackDelay());
}
function playSolution() {
if (solutionPlaying) {
pauseSolution();
return;
}
if (solutionIndex >= solution.moves.length) {
resetSolution();
}
solutionPlaying = true;
updateSolutionUI();
scheduleSolutionStep();
}
function pauseSolution() {
solutionPlaying = false;
clearTimeout(solutionTimer);
updateSolutionUI();
}
function updateSolutionUI() {
document.querySelector("#solutionStep").textContent =
`${solutionIndex} / ${solution.moves.length}`;
document.querySelector("#solutionPrevButton").disabled =
solutionBusy || solutionIndex === 0;
document.querySelector("#solutionNextButton").disabled =
solutionBusy || solutionIndex >= solution.moves.length;
const playButton = document.querySelector("#solutionPlayButton");
playButton.textContent = solutionPlaying
? "Ⅱ Pause"
: solutionIndex >= solution.moves.length
? "↻ Replay"
: "▶ Play";
document.querySelectorAll("[data-solution-index]").forEach((chip) => {
chip.classList.toggle(
"current",
Number(chip.dataset.solutionIndex) === solutionIndex - 1
);
});
}
// -------------------------------------------------------------------------
// DOM events
// -------------------------------------------------------------------------
document.querySelector("#undoButton").addEventListener("click", undoPlayer);
document.querySelector("#resetButton").addEventListener("click", () => resetPlayer());
document.querySelector("#resetAllButton").addEventListener("click", () => {
resetPlayer();
resetSolution();
});
document.querySelectorAll(".dpad button").forEach((button) => {
button.addEventListener("click", () => moveSelected(button.dataset.direction));
});
document.querySelector("#solutionPrevButton").addEventListener(
"click",
solutionPrevious
);
document.querySelector("#solutionNextButton").addEventListener(
"click",
solutionStep
);
document.querySelector("#solutionPlayButton").addEventListener(
"click",
playSolution
);
document.querySelector("#solutionResetButton").addEventListener(
"click",
resetSolution
);
document.querySelector("#solutionSpeed").addEventListener("change", () => {
if (solutionPlaying) scheduleSolutionStep();
});
document.querySelector("#autoSolveButton").addEventListener(
"click",
autoSolvePlayer
);
playerView.renderer.domElement.addEventListener("keydown", (event) => {
const keyMap = {
ArrowUp: "up",
ArrowDown: "down",
ArrowLeft: "left",
ArrowRight: "right"
};
if (keyMap[event.key]) {
event.preventDefault();
moveSelected(keyMap[event.key]);
return;
}
if (/^[1-8]$/.test(event.key)) {
event.preventDefault();
selectTile(Number(event.key));
}
});
let toastTimer;
function showToast(message) {
const toast = document.querySelector("#toast");
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 2300);
}
// Shared render loop.
function frame(now) {
playerView.render(now);
solutionView.render(now);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>
```