I'm writing a small roguelike game for my university programming project. I wanted to try implementing a simple pathfinding mechanism, which would involve filling the tilemap with numbers going upwards from 0, the number being the distance to the player. This would allow the monsters to find the shortest path to the player. This is the algorithm I came up with:
void monster_vision(int player_x, int player_y, int score = 0)
{
if (map[player_x][player_y] == '.')
{
map[player_x][player_y] = score;
}
else
return;
monster_vision(player_x - 1, player_y, score + 1);
monster_vision(player_x + 1, player_y, score + 1);
monster_vision(player_x, player_y - 1, score + 1);
monster_vision(player_x, player_y + 1, score + 1);
}
as I said, this is just a single-file draft of the feature, the map is of type std::array<std::array<char, map_size>, map_size
initially filled with # at the edges and dots inside
I expected the map to look something like this: for example, if the map's size is set to 5 and the function call is: monster_vision(2, 2)
#####
#212#
#101#
#212#
#####
what I get instead is:
#####
#218#
#307#
#456#
#####
from my understanding, some of the recursive calls must somehow overlap, but I thought the guard I put in place should be sufficient to prevent writing onto an already-scored cell.