迷宫 C++源代码
oenglD迷宫 C实现 源代码
o e n g l D迷宫C实现源代码集团标准化办公室:[VV986T-J682P28-JP266L8-68PNN]#include <iostream>using namespace std;void drawwalls(void);void drawtop(void);void drawball(void);#define IDM_APPLICATION_EXIT (101)#define IDM_APPLICATION_TEXTURE (102)#define IDM_APPLICATION_BANK (103)#define MAZE_HEIGHT (16)#define MAZE_WIDTH (16)#define STARTING_POINT_X ;#define STARTING_POINT_Y ;#define STARTING_HEADING ;float player_x = STARTING_POINT_X ;float player_y = STARTING_POINT_Y ;float player_h = STARTING_HEADING ; // player's headingfloat player_s = ; // forward speed of the playerfloat player_m = ; // speed multiplier of the playerfloat player_t = ; // player's turning (change in heading)float player_b = ; // viewpoint bank (roll)static float texcoordX=;int walllist=0;int mazelist=0;int balllist=0;int status=1;bool searchroute=false;bool keystate[4]={false,false,false,false};char mazedata[MAZE_HEIGHT][MAZE_WIDTH] = {{'H','H','H','H','H','H','H','H','H','H','H','H','H','H','H','H'}, {'H',' ',' ',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H'}, {'H',' ','H',' ','H','H','H',' ','H',' ','H',' ',' ',' ',' ','H'}, {'H',' ','H','H',' ',' ','H',' ','H','H',' ','H',' ','H',' ','H'},{'H',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H',' ','H'}, {'H',' ','H','H','H','H','H','H','H','H',' ','H','H','H',' ','H'}, {'H',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','H',' ',' ','H'}, {'H',' ','H','H','H','H','H',' ','H','H','H',' ','H','H','H','H'}, {'H',' ','H',' ',' ',' ','H',' ',' ',' ','H',' ',' ',' ',' ','H'}, {'H',' ',' ',' ','H','H','H','H','H','H','H',' ',' ',' ',' ','H'}, {'H',' ','H',' ',' ',' ','H',' ',' ',' ','H',' ',' ','H',' ','H'}, {'H',' ','H','H','H','H','H',' ','H','H','H','H',' ','H',' ','H'}, {'H',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H',' ','H'}, {'H',' ',' ','H','H',' ','H','H','H','H',' ','H','H','H',' ','H'}, {'H',' ',' ',' ','H',' ','H',' ',' ',' ',' ','H',' ',' ',' ','H'}, {'H','H','H','H','H','H','H','H','H','H','H','H','H',' ','H','H'}, };void myinit(){glClearColor, , , ;glColor3f,,;glEnable(GL_DEPTH_TEST);glEnable(GL_TEXTURE_2D);walllist=glGenLists(2);mazelist=walllist+1;balllist=walllist+2;glNewList(walllist,GL_COMPILE);drawwalls();glEndList();glNewList(mazelist,GL_COMPILE);drawtop();glEndList();glNewList(balllist,GL_COMPILE);drawball();glEndList();glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective, , , ;glMatrixMode(GL_MODELVIEW);glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);//ê1àí2±D}bool wall(int x,int y) {return (x>=0 && y>=0 && x<MAZE_WIDTH && y<MAZE_HEIGHT && mazedata[y][x]!=' ');}bool onopen(int x,int y){if(wall(x,y)){return(mazedata[y][x]=='H');}}void closeit(int x,int y) {if(onopen(x,y)){mazedata[y][x]= 'X';}}bool neighbor(int x,int y,int w,int *nx,int *ny){ switch(w) {case 0:*nx = x-1; *ny=y; break;case 1:*nx = x; *ny=y+1; break;case 2:*nx = x+1; *ny=y; break;case 3:*nx = x; *ny=y-1; break;default:break;}return wall(*nx,*ny);}bool diagnal(int x,int y,int w,int *nx,int *ny){ switch(w) {case 0:*nx = x-1; *ny=y-1; break;case 1:*nx = x-1; *ny=y+1; break;case 2:*nx = x+1; *ny=y+1; break;case 3:*nx = x+1; *ny=y-1; break;default:break;}return wall(*nx,*ny);}void dw(int x,int y,int p) {int w=p;closeit(x,y);do{int x2=0;int y2=0;if(neighbor(x,y,w,&x2,&y2)){if(onopen(x2,y2)) {dw(x2,y2,(w+3)%4);}else {if((w+1)%4 ==p){return ;}}}else {float fx;float fy;if(diagnal(x,y,w,&x2,&y2) && onopen(x2,y2)) {dw(x2,y2,(w+2)%4);}texcoordX=(texcoordX<:;fx = (float)x+((w==1||w==2):;fy = (float)y+((w==0||w==1):;glTexCoord2f(texcoordX,;glVertex3f(fx,fy,;glTexCoord2f(texcoordX,;glVertex3f(fx,fy,;}w++;w%=4;}while (w!=p);return ;}void drawwalls() {glEnable(GL_TEXTURE_2D); glBegin(GL_QUAD_STRIP);glColor3f,,;glVertex3f, , ;glVertex3f, , ;dw(0,0,0);glEnd();}void drawtop() {int x,y;glBegin(GL_QUADS);for(y=0;y<MAZE_HEIGHT;y++) {for(x=0;x<MAZE_WIDTH;x++) {if(wall(x,y)) {mazedata[y][x]= 'X';glVertex3f(x+ ,y+ , );glVertex3f(x+ ,y+ , );glVertex3f(x+ ,y+ , );glVertex3f(x+ ,y+ , );}}}glEnd();}void forward(float px,float py,float bf) { int x = ((int)player_x);int y = ((int)player_y);int h=0;if((px> x+ - bf) && wall(x+1,y)) { px = (float)(x)+;h++;}if(py> y+ && wall(x,y+1)) {py = (float)(y)+;h++;}if(px< x+bf && wall(x-1,y)) {px = (float)(x)+bf;h++;}if(py< y+bf && wall(x,y-1)) {py = (float)(y)+bf;h++;}player_x=px;player_y=py;}void drawball(){glDisable(GL_TEXTURE_2D);glColor3f,,;glutSolidSphere,15,15);}void navmaze1(){forward(player_x+player_s*(float)sin(player_h*180), player_y+player_s*(float)cos(player_h*180),;cout<<player_x<<player_y<<endl;player_h+=player_t;glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();glPushMatrix();glRotatef,,,;glRotatef(player_h,,,;glTranslatef(-player_x,-player_y,;glCallList(walllist);glPopMatrix();}void navmaze2(){forward(player_x+player_m*player_s*(float)sin(player_h*180), player_y+player_m*player_s*(float)cos(player_h*180),;cout<<player_x<<player_x<<endl;player_h+=player_t;glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity();glOrtho,,,,,;glPushMatrix();glRotatef,,,;glTranslatef(-MAZE_WIDTH /2,-MAZE_HEIGHT/2,;glCallList(walllist);glCallList(mazelist);glPushMatrix();glTranslatef(player_x,player_y,;glCallList(balllist);glPopMatrix();glPopMatrix();}void myDisplay(){if(status==1){if(searchroute==true){}else navmaze1();}if(status==3){if(searchroute==true){}else navmaze2();}glFlush();glutSwapBuffers();}void myReshape(int w, int h){glViewport(0,0,w,h);glMatrixMode(GL_PROJECTION);glLoadIdentity();glMatrixMode(GL_MODELVIEW);glLoadIdentity();glutPostRedisplay();}void specialKeys(int key,int x,int y){switch (key){case GLUT_KEY_LEFT:keystate[2] = true;player_t = ;break;case GLUT_KEY_RIGHT:keystate[3] = true;player_t = ;break;case GLUT_KEY_UP:keystate[0] = true;player_s = ;break;case GLUT_KEY_DOWN:keystate[1] = true;player_s = ;break;default:break;}}void keyboard(unsigned char key,int x,int y) {switch (key){case '1':status=1;break;case '3':status=3;break;default:break;}glutPostRedisplay();}void upSpecialKeyboard(int key,int x,int y){switch (key){case GLUT_KEY_LEFT:keystate[2] = false;player_t = ;break;case GLUT_KEY_RIGHT:keystate[3] = false;player_t = ;break;case GLUT_KEY_UP:keystate[0] = false;player_s = ;break;case GLUT_KEY_DOWN:keystate[1] = false;player_s = ;break;default:break;}// glutPostRedisplay();}void idle(){if(keystate[0]||keystate[1]||keystate[2]||keystate[3]) glutPostRedisplay();else{}}//êí·°′üoóíèD×′ì£è1D×′ì2ò±′í£íá-í£í£′··¨è±μêaúoü′óvoid main(int argc, char** argv){glutInit(&argc,argv);glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(500, 500);glutCreateWindow("polygon modeler");glutDisplayFunc(myDisplay);myinit ();glutSpecialFunc(specialKeys);glutKeyboardFunc(keyboard);glutSpecialUpFunc(upSpecialKeyboard);glutIdleFunc(idle);glutMainLoop();}。
迷宫程序源代码
#include"stdio.h"#include"stdlib.h"#define M1 11#define N1 11 /*M1*N1为加上围墙后的迷宫大小*/#define MAX 100 /*定义栈的最大长度*/int M=M1-2;int N=N1-2; /*M*N为原迷宫大小*/typedef struct /*定义栈元素的类型*/{int x,y,dir;}elemtype;typedef struct /*定义顺序栈*/{elemtype stack[MAX];int top;}P;struct moved /*定义方向位移数组的类型*/{int dx;int dy;};void Newmg(int mg[M1][N1]) /*迷宫的初始化*/{int i,j,num;printf("迷宫:\n");for (i=1;i<=M;i++){for (j=1;j<=N;j++){num=(800*(i+j)+1500)%327; /*根据N和M值伪随机产生迷宫*/if((num<150)&&(i!=M||j!=N))mg[i][j]=1;elsemg[i][j]=0;printf("%3d",mg[i][j]);} /*输出迷宫*/printf("\n");}printf("\n");for(i=0;i<=M+1;i++) /*设置迷宫的围墙*/{mg[i][0]=1;mg[i][N+1]=1;}for(j=0;j<=N+1;j++)mg[0][j]=1;mg[N+1][j]=1;}}void Newmove(struct moved move[8]) /*定义存储坐标变量的方向位移*/ {move[0].dx=0;move[0].dy=1; /*寻找方向依次为:东,东南,南,move[1].dx=1;move[1].dy=1; 西南,西,西北,北,东北*/ move[2].dx=1;move[2].dy=0;move[3].dx=1;move[3].dy=-1;move[4].dx=0;move[4].dy=-1;move[5].dx=-1;move[5].dy=-1;move[6].dx=-1;move[6].dy=0;move[7].dx=-1;move[7].dy=1;}void Newstack(P *s) /*初始化栈*/{s->top=-1;}int RuZhan(P *s ,elemtype x) /*将数据元素x压入指针s所指的栈中*/ {if (s->top==MAX-1)return (0); /*如栈满,即压栈失败,则返回0*/ else{s->stack[++s->top]=x;return(1); /*压栈成功,则返回1*/}}elemtype ChuZhan(P *s) /*栈顶元素出栈*/{elemtype elem;if (s->top<0) /*如果栈空,返回空值*/{elem.x=NULL;elem.y=NULL;elem.dir=NULL;return(elem);}elses->top--;return(s->stack[s->top+1]); /*如果栈非空,返回栈顶元素*/}}void Search(int mg[M1][N1],struct moved move[8],P *s){ /*寻找迷宫的通路*/int i,j,dir,x,y,k;elemtype elem;i=1;j=1;dir=0;mg[1][1]=-1; /*设置(1,1)为入口处*/do{x=i+move[dir].dx; /*寻找下一步可行的到达点的坐标*/y=j+move[dir].dy;if(mg[x][y]==0){elem.x=i;elem.y=j;elem.dir=dir;k=RuZhan(s,elem); /*如果可通过,将此点数据压栈*/if(k==0)printf("栈长度太短\n"); /*如果入栈操作返回0,说明栈容量不够*/i=x;j=y;dir=0;mg[x][y]=-1;}else if(dir<7)dir++;else /*如果八个方向都不可行,就退回一步*/ {elem=ChuZhan(s);if (elem.x!=NULL){i=elem.x;j=elem.y;dir=elem.dir+1;}}}while (!((s->top==-1)&&(dir>=7)||(x==M)&&(y==N)));/*循环,直到入口处或出口处为止*/if(s->top==-1) /*如果最终是入口处,则迷宫无通路*/printf("此迷宫无通路\n");else{elem.x=x;elem.y=y;elem.dir=dir;k=RuZhan(s,elem); /*将最后出口的坐标压入栈中*/printf("迷宫通路:\n");printf (" 入口->");i=0;while (i<=s->top){printf("(%d,%d)->",s->stack[i].x,s->stack[i].y); /*显示迷宫通路*/ if(i!=s->top)if((i+1)%4==0)printf("\n");i++;}printf ("出口\n");}}void main() /*寻找迷宫通路程序*/{P *s;int mg[M1][N1];struct moved move[8];Newmg (mg); /*调用函数初始化迷宫*/s=(P*)malloc(sizeof(P));Newstack(s); /*调用函数初始化栈*/Newmove(move); /*调用函数初始化位移数组*/ Search (mg,move,s); /*调用函数寻找迷宫通路*/}。
迷宫(direction)C语言代码
voidmazePath(intmaze[][N],intdirection[][2],intx1,inty1,intx2,inty2) {
inti, j, k, g, h;
PSeqStackst;
DataTypeelement;
1,1,1,1,1,1,1,1,1,1,1
};
mazePath(maze,direction,1,1,6,9);
getchar();
return 0;
}
#include<stdio.h>
#include<conio.h>
intmigong[10][10]= //设置迷宫,最外围1为墙 里边0为可走路径 1为障碍
find=1;
}
if(find==1){ //判断是否找得到
lj[top].d=d;
top++;
lj[top].x=x;
lj[top].y=y;
d=-1;find=0; //重新调整方向
migong[x][y]=-1;}
else{
migong[lj[top].x][lj[top].y]=0;
top--;d=lj[top].d; //找不到的话退栈
case1:x=lj[top].x; y=lj[top].y+1;break;//方向为右
case2:x=lj[top].x+1; y=lj[top].y; break;//方向为下
case3:x=lj[top].x; y=lj[top].y-1;}//方向为左
if(migong[x][y]==0)
c语言迷宫问题代码实现
structStackList
{
SEAT stack[MAXSIZE];
inttop;
}*Stack;
intEmptyStack(StackList*Stack)//判断是否为空栈
{
if(Stack->top==0)
return 0;
else
return 1;
}
intMove[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//分别表示向东、西、南、北需要加上的坐标
CurSeat=temp;
find =1;
}
}
}
}
}while(EmptyStack(Stack));
return false;
}
voidPrintStack(StackList*Stack)//输出路线
{
if(Stack->top==0)
printf("There is no route can be out of the maze\n");
Mark(CurSeat);
if(CurSeat.x==end.x+1&&CurSeat.y==end.y+1)//如果找到出口,返回
{
return true;
}
else
{
intfind=0;
while(CurSeat.di<3&&find==0)//找下一个结点的方向
{
CurSeat.di++;
SEAT temp;
scanf("%d",&n);
printf("Please enter the labyrinth of the coordinates of the wall unit(0<=row,column):\n");
用c语言实现迷宫求解完美源代码
优先队列:用于存储待扩展节点,按照 f(n)值从小到大排序
A*搜索算法的C语言实现
算法流程:包括初始化、搜索、更新父节点等步骤 数据结构:使用优先队列来存储待搜索节点和已访问节点 实现细节:包括如何计算启发式函数、如何选择下一个节点等 性能优化:可以采用多线程、缓存等技术来提高算法的效率
A*搜索算法在迷宫求解中的应用
C语言实现A*搜 索算法
A*搜索算法的基本原理
定义:A*搜索算法是一种启发式搜索 算法,结合了最佳优先搜索和Dijkstra 算法的优点
基本思想:使用启发函数来评估节点的 重要性,优先选择最有希望的节点进行 扩展,从而有效地缩小搜索范围
关键参数:g(n):从起点经过节点n的 实际代价;h(n):从n到目标的估计代 价(启发式函数);f(n)=g(n)+h(n)
最短路径搜索
优化技巧:为了 提高搜索效率和 精度,可以采用 一些优化技巧, 如限制搜索范围、 使用优先队列等
C语言实现 Dijkstra算法
Dijkstra算法的基本原理
Dijkstra算法是一种用于求解最短路径问题的贪心算法 该算法通过不断选择当前最短路径的节点来逼近最短路径 Dijkstra算法适用于带权重的图,其中权重表示节点之间的距离 Dijkstra算法的时间复杂度为O((V+E)logV),其中V是节点数,E是边数
算法复杂度分析:时间复杂 度和空间复杂度分析
感谢您的观看
汇报人:XX
迷宫求解算法的C语言实现流程
初始化迷宫和路径
定义四个方向的移动方向
遍历迷宫,找到起点和终点
使用深度优先搜索或广度优先 搜索算法求解路径
C语言实现深度 优先搜索算法
深度优先搜索算法的基本原理
c语言走迷宫代码
c语言走迷宫代码以下是一个简单的 C 语言走迷宫代码示例,使用了递归算法: ```c#include <stdio.h>#include <stdlib.h>int main() {int size, row, col, choice, i, j;maze[0][0] = "*";maze[1][0] = "O";maze[0][1] = "O";maze[1][1] = "*";size = 2;row = 2;col = 2;while (1) {printf("Enter row: ");scanf("%d", &row);printf("Enter col: ");scanf("%d", &col);if (row < 0 || row > size || col < 0 || col > size) { printf("Invalid row or col. Try again.");}if (maze[row][col] != "*") {printf("Current cell is free. Try again. ");continue;}maze[row][col] = "X";printf("Enter a choice (1-6): ");scanf("%d", &choice);switch (choice) {case 1:row++;col = 0;break;case 2:row--;col = 0;break;case 3:col++;break;col--;break;case 5:row--;col = 1;break;case 6:row++;col = 1;break;default:printf("Invalid choice. Try again. ");continue;}}printf(" maze: ");for (i = 0; i < size * size; i++) { for (j = 0; j < size; j++) {if (maze[i][j] == "*")printf("*");elseprintf("%c", maze[i][j]);}printf("");}return 0;}```该程序首先初始化了一个 2x2 的迷宫,其中 `maze[0][0]` 和`maze[1][0]` 分别标记为 `"O"` 和 `"*"`,其他地方都为空。
C语言迷宫源代码
#include <graphics.h>#include <stdlib.h>#include <bios.h>/*定义几个功能按键*/#define ESC 0x11b /*强行退出游戏*/#define UP 0x4800 /*上下左右四个按键移动小人*/#define DOWN 0x5000#define LEFT 0x4b00#define RIGHT 0x4d00int a[50][50]={0}; /* 存放地图信息的数组0:不可走的障碍物1:可以走的路*/ int qdx=1,qdy=1,zdx=20,zdy=20; /* 起点和终点的坐标*/int renx,reny; /* 小人坐标*/int d=20; /* 小格子的间距*/int kk=0,rr=2;main(){int i,j,m=30,n=16,d=20,k;int gdriver = DETECT, gmode;randtu(200);renx=qdx,reny=qdy;registerbgidriver(gdriver);initgraph(&gdriver, &gmode, "c:\\turboc2");redraw();while(1) /* 反复从键盘获得程序需要的按键*/{if(bioskey(1)) /* 判断是否有按键*/{k=bioskey(0); /* 将按键存入变量k */switch(k) /* 对按键进行分情况处理*/{case ESC: /* ESC键退出*/printf("%d times\n",kk);exit(0); break;case UP: /* UP键向上移动光标*/if(a[renx][reny-1]==1){reny-=1;redraw();}break;case DOWN: /* DOWN键向下移动光标*/if(a[renx][reny+1]==1){reny+=1;redraw();}break;case LEFT: /* LEFT键向左移动光标*/if(a[renx-1][reny]==1){renx-=1;redraw();}break;case RIGHT: /* RIGHT键向右移动光标*/if(a[renx+1][reny]==1){renx+=1;redraw();}break;}}}getch();closegraph();}/*redraw重画函数在用户有操作后,重画游戏画面*/redraw(){int i,j;for(i=qdx;i<=zdx;i++)for(j=qdy;j<=zdy;j++){if(i<renx+rr && i>renx-rr && j<reny+rr && j>reny-rr)if(a[i][j]==0) geziza(i*d,j*d);else gezilu(i*d,j*d);else gezibk(i*d,j*d);}drawren(renx*d,reny*d);}/*随机地图(randlei)函数用于随机生成地图*/randtu(int num){int i,j,xx,yy,sum,t,m,n;srand(time(NULL));loop: sum=0;m=zdy-qdy+1;n=zdx-qdx+1;a[qdx][qdy]=1;a[zdx][zdy]=1;do{t=random(m*n);xx=t/m+1;yy=t%m+1;if(a[xx][yy]==0){a[xx][yy]=1;sum++;}}while(sum<num);if(ok()) return;for(i=0;i<50;i++)for(j=0;j<50;j++)a[i][j]=0;kk++;goto loop;}ok(){ int b[50][50]={0};b[qdx][qdy]=1;tansuo(qdx,qdy,b);return(b[zdx][zdy]);}tansuo(int x,int y,int *b[50][50]) /* 如果当前格子为空白无雷情况,向周围探索相类似的情况,并打开周围的数字*/{if(a[x][y-1]==1 && b[x][y-1]==0){b[x][y-1]=1;tansuo(x,y-1,b);}if(a[x+1][y]==1 && b[x+1][y]==0){b[x+1][y]=1;tansuo(x+1,y,b);}if(a[x-1][y]==1 && b[x-1][y]==0){b[x-1][y]=1;tansuo(x-1,y,b);}if(a[x][y+1]==1 && b[x][y+1]==0){b[x][y+1]=1;tansuo(x,y+1,b);}}/*绘制障碍物小格子(geziza)int x : 格子左上角点横坐标int y :格子左上角点纵坐标*/geziza(int x,int y){int i;setcolor(8);rectangle(x,y,x+d,y+d);setcolor(RED);setfillstyle(2,RED);bar(x+1,y+1,x+d-1,y+d-1);/* 设置深灰色为格子边框*/ }/*绘制障碍物小格子(geziza)int x : 格子左上角点横坐标int y :格子左上角点纵坐标*/gezibk(int x,int y){int i;setcolor(8);rectangle(x,y,x+d,y+d);setcolor(BLUE);setfillstyle(2,BLUE);bar(x+1,y+1,x+d-1,y+d-1);/* 设置深灰色为格子边框*/}gezilu(int x,int y){int i;setcolor(8); /* 设置深灰色为格子边框*/ rectangle(x,y,x+d,y+d);setcolor(BLUE);setfillstyle(8,BLUE);bar(x+1,y+1,x+d-1,y+d-1);}/*画小人(drawren)函数用于绘制给定坐标位置的小人小人画在格子的正中心格子背景色为红色int x : 所在格子左上角点横坐标int y :所在格子左上角点纵坐标*/drawren(int x,int y){int i;setcolor(8); /* 设置深灰色为格子边框*/ rectangle(x,y,x+d,y+d);setcolor(YELLOW);for(i=1;i<d/2-3;i++)circle(x+d/2,y+d/2,i);}/*over(over)函数用于判断游戏是否结束*/over(){}。
c语言版 迷宫 完整版代码
line(500,200,450,250);
outtextxy(445,270,"z");
line(500,200,550,250);
case 7: (*y)--;break; /*左*/
case 8: (*x)--;(*y)--;break; /*左上*/ }
setfillstyle(SOLID_FILL,RED);/*新位置显示探索物*/
bar(100+(*y)*15-6,50+(*x)*15-6,100+(*y)*15+6,50+(*x)*15+6); }
else if(c=='x'&&map[x+1][y]!=1) DrawPeople(&x,&y,5);/*下*/
else if(c=='z'&&map[x+1][y-1]!=1) DrawPeople(&x,&y,6); /*左下*/
WayCopy(oldmap,map);
if(oldmap[i+1][j]==0&&!yes)/*判断下方是否可以走,如果标志yes已经是1也不用找下去了*/
{ FindWay(oldmap,i+1,j);
{ FindWay(oldmap,i,j+1);
if(yes) { way[wayn][0]=i; way[wayn++][1]=j; return; } }
WayCopy(oldmap,map);
#include <graphics.h>
c语言迷宫代码
c语言迷宫代码C语言迷宫代码是指用C语言编写的程序,用于生成和解决迷宫问题的算法。
迷宫通常由一个矩形网格组成,其中包含墙壁和通道。
目标是找到从迷宫的起点到终点的路径,同时避开墙壁。
下面是一个简单的示例代码,用于生成迷宫:```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h>#define ROWS 10#define COLS 10typedef struct {int x;int y;} Point;void generateMaze(int maze[ROWS][COLS]) {for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {if (i % 2 == 0 || j % 2 == 0) { maze[i][j] = 1; // 墙壁} else {maze[i][j] = 0; // 通道}}}}void printMaze(int maze[ROWS][COLS]) {for (int i = 0; i < ROWS; i++) {for (int j = 0; j < COLS; j++) {printf('%d ', maze[i][j]);}printf('');}}int main() {int maze[ROWS][COLS];generateMaze(maze);printMaze(maze);return 0;}```在上面的代码中,我们使用一个二维数组来表示迷宫。
数组中的值为1表示墙壁,值为0表示通道。
使用generateMaze函数,我们将迷宫的墙壁和通道初始化为适当的值。
然后使用printMaze函数打印迷宫。
通过运行上面的代码,我们可以得到一个简单的迷宫的表示:```1 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 11 1 1 1 1 1 1 1 1 11 0 1 0 1 0 1 0 1 1```当然,上述代码只是生成了一个简单的迷宫,还没有解决迷宫问题。
迷宫游戏C语言小游戏源代码
PosType NextPos(PosType seat,i nt di);
Status MazePath(PosType start,PosType end);
void CreatMaze(void)
/* Forቤተ መጻሕፍቲ ባይዱ the maze. */
case ''''''''''''''''''''''''''''''''2'''''''''''''''''''''''''''''''':Maze[j][k]=2・break・
case ''''''''''''''''''''''''''''''''3'''''''''''''''''''''''''''''''':Maze[j][k]=1・
用c语言实现迷宫求解完美源代码
用c语言实现迷宫求解完美源代码#include#include#include#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0#define OVERFLOW -2#define UNDERFLOW -2typedef int Status;//-----栈开始-----typedef struct{//迷宫中r行c列的位置int r;int c;}PostType;//坐标位置类型typedef struct{int ord;// 当前位置在路径上的序号PostType seat;// 当前坐标int di;// 从此通块走向下一通块的“方向”}SElemType;// 栈的元素类型//定义链式栈的存储结构struct LNode{SElemType data;//数据域struct LNode *next;//指针域};struct LStack{struct LNode *top;//栈顶指针};Status InitStack(LStack &s)//操作结果:构造一个空栈S {struct LNode *p;p=(LNode *)malloc(sizeof(LNode));if(!p){printf("分配失败,退出程序");exit(ERROR);}s.top=p;p->next=NULL;return OK;}Status StackEmpty(LStack s)//若栈s为空栈,则返回TRUE,否则FALSE{if(s.top->next==NULL) return TRUE;return FALSE;}Status Push(LStack &s,SElemType e)//插入元素e成为新的栈顶元素{struct LNode *p;p=(LNode *)malloc(sizeof(LNode));if(!p) exit(OVERFLOW);s.top->data=e;p->next=s.top;s.top=p;return OK;}Status Pop(LStack &s,SElemType &e)//删除s的栈顶元素,并且用e返回其值{struct LNode *p;if(!(s.top->next)) exit(UNDERFLOW);p=s.top;s.top=p->next;e=s.top->data;free(p);return OK;}Status DestroyStack(LStack &s)//操作结果:栈s被销毁{struct LNode *p;p=s.top;while(p){s.top=p->next;free(p);p=s.top;}return OK;}//-----栈结束------//-----迷宫开始-------#define MAXLEN 10// 迷宫包括外墙最大行列数typedef struct{int r;int c;char adr[MAXLEN][MAXLEN];// 可取' ''*' '@' '#'}MazeType;// 迷宫类型Status InitMaze(MazeType&maze){// 初始化迷宫,成功返回TRUE,否则返回FALSE int m,n,i,j;printf("输入迷宫行数和列数(包括了外墙): ");scanf("%d%d",&maze.r,&maze.c); // 输入迷宫行数和列数for(i=0;i<=maze.c+1;i++){// 迷宫行外墙maze.adr[0][i]='#';maze.adr[maze.r+1][i]='#';}//forfor(i=0;i<=maze.r+1;i++){// 迷宫列外墙maze.adr[i][0]='#';maze.adr[i][maze.c+1]='#';}for(i=1;i<=maze.r;i++)for(j=1;j<=maze.c;j++)maze.adr[i][j]=' ';// 初始化迷宫printf("输入障碍的坐标((-1 -1)结束): ");scanf("%d%d",&m,&n);// 接收障碍的坐标while(m!=-1){if(m>maze.r || n>maze.c)// 越界exit(ERROR);maze.adr[m][n]='#';// 迷宫障碍用#标记printf("输入障碍的坐标((-1,-1)结束): ");scanf("%d%d",&m,&n);}//whilereturn OK;}//InitMazeStatus Pass(MazeType maze,PostType curpos){// 当前位置可同则返回TURE,否则返回FALSEif(maze.adr[curpos.r][curpos.c]==' ')// 可通return TRUE;elsereturn FALSE;}//PassStatus FootPrint(MazeType &maze,PostType curpos) {// 若走过并且可通,则返回TRUE,否则返回FALSE maze.adr[curpos.r][curpos.c]='*';//"*"表示可通return OK;}//FootPrintPostType NextPos(PostType &curpos,int i){// 指示并返回下一位置的坐标PostType cpos;cpos=curpos;switch(i){//1.2.3.4 分别表示东南西北方向case 1 : cpos.c+=1; break;case 2 : cpos.r+=1; break;case 3 : cpos.c-=1; break;case 4 : cpos.r-=1; break;default: exit(ERROR);}return cpos;}//NextposStatus MarkPrint(MazeType &maze,PostType curpos) {// 曾走过,但不是通路标记,并返回OKmaze.adr[curpos.r][curpos.c]='@';//"@" 表示曾走过但不通return OK;}//MarkPrintStatus MazePath(MazeType &maze,PostType start,PostType end){// 若迷宫maze存在通路,则求出一条同路放在栈中,并返回TRUE,否则返回FALSE struct LStack S;PostType curpos;int curstep;// 当前序号,1,2,3,4分别表示东南西北方向SElemType e;InitStack(S);curpos=start; //设置"当前位置"为"入口位置"curstep=1;// 探索第一位printf("以三元组形式表示迷宫路径:\n");do{if(Pass(maze,curpos)){// 当前位置可以通过FootPrint(maze,curpos);// 留下足迹e.ord=curstep;e.seat=curpos;e.di=1;printf("%d %d %d-->",e.seat.r,e.seat.c,e.di);Push(S,e);// 加入路径if(curpos.r==end.r&&curpos.c==end.c)if(!DestroyStack(S))// 销毁失败exit(OVERFLOW);elsereturn TRUE; // 到达出口else{curpos=NextPos(curpos,1);// 下一位置是当前位置的东邻curstep++;// 探索下一步}//else}//ifelse{// 当前位置不通时if(!StackEmpty(S)){Pop(S,e);while(e.di==4&& !StackEmpty(S)){MarkPrint(maze,e.seat);Pop(S,e);// 留下不能通过的标记,并退一步}//whileif(e.di < 4){e.di++;// 换一个方向探索Push(S,e);curpos=NextPos(e.seat,e.di);// 设定当前位置是该方向上的相邻printf("%d %d %d-->",e.seat.r,e.seat.c,e.di);}//if}//if}//else}while(!StackEmpty(S));if(!DestroyStack(S))// 销毁栈exit(OVERFLOW);elsereturn FALSE;}//MazePathvoid PrintMaze(MazeType &maze){// 将标记路径信息的迷宫输出到终端int i,j;printf("\n输出迷宫(*表示通路):\n\n");printf("");for(i=0;i<=maze.r+1;i++)// 打印列数名printf("%4d",i);printf("\n\n");for(i=0;i<=maze.r+1;i++){printf("%2d",i);// 打印行名for(j=0;j<=maze.c+1;j++)printf("%4c",maze.adr[i][j]);// 输出迷宫当前位置的标记printf("\n\n");}}//PrintMazeint main(){// 主函数MazeType maze;PostType start,end;char cmd;do{printf("-------创建迷宫--------\n");if(!InitMaze(maze)){printf("Initialization errors\n");exit(OVERFLOW);// 初始化失败}do{// 输入迷宫入口坐标printf("\n输入迷宫入口坐标: ");scanf("%d%d",&start.r,&start.c);if(start.r>maze.r ||start.c>maze.c){printf("\nBeyond the maze\n"); continue;}}while(start.r>maze.r ||start.c>maze.c);do{// 输入迷宫出口坐标printf("\n输入迷宫出口坐标: ");scanf("%d%d",&end.r,&end.c);if(end.r>maze.r ||end.c>maze.c){printf("\nBeyond the maze\n"); continue;}}while(end.r>maze.r ||end.c>maze.c);if(!MazePath(maze,start,end))//迷宫求解printf("\nNo path from entranceto exit!\n"); elsePrintMaze(maze);// 打印路径printf("\n需要继续创建新的迷宫吗?(y/n): "); scanf("%s",&cmd);}while(cmd=='y' || cmd=='Y');}。
c语言迷宫代码
if(tt.l<min) min = tt.l;//最短路径更新
temp = s;
push(&p, tt);//从终点到起点依次入栈p,保存路径
push(&p, t);
while(!empty(&temp))
{
pop(&temp, &tt);
push(&p,tt);
}
step=0;
while(!empty(&p))//从起点到终点依次出栈p,输出路径
{
pop(&p, &tt);
if(step==0) step=1;
else printf(" -> ");
printf("(%d,%d)",tt.x,tt.y);
}
printf("\n");
if(map[i][j] == 'S') sx=i, sy=j;//寻找起点坐标
if(map[i][j] == 'E') ex=i, ey=j;//寻找终点坐标
}
}
dfs();//搜索路径
printf("路径总数:%d\n", num);//输出路径总数
if(num > 0)//若存在可行路径,输出最短、最长路径长度
{
printf("最短路径:%d\n", min);
printf("最长路径:%d\n", max);
}
}
{
datatype data[Maxn];//栈数据
数据结构迷宫源代码
#include <stdio.h>#include <malloc.h>#include <stdlib.h>#include <string.h>#include <time.h>#define OK 1#define ERROR 0#define NULL 0#define OVERFLOW -2#define STACK_INIT_SIZE 100#define STACKINCREMENT 10//栈的顺序存储表示typedef struct{int x; /*列*/int y; /*行*/}PosType; //坐标位置类型typedef struct{int ord; //通道块在路径上的序号PosType seat; //通道块在迷宫中的坐标位置int di; //从此通道块走向下一通道块的方向}SElemType; //栈的元素类型typedef struct {SElemType *base;SElemType *top;int stacksize; //当前已分配的存储空间,以元素为单位}SqStack;//基本操作int InitStack(SqStack *S){S->base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));if(!S->base)exit(OVERFLOW);S->top=S->base;S->stacksize=STACK_INIT_SIZE;return OK;}//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR int GetTop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*(S->top-1);return OK;}int Push(SqStack *S,SElemType *e)//插入元素e作为新的栈顶元素{if(S->top-S->base>=S->stacksize)/*栈满,追加存储空间*/{S->base = (SElemType *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof(SElemType));if(!S->base) exit(OVERFLOW);S->top=S->base+S->stacksize;S->stacksize+=STACKINCREMENT;}*S->top++=*e;return OK;}//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERRORint Pop(SqStack *S,SElemType *e){if(S->top==S->base) return ERROR;*e=*--S->top;return OK;}int StackEmpty(SqStack *S){return(S->top==S->base) ;}//迷宫程序typedef struct {int lie; /*列数*/int hang; /*行数*/char a[999][999];}MazeType; /*迷宫类型*//*随机生成迷宫*/int generatemaze( MazeType *maze){int i,j;maze->a[0][0]=2;maze->a[++maze->hang][++maze->lie]=3;/*设置外墙*/maze->a[0][maze->lie]='!';maze->a[maze->hang][0]='!';for(j=1;j<maze->lie;j++){maze->a[0][j]='!';maze->a[maze->hang][j]='!';}for(i=1;i<maze->hang;i++){maze->a[i][0]='!';maze->a[i][maze->lie]='!';}srand((unsigned)time( NULL ));rand();for(i=1; i <maze->hang; i++)for(j=1;j<maze->lie;j++){if (rand()>=RAND_MAX/4) maze->a[i][j] =' '; //' ' 暗示出路else maze->a[i][j] ='!'; //'!'暗示无出路}return OK;}int Pass(MazeType *maze, PosType curpos ) //判断当前位置可否通过{if ((curpos.x < 1) || (curpos.x >= maze->lie)) return ERROR;if ((curpos.y < 1) || (curpos.y >= maze->hang)) return ERROR;if (maze->a[curpos.y][curpos.x]==' ') return OK;else return ERROR;}int FootPrint(MazeType *maze,PosType curpos) //留下足迹{maze->a[curpos.y][curpos.x]='*';return OK;}int MarkPrint(MazeType *maze,PosType curpos) //留下不能通过的标记{maze->a[curpos.y][curpos.x]='@';return OK;}PosType NextPos(PosType curpos,int di) //返回当前位置的下一位置{PosType pos=curpos;switch(di){case 1: //右东pos.x++;break;case 2: //下南pos.y++;break;case 3: //左西pos.x--;break;case 4: //上北pos.y--;break;}return pos;}//若迷宫有解,则求得一条存放在栈中(从栈底到栈顶),并返回OK,否则返回ERROR int MazePath(MazeType *maze,PosType start,PosType end){PosType curpos;SqStack *S=(SqStack *)malloc(sizeof(SqStack));InitStack(S);SElemType *e;e=(SElemType *)malloc(sizeof(SElemType));curpos=start; //设定当前位置为入口位置int curstep = 1; //探索第一步do{if(Pass(maze,curpos)) //当前位置可通过{FootPrint(maze,curpos);e->ord=curstep;e->seat=curpos;e->di=1;Push(S,e);if(curpos.x==end.x&&curpos.y==end.y) return (OK);curpos=NextPos(curpos,1);curstep++;}else{if(!StackEmpty(S)){Pop(S,e);while(e->di==4&&!StackEmpty(S)) //栈不空但栈顶位置四周均不通{MarkPrint(maze,e->seat);Pop(S,e);}if(e->di<4) //栈不空且栈顶位置四周有其他位置未探索{e->di++;Push(S,e);curpos=e->seat;curpos=NextPos(curpos,e->di);}}}}while(!StackEmpty(S));return ERROR;}void PrintMaze(MazeType *maze) //打印迷宫{int i,j,k,n;int c[999],d[999];for(i=0,k=0;i<=maze->hang;i++){for(j=0;j<=maze->lie;j++){printf("%c ",maze->a[i][j]);if(maze->a[i][j]=='*'){c[k]=i;d[k]=j;k++;}}printf("\n");}n=k;for(k=0;k<n;k++)printf("<%d,%d>",c[k],d[k]);printf("\n");printf("\n");}int main(){int zmg;char ch;printf(" 数据结构课程设计--迷宫问题求解\n\n");printf(" |----------------------------------------|\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | |\n");printf(" | XXXX XXXXXXXXXXXXXX |\n");printf(" | XXXXXXX |\n");printf(" |----------------------------------------|\n");getchar();do{system("cls");fflush(stdin);MazeType *maze=(MazeType *)malloc(sizeof(MazeType));//设置迷宫的长宽不含外墙printf("请输入迷宫的列数(不含外墙时):");scanf("%d",&maze->lie);printf("请输入迷宫的行数(不含外墙时):");scanf("%d",&maze->hang);generatemaze(maze);printf("随机创建迷宫\n");PrintMaze(maze);getchar();getchar();PosType start,end;start.x=1;start.y=1;end.x=maze->lie-1;end.y=maze->hang-1;zmg=MazePath(maze,start,end);if(zmg){printf("此迷宫通路为\n");PrintMaze(maze);}else printf("此迷宫无通路\n");//getchar();printf("再次尝试?(Y/N)?");scanf("%c",&ch);}while(ch=='Y'||ch=='y');return 0; }。
迷宫问题源代码及运行结果
//其中0表示路,1表示墙,-1表示已走过//迷宫问题广度优先算法# include<stdio.h># include<stdlib.h>typedef struct squeue{int x;int y;int pre;}squeue;squeue Q[100]; //队列用于存放迷宫通路int qe,qh; //队列指针int map[8][8]={{0,0,0,0,0,0,0,0},{0,1,1,1,1,0,1,0},{0,0,0,0,1,0,1,0},{0,1,0,0,0,0,1,0},{0,1,0,1,1,0,1,0},{0,1,0,0,0,0,1,1},{0,1,0,0,1,0,0,0},{0,1,1,1,1,1,1,0}}; //存放迷宫地图int fx[5]={0,1,-1,0,0},fy[5]={0,0,0,-1,1}; //模拟四个运动方向int check(int i,int j) //检查当前位置是否合适{int flag=1;if(i<0||i>7) //检查行是否越界flag=0;if(j<0||j>7) //检查列是否越界flag=0;if(map[i][j]==1||map[i][j]==-1) //当前位置是否可行flag=0;return flag;}void print() //输出迷宫路径{ int sum=1;printf("\n所求密宫路径为:\n");printf("(%d,%d)",Q[qe].x,Q[qe].y);while(Q[qe].pre!=0){qe=Q[qe].pre;printf("<--(%d,%d)",Q[qe].x,Q[qe].y);sum++;if(sum%5==0)printf("\n");}// printf("<--(%d,%d)\n",Q[qe].x,Q[qe].y);}int search() //走迷宫{int i,j,k;qh=0;qe=1;map[0][0]=-1; //入口入队列,并将其标志变量致零Q[1].pre=0;Q[1].x=0;Q[1].y=0;while(qh!=qe){qh++; //队首元素出队列for(k=1;k<=4;k++) //搜索前后左右四个方向{i=Q[qh].x+fx[k];j=Q[qh].y+fy[k];if(check(i,j)==1){qe++; //入队列,并改变其标志变量Q[qe].x=i;Q[qe].y=j;Q[qe].pre=qh;map[i][j]=-1;if(Q[qe].x==7&&Q[qe].y==7) //若到迷宫出口,则输出路径{print();return 0;}}}}printf("NO Way!\n");return 0;}void main(){int i,j;printf("迷宫图为:");for(i=0;i<=7;i++) //输出原迷宫图{printf("\n");for(j=0;j<=7;j++)printf("%d ",map[i][j]);}printf("\n");search();}。
C++迷宫游戏源代码
if(maze[i][j]==-1)
maze[i][j]=0;
}
}
}
int path1(int **maze,int m,int n,int c,int d,int x1,int y1)//最短路径
{ //m,n为迷宫的ze为迷宫;
front++; //当前点搜索完,取下一个点搜索
} //while
G:cout<<"无路径。"<<endl;
return 0;
}
void path(int **maze,int a,int b,int m,int n)
{
item move[8]={{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
#include<iostream>
#include<stack>
#include<stdio.h>
#include<time.h>
#include<string>
using namespace std;
typedef struct
{
int x,y;
}item;
typedef struct
}
if(i==x1&&j==y1){
cout<<"最短路径为:"<<endl;
printpath(sq,rear); //输出路径;
restore(maze,m,n); //恢复迷宫;
openglD迷宫C实现源代码完整版
o p e n g l D迷宫C实现源代码HUA system office room 【HUA16H-TTMS2A-HUAS8Q8-HUAH1688】#include <iostream>using namespace std;void drawwalls(void);void drawtop(void);void drawball(void);#define IDM_APPLICATION_EXIT (101) #define IDM_APPLICATION_TEXTURE (102) #define IDM_APPLICATION_BANK (103) #define MAZE_HEIGHT (16)#define MAZE_WIDTH (16)#define STARTING_POINT_X (13.5f);#define STARTING_POINT_Y (1.5f);#define STARTING_HEADING (90.0f); float player_x = STARTING_POINT_X ; float player_y = STARTING_POINT_Y ;float player_h = STARTING_HEADING ; // player's headingfloat player_s = 0.0f; // forward speed of the playerfloat player_m = 1.0f; // speed multiplier of the playerfloat player_t = 0.0f; // player's turning (change in heading)float player_b = 0.0f; // viewpoint bank (roll)static float texcoordX=0.0f;int walllist=0;int mazelist=0;int balllist=0;int status=1;bool searchroute=false;bool keystate[4]={false,false,false,false};char mazedata[MAZE_HEIGHT][MAZE_WIDTH] = {{'H','H','H','H','H','H','H','H','H','H','H','H','H','H','H','H'}, {'H',' ',' ',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H'}, {'H',' ','H',' ','H','H','H',' ','H',' ','H',' ',' ',' ',' ','H'},{'H',' ','H','H',' ',' ','H',' ','H','H',' ','H',' ','H',' ','H'}, {'H',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H',' ','H'}, {'H',' ','H','H','H','H','H','H','H','H',' ','H','H','H',' ','H'}, {'H',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','H',' ',' ','H'}, {'H',' ','H','H','H','H','H',' ','H','H','H',' ','H','H','H','H'}, {'H',' ','H',' ',' ',' ','H',' ',' ',' ','H',' ',' ',' ',' ','H'}, {'H',' ',' ',' ','H','H','H','H','H','H','H',' ',' ',' ',' ','H'}, {'H',' ','H',' ',' ',' ','H',' ',' ',' ','H',' ',' ','H',' ','H'}, {'H',' ','H','H','H','H','H',' ','H','H','H','H',' ','H',' ','H'}, {'H',' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ','H',' ','H'}, {'H',' ',' ','H','H',' ','H','H','H','H',' ','H','H','H',' ','H'}, {'H',' ',' ',' ','H',' ','H',' ',' ',' ',' ','H',' ',' ',' ','H'}, {'H','H','H','H','H','H','H','H','H','H','H','H','H',' ','H','H'}, };void myinit(){glClearColor(0.5f, 0.5f, 0.5f, 0.0f); glColor3f(1.0,1.0,1.0);glEnable(GL_DEPTH_TEST);glEnable(GL_TEXTURE_2D);walllist=glGenLists(2);mazelist=walllist+1;balllist=walllist+2;glNewList(walllist,GL_COMPILE);drawwalls();glEndList();glNewList(mazelist,GL_COMPILE);drawtop();glEndList();glNewList(balllist,GL_COMPILE);drawball();glEndList();glMatrixMode(GL_PROJECTION);glLoadIdentity();gluPerspective(60.0, 1.0 , 0.1, 60.0);glMatrixMode(GL_MODELVIEW);glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST);//ê1àí2±D}bool wall(int x,int y) {return (x>=0 && y>=0 && x<MAZE_WIDTH && y<MAZE_HEIGHT && mazedata[y][x]!=' ');}bool onopen(int x,int y){if(wall(x,y)){return(mazedata[y][x]=='H');}}void closeit(int x,int y) {if(onopen(x,y)){mazedata[y][x]= 'X';}}bool neighbor(int x,int y,int w,int *nx,int *ny){ switch(w) {case 0:*nx = x-1; *ny=y; break;case 1:*nx = x; *ny=y+1; break;case 2:*nx = x+1; *ny=y; break;case 3:*nx = x; *ny=y-1; break;default:break;}return wall(*nx,*ny);}bool diagnal(int x,int y,int w,int *nx,int *ny){ switch(w) {case 0:*nx = x-1; *ny=y-1; break;case 1:*nx = x-1; *ny=y+1; break;case 2:*nx = x+1; *ny=y+1; break;case 3:*nx = x+1; *ny=y-1; break;default:break;}return wall(*nx,*ny);}void dw(int x,int y,int p) {int w=p;closeit(x,y);do{int x2=0;int y2=0;if(neighbor(x,y,w,&x2,&y2)){if(onopen(x2,y2)) {dw(x2,y2,(w+3)%4);}else {if((w+1)%4 ==p){return ;}}}else {float fx;float fy;if(diagnal(x,y,w,&x2,&y2) && onopen(x2,y2)) {dw(x2,y2,(w+2)%4);}texcoordX=(texcoordX<0.5)1.0f:0.0f;fx = (float)x+((w==1||w==2)1.0f:0.0f);fy = (float)y+((w==0||w==1)1.0f:0.0f);glTexCoord2f(texcoordX,0.0f);glVertex3f(fx,fy,0.0f);glTexCoord2f(texcoordX,1.0f);glVertex3f(fx,fy,1.0f);}w++;w%=4;}while (w!=p);return ;}void drawwalls() {glEnable(GL_TEXTURE_2D);glBegin(GL_QUAD_STRIP);glColor3f(1.0,1.0,1.0);glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); dw(0,0,0);glEnd();}void drawtop() {int x,y;glBegin(GL_QUADS);for(y=0;y<MAZE_HEIGHT;y++) {for(x=0;x<MAZE_WIDTH;x++) {if(wall(x,y)) {mazedata[y][x]= 'X';glVertex3f(x+0.0f ,y+0.0f ,1.0f ); glVertex3f(x+1.0f ,y+0.0f ,1.0f ); glVertex3f(x+1.0f ,y+1.0f ,1.0f ); glVertex3f(x+0.0f ,y+1.0f ,1.0f ); }}}glEnd();}void forward(float px,float py,float bf) {int x = ((int)player_x);int y = ((int)player_y);int h=0;if((px> x+1.0f - bf) && wall(x+1,y)) { px = (float)(x)+1.0f-bf;h++;}if(py> y+1.0f-bf && wall(x,y+1)) {py = (float)(y)+1.0f-bf;h++;}if(px< x+bf && wall(x-1,y)) {px = (float)(x)+bf;h++;}if(py< y+bf && wall(x,y-1)) {py = (float)(y)+bf;h++;}player_x=px;player_y=py;}void drawball(){glDisable(GL_TEXTURE_2D);glColor3f(1.0,0.0,0.0);glutSolidSphere(0.2f,15,15);}void navmaze1(){forward(player_x+player_s*(float)sin(player_h*3.14/180),player_y+player_s*(float)cos(player_h*3.14/180),0.2f);player_h+=player_t;player_b = 3*player_b/4 + player_t/4;glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();glPushMatrix();glRotatef(-90.0f,1.0f,0.0f,0.0f);glRotatef(player_h,0.0f,0.0f,1.0f);glTranslatef(-player_x,-player_y,-0.5f);glCallList(walllist);glPopMatrix();}void navmaze2(){forward(player_x+player_m*player_s*(float)sin(player_h*3.14/180),player_y+player_m*player_s*(float)cos(player_h*3.14/180),0.2f);player_h+=player_t;player_b = 3*player_b/4 + player_t/4;glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();glOrtho(-16.0,16.0,-16.0,16.0,-2.0,20.0);glPushMatrix();glRotatef(90.0f,0.0f,0.0f,1.0f);glTranslatef(-MAZE_WIDTH /2,-MAZE_HEIGHT/2,-0.5f);glCallList(walllist);glCallList(mazelist);glPushMatrix();glTranslatef(player_x,player_y,0.5f);glCallList(balllist);glPopMatrix();glPopMatrix();}void myDisplay(){if(status==1){if(searchroute==true){}else navmaze1();}if(status==3){if(searchroute==true){}else navmaze2();glFlush();glutSwapBuffers();}void myReshape(int w, int h){glViewport(0,0,w,h);glMatrixMode(GL_PROJECTION); glLoadIdentity();glMatrixMode(GL_MODELVIEW); glLoadIdentity();glutPostRedisplay();}void specialKeys(int key,int x,int y) {switch (key)case GLUT_KEY_LEFT:keystate[2] = true;player_t = -2.0f;break;case GLUT_KEY_RIGHT:keystate[3] = true;player_t = 2.0f;break;case GLUT_KEY_UP:keystate[0] = true;player_s = 0.01f;break;case GLUT_KEY_DOWN:keystate[1] = true;player_s = -0.01f;break;default:break;}}void keyboard(unsigned char key,int x,int y) {switch (key){case '1':status=1;break;case '3':status=3;break;default:break;}glutPostRedisplay();}void upSpecialKeyboard(int key,int x,int y){switch (key){case GLUT_KEY_LEFT:keystate[2] = false;player_t = 0.0f;break;case GLUT_KEY_RIGHT:keystate[3] = false;player_t = 0.0f;break;case GLUT_KEY_UP:keystate[0] = false;player_s = 0.0f;break;case GLUT_KEY_DOWN:keystate[1] = false;player_s = 0.0f;break;default:break;}// glutPostRedisplay();}void idle(){if(keystate[0]||keystate[1]||keystate[2]||keystate[3]) glutPostRedisplay();else{}}//êí·°′üoóíèD×′ì£è1D×′ì2ò±′í£íá-í£í£′··¨è±μêaúoü′óvoid main(int argc, char** argv){glutInit(&argc,argv);glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(500, 500);glutCreateWindow("polygon modeler");glutDisplayFunc(myDisplay);myinit ();glutSpecialFunc(specialKeys);glutKeyboardFunc(keyboard);glutSpecialUpFunc(upSpecialKeyboard);glutIdleFunc(idle);glutMainLoop();}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
g_rtSight.left = 0; // 设置视野范围
g_rtSight.top = 0;
g_rtSight.right = 17;
g_rtSight.bottom= 13;
// 设置 GPS 显示区
setfillstyle(BLUE);
setfillstyle(YELLOW);
setcolor(YELLOW);
fillellipse(2, 2, 17, 17);
setcolor(BLACK);
line(7, 7, 7, 8);
line(12, 7, 12, 8);
arc(5, 6, 14, 14, 3.34, 6.08);
outtextxy(4, 4, _T("入"));
// 绘制出口
setorigin(MAP_EXIT, 0);
outtextxy(4, 4, _T("出"));
// 绘制迷宫外面的空地
setorigin(MAP_OUTSIDE, 0);
setfillstyle(GREEN, PATTERN_FILL, "\x50\x55\x22\x20\x05\x55\x22\x02");
int c;
while( !((GetCmd(&c) == CMD_QUIT) && Quit()) )
{
DispatchCmd(c);
Paint();
if (CheckWin())
break;
// 延时
Sleep(100);
}
// 清理迷宫地图占用的内存
Resize(&g_imgGPS, g_szGPS.cx, g_szGPS.cy);
g_ptGPS.x = 530 + 50 - g_szGPS.cx / 2;
g_ptGPS.y = 370 + 50 - g_szGPS.cy / 2;
// 画迷你地图外框
setcolor(RED);
setcolor(GREEN);
moveto(5, 15);
linerel(0, -10); linerel(5, 5); linerel(5, -5); linerel(0, 10);
// 绘制黄色标记
setorigin(MAP_MARKYELLOW, 0);
setcolor(YELLOW);
bar(0, 0, 19, 19);
// 恢复坐标系
setorigin(0, 0);
// 显示作者
SetWorkingImage();
setcolor(BLUE);
TCHAR author[] = _T("Powered by zhaoh1987@");
outtextxy(471, 4, author);
//////////////////////////////////////////////////////
// 函数声明
//
void Welcome(); // 绘制游戏界面
void InitImage(); // 初始化游戏图片
void InitGame(); // 初始化游戏数据
bar(522, 368, 637, 471);
if (g_szMap.cx > g_szMap.cy) { g_szGPS.cx = 100; g_szGPS.cy = (int)(100.0 * g_szMap.cy / g_szMap.cx + 0.5); }
else { g_szGPS.cy = 100; g_szGPS.cx = (int)(100.0 * g_szMap.cx / g_szMap.cy + 0.5); }
POINT g_ptGPS; // 迷你地图的显示位置
SIZE g_szGPS; // 迷你地图的尺寸
POINT g_ptPlayer; // 游戏者的位置
// 枚举地图元素,兼做元素位置的 x 坐标
enum MAPITEM { MAP_WALL = 0, MAP_PLAYER = 20, MAP_GROUND = 40, MAP_MARKRED = 60, MAP_MARKGREEN = 80, MAP_MARKYELLOW = 100, MAP_ENTRANCE = 120, MAP_EXIT = 140, MAP_OUTSIDE = 160 };
SIZE g_szMap; // 迷宫地图的尺寸
IMAGE g_imgSight(360, 280); // 游戏的视野
RECT g_rtSight; // 游戏的视野的范围
IMAGE g_imgItem(180, 20); // 地图元素
IMAGE g_imgGPS; // 迷你地图,用于显示游戏者在地图中的位置
void OnUp(); // 向上移动
void OnLeft(); // 向左移动
void OnRight(); // 向右移动
void OnDown(); // 向下移动
void OnMark(MAPITEM value); // 在地图中做标记
bool CheckWin(); // 检查是否到出口
bool Quit(); // 询问用户是否退出游戏
//////////////////////////////////////////////////////
// 函数定义
//
// 主程序
void main()
MAPITEM GetMazeItem(int x, int y); // 获取指定坐标的迷宫元素
void Paint(); // 绘制视野范围内的迷宫
int GetCmd(int* c); // 获取用户输入的命令
void DispatchCmd(int cmd); // 处理用户输入的命令
for(int x = 0; x < g_szMap.cx + 2; x++)
delete[] g_imgMap[x];
delete [] g_imgMap;
// 关闭图形模式
closegraph();
}
// 绘制游戏界面
void Welcome()
{
// 绘制渐变色外框
void GetMazeSize(); // 提示用户输入迷宫大小
void MakeMaze(int width, int height); // 生成迷宫:初始化(注:宽高必须是奇数)
void TravelMaze(int x, int y); // 生成迷宫:遍历 (x, y) 四周
{
// 初始化
initgraph(640, 480); // 创建绘图窗口
srand((unsigned)time(NULL)); // 设置随机种子
// 显示主界面
Welcome();
// 初始化
InitImage();
InitGame();
// 游戏过程
moveto(5, 15);
linerel(0, -10); linerel(5, 5); linerel(5, -5); linerel(0, 10);
// 绘制入口
setorigin(MAP_ENTRANCE, 0);
setcolor(GREEN);
setfont(12, 0, _T("宋体"));
setbkmode(TRANSPARENT);
// 绘制标题
setfont(36, 0, _T("宋体"));
outtextxy(248, 40, _T("迷 宫"));
// 绘制操作说明
setfont(12, 0, _T("宋体"));
outtextxy(50, 382, _T("控制说明:"));
///////////////////////////////////////////////////
// 程序名称:迷宫 游戏
// 编译环境:Visual C++ 6.0 / 2010,EasyX 2011惊蛰版
// 作 者:krissi <zhaoh1987@>
// 最后修改:2011-3-12
setcolor(LIGHTBLUE);
outtextxy(470, 3, author);
}
// 初始化游戏数据
void InitGame()
{
// 提示用户输入迷宫大小
GetMazeSize();
// 初始化参数
if (g_imgMap != NULL)
{ // 清理迷宫地图占用的内存
outtextxy(74, 400, _T("方向键或 A/S/D/W:移动"));
outtextxy(74, 418, _T("空格、Y、G:在地图上做红、黄、绿色 M 标记"));
outtextxy(74, 436, _T("C:清除地图上的标记"));
outtextxy(74, 454, _T("ESC:退出程序"));
// 绘制墙壁
setorigin(MAP_WALL, 0);
setfillstyle(BROWN, PATTERN_FILL, "\x20\x20\x20\xff\x04\x04\x04\xff");