With our items being spawned in our Game::PopulateLevel
function, and the ability to call a function a random number of times, let's update the code so we spawn a random number of items when we start the game.
To achieve this, all we need to do is create the same loop as in the previous exercise, and encapsulate our spawn code within it. Let's update Game::PopulateLevel
with the following:
// Populate the level with items. void Game::PopulateLevel() { // A Boolean variable used to determine if an object should be spawned. bool canSpawn; // Generate a random number between 1 and 10. int iterations = std::rand() % 10 + 1; // Now loop that number of times. for (int i = 0; i < iterations; i++) { // Spawn an item. canSpawn = std::rand() % 2; if (canSpawn) { int itemIndex = std::rand() % 2; std::unique_ptr<Item> item; switch (itemIndex) { case 0: item = std::make_unique<Gold>(...