openglD迷宫C实现源代码

合集下载

迷宫 C++源代码

迷宫 C++源代码
g_ptPlayer.y = 2;
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);
}
// 清理迷宫地图占用的内存

迷宫游戏C语言代码讲解

迷宫游戏C语言代码讲解
HANDLE WINAPI GetStdHandle( //获得输入、输出/错误的屏幕缓冲区的句柄。__in DWORD nStdHandle );
而其参数nStdHandle的值可以为下面几种类型的一种:STD_INPUT_HANDLE标准输入的句柄STD_OUTPUT_HANDLE标准输出的句柄STD_ERROR_HANDLE标准错误的句柄
void game() //游戏相关操作
先不要管main函数里的代码,我们先逐个分析一下函数
先来看看gotoxy()接受两个参数,代码如下
void gotoxy(int x,int y) //移动坐标
{
COORD coord;
coord.X=x;
coord.Y=y;
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord );
if(c==Esc)
{
gotoxy(0,24);
5
回复
1楼
2011-12-07 15:46
举报|
我也说一句
未来未来
追忆曾经_
团子家族
10
break;
}
switch(c)
{
case Up: //向上走
if(map[x-1][y]!=Wall)
{
paint(x,y);
x--;
}
break;
case Down: //向下走
map[i][Width+1]=Wall;
}
for(j=0;j<=Width+1;j++) //边界处理
{
map[0][j]=Wall;

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语言编写迷宫

C语言编写迷宫

迷宫源代码:#include <stdio.h>#include <slib.h>#include <malloc.h>#include <conio.h>#include <dos.h>#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0#define F9 0x43#define Esc 0x1b#define Del 0x53#define Home 0x47#define End 0x4f#define Space 0x20#define Up 0x48#define Down 0x50#define Left 0x4b#define Right 0x4d#define Enter 0x0d#define F2 0x3c#define F3 0x3d#define STACK_INIT_SIZE 200 #define STACKINCREMENT 10 typedef int Boolean;typedef int Status;typedef suct {int x;int y;} PosType;typedef suct {int ord;PosType seat;int di;} SElemType;typedef suct {int ;int foot;int mark;} MazeType;typedef suct {SElemType *base; SElemType *top;int stacksize;} Stack;int Maze[20][30];MazeType maze[20][30];PosType StartPlace;PosType EndPlace;int count;int m,n;Boolean b_start=FALSE,b_end=FALSE;void CreatMaze(void);Status SaveMaze(char *filename);Status LoadMaze(char *filename);void Error(char *message);Status InitStack(Stack *s);Status DesoyStack(Stack *s);Status ClearStack(Stack *s);Boolean StackEmpty(Stack *s);int StackLength(Stack *s);Status Push(Stack *s,SElemType e);SElemType Pop(Stack *s,SElemType e);Status GetTop(Stack *s,SElemType *e);Status StackTraverse(Stack *s,Status (* visit)(SElemType *se)); Boolean Pass(PosType curpos);void MarkPrint(PosType seat);void FootPrint(PosType curpos);PosType NextPos(PosType seat,int di);Status MazePath(PosType start,PosType end);void CreatMaze(void)/* Form the maze. */{void Error(char *message);Status SaveMaze(char *filename);Status LoadMaze(char *filename);int i,j;int x,y;char c;char savename[12],loadname[12];Boolean flag=FALSE,load=FALSE;clrscr();printf("Menu:\n\n");printf("1.Load Mazefile:(*.dd)\n\n");printf("2.Input Maze:\n\n");printf("Input your choice: ");do{c=getch();switch(c){case ''''''''''''''''''''''''''''''''1'''''''''''''''''''''''''''''''': putch(''''''''''''''''''''''''''''''''1''''''''''''''''''''''''''''''''); break;case ''''''''''''''''''''''''''''''''2'''''''''''''''''''''''''''''''': putch(''''''''''''''''''''''''''''''''2''''''''''''''''''''''''''''''''); break;case Esc: sleep(1); exit(1);default: break;}}while(c!=''''''''''''''''''''''''''''''''1''''''''''''''''''''''''''''''''&&c!=''''''''''''''''''''''''''''''''2'''''''''''''''''''''''''''''''') ; if(c==''''''''''''''''''''''''''''''''1''''''''''''''''''''''''''''''''){printf("\n\nLoadName: ");scanf("%s",loadname);if(LoadMaze(loadname)){sleep(1); load=TRUE;}else { gotoxy(1,9); printf("Load fail! "); }}if(!load){printf("\nInput the maze''''''''''''''''''''''''''''''''s size:\n");printf("\nInput Length :\n");scanf("%d",&m);printf("\nInput Width :\n");scanf("%d",&n);if(m<4||n<4) Error("Input");if(m>30||n>20) Error("Maze too large");for(i=0;i<30;i )for(j=0;j<20;j )Maze[j][i]=2;StartPlace.x=0;StartPlace.y=0;EndPlace.x=0;EndPlace.y=0;clrscr();BR> for(i=1;i<=n;i ){for(j=1;j<=m;j ){printf(" #");Maze[i-1][j-1]=0;}printf("\n");}}gotoxy(65,5);printf("''''''''''''''''''''''''''''''''#'''''''''''''''''''''''''''''''':Wall");gotoxy(65,7);printf("Start:Home");gotoxy(65,9);printf("End:End");gotoxy(65,11);printf("Delete Wall:Del");gotoxy(65,13);printf("Enter Wall:Enter");gotoxy(65,15);printf("Save Maze:F2");gotoxy(65,17);printf("Complete:F9");gotoxy(65,19);printf("Exit:Esc");gotoxy(4,3);x=4;y=3;do{c=getch();switch(c){case Up: if(y>3) { y--; gotoxy(x,y); }break;case Down: if(y<n) { y ; gotoxy(x,y); }break;case Left: if(x>4) { x-=2; gotoxy(x,y); }break;case Right: if(x<2*m-2) { x =2; gotoxy(x,y); }break;case Del: if(y-2==StartPlace.y&&x/2-1==StartPlace.x) b_start=FALSE; if(y-2==EndPlace.y&&x/2-1==EndPlace.x) b_end=FALSE;putch('''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''''''); Maze[y-2][x/2-1]=1; gotoxy(x,y); break;case Enter: if(y-2==StartPlace.y&&x/2-1==StartPlace.x) break;if(y-2==EndPlace.y&&x/2-1==EndPlace.x) break;putch(''''''''''''''''''''''''''''''''#''''''''''''''''''''''''''''''''); Maze[y-2][x/2-1]=0; gotoxy(x,y); break;case Home: if(Maze[y-2][x/2-1]&&!b_start){StartPlace.x=x/2-1;StartPlace.y=y-2;putch(''''''''''''''''''''''''''''''''S'''''''''''''''''''''''''''''''');gotoxy(x,y);b_start=TRUE;}break;case End: if(Maze[y-2][x/2-1]&&!b_end){EndPlace.x=x/2-1;EndPlace.y=y-2;putch(''''''''''''''''''''''''''''''''E'''''''''''''''''''''''''''''''');gotoxy(x,y);b_end=TRUE;}break;case Esc: gotoxy(2,22); printf("exit"); sleep(1); exit(1); case F9: if(b_start&&b_end) flag=TRUE; break;case F2: gotoxy(2,22);printf("Savename:");scanf("%s",savename);gotoxy(2,22);if(SaveMaze(savename)) printf("Save OK! ");else printf("Save fail! ");sleep(1);gotoxy(2,22);printf(" ");gotoxy(x,y);break;default: break;}}while(!flag);for(i=0;i<30;i )for(j=0;j<20;j ){maze[j][i].=Maze[j][i];maze[j][i].mark=0;maze[j][i].foot=0;}}Status LoadMaze(char *file)/* The maze has been loaded. */{FILE *fp;char *buffer;char ch;int i=0,j,k;Boolean len=FALSE,wid=FALSE;if((fp=fopen(file,"r"))==NULL)return ERROR;buffer=(char *)malloc(600*sizeof(char));ch=fgetc(fp);while(ch!=EOF){buffer[i]=ch;i ;ch=fgetc(fp);}m=30;n=20;for(i=0;i<600;i ){j=i/30; k=i0;if(buffer[i]==''''''''''''''''''''''''''''''''2''''''''''''''''''''''''''''''''&&!len){ m=i; len=TRUE; }if(k==0&&buffer[i]==''''''''''''''''''''''''''''''''2''''''''''''''''''''''''''''''''&&!wid){ n=j; wid=TRUE; } switch(buffer[i]){case ''''''''''''''''''''''''''''''''0'''''''''''''''''''''''''''''''': Maze[j][k]=0; break;case ''''''''''''''''''''''''''''''''1'''''''''''''''''''''''''''''''': Maze[j][k]=1; break;case ''''''''''''''''''''''''''''''''2'''''''''''''''''''''''''''''''': Maze[j][k]=2; break;case ''''''''''''''''''''''''''''''''3'''''''''''''''''''''''''''''''': Maze[j][k]=1;StartPlace.x=k;StartPlace.y=j;b_start=TRUE;break;case ''''''''''''''''''''''''''''''''4'''''''''''''''''''''''''''''''': Maze[j][k]=1;EndPlace.x=k;EndPlace.y=j;b_end=TRUE;break;default : break;}}fclose(fp);clrscr();for(i=0;i<30;i )for(j=0;j<20;j ){maze[j][i].=Maze[j][i];maze[j][i].foot=0;maze[j][i].mark=0;if(Maze[j][i]==0){gotoxy(2*i 2,j 2);putch(''''''''''''''''''''''''''''''''#'''''''''''''''''''''''''''''''');}}gotoxy(2*StartPlace.x 2,StartPlace.y 2);putch(''''''''''''''''''''''''''''''''S'''''''''''''''''''''''''''''''');gotoxy(2*EndPlace.x 2,EndPlace.y 2);putch(''''''''''''''''''''''''''''''''E'''''''''''''''''''''''''''''''');return OK;}Status SaveMaze(char *filename)/* The maze has been saved. */{FILE *fp;char *buffer;int i,j,k;fp=fopen(filename,"wb");buffer=(char *)malloc(600*sizeof(char));for(i=0;i<600;i ){j=i/30; k=i0;switch(Maze[j][k]){case 0: buffer[i]=''''''''''''''''''''''''''''''''0''''''''''''''''''''''''''''''''; break;case 1: buffer[i]=''''''''''''''''''''''''''''''''1''''''''''''''''''''''''''''''''; break;case 2: buffer[i]=''''''''''''''''''''''''''''''''2''''''''''''''''''''''''''''''''; break;default : Error("Write"); break;}if(k==StartPlace.x&&j==StartPlace.y) buffer[i]=''''''''''''''''''''''''''''''''3''''''''''''''''''''''''''''''''; if(k==EndPlace.x&&j==EndPlace.y) buffer[i]=''''''''''''''''''''''''''''''''4''''''''''''''''''''''''''''''''; }fwrite(buffer,600,1,fp);free(buffer);fclose(fp);return OK;}void Error(char *message){clrscr();fprintf(serr,"Error:%s\n",message);exit(1);} /* Error */Status InitStack(Stack *s)/* The stack s has been created and is initialized to be empty. */{s->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!s->base) Error("Overflow");s->top=s->base;s->stacksize=STACK_INIT_SIZE;return OK;} /* InitStack */Status DesoyStack(Stack *s)/* The stack s has been desoyed. */{s->top=NULL;s->stacksize=0;free(s->base);s->base=NULL;return OK;} /* DesoyStack */Status ClearStack(Stack *s)/* The stack has been clear to be maximum. */{s->top=s->base;s->stacksize=STACK_INIT_SIZE;return OK;} /* ClearStack */Boolean StackEmpty(Stack *s)/* Check if the stack s is empty. */{if(s->top==s->base) return TRUE;else return FALSE;} /* StackEmpty */int StackLength(Stack *s)/* Gain the length of the stack s. */{if(s->top>s->base) return (int)(s->top-s->base);else return 0;} /* StackLength */Status Push(Stack *s,SElemType e)/* The element e has been pushed into the stack s. */{if(s->top-s->base>=s->stacksize){s->base=(SElemType *)realloc(s->base,(s->stacksize STACKINCREMENT)*sizeof(SElemType));if(!s->base) Error("Overflow");s->top=s->base s->stacksize;s->stacksize =STACKINCREMENT;}*s->top =e;return OK;} /* Push */SElemType Pop(Stack *s,SElemType e)/* The element e has been removed from the stack s. */{if(s->top==s->base) Error("Pop");e=*--s->top;return e;} /* Pop */Status GetTop(Stack *s,SElemType *e)/* The element e has got to the top of the stack s.*/{if(s->top==s->base) Error("GetTop");*e=*(s->top-1);return OK;} /* GetTop *//* Traverse the stack s using ''''''''''''''''''''''''''''''''visiting'''''''''''''''''''''''''''''''' function. */ /* Status StackTraverse(Stack *s,Status (* visit)(SElemType *se)){SElemType p;int result;if(s->top==s->base) return ERROR;p=s->base;while(!(p==s->top)){result=(*visit)(p);p ;}return OK;} */Boolean Pass(PosType curpos)/* Check if the current position can be passed. */{if(maze[curpos.x][curpos.y].==1&&maze[curpos.x][curpos.y].foot==0&&maze[curpos.x][curpos.y].mark==0) return TRUE;else return FALSE;} /* Pass */void MarkPrint(PosType seat)/* Mark the position seat. */{maze[seat.x][seat.y].mark=-1;/* Marking ''''''''''''''''''''''''''''''''-1'''''''''''''''''''''''''''''''' symbolize the current position cannot be put. */} /* MarkPrint */void FootPrint(PosType curpos)/* The foot of the curpos of the maze has been set''''''''''''''''''''''''''''''''ue''''''''''''''''''''''''''''''''. */{maze[curpos.x][curpos.y].foot=1;} /* FootPrint */PosType NextPos(PosType seat,int di){switch(di){case 1: seat.y ; return seat; /* Eastward */case 2: seat.x ; return seat; /* Southward */case 3: seat.y--; return seat; /* Westward */case 4: seat.x--; return seat; /* Northward */default: seat.x=0; seat.y=0; return seat;}} /* NextPos *//* The key to the program. *//* Pre: The maze array & the startplace & the endplace.Post: Find the one averse of the maze and perform the mazepath.Uses: The ADT stack class.*/Status MazePath(PosType start,PosType end){PosType curpos;int curstep;SElemType e;Stack *s,stack;stack.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!stack.base) Error("Overflow");stack.top=stack.base;stack.stacksize=STACK_INIT_SIZE;s=&stack;curpos=start;cursteprintf("\n");<'0''''''''''''''''''''''''''''''''; break;case 1: buffer[i]=''''''''''''''''''''''''''''''''1''''''''''''''''''''''''''''''''; break;case 2: buffer[i]=''''''''''''''''''''''''''''''''2''''''''''''''''''''''''''''''''; break;default : Error("Write"); break;}if(k==StartPlace.x&&j==StartPlace.y) buffer[i]=''''''''''''''''''''''''''''''''3''''''''''''''''''''''''''''''''; if(k==EndPlace.x&&j==EndPlace.y) buffer[i]=''''''''''''''''''''''''''''''''4''''''''''''''''''''''''''''''''; }fwrite(buffer,600,1,fp);free(buffer);fclose(fp);return OK;}void Error(char *message){clrscr();fprintf(serr,"Error:%s\n",message);exit(1);} /* Error */Status InitStack(Stack *s)/* The stack s has been created and is initialized to be empty. */{s->base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!s->base) Error("Overflow");s->top=s->base;s->stacksize=STACK_INIT_SIZE;return OK;} /* InitStack */Status DesoyStack(Stack *s)/* The stack s has been desoyed. */{s->top=NULL;s->stacksize=0;free(s->base);s->base=NULL;return OK;} /* DesoyStack */Status ClearStack(Stack *s)/* The stack has been clear to be maximum. */{s->top=s->base;s->stacksize=STACK_INIT_SIZE;return OK;} /* ClearStack */Boolean StackEmpty(Stack *s)/* Check if the stack s is empty. */{if(s->top==s->base) return TRUE;else return FALSE;} /* StackEmpty */int StackLength(Stack *s)/* Gain the length of the stack s. */{if(s->top>s->base) return (int)(s->top-s->base);else return 0;} /* StackLength */Status Push(Stack *s,SElemType e)/* The element e has been pushed into the stack s. */ {if(s->top-s->base>=s->stacksize){s->base=(SElemType *)realloc(s->base,(s->stacksize STACKINCREMENT)*sizeof(SElemType)); if(!s->base) Error("Overflow");s->top=s->base s->stacksize;s->stacksize =STACKINCREMENT;}*s->top =e;return OK;} /* Push */SElemType Pop(Stack *s,SElemType e)/* The element e has been removed from the stack s. */ {if(s->top==s->base) Error("Pop");e=*--s->top;return e;} /* Pop */Status GetTop(Stack *s,SElemType *e)/* The element e has got to the top of the stack s.*/{if(s->top==s->base) Error("GetTop");*e=*(s->top-1);return OK;} /* GetTop *//* Traverse the stack s using ''''''''''''''''''''''''''''''''visiting'''''''''''''''''''''''''''''''' function. *//* Status StackTraverse(Stack *s,Status (* visit)(SElemType *se)){SElemType p;int result;if(s->top==s->base) return ERROR;p=s->base;while(!(p==s->top)){result=(*visit)(p);p ;}return OK;} */Boolean Pass(PosType curpos)/* Check if the current position can be passed. */{if(maze[curpos.x][curpos.y].==1&&maze[curpos.x][curpos.y].foot==0&&maze[curpos.x][curpos.y].mark==0) return TRUE;else return FALSE;} /* Pass */void MarkPrint(PosType seat)/* Mark the position seat. */{maze[seat.x][seat.y].mark=-1;/* Marking ''''''''''''''''''''''''''''''''-1'''''''''''''''''''''''''''''''' symbolize the current position cannot be put. */} /* MarkPrint */void FootPrint(PosType curpos)/* The foot of the curpos of the maze has been set''''''''''''''''''''''''''''''''ue''''''''''''''''''''''''''''''''. */{maze[curpos.x][curpos.y].foot=1;} /* FootPrint */PosType NextPos(PosType seat,int di){switch(di){case 1: seat.y ; return seat; /* Eastward */case 2: seat.x ; return seat; /* Southward */case 3: seat.y--; return seat; /* Westward */case 4: seat.x--; return seat; /* Northward */default: seat.x=0; seat.y=0; return seat;}} /* NextPos *//* The key to the program. *//* Pre: The maze array & the startplace & the endplace.Post: Find the one averse of the maze and perform the mazepath.Uses: The ADT stack class.*/Status MazePath(PosType start,PosType end){PosType curpos;int curstep;SElemType e;Stack *s,stack;stack.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!stack.base) Error("Overflow");stack.top=stack.base;stack.stacksize=STACK_INIT_SIZE;s=&stack;curpos=start;curstep=1;do{if(Pass(curpos)){FootPrint(curpos);e.ord=curstep; e.seat=curpos; e.di=1;gotoxy((curpos.y 1)*2,curpos.x 2);putch(''''''''''''''''''''''''''''''''@'''''''''''''''''''''''''''''''');delay(8000); /* pospone time. */Push(s,e);if(curpos.x==end.x&&curpos.y==end.y) /* Proceed recursively. */{DesoyStack(s);return TRUE;}curpos=NextPos(curpos,1); /* Try next position. */curstep ;}else{if(!StackEmpty(s)){e=Pop(s,e); /* Removed e from s. */while(e.di==4&&!StackEmpty(s)) /* Four directions have been checked and s is not empty. */{MarkPrint(e.seat);gotoxy((e.seat.y 1)*2,e.seat.x 2);putch(''''''''''''''''''''''''''''''''@'''''''''''''''''''''''''''''''');delay(8000); /* Pospone time. */gotoxy((e.seat.y 1)*2,e.seat.x 2);putch('''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''');e=Pop(s,e); /* Remove e from s. */curstep--;}if(e.di<4) /* The current position hasnot been checked. */{e.di ;Push(s,e); /* Insert e into s. */curpos=NextPos(e.seat,e.di); /* Try next position. */}}}}while(!StackEmpty(s));DesoyStack(s);return FALSE;} /* MazePath */void main(){PosType start,end;CreatMaze();start.x=StartPlace.y;start.y=StartPlace.x;end.x=EndPlace.y;end.y=EndPlace.x;if(MazePath(start,end)){gotoxy(2,22);printf("Path found\n");}else{gotoxy(2,22);printf("Path not found\n");}。

迷宫(direction)C语言代码

迷宫(direction)C语言代码
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为障碍
voidpush_seq(PSeqStackpastack,DataTypex ) {
if(pastack->t >= MAXNUM - 1 )
printf( "Overflow! \n" );
else {
pastack->t++;
pastack->s[pastack->t] = x;
}
}
/* 删除栈顶元素 */
element =top_seq(st);
pop_seq(st);
i=element.x; j =element.y;
for (k =element.d+ 1; k <= 3; k++) { /* 依次试探每个方向 */
g =i+ direction[k][0];h = j + direction[k][1];
lj[top].x=1;
lj[top].y=1;
migong[1][1]=-1;
find=0;d=-1;
while(top>-1){
if(lj[top].x==8&&lj[top].y==8)
{
printf("迷宫路径如下:\n");

迷宫问题实验报告(c++编写,附源代码)

迷宫问题实验报告(c++编写,附源代码)

迷宫问题实验报告级班年月日姓名学号_1.实验题目以一个mXn的长方阵表示迷宫,0和1分别表示迷宫中的通路和障碍。

设计一个程序,对任意设定的迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。

2.需求分析本程序使用VC编写,实现设定迷宫或自动生成迷宫长方阵表的功能,并且求出一条从指定入口到指定出口的通路,或得出没有通路的结论。

①输入的形式和输入值的范围:A.输入指定的数字,以此选择迷宫的创建方式,分为手动创建迷宫和自动创建迷宫B. 输入迷宫阵表的行数和列数,行数和列数不超过40行C. 手动创建迷宫时,需要输入迷宫结点的通畅和障碍情况,0和1分别表示迷宫中的通路和障碍。

②输出的形式:输出没有通路的结论,或者输出一个长方阵表,其中路径的每个结点都输出→、↓、←、↑之一,表示从当前结点到下一个结点的方向。

③程序所能达到的功能:实现设定迷宫或自动生成迷宫长方阵表的功能,并且求出一条从指定入口到指定出口的通路(迷宫的入口指定为坐标为(1,1)的结点,迷宫的出口指定为坐标为(迷宫最大行,迷宫最大列)的结点),或得出没有通路的结论。

④测试数据:输入数据:A.出现选择生成迷宫方式的菜单时,输入1(即手动输入数据,生成迷宫);B.输入迷宫的行数和列数,行数输入3,列数输入3;C.输入每个迷宫结点的信息:0 0 11 0 01 0 0输出结果:→↓ 11 →↓1 0 03.概要设计1)为了实现上述程序功能,需要定义迷宫的抽象数据类型:typedef struct//定义迷宫结构体{int maze_array[maxsize][maxsize];//二维数组存放迷宫每个点是通畅或阻隔的信息int max_x,max_y; //迷宫的行数和和列数}2)定义迷宫中点的指针的结构体typedef struct point{int vex_x,vex_y; //结点的横纵坐标(横坐标为行号,纵坐标为列号)struct point *ahead;//在链栈中,指向前一个结点的指针int direction; //从当前结点走至下一个结点的方向};基本操作:A. Maze creat_manual()初始条件:无操作结果:手动创建一个迷宫。

c语言迷宫代码

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语言实现迷宫求解完美源代码

用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');}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

o p e n g l D迷宫C实现源代码Document serial number【LGGKGB-LGG98YT-LGGT8CB-LGUT-#include ""#include <>#include <>#include <GL/>#include <>#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;player_b = 3*player_b/4 + player_t/4;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;player_b = 3*player_b/4 + player_t/4;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();}。

相关文档
最新文档