examples

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

commit acad23d153291c4a1836eb285f8d38869eae2ca6
parent 3f1a9b58f4d9a047f668e47c1f161b5af4f5ae3a
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Sun,  3 Apr 2022 21:12:38 +0100

gl-asteroids: Quit more gracefully

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

diff --git a/src/gl-asteroids.cpp b/src/gl-asteroids.cpp @@ -222,6 +222,29 @@ bool is_pressed(int key) return glfwGetKey(w, key) != GLFW_RELEASE; } +std::vector<entity> rocks; +std::vector<entity> bullets; +physics s{{}, {}, 0.f, 0.f, .06f}; + +void draw_scene(void) +{ + glClearColor(0,0,0,1); + glClear(GL_COLOR_BUFFER_BIT); + + particle::draw_all(); + for (auto& r : rocks) + r.draw(); + for (auto& b : bullets) + b.draw(); + + draw_wrapped(ship, s); + if (is_pressed(GLFW_KEY_UP)) + draw(flame, s); + + glfwSwapBuffers(w); + glfwPollEvents(); +} + int main(int argc, char* argv[]) { unsigned score = 0; @@ -242,11 +265,7 @@ int main(int argc, char* argv[]) float last_t = glfwGetTime(); - std::vector<entity> rocks; - std::vector<entity> bullets; - float rock_time = 1, bullet_time = 0; - physics s{{}, {}, 0.f, 0.f, .06f}; while (!glfwWindowShouldClose(w) && not is_pressed(GLFW_KEY_ESCAPE)) { @@ -308,8 +327,7 @@ int main(int argc, char* argv[]) else s.ang_mom = 0; - bool up = is_pressed(GLFW_KEY_UP); - if (up) + if (is_pressed(GLFW_KEY_UP)) { float sr = sin(s.rot), cr = cos(s.rot); s.vel += coord{sr, cr} * dt; @@ -332,9 +350,6 @@ int main(int argc, char* argv[]) // handle collisions - if(any_of(rocks.begin(), rocks.end(), [&s](auto& r) { return is_colliding(s, r.p); })) - glfwSetWindowShouldClose(w, 1); - for (unsigned i = 0; i < rocks.size();) { auto r = rocks.begin() + i; @@ -373,29 +388,21 @@ int main(int argc, char* argv[]) bang: continue; } - // Draw scene - - glClearColor(0,0,0,1); - glClear(GL_COLOR_BUFFER_BIT); - - particle::draw_all(); - for (auto& r : rocks) - r.draw(); - for (auto& b : bullets) - b.draw(); - - draw_wrapped(ship, s); - if (up) - draw(flame, s); + if(any_of(rocks.begin(), rocks.end(), [](auto& r) { return is_colliding(s, r.p); })) + { + using namespace std::chrono_literals; + auto timeout = std::chrono::steady_clock::now() + 1s; + std::cout << "Score: " << score << '\n'; + while (std::chrono::steady_clock::now() < timeout) + draw_scene(); + break; + } - glfwSwapBuffers(w); - glfwPollEvents(); + draw_scene(); } + glfwDestroyWindow(w); glfwTerminate(); - std::cout << "Score: " << score << '\n'; - using namespace std::chrono_literals; - std::this_thread::sleep_for(1s); return 0; }