0
\$\begingroup\$

I'm creating a dungeon crawler in C++ and I'm almost done but I need to make the monster move and I'm at the end of my wits.

This is my map:

Char Map[10][10];

and this is how I initialize the positions of the monsters:

void fieldinfo::RandomizeMonsterPositions()
{
    amountEnemies=10;
    srand(time(0));

    for(i=0; i<amountEnemies; i++){
        map[rand()%9][rand()%9] = enemy;
    }
}

fieldinfo is the name of my class.

Each time the player moves, the map is redrawn with the updated players position and I need the monster to move every time the player does (randomly or not I don't care).

\$\endgroup\$
1
  • \$\begingroup\$ Are you referring to enemy AI? Simply just moving the AI inside your map? \$\endgroup\$
    – CobaltHex
    Dec 26, 2017 at 22:54

1 Answer 1

2
\$\begingroup\$

I'd start by storing all enemy positions in a separate container (a vector for an example).

Then, when you execute a turn, you'd start by clearing the old positions of the enemies.

for (auto& enemyPosition : EnemyPositions)
{
    Map[enemyPosition.y][enemyPosition.x] = empty;
}

Then you'd do a move pass and update all monster positions:

for (auto& enemyPosition : EnemyPositions)
{
    // TODO: Replace with your own movement logic.
    if (rand() % 2 == 0)
        enemyPosition.x += 1  
    else
        enemyPosition.y += 1
}

After that you could do some sort of collision pass to make sure the enemies don't walk through walls or check if they collide with each other or the player and handle those situations accordingly.

And finally you'll just blop the enemies back to the map with their new adjusted positions:

for (auto& enemyPosition : EnemyPositions)
{
    Map[enemyPosition.y][enemyPosition.x] = enemy;
}

As a side note, I'd suggest creating more of a separation of visuals & world state, since it's very easy to accidentally overwrite something in your map grid, which could result in a wide variety of bugs.

\$\endgroup\$
1
  • \$\begingroup\$ You're right i'm actually trying to make it so the monster don't spawn at the same positions but i got some issues with that. but thank you for your help i'll try to first understand what vectors are and can do ! thx a lot! \$\endgroup\$ Dec 26, 2017 at 13:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .