I'm working on a simple C++ game to learn the language. It's ASCII, and features a tile-based map, enemies and items that spawn randomly. The player is, as usual, the '@' character. I'm trying to find the best way to handle the map and characters. I have the map in a 2D vector. Originally, it was a vector of characters, but then that became too hard to manage and too fixed, so the map is now a 2D vector of Tile
objects. My enemies are contained in a vector called NPCs
, and the items that get spawned are contained in a vector called Items
.
My problem is in handling the relation between my map tiles and enemies/items. When an enemy stands on a tile, I have a pointer in the tile that points to that enemy, called npcPtr
. Same goes for items, with another attribute of that object called itemPtr
. This creates problems, because when an enemy dies and gets deleted from the NPCs
vector, the pointers in the map don't dynamically update, and now point to the wrong enemies. The same happens for items. I partially solved this by updating the pointers in all the tiles after every move, but that does not seem like the best approach. How should I handle this tile/character relation?
I read this similar question, and that's pretty much how I handle things, but it doesn't seem to be an optimal approach. The advantage to having pointers in the tile is that I can check whether that tile is an enemy, an item or nothing; I don't want to lose that functionality. I can also obtain the NPC/item data right away, using the pointer, without having to parse through the NPCs
vector.
My Code:
vector <vector <Tile>> _level //this is my level vector
vector <Character> _NPCs //this is my enemies vector
Making a new tile
Tile t //and then I set the tile parameters
Adding a tile to the level
levelLine.push_back(t)
Adding a whole line to the level
_level.push_back(levelLine)
Making an enemy
Character c //and then I set the parameters
Adding an enemy to the _NPCs
vector
_NPCs.push_back(c)
Positioning the enemy objects in the level
//for j in level lines and k in level colums
if (j = _NPCs[i].getY() && k = NPCs[i].getX()){
_level[j][k].setNPCptr(&_NPCs[i]); }
Handling enemy death
//re-initialize tile where enemy was to empty tile,
//_NPCptr gets set to nullptr
_NPCs.erase(_NPCs.begin() + npcPosition) //erase NPC from enemy vector
for (size_t i=0; i<_NPCs.size(); i++){
_level[_NPCs[i].getY()][_NPCs[i].getX()].setNPCptr(&_NPCs[i]);
}