C语言用图形函数实现电脑自动演示汉诺塔

你唯一需要注意的是必须要安装图形函数库,我是在VC和VS上用Easyx图形函数库。

代码如下:

#include<stdio.h>
#include<graphics.h>	//图形函数库
#include<windows.h>		//windows函数库

#define DISKHEIGHT 20	//每个碟子高度
#define WIDTH 10		//碟子宽度比例系数

typedef struct
{
	int type;		//盘的大小,从1到7不等
}disk;

//塔的栈结构
typedef struct
{
	disk d[30];
	int top;
}tower;

//初始化栈函数
int init(tower &tmp)
{
	tmp.top = -1;
	return 1;
}

//入栈
int push(tower &tmp, int tp)
{
	tmp.d[++tmp.top].type = tp;
	return 1;
}

//出栈
int pop(tower &tmp)
{
	return tmp.d[tmp.top--].type;
}


void draw();

tower a, b, c;		//三座塔
int m;				//初始碟子个数
int sleeptime;		//移动间隔时间

//移动碟子
void move(int x, int y)
{
	int ret;
	printf("%d -> %d\n", x, y);
	switch (x)
	{
	case 1:ret = pop(a); break;
	case 2:ret = pop(b); break;
	case 3:ret = pop(c); break;
	default:printf("error ocur!\n");
	}

	switch (y)
	{
	case 1: push(a, ret); break;
	case 2: push(b, ret); break;
	case 3: push(c, ret); break;
	default:printf("error ocur!\n");
	}
	draw();
}

//汉诺塔的递归函数
void hanoi(int n, int one, int two, int three)
{
	if (n == 1)
		move(one,three);
	else
	{
		hanoi(n - 1, one ,three,two);
		move(one, three);
		hanoi(n - 1, two, one, three);
	}
}

//画一个塔
void drawtower(int px,int py,tower tmp)
{
	int nowBottom = py+m*DISKHEIGHT;
	setcolor(RGB(255,0,0));
	fillrectangle(px-2,py,px+2,nowBottom+DISKHEIGHT);
	setcolor(RGB(0, 0, 240));
	int i;
	for (i = 0; i <= tmp.top; i++)
	{
		fillrectangle(px - tmp.d[i].type*WIDTH,nowBottom,px+tmp.d[i].type*WIDTH,nowBottom+DISKHEIGHT);
		nowBottom -= DISKHEIGHT;
	}

}

//调用画塔函数画三个塔
void draw()
{
	cleardevice();
	drawtower(100+m * WIDTH, 20, a);
	drawtower(200+3 * m * WIDTH, 20, b);
	drawtower(300+5 * m * WIDTH, 20, c);
	FlushBatchDraw();
	Sleep(sleeptime);
}

//主函数
int main()
{
	int i;
	init(a); init(b); init(c);
	printf("请输入塔的层数(1~30):");
	scanf("%d", &m);
	printf("请输入移动时间间隔(ms):");
	scanf("%d",&sleeptime);

	for (i = 0; i < m; i++)
	{
		push(a, m - i);
	}
	initgraph(m*2*WIDTH*3+400, m*DISKHEIGHT+100,SHOWCONSOLE);
	setcolor(RGB(0, 0, 240));
	BeginBatchDraw();
	hanoi(m, 1, 2, 3);
	EndBatchDraw();
	system("pause");
}

效果如下:


  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值