openglD迷宫C实现源代码
迷宫 C++源代码
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语言代码讲解
而其参数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#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 <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语言代码
};
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++编写,附源代码)
迷宫问题实验报告级班年月日姓名学号_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#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语言实现迷宫求解完美源代码#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语言实现的迷宫算法示例
基于C语⾔实现的迷宫算法⽰例本⽂实例讲述了基于C语⾔实现的迷宫算法。
分享给⼤家供⼤家参考,具体如下:利⽤c语⾔实现迷宫算法,环境是vc++6.0.#include<stdio.h>#include<time.h>#include<cstdlib>int visit(int,int);void setmaze();int maze[11][11]={{0,0,2,2,2,2,2,2,2,2},{2,0,2,2,0,2,0,2,0,2},{2,0,2,0,0,0,0,0,0,2},{2,0,2,2,2,0,2,0,0,2},{2,0,0,0,0,0,2,2,0,2},{2,2,0,2,2,0,2,2,0,2},{2,2,2,0,0,0,0,0,0,2},{2,0,2,0,2,0,2,2,0,2},{2,0,0,0,0,2,0,2,0,0},{2,2,2,2,2,2,2,2,2,2}};int startI,startJ; //定义⼊⼝变量int endI,endJ; //定义出⼝变量int success=0; //定义返回变量int p;void setStart() // 设置⼊⼝{printf("请设置迷宫⼊⼝(i,j):");scanf("%d,%d",&startI,&startJ);}void setEnd() // 设置出⼝{printf("请设置迷宫出⼝(i,j):");scanf("%d,%d",&endI,&endJ);}void setmaze() //设置迷宫图{int i,j,a,p;for(i=0;i<10;i++)for(j=0;j<10;j++){p=rand()%2;if(p==0) a=0;else a=2;maze[i][j]=a;}}void DisplayMaze() //打印迷宫{int i,j;for(i=0;i<10;i++){printf(" ");for(j=0;j<10;j++)if(maze[i][j]==2) printf("##"); //打印墙壁else printf(" "); //打印路径printf("/n");}}void Maze_PS() //输出迷宫路径{int i,j;if(visit(startI,startJ)==0) //寻找路径printf("/n没有找到出⼝!/n");else{maze[startI][startJ]=8;//设置⼊⼝标志maze[endI][endJ]=9;//设置出⼝标志printf("/n显⽰路径:/n");for(i=0;i<10;i++){for(j=0;j<10;j++){if(maze[i][j]==8) printf("☆");//标志⼊⼝else if(maze[i][j]==9) printf("○");//标志出⼝else if(maze[i][j]==2) printf("##"); //表⽰墙壁else if(maze[i][j]==1) printf(" >"); //表⽰路径else printf(" "); //通路}printf("/n");}}}int visit(int i,int j) //寻找迷宫路径函数,找到路径返回1,找不到路径返回0{maze[i][j]=1;if((i==endI)&&(j==endJ)) success=1; //找到出⼝,返回值success为1if((success!=1)&&(maze[i][j+1]==0)) visit(i,j+1); //检测右⾯通路,若通,向右移动 if((success!=1)&&(maze[i+1][j]==0)) visit(i+1,j); //检测下⾯通路,若通,向下移动 if((success!=1)&&(maze[i][j-1]==0)) visit(i,j-1); //检测左⾯通路,若通,向左移动 if((success!=1)&&(maze[i-1][j]==0)) visit(i-1,j); //检测上⾯通路,若通,向上移动 if(success!=1) maze[i][j]=0; //退回,⾃⾝标为0return success;}main(void) //主函数{int c1,c2;for(c2=1;c2==1;){srand(time(0));printf("显⽰迷宫:/n");for(c1=1;c1==1;){DisplayMaze();printf("按'1'输出新迷宫,'2'开始求解路径:/n");scanf("%d",&c1);rewind(stdin);//清除输⼊缓冲区if(c1==1) setmaze() ;}if(c1!=1&&c1!=2) {printf("Error!!/n");break;}setStart();setEnd();Maze_PS();printf("Continue?(1 to continue,2 to exit.1)");scanf("%d",&c2);if(c2==1) setmaze();else break;}system("pause");}希望本⽂所述对⼤家C语⾔程序设计有所帮助。
迷宫c语言
迷宫c语言#include<stdio.h>#include<conio.h>#include<windows.h>#include<time.h>#定义权31//迷宫的高度必须是奇数#定义的高度25//迷宫的宽度必须是奇数#定义的高度1#定义的高度0#定义的高度3#定义的高度5#定义的宽度1#定义的宽度2#定义的宽度3#定义的宽度4intmap[height+2][width+2];voidgotoxy(intx,inty)//移动坐标{合作社;库德。
x=x;库德。
y=y;setconsolecursorposition(getstdhandle(std_output_handle),coord);}Void hidden()//隐藏光标{handlehout=getstdhandle(std_output_handle);console_cursor_infocci;GetConsoleUrsorInfo(hout和cci);cci。
bvisible=0;//指定1显示,指定0隐藏设置控制台或信息(hout,&CCI);}voidcreate(intx,inty)//随机生成迷宫{intc[4][2]={0,1,1,0,0,-1,-1,0};//四个方向inti,J,t//分解(I=0;I<4;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;i<4;i++)如果(映射[x+2*c[i][0][y+2*c[i][1]]==墙){map[x+c[i][0]][y+c[i][1]]=road;create(x+2*c[i][0],y+2*c[i][1]);}}intget_uokey()//接收密钥{charc;while(C=getch()){if(c==27)returnesc;//escif(c!=-32)continue;c=getch();如果(c==72)返回;//上if(C==80)returndown//下if(C==75)returneft//左if(c==77)returnright;//右}return0;}虚空绘制(intx,inty)//绘制迷宫{gotoxy(2*y-2,x-1);switch(map[x][y]){casestart:Printf(“in”);中断;//图纸输入框结束:printf("出");break;//画出口casewall:printf(“※”);中断;//画墙凯斯路:printf("");break;//画路}}虚空游戏(){intx=2,y=1;//玩家当前位置,刚开始在入口处intc;//接收键(1时){gotoxy(2*y-2,x-1);printf(“☆“”;//如果(map[x][y]==end)//判断是否到达出口,则绘制玩家的当前位置{gotoxy(30,24);Printf(“到达终点时,按任意键结束”);getch();打破;}c=get_key();if(c==esc){gotoxy(0,24);打破;}开关(c){caseup://向上走if(map[x-1][y]!=wall)。
opengl 3D迷宫 C 实现 源代码精编版
#include "stdafx.h"#include <stdio.h>#include <stdlib.h>#include <GL/glut.h>#include <math.h>#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);//ʹÎÆÀí²»±äÐÎ}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);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(-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);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(-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{}}//ÊÍ·Å°´¼üºó¾Í½øÈë¿ÕÏÐ״̬£¬Èç¹û¿ÕÏÐ״̬²»Ò»Ö±Öظ´»æͼ£¬¾Í»á»-ÃæÍ£ÖÍ¡£´Î·½·¨È±µãÊÇ¿ªÏúºÜ´ó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();}。
基于C语言实现简单的走迷宫游戏
基于C语⾔实现简单的⾛迷宫游戏本⽂实例讲述了C语⾔实现简单的⾛迷宫游戏的⽅法,代码完整,便于读者理解。
学数据结构时⽤“栈”写的⼀个⾛迷宫程序,实际上⽤到双向队列,⽅便在运⾏完毕后输出经过的点。
#include <cstdio>#include <deque>#include <windows.h>using namespace std;class node{public:int x,y;int lastOpt;};deque<node> sta;int x,y;int endx,endy;int mapW,mapH;int steps;int xopt[5]= {0,0,1,0,-1};int yopt[5]= {0,1,0,-1,0};int map[100][100]={};void init(){x = 1;y = 1;endx = 1;endy = 9;mapH = 10;mapW = 10;for(int i=0; i<=mapH; i++)for(int j=0; j<=mapW; j++){if(i==0 ||j==0 ||i==mapH||j==mapW)map[i][j]=-1;}steps=0;map[1][2]=-1;map[2][2]=-1;map[3][2]=-1;map[4][2]=-1;map[6][2]=-1;map[7][2]=-1;map[8][2]=-1;map[9][2]=-1;map[9][3]=-1;map[8][3]=-1;map[1][4]=-1;map[3][4]=-1;map[4][4]=-1;map[5][4]=-1;map[6][4]=-1;map[7][4]=-1;map[1][6]=-1;map[2][6]=-1;map[3][6]=-1;map[4][6]=-1;map[5][6]=-1;map[6][6]=-1;map[7][6]=-1;map[8][6]=-1;map[8][7]=-1;map[8][8]=-1;map[7][8]=-1;map[6][8]=-1;map[5][8]=-1;map[4][8]=-1;map[2][8]=-1;map[1][8]=-1;map[endx][endy]=5;}void dis(){system("cls");int ori = map[x][y];map[x][y]=1;for(int i=0; i<=mapH; ++i){for(int j=0; j<=mapW; ++j){if(map[i][j]==0)printf(" ");else if(map[i][j]==-1)printf(" #");else if(map[i][j]==1)printf(" @");else if(map[i][j]==2)printf(" .");else if(map[i][j]==5)printf(" !");}cout<<i<<endl;}for(int j=0; j<=mapW; ++j)cout<<j<<" ";printf("\n\n > steps:%d Exit:(%d,%d)\n",steps,endx,endy);map[x][y] = ori;}int can(int n){if(map[x+xopt[n]][y+yopt[n]] == 0 || map[x+xopt[n]][y+yopt[n]] == 5) return 1;return 0;}void visit(int n){map[x][y]=2;x+=xopt[n];y+=yopt[n];node tem;tem.x = x;tem.y = y;stOpt = n;sta.push_back(tem);steps++;}int main(){init();node tem;while( x != endx || y!=endy){int cans = 0;for(int i=1; i<=4; i++){if(can(i)){cans = 1;visit(i);break;}}if(!cans){if(!sta.empty()){tem = sta.back();map[tem.x][tem.y]=0;}else{map[x][y]=2;x+=xopt[stOpt];x+=yopt[stOpt];dis();break;}}dis();Sleep(500);}if(x==endx && y == endy)cout<<"\n > i am finished....\n";elsecout<<"\n > i am finished...but i can't find the right way\n";return 0;}效果图:以上就是本⽂的全部内容,希望对⼤家学习C语⾔有所帮助。
(完整word版)数据结构C语言迷宫求解问题(有要求和源代码)
1、迷宫求解设计一个迷宫求解程序,要求如下:✓以M × N表示长方阵表示迷宫,求出一条从入口到出口的通路,或得出没有通路的结论。
✓能任意设定的迷宫✓(选作)如果有通路,列出所有通路提示:✓以一个二维数组来表示迷宫,0和1分别表示迷宫中的通路和障碍,如下图迷宫数据为:1111111111 Array 100100010110010001011000011001101110000110001000011010001001101110110111000000011111111111入口位置:1 1出口位置:8 8✓探索过程可采用如下算法,设定当前位置的初值为入口位置;do {若当前位置可通,则{将当前位置插入栈顶;若该位置是出口位置,则结束;否则切换当前位置的东邻方块为新的当前位置;}否则,{若栈不空且栈顶位置尚有其他方向未经探索,则设定新的当前位置为沿顺时针方向旋转找到的栈顶位置的下一相邻块;若栈不空但栈顶位置的四周均不可通,则{删去栈顶位置;//从路径中删去该通道块若栈不空,则重新测试新的栈顶位置,直至找到一个可通的相邻块出栈至栈空;}}}while (栈不空);#include<stdio.h>#include<string.h>#define MaxSize 32int a[30][30];int b[30][30];int m,n;typedef struct{int i;int j;int di;}Box;typedef struct{Box data[MaxSize];int top;}StackType;bool sereach(int X,int Y,int X1,int Y1);void main(){int X,Y,Y1,X1;memset(a,0,sizeof(a));memset(b,0,sizeof(b));// for()printf("请输入迷宫的长度和宽度\n");while(~scanf("%d%d",&m,&n)){printf("请输入迷宫(0表示空地,1表示围墙)\n");for(int i=0;i<n;i++){for(int j=0;j<m;j++){scanf("%d",&a[i][j]);if(a[i][j]==1)b[i][j]=-1;}}printf("请输入迷宫起点的行号和列号\n");scanf("%d%d",&X,&Y);printf("请输入迷宫终点的行号和列号\n");scanf("%d%d",&X1,&Y1);if(!sereach(X,Y,X1,Y1))printf("该迷宫没有解!\n");printf("请输入迷宫的长度和宽度\n");}// return 0;}bool sereach(int X,int Y,int X1,int Y1){StackType st;int i,j,di,find;st.top=-1;while(a[X][Y]!=0){printf("迷宫起点的行号和列号有错,请重新输入\n");scanf("%d%d",&X,&Y);}if(a[X][Y]==0)b[X][Y]=-1;while(a[X1][Y1]!=0){printf("迷宫终点的行号和列号有错,请重新输入\n");scanf("%d%d",&X1,&Y1);}st.top++;st.data[st.top].i=X;st.data[st.top].j=Y;st.data[st.top].di=-1;do{find=0;i=st.data[st.top].i;j=st.data[st.top].j;di=st.data[st.top].di;while(di<4&&find==0){di++;switch(di){case 0:i=st.data[st.top].i-1;j=st.data[st.top].j;break;case 1:i=st.data[st.top].i;j=st.data[st.top].j+1;break;case 2:i=st.data[st.top].i+1;j=st.data[st.top].j;break;case 3:i=st.data[st.top].i;j=st.data[st.top].j-1;break;}if(b[i][j]==0&&i>=0&&i<n&&j>=0&&j<m)find=1;}if(find == 1){st.data[st.top].di=di;st.top++;st.data[st.top].i=i;s t.data[st.top].j=j;st.data[st.top].di=-1;b[i][j]=-1;find=0;}else{b[st.data[st.top].i][st.data[st.top].j]=0;st.top--;}if(i==X1&&j==Y1){printf("迷宫路径如下:\n");for(int k=0;k<=st.top;k++){printf("%d,%d\t",st.data[k].i,st.data[k].j);if((k+1)%6==0)printf("\n");}printf("\n");。
C语的迷宫小游戏_源代码
C语的迷宫小游戏_源代码编辑整理:尊敬的读者朋友们:这里是精品文档编辑中心,本文档内容是由我和我的同事精心编辑整理后发布的,发布之前我们对文中内容进行仔细校对,但是难免会有疏漏的地方,但是任然希望(C语的迷宫小游戏_源代码)的内容能够给您的工作和学习带来便利。
同时也真诚的希望收到您的建议和反馈,这将是我们进步的源泉,前进的动力。
本文可编辑可修改,如果觉得对您有帮助请收藏以便随时查阅,最后祝您生活愉快业绩进步,以下为C语的迷宫小游戏_源代码的全部内容。
C语言编写的迷宫游戏源代码#include 〈graphics。
h>#include 〈stdlib.h>#include 〈stdio.h〉#include <conio。
h〉#include <dos。
h〉#define N 20/*迷宫的大小,可改变*/int oldmap[N][N];/*递归用的数组,用全局变量节约时间*/int yes=0;/*yes是判断是否找到路的标志,1找到,0没找到*/int way[100][2],wayn=0;/*way数组是显示路线用的,wayn是统计走了几个格子*/void Init(void);/*图形初始化*/void Close(void);/*图形关闭*/void DrawPeople(int *x,int *y,int n);/*画人工探索物图*/void PeopleFind(int (*x)[N]);/*人工探索*/void WayCopy(int (*x)[N],int (*y)[N]);/*为了8个方向的递归,把旧迷宫图拷贝给新数组*/int FindWay(int (*x)[N],int i,int j);/*自动探索函数*/void MapRand(int (*x)[N]);/*随机生成迷宫函数*/void PrMap(int (*x)[N]);/*输出迷宫图函数*/void Result(void);/*输出结果处理*/void Find(void);/*成功处理*/void NotFind(void);/*失败处理*/void main(void)/*主函数*/{int map[N][N]; /*迷宫数组*/char ch;clrscr();printf("\n Please select hand(1) else auto\n”);/*选择探索方式*/ scanf("%c",&ch);Init(); /*初始化*/MapRand(map);/*生成迷宫*/PrMap(map);/*显示迷宫图*/if(ch==’1')PeopleFind(map);/*人工探索*/elseFindWay(map,1,1);/*系统自动从下标1,1的地方开始探索*/Result();/*输出结果*/Close();}void Init(void)/*图形初始化*/{int gd=DETECT,gm;initgraph(&gd,&gm,”c:\\tc");}void DrawPeople(int *x,int *y,int n)/*画人工控制图*/{/*如果将以下两句注释掉,则显示人工走过的路径,*/setfillstyle(SOLID_FILL,WHITE); /*设置白色实体填充样式*/bar(100+(*y)*15-6,50+(*x)*15—6,100+(*y)*15+6,50+(*x)*15+6);/*恢复原通路*/switch(n)/*判断x,y的变化,8个方向的变化*/{case 1: (*x)—-;break; /*上*/case 2: (*x)——;(*y)++;break ;/*右上*/case 3:(*y)++;break; /*右*/case 4: (*x)++;(*y)++;break; /*右下*/case 5: (*x)++;break; /*下*/case 6: (*x)++;(*y)—-;break; /*左下*/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);}void PeopleFind(int (*map)[N])/*人工手动查找*/{int x,y;char c=0;/*接收按键的变量*/x=y=1;/*人工查找的初始位置*/setcolor(11);line(500,200,550,200);outtextxy(570,197,"d”);line(500,200,450,200);outtextxy(430,197,"a");line(500,200,500,150);outtextxy(497,130,"w”);line(500,200,500,250);outtextxy(497,270,"x”);line(500,200,450,150);outtextxy(445,130,”q");line(500,200,550,150);outtextxy(550,130,"e”);line(500,200,450,250);outtextxy(445,270,”z”);line(500,200,550,250);outtextxy(550,270,"c");/*以上是画8个方向的控制介绍*/setcolor(YELLOW);outtextxy(420,290,"Press 'Enter' to end");/*压回车键结束*/setfillstyle(SOLID_FILL,RED);bar(100+y*15-6,50+x*15—6,100+y*15+6,50+x*15+6);/*入口位置显示*/ while(c!=13)/*如果按下的不是回车键*/{c=getch();/*接收字符后开始各个方向的探索*/if(c==’w'&&map[x—1][y]!=1)DrawPeople(&x,&y,1);/*上*/elseif(c=='e'&&map[x—1][y+1]!=1)DrawPeople(&x,&y,2);/*右上*/elseif(c==’d’&&map[x][y+1]!=1)DrawPeople(&x,&y,3);/*右*/elseif(c=='c'&&map[x+1][y+1]!=1)DrawPeople(&x,&y,4);/*右下*/elseif(c==’x’&&map[x+1][y]!=1)DrawPeople(&x,&y,5);/*下*/elseif(c=='z'&&map[x+1][y-1]!=1)DrawPeople(&x,&y,6); /*左下*/elseif(c=='a’&&map[x][y-1]!=1)DrawPeople(&x,&y,7); /*左*/else if(c==’q’&&map[x—1][y-1]!=1)DrawPeople(&x,&y,8); /*左上*/}setfillstyle(SOLID_FILL,WHITE); /*消去红色探索物,恢复原迷宫图*/bar(100+y*15-6,50+x*15-6,100+y*15+6,50+x*15+6);if(x==N-2&&y==N-2)/*人工控制找成功的话*/yes=1; /*如果成功标志为1*/}void WayCopy(int (*oldmap)[N],int (*map)[N])/*拷贝迷宫数组*/ {int i,j;for(i=0;i<N;i++)for(j=0;j<N;j++)oldmap[i][j]=map[i][j];}int FindWay(int (*map)[N],int i,int j)/*递归找路*/{if(i==N—2&&j==N-2)/*走到出口*/{yes=1;/*标志为1,表示成功*/return;}map[i][j]=1;/*走过的地方变为1*/WayCopy(oldmap,map); /*拷贝迷宫图*/if(oldmap[i+1][j+1]==0&&!yes)/*判断右下方是否可走*/{FindWay(oldmap,i+1,j+1);if(yes)/*如果到达出口了,再把值赋给显示路线的way数组,也正是这个原因,所以具体路线是从最后开始保存*/{way[wayn][0]=i;way[wayn++][1]=j;return;}}WayCopy(oldmap,map);if(oldmap[i+1][j]==0&&!yes)/*判断下方是否可以走,如果标志yes已经是1也不用找下去了*/{FindWay(oldmap,i+1,j);if(yes){way[wayn][0]=i;way[wayn++][1]=j;。
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();}。
C++迷宫的实现代码
C++迷宫的实现代码本⽂实例为⼤家分享了C++实现迷宫游戏的具体代码,供⼤家参考,具体内容如下//⽂件的输⼊,有墙#include<iostream>#include<ctime>#include<cstdlib>#include<fstream>using namespace std;const int max1=100*100; //加⼊墙const int max2=102;bool value[max2][max2]; //记录是否被访问过int maze[max2][max2]; //迷宫的⼤⼩int n,m; //输⼊迷宫的长和宽ofstream outfile("path.txt"); //⽂件保存迷宫及输出的路径struct Point //栈中的数据{int x;int y;};struct Stack{int top;Point path[max1]; //存坐标点的数组栈stack(){top=-1; //栈中从0开始存数据}bool Empty() //检验是否为空{if(top==-1)return true;elsereturn false;}void Clear() //清空栈{top=-1;}void Push(Point p) //进栈{top++;path[top]=p;}Point Pop() //返回栈顶元素{return path[top];}void Delete_Pop() //删除顶栈元素{top--;}int Y_N_Push(){int x=path[top].x;int y=path[top].y;if(x<1||y<1||x>n||y>m||!value[x][y]||maze[x][y]) //不符合要求{value[x][y]=false; //标记这个点被访问过(不能任意做标记)return 1;}elseif((x==n)&&(y==m)) //已经找到出⼝,不要标记,后⾯直接跳出return 2;else{value[x][y]=false; //标记这个点被访问过return 3; //可以进栈}}void Output() //输出栈中的路径{int i;for(i=0;i<top;i++){cout<<"("<<path[i].x<<","<<path[i].y<<")"<<"--->";}cout<<"("<<path[i].x<<","<<path[i].y<<")"<<endl;outfile<<"该迷宫的路径为:"<<endl; //⽂件的输出for(i=0;i<top;i++){outfile<<"("<<path[i].x<<","<<path[i].y<<")"<<"--->";}outfile<<"("<<path[i].x<<","<<path[i].y<<")"<<endl;}};Stack stack; //不可以放在栈的定义前⾯bool Test_value() //检验每个节点是否是否被访问过,全访问过了则为true,false为没有全部访问过{int i,j;bool t=true;for(i=1;i<=n;i++)for(j=1;j<=m;j++)if(value[i][j]!=false){t=false;break;}return t;}int Judge(){Point t;int frage=0; //先规定先向右while(frage==0){t=stack.Pop(); //返回栈顶元素t.y=t.y+1; //向右stack.Push(t);if(stack.Y_N_Push()==1) //不符合要求的节点{stack.Delete_Pop();t=stack.Pop();t.x=t.x+1; //向下stack.Push(t);if(stack.Y_N_Push()==1){stack.Delete_Pop();t=stack.Pop();t.y=t.y-1; //向左stack.Push(t);if(stack.Y_N_Push()==1){stack.Delete_Pop();t=stack.Pop();t.x=t.x-1; //向上stack.Push(t);if(stack.Y_N_Push()==1){frage=4; //这个点4个⽅向都不成⽴stack.Delete_Pop();}}}}if(stack.Y_N_Push()==2){frage=5; //找到了出⼝并跳出break;}}return frage;}void Search(){stack.Clear();Point u;u.x=1;u.y=1;stack.Push(u);value[1][1]=false;while(true){int t=Judge();if(t==5) //找到了路{cout<<"找到了能通的路,路径为(⽤那个点的坐标表⽰):"<<endl;stack.Output();break;}if(t==4)stack.Delete_Pop(); //退回⼀个点继续找if((Test_value()==true)||(stack.top==-1)) //很重要的条件,stack.top==-1,否则的话当有个点四周都不能通过的话,⽽且前⾯的点也不能通的话,就没有通路 {cout<<"没有通路!"<<endl;outfile<<"没有通路!"<<endl;break;}}}int main(){int i,j;cout<<"请输⼊迷宫的长和宽:"; //⼆维数组从maze[0][0]开始cin>>n>>m;for(i=0;i<=(m+1);i++)maze[0][i]=maze[n+1][i]=1;for(i=1;i<=(n+1);i++)maze[i][0]=maze[i][m+1]=1;cout<<"输⼊迷宫,1为墙,0为可通路(规定左上⾓为⼊⼝,右下⾓为出⼝):"<<endl;srand(unsigned(time(NULL)));for(i=1;i<=n;i++)for(j=1;j<=m;j++)maze[i][j]=(rand()%2);maze[1][1]=maze[n][m]=0;cout<<"输⼊的迷宫(带有墙)是:"<<endl;for(i=0;i<=(n+1);i++){for(j=0;j<=(m+1);j++)cout<<maze[i][j]<<" ";cout<<endl;}if(!outfile){cerr<<"open error!"<<endl;exit(1);}outfile<<"⽣成"<<n<<"⾏"<<m<<"列"<<"的迷宫为:"<<endl;for(i=0;i<=(n+1);i++){for(j=0;j<=(m+1);j++)outfile<<maze[i][j]<<" ";outfile<<endl;}for(i=1;i<=n;i++) //记录从value[0][0]开始for(j=1;j<=m;j++)value[i][j]=true;Search();return 0;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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();}。