免費論壇 繁體 | 簡體
Sclub交友聊天~加入聊天室當版主
分享
返回列表 发帖

用Mathematica玩《关灯游戏》

本帖最后由 青青子衿 于 2021-8-1 17:49 编辑

Lights Out(关灯游戏)是一款益智游戏,也算一种“康威生命游戏”。
https://mathworld.wolfram.com/LightsOutPuzzle.html
https://projecteuler.net/problem=707
Light_Out_Simplified_Editon.
  1. k = 5;
  2. Manipulate[
  3. Module[{},
  4.   EventHandler[Dynamic[ArrayPlot[matrix, Mesh -> True]],
  5.    "MouseDown" :> Module[{}, clickPoint = MousePosition["Graphics"];
  6.      currentPoint = {k + 1 - Ceiling[clickPoint][[2]],
  7.        Ceiling[clickPoint][[1]]}; changeMethod[currentPoint];
  8.      If[Count[Flatten[matrix], 1] == k^2,
  9.       MessageDialog["Well done!"]]]]],
  10. Button["New", matrix = Array[0 &, {k, k}]],
  11. Initialization -> {matrix = Array[0 &, {k, k}];
  12.    changeMethod[point_] :=
  13.     Module[{a, b}, a = point[[1]]; b = point[[2]];
  14.      jud[k_, a_, b_] := If[1 <= a <= k && 1 <= b <= k,
  15.        Select[{{a + 1, b}, {a - 1, b}, {a, b - 1}, {a, b + 1}, {a,
  16.           b}}, 0 < #[[1]] < k + 1 && 0 < #[[2]] < k + 1 &],
  17.        Null];
  18.      list =
  19.       jud[k, a,
  20.        b]; (matrix[[#[[1]], #[[2]]]] =
  21.          1 - matrix[[#[[1]], #[[2]]]]) & /@ list]}]
复制代码
http://hi.baidu.com/guishidan/item/fd04601ba978f8f365eabfb1
分享到: QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友

本帖最后由 青青子衿 于 2021-8-3 00:56 编辑


Light_Out_Express_Editon.
  1. k = 5;
  2. Manipulate[
  3. Module[{},
  4.   EventHandler[
  5.    Dynamic[ArrayPlot[matrix, Mesh -> True,
  6.      PlotRangePadding -> Scaled[0.05]]],
  7.    "MouseDown" :> Module[{}, clickPoint = MousePosition["Graphics"];
  8.      AppendTo[points,
  9.       If[1 <= #1 <= k && 1 <= #2 <= k & @@ #, steps = 0;
  10.          backup = {}; #, {}] &[{k + 1 - #2, #1} & @@
  11.         Ceiling@clickPoint]];
  12.      points = DeleteCases[points, {}];
  13.      changeMethod @@ points;
  14.      If[Count[Flatten[matrix], 1] == k^2, MessageDialog["Well done!"]]
  15.      ]
  16.    ]
  17.   ],
  18. Row@
  19.   {Button["New", matrix = Array[0 &, {k, k}]; points = {};
  20.     backup = {};],
  21.    Button["Undo",
  22.     If[points != {}, changeMethod@Last@points;
  23.      AppendTo[backup, Last@points]; points = Most@points;
  24.      steps += 1;]],
  25.    Button["Redo",
  26.     If[steps > 0, changeMethod@Last@backup;
  27.      AppendTo[points, Last@backup]; backup = Most@backup;
  28.      steps -= 1;]]},
  29. Initialization -> {
  30.    matrix = Array[0 &, {k, k}]; points = {}; backup = {}; steps = 0;
  31.    Clear[fun];
  32.    fun[k_, u_, v_] :=
  33.     fun[k, u, v] =
  34.      SparseArray[{i_, j_} /; Norm[{i, j} - {u, v}] <= 1 :> 1, {k, k}];
  35.    changeMethod[{u_, v_}] := (matrix = Abs[matrix - fun[k, u, v]]);
  36.    changeMethod[points___] := (matrix = Array[0 &, {k, k}];
  37.      Do[changeMethod[i], {i, {points}}]);
  38.    }]
复制代码

TOP

返回列表 回复 发帖