C语言之180行“随机迷宫”代码详解与分析之整理版.pdfVIP

  • 10
  • 0
  • 约1.15万字
  • 约 13页
  • 2021-12-11 发布于河北
  • 举报

C语言之180行“随机迷宫”代码详解与分析之整理版.pdf

C 语言之 180 行“随机迷宫”代码详解与分 析之整理版 代码如下: * 迷宫游戏 by CDQ*/ /* vc++ 6.0 编译成功 本程序参照网上一个特殊算法随机生成迷宫 该算法优点: 效率高,从入口到出口只有唯一路径,入口出口自己设定 该算法缺点: 宽度高度都必须为奇数,只能生成 n*m 矩阵迷宫 */ #include stdio.h #include conio.h #include windows.h #include time.h #define Height 31 // 迷宫的高度,必须为奇数 #define Width 25 // 迷宫的宽度,必须为奇数 #define Wall 1 #define Road 0 #define Start 2 #define End 3 #define Esc 5 #define Up 1 #define Down 2 #define Left 3 #define Right 4 int map[Height+2][Width+2]; void gotoxy(int x,int y) // 移动坐标 { COORD coord; coord.X=x; coord.Y=y; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord ); } void hidden()// 隐藏光标 { HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(hOut,cci); cci.bVisible=0;// 赋 1 为显示,赋 0 为隐藏 SetConsoleCursorInfo(hOut,cci); } void create(int x,int y) // 随机生成迷宫 { int c[4][2]={0,1,1,0,0,-1,-1,0}; // 四个方向 int i,j,t; // 将方向打乱 for(i=0;i4;i++) { j=rand()%4; t=c[i][0];c[i][0]=c[j][0];c[j][0]=t; t=c[i][1];c[i][1]=c[j][1];c[j][1]=t; } map[x][y]=Road; for(i=0;i4;i++) if(map[x+2*c[i][0]][y+2*c[i][1]]==Wall) { map[x+c[i][0]][y+c[i][1]]=Road; create(x+2*c[i][0],y+2*c[i][1]); } } int get_key() // 接收按键 { char c; while(c=getch()) { if(c==27) return Esc; //Esc if(c!=-32)continue; c=getch(); if(c==72) return Up; // 上 if(c==80) return Down; // 下 if(c==75) return Left; // 左 if(c==77) return Right; // 右 } return 0; } void paint(int x,int y) // 画迷宫 { gotoxy(2*y-2,x-1); switch(map[x][y]) { case Start: printf( 入 );break; // 画入口 case End: printf( 出);break; // 画出口 case Wall: printf( ※);break; // 画墙 case Road: printf( );break; // 画路 } } void game() { int x=2,y=1; // 玩家当前位置,刚开始在入口处 int c; // 用来接收按键 while(1) { gotoxy(2*y-2,x-1); printf( ☆ ); // 画出玩家当前位置 if(map[x][y]==End) // 判断是否到达出口 { gotoxy(30,24); printf( 到达

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档