aboutsummaryrefslogtreecommitdiffstats
path: root/main.cpp
blob: 09b55f4bb7ede86c1db24d11644650623f40164c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "components/point.hpp"
#include "components/player.hpp"
#include "components/texture.hpp"
#include "components/velocity.hpp"
#include "window.hpp"

#include <chrono>
#include <thread>

#include <entt/entt.hpp>
#include <SDL2/SDL.h>

constexpr std::chrono::microseconds FRAME_TIME (1'000'000 / 60);

static bool handleInputs(entt::registry& registry);

int main()
{
    if (auto err = sdl2Initialize(); err)
        return err;

    entt::registry registry;

    const auto ent = registry.create();
    registry.emplace<Player>(ent);
    registry.emplace<Point>(ent, 0.f, WINDOW_HEIGHT - 100.f);
    registry.emplace<Velocity>(ent, 0.f, 0.f);
    registry.emplace<Texture>(ent, "img/player.png");

    do {
        const auto now = std::chrono::high_resolution_clock::now();

        SDL_RenderClear(renderer);
        registry.view<Texture, Point>().each([](auto& tex, auto& p) { tex(renderer, p); });
        SDL_RenderPresent(renderer);

        registry.view<Velocity, Point>().each([](auto& v, auto& p) { p += v; });

        std::this_thread::sleep_until(now + FRAME_TIME);
    } while (handleInputs(registry));
}

bool handleInputs(entt::registry& registry)
{
    bool quit = false;

    for (SDL_Event e; SDL_PollEvent(&e);) {
        if (e.type == SDL_QUIT) {
            quit = true;
        } else if (e.type == SDL_KEYDOWN && !e.key.repeat) {
            auto view = registry.view<Player, Velocity>();

            switch (e.key.keysym.sym) {
            case SDLK_d:
                view.each([](Player& p, Velocity& v) { v.x += 1.5f; });
                break;
            case SDLK_a:
                view.each([](Player& p, Velocity& v) { v.x -= 1.5f; });
                break;
            }
        } else if (e.type == SDL_KEYUP && !e.key.repeat) {
            auto view = registry.view<Player, Velocity>();

            switch (e.key.keysym.sym) {
            case SDLK_d:
                view.each([](Player& p, Velocity& v) { v.x -= 1.5f; });
                break;
            case SDLK_a:
                view.each([](Player& p, Velocity& v) { v.x += 1.5f; });
                break;
            }
        }
    }

    return !quit;
}