Certainly! Below is a complete example of a 15 puzzle (sliding puzzle) implemented and visualized in the browser using Three.js. The puzzle consists of a 4x4 grid with 15 numbered tiles and one empty space. You can click on tiles adjacent to the empty space to slide them.
How it works:
- The puzzle is rendered as 3D tiles on a flat plane.
- Each tile is a square with a number on it.
- Clicking a tile adjacent to the empty space slides it into the empty space.
- The empty space is visually represented by the absence of a tile.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>15 Puzzle with Three.js</title>
<style>
body { margin: 0; overflow: hidden; }
#info {
position: absolute;
top: 10px; left: 10px;
color: #fff;
font-family: sans-serif;
z-index: 1;
user-select: none;
}
#shuffleBtn {
margin-top: 10px;
padding: 5px 10px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="info">
<div>Click tiles adjacent to the empty space to slide.</div>
<button id="shuffleBtn">Shuffle</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.152.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.152.2/examples/js/controls/OrbitControls.min.js"></script>
<script>
// Basic setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x202020);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 15, 20);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Controls (optional, for better view)
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enablePan = false;
controls.minDistance = 10;
controls.maxDistance = 40;
controls.maxPolarAngle = Math.PI / 2.2;
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight.position.set(10, 20, 10);
scene.add(directionalLight);
// Puzzle parameters
const gridSize = 4;
const tileSize = 3;
const tileSpacing = 0.1;
const tileFullSize = tileSize + tileSpacing;
// Data structure for puzzle state
// 0 represents empty space
let puzzle = [
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13,14, 15, 0
];
// Store tile meshes by their number
const tiles = new Map();
// Create tile geometry and materials
const tileGeometry = new THREE.BoxGeometry(tileSize, 1, tileSize);
// Create canvas textures for numbers
function createTileTexture(number) {
const size = 128;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
// Background
ctx.fillStyle = '#1565c0';
ctx.fillRect(0, 0, size, size);
// Border
ctx.strokeStyle = '#0d47a1';
ctx.lineWidth = 8;
ctx.strokeRect(0, 0, size, size);
// Number
ctx.fillStyle = 'white';
ctx.font = 'bold 80px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(number, size/2, size/2);
const texture = new THREE.CanvasTexture(canvas);
texture.minFilter = THREE.LinearFilter;
return texture;
}
// Create tile mesh for a given number
function createTile(number) {
const material = new THREE.MeshPhongMaterial({
map: createTileTexture(number),
shininess: 50,
});
const mesh = new THREE.Mesh(tileGeometry, material);
mesh.userData.number = number;
return mesh;
}
// Position tile mesh based on index in puzzle array
function positionTileMesh(mesh, index) {
const row = Math.floor(index / gridSize);
const col = index % gridSize;
// Center grid at origin
const x = (col - (gridSize - 1) / 2) * tileFullSize;
const z = (row - (gridSize - 1) / 2) * tileFullSize;
mesh.position.set(x, 0.5, z);
}
// Initialize tiles in scene
function initTiles() {
// Remove old tiles
tiles.forEach(tile => scene.remove(tile));
tiles.clear();
for (let i = 0; i < puzzle.length; i++) {
const num = puzzle[i];
if (num === 0) continue; // skip empty
const tileMesh = createTile(num);
positionTileMesh(tileMesh, i);
scene.add(tileMesh);
tiles.set(num, tileMesh);
}
}
initTiles();
// Raycaster for mouse interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Find index of empty space
function findEmptyIndex() {
return puzzle.indexOf(0);
}
// Check if two indices are adjacent in grid
function isAdjacent(i1, i2) {
const r1 = Math.floor(i1 / gridSize);
const c1 = i1 % gridSize;
const r2 = Math.floor(i2 / gridSize);
const c2 = i2 % gridSize;
return (r1 === r2 && Math.abs(c1 - c2) === 1) || (c1 === c2 && Math.abs(r1 - r2) === 1);
}
// Swap tiles in puzzle array
function swapTiles(i1, i2) {
const temp = puzzle[i1];
puzzle[i1] = puzzle[i2];
puzzle[i2] = temp;
}
// Animate tile movement
let animating = false;
function animateTileMove(tileMesh, fromPos, toPos, onComplete) {
animating = true;
const duration = 200; // ms
const startTime = performance.now();
function animate() {
const now = performance.now();
const elapsed = now - startTime;
const t = Math.min(elapsed / duration, 1);
tileMesh.position.lerpVectors(fromPos, toPos, t);
if (t < 1) {
requestAnimationFrame(animate);
} else {
animating = false;
if (onComplete) onComplete();
}
}
animate();
}
// Handle click event
function onClick(event) {
if (animating) return; // ignore clicks during animation
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
// Intersect tiles
const intersects = raycaster.intersectObjects(Array.from(tiles.values()));
if (intersects.length === 0) return;
const clickedTile = intersects[0].object;
const clickedNumber = clickedTile.userData.number;
// Find clicked tile index and empty index
const clickedIndex = puzzle.indexOf(clickedNumber);
const emptyIndex = findEmptyIndex();
if (isAdjacent(clickedIndex, emptyIndex)) {
// Animate tile to empty position
const fromPos = clickedTile.position.clone();
const row = Math.floor(emptyIndex / gridSize);
const col = emptyIndex % gridSize;
const toX = (col - (gridSize - 1) / 2) * tileFullSize;
const toZ = (row - (gridSize - 1) / 2) * tileFullSize;
const toPos = new THREE.Vector3(toX, 0.5, toZ);
animateTileMove(clickedTile, fromPos, toPos, () => {
// Update puzzle state
swapTiles(clickedIndex, emptyIndex);
// Update tile map keys
tiles.set(clickedNumber, clickedTile);
});
}
}
window.addEventListener('click', onClick);
// Shuffle function (simple random moves)
function shufflePuzzle(moves = 100) {
let emptyIndex = findEmptyIndex();
for (let i = 0; i < moves; i++) {
// Find neighbors of empty space
const neighbors = [];
const r = Math.floor(emptyIndex / gridSize);
const c = emptyIndex % gridSize;
if (r > 0) neighbors.push(emptyIndex - gridSize);
if (r < gridSize - 1) neighbors.push(emptyIndex + gridSize);
if (c > 0) neighbors.push(emptyIndex - 1);
if (c < gridSize - 1) neighbors.push(emptyIndex + 1);
// Pick random neighbor to swap with empty
const swapIndex = neighbors[Math.floor(Math.random() * neighbors.length)];
swapTiles(emptyIndex, swapIndex);
emptyIndex = swapIndex;
}
initTiles();
}
document.getElementById('shuffleBtn').addEventListener('click', () => {
if (animating) return;
shufflePuzzle(200);
});
// Render loop
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();
// Handle resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
How to use:
- Open the above HTML file in a modern browser.
- You will see a 3D 15 puzzle.
- Click on tiles adjacent to the empty space to slide them.
- Use the Shuffle button to randomize the puzzle.
- You can orbit the camera around the puzzle with mouse drag (left-click + drag).
If you want me to add features like checking for solved state, animations for shuffle, or keyboard controls, just ask!