아래 코드를 그대로 Google Colab의 “코드 셀” 에 붙여 넣고 실행(Shift + Enter)하면,
셀 출력 영역 안에서 3D 루빅스 큐브를 직접 돌려 보며 학습할 수 있습니다.
(Three.js 100 % 클라이언트-사이드라 Colab 권한이나 런타임과 무관하게 동작!)
# Colab 용 3D 루빅스 큐브 ― 단일 HTML/JS 셀
%%html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>3D 루빅스 큐브 – Colab</title>
<!-- Three.js & OrbitControls -->
<script src="https://unpkg.com/three@0.154.0/build/three.min.js"></script>
<script src="https://unpkg.com/three@0.154.0/examples/js/controls/OrbitControls.js"></script>
<style>
html,body{margin:0;height:100%;overflow:hidden;font-family:sans-serif;background:#111}
#app{position:relative;width:100%;height:600px;}
#ui{
position:absolute;top:12px;left:12px;z-index:10;
background:rgba(0,0,0,.8);color:#fff;padding:14px 16px;border-radius:10px;
backdrop-filter:blur(6px);max-width:320px;font-size:14px
}
#ui h2{margin:0 0 8px;font-size:18px;color:#4caf50}
.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}
button{
cursor:pointer;border:none;border-radius:4px;padding:6px 4px;
color:#fff;font-weight:600;transition:.2s;background:#4caf50
}
button:hover{background:#66bb6a} button:active{transform:scale(.95)}
#shuffle{background:#ff9800} #reset{background:#f44336}
.hint{margin-top:10px;font-size:12px;color:#ccc;line-height:1.4}
.key{background:#333;padding:1px 5px;border-radius:3px;font-family:monospace}
</style>
</head>
<body>
<div id="app"></div>
<div id="ui">
<h2>3D 루빅스 큐브</h2>
<div class="grid">
<button data-m="U">U</button><button data-m="D">D</button><button data-m="F">F</button>
<button data-m="B">B</button><button data-m="L">L</button><button data-m="R">R</button>
<button data-m="U'">U'</button><button data-m="D'">D'</button><button data-m="F'">F'</button>
<button data-m="B'">B'</button><button data-m="L'">L'</button><button data-m="R'">R'</button>
</div>
<div style="display:flex;gap:6px;margin-top:10px">
<button id="shuffle">랜덤 섞기</button>
<button id="reset">초기화</button>
</div>
<div class="hint">
• 마우스 드래그: 시점 회전<br>
• 휠: 줌 인/아웃<br>
• 키보드 <span class="key">U D L R F B</span>
(+ <span class="key">Shift</span> = 반시계)
</div>
</div>
<script>
// ────────────────── Three.js 기본 셋업 ──────────────────
const { Scene, PerspectiveCamera, WebGLRenderer,
AmbientLight, DirectionalLight, Group,
BoxGeometry, PlaneGeometry, MeshPhongMaterial, Mesh,
Vector3, Quaternion } = THREE;
const app = document.getElementById('app');
const scene = new Scene();
const cam = new PerspectiveCamera(60, app.clientWidth/app.clientHeight, .1, 100);
cam.position.set(6,6,6);
const renderer = new WebGLRenderer({antialias:true});
renderer.setSize(app.clientWidth, app.clientHeight);
app.appendChild(renderer.domElement);
const ctl = new THREE.OrbitControls(cam, renderer.domElement);
ctl.enableDamping = true;
// 조명
scene.add(new AmbientLight(0xffffff, .6));
const dir = new DirectionalLight(0xffffff,.8); dir.position.set(3,5,4);
scene.add(dir);
// ────────────────── 큐브 생성 ──────────────────
const SIZE = 3; // 3x3x3
const GAP = .04;
const UNIT = 1 - GAP; // 큐비 한 변 길이
const HALF = (SIZE-1)/2; // 1
const COLORS = {
U:0xffffff, D:0xffd500, F:0x0051ba,
B:0x009e60, L:0xff5800, R:0xc41e3a, CORE:0x222222
};
const cube = new Group(); scene.add(cube);
let cubies=[]; // 모든 큐비 저장
createCube();
// ────────────────── 함수 정의 ──────────────────
function createCubie(i,j,k){
const g = new Group();
g.position.set(i, j, k);
// 중심 블록
const body = new Mesh(new BoxGeometry(UNIT,UNIT,UNIT),
new MeshPhongMaterial({color:COLORS.CORE}));
g.add(body);
const faceGeo = new PlaneGeometry(UNIT,UNIT);
function addFace(cond, color, rot, pos){
if(cond){
const m = new Mesh(faceGeo,new MeshPhongMaterial({color}));
m.rotation.set(...rot);
m.position.set(...pos);
g.add(m);
}
}
addFace(j=== HALF, COLORS.U,[ -Math.PI/2,0,0],[0, UNIT/2,0]);
addFace(j===-HALF, COLORS.D,[ Math.PI/2,0,0],[0,-UNIT/2,0]);
addFace(k=== HALF, COLORS.F,[0,0,0],[0,0, UNIT/2]);
addFace(k===-HALF, COLORS.B,[0, Math.PI,0],[0,0,-UNIT/2]);
addFace(i===-HALF, COLORS.L,[0, Math.PI/2,0],[-UNIT/2,0,0]);
addFace(i=== HALF, COLORS.R,[0,-Math.PI/2,0],[ UNIT/2,0,0]);
cube.add(g);
cubies.push(g);
}
function createCube(){
cubies=[]; cube.clear();
for(let i=-HALF;i<=HALF;i++)
for(let j=-HALF;j<=HALF;j++)
for(let k=-HALF;k<=HALF;k++)
if(Math.abs(i)+Math.abs(j)+Math.abs(k)>0) createCubie(i,j,k);
}
// ────────────────── 회전 로직 ──────────────────
let busy=false, queue=[];
function doMove(move){
if(busy){queue.push(move);return;}
busy=true;
const prime = move.endsWith("'"); // 반시계?
const layer = move[0];
const angle = (prime?-1:1)*Math.PI/2;
// 축/레이어 선택
let axis, sel; // sel(cubie) == true 인 큐비만 회전
switch(layer){
case 'U': axis='y'; sel=c=>Math.abs(c.position.y- HALF)<1e-3;break;
case 'D': axis='y'; sel=c=>Math.abs(c.position.y+HALF)<1e-3;break;
case 'L': axis='x'; sel=c=>Math.abs(c.position.x+HALF)<1e-3;break;
case 'R': axis='x'; sel=c=>Math.abs(c.position.x- HALF)<1e-3;break;
case 'F': axis='z'; sel=c=>Math.abs(c.position.z- HALF)<1e-3;break;
case 'B': axis='z'; sel=c=>Math.abs(c.position.z+HALF)<1e-3;break;
default: return;
}
// 회전 그룹에 해당 큐비만 담기
const rotGrp=new Group();
cube.add(rotGrp);
cubies.filter(sel).forEach(c=>{
rotGrp.attach(c); // parenting
});
// 애니메이션
const qStart = new Quaternion();
const qEnd = new Quaternion().setFromAxisAngle(
new Vector3(axis==='x',axis==='y',axis==='z'), angle);
const dur=250, t0=performance.now();
function anim(){
const t = (performance.now()-t0)/dur;
if(t<1){
rotGrp.quaternion.slerpQuaternions(qStart,qEnd,t);
requestAnimationFrame(anim);
}else{
rotGrp.quaternion.copy(qEnd); // 정확히 맞추기
// 회전 끝나면 큐비 다시 메인 그룹으로 돌려놓기
while(rotGrp.children.length){
cube.attach(rotGrp.children[0]);
}
cube.remove(rotGrp);
busy=false;
if(queue.length) doMove(queue.shift());
}
}
anim();
}
// ────────────────── 유틸 : 섞기/리셋 ──────────────────
function scramble(cnt=25){
const mv = ['U','D','L','R','F','B'];
for(let i=0;i<cnt;i++){
const m = mv[Math.floor(Math.random()*6)];
queue.push(Math.random()<.5?m:m+"'")
}
if(!busy) doMove(queue.shift());
}
function reset(){
queue=[];busy=false;
createCube();
}
// ────────────────── UI 이벤트 ──────────────────
document.querySelectorAll('button[data-m]').forEach(btn=>{
btn.onclick=()=>doMove(btn.dataset.m);
});
document.getElementById('shuffle').onclick=()=>scramble();
document.getElementById('reset').onclick =reset;
window.addEventListener('keydown',e=>{
const k=e.key.toUpperCase();
if('UDLRFB'.includes(k)) doMove(e.shiftKey?k+"'":k);
});
// ────────────────── 렌더 루프 ──────────────────
function loop(){
requestAnimationFrame(loop);
ctl.update();
renderer.render(scene,cam);
}
loop();
window.addEventListener('resize',()=>{
cam.aspect=app.clientWidth/app.clientHeight;
cam.updateProjectionMatrix();
renderer.setSize(app.clientWidth,app.clientHeight);
});
</script>
</body>
</html>
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
사용 TIP
- 셀 실행 후 출력 창 안에서 마우스를 드래그해 큐브를 돌려보세요.
- UI 버튼 또는 키보드(U, D, L, R, F, B + Shift)로 면을 회전할 수 있습니다.
- “랜덤 섞기”를 눌러 25 회 무작위로 섞고, 스스로 복원하며 연습하세요.
- 언제든 “초기화”로 완벽한 solved 상태로 돌아갑니다.
Three.js만 사용하므로 별도 파이썬 패키지 설치가 필요 없고,
Colab 노트북에서 바로 실행→학습까지 원-스톱으로 즐기실 수 있습니다. 즐거운 큐빙 🔥