- 积分
- 12
- 注册时间
- 2008-7-11
- 仿真币
-
- 最后登录
- 1970-1-1
|
虽然在Demonstration Project上面已经有Roman Maeder老师写的魔方演示,我还是用Dynamic写了一个naive的版本,因为这样有利于和以后的魔方求解器接驳- Matrix = Map[
- Function[x,
- Map[x + # &, {{-1.5, -1.5}, {-0.5, -1.5}, {-0.5, -0.5}, {-1.5, \
- -0.5}}]], {{{0, 0}, {0, 1}, {0, 2}}, {{1, 0}, {1, 1}, {1, 2}}, {{2,
- 0}, {2, 1}, {2, 2}}}, {-2}];
- (*这是一个面9个小方格的坐标,由16个不同的顶点组成。这16个顶点的坐标是由-1.5,-0.5,0.5以及1.5四个数字Outer出来的*)
- FinalMatrix =
- Flatten[Table[
- Map[Insert[#, i, j] &,
- Matrix, {-2}], {i, {-1.5, 1.5}}, {j, {1, 2, 3}}], 1];
- (*将其变换为六个三维的面*)
- FinalGraphics =
- Flatten@Riffle[{Yellow, Green, Orange, White, Blue, Red},
- Map[Polygon, FinalMatrix, {-3}]];
- (*插入图形Primitive以及颜色*)
- Twist[a_, b_] :=
- Do[FinalGraphics[[Flatten[
- Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a], b], ___}]]]]] =
- Map[#.RotationMatrix[Pi/90, Insert[{0, 0}, a, b]] &,
- FinalGraphics[[Flatten[
- Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a],
- b], ___}]]]]], {-2}], {i, 45}]
- (*旋转应用了模式匹配。一次旋转需要改变21个小方块的坐标,这21个小方块的特点是它们一定会有至少两个在相同的平面上。用Position找到\
- 它们在FinalGraphics中的原始位置,然后乘以用RotationMatrix生成的旋转矩阵*)
- QuickTwist[a_, b_] :=
- Do[FinalGraphics[[Flatten[
- Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a], b], ___}]]]]] =
- Map[#.RotationMatrix[Pi/2, Insert[{0, 0}, a, b]] &,
- FinalGraphics[[Flatten[
- Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a],
- b], ___}]]]]], {-2}], {1}]
- (*考虑魔方由原始位置打乱顺序不需要详细显示旋转过程,所以在此采取\[OpenCurlyDoubleQuote]一步到位\
- \[CloseCurlyDoubleQuote]的旋转*)
- Scramble[n_] :=
- Do[QuickTwist[RandomChoice[{-1, 1}], RandomChoice[{1, 2, 3}]], {n}]
- (*随机地旋转,制定打乱顺序的操作次数*)
- Dynamic[Graphics3D[FinalGraphics, PlotRange -> 2.1]]
复制代码 使用方法:运行之后输入Twist[a,b],其中a可为1和-1两个值,b为1,2,3三个值。b代表xyz三个方向,而a代表三个方向上的正负,加起来刚好6个,神奇吧。
不过由于它需要不断进行模式匹配,所以不可避免地会在计算下一个转动位置时浪费大量时间,这样导致转动很不流畅。
我正在寻求解决方案,如果大家有意见请千万不要犹豫。
Danke!
--补充了Scramble,打乱顺序。使用方法为Scramble[n],其中n为打乱顺序操作的步数。
--------------------------------------------
如果将RotationMatrix换成RotationTransform速度会大大提高。我想是因为RotationTransform生成的是编译过的TransformFunction,而这要比对两个向量求内积要快很多。改进后的Twist为
- Twist2[a_, b_] :=(*RotateTransform version (much faster) *)
- Do[FinalGraphics[[
- Flatten[Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a], b], ___}]]]]] =
- Map[RotationTransform[Pi/270, Insert[{0, 0}, a, b]],
- FinalGraphics[[
- Flatten[Position[FinalGraphics,
- Polygon[{___,
- Insert[{_, _}, x_ /; If[a > 0, x > a, x < a],
- b], ___}]]]]], {-3}], {i, 135}]
复制代码
[ 本帖最后由 marveloustau 于 2009-1-18 13:42 编辑 ] |
评分
-
2
查看全部评分
-
|