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

ItemManager::ItemManager()
	: m_pItems{ }
{
	
}

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

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

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

		for (size_t x{}; x < str.length(); x++)
		{
			switch (str[x])
			{
			case '0':
				break;
			case 'c':
				AddItem(new Gold(static_cast<int>(x), static_cast<int>(y), Gold::Type::COIN));
				break;
			case 'C':
				AddItem(new Gold(static_cast<int>(x), static_cast<int>(y), Gold::Type::THREE_COINS));
				break;
			case 'x':
				AddItem(new Gold(static_cast<int>(x), static_cast<int>(y), Gold::Type::SMALL_CHUNK));
				break;
			case 'X':
				AddItem(new Gold(static_cast<int>(x), static_cast<int>(y), Gold::Type::BIG_CHUNK));
				break;
			case 'r':
				AddItem(new Diamond(static_cast<int>(x), static_cast<int>(y), Diamond::Type::RED));
				break;
			case 'B':
				AddItem(new Diamond(static_cast<int>(x), static_cast<int>(y), Diamond::Type::GREEN));
				break;
			case 'b':
				AddItem(new Diamond(static_cast<int>(x), static_cast<int>(y), Diamond::Type::BLUE));
				break;
			default:
				break;
			}
		}

		y--;
	}

	SortItems();
}

void ItemManager::SortItems()
{
	std::sort(m_pItems.begin(), m_pItems.end(), [](const Item* lhs, const Item* rhs)
	{
		return (lhs->GetTypeHash() < rhs->GetTypeHash());
	});

	/*
	for (Item* pItem : m_pItems)
	{
		std::cout << std::to_string(pItem->GetTypeHash()) << ", ";
	}
	std::cout << '\n';
	*/
}

void ItemManager::Update( float elapsedSec, const Level& level )
{
	for (Item* pItem : m_pItems)
	{
		pItem->Update(elapsedSec, level);
	}
}

void ItemManager::Draw( ) const
{
	for (Item* pItem : m_pItems)
	{
		pItem->Draw();
	}
}

size_t ItemManager::Size( ) const
{
	return m_pItems.size();
}

Item* ItemManager::AddItem( Item* pItem )
{
	m_pItems.push_back(pItem);
	return m_pItems.back();
}

std::vector<Item*>& ItemManager::GetItems()
{
	return m_pItems;
}