Monster Spawning using Loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::string monsterNames[2] {"Weezer", "Leppin"};

for (int vecID = 1; vecID < 5; ++vecID)
    {
		if(newmonster.monsterData[vecID-1].posX != newmonster.monsterData[vecID].posX && newmonster.monsterData[vecID-1].posY != newmonster.monsterData[vecID].posY)
        {
            int randIndex = rand()% 2;
            int randPosX = rand()% 3;
            int randPosY = rand()% 3;

            newmonster.CreateMonster(monsterNames[randIndex], randPosX, randPosY);
            newmonster.monsterData.push_back(newmonster);
        }
        else
        {
            continue;
        }
    }


I know what is wrong with this code - the monster vector is created after the if statement checks for element comparison. Silly and impossible way.
The program spawns random monster names at random locations and the if statement checks whether a monster at that location already exists, but of course, it doesn't work at this time.
I have to use a loop to create monsters because it's the only way the numbers will re-randomise.
Last edited on
You can use a 2d array as a static field for your newmonster class to make checking easier. I'd make an accessor function for fields, for both monsterdata and the new 2d array. As for re-randomising the array, could you be more precise? Do you mean that it produces the same random number? If then, use srand(time(0)) or use std::random_device.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::random_device location;

while(your_condition)
{
    int unsigned index=location()%2;
    int unsigned x= location()%3;
    int unsigned y= location()%3; 

if(newmonster.check_position(x,y)) //accessor for the 2d array
{
    newmonster.CreateMonster(monsterNames[index], x, y);
    newmonster.addMonster(newmonster); //adds a monster to monsterdata
}
else continue;

}
Last edited on
Topic archived. No new replies allowed.