-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameEngine.h
548 lines (469 loc) · 15.7 KB
/
GameEngine.h
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//
// GameEngine.h
// Termin8or
//
// Created by Rasmus Anthin on 2023-12-30.
//
#pragma once
#include "Keyboard.h"
#include "ScreenUtils.h"
#include <Core/Delay.h>
#include <Core/Rand.h>
#include <Core/Math.h>
#include <Core/FolderHelper.h>
#include <Core/OneShot.h>
#include <chrono>
#include <sstream>
struct GameEngineParams
{
bool enable_title_screen = true;
bool enable_instructions_screen = true;
bool enable_quit_confirm_screen = true;
bool quit_confirm_unsaved_changes = false;
bool enable_hiscores = true;
bool enable_pause = true;
bool enable_terminal_window_resize = true; // If true it will resize the terminal window if too small for the game screen.
Color screen_bg_color_default = Color::Default;
Color screen_bg_color_title = Color::Default;
Color screen_bg_color_instructions = Color::Default;
std::optional<Color> screen_bg_color_paused = std::nullopt;
std::optional<Color> screen_bg_color_quit_confirm = Color::DarkCyan;
styles::Style quit_confirm_title_style { Color::Black, Color::DarkCyan };
styles::ButtonStyle quit_confirm_button_style { Color::Black, Color::DarkCyan, Color::Cyan };
styles::Style quit_confirm_info_style { Color::White, Color::DarkCyan };
std::optional<Color> screen_bg_color_input_hiscore = Color::DarkGray;
styles::Style input_hiscore_title_style { Color::Green, Color::Black };
styles::PromptStyle input_hiscore_prompt_style { Color::Green, Color::Black, Color::DarkGreen };
styles::Style input_hiscore_info_style { Color::DarkGreen, Color::Black };
std::optional<Color> screen_bg_color_hiscores = Color::DarkGray;
styles::Style hiscores_title_style { Color::Green, Color::Black };
styles::HiliteFGStyle hiscores_nr_style { Color::Green, Color::Black, Color::Cyan };
styles::HiliteFGStyle hiscores_score_style { Color::Green, Color::Black, Color::Cyan };
styles::HiliteFGStyle hiscores_name_style { Color::Green, Color::Black, Color::Cyan };
styles::Style hiscores_info_style { Color::DarkGreen, Color::Black };
};
template<int NR = 30, int NC = 80>
class GameEngine
{
bool paused = false;
bool show_title = true;
bool show_instructions = false;
bool show_quit_confirm = false;
bool show_game_over = false;
bool show_you_won = false;
bool show_input_hiscore = false;
bool show_hiscores = false;
std::string_view path_to_exe; // Includes the <program>.exe file.
std::string exe_file; // Only the <program>.exe file.
std::string exe_path; // Excludes the <program>.exe file.
GameEngineParams m_params;
// Simulation delay.
int sim_delay = 50'000; // 100'000 (10 FPS) // 60'000 (16.67 FPS);
// Real-time FPS.
float real_fps = 12.f; // 5
float sim_dt_s = static_cast<float>(sim_delay) / 1e6f;
float sim_time_s = 0.f;
double real_time_s = 0.;
double real_last_time_s = 0.;
double real_dt_s = 0.;
struct AnimCtrData
{
int anim_count_per_frame_count = 1;
int anim_ctr = 0;
};
std::vector<AnimCtrData> anim_ctr_data;
int frame_ctr = 0;
int frame_ctr_measure = 0;
YesNoButtons quit_confirm_button = YesNoButtons::No;
std::vector<HiScoreItem> hiscore_list;
int score = 0;
HiScoreItem curr_score_item;
int hiscore_caret_idx = 0;
int term_win_rows = 0;
int term_win_cols = 0;
OneShot trg_update_halted, trg_update_resumed;
bool handle_hiscores(const HiScoreItem& curr_hsi)
{
const int c_max_num_hiscores = 20;
const std::string c_file_path = folder::join_file_path({ exe_path, "hiscores.txt" });
// Read saved hiscores.
std::vector<std::string> lines;
if (std::filesystem::exists(c_file_path))
{
if (!TextIO::read_file(c_file_path, lines))
return false;
}
// Import saved hiscores from vector of strings.
hiscore_list.clear();
for (const auto& hs_str : lines)
{
std::istringstream iss(hs_str);
HiScoreItem hsi;
iss >> hsi.name >> hsi.score;
hiscore_list.emplace_back(hsi);
}
// Add current hiscore.
hiscore_list.push_back(curr_hsi);
// Sort hiscores.
auto num_hiscores = static_cast<int>(hiscore_list.size());
stlutils::sort(hiscore_list,
[](const auto& hsi_A, const auto& hsi_B) { return hsi_A.score > hsi_B.score; });
if (num_hiscores >= 1)
hiscore_list = stlutils::subset(hiscore_list, 0, std::min(num_hiscores, c_max_num_hiscores) - 1);
else
{
std::cerr << "ERROR: Unknown error while saving hiscores!" << std::endl;
return false;
}
// Export hiscores to vector of strings.
lines.clear();
for (const auto& hsi : hiscore_list)
{
std::ostringstream oss;
oss << str::trim_ret(hsi.name) << " " << hsi.score;
lines.emplace_back(oss.str());
}
// Save hiscores.
if (!TextIO::write_file(c_file_path, lines))
return false;
return true;
}
protected:
std::chrono::time_point<std::chrono::steady_clock> real_start_time_s;
OneShot time_inited;
ScreenHandler<NR, NC> sh;
Color bg_color = Color::Default;
keyboard::KeyPressDataPair kpdp;
std::unique_ptr<keyboard::StreamKeyboard> keyboard;
bool exit_requested = false;
unsigned int curr_rnd_seed = 0;
void set_real_fps(float fps_val)
{
if (keyboard != nullptr)
keyboard->set_held_buffer_size_from_fps(fps_val);
anim_ctr_data[0].anim_count_per_frame_count = math::roundI(fps_val / 5);
real_fps = fps_val;
}
// Used for dynamics and stuff.
void set_sim_delay_us(float delay_us)
{
sim_delay = math::roundI(delay_us);
sim_dt_s = static_cast<float>(sim_delay) / 1e6f;
}
int& ref_score() { return score; }
double get_real_time_s() const { return real_time_s; }
double get_real_dt_s() const { return real_dt_s; }
float get_sim_time_s() const { return sim_time_s; }
float get_sim_dt_s() const { return sim_dt_s; }
void set_anim_rate(int anim_channel, int val)
{
if (anim_channel < 0)
return;
anim_channel++; // Reserving the true index 0 for system animations.
auto& ad = stlutils::at_growing(anim_ctr_data, anim_channel);
ad.anim_count_per_frame_count = std::max(1, val);
}
int get_anim_rate(int anim_channel)
{
if (anim_channel < 0)
return 1;
anim_channel++; // Reserving the true index 0 for system animations.
auto& ad = stlutils::at_growing(anim_ctr_data, anim_channel);
return ad.anim_count_per_frame_count;
}
int get_frame_count() const { return frame_ctr; }
int get_frame_count_measure() const { return frame_ctr_measure; }
int get_anim_count(int anim_channel)
{
if (anim_channel < 0)
return 1;
anim_channel++; // Reserving the true index 0 for system animations.
auto& ad = stlutils::at_growing(anim_ctr_data, anim_channel);
return ad.anim_ctr;
}
std::string get_exe_folder() const { return exe_path; }
void enable_quit_confirm_screen(bool enable)
{
m_params.enable_quit_confirm_screen = enable;
}
// Callbacks
virtual void update() = 0;
virtual void draw_title() {}
virtual void draw_instructions() {}
virtual void on_quit() {}
virtual void on_exit_title() {}
virtual void on_exit_instructions() {}
virtual void on_enter_game_loop() {}
virtual void on_exit_game_loop() {}
virtual void on_enter_game_over() {}
virtual void on_halt_game_loop() {}
virtual void on_resume_game_loop() {}
virtual void on_exit_game_over() {}
virtual void on_enter_you_won() {}
virtual void on_exit_you_won() {}
virtual void on_enter_input_hiscore() {}
virtual void on_exit_input_hiscore() {}
virtual void on_enter_hiscores() {}
virtual void on_enter_paused() {}
virtual void on_exit_paused() {}
public:
GameEngine(std::string_view exe_full_path,
const GameEngineParams& params)
: path_to_exe(exe_full_path)
, m_params(params)
, anim_ctr_data(1)
{
std::tie(exe_path, exe_file) = folder::split_file_path(std::string(path_to_exe));
show_title = params.enable_title_screen;
if (!show_title)
show_instructions = params.enable_instructions_screen;
}
virtual ~GameEngine() = default;
void init()
{
if (exit_requested)
return;
keyboard = std::make_unique<keyboard::StreamKeyboard>();
keyboard->set_held_buffer_size_from_fps(real_fps);
begin_screen();
if (m_params.enable_terminal_window_resize)
{
std::tie(term_win_rows, term_win_cols) = get_terminal_window_size();
int new_rows = term_win_rows;
int new_cols = term_win_cols;
math::maximize(new_rows, NR + 1);
math::maximize(new_cols, NC);
resize_terminal_window(new_rows, new_cols);
}
//nodelay(stdscr, TRUE);
curr_rnd_seed = rnd::srand_time();
if (time_inited.once())
real_start_time_s = std::chrono::steady_clock::now();
}
virtual void generate_data() = 0;
void run()
{
if (exit_requested)
return;
// RT-Loop
clear_screen();
on_enter_game_loop();
auto update_func = std::bind(&GameEngine::engine_update, this);
Delay::update_loop(real_fps, update_func);
on_exit_game_loop();
}
float get_real_fps() const { return real_fps; }
int get_sim_delay_us() const { return sim_delay; }
void set_state_game_over() { show_game_over = true; }
void set_state_you_won() { show_you_won = true; }
void request_exit() { exit_requested = true; }
void set_screen_bg_color_default(Color bg_color) { m_params.screen_bg_color_default = bg_color; }
private:
void pre_quit()
{
end_screen(sh);
if (m_params.enable_terminal_window_resize)
if (term_win_rows > 0 && term_win_cols > 0)
resize_terminal_window(term_win_rows, term_win_cols);
on_quit();
}
bool engine_update()
{
if (exit_requested)
return false;
if (time_inited.was_triggered())
{
auto curr_time = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed_seconds = curr_time - real_start_time_s;
real_last_time_s = real_time_s;
real_time_s = elapsed_seconds.count();
real_dt_s = real_time_s - real_last_time_s;
}
return_cursor();
sh.clear();
kpdp = keyboard->readKey();
auto key = keyboard::get_char_key(kpdp.transient);
auto lo_key = str::to_lower(key);
auto quit = lo_key == 'q';
auto pause = lo_key == 'p';
if (quit)
{
math::toggle(show_quit_confirm);
quit_confirm_button = YesNoButtons::No;
}
else if (m_params.enable_pause && pause)
{
math::toggle(paused);
if (paused)
on_enter_paused();
else
on_exit_paused();
}
if (!m_params.enable_quit_confirm_screen && quit)
{
pre_quit();
return false;
}
else if (show_quit_confirm && !show_hiscores && !show_input_hiscore)
{
bg_color = m_params.screen_bg_color_quit_confirm.value_or(bg_color);
std::vector<std::string> titles;
if (m_params.quit_confirm_unsaved_changes)
titles.emplace_back("You have unsaved changes!");
titles.emplace_back("Are you sure you want to quit?");
auto special_key = keyboard::get_special_key(kpdp.transient);
draw_confirm(sh, titles, quit_confirm_button,
m_params.quit_confirm_title_style,
m_params.quit_confirm_button_style,
m_params.quit_confirm_info_style);
if (special_key == keyboard::SpecialKey::Left)
quit_confirm_button = YesNoButtons::Yes;
else if (special_key == keyboard::SpecialKey::Right)
quit_confirm_button = YesNoButtons::No;
if (special_key == keyboard::SpecialKey::Enter)
{
if (quit_confirm_button == YesNoButtons::Yes)
{
pre_quit();
return false;
}
else
show_quit_confirm = false;
}
}
else
{
bg_color = m_params.screen_bg_color_default;
if (m_params.enable_title_screen && show_title)
{
bg_color = m_params.screen_bg_color_title;
draw_title();
if (key == ' ')
{
on_exit_title();
show_title = false;
show_instructions = true;
}
}
else if (m_params.enable_instructions_screen & show_instructions)
{
bg_color = m_params.screen_bg_color_instructions;
draw_instructions();
if (key == ' ')
{
on_exit_instructions();
show_instructions = false;
}
}
else if (show_game_over)
{
if (game_over_timer == 0)
draw_game_over(sh, 0.1f*(7.f/real_fps));
else
{
game_over_timer--;
if (game_over_timer == 0)
on_enter_game_over();
}
update();
if (m_params.enable_hiscores && key == ' ')
{
on_exit_game_over();
show_game_over = false;
show_input_hiscore = true;
curr_score_item.init(score);
hiscore_caret_idx = 0;
on_enter_input_hiscore();
}
}
else if (show_you_won)
{
if (you_won_timer == 0)
draw_you_won(sh, 0.07f*(7.f/real_fps));
else
{
you_won_timer--;
if (you_won_timer == 0)
on_enter_you_won();
}
update();
if (m_params.enable_hiscores && key == ' ')
{
on_exit_you_won();
show_you_won = false;
show_input_hiscore = true;
curr_score_item.init(score);
hiscore_caret_idx = 0;
on_enter_input_hiscore();
}
}
else if (show_input_hiscore)
{
bg_color = m_params.screen_bg_color_input_hiscore.value_or(bg_color);
if (draw_input_hiscore(sh, kpdp.transient, curr_score_item, hiscore_caret_idx, anim_ctr_data[0].anim_ctr,
m_params.input_hiscore_title_style,
m_params.input_hiscore_prompt_style,
m_params.input_hiscore_info_style))
{
on_exit_input_hiscore();
handle_hiscores(curr_score_item);
show_input_hiscore = false;
show_hiscores = true;
on_enter_hiscores();
}
}
else if (show_hiscores)
{
bg_color = m_params.screen_bg_color_hiscores.value_or(bg_color);
draw_hiscores(sh, hiscore_list,
m_params.hiscores_title_style,
m_params.hiscores_nr_style,
m_params.hiscores_score_style,
m_params.hiscores_name_style,
m_params.hiscores_info_style);
if (key == ' ' || quit)
{
pre_quit();
return false;
}
}
else if (paused)
{
bg_color = m_params.screen_bg_color_paused.value_or(bg_color);
draw_paused(sh, anim_ctr_data[0].anim_ctr);
}
else
update();
}
sh.print_screen_buffer(bg_color);
//sh.print_screen_buffer_chars();
//sh.print_screen_buffer_fg_colors();
//sh.print_screen_buffer_bg_colors();
///
frame_ctr++;
if (frame_ctr % anim_ctr_data[0].anim_count_per_frame_count == 0)
anim_ctr_data[0].anim_ctr++;
if (!show_title && !show_instructions && !show_quit_confirm && !show_input_hiscore && !show_hiscores && !paused)
{
if (trg_update_resumed.once())
{
on_resume_game_loop();
trg_update_halted.reset();
}
frame_ctr_measure++;
for (size_t ad_idx = 0; ad_idx < anim_ctr_data.size(); ++ad_idx)
if (frame_ctr_measure % anim_ctr_data[ad_idx].anim_count_per_frame_count == 0)
anim_ctr_data[ad_idx].anim_ctr++;
sim_time_s += sim_dt_s;
}
else
{
if (trg_update_halted.once())
{
on_halt_game_loop();
trg_update_resumed.reset();
}
}
return true;
}
};