Your problem is two fold.
First, you're using >= and <= instead of > and <. Why is this a problem? Just think.
If a user is at (0, 0) and wanted to go left, your code would have allowed him to do so!
Second, in all 4 cases you're checking if the
current position out of bounds which should never happen. What you should be checking is if the
potential (i.e.
new) position is out of bounds and not move if it is!
In a nutshell, your code doesn't prevent the user to go out of bounds; it just alerts him that he has done so!
If you fixed the above two then your code would work. But of course (as you noticed) it's really repetitive.
A much more elegant way to write it is like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
int main()
{
initMap();
map[0][0] = 'X';
int currentCol = 0;
int currentRow = 0;
int start = true;
bool quit = false;
while (! quit) {
options();
int choice;
cin >> choice;
int changeRow = 0;
int changeCol = 0;
switch (choice) {
case 1: changeRow = 1; break;
case 2: changeRow = -1; break;
case 3: changeCol = 1; break;
case 4: changeCol = -1; break;
case 5: quit = true; break;
default: cout << "Bad input" << endl; break;
}
if (quit)
break;
if (! OutOfBounds(currentRow + changeRow, currentCol + changeCol)) {
map[currentCol][currentRow] = '0';
currentRow += changeRow;
currentCol += changeCol;
map[currentCol][currentRow] = 'X';
} else {
cout << "Out of bounds" << endl;
}
showMap();
cout << endl;
}
}
|
The out of bounds function could look like this:
1 2 3 4 5 6 7
|
#define MAP_WIDTH 5
#define MAP_HEIGHT 10
char map[MAP_WIDTH][MAP_HEIGHT];
bool OutOfBounds(int x, int y)
{
return (x < 0 || x >= MAP_WIDTH) || (y < 0 || y >= MAP_HEIGHT);
}
|
Note that you should always tend to use named constants instead of putting magic numbers like 5 or 10 directly into code. This way, you could easily change dimensions of the map just by changing two numbers! In your code, if you wanted to change dimensions of the map you would need to change numbers all over the place.