#include<iostream> #include<fstream> #include<string> #include<conio.h> #include<cstdlib> using namespace std;
int find(char ch,int &x,int &y,string openMaze,int& width ) { string str; ifstream fin(openMaze.c_str()); if(!fin) {cout<<"can't open"<<endl; return 0;} while(getline(fin,str)) { x++; y=str.find(ch,0); if(y!=string::npos) break; } width=str.size(); fin.close(); x--; return 1; }//find 'e' and return width
int loadMap(string* load,string openMaze,int & height) { string str; ifstream fin(openMaze.c_str()); if(!fin) {cout<<"can't open"<<endl; return 0;} while(getline(fin,str)) { load[height]=str; height++; } fin.close(); return 1; }//load the map into a string pointer and return height //method: //1.R 2.D 3.L 4.U //o------> //| | //|<-----V bool findWay(int x,int y,string* load) { load[x][y]='O'; if (load[x+1][y]=='x') return true; if (load[x-1][y]=='x') return true; if (load[x][y+1]=='x') return true; if (load[x][y-1]=='x') return true; if (load[x][y+1]=='.') { if(findWay(x,y+1,load)==true) return true; } if (load[x+1][y]=='.') { if(findWay(x+1,y,load)==true) return true; } if (load[x][y-1]=='.') { if(findWay(x,y-1,load)==true) return true; } if (load[x-1][y]=='.') { if(findWay(x-1,y,load)==true) return true; } load[x][y]='.'; return false; }//use square to sign where it has been ,if can't go through,turn it back to '.'
int main() { int i,width=0,height=0; int x=0,y=0,x1=0,y1=0; //int director; string openMaze; cout<<"which map do you like to play?maze1.txt or maze2.txt?"<<endl; cin>>openMaze; cout<<endl; if(find('e',x,y,openMaze,width)) {cout<<"can find entrance "; cout<<"x: "<<x<<" y: "<<y<<"!"<<endl;} else {cout<<"can't find entrance !"<<endl; return 1; } if(find('x',x1,y1,openMaze,width)) {cout<<"can find exit "; cout<<"x: "<<x1<<" y: "<<y1<<"!"<<endl;} else {cout<<"can't find exit !"<<endl; return 1; } string* load=new string[width];//create the string pointer to load map
loadMap(load,openMaze,height); cout<<"the map is :"<<height<<" * "<<width<<" type."<<endl; load[x][y]='\004';load[x1][y1]='\004'; for (i=0;i<=height;i++) cout<<load[i]<<endl;
load[x1][y1]='x'; if (findWay(x,y,load)) { cout<<"can find the way!"<<endl; for (i=0;i<=height;i++) cout<<load[i]<<endl; } else cout<<"can't find,sorry!"<<endl; delete [] load; return 0; } 
|