以下是编码,和大神编码一致,运行出来没有动图,只是一张静态的图,动图更新开启了,二楼再发运行结果,求大佬指点,万分感谢!
Clear["Global`*"]
width = 20;
goalNum = 25;
delay = 0.01;
AllPoint = Join @@ Table[{i, j}, {i, width}, {j, width}];
snake = {{1, 2}, {1, 1}};
goal = RandomSample[DeleteCases[AllPoint, Alternatives @@ snake],
goalNum];
newgoal :=
RandomChoice[
DeleteCases[AllPoint, Alternatives @@ Join[snake, goal]]];
direction := Switch[snake[[1]],
{x_, y_} /; x == width && y == 2, {0, -1},
{x_, y_} /; x == 1 && y == 1, {0, 1},
{x_, y_} /; (Mod[x - 1, 2] == 1) && 2 <= y <= width - 1, {0, 1},
{x_, y_} /; (Mod[x, 2] == 0) && 3 <= y <= width, {0, -1},
{x_, y_} /; y = width, {1, 0},
{x_, y_} /; y = 2, {1, 0},
{x_, y_} /; y = 1, {-1, 0}];
GoForward := Module[{d},
d = direction;
If[NemberQ[goal, snake[[1]] + d],
{
PrependTo[snake, snake[[1]] + d];
goal = DeleteCases[goal, snake[[1]]];
If[Length@Snake <= width^2 - goalNum, PrependTo[goal, newgoal]]
},
{
snake = RotateRight[snake, 1];
snake[[1]] = snake[[2]] + d
}
];
];
WinQ := Length@snake = width^2;
t0 = AbsoluteTime[];
Dynamic@Graphics[{Thickness[0.025],
Line[{#[[2]], width + 1 - #[[1]]} & /@ snake], Blue,
PointSize[0.05], Point[{#[[2]], width + 1 - #[[1]]} & /@ goal]},
PlotRange -> {{0, width + 1}, {0, width + 1}}, Frame -> True,
FrameTicks -> None]
While[Not@WinQ, Pause[delay]; GoForward]
AbsoluteTime[] - t0
Clear["Global`*"]
width = 20;
goalNum = 25;
delay = 0.01;
AllPoint = Join @@ Table[{i, j}, {i, width}, {j, width}];
snake = {{1, 2}, {1, 1}};
goal = RandomSample[DeleteCases[AllPoint, Alternatives @@ snake],
goalNum];
newgoal :=
RandomChoice[
DeleteCases[AllPoint, Alternatives @@ Join[snake, goal]]];
direction := Switch[snake[[1]],
{x_, y_} /; x == width && y == 2, {0, -1},
{x_, y_} /; x == 1 && y == 1, {0, 1},
{x_, y_} /; (Mod[x - 1, 2] == 1) && 2 <= y <= width - 1, {0, 1},
{x_, y_} /; (Mod[x, 2] == 0) && 3 <= y <= width, {0, -1},
{x_, y_} /; y = width, {1, 0},
{x_, y_} /; y = 2, {1, 0},
{x_, y_} /; y = 1, {-1, 0}];
GoForward := Module[{d},
d = direction;
If[NemberQ[goal, snake[[1]] + d],
{
PrependTo[snake, snake[[1]] + d];
goal = DeleteCases[goal, snake[[1]]];
If[Length@Snake <= width^2 - goalNum, PrependTo[goal, newgoal]]
},
{
snake = RotateRight[snake, 1];
snake[[1]] = snake[[2]] + d
}
];
];
WinQ := Length@snake = width^2;
t0 = AbsoluteTime[];
Dynamic@Graphics[{Thickness[0.025],
Line[{#[[2]], width + 1 - #[[1]]} & /@ snake], Blue,
PointSize[0.05], Point[{#[[2]], width + 1 - #[[1]]} & /@ goal]},
PlotRange -> {{0, width + 1}, {0, width + 1}}, Frame -> True,
FrameTicks -> None]
While[Not@WinQ, Pause[delay]; GoForward]
AbsoluteTime[] - t0