#include "engine.hpp" #include "util/function.hpp" #include #include #include CLIGameEngine::CLIGameEngine( IGameFactory game_factory, ISceneFactory scene_factory, std::shared_ptr input_handler, std::shared_ptr cursor_controller) noexcept : _game_factory(std::move(game_factory)), _scene_factory(std::move(scene_factory)), _input_handler(std::move(input_handler)), _cursor_controller(std::move(cursor_controller)) { } void CLIGameEngine::start() noexcept { std::shared_ptr scene = _scene_factory(_cursor_controller); scene->enter(); _input_handler->enter_raw_mode(); auto game = _game_factory(scene, _cursor_controller); game->on_start(); std::atexit(normalize_lambda( [this, scene, &game]() { scene->leave(); _input_handler->leave_raw_mode(); game->on_exit(); })); _configure_input(game->get_input_config()); auto listen_input_thread = std::thread(normalize_lambda( [this]() { _input_handler->listen(); })); auto last_update_time = std::chrono::system_clock::now(); const auto get_millis_since_update = [&last_update_time]() { return std::chrono::duration_cast( std::chrono::system_clock::now() - last_update_time); }; while (true) { const auto time_since_last_update = get_millis_since_update(); if (time_since_last_update.count() < MIN_TIME_SINCE_LAST_UPDATE_MILLIS) { while (get_millis_since_update().count() < MIN_TIME_SINCE_LAST_UPDATE_MILLIS) { } } game->on_update(); last_update_time = std::chrono::system_clock::now(); } } void CLIGameEngine::_configure_input( const std::unordered_map> &input_config) noexcept { for (const auto &config_pair : input_config) { auto key = config_pair.first; auto command = config_pair.second; _input_handler->subscribe(key, command); } }