Prompt specification
Build or customize the Three.js 3D scene "Route a Knight to Every Target" 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: Route a Knight to Every Target
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/route-a-knight-to-every-target-x3608
Scene Description Prompt:
Create a bounded knight-path puzzle with target squares and optional blockers under declared rules. Verify the path from movement offsets and allow multiple valid solutions. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (route-a-knight-to-every-target-x3608):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Knight Relay — Voxel Path Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: rgba(10, 21, 32, 0.88);
--panel-strong: rgba(12, 25, 38, 0.96);
--border: rgba(154, 214, 235, 0.16);
--border-bright: rgba(154, 214, 235, 0.32);
--text: #edf8fb;
--muted: #91a8b4;
--cyan: #53e6ff;
--gold: #ffc857;
--green: #62e6a7;
--red: #ff6f7d;
--violet: #b899ff;
--shadow: 0 18px 60px rgba(0, 0, 0, 0.38);
}
* {
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,
select {
font: inherit;
}
button {
color: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand,
.top-badge {
pointer-events: auto;
border: 1px solid var(--border);
background: rgba(7, 16, 25, 0.78);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 260px;
padding: 10px 14px 10px 10px;
border-radius: 16px;
}
.brand-icon {
display: grid;
width: 42px;
height: 42px;
place-items: center;
border-radius: 12px;
color: #071019;
background: linear-gradient(145deg, #88f2ff, #3cc9e7);
box-shadow: 0 0 30px rgba(83, 230, 255, 0.25);
font-size: 27px;
font-weight: 900;
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: 0.02em;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.top-badge {
padding: 10px 13px;
border-radius: 999px;
color: #b9d0d9;
font-size: 12px;
}
.top-badge strong {
color: var(--cyan);
font-weight: 700;
}
.panel {
position: fixed;
z-index: 9;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
.left-panel {
top: 88px;
bottom: 76px;
left: 20px;
width: 322px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #34515e transparent;
}
.right-panel {
top: 88px;
right: 20px;
width: 286px;
padding: 18px;
}
.section {
padding: 17px;
border-bottom: 1px solid var(--border);
}
.section:last-child {
border-bottom: 0;
}
.eyebrow {
margin: 0 0 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h2,
h3,
p {
margin-top: 0;
}
h2 {
margin-bottom: 5px;
font-size: 20px;
}
h3 {
margin-bottom: 11px;
font-size: 13px;
letter-spacing: 0.02em;
}
.muted {
color: var(--muted);
}
.small {
font-size: 12px;
line-height: 1.5;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 13px 0;
}
.stat {
min-width: 0;
padding: 10px 7px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
text-align: center;
}
.stat span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 4px;
font-size: 18px;
}
.field {
margin-top: 12px;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.09em;
text-transform: uppercase;
}
select {
width: 100%;
padding: 10px 11px;
border: 1px solid var(--border-bright);
border-radius: 10px;
outline: none;
background: #0b1925;
color: var(--text);
font-size: 12px;
}
select:focus {
border-color: var(--cyan);
}
.button-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
button {
border: 1px solid var(--border-bright);
border-radius: 10px;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(83, 230, 255, 0.55);
background: rgba(83, 230, 255, 0.09);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: not-allowed;
opacity: 0.32;
}
button:focus-visible,
select:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.button-row > button {
flex: 1;
font-size: 12px;
font-weight: 700;
}
.mode-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.mode-btn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px;
text-align: left;
font-size: 12px;
font-weight: 700;
}
.mode-swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border-radius: 4px;
box-shadow: 0 0 12px currentColor;
}
.mode-btn.active {
border-color: var(--cyan);
background: rgba(83, 230, 255, 0.13);
box-shadow: inset 0 0 0 1px rgba(83, 230, 255, 0.15);
}
.mode-hint {
min-height: 34px;
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.legend {
display: grid;
gap: 8px;
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: #c5d7de;
font-size: 12px;
}
.legend-dot {
width: 11px;
height: 11px;
border-radius: 3px;
}
.rules {
margin: 0;
padding-left: 18px;
color: #b6c9d1;
font-size: 11px;
line-height: 1.55;
}
.rules li + li {
margin-top: 6px;
}
.rules code {
padding: 1px 4px;
border-radius: 4px;
background: rgba(83, 230, 255, 0.09);
color: #a8f2ff;
font-size: 10px;
}
.primary {
width: 100%;
margin-top: 14px;
padding: 13px;
border-color: rgba(83, 230, 255, 0.5);
background: linear-gradient(135deg, #57e9ff, #3ac5e2);
color: #06131a;
font-weight: 900;
letter-spacing: 0.03em;
box-shadow: 0 8px 28px rgba(83, 230, 255, 0.14);
}
.primary:hover:not(:disabled) {
border-color: #b9f7ff;
background: linear-gradient(135deg, #78efff, #50d4ee);
}
.status-card {
padding: 15px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.status-card[data-kind="success"] {
border-color: rgba(98, 230, 167, 0.34);
background: rgba(98, 230, 167, 0.07);
}
.status-card[data-kind="error"] {
border-color: rgba(255, 111, 125, 0.36);
background: rgba(255, 111, 125, 0.07);
}
.status-title {
margin: 4px 0 5px;
font-size: 17px;
font-weight: 850;
}
.status-card[data-kind="success"] .status-title {
color: var(--green);
}
.status-card[data-kind="error"] .status-title {
color: var(--red);
}
.status-detail {
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.order-title {
margin: 16px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.target-order {
display: flex;
flex-wrap: wrap;
gap: 7px;
min-height: 29px;
}
.order-chip {
padding: 6px 8px;
border: 1px solid rgba(255, 200, 87, 0.28);
border-radius: 8px;
background: rgba(255, 200, 87, 0.08);
color: var(--gold);
font-size: 10px;
font-weight: 800;
}
.solution-number {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--border);
}
.solution-number span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.solution-number strong {
color: var(--cyan);
font-size: 23px;
}
.solution-nav {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.solution-nav button {
font-size: 12px;
font-weight: 750;
}
#playButton {
width: 100%;
margin-top: 9px;
color: var(--cyan);
}
.sample-note {
margin: 8px 0 0;
color: #708894;
font-size: 10px;
line-height: 1.45;
text-align: center;
}
.bottom-bar {
position: fixed;
z-index: 10;
right: 20px;
bottom: 18px;
left: 20px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.hint,
.camera-controls {
pointer-events: auto;
border: 1px solid var(--border);
background: rgba(7, 16, 25, 0.78);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
}
.hint {
margin-left: 362px;
padding: 10px 13px;
border-radius: 12px;
color: var(--muted);
font-size: 11px;
}
.hint kbd {
display: inline-block;
margin: 0 2px;
padding: 2px 5px;
border: 1px solid var(--border-bright);
border-radius: 4px;
background: rgba(255, 255, 255, 0.05);
color: #d9edf2;
font: inherit;
font-size: 10px;
}
.camera-controls {
display: flex;
gap: 7px;
padding: 7px;
border-radius: 12px;
}
.camera-controls button {
padding: 8px 10px;
border: 0;
background: transparent;
color: #b5cbd4;
font-size: 11px;
font-weight: 750;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 27px;
max-width: min(90vw, 460px);
padding: 11px 15px;
border: 1px solid var(--border-bright);
border-radius: 10px;
background: var(--panel-strong);
box-shadow: var(--shadow);
color: #d8ebf0;
font-size: 12px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition:
opacity 160ms ease,
transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 960px) {
.right-panel {
width: 250px;
}
.hint {
display: none;
}
}
@media (max-width: 720px) {
.topbar {
top: 10px;
right: 10px;
left: 10px;
}
.brand {
min-width: 0;
}
.brand p,
.top-badge {
display: none;
}
.left-panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 42vh;
}
.right-panel {
top: 72px;
right: 10px;
width: 230px;
padding: 12px;
}
.section {
padding: 13px;
}
.rules {
display: none;
}
.bottom-bar {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="topbar">
<div class="brand">
<div class="brand-icon" aria-hidden="true">♞</div>
<div>
<h1>Knight Relay</h1>
<p>Bounded voxel path laboratory</p>
</div>
</div>
<div class="top-badge">
<strong>8 × 8</strong> bounded board · standard knight offsets
</div>
</header>
<aside class="panel left-panel" aria-label="Puzzle controls">
<section class="section">
<p class="eyebrow">Puzzle setup</p>
<h2>Build a route</h2>
<p class="muted small">
Place targets, add optional blockers, then verify the knight's path.
</p>
<div class="stats">
<div class="stat">
<span>Targets</span>
<strong id="targetCount">0</strong>
</div>
<div class="stat">
<span>Blockers</span>
<strong id="blockerCount">0</strong>
</div>
<div class="stat">
<span>Board</span>
<strong>64</strong>
</div>
</div>
<div class="field">
<label for="presetSelect">Preset</label>
<select id="presetSelect">
<option value="open">Open Sprint</option>
<option value="gate">Gate Run</option>
<option value="switchback">Switchback</option>
</select>
</div>
<div class="field">
<label for="difficultySelect">Random difficulty</label>
<select id="difficultySelect">
<option value="easy">Relaxed — 3 targets / 3 blockers</option>
<option value="classic" selected>Classic — 4 targets / 6 blockers</option>
<option value="hard">Dense — 5 targets / 9 blockers</option>
</select>
</div>
<div class="button-row">
<button id="randomizeButton" type="button">Randomize</button>
<button id="resetButton" type="button">Reset preset</button>
</div>
</section>
<section class="section">
<p class="eyebrow">Board editor</p>
<h3>Select an edit tool</h3>
<div class="mode-grid" role="group" aria-label="Editing mode">
<button class="mode-btn active" data-mode="target" type="button">
<span class="mode-swatch" style="color:#ffc857;background:#ffc857"></span>
Target
</button>
<button class="mode-btn" data-mode="blocker" type="button">
<span class="mode-swatch" style="color:#ff6f7d;background:#ff6f7d"></span>
Blocker
</button>
<button class="mode-btn" data-mode="start" type="button">
<span class="mode-swatch" style="color:#62e6a7;background:#62e6a7"></span>
Start
</button>
<button class="mode-btn" data-mode="erase" type="button">
<span class="mode-swatch" style="color:#b899ff;background:#b899ff"></span>
Erase
</button>
</div>
<p id="modeHint" class="mode-hint">
Click a square to toggle a target. A target cannot share a square with a blocker.
</p>
</section>
<section class="section">
<h3>Board legend</h3>
<div class="legend">
<div class="legend-item">
<span class="legend-dot" style="background:#62e6a7"></span>
Start square
</div>
<div class="legend-item">
<span class="legend-dot" style="background:#ffc857"></span>
Required target
</div>
<div class="legend-item">
<span class="legend-dot" style="background:#e14e61"></span>
Blocked landing square
</div>
<div class="legend-item">
<span class="legend-dot" style="background:#53e6ff"></span>
Verified route
</div>
</div>
</section>
<section class="section">
<p class="eyebrow">Declared rules</p>
<ol class="rules">
<li>The board is a bounded <code>8 × 8</code> grid; moves never wrap.</li>
<li>A legal knight move is <code>(±1, ±2)</code> or <code>(±2, ±1)</code>.</li>
<li>The knight begins on <code>S</code> and must land only on in-bounds, non-blocked squares.</li>
<li>Blockers may be jumped over; only the landing square matters.</li>
<li>Every target must be visited at least once. Target order is unrestricted, and revisits are allowed.</li>
<li>All valid routes are accepted. The verifier reports and can display multiple shortest routes.</li>
</ol>
<button id="verifyButton" class="primary" type="button">Verify knight path</button>
</section>
</aside>
<aside class="panel right-panel" aria-label="Solution status">
<div id="statusCard" class="status-card" data-kind="neutral" aria-live="polite">
<p class="eyebrow">Route status</p>
<div id="statusTitle" class="status-title">Awaiting verification</div>
<div id="statusDetail" class="status-detail">
Select a preset or edit the board, then verify the route.
</div>
</div>
<div class="order-title">Target visit order</div>
<div id="targetOrder" class="target-order">
<span class="muted small">No route yet</span>
</div>
<div class="solution-number">
<span>Shortest solutions</span>
<strong id="solutionCount">—</strong>
</div>
<div class="solution-nav">
<button id="previousButton" type="button" disabled>← Previous</button>
<button id="nextButton" type="button" disabled>Next →</button>
</div>
<button id="playButton" type="button" disabled>▶ Play route</button>
<p id="sampleNote" class="sample-note">
Alternative shortest routes will appear here when available.
</p>
</aside>
<div class="bottom-bar">
<div class="hint">
<kbd>Drag</kbd> orbit · <kbd>Wheel</kbd> zoom · <kbd>V</kbd> verify ·
<kbd>Space</kbd> play/pause · <kbd>←</kbd> <kbd>→</kbd> alternate route
</div>
<div class="camera-controls">
<button id="cameraResetButton" type="button">Reset view</button>
<button id="cameraTopButton" type="button">Top view</button>
</div>
</div>
<div id="toast" role="status"></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 SIZE = 8;
const MAX_SAMPLED_SOLUTIONS = 64;
// The complete set of legal knight offsets.
const KNIGHT_OFFSETS = [
[1, 2],
[2, 1],
[-1, 2],
[-2, 1],
[1, -2],
[2, -1],
[-1, -2],
[-2, -1]
];
const PRESETS = {
open: {
start: 0,
targets: [10, 42, 21, 53],
blockers: []
},
gate: {
start: 0,
targets: [10, 42, 21, 53],
blockers: [3, 18, 9, 12, 14, 46, 31, 13]
},
switchback: {
start: 0,
targets: [10, 42, 21, 53, 59],
blockers: [3, 18, 9, 12, 14, 50, 46, 31, 13, 29]
}
};
const $ = (id) => document.getElementById(id);
const viewport = $("viewport");
let start = 0;
let targets = new Set();
let blockers = new Set();
let activeMode = "target";
let targetIndex = new Map();
let targetAnimations = [];
let solutions = [];
let solutionIndex = 0;
let solutionCount = 0;
let currentPath = [];
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const animation = {
elapsed: 0,
playing: false,
moveDuration: 0.56
};
const idToX = (id) => id % SIZE;
const idToZ = (id) => Math.floor(id / SIZE);
const xzToId = (x, z) => z * SIZE + x;
const inBounds = (x, z) => x >= 0 && x < SIZE && z >= 0 && z < SIZE;
const boardX = (id) => idToX(id) - (SIZE - 1) / 2;
const boardZ = (id) => idToZ(id) - (SIZE - 1) / 2;
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 17, 36);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive 3D knight path puzzle board");
viewport.appendChild(renderer.domElement);
const cameraState = {
theta: 0.64,
phi: 0.77,
radius: 14.5
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.radius * Math.cos(cameraState.phi),
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(0, 0, 0);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbdeeff, 0x17212b, 1.6);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(7, 12, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const cyanRim = new THREE.PointLight(0x43dfff, 20, 18, 2);
cyanRim.position.set(-6, 4, -5);
scene.add(cyanRim);
const warmRim = new THREE.PointLight(0xffba5d, 13, 15, 2);
warmRim.position.set(6, 3, 5);
scene.add(warmRim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x071019,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.72;
ground.receiveShadow = true;
scene.add(ground);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(SIZE + 0.34, 0.42, SIZE + 0.34),
new THREE.MeshStandardMaterial({
color: 0x142735,
roughness: 0.72,
metalness: 0.18
})
);
platform.position.y = -0.32;
platform.castShadow = true;
platform.receiveShadow = true;
scene.add(platform);
const platformTrim = new THREE.Mesh(
new THREE.BoxGeometry(SIZE + 0.39, 0.055, SIZE + 0.39),
new THREE.MeshStandardMaterial({
color: 0x287087,
emissive: 0x123a47,
emissiveIntensity: 0.8,
roughness: 0.55,
metalness: 0.35
})
);
platformTrim.position.y = -0.535;
scene.add(platformTrim);
const tileMeshes = [];
const tileGeometry = new THREE.BoxGeometry(0.91, 0.18, 0.91);
const tileMaterials = [
new THREE.MeshStandardMaterial({
color: 0x163041,
roughness: 0.78,
metalness: 0.08
}),
new THREE.MeshStandardMaterial({
color: 0x102735,
roughness: 0.82,
metalness: 0.06
})
];
for (let z = 0; z < SIZE; z++) {
for (let x = 0; x < SIZE; x++) {
const id = xzToId(x, z);
const tile = new THREE.Mesh(
tileGeometry,
tileMaterials[(x + z) % 2]
);
tile.position.set(boardX(id), -0.02, boardZ(id));
tile.receiveShadow = true;
tile.castShadow = true;
tile.userData.id = id;
scene.add(tile);
tileMeshes.push(tile);
}
}
const hoverMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.96, 0.045, 0.96),
new THREE.MeshBasicMaterial({
color: 0x8deeff,
transparent: true,
opacity: 0.22,
depthWrite: false
})
);
hoverMesh.visible = false;
scene.add(hoverMesh);
const specialsGroup = new THREE.Group();
const pathGroup = new THREE.Group();
scene.add(specialsGroup, pathGroup);
// -------------------------------------------------------------------------
// Voxel knight
// -------------------------------------------------------------------------
function createKnight() {
const knight = new THREE.Group();
const silver = new THREE.MeshStandardMaterial({
color: 0xd9f6ff,
roughness: 0.27,
metalness: 0.58,
emissive: 0x123743,
emissiveIntensity: 0.35
});
const dark = new THREE.MeshStandardMaterial({
color: 0x31576a,
roughness: 0.42,
metalness: 0.45
});
const accent = new THREE.MeshStandardMaterial({
color: 0x53e6ff,
emissive: 0x1b7c91,
emissiveIntensity: 1.25,
roughness: 0.35,
metalness: 0.4
});
function box(parent, sx, sy, sz, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(sx, sy, sz),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
box(knight, 0.35, 0.29, 0.44, 0, 0.42, 0.04, silver);
box(knight, 0.28, 0.29, 0.26, 0, 0.68, -0.055, silver);
box(knight, 0.32, 0.26, 0.28, 0, 0.91, -0.13, silver);
box(knight, 0.19, 0.14, 0.24, 0, 0.83, -0.32, dark);
box(knight, 0.10, 0.19, 0.10, -0.095, 1.10, -0.08, silver);
box(knight, 0.10, 0.19, 0.10, 0.095, 1.10, -0.08, silver);
for (const x of [-0.11, 0.11]) {
for (const z of [-0.12, 0.13]) {
box(knight, 0.115, 0.25, 0.115, x, 0.16, z, dark);
}
}
box(knight, 0.31, 0.055, 0.34, 0, 0.575, 0.04, accent);
box(knight, 0.025, 0.13, 0.025, -0.165, 0.93, -0.18, accent);
box(knight, 0.025, 0.13, 0.025, 0.165, 0.93, -0.18, accent);
return knight;
}
const knight = createKnight();
scene.add(knight);
// -------------------------------------------------------------------------
// Text sprites and board labels
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeTextSprite(
text,
foreground = "#eafaff",
background = "rgba(5, 15, 23, 0.82)",
size = 128
) {
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, size, size);
if (background) {
ctx.fillStyle = background;
roundedRect(ctx, 8, 8, size - 16, size - 16, 22);
ctx.fill();
ctx.strokeStyle = "rgba(150, 230, 255, 0.22)";
ctx.lineWidth = 3;
ctx.stroke();
}
ctx.fillStyle = foreground;
ctx.font = `800 ${Math.round(size * 0.48)}px ui-sans-serif, system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, size / 2, size / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
return new THREE.Sprite(material);
}
const coordinateGroup = new THREE.Group();
scene.add(coordinateGroup);
for (let x = 0; x < SIZE; x++) {
const sprite = makeTextSprite(
String.fromCharCode(65 + x),
"#6d8c99",
"rgba(0,0,0,0)",
64
);
sprite.position.set(x - 3.5, -0.19, 4.38);
sprite.scale.set(0.34, 0.34, 1);
coordinateGroup.add(sprite);
}
for (let z = 0; z < SIZE; z++) {
const sprite = makeTextSprite(
String(z + 1),
"#6d8c99",
"rgba(0,0,0,0)",
64
);
sprite.position.set(-4.38, -0.19, z - 3.5);
sprite.scale.set(0.34, 0.34, 1);
coordinateGroup.add(sprite);
}
// -------------------------------------------------------------------------
// Special-square visuals
// -------------------------------------------------------------------------
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) {
if (material.map) {
material.map.dispose();
}
material.dispose();
}
}
});
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children[0];
group.remove(child);
disposeObject(child);
}
}
function addBox(parent, sx, sy, sz, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(sx, sy, sz),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function rebuildSpecials() {
clearGroup(specialsGroup);
targetAnimations = [];
const orderedTargets = [...targets].sort((a, b) => a - b);
targetIndex = new Map(
orderedTargets.map((id, index) => [id, index])
);
const gold = new THREE.MeshStandardMaterial({
color: 0xffca5b,
emissive: 0xa65b05,
emissiveIntensity: 0.75,
roughness: 0.36,
metalness: 0.35
});
const goldBright = new THREE.MeshStandardMaterial({
color: 0xffe49b,
emissive: 0xffa51c,
emissiveIntensity: 1.5,
roughness: 0.28,
metalness: 0.2
});
for (const id of orderedTargets) {
const group = new THREE.Group();
group.position.set(boardX(id), 0.08, boardZ(id));
for (const x of [-0.23, 0.23]) {
for (const z of [-0.23, 0.23]) {
addBox(group, 0.075, 0.31, 0.075, x, 0.16, z, gold);
}
}
addBox(group, 0.53, 0.055, 0.53, 0, 0.035, 0, gold);
const core = addBox(
group,
0.19,
0.19,
0.19,
0,
0.19,
0,
goldBright
);
const label = makeTextSprite(`T${targetIndex.get(id) + 1}`, "#ffe4a0");
label.position.set(0, 0.98, 0);
label.scale.set(0.48, 0.48, 1);
group.add(label);
group.userData.core = core;
group.userData.phase = targetIndex.get(id) * 0.8;
targetAnimations.push(group);
specialsGroup.add(group);
}
const blockerMaterial = new THREE.MeshStandardMaterial({
color: 0x8f3442,
roughness: 0.56,
metalness: 0.25
});
const blockerTop = new THREE.MeshStandardMaterial({
color: 0xff6071,
emissive: 0x6e1020,
emissiveIntensity: 0.85,
roughness: 0.38,
metalness: 0.28
});
for (const id of blockers) {
const group = new THREE.Group();
group.position.set(boardX(id), 0.07, boardZ(id));
addBox(group, 0.72, 1.05, 0.72, 0, 0.525, 0, blockerMaterial);
addBox(group, 0.56, 0.13, 0.56, 0, 1.105, 0, blockerTop);
addBox(group, 0.76, 0.08, 0.16, 0, 0.72, 0, blockerTop);
specialsGroup.add(group);
}
const startMaterial = new THREE.MeshStandardMaterial({
color: 0x62e6a7,
emissive: 0x16734a,
emissiveIntensity: 1.15,
roughness: 0.4,
metalness: 0.28
});
const startGroup = new THREE.Group();
startGroup.position.set(boardX(start), 0.08, boardZ(start));
for (const x of [-0.32, 0.32]) {
for (const z of [-0.32, 0.32]) {
addBox(startGroup, 0.095, 0.18, 0.095, x, 0.10, z, startMaterial);
}
}
const startLabel = makeTextSprite("S", "#b9ffe0");
startLabel.position.set(0, 1.08, 0);
startLabel.scale.set(0.48, 0.48, 1);
startGroup.add(startLabel);
specialsGroup.add(startGroup);
}
// -------------------------------------------------------------------------
// Solver
//
// State = (knight square, bitmask of collected targets).
// BFS finds the shortest solution length. A backward pass counts every
// shortest route and samples up to MAX_SAMPLED_SOLUTIONS distinct routes.
// -------------------------------------------------------------------------
function solvePuzzle() {
const orderedTargets = [...targets].sort((a, b) => a - b);
if (orderedTargets.length === 0) {
return {
ok: false,
reason: "Add at least one target square before verifying."
};
}
const bitMap = new Map(
orderedTargets.map((id, index) => [id, 1 << index])
);
const fullMask = (1 << orderedTargets.length) - 1;
const startMask = bitMap.get(start) || 0;
const keyFor = (position, mask) => `${position}|${mask}`;
function nextPositions(position) {
const x = idToX(position);
const z = idToZ(position);
const result = [];
for (const [dx, dz] of KNIGHT_OFFSETS) {
const nx = x + dx;
const nz = z + dz;
if (!inBounds(nx, nz)) {
continue;
}
const nextId = xzToId(nx, nz);
if (blockers.has(nextId)) {
continue;
}
result.push(nextId);
}
return result;
}
const startState = {
position: start,
mask: startMask
};
const startKey = keyFor(startState.position, startState.mask);
const distance = new Map([[startKey, 0]]);
const layers = [[startState]];
const queue = [startState];
for (let head = 0; head < queue.length; head++) {
const state = queue[head];
const stateKey = keyFor(state.position, state.mask);
const depth = distance.get(stateKey);
for (const nextPosition of nextPositions(state.position)) {
const nextMask =
state.mask | (bitMap.get(nextPosition) || 0);
const nextKey = keyFor(nextPosition, nextMask);
if (distance.has(nextKey)) {
continue;
}
const nextState = {
position: nextPosition,
mask: nextMask
};
distance.set(nextKey, depth + 1);
queue.push(nextState);
if (!layers[depth + 1]) {
layers[depth + 1] = [];
}
layers[depth + 1].push(nextState);
}
}
const goals = queue.filter((state) => state.mask === fullMask);
if (goals.length === 0) {
return {
ok: false,
reason: "No route exists. A target is blocked off or the blockers separate the board."
};
}
const shortestLength = Math.min(
...goals.map((goal) => distance.get(keyFor(goal.position, goal.mask)))
);
const goodStates = new Set();
const pathCounts = new Map();
for (const goal of goals) {
const goalKey = keyFor(goal.position, goal.mask);
if (distance.get(goalKey) === shortestLength) {
goodStates.add(goalKey);
pathCounts.set(goalKey, 1);
}
}
// Backward dynamic programming over shortest-route states.
for (let depth = shortestLength; depth > 0; depth--) {
for (const state of layers[depth - 1]) {
let count = 0;
for (const nextPosition of nextPositions(state.position)) {
const nextMask =
state.mask | (bitMap.get(nextPosition) || 0);
const nextKey = keyFor(nextPosition, nextMask);
if (
goodStates.has(nextKey) &&
distance.get(nextKey) === depth
) {
count += pathCounts.get(nextKey) || 0;
}
}
if (count > 0) {
const stateKey = keyFor(state.position, state.mask);
goodStates.add(stateKey);
pathCounts.set(stateKey, count);
}
}
}
// Collect a bounded set of distinct shortest solutions for playback.
const sampledPaths = [];
function collectPaths(state, path) {
if (sampledPaths.length >= MAX_SAMPLED_SOLUTIONS) {
return;
}
if (state.mask === fullMask) {
sampledPaths.push([...path]);
return;
}
const stateKey = keyFor(state.position, state.mask);
const depth = distance.get(stateKey);
for (const nextPosition of nextPositions(state.position)) {
const nextMask =
state.mask | (bitMap.get(nextPosition) || 0);
const nextKey = keyFor(nextPosition, nextMask);
if (
goodStates.has(nextKey) &&
distance.get(nextKey) === depth + 1
) {
collectPaths(
{
position: nextPosition,
mask: nextMask
},
[...path, nextPosition]
);
}
}
}
collectPaths(startState, []);
return {
ok: true,
count: pathCounts.get(startKey) || 0,
paths: sampledPaths,
length: shortestLength
};
}
// -------------------------------------------------------------------------
// Route rendering and animation
// -------------------------------------------------------------------------
function setKnightAt(id) {
knight.position.set(boardX(id), 0.08, boardZ(id));
knight.rotation.y = 0;
}
function clearRoute() {
clearGroup(pathGroup);
currentPath = [];
animation.elapsed = 0;
animation.playing = false;
setKnightAt(start);
updatePlayButton();
}
function drawRoute(path, autoplay = true) {
clearGroup(pathGroup);
currentPath = [...path];
const points = [start, ...currentPath].map((id) =>
new THREE.Vector3(boardX(id), 0.24, boardZ(id))
);
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(
lineGeometry,
new THREE.LineBasicMaterial({
color: 0x53e6ff,
transparent: true,
opacity: 0.72,
depthTest: true
})
);
pathGroup.add(line);
const markerGeometry = new THREE.BoxGeometry(0.19, 0.09, 0.19);
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0x65eaff,
emissive: 0x167b92,
emissiveIntensity: 1.3,
roughness: 0.3,
metalness: 0.3
});
points.forEach((point, index) => {
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
marker.position.copy(point);
marker.position.y = 0.14;
marker.castShadow = true;
pathGroup.add(marker);
const label = makeTextSprite(
index === 0 ? "S" : String(index),
"#d9fbff",
"rgba(4, 26, 35, 0.88)",
64
);
label.position.set(point.x, 0.36, point.z);
label.scale.set(0.28, 0.28, 1);
pathGroup.add(label);
});
animation.elapsed = 0;
animation.playing = autoplay && currentPath.length > 0 && !reducedMotion;
setKnightAt(start);
updatePlayButton();
updateTargetOrder();
}
function updateTargetOrder() {
const orderElement = $("targetOrder");
orderElement.replaceChildren();
if (currentPath.length === 0 && solutions.length === 0) {
const empty = document.createElement("span");
empty.className = "muted small";
empty.textContent = "No route yet";
orderElement.appendChild(empty);
return;
}
const seen = new Set();
const route = [start, ...currentPath];
for (const id of route) {
if (!targetIndex.has(id) || seen.has(id)) {
continue;
}
seen.add(id);
const chip = document.createElement("span");
chip.className = "order-chip";
chip.textContent = `T${targetIndex.get(id) + 1}`;
orderElement.appendChild(chip);
}
}
function updatePlayButton() {
const button = $("playButton");
button.disabled = currentPath.length === 0;
if (animation.playing) {
button.textContent = "Ⅱ Pause route";
} else if (currentPath.length > 0) {
const finished =
animation.elapsed >= currentPath.length * animation.moveDuration;
button.textContent = finished ? "↻ Replay route" : "▶ Continue route";
} else {
button.textContent = "▶ Play route";
}
}
function updateSolutionNavigation() {
$("previousButton").disabled = solutions.length < 2;
$("nextButton").disabled = solutions.length < 2;
if (solutions.length > 0) {
$("sampleNote").textContent =
solutions.length < solutionCount
? `Showing ${solutions.length} of ${solutionCount.toLocaleString()} shortest routes.`
: `Showing all ${solutionCount.toLocaleString()} shortest routes.`;
} else {
$("sampleNote").textContent =
"Alternative shortest routes will appear here when available.";
}
}
function updateKnightAnimation(delta) {
if (!animation.playing || currentPath.length === 0) {
return;
}
animation.elapsed += delta;
const total = currentPath.length * animation.moveDuration;
if (animation.elapsed >= total) {
animation.elapsed = total;
animation.playing = false;
const finalId = currentPath[currentPath.length - 1];
setKnightAt(finalId);
updatePlayButton();
return;
}
const segment = Math.min(
currentPath.length - 1,
Math.floor(animation.elapsed / animation.moveDuration)
);
const fraction =
(animation.elapsed - segment * animation.moveDuration) /
animation.moveDuration;
const fromId = segment === 0 ? start : currentPath[segment - 1];
const toId = currentPath[segment];
const fromX = boardX(fromId);
const fromZ = boardZ(fromId);
const toX = boardX(toId);
const toZ = boardZ(toId);
knight.position.x = THREE.MathUtils.lerp(fromX, toX, fraction);
knight.position.z = THREE.MathUtils.lerp(fromZ, toZ, fraction);
knight.position.y = 0.08 + Math.sin(fraction * Math.PI) * 0.95;
const dx = toX - fromX;
const dz = toZ - fromZ;
knight.rotation.y = Math.atan2(-dx, -dz);
}
// -------------------------------------------------------------------------
// Status and UI
// -------------------------------------------------------------------------
function setStatus(kind, title, detail) {
$("statusCard").dataset.kind = kind;
$("statusTitle").textContent = title;
$("statusDetail").textContent = detail;
}
let toastTimeout;
function toast(message) {
const element = $("toast");
element.textContent = message;
element.classList.add("show");
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => {
element.classList.remove("show");
}, 2400);
}
function updateStats() {
$("targetCount").textContent = targets.size;
$("blockerCount").textContent = blockers.size;
}
function clearSolution() {
solutions = [];
solutionIndex = 0;
solutionCount = 0;
$("solutionCount").textContent = "—";
clearRoute();
updateSolutionNavigation();
updateTargetOrder();
}
function verifySolution() {
const result = solvePuzzle();
if (!result.ok) {
clearSolution();
setStatus("error", "No valid route", result.reason);
return;
}
solutions = result.paths;
solutionIndex = 0;
solutionCount = result.count;
$("solutionCount").textContent = result.count.toLocaleString();
drawRoute(solutions[0], true);
updateSolutionNavigation();
const routeWord = result.count === 1 ? "route" : "routes";
setStatus(
"success",
"Route verified",
`${result.length} move${result.length === 1 ? "" : "s"} · ${result.count.toLocaleString()} shortest ${routeWord}. Target order is unrestricted.`
);
}
function showAlternative(offset) {
if (solutions.length < 2) {
return;
}
solutionIndex =
(solutionIndex + offset + solutions.length) % solutions.length;
drawRoute(solutions[solutionIndex], true);
}
function togglePlayback() {
if (currentPath.length === 0) {
return;
}
if (
!animation.playing &&
animation.elapsed >= currentPath.length * animation.moveDuration
) {
animation.elapsed = 0;
}
animation.playing = !animation.playing;
updatePlayButton();
}
function setMode(mode) {
activeMode = mode;
document.querySelectorAll(".mode-btn").forEach((button) => {
button.classList.toggle("active", button.dataset.mode === mode);
});
const hints = {
target: "Click a square to toggle a target. A target cannot share a square with a blocker.",
blocker: "Click a square to add or remove a blocker. The start square cannot be blocked.",
start: "Click any square to move the knight's starting position.",
erase: "Click a square to remove its target and blocker markers."
};
$("modeHint").textContent = hints[mode];
}
function editSquare(id) {
let changed = false;
if (activeMode === "target") {
if (targets.has(id)) {
targets.delete(id);
} else {
targets.add(id);
blockers.delete(id);
}
changed = true;
} else if (activeMode === "blocker") {
if (id === start) {
toast("The start square cannot be blocked.");
return;
}
if (blockers.has(id)) {
blockers.delete(id);
} else {
blockers.add(id);
targets.delete(id);
}
changed = true;
} else if (activeMode === "start") {
if (id !== start) {
start = id;
blockers.delete(id);
changed = true;
}
} else if (activeMode === "erase") {
if (targets.delete(id) || blockers.delete(id)) {
changed = true;
}
}
if (!changed) {
return;
}
clearSolution();
rebuildSpecials();
updateStats();
setStatus(
"neutral",
"Board edited",
"The previous result was cleared. Verify again when the board is ready."
);
}
// -------------------------------------------------------------------------
// Presets and random generation
// -------------------------------------------------------------------------
function loadPreset(name) {
const preset = PRESETS[name] || PRESETS.gate;
start = preset.start;
targets = new Set(preset.targets);
blockers = new Set(preset.blockers);
clearSolution();
rebuildSpecials();
updateStats();
setStatus(
"neutral",
"Puzzle ready",
"Edit the board or verify the current arrangement."
);
}
function randomInteger(max) {
return Math.floor(Math.random() * max);
}
function shuffledNumbers(count) {
const values = Array.from({ length: count }, (_, index) => index);
for (let index = values.length - 1; index > 0; index--) {
const swapIndex = randomInteger(index + 1);
[values[index], values[swapIndex]] = [
values[swapIndex],
values[index]
];
}
return values;
}
function randomizePuzzle() {
const difficulty = $("difficultySelect").value;
const settings = {
easy: { targetCount: 3, blockerCount: 3 },
classic: { targetCount: 4, blockerCount: 6 },
hard: { targetCount: 5, blockerCount: 9 }
}[difficulty];
let fallback = null;
for (let attempt = 0; attempt < 350; attempt++) {
const candidateStart = randomInteger(SIZE * SIZE);
const available = shuffledNumbers(SIZE * SIZE).filter(
(id) => id !== candidateStart
);
const candidateTargets = new Set(
available.slice(0, settings.targetCount)
);
const candidateBlockers = new Set(
available
.slice(settings.targetCount, settings.targetCount + settings.blockerCount)
.filter((id) => !candidateTargets.has(id))
);
start = candidateStart;
targets = candidateTargets;
blockers = candidateBlockers;
const result = solvePuzzle();
if (!result.ok) {
continue;
}
const candidate = {
start,
targets: new Set(targets),
blockers: new Set(blockers),
result
};
if (!fallback) {
fallback = candidate;
}
// Prefer a puzzle with more than one shortest solution.
if (result.count > 1) {
start = candidate.start;
targets = candidate.targets;
blockers = candidate.blockers;
break;
}
}
if (fallback && solutionCount < 2) {
// Keep the fallback if no multi-solution board was found.
const multiFound = (() => {
start = fallback.start;
targets = fallback.targets;
blockers = fallback.blockers;
return fallback.result.count > 1;
})();
if (!multiFound) {
start = fallback.start;
targets = fallback.targets;
blockers = fallback.blockers;
}
}
clearSolution();
rebuildSpecials();
updateStats();
const verified = solvePuzzle();
setStatus(
"neutral",
"New puzzle generated",
verified.ok
? `${verified.count.toLocaleString()} shortest route${verified.count === 1 ? "" : "s"} found. Verify or edit the board.`
: "Generated board needs another verification pass."
);
toast("A fresh solvable board has been generated.");
}
// -------------------------------------------------------------------------
// Picking and custom camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickTile(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(tileMeshes, false);
if (intersections.length > 0) {
editSquare(intersections[0].object.userData.id);
}
}
function updateHover(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(tileMeshes, false);
if (intersections.length > 0) {
const id = intersections[0].object.userData.id;
hoverMesh.position.set(boardX(id), 0.095, boardZ(id));
hoverMesh.visible = true;
renderer.domElement.style.cursor = "pointer";
} else {
hoverMesh.visible = false;
renderer.domElement.style.cursor = "grab";
}
}
const pointerState = {
down: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
total: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) {
return;
}
pointerState.down = true;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.total = 0;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerState.down) {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.total = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (pointerState.total > 4) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.08,
1.32
);
hoverMesh.visible = false;
updateCamera();
}
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerState.down) {
return;
}
const wasClick = pointerState.total < 5;
pointerState.down = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
if (wasClick) {
pickTile(event);
}
updateHover(event);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState.down = false;
hoverMesh.visible = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerState.down) {
hoverMesh.visible = false;
}
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.008,
9,
22
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
document.querySelectorAll(".mode-btn").forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
$("presetSelect").addEventListener("change", (event) => {
loadPreset(event.target.value);
});
$("resetButton").addEventListener("click", () => {
loadPreset($("presetSelect").value);
toast("Preset restored.");
});
$("randomizeButton").addEventListener("click", randomizePuzzle);
$("verifyButton").addEventListener("click", verifySolution);
$("playButton").addEventListener("click", togglePlayback);
$("previousButton").addEventListener("click", () => showAlternative(-1));
$("nextButton").addEventListener("click", () => showAlternative(1));
$("cameraResetButton").addEventListener("click", () => {
cameraState.theta = 0.64;
cameraState.phi = 0.77;
cameraState.radius = 14.5;
updateCamera();
});
$("cameraTopButton").addEventListener("click", () => {
cameraState.theta = 0;
cameraState.phi = 0.08;
cameraState.radius = 12.8;
updateCamera();
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLSelectElement
) {
return;
}
if (event.key.toLowerCase() === "v") {
verifySolution();
} else if (event.code === "Space") {
event.preventDefault();
togglePlayback();
} else if (event.key === "ArrowLeft") {
showAlternative(-1);
} else if (event.key === "ArrowRight") {
showAlternative(1);
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Start and render loop
// -------------------------------------------------------------------------
loadPreset("gate");
let previousTime = performance.now();
function animate(time) {
const delta = Math.min(0.05, (time - previousTime) / 1000);
previousTime = time;
updateKnightAnimation(delta);
const pulse = time * 0.003;
for (const target of targetAnimations) {
const core = target.userData.core;
core.position.y = 0.19 + Math.sin(pulse + target.userData.phase) * 0.045;
core.rotation.y = pulse * 0.65 + target.userData.phase;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```