Okay, this is an exciting and challenging project! Building a 3D Rubik's Cube with step-by-step animations requires careful handling of 3D objects, state management, and animation.
We'll use three.js for 3D rendering and tween.js for smooth animations.
Core Concepts:
- 3D Representation: We'll model the Rubik's Cube as 27 individual "cubies" (small cubes), though the center cubie is invisible. Each visible cubie will have materials (colors) applied to its outer faces.
- Cube State: The "state" of the cube will be managed by the
position and rotation of the three.js mesh objects themselves. When a layer rotates, the cubies in that layer physically rotate and change their world positions.
- Moves: A move (e.g.,
R, U', F2) involves identifying the cubies in the affected layer, grouping them temporarily, rotating the group, and then "baking" that rotation into the individual cubies.
- Scrambling: Generate a random sequence of valid moves and apply them.
- Solving (Initial Simple Version): For this initial version, we'll implement a "reverse scramble" solver. This means we record the scramble moves, and to "solve" it, we simply apply the inverse of those moves in reverse order. This fulfills the animation requirement without needing a complex solving algorithm right away. This is the "easily extendable for later" part, as you can replace this with a real solver.
- Animation Queue: To ensure moves happen one after another, we'll use an animation queue.
Project Structure
rubiks-cube-solver/
├── index.html
├── style.css
└── script.js
1. index.html
This will set up the basic HTML structure, include the three.js and tween.js libraries, and link our CSS and JavaScript files.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Rubik's Cube Scrambler & Solver</title>
<link rel="stylesheet" href="style.css">
<!-- Three.js CDN -->
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.158.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.158.0/examples/jsm/"
}
}
</script>
<!-- Tween.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/21.0.0/tween.umd.min.js"></script>
</head>
<body>
<div id="info">
<h1>3D Rubik's Cube</h1>
<div class="controls">
<button id="scrambleBtn">Scramble</button>
<button id="solveBtn" disabled>Solve</button>
<button id="resetBtn" disabled>Reset</button>
</div>
<p id="status">Ready.</p>
<div class="speed-control">
<label for="speedSlider">Animation Speed:</label>
<input type="range" id="speedSlider" min="100" max="1000" value="500">
<span id="speedValue">500ms</span>
</div>
<p>Use your mouse to rotate the cube when idle.</p>
</div>
<div id="container"></div>
<script type="module" src="script.js"></script>
</body>
</html>
2. style.css
Basic styling for the page and buttons.
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
background-color: #282c34;
color: #e0e0e0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
#info {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
background-color: rgba(0, 0, 0, 0.7);
padding: 15px 25px;
border-radius: 8px;
text-align: center;
z-index: 100;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
h1 {
margin-top: 0;
color: #61dafb;
}
.controls button {
background-color: #61dafb;
color: #282c34;
border: none;
padding: 10px 20px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease, transform 0.1s ease;
}
.controls button:hover:not(:disabled) {
background-color: #21a1f1;
transform: translateY(-2px);
}
.controls button:active:not(:disabled) {
transform: translateY(0);
}
.controls button:disabled {
background-color: #555;
cursor: not-allowed;
opacity: 0.6;
}
#status {
font-style: italic;
margin-top: 10px;
}
.speed-control {
margin-top: 15px;
}
#speedSlider {
width: 200px;
margin-left: 10px;
}
#container {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
canvas {
display: block;
}
3. script.js
This is where the magic happens!
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// --- Global Variables ---
let scene, camera, renderer, controls;
let cubeGroup; // This group holds all 27 individual cubie meshes
let cubies = []; // Array to hold references to all 27 cubie meshes
const CUBIE_SIZE = 1;
const GAP_SIZE = 0.05; // Small gap between cubies for visual effect
const TOTAL_CUBIE_SIZE = CUBIE_SIZE + GAP_SIZE;
const COLORS = {
'U': '#FFFFFF', // White - Up
'D': '#FFFF00', // Yellow - Down
'F': '#00FF00', // Green - Front
'B': '#0000FF', // Blue - Back
'L': '#FFA500', // Orange - Left
'R': '#FF0000', // Red - Right
'X': '#222222' // Dark Grey - for inner faces
};
let animationQueue = [];
let isAnimating = false;
let scrambleMoves = []; // Stores the sequence of moves for scrambling
let animationSpeed = 500; // Default animation duration in ms
// --- DOM Elements ---
const scrambleBtn = document.getElementById('scrambleBtn');
const solveBtn = document.getElementById('solveBtn');
const resetBtn = document.getElementById('resetBtn');
const statusText = document.getElementById('status');
const speedSlider = document.getElementById('speedSlider');
const speedValueSpan = document.getElementById('speedValue');
// --- Initialization ---
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333);
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 0, 5);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('container').appendChild(renderer.domElement);
// Controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // For smooth camera movement
controls.dampingFactor = 0.05;
controls.minDistance = 3;
controls.maxDistance = 10;
controls.update();
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040, 2); // soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Create the Rubik's Cube
createRubiksCube();
// Event Listeners
window.addEventListener('resize', onWindowResize);
scrambleBtn.addEventListener('click', scrambleCube);
solveBtn.addEventListener('click', solveCube);
resetBtn.addEventListener('click', resetCube);
speedSlider.addEventListener('input', (event) => {
animationSpeed = parseInt(event.target.value);
speedValueSpan.textContent = `${animationSpeed}ms`;
});
// Start animation loop
animate();
}
// --- Cube Creation ---
function createRubiksCube() {
if (cubeGroup) {
scene.remove(cubeGroup);
cubies = [];
}
cubeGroup = new THREE.Group();
scene.add(cubeGroup);
// Create 27 cubies (3x3x3 grid)
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
// Skip the very center cubie, it's not visible
if (x === 0 && y === 0 && z === 0) continue;
const cubieMesh = createCubie(x, y, z);
cubies.push(cubieMesh);
cubeGroup.add(cubieMesh);
}
}
}
resetBtn.disabled = true; // Initially cube is solved
}
function createCubie(x, y, z) {
const geometry = new THREE.BoxGeometry(CUBIE_SIZE, CUBIE_SIZE, CUBIE_SIZE);
const materials = [];
// Order of faces: Right (+X), Left (-X), Top (+Y), Bottom (-Y), Front (+Z), Back (-Z)
// Apply colors based on the cubie's initial position
materials.push(new THREE.MeshStandardMaterial({ color: x === 1 ? COLORS.R : COLORS.X })); // Right (+X)
materials.push(new THREE.MeshStandardMaterial({ color: x === -1 ? COLORS.L : COLORS.X })); // Left (-X)
materials.push(new THREE.MeshStandardMaterial({ color: y === 1 ? COLORS.U : COLORS.X })); // Top (+Y)
materials.push(new THREE.MeshStandardMaterial({ color: y === -1 ? COLORS.D : COLORS.X })); // Bottom (-Y)
materials.push(new THREE.MeshStandardMaterial({ color: z === 1 ? COLORS.F : COLORS.X })); // Front (+Z)
materials.push(new THREE.MeshStandardMaterial({ color: z === -1 ? COLORS.B : COLORS.X })); // Back (-Z)
const cubie = new THREE.Mesh(geometry, materials);
cubie.position.set(x * TOTAL_CUBIE_SIZE, y * TOTAL_CUBIE_SIZE, z * TOTAL_CUBIE_SIZE);
// Store initial position for resetting
cubie.userData.initialPosition = cubie.position.clone();
cubie.userData.initialQuaternion = cubie.quaternion.clone();
return cubie;
}
// --- Cube Logic (Moves) ---
const MOVES = {
'R': { axis: 'x', layer: 1, angle: Math.PI / 2 },
'L': { axis: 'x', layer: -1, angle: -Math.PI / 2 },
'U': { axis: 'y', layer: 1, angle: Math.PI / 2 },
'D': { axis: 'y', layer: -1, angle: -Math.PI / 2 },
'F': { axis: 'z', layer: 1, angle: Math.PI / 2 },
'B': { axis: 'z', layer: -1, angle: -Math.PI / 2 },
// Wide moves (can be implemented later if desired, or as double layer moves)
// 'r': { axis: 'x', layer: 0, angle: Math.PI / 2 }, // Slice M
// 'M': { axis: 'x', layer: 0, angle: -Math.PI / 2 }, // Slice M (often denoted M')
// 'E': { axis: 'y', layer: 0, angle: -Math.PI / 2 }, // Slice E
// 'S': { axis: 'z', layer: 0, angle: Math.PI / 2 }, // Slice S
};
// Function to get cubies in a specific layer
function getCubiesInLayer(axis, layer) {
return cubies.filter(cubie => {
const worldPosition = new THREE.Vector3();
cubie.getWorldPosition(worldPosition); // Get current world position
// Check if the cubie is in the specified layer with a small tolerance
const tolerance = TOTAL_CUBIE_SIZE / 2; // Half the cubie size
if (axis === 'x') return Math.abs(worldPosition.x - (layer * TOTAL_CUBIE_SIZE)) < tolerance;
if (axis === 'y') return Math.abs(worldPosition.y - (layer * TOTAL_CUBIE_SIZE)) < tolerance;
if (axis === 'z') return Math.abs(worldPosition.z - (layer * TOTAL_CUBIE_SIZE)) < tolerance;
return false;
});
}
function applyMove(moveString, animationDuration = animationSpeed) {
// Add to queue if animation is in progress
if (isAnimating) {
animationQueue.push({ move: moveString, duration: animationDuration });
return;
}
// Parse move string (e.g., 'R', 'U'', 'F2')
const baseMove = moveString[0];
const modifier = moveString.slice(1);
const moveInfo = MOVES[baseMove];
if (!moveInfo) {
console.warn(`Unknown move: ${moveString}`);
processNextAnimation(); // Continue with next if invalid move
return;
}
let { axis, layer, angle } = moveInfo;
// Adjust angle for modifiers
if (modifier === "'") {
angle *= -1;
} else if (modifier === "2") {
angle *= 2;
}
const affectedCubies = getCubiesInLayer(axis, layer);
if (affectedCubies.length === 0) {
console.warn(`No cubies found for move: ${moveString}. Cube might be in an unexpected state.`);
processNextAnimation();
return;
}
const tempGroup = new THREE.Group();
scene.add(tempGroup); // Add to scene so world positions are correctly maintained during attachment
affectedCubies.forEach(cubie => {
tempGroup.attach(cubie); // This changes cubie's parent from cubeGroup to tempGroup
});
isAnimating = true;
controls.enabled = false; // Disable orbit controls during animation
new TWEEN.Tween(tempGroup.rotation)
.to({
[axis]: tempGroup.rotation[axis] + angle
}, animationDuration)
.easing(TWEEN.Easing.Quadratic.Out)
.onComplete(() => {
// Bake the rotation into the cubies' own transforms
affectedCubies.forEach(cubie => {
cubeGroup.attach(cubie); // This moves cubie back to cubeGroup, baking the transformation
});
scene.remove(tempGroup); // Remove temporary group from scene
isAnimating = false;
controls.enabled = true; // Re-enable orbit controls
processNextAnimation(); // Process the next move in the queue
})
.start();
}
// Handles the animation queue
function processNextAnimation() {
if (animationQueue.length > 0) {
const next = animationQueue.shift();
applyMove(next.move, next.duration);
} else {
// All animations complete
updateButtonStates();
}
}
// --- Scramble & Solve Logic ---
function scrambleCube() {
if (isAnimating) return;
resetCube(); // Ensure cube is in a solved state before scrambling
statusText.textContent = 'Scrambling...';
disableButtons();
scrambleMoves = [];
const possibleMoves = Object.keys(MOVES);
const numMoves = 20; // Standard number of scramble moves
for (let i = 0; i < numMoves; i++) {
let randomMove = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
const modifier = Math.random() < 0.3 ? "'" : (Math.random() < 0.3 ? "2" : ""); // Add ' or 2
randomMove += modifier;
scrambleMoves.push(randomMove);
animationQueue.push({ move: randomMove, duration: animationSpeed / 2 }); // Faster scramble animation
}
processNextAnimation();
solveBtn.disabled = false;
}
function getInverseMove(move) {
const baseMove = move[0];
const modifier = move.slice(1);
if (modifier === "'") {
return baseMove; // Inverse of U' is U
} else if (modifier === "2") {
return baseMove + "2"; // Inverse of U2 is U2
} else {
return baseMove + "'"; // Inverse of U is U'
}
}
function solveCube() {
if (isAnimating || scrambleMoves.length === 0) return;
statusText.textContent = 'Solving...';
disableButtons();
// Reverse the scramble moves and invert them
const solveSequence = scrambleMoves.reverse().map(getInverseMove);
scrambleMoves = []; // Clear scramble moves after creating solve sequence
solveSequence.forEach(move => {
animationQueue.push({ move: move, duration: animationSpeed });
});
processNextAnimation();
solveBtn.disabled = true; // Disable solve button until next scramble
}
function resetCube() {
if (isAnimating) return; // Prevent reset during animation
statusText.textContent = 'Resetting...';
disableButtons();
// Restore cubies to initial positions and rotations
cubies.forEach(cubie => {
cubeGroup.remove(cubie); // Temporarily remove from group
cubie.position.copy(cubie.userData.initialPosition);
cubie.quaternion.copy(cubie.userData.initialQuaternion);
cubeGroup.add(cubie); // Add back to group
});
scrambleMoves = [];
animationQueue = []; // Clear any pending animations
statusText.textContent = 'Ready.';
updateButtonStates();
}
// --- UI Management ---
function disableButtons() {
scrambleBtn.disabled = true;
solveBtn.disabled = true;
resetBtn.disabled = true;
}
function updateButtonStates() {
scrambleBtn.disabled = isAnimating;
solveBtn.disabled = isAnimating || scrambleMoves.length === 0;
resetBtn.disabled = isAnimating; // You might want to allow reset even during solve for advanced cases
if (!isAnimating) {
statusText.textContent = 'Ready.';
}
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
controls.update(); // Only required if controls.enableDamping or controls.autoRotate are set to true
TWEEN.update(); // Update all active tweens
renderer.render(scene, camera);
}
// --- Handle Window Resizing ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Initialize the application
init();
How to Run:
- Save the files: Create the
rubiks-cube-solver folder. Inside it, save the index.html, style.css, and script.js files as shown above.
- Open
index.html: Simply open index.html in your web browser.
Key Features and Future Extensions:
- 3D Visualization: The cube is rendered in 3D using
three.js.
- Interactive Camera: You can drag your mouse to rotate the camera around the cube when it's idle.
- Scramble: Click "Scramble" to apply a random sequence of moves to the cube.
- Solve (Reverse Scramble): After scrambling, click "Solve" to reverse the scramble and bring the cube back to its solved state.
- Reset: The "Reset" button brings the cube back to its initial solved state immediately.
- Animation Queue: Ensures moves animate one after another without overlap.
- Animation Speed Slider: Adjust the speed of the rotations.
Extending for Custom Input Positions and Real Solving:
The current solveCube function is a placeholder. To allow custom input and a real solver:
-
Cube State Representation:
- Currently, the state is implicitly stored in the
position and quaternion of the THREE.Mesh objects.
- For a real solver, you'll need a logical representation of the cube's state (e.g., a 2D array of colors for each face, or a list of cubies with their current positions and orientations).
- Example:
const cubeState = new RubiksCubeState(); where RubiksCubeState is a class that stores colors/cubie positions internally, independent of the 3D rendering.
- You'd need methods to
getCubeState() from your three.js model and setCubeState(newState) to update the 3D model.
-
Inputting Custom Positions:
- You'd need a UI to allow users to input a state (e.g., a 2D representation of the faces, or a specific notation).
- Once inputted, you'd use
setCubeState to update the 3D model to that custom position.
-
Integrating a Solver Algorithm:
- This is the most complex part. Implementing a full Rubik's Cube solver (like Kociemba, Fridrich, etc.) is a massive undertaking.
- Recommendation: Look for existing JavaScript Rubik's Cube solver libraries. There are a few out there on npm (e.g.,
rubiks-cube-solver, cubejs).
- How it would work:
import { solve } from 'some-rubiks-solver-library'; // Example import
function solveCustomPosition() {
// 1. Get the current logical state of your 3D cube
const currentState = getLogicalCubeState(); // You'd need to implement this
// 2. Pass the state to the solver library
// The format required by the library will vary. It might be a string
// like "UFURDLDF..." or an array of face colors.
const solveSequence = solve(currentState); // This returns an array of moves ['R', 'U'', 'F2', ...]
// 3. Add the solver's sequence to your animation queue
solveSequence.forEach(move => {
animationQueue.push({ move: move, duration: animationSpeed });
});
processNextAnimation();
}
- You'll need to map your
three.js cubie orientations/colors to the solver library's required input format and vice-versa for the output moves.
This project provides a solid foundation for your interactive 3D Rubik's Cube. Good luck!