本文实例讲述了基于C语言实现迷宫游戏的方法,代码备有较为详尽的注释,便于读者理解。通过该游戏代码可以很好的复习C语言的递归算法与流程控制等知识,相信对于学习游戏开发的朋友有一定的借鉴价值。
完整的实例代码如下:
#include#include #include #include #include #define N 20 int oldmap[N][N]; int yes=0; int way[100][2],wayn=0; 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]); 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 auton"); scanf("%c",&ch); Init(); MapRand(map); PrMap(map); if(ch=='1') PeopleFind(map); else FindWay(map,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) { 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"); 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); else if(c=='e'&&map[x-1][y+1]!=1) DrawPeople(&x,&y,2); else if(c=='d'&&map[x][y+1]!=1) DrawPeople(&x,&y,3); else if(c=='c'&&map[x+1][y+1]!=1) DrawPeople(&x,&y,4); else if(c=='x'&&map[x+1][y]!=1) DrawPeople(&x,&y,5); else if(c=='z'&&map[x+1][y-1]!=1) DrawPeople(&x,&y,6); else if(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; } void WayCopy(int (*oldmap)[N],int (*map)[N]) { int i,j; for(i=0;i =0;i--) { bar(100+way[i][1]*15-6,50+way[i][0]*15-6,100+ way[i][1]*15+6,50+way[i][0]*15+6); sleep(1); } bar(100+(N-2)*15-6,50+(N-2)*15-6,100+ (N-2)*15+6,50+(N-2)*15+6); setcolor(GREEN); settextstyle(0,0,2); outtextxy(130,400,"Find a way!"); } void NotFind(void) { setcolor(GREEN); settextstyle(0,0,2); outtextxy(130,400,"Not find a way!"); } void Result(void) { if(yes) Find(); else NotFind(); getch(); } void Close(void) { closegraph(); }



