创建一个魔方项目可以有不同的实现方式,取决于你的目标平台(Web、桌面应用、3D可视化等)。以下我将为你展示一个使用 Python 和 `matplotlib` 实现的 **3D 魔方模拟器**。这个项目将展示一个可旋转的 3x3 魔方。
---
### 🧩 项目目标:
- 创建一个 3D 魔方模拟器
- 支持基本的旋转操作(如 U, D, L, R, F, B)
- 使用 `matplotlib` 进行可视化
---
### ✅ 所需库:
```bash
pip install matplotlib numpy
```
---
### 🧱 魔方结构:
我们将使用一个 3D 数组来表示魔方,其中每个面是一个 3x3 的二维数组,总共 6 个面。
---
### 🧠 代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
# 魔方颜色定义
colors = {
'W': '#FFFFFF', # 白色
'Y': '#FFFF00', # 黄色
'G': '#00FF00', # 绿色
'B': '#0000FF', # 蓝色
'R': '#FF0000', # 红色
'O': '#FFA500' # 橙色
}
class RubiksCube:
def __init__(self):
# 初始化魔方,每个面为 3x3 的颜色矩阵
self.cube = np.array([
np.full((3, 3), color) for color in ['W', 'Y', 'G', 'B', 'R', 'O']
])
def draw(self):
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)
ax.set_zlim(-3, 3)
ax.set_box_aspect([1, 1, 1])
ax.axis('off')
# 定义每个面的中心位置
centers = [
(0, 3, 0), (0, -3, 0), (3, 0, 0),
(-3, 0, 0), (0, 0, 3), (0, 0, -3)
]
face_axes = [
(1, 2), (1, 2), (0, 2),
(0, 2), (0, 1), (0, 1)
]
for i, center in enumerate(centers):
face = self.cube[i]
x, y, z = center
a, b = face_axes[i]
for r in range(3):
for c in range(3):
color = colors[face[r, c]]
x0 = x + (c - 1) * 0.5
y0 = y + (r - 1) * 0.5
z0 = z
if a == 0 and b == 1:
rect = Rectangle((x0, z0), 0.5, 0.5, color=color)
elif a == 0 and b == 2:
rect = Rectangle((y0, z0), 0.5, 0.5, color=color)
else:
rect = Rectangle((x0, y0), 0.5, 0.5, color=color)
ax.add_patch(rect)
art3d.pathpatch_2d_to_3d(rect, z=0 if a == 0 and b == 1 else y0 if b == 0 else x0, zdir='y' if b == 1 else 'z' if a == 0 else 'x')
plt.show()
def rotate_face_clockwise(self, face_index):
"""旋转某个面顺时针"""
self.cube[face_index] = np.rot90(self.cube[face_index], k=3)
def rotate_face_counter_clockwise(self, face_index):
"""旋转某个面逆时针"""
self.cube[face_index] = np.rot90(self.cube[face_index], k=1)
# 测试:创建并绘制魔方
cube = RubiksCube()
cube.draw()
```
---
### 🔍 代码解释:
- **RubiksCube 类**:表示魔方,包含一个 6×3×3 的数组表示 6 个面。
- **draw() 方法**:使用 `matplotlib` 绘制 3D 魔方,每个小方块用 `Rectangle` 表示。
- **rotate_face_clockwise()**:对指定面进行顺时针旋转(通过 `np.rot90(k=3)` 实现)。
- **颜色映射**:使用字典将字母映射到颜色代码。
---
### 📌 当前限制:
- 目前只能绘制魔方,不能进行交互式旋转(如按键触发)
- 没有实现相邻面的联动旋转(例如转动 U 面时,上面的边缘也需要联动)
---
###