troop_count_registry.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include "troop_count_registry.h"
  2. #include "../core/component.h"
  3. #include "../core/world.h"
  4. #include "../units/troop_config.h"
  5. #include "core/event_manager.h"
  6. #include "units/spawn_type.h"
  7. namespace Game::Systems {
  8. auto TroopCountRegistry::instance() -> TroopCountRegistry & {
  9. static TroopCountRegistry inst;
  10. return inst;
  11. }
  12. void TroopCountRegistry::initialize() {
  13. m_unit_spawned_subscription =
  14. Engine::Core::ScopedEventSubscription<Engine::Core::UnitSpawnedEvent>(
  15. [this](const Engine::Core::UnitSpawnedEvent &e) {
  16. on_unit_spawned(e);
  17. });
  18. m_unit_died_subscription =
  19. Engine::Core::ScopedEventSubscription<Engine::Core::UnitDiedEvent>(
  20. [this](const Engine::Core::UnitDiedEvent &e) { on_unit_died(e); });
  21. }
  22. void TroopCountRegistry::clear() { m_troop_counts.clear(); }
  23. auto TroopCountRegistry::get_troop_count(int owner_id) const -> int {
  24. auto it = m_troop_counts.find(owner_id);
  25. if (it != m_troop_counts.end()) {
  26. return it->second;
  27. }
  28. return 0;
  29. }
  30. void TroopCountRegistry::on_unit_spawned(
  31. const Engine::Core::UnitSpawnedEvent &event) {
  32. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  33. return;
  34. }
  35. int const production_cost =
  36. Game::Units::TroopConfig::instance().getProductionCost(event.spawn_type);
  37. m_troop_counts[event.owner_id] += production_cost;
  38. }
  39. void TroopCountRegistry::on_unit_died(
  40. const Engine::Core::UnitDiedEvent &event) {
  41. if (event.spawn_type == Game::Units::SpawnType::Barracks) {
  42. return;
  43. }
  44. int const production_cost =
  45. Game::Units::TroopConfig::instance().getProductionCost(event.spawn_type);
  46. int old_count = m_troop_counts[event.owner_id];
  47. m_troop_counts[event.owner_id] -= production_cost;
  48. if (m_troop_counts[event.owner_id] < 0) {
  49. m_troop_counts[event.owner_id] = 0;
  50. }
  51. }
  52. void TroopCountRegistry::rebuild_from_world(Engine::Core::World &world) {
  53. m_troop_counts.clear();
  54. auto entities = world.get_entities_with<Engine::Core::UnitComponent>();
  55. for (auto *e : entities) {
  56. auto *unit = e->get_component<Engine::Core::UnitComponent>();
  57. if ((unit == nullptr) || unit->health <= 0) {
  58. continue;
  59. }
  60. if (unit->spawn_type == Game::Units::SpawnType::Barracks) {
  61. continue;
  62. }
  63. int const production_cost =
  64. Game::Units::TroopConfig::instance().getProductionCost(
  65. unit->spawn_type);
  66. m_troop_counts[unit->owner_id] += production_cost;
  67. }
  68. }
  69. } // namespace Game::Systems