This article describes the C language to achieve a simple maze game method, code integrity, easy to understand the reader.
Learn the data structure of the "stack" written by a maze of procedures, actually used to two-way queues, convenient after the operation of the output after the point.
#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[3][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 > steps:%d Exit: (%d,%d) \ n", Steps,endx,endy);
Map[x][y] = the 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;
tem.lastopt = 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;
Sta.pop_back ();
else {map[x][y]=2;
X+=XOPT[TEM.LASTOPT];
X+=YOPT[TEM.LASTOPT];
Dis ();
Break
} dis ();
Sleep (500);
} if (x==endx && y = = Endy) cout<< "\ n > I am finished....\n";
else cout<< "\ n > I am finished...but I can ' t find the right way\n";
return 0; }
Effect Chart:
The above is the entire content of this article, I hope to learn C language to help you.