aboutsummaryrefslogtreecommitdiff
path: root/src/engine/engine.cpp
blob: afa5924cc5fa362686b9703222c5aba02dbb9084 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "engine.hpp"

#include "input_actions.hpp"
#include "strings.hpp"
#include "util/function.hpp"

#include <fmt/core.h>
#include <iostream>
#include <utility>

CLIGameEngine::CLIGameEngine(IGameFactory game_factory, ISceneFactory scene_factory,
							 std::shared_ptr<IInputHandler> input_handler,
							 std::shared_ptr<ICursorController> cursor_controller,
							 std::shared_ptr<IWindow> window) noexcept
	: _game_factory(game_factory),
	  _scene_factory(scene_factory),
	  _input_handler(std::move(input_handler)),
	  _cursor_controller(std::move(cursor_controller)),
	  _window(std::move(window))
{
}

void CLIGameEngine::start() noexcept
{
	auto scene = _scene_factory(_cursor_controller, _window);

	scene->enter();
	_input_handler->enter_raw_mode();

	const auto window_size = _window->size();

	const auto center_position =
		Vector2({.x = static_cast<Vector2::Value>(window_size.get_width()) / 2,
				 .y = static_cast<Vector2::Value>(window_size.get_height()) / 2});

	_cursor_controller->move_to(center_position);

	scene->write_status(fmt::format(STATUS_BAR_COORDINATES,
									fmt::arg("x", center_position.get_x()),
									fmt::arg("y", center_position.get_y())));

	std::atexit(normalize_lambda(
		[this, scene]()
		{
			scene->leave();
			_input_handler->leave_raw_mode();

			for (auto row : *scene->get_matrix())
			{
				for (auto &col : row)
				{
					fmt::print("{}", col);
				}

				fmt::print("\n");
			}

			std::cout.flush();
		}));

	const std::unordered_map<char, Callback> input_config = {
		{'q', InputActions::exit_success},
		{'i',
		 [this, scene]()
		 {
			 const auto position = _cursor_controller->where();

			 std::cout.put('x');
			 std::cout.flush();

			 _cursor_controller->move_to(position);

			 auto matrix = scene->get_matrix();

			 matrix->set(position - Vector2({.x = 0U, .y = 1U}), "#");
		 }},
		{'k',
		 InputActions::move_cursor(Vector2::up(), _cursor_controller, scene, _window)},
		{'j',
		 InputActions::move_cursor(Vector2::down(), _cursor_controller, scene, _window)},
		{'h',
		 InputActions::move_cursor(Vector2::left(), _cursor_controller, scene, _window)},
		{'l', InputActions::move_cursor(Vector2::right(), _cursor_controller, scene,
										_window)}};

	_configure_input(input_config);

	_input_handler->listen();

	auto game = _game_factory();

	game->run();
}

void CLIGameEngine::_configure_input(
	const std::unordered_map<char, Callback> &input_config) noexcept
{
	for (const auto &config_pair : input_config)
	{
		_input_handler->attach(config_pair.first, config_pair.second);
	}
}