First of all, use arrays to your advantage.
Code:
/** Moves the unit currently at (x,y) by x_add in the x direction, y_add in the y direction.
Returns true upon success, false otherwise.
*/
bool move_unit(int x, int y, int x_add, int y_add) {
char unit = dungeon[x][y];
int new_x = x + x_add;
int new_y = y + y_add;
if(new_x < 0 || new_y < 0 || new_x >= 9 || new_y >= 9) {
return false;
}
dungeon[x][y] = ' '; // or whatever the "clear" character is
dungeon[new_x][new_y] = unit;
return true;
}
If you had a function like that, your entire heromove() function could be replaced with
Code:
void heromove() {
for(;;) {
cout << "Enter direction (w,a,s,d): ";
char direction;
cin >> direction;
int x_add = 0, y_add = 0;
if(direction == 'w') y_add --;
if(direction == 'a') x_add --;
if(direction == 's') y_add ++;
if(direction == 'd') x_add ++;
if(move_unit(heroposition[0], heroposition[1], x_add, y_add)) {
heroposition[0] += x_add;
heroposition[1] += y_add;
break; // exit infinite for(;;) loop
}
else {
cout << "Invalid move, try again." << endl;
}
}
}
There are other ways to do this, of course. I tried to make my example understandable. But don't copy-paste code just to change a few --'s to ++'s!
Now I'm not really sure what your question is. If you have random monsters, presumably you're keeping track of them somehow. If there are monsterposition[] arrays you can use a similar scheme as the above. But even if you aren't remembering where monsters are, you could just use something like
Code:
for(int x = 0; x < 9; x ++) {
for(int y = 0; y < 9; y ++) {
if(dungeon[x][y] == '!') { // whatever monster symbol is
int x_add = 0, y_add = 0;
if(rand() % 2) {
if(rand() % 2) x_add = -1;
else x_add = +1;
}
else {
if(rand() % 2) y_add = -1;
else y_add = +1;
}
move_unit(x, y, x_add, y_add); // don't care if this fails
}
}
}
If you want to be really fancy:
Code:
void random_movement(int x, int y) {
int moves[][2] = {
{+1, 0},
{-1, 0},
{0, +1},
{0, -1}
};
int r = rand() % 4;
move_unit(x, y, moves[r][0], moves[r][1]);
}
I could typing code snippets all day but I'm not sure what your question is, so I'll stop . . . .