Skip to content

Commit

Permalink
Make SpawnTimer polymorphic, store vector.
Browse files Browse the repository at this point in the history
  • Loading branch information
karnkaul committed Jun 25, 2024
1 parent 2436fa9 commit 756df27
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 7 additions & 2 deletions src/spaced/spaced/scenes/endless.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include <bave/core/random.hpp>
#include <spaced/game/enemies/creep.hpp>
#include <spaced/game/powerups/beam.hpp>
#include <spaced/scenes/endless.hpp>
#include <spaced/services/game_signals.hpp>
Expand All @@ -9,18 +10,22 @@ using bave::random_in_range;
using bave::Seconds;
using bave::Services;

EndlessScene::EndlessScene(App& app, Services const& services) : GameScene(app, services), m_creeps{.services = &services} {
EndlessScene::EndlessScene(App& app, Services const& services) : GameScene(app, services) {
m_on_player_scored = services.get<GameSignals>().player_scored.connect([this](Enemy const& e) {
if (random_in_range(0, 10) < 3) { debug_spawn_powerup(e.get_position()); }
});

m_spawn_timers.push_back(std::make_unique<SpawnTimer<enemy::Creep>>(&services));
}

void EndlessScene::tick(Seconds const dt) {
GameScene::tick(dt);

if (is_game_over()) { return; }

if (auto creep = m_creeps.tick(dt)) { push_enemy(std::move(creep)); }
for (auto const& spawn_timer : m_spawn_timers) {
if (auto enemy = spawn_timer->tick(dt)) { push_enemy(std::move(enemy)); }
}
}

void EndlessScene::debug_spawn_powerup(glm::vec2 const position) {
Expand Down
13 changes: 9 additions & 4 deletions src/spaced/spaced/scenes/endless.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#pragma once
#include <spaced/game/enemies/creep.hpp>
#include <spaced/scenes/game.hpp>
#include <spaced/signal.hpp>

Expand All @@ -9,13 +8,19 @@ class EndlessScene : public GameScene {
EndlessScene(bave::App& app, bave::Services const& services);

private:
struct ISpawnTimer : bave::Polymorphic {
virtual auto tick(bave::Seconds dt) -> std::unique_ptr<Enemy> = 0;
};

template <std::derived_from<Enemy> T>
struct SpawnTimer {
struct SpawnTimer : ISpawnTimer {
bave::NotNull<bave::Services const*> services;
bave::Seconds spawn_rate{1s};
bave::Seconds elapsed{};

auto tick(bave::Seconds const dt) -> std::unique_ptr<T> {
explicit SpawnTimer(bave::NotNull<bave::Services const*> services) : services(services) {}

auto tick(bave::Seconds const dt) -> std::unique_ptr<Enemy> final {
auto ret = std::unique_ptr<T>{};
elapsed += dt;
if (elapsed >= spawn_rate) {
Expand All @@ -32,6 +37,6 @@ class EndlessScene : public GameScene {

SignalHandle m_on_player_scored{};

SpawnTimer<enemy::Creep> m_creeps;
std::vector<std::unique_ptr<ISpawnTimer>> m_spawn_timers{};
};
} // namespace spaced

0 comments on commit 756df27

Please sign in to comment.