simple walk batching

and poll events roughly every 100ms
This commit is contained in:
Jakob Hördt 2024-08-03 23:52:26 +02:00
parent d521c06c34
commit 2c88eff416

View file

@ -2,10 +2,13 @@
#include <SDL2/SDL.h>
#include <chrono>
#include <memory>
#include <print>
#include <random>
namespace {
template <typename SDLT, auto deletef>
struct sdl_wrapper_t : std::unique_ptr<SDLT, decltype(deletef)> {
explicit sdl_wrapper_t(SDLT* p)
@ -47,6 +50,15 @@ struct [[nodiscard("give this a name so SDL_Quit is called at the end"
~Defer() { EF(); }
};
using clock = std::chrono::steady_clock;
auto poll_events(bool& continu) {
for (SDL_Event e; SDL_PollEvent(&e);) {
if (e.type == SDL_QUIT) { continu = false; }
}
}
} // namespace
int main() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::println("fuck");
@ -87,23 +99,29 @@ int main() {
// aarrggbb??
constexpr Uint32 walk_color = 0xff00ff00;
const auto start_time = clock::now();
auto next_poll_events_time = start_time;
for (bool continu = true; continu;) {
SDL_Point newpoint;
do {
newpoint = pos + directions[dist(rne)];
} while (newpoint.x < 0 or newpoint.x >= width or newpoint.y < 0 or
newpoint.y >= height);
pos = newpoint;
SDL_LockSurface(window_surface);
static_cast<Uint32*>(window_surface->pixels
)[pos.x + pos.y * window_surface->h] = walk_color;
SDL_UnlockSurface(window_surface);
for (SDL_Event e; SDL_PollEvent(&e);) {
if (e.type == SDL_QUIT) { continu = false; }
for (auto batch = 0z; batch < 1000; ++batch) {
SDL_Point newpoint;
do {
newpoint = pos + directions[dist(rne)];
} while (newpoint.x < 0 or newpoint.x >= width or newpoint.y < 0 or
newpoint.y >= height);
pos = newpoint;
static_cast<Uint32*>(window_surface->pixels
)[pos.x + pos.y * window_surface->h] = walk_color;
}
SDL_UnlockSurface(window_surface);
SDL_UpdateWindowSurface(window);
const auto now = clock::now();
if (now >= next_poll_events_time) {
next_poll_events_time = now + std::chrono::milliseconds{100};
poll_events(continu);
}
}
// leaking memory, nothing I can do