Here's a complete HTML file that implements an interactive Rubik's Cube with Three.js:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Rubik's Cube</title>
<style>
body {
margin: 0;
padding: 0;
background: #222;
font-family: Arial, sans-serif;
overflow: hidden;
}
#container {
position: relative;
width: 100vw;
height: 100vh;
}
#controls {
position: absolute;
top: 20px;
left: 20px;
z-index: 100;
background: rgba(0, 0, 0, 0.8);
padding: 20px;
border-radius: 10px;
color: white;
}
.button-group {
margin: 10px 0;
}
.button-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
button {
margin: 2px;
padding: 8px 12px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
button:hover {
background: #45a049;
}
button:disabled {
background: #666;
cursor: not-allowed;
}
.special-button {
background: #2196F3;
padding: 10px 15px;
font-size: 14px;
margin: 5px;
}
.special-button:hover {
background: #1976D2;
}
#status {
margin-top: 15px;
padding: 10px;
background: rgba(255, 255, 255, 0.1);
border-radius: 5px;
font-size: 14px;
}
</style>
</head>
<body>
<div id="container">
<div id="controls">
<h3>Rubik's Cube Controls</h3>
<div class="button-group">
<label>Face Rotations:</label>
<button onclick="performMove('U')">U</button>
<button onclick="performMove('U\'')">U'</button>
<button onclick="performMove('D')">D</button>
<button onclick="performMove('D\'')">D'</button>
<button onclick="performMove('L')">L</button>
<button onclick="performMove('L\'')">L'</button>
<button onclick="performMove('R')">R</button>
<button onclick="performMove('R\'')">R'</button>
<button onclick="performMove('F')">F</button>
<button onclick="performMove('F\'')">F'</button>
<button onclick="performMove('B')">B</button>
<button onclick="performMove('B\'')">B'</button>
</div>
<div class="button-group">
<button class="special-button" onclick="scrambleCube()">Scramble</button>
<button class="special-button" onclick="startUnscramble()">Auto Solve</button>
<button class="special-button" onclick="stopUnscramble()">Stop Solve</button>
<button class="special-button" onclick="resetCube()">Reset</button>
</div>
<div id="status">
<div>Status: <span id="cube-status">Solved</span></div>
<div>Moves: <span id="move-count">0</span></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script>
// Global variables
let scene, camera, renderer, controls;
let cubies = [];
let solvedStates = [];
let moveHistory = [];
let isAnimating = false;
let unscrambleInterval = null;
let moveCount = 0;
// Cube colors (standard Rubik's cube)
const colors = {
white: 0xffffff, // Top (U)
yellow: 0xffff00, // Bottom (D)
red: 0xff0000, // Right (R)
orange: 0xff8000, // Left (L)
blue: 0x0000ff, // Front (F)
green: 0x00ff00 // Back (B)
};
// Initialize the scene
function init() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333);
// Create camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(5, 5, 5);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('container').appendChild(renderer.domElement);
// Add controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Add lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(directionalLight);
// Create the cube
createCube();
// Start render loop
animate();
// Handle window resize
window.addEventListener('resize', onWindowResize);
}
function createCube() {
cubies = [];
solvedStates = [];
// Create 27 cubies (3x3x3)
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
const cubie = createCubie(x, y, z);
cubies.push(cubie);
scene.add(cubie);
// Store solved state
solvedStates.push({
position: cubie.position.clone(),
rotation: cubie.rotation.clone()
});
}
}
}
}
function createCubie(x, y, z) {
const geometry = new THREE.BoxGeometry(0.95, 0.95, 0.95);
// Create materials for each face
const materials = [];
// Right face (x = 1)
materials.push(new THREE.MeshLambertMaterial({
color: x === 1 ? colors.red : 0x000000
}));
// Left face (x = -1)
materials.push(new THREE.MeshLambertMaterial({
color: x === -1 ? colors.orange : 0x000000
}));
// Top face (y = 1)
materials.push(new THREE.MeshLambertMaterial({
color: y === 1 ? colors.white : 0x000000
}));
// Bottom face (y = -1)
materials.push(new THREE.MeshLambertMaterial({
color: y === -1 ? colors.yellow : 0x000000
}));
// Front face (z = 1)
materials.push(new THREE.MeshLambertMaterial({
color: z === 1 ? colors.blue : 0x000000
}));
// Back face (z = -1)
materials.push(new THREE.MeshLambertMaterial({
color: z === -1 ? colors.green : 0x000000
}));
const cubie = new THREE.Mesh(geometry, materials);
cubie.position.set(x, y, z);
cubie.castShadow = true;
cubie.receiveShadow = true;
return cubie;
}
function performMove(move) {
if (isAnimating) return;
moveHistory.push(move);
moveCount++;
updateStatus();
const axis = getMoveAxis(move);
const layer = getMoveLayer(move);
const clockwise = !move.includes('\'');
animateRotation(axis, layer, clockwise);
}
function getMoveAxis(move) {
const face = move.charAt(0);
switch (face) {
case 'U':
case 'D':
return 'y';
case 'L':
case 'R':
return 'x';
case 'F':
case 'B':
return 'z';
}
}
function getMoveLayer(move) {
const face = move.charAt(0);
switch (face) {
case 'U': return 1; // Top layer
case 'D': return -1; // Bottom layer
case 'R': return 1; // Right layer
case 'L': return -1; // Left layer
case 'F': return 1; // Front layer
case 'B': return -1; // Back layer
}
}
function animateRotation(axis, layer, clockwise) {
isAnimating = true;
// Find cubies in the layer
const layerCubies = cubies.filter(cubie => {
const pos = cubie.position;
switch (axis) {
case 'y': return Math.abs(pos.y - layer) < 0.1;
case 'x': return Math.abs(pos.x - layer) < 0.1;
case 'z': return Math.abs(pos.z - layer) < 0.1;
}
});
// Create rotation group
const rotationGroup = new THREE.Group();
scene.add(rotationGroup);
// Move cubies to rotation group
layerCubies.forEach(cubie => {
const worldPosition = new THREE.Vector3();
const worldQuaternion = new THREE.Quaternion();
const worldScale = new THREE.Vector3();
cubie.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
scene.remove(cubie);
cubie.position.copy(worldPosition);
cubie.quaternion.copy(worldQuaternion);
rotationGroup.add(cubie);
});
// Animate rotation
const startRotation = 0;
const endRotation = clockwise ? Math.PI / 2 : -Math.PI / 2;
const duration = 300; // milliseconds
const startTime = Date.now();
function animateStep() {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
// Easing function
const easeProgress = 1 - Math.pow(1 - progress, 3);
const currentRotation = startRotation + (endRotation - startRotation) * easeProgress;
rotationGroup.rotation[axis] = currentRotation;
if (progress < 1) {
requestAnimationFrame(animateStep);
} else {
// Animation complete - move cubies back to scene
layerCubies.forEach(cubie => {
const worldPosition = new THREE.Vector3();
const worldQuaternion = new THREE.Quaternion();
const worldScale = new THREE.Vector3();
cubie.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
rotationGroup.remove(cubie);
cubie.position.copy(worldPosition);
cubie.quaternion.copy(worldQuaternion);
scene.add(cubie);
});
scene.remove(rotationGroup);
isAnimating = false;
updateStatus();
}
}
animateStep();
}
function scrambleCube() {
if (isAnimating) return;
stopUnscramble();
moveHistory = [];
moveCount = 0;
const moves = ['U', 'U\'', 'D', 'D\'', 'L', 'L\'', 'R', 'R\'', 'F', 'F\'', 'B', 'B\''];
const scrambleLength = 20;
let moveIndex = 0;
function performNextMove() {
if (moveIndex < scrambleLength) {
const randomMove = moves[Math.floor(Math.random() * moves.length)];
performMove(randomMove);
moveIndex++;
setTimeout(performNextMove, 350);
}
}
performNextMove();
}
function startUnscramble() {
if (moveHistory.length === 0 || isAnimating) return;
stopUnscramble();
unscrambleInterval = setInterval(() => {
if (moveHistory.length > 0 && !isAnimating) {
const lastMove = moveHistory.pop();
const inverseMove = getInverseMove(lastMove);
// Don't add inverse moves to history
const originalHistory = [...moveHistory];
performMove(inverseMove);
moveHistory = originalHistory;
moveCount--;
if (moveHistory.length === 0) {
stopUnscramble();
}
} else if (moveHistory.length === 0) {
stopUnscramble();
}
}, 500);
}
function stopUnscramble() {
if (unscrambleInterval) {
clearInterval(unscrambleInterval);
unscrambleInterval = null;
}
}
function getInverseMove(move) {
if (move.includes('\'')) {
return move.charAt(0);
} else {
return move + '\'';
}
}
function resetCube() {
if (isAnimating) return;
stopUnscramble();
// Remove all cubies
cubies.forEach(cubie => scene.remove(cubie));
// Recreate cube
createCube();
// Reset state
moveHistory = [];