汉诺塔c语言 动画演示 地址1162765886@qq.com
发布网友
发布时间:2022-05-20 19:40
我来回答
共1个回答
热心网友
时间:2023-11-18 08:38
#include
#include
#include
#include
#include
#include
#define N 10 //定义盘数
RECT r = {240, 0, 460, 240};
TCHAR step[5];
int stepn=0;
int pan[3];
void dizuo()
{
setlinestyle(PS_SOLID,NULL,4);
line(20,400,160,400);
line(90,200,90,400);
line(220,400,360,400);
line(290,200,290,400);
line(420,400,560,400);
line(490,200,490,400);
}
//初始化汉诺塔
void hanoi_draw()
{
int i;
setlinestyle(PS_SOLID,NULL,12);
for(i=0;i<=(N-1)*7;i+=7)
{
setcolor(HSLtoRGB(12*15, 1, 0.5));
line(20+i,390-2*i,160-i,390-2*i);
}
}
//移动
void move(int n,int one,int three)
{
sprintf(step, _T("%d"),++stepn);
outtextxy(340,140,step);
pan[one-1]-=1;
pan[three-1]+=1;
setlinestyle(PS_SOLID,NULL,12);
clearrectangle((one-1)*200+(N-n)*7,390-(pan[one-1])*14-6,(one-1)*200+180-(N-n)*7,390-(pan[one-1])*14+6);
dizuo();
setlinestyle(PS_SOLID,NULL,12);
line((three-1)*200+(N-n)*7+14,390-(pan[three-1]-1)*14,(three-1)*200+166-(N-n)*7,390-(pan[three-1]-1)*14);
}
//汉诺塔算法
void hanoi(int n,int one,int two,int three)
{
if (n==1)
{
move(n-1,one,three);
}
else
{
hanoi(n-1,one,three,two);
Sleep(2000);
move(n-1,one,three);
Sleep(2000);
hanoi(n-1,two,one,three);
}
}
void main()
{
initgraph(640,480); //初始化图形
// 设置背景色为蓝色
setbkcolor(BLUE);
// 用背景色清空屏幕
cleardevice();
settextstyle(30, 0, _T("宋体"));
drawtext(_T("汉诺塔动画演示"), &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
settextstyle(16, 0, _T("宋体"));
outtextxy(300,140,"step:");
pan[0]=N; //第一个座初始有3个盘
dizuo(); //画出底座
hanoi_draw(); //初始化汉诺塔
Sleep(2000);
hanoi(N,1,2,3);
getch();
closegraph;
}