I cannot get my maze to traverse correctly and when I trap myself, it just continues to recursively call itself …what am I doing wrong? I know the code is sloppy I just want to figure out what I am doing wrong.
sample mazeCode:#include <iostream.h> #include <stdlib.h> #include <fstream.h> #include <string.h> void Traverse( char[][10], int, int, int); void Print_Maze(const char[][10]); bool Valid_Move(const char[][10],int,int); bool Maze_End(int,int); enum direction {DOWN,RIGHT,UP,LEFT}; const int x = 2; // starting const int y = 0; // coordinates const int MAX = 10; char maze[MAX][MAX]; char buffer[100]; char *bufptr = buffer; const int MAXLENGTH = 50; char filename[MAXLENGTH]; static int times = 0; ////****Main****//// int main() { char ch, newline = '\n'; ifstream file; int num = 0; cout <<"enter the file name" <<endl; cin >> filename; strcat ( filename, ".txt"); file.open(filename, ios::nocreate | ios::in); if (file.fail()) { cout << "ERROR opening file: " << filename << endl; system("pause"); exit(1); } while ((ch = file.peek()) != EOF && num <=109 ) { file.unsetf(ios::skipws); file >> ch; if (ch != newline) *bufptr++ = ch; num++; } bufptr = buffer; for (int i=0; i<MAX; i++) { for (int k=0; k<MAX; k++) maze[i][k]= *bufptr++; } Traverse(maze,x,y,RIGHT); return 0; } ///////////////////////////////////Functions///////////////////////////////// void Traverse(char maze[MAX][MAX], int xlocation, int ylocation, int direction) { maze[xlocation][ylocation]='@'; Print_Maze(maze); if (Maze_End(xlocation,ylocation) && xlocation != x && ylocation != y) { cout <<" Hooray! I'm free " << times <<" moves made" <<endl; system("PAUSE"); return; } else if (xlocation == x && ylocation == x) { cout<<" Help! I'm trapped" << endl; system("PAUSE"); return; } else { for (int move=direction,count=0; count<4; count++,move++,move%=4) switch (move) { case DOWN: if (Valid_Move(maze,xlocation+1,ylocation)) { Traverse(maze,xlocation+1,ylocation,LEFT); return; } break; case RIGHT: if (Valid_Move(maze,xlocation,ylocation+1)) { Traverse(maze,xlocation,ylocation+1,DOWN); return; } break; case UP: if (Valid_Move(maze,xlocation-1,ylocation)) { Traverse(maze,xlocation-1,ylocation,RIGHT); return; } break; case LEFT: if (Valid_Move(maze,xlocation,ylocation-1)) { Traverse(maze,xlocation,ylocation-1,UP); return; } break; } // end switch }// end else } //end traverse bool Valid_Move(const char maze[MAX][MAX],int r, int c) { return (r>=0 && r<=9 && c>=0 && c<=9 && maze[r][c] != '+'); } bool Maze_End(int x,int y) { if ((x == 0 || x == 9) && (y >= 0 && y <= 9)) return true; else if ((y == 0 || y == 9) && (x >= 0 && x <= 9)) return true; else { times++; return false; } } void Print_Maze(const char maze[MAX][MAX]) { for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) cout<<maze[x][y]<<' '; cout<<'\n'; } cout<<"Press Enter for next move \n"; cin.get(); }
Code:+++ +++ ++ + + +++ ++ + ++ + +++++ + +++++ + ++ + + + +++ + + ++++ + +++ + ++++++++++



LinkBack URL
About LinkBacks



