randomwalk/main.cpp
2024-08-03 18:55:58 +02:00

99 lines
No EOL
2.3 KiB
C++

#include <SDL2/SDL.h>
#include <chrono>
#include <memory>
#include <print>
#include <random>
template <typename SDLT, auto deletef>
struct sdl_wrapper_t : std::unique_ptr<SDLT, decltype(deletef)> {
explicit sdl_wrapper_t(SDLT* p)
: std::unique_ptr<SDLT, decltype(deletef)>{p, deletef} {}
operator SDLT*() { return std::unique_ptr<SDLT, decltype(deletef)>::get(); }
};
using window_t = sdl_wrapper_t<SDL_Window, SDL_DestroyWindow>;
using surface_t = sdl_wrapper_t<SDL_Surface, SDL_FreeSurface>;
using renderer_t = sdl_wrapper_t<SDL_Renderer, SDL_DestroyRenderer>;
struct Point {
int x;
int y;
};
auto operator+(Point a, Point b) {
return Point{.x = a.x + b.x, .y = a.y + b.y};
}
constexpr int width = 3440;
constexpr int height = 1440;
int main() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::println("fuck");
return EXIT_FAILURE;
}
{
window_t window{SDL_CreateWindow(
"random walk", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
width, height, SDL_WINDOW_FULLSCREEN
)};
renderer_t renderer{
SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)
};
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
if (!window) {
std::println(
"Window could not be created! SDL_Error: {}", SDL_GetError()
);
return EXIT_FAILURE;
}
auto surface = surface_t{SDL_GetWindowSurface(window)};
auto point = Point{.x = width / 2, .y = height / 2};
const Point directions[] = {
{.x = -1, .y = 0},
{.x = 1, .y = 0},
{.x = 0, .y = -1},
{.x = 0, .y = 1}
};
std::mt19937_64 rne(std::random_device{}());
std::uniform_int_distribution<int> dist(0, 3);
bool quit = false;
auto next_frame = std::chrono::steady_clock::now();
while (!quit) {
SDL_RenderDrawPoint(renderer, point.x, point.y);
Point newpoint;
do {
newpoint = point + directions[dist(rne)];
} while (newpoint.x < 0 or newpoint.x >= width or newpoint.y < 0 or
newpoint.y >= height);
point = newpoint;
if (std::chrono::steady_clock::now() > next_frame) {
next_frame += std::chrono::milliseconds{200};
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) { quit = true; }
}
SDL_RenderPresent(renderer);
// SDL_RenderClear(renderer);
}
}
}
SDL_Quit();
// leaking memory, nothing I can do
}