猿猴崛起中猴子玩的汉诺塔游戏--北太天元软件帮你玩

% 汉诺塔游戏(hanoi)
%汉诺塔(Tower of Hanoi),又称河内塔,是一个源于印度古老传说的益智玩具。
%大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。
%大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。
%并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
% 北太天元数值计算软件上实现 number 片圆盘的从柱子'A'移动到柱子'C'
function hanoi
global total;
total = 0;
number = input("请输入移盘数:");
hanoi_step(number, 'A', 'B', 'C');
disp(['共需' , num2str(total), '步。\n']);
hanoi_plot(number);
end
function hanoi_step(num, a, b, c)
if (num == 1)
move(a, c);
else
hanoi_step(num - 1, a, c, b);
move(a, c);
hanoi_step(num - 1, b, a, c);
end
end
function move(x, y)
global total;
disp([x '-->' y '\n']);
total = total + 1;
end
function hanoi_plot(num)
clf;close all;
hold on
ymin = 0 ;
ymax = 3*num;
xmin = 0;
xmax = 10*3*num + 2*3
[X,Y] = getRectangle([xmin+5,ymax/2], 1,ymax, 0);
fill(X,Y,'k')
[X,Y] = getRectangle([xmin+5+12,ymax/2], 1,ymax, 0);
fill(X,Y,'k')
[X,Y] = getRectangle([xmin+5+12*2,ymax/2], 1,ymax, 0);
fill(X,Y,'k')
for i=1:num
xc = xmin+5;
yc = i*2-1;
[X,Y] = getRectangle([xc,yc], 10-i,2-i/5, 0);
fill(X,Y,[184*i/3,20,25]./255)
end
hold off
end
% 矩形数据点生成函数
function [X,Y]=getRectangle(Mu,XR,YR,theta)
% Mu | 中心点
% XR,YR | x方向长度,y方向长度
% theta | 旋转角度
[X ] = [ Mu(1)-XR/2 Mu(1)+XR/2 Mu(1)+XR/2, Mu(1)-XR/2];
[Y ] = [ Mu(2)-YR/2 Mu(2)-YR/2 Mu(2)+YR/2, Mu(2)+YR/2];
rotateMat = [cos(theta),-sin(theta);sin(theta),cos(theta)];
XY = rotateMat*[X;Y];
X = XY(1,:);
Y = XY(2,:);
end