# Why aren't my enemy positions updating?

I'm trying to make a dungeon crawler but I need to make the monster move around each turn.

Here's what I tried:

My map is initialized like this:

char map[10][10];


and this is how I spawn the monsters to avoid overwriting:

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

do
{
MposX=rand()%9;
MposY=rand()%9;

if(map[MposX][MposY]==enemy)
{
//do nothing
}
else if(map[MposX][MposY]==player)
{
//do nothing
}
else
{
map[MposX][MposY] = enemy;
tempPosX[i]=MposX;
tempPosY[i]=MposY;
i++;
Mcounter++;
}

}while(Mcounter<10);
}


You can see that I tried to "save" each monster's position in the tempPosX/Y variables to use them here, in my movement logic:

void fieldinfo::RandomizeMonsterMovement()
{
int mouvement;
for(int i; i<amountEnemies; i++)
{
mouvement=rand()%0;
switch(mouvement)
{
case 0:
tempPosX[i]++;
MposX=tempPosX[i];
break;
case 1:
tempPosX[i]--;
MposX=tempPosX[i];
break;
case 2:
tempPosY[i]++;
MposY=tempPosY[i];
break;
case 3:
tempPosY[i]--;
MposY=tempPosY[i];
break;
}
}
}


This doesn't work and I don't know why?

• What doesn't work? Are the monsters not moving? Not showing up at all? Something else?
– user35344
Dec 26 '17 at 14:51
• well monsters are not moving at all ^^ here's the map drawing method: void fieldinfo::DrawField() { int b,w; for(b=0; b<10; b++) { for(w=0; w<10; w++) cout << map[b][w]<< " "; cout << endl; } } Dec 26 '17 at 15:15
• rand()%0? That's undefined behaviour, and a SIGFPE in most cases I've seen... Dec 26 '17 at 16:00

You're not updating the map when the positions change.

You probably want to do something like the following:

void fieldinfo::RandomizeMonsterMovement()
{
for(int i = 0; i < amountEnemies; i++)
{
// Clears the current position.
map[tempPosX[i]][tempPosY[i]] = empty;

const int movement = rand() % 4;
switch(movement)
{
case 0:
tempPosX[i]++;
break;
case 1:
tempPosX[i]--;
break;
case 2:
tempPosY[i]++;
break;
case 3:
tempPosY[i]--;
break;
}

// Updates the map in the new position.
map[tempPosX[i]][tempPosY[i]] = enemy;
}
}


I'm not really sure what you tried to accomplish with MposX and MposY...

Anyways, I've got a basic example program with a single enemy moving around here: https://onlinegdb.com/HknD1eeQG

Please refer to my previous answer on how to improve the general movement system to handle corner cases in a much more improved manner.

• I really wish i could do something for you in exchange! You don't know how much you actually helped me and i'm really sorry to have bothered you with something like this! This gave me a better understanding of the c++ language! thanks a lot and I wish you a happy newyear Dec 26 '17 at 16:16
• Just a guess, but one possibility is that the values in tempPosX/Y become negative or larger than the size of your map, which will result in a crash since you're writing stuff outside of an array.