shadow-over-bishkek001/src/items/Item.cpp
2026-07-07 11:24:21 +03:00

56 lines
1.5 KiB
C++

#include "Item.h"
#include "ItemRegistry.h"
#include "external/nlohmann/json.hpp"
#include <algorithm>
#include <iostream>
namespace ZL {
void Inventory::addItem(const std::string& itemId) {
itemIds.push_back(itemId);
std::cout << "Item added to inventory: " << itemId << std::endl;
if (onItemAdded) onItemAdded(itemId);
}
void Inventory::removeItem(const std::string& itemId) {
auto it = std::find(itemIds.begin(), itemIds.end(), itemId);
if (it != itemIds.end()) {
std::cout << "Item removed from inventory: " << itemId << std::endl;
if (onItemRemoved) onItemRemoved(itemId);
itemIds.erase(it);
}
}
bool Inventory::hasItem(const std::string& itemId) const {
return std::find(itemIds.begin(), itemIds.end(), itemId) != itemIds.end();
}
std::vector<Item> Inventory::getItems() const {
std::vector<Item> result;
result.reserve(itemIds.size());
for (const auto& id : itemIds) {
const Item* def = ItemRegistry::instance().findById(id);
if (def) result.push_back(*def);
}
return result;
}
void Inventory::save(nlohmann::json& out) const {
out["items"] = itemIds;
}
void Inventory::load(const nlohmann::json& in) {
itemIds.clear();
if (!in.contains("items") || !in["items"].is_array()) return;
for (const auto& j : in["items"]) {
if (j.is_string()) {
itemIds.push_back(j.get<std::string>());
} else if (j.is_object()) {
// Backward-compat with old save files that stored full item structs.
const std::string id = j.value("id", "");
if (!id.empty()) itemIds.push_back(id);
}
}
}
} // namespace ZL