examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

commit 3917a91f68f8dceb8155bf59c92df22f8152d23e
parent 9636e425c8ecf42cd00f574ced88656a5d528ac2
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Thu, 28 Apr 2022 22:58:00 +0100

gl-asteroids: Tidy up a bit using inheritance

Diffstat:
Msrc/gl-asteroids.cpp | 42++++++++++++++++++++++++++++--------------
1 file changed, 28 insertions(+), 14 deletions(-)

diff --git a/src/gl-asteroids.cpp b/src/gl-asteroids.cpp @@ -265,9 +265,13 @@ struct entity } }; -struct particle +static bool left_arena(entity const& e) +{ + return e.phys.left_arena(); +} + +struct particle : entity { - entity ent; float ttl; static particle& make_particle(entity e, float ttl) @@ -279,15 +283,15 @@ struct particle for (auto& p : particles) { p.ttl -= dt; - p.ent.phys.move(dt); + p.phys.move(dt); } std::erase_if(particles, [](auto& p) { return p.ttl <= 0; }); - std::erase_if(particles, [](auto const& p) { return p.ent.phys.left_arena(); }); + std::erase_if(particles, left_arena); } static void draw_all() { for (auto& p : particles) - p.ent.draw(); + p.draw(); } private: static std::vector<particle> particles; @@ -302,10 +306,19 @@ bool is_pressed(int key) return glfwGetKey(w, key) != GLFW_RELEASE; } +struct powerup : entity +{ + std::function<void(void)> cb; + + powerup(entity e, std::function<void(void)> c) + : entity(e) + , cb(c) + {} +}; + std::vector<entity> rocks; std::vector<entity> bullets; -std::optional<entity> powerups; -std::function<void(void)> powerup_cb; +std::optional<powerup> powerups; physics ship_phys{{}, {}, 0.f, 0.f, .06f}; bool up = false; @@ -450,21 +463,22 @@ int main(int argc, char* argv[]) } visual const* vis; + std::function<void(void)> cb; static int type; switch (type++ % 2) { case 0: vis = &powerup_bulletspeed; - powerup_cb = [&firerate](){ firerate += .5f; }; + cb = [&firerate](){ firerate += .5f; }; break; case 1: vis = &powerup_firerate; - powerup_cb = [&bullet_speed](){ bullet_speed += .2f; }; + cb = [&bullet_speed](){ bullet_speed += .2f; }; break; } - powerups.emplace(*vis, physics{p, v, 0, 0, scale}); + powerups.emplace(entity{*vis, physics{p, v, 0, 0, scale}}, cb); } if (ammo < 20 && ammo_refill_time < t) @@ -597,7 +611,7 @@ int main(int argc, char* argv[]) if (is_colliding(ship_phys, powerups->phys)) { play_sample(blip); - powerup_cb(); + powerups->cb(); powerups.reset(); score += 10; } @@ -615,10 +629,10 @@ int main(int argc, char* argv[]) break; } - score -= std::erase_if(bullets, [](auto const& e) { return e.phys.left_arena(); }); - score -= std::erase_if(rocks, [](auto const& e) { return e.phys.left_arena(); }); + score -= std::erase_if(bullets, left_arena); + score -= std::erase_if(rocks, left_arena); - if (powerups && powerups->phys.left_arena()) + if (powerups && left_arena(*powerups)) { powerups.reset(); --score;