Chess Engine
A Chess Engine project written in C++.
Loading...
Searching...
No Matches
app_state.hpp
1
2#pragma once
3
4#include <atomic>
5#include <cstddef>
6#include <functional>
7#include <mutex>
8#include <optional>
9#include <vector>
10
11#include "game.hpp"
12
13class AppState {
14 public:
15 void addGame(const std::function<void(Game&)>& initializer = {}) {
16 std::lock_guard lock(m_mutex);
17 m_games.emplace_back();
18 auto& new_game = m_games.back();
19
20 if (initializer) {
21 initializer(new_game);
22 }
23
24 m_selected_index = m_games.size() - 1;
25 }
26
27 void selectGame(std::size_t index) {
28 std::lock_guard lock(m_mutex);
29 if (index < m_games.size()) {
30 m_selected_index = index;
31 }
32 }
33
34 void closeGame(size_t index) {
35 std::lock_guard lock(m_mutex);
36 if (index >= m_games.size()) return;
37
38 m_games.erase(m_games.begin() + static_cast<int>(index));
39
40 if (!m_selected_index) return;
41
42 if (index < *m_selected_index) {
43 --(*m_selected_index);
44 } else if (index == *m_selected_index) {
45 if (m_games.empty()) {
46 m_selected_index.reset();
47 } else if (index >= m_games.size()) {
48 m_selected_index = m_games.size() - 1;
49 }
50 }
51 }
52
53 void applyToAllGames(const std::function<void(Game&)>& action) {
54 std::lock_guard lock(m_mutex);
55 for (auto& game : m_games) {
56 action(game);
57 }
58 }
59
60 void applyToCurrentGame(const std::function<void(Game&)>& action) {
61 std::lock_guard lock(m_mutex);
62 if (auto index = currentIndex()) {
63 action(m_games[*index]);
64 }
65 }
66
67 struct UISnapshot {
68 std::vector<std::string> game_titles;
69 std::optional<std::size_t> selected_index;
70 const Game* current_game = nullptr;
71 };
72
73 UISnapshot snapshot() const {
74 std::lock_guard lock(m_mutex);
75 UISnapshot snap;
76 snap.game_titles.reserve(m_games.size());
77
78 for (const auto& game : m_games) {
79 snap.game_titles.push_back(game.title());
80 }
81
82 snap.selected_index = m_selected_index;
83
84 if (auto index = currentIndex()) {
85 snap.current_game = &m_games[*index];
86 }
87 return snap;
88 }
89
90 [[nodiscard]] bool shouldQuit() const { return m_quit_flag.load(); }
91 void signalQuit() { m_quit_flag = true; }
92
93 private:
94 std::optional<std::size_t> currentIndex() const {
95 if (m_selected_index.has_value() && m_selected_index.value() < m_games.size()) {
96 return m_selected_index;
97 }
98 return std::nullopt;
99 }
100
101 std::vector<Game> m_games;
102 std::optional<std::size_t> m_selected_index;
103 mutable std::mutex m_mutex;
104 std::atomic<bool> m_quit_flag{false};
105};
Definition app_state.hpp:13
Definition game.hpp:7
Definition app_state.hpp:67