SpelunkyRemake / EnemyManager.cpp
EnemyManager.cpp
Raw
#include "pch.h"
#include "EnemyManager.h"
#include <algorithm>
#include <fstream>

EnemyManager::EnemyManager()
	: m_pEnemies{ }
	, m_EnemyDieSFX{ "Resources/Sounds/splat.wav" }
{

}

EnemyManager::~EnemyManager()
{
	for (int i{}; i < int(m_pEnemies.size()); i++)
	{
		delete m_pEnemies[i];
		m_pEnemies[i] = nullptr;
	}
}

void EnemyManager::LoadEnemies(const Level::Info& levelInfo)
{
	std::ifstream enemiesFile{ "Resources/Levels/" + std::to_string(levelInfo.world) + "-" + std::to_string(levelInfo.stage) + "/level.lvl" };

	int y{ Level::m_NrTilesY - 1 };
	while (enemiesFile)
	{
		std::string str{};
		std::getline(enemiesFile, str);

		for (size_t x{}; x < str.length(); x++)
		{
			switch (str[x])
			{
			case 's':
				AddEnemy(new Snake(static_cast<int>(x), static_cast<int>(y)));
				break;
			case 'S':
				AddEnemy(new Spider(static_cast<int>(x), static_cast<int>(y)));
				break;
			default:
				break;
			}
		}

		y--;
	}
}

void EnemyManager::Update(float elapsedSec, const Level& level, Player* pPlayer, ParticleManager* pParticleManager)
{
	bool deleted{};
	using ForwardIt = std::vector<Enemy*>::reverse_iterator;

	for (ForwardIt it{ m_pEnemies.rbegin() }; it != m_pEnemies.rend(); it++)
	{
		(*it)->Update(elapsedSec, level, pPlayer, pParticleManager);

		if ((*it)->GetLives() <= 0)
		{
			m_EnemyDieSFX.Play(0);
			
			deleted = true;

			delete *it;
			*it = nullptr;
		}
	}

	if (deleted)
	{
		m_pEnemies.erase(remove_if(m_pEnemies.begin(), m_pEnemies.end(), [](Enemy* enemy)
		{
			return enemy == nullptr;
		}));
	}
}

void EnemyManager::Draw() const
{
	for (Enemy* pEnemy : m_pEnemies)
	{
		pEnemy->Draw();
	}
}

size_t EnemyManager::Size() const
{
	return m_pEnemies.size();
}

Enemy* EnemyManager::AddEnemy(Enemy* pEnemy)
{
	m_pEnemies.push_back(pEnemy);
	return m_pEnemies.back();
}

std::vector<Enemy*>& EnemyManager::GetEnemies()
{
	return m_pEnemies;
}