Okay, Google Colab 환경에서 인터랙티브하게 작동하는 3D 루빅스 큐브 학습 프로그램을 만들어 보겠습니다. Colab은 기본적으로 Python 환경이지만, %%html 매직 명령어를 사용하면 HTML, CSS, JavaScript 코드를 포함하여 웹 기반 콘텐츠를 렌더링할 수 있습니다. 이를 활용하여 Three.js 라이브러리로 3D 루빅스 큐브를 만들고, 사용자가 버튼 클릭이나 키보드로 조작할 수 있도록 구현하겠습니다.
주의: Colab의 출력 셀에서 실행되는 JavaScript는 Colab 환경의 제약 사항(예: 파일 시스템 접근 제한)을 따릅니다. 이 코드는 순수하게 브라우저 렌더링을 통해 작동합니다.
# -*- coding: utf-8 -*-
# Colab에서 3D 루빅스 큐브를 실행하기 위한 코드
# %%html 매직 명령어를 사용하여 HTML, CSS, JavaScript를 통합합니다.
%%html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D 루빅스 큐브 (Colab)</title>
<!-- Three.js 라이브러리 로드 -->
<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.min.js"></script>
<style>
body { margin: 0; overflow: hidden; font-family: Arial, sans-serif; }
#rubiks-container {
width: 100%;
height: 600px; /* Colab 셀 크기에 맞게 조절 */
position: relative;
border: 1px solid #444;
background-color: #111; /* 배경색 */
}
#rubiks-ui {
position: absolute;
top: 10px;
left: 10px;
background: rgba(0,0,0,0.8);
color: white;
padding: 15px;
border-radius: 8px;
z-index: 100;
max-width: 350px;
font-size: 14px;
box-shadow: 0 4px 8px rgba(0,0,0,0.5);
}
#rubiks-ui h3 {
margin-top: 0;
color: #4CAF50;
border-bottom: 1px solid #4CAF50;
padding-bottom: 5px;
}
#rubiks-ui button {
background-color: #4CAF50;
color: white;
border: none;
padding: 8px 12px;
margin: 4px 2px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
font-size: 13px;
}
#rubiks-ui button:hover {
background-color: #45a049;
}
#rubiks-ui button:active {
background-color: #3e8e41;
}
.controls-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 10px;
margin-bottom: 10px;
}
.key-hint {
font-size: 12px;
margin-top: 10px;
background: #333;
padding: 8px;
border-radius: 4px;
}
.key {
background: #555;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
font-weight: bold;
}
/* 반응형 조절 */
@media (max-width: 768px) {
#rubiks-ui {
width: calc(100% - 20px);
left: 10px;
top: 10px;
max-width: none;
}
#rubiks-container {
height: 400px; /* 모바일 환경에서는 높이 줄임 */
}
}
</style>
</head>
<body>
<div id="rubiks-container">
<div id="rubiks-ui">
<h3>3D 루빅스 큐브 학습</h3>
<div>
<button onclick="shuffleCube(25)">섞기 (25회)</button>
<button onclick="resetCube()">초기화</button>
</div>
<p>회전 조작:</p>
<div class="controls-grid">
<button onclick="requestRotation('U')">U (윗면)</button>
<button onclick="requestRotation('D')">D (아랫면)</button>
<button onclick="requestRotation('L')">L (왼쪽)</button>
<button onclick="requestRotation('R')">R (오른쪽)</button>
<button onclick="requestRotation('F')">F (앞면)</button>
<button onclick="requestRotation('B')">B (뒷면)</button>
<button onclick="requestRotation('U\'')">U' (반시계)</button>
<button onclick="requestRotation('D\'')">D' (반시계)</button>
<button onclick="requestRotation('L\'')">L' (반시계)</button>
<button onclick="requestRotation('R\'')">R' (반시계)</button>
<button onclick="requestRotation('F\'')">F' (반시계)</button>
<button onclick="requestRotation('B\'')">B' (반시계)</button>
</div>
<div class="key-hint">
<strong>단축키:</strong> <span class="key">U</span>, <span class="key">D</span>, <span class="key">L</span>, <span class="key">R</span>, <span class="key">F</span>, <span class="key">B</span> (시계방향)<br>
+ <span class="key">Shift</span> (반시계방향). 마우스 드래그: 시점 변경, 휠: 확대/축소.
</div>
</div>
</div>
<script>
// --- Three.js 기본 설정 ---
const container = document.getElementById('rubiks-container');
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
const controls = new THREE.OrbitControls(camera, renderer.domElement);
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio); // 고해상도 디스플레이 지원
container.appendChild(renderer.domElement);
// 조명
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 5, 5).normalize();
scene.add(directionalLight);
const directionalLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
directionalLight2.position.set(-5, -5, -5).normalize();
scene.add(directionalLight2);
// 카메라 초기 위치
camera.position.set(5, 5, 5);
controls.update();
// --- 큐브 로직 ---
const CUBE_SIZE = 3; // 전체 큐브 크기
const cubieSize = 0.9; // 개별 큐비 크기 (틈새 고려)
const gap = (CUBE_SIZE - cubieSize) / 2; // 큐비 간 간격
const CUBE_HALF_SIZE = CUBE_SIZE / 2;
const cubeGroup = new THREE.Group(); // 모든 큐비를 담을 그룹
scene.add(cubeGroup);
// 큐비(작은 정육면체) 생성 함수
function createCubie(x, y, z, colors) {
const cubie = new THREE.Group();
cubie.position.set(x, y, z);
// 중앙 부분 (보이지 않음)
const centerGeometry = new THREE.BoxGeometry(cubieSize, cubieSize, cubieSize);
const centerMaterial = new THREE.MeshPhongMaterial({ color: 0x222222 }); // 검정색
const centerMesh = new THREE.Mesh(centerGeometry, centerMaterial);
cubie.add(centerMesh);
// 면 추가 (각 면의 위치에 따라 색상 지정)
const faceGeometry = new THREE.PlaneGeometry(cubieSize, cubieSize);
// Top (White)
if (y === CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.white }));
face.rotation.x = -Math.PI / 2;
face.position.y = cubieSize / 2;
cubie.add(face);
}
// Bottom (Yellow)
if (y === -CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.yellow }));
face.rotation.x = Math.PI / 2;
face.position.y = -cubieSize / 2;
cubie.add(face);
}
// Left (Orange)
if (x === -CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.orange }));
face.rotation.y = Math.PI / 2;
face.position.x = -cubieSize / 2;
cubie.add(face);
}
// Right (Red)
if (x === CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.red }));
face.rotation.y = -Math.PI / 2;
face.position.x = cubieSize / 2;
cubie.add(face);
}
// Front (Blue)
if (z === CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.blue }));
face.position.z = cubieSize / 2;
cubie.add(face);
}
// Back (Green)
if (z === -CUBE_HALF_SIZE) {
const face = new THREE.Mesh(faceGeometry, new THREE.MeshPhongMaterial({ color: colors.green }));
face.rotation.y = Math.PI;
face.position.z = -cubieSize / 2;
cubie.add(face);
}
// 큐비의 원래 위치와 방향을 저장 (애니메이션 후 재정렬에 사용)
cubie.userData = {
originalPosition: { x: x, y: y, z: z },
originalRotation: cubie.rotation.clone()
};
return cubie;
}
// 큐브 초기화 함수
const rubiksColors = {
white: 0xffffff, red: 0xff0000, blue: 0x0000ff,
orange: 0xff8800, green: 0x00ff00, yellow: 0xffff00
};
let cubies = []; // 큐비 객체 배열
function initializeCube() {
// 기존 큐비 제거
while(cubeGroup.children.length > 0) {
cubeGroup.remove(cubeGroup.children[0]);
}
cubies = [];
// 3x3x3 큐브 생성
for (let x = -1; x <= 1; x++) {
for (let y = -1; y <= 1; y++) {
for (let z = -1; z <= 1; z++) {
// 중앙 큐비 제외 (내부)
if (Math.abs(x) + Math.abs(y) + Math.abs(z) < 3) {
const position = { x: x * (cubieSize + gap), y: y * (cubieSize + gap), z: z * (cubieSize + gap) };
const cubie = createCubie(position.x, position.y, position.z, rubiksColors);
cubeGroup.add(cubie);
cubies.push(cubie);
}
}
}
}
// 초기 카메라 위치 설정
camera.position.set(5, 5, 5);
controls.target.set(0, 0, 0);
controls.update();
}
// --- 회전 애니메이션 ---
let isAnimating = false;
let animationQueue = [];
function animate() {
requestAnimationFrame(animate);
controls.update(); // OrbitControls 업데이트
renderer.render(scene, camera);
}
function applyRotation(cubie, axis, angle, duration = 300) {
return new Promise(resolve => {
const startRotation = cubie.rotation.clone();
const endTime = Date.now() + duration;
const initialLocalRotation = cubie.userData.originalRotation.clone(); // 큐비의 초기 로컬 회전
const update = () => {
const now = Date.now();
let t = (now >= endTime) ? 1 : (now - (Date.now() - duration)) / duration; // 시간 비율 (0 ~ 1)
t = Math.max(0, Math.min(1, t)); // Clamp t between 0 and 1
// 회전 축 설정
let quaternion = new THREE.Quaternion();
if (axis === 'x') quaternion.setFromAxisAngle(new THREE.Vector3(1, 0, 0), initialLocalRotation.x + angle * t);
else if (axis === 'y') quaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), initialLocalRotation.y + angle * t);
else if (axis === 'z') quaternion.setFromAxisAngle(new THREE.Vector3(0, 0, 1), initialLocalRotation.z + angle * t);
cubie.quaternion.copy(quaternion); // 쿼터니언을 직접 적용
if (now < endTime) {
requestAnimationFrame(update);
} else {
// 애니메이션 완료 후 최종 상태 업데이트
cubie.rotation.setFromQuaternion(cubie.quaternion); // 실제 rotation 업데이트
cubie.userData.originalRotation.copy(cubie.rotation); // 로컬 회전 정보 업데이트
resolve();
}
};
update();
});
}
async function executeRotation(move) {
if (isAnimating) {
animationQueue.push(move);
return;
}
isAnimating = true;
const angle = move.endsWith("'") ? -Math.PI / 2 : Math.PI / 2;
const axis =
(move === 'U' || move === "U'") ? 'y' :
(move === 'D' || move === "D'") ? 'y' :
(move === 'L' || move === "L'") ? 'x' :
(move === 'R' || move === "R'") ? 'x' :
(move === 'F' || move === "F'") ? 'z' :
(move === 'B' || move === "B'") ? 'z' : null;
const layerValue =
(move === 'U' || move === "U'") ? CUBE_HALF_SIZE :
(move === 'D' || move === "D'") ? -CUBE_HALF_SIZE :
(move === 'L' || move === "L'") ? -CUBE_HALF_SIZE :
(move === 'R' || move === "R'") ? CUBE_HALF_SIZE :
(move === 'F' || move === "F'") ? CUBE_HALF_SIZE :
(move === 'B' || move === "B'") ? -CUBE_HALF_SIZE : null;
const rotationPromises = [];
cubies.forEach(cubie => {
let relevant = false;
if (axis === 'y' && Math.abs(cubie.position.y - layerValue) < 0.1) relevant = true;
if (axis === 'x' && Math.abs(cubie.position.x - layerValue) < 0.1) relevant = true;
if (axis === 'z' && Math.abs(cubie.position.z - layerValue) < 0.1) relevant = true;
if (axis === 'y') { // U, D 회전
if (Math.abs(cubie.position.y - layerValue) < 0.1) {
rotationPromises.push(applyRotation(cubie, axis, angle));
}
} else if (axis === 'x') { // L, R 회전
if (Math.abs(cubie.position.x - layerValue) < 0.1) {
rotationPromises.push(applyRotation(cubie, axis, angle));
}
} else if (axis === 'z') { // F, B 회전
if (Math.abs(cubie.position.z - layerValue) < 0.1) {
rotationPromises.push(applyRotation(cubie, axis, angle));
}
}
});
await Promise.all(rotationPromises);
// 애니메이션 완료 후, 큐비들의 실제 위치/회전 업데이트 및 원위치
cubies.forEach(cubie => {
let relevant = false;
if (axis === 'y' && Math.abs(cubie.position.y - layerValue) < 0.1) relevant = true;
if (axis === 'x' && Math.abs(cubie.position.x - layerValue) < 0.1) relevant = true;
if (axis === 'z' && Math.abs(cubie.position.z - layerValue) < 0.1) relevant = true;
if (relevant) {
// 큐비의 최종 회전을 적용하고 userData 업데이트
cubie.rotation.setFromQuaternion(cubie.quaternion);
cubie.userData.originalRotation.copy(cubie.rotation);
}
});
isAnimating = false;
// 큐에 다음 동작이 있다면 실행
if (animationQueue.length > 0) {
const nextMove = animationQueue.shift();
executeRotation(nextMove);
}
}
// --- 이벤트 핸들러 ---
function requestRotation(move) {
executeRotation(move);
}
function shuffleCube(moves = 20) {
const possibleMoves = ['U', "U'", 'D', "D'", 'L', "L'", 'R', "R'", 'F', "F'", 'B', "B'"];
let lastMoveAxis = null; // 연속 동일 축 회전 방지 (선택 사항)
function getRandomMove() {
let move;
do {
move = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
} while (move[0] === lastMoveAxis); // 간단한 연속 축 회전 방지
return move;
}
let shuffleSequence = [];
for (let i = 0; i < moves; i++) {
shuffleSequence.push(getRandomMove());
}
// 큐에 순차적으로 추가하여 애니메이션
shuffleSequence.forEach(move => animationQueue.push(move));
if (!isAnimating) { // 현재 애니메이션 중이 아니면 첫 동작 실행
executeRotation(animationQueue.shift());
}
}
function resetCube() {
// 애니메이션 큐 비우기
animationQueue = [];
isAnimating = false;
initializeCube(); // 큐브를 초기 상태로 재설정
}
// 키보드 이벤트 리스너
window.addEventListener('keydown', (event) => {
let move = '';
const shiftPressed = event.shiftKey;
switch (event.key.toUpperCase()) {
case 'U': move = shiftPressed ? "U'" : 'U'; break;
case 'D': move = shiftPressed ? "D'" : 'D'; break;
case 'L': move = shiftPressed ? "L'" : 'L'; break;
case 'R': move = shiftPressed ? "R'" : 'R'; break;
case 'F': move = shiftPressed ? "F'" : 'F'; break;
case 'B': move = shiftPressed ? "B'" : 'B'; break;
}
if (move) {
requestRotation(move);
}
});
// 창 크기 변경 시 캔버스 크기 조절
function onWindowResize() {
const width = container.clientWidth;
const height = container.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
window.addEventListener('resize', onWindowResize);
// 초기 큐브 생성 및 애니메이션 시작
initializeCube();
animate();
</script>
</body>
</html>
사용 방법:
- Colab 노트북 열기: Google Colab에서 새 노트북을 엽니다.
- 코드 셀에 붙여넣기: 위 코드를 새 코드 셀에 복사하여 붙여넣습니다.
- 셀 실행: 셀의 왼쪽 재생 버튼(▶)을 클릭하거나
Shift + Enter를 눌러 셀을 실행합니다.
- 상호작용:
- 코드 셀 아래에 3D 루빅스 큐브가 나타납니다.
- 마우스: 드래그하여 큐브를 돌리고, 휠로 확대/축소할 수 있습니다.
- 버튼: UI에 있는 "섞기", "초기화", "U", "D" 등의 버튼을 클릭하여 큐브를 조작할 수 있습니다.
- 키보드: 큐브가 보이는 셀을 클릭하여 포커스를 맞춘 후, 키보드의
U, D, L, R, F, B 키를 눌러 시계 방향 회전을, Shift 키와 함께 누르면 반시계 방향 회전을 할 수 있습니다.
코드 설명:
%%html: Colab에서 HTML 콘텐츠를 렌더링하도록 지시합니다.
- HTML 구조:
#rubiks-container: 3D 캔버스가 그려질 영역입니다.
#rubiks-ui: 조작 버튼과 안내가 포함된 UI 영역입니다. position: absolute를 사용하여 3D 캔버스 위에 표시됩니다.
- CSS: UI 요소와 컨테이너의 스타일을 지정합니다. 반응형 디자인을 위해 간단한 미디어 쿼리도 포함되어 있습니다.
- JavaScript:
- Three.js 초기화: Scene, Camera, Renderer, OrbitControls를 설정하여 3D 렌더링 환경을 구축합니다.
- 큐브 생성 (
initializeCube, createCubie):
cubieSize와 gap을 정의하여 큐브의 크기와 큐비 사이의 간격을 설정합니다.
- -1, 0, 1 좌표를 사용하여 3x3x3 그리드를 만듭니다.
createCubie 함수는 각 작은 큐브(cubie)를 생성합니다. 각 큐비는 중앙 검정색 부분과 보이는 면(최대 3개)으로 구성됩니다. 면의 색상은 큐비의 위치에 따라 결정됩니다.
userData에 큐비의 원래 위치와 회전 값을 저장하여 애니메이션 후 상태를 정확히 복원합니다.
- 회전 로직 (
executeRotation, applyRotation):
executeRotation 함수는 사용자의 입력(버튼 클릭 또는 키보드)을 받아 어떤 면을 어떻게 회전시킬지 결정합니다.
- 회전할 면에 속하는 큐비들을 찾습니다.
applyRotation 함수는 각 큐비를 지정된 축(x, y, z)을 기준으로 부드럽게 회전시킵니다. Promise를 사용하여 애니메이션이 완료될 때까지 기다립니다.
- 애니메이션 완료 후, 큐비들의 실제 Three.js 객체 변환(위치, 회전)을 업데이트하여
OrbitControls가 올바르게 작동하도록 합니다.
- 애니메이션 관리:
isAnimating 플래그와 animationQueue를 사용하여 여러 회전 요청이 동시에 처리되지 않고 순서대로 실행되도록 합니다.
- 사용자 입력:
- 버튼 클릭(
onclick)과 키보드 입력(window.addEventListener('keydown'))을 처리합니다.
Shift 키를 사용하여 반시계 방향 회전을 지원합니다.
- 창 크기 조절:
window.addEventListener('resize')를 사용하여 브라우저 창 크기가 변경될 때 3D 뷰를 자동으로 조절합니다.
animate 함수: 렌더링 루프를 실행하여 화면을 계속 업데이트하고 OrbitControls를 적용합니다.
이 코드를 Colab 셀에 넣고 실행하면, 바로 인터랙티브한 3D 루빅스 큐브를 체험할 수 있습니다. 학습용으로 큐브를 섞고, 특정 회전을 연습하는 데 사용할 수 있습니다.