-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.cpp
2638 lines (2127 loc) · 106 KB
/
main.cpp
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CMake-generated header containing timestamp of the build
#include "build_timestamp.h"
#include "imgui-extra/imgui_impl.h"
#include "imgui/imgui_internal.h"
#include "IconsFontAwesome5.h"
#include "IconsFontAwesome5Brands.h"
#define SDL_DISABLE_ARM_NEON_H 1
#include <SDL.h>
#include <SDL_opengl.h>
#include <array>
#include <cmath>
#include <fstream>
#include <functional>
#include <map>
#include <sstream>
#include <vector>
#include <memory>
#include <algorithm>
#include <chrono>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten/bind.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif
#include "imgui-helpers.h"
//
// Constants
//
using TColor = uint32_t;
const auto kTitle = "УЪРДЪЛ";
const auto kTitleClipboard = "Уърдъл 🇧🇬";
const auto kURL = "wordle-bg.ggerganov.com";
const auto kHashtag = "#уърдъл";
const auto kFontScale = 3.0f;
// animation time in seconds
const float kTimeFlip = 0.35f; // cell flip on submit
const float kTimeFill = 0.50f; // cell flip on submit
const float kTimeBump = 0.10f; // cell bump on key press
const float kTimeShake = 0.50f; // cell shake on incorrect input
const float kTimeShow = 0.20f; // time to show popup window
const float kTimeGuessed = 2.00f; // time to display text upon correct answer
const float kTimeClipboard = 2.00f; // time to display text about result being copied to the clipboard
const float kTimeIncorrect = 1.00f; // time to display text about incorrect input
const float kTimeInitialize = 2.00f; // time to initialize the UI
// timestamp of the first puzzle
// 15 Jan 2022 00:00:00
const int64_t kTimestamp0 = 1642197600;
// available color themes
enum class EColorTheme {
Light,
Dark,
};
// colors
enum class EColor {
Title,
Text,
TextSubmitted,
Background,
EmptyBorder,
EmptyFill,
PendingBorder,
PendingFill,
AbsentBorder,
AbsentFill,
PresentBorder,
PresentFill,
CorrectBorder,
CorrectFill,
KeyboardUnused,
};
using TColorTheme = std::map<EColor, TColor>;
const std::map<EColorTheme, TColorTheme> kColorThemes = {
{
EColorTheme::Light, {
{ EColor::Title, ImGui::ColorConvertFloat4ToU32({ float(0x1A)/256.0f, float(0x1A)/256.0f, float(0x1B)/256.0f, 1.00f }), },
{ EColor::Text, ImGui::ColorConvertFloat4ToU32({ float(0x1A)/256.0f, float(0x1A)/256.0f, float(0x1B)/256.0f, 1.00f }), },
{ EColor::TextSubmitted, ImGui::ColorConvertFloat4ToU32({ float(0xFF)/256.0f, float(0xFF)/256.0f, float(0xFF)/256.0f, 1.00f }), },
{ EColor::Background, ImGui::ColorConvertFloat4ToU32({ float(0xFF)/256.0f, float(0xFF)/256.0f, float(0xFF)/256.0f, 1.00f }), },
{ EColor::PendingBorder, ImGui::ColorConvertFloat4ToU32({ float(0x56)/256.0f, float(0x57)/256.0f, float(0x58)/256.0f, 1.00f }), },
{ EColor::PendingFill, ImGui::ColorConvertFloat4ToU32({ float(0x56)/256.0f, float(0x57)/256.0f, float(0x58)/256.0f, 0.00f }), },
{ EColor::EmptyBorder, ImGui::ColorConvertFloat4ToU32({ float(0xD3)/256.0f, float(0xD6)/256.0f, float(0xDA)/256.0f, 1.00f }), },
{ EColor::EmptyFill, ImGui::ColorConvertFloat4ToU32({ float(0x00)/256.0f, float(0x00)/256.0f, float(0x00)/256.0f, 0.00f }), },
{ EColor::AbsentBorder, ImGui::ColorConvertFloat4ToU32({ float(0x78)/256.0f, float(0x7C)/256.0f, float(0x7E)/256.0f, 1.00f }), },
{ EColor::AbsentFill, ImGui::ColorConvertFloat4ToU32({ float(0x78)/256.0f, float(0x7C)/256.0f, float(0x7E)/256.0f, 1.00f }), },
{ EColor::PresentBorder, ImGui::ColorConvertFloat4ToU32({ float(0xC9)/256.0f, float(0xB4)/256.0f, float(0x58)/256.0f, 1.00f }), },
{ EColor::PresentFill, ImGui::ColorConvertFloat4ToU32({ float(0xC9)/256.0f, float(0xB4)/256.0f, float(0x58)/256.0f, 1.00f }), },
{ EColor::CorrectBorder, ImGui::ColorConvertFloat4ToU32({ float(0x6A)/256.0f, float(0xAA)/256.0f, float(0x64)/256.0f, 1.00f }), },
{ EColor::CorrectFill, ImGui::ColorConvertFloat4ToU32({ float(0x6A)/256.0f, float(0xAA)/256.0f, float(0x64)/256.0f, 1.00f }), },
{ EColor::KeyboardUnused, ImGui::ColorConvertFloat4ToU32({ float(0xD3)/256.0f, float(0xD6)/256.0f, float(0xDA)/256.0f, 1.00f }), },
},
},
{
EColorTheme::Dark, {
{ EColor::Title, ImGui::ColorConvertFloat4ToU32({ float(0xD7)/256.0f, float(0xDA)/256.0f, float(0xDC)/256.0f, 1.00f }), },
{ EColor::Text, ImGui::ColorConvertFloat4ToU32({ float(0xD7)/256.0f, float(0xDA)/256.0f, float(0xDC)/256.0f, 1.00f }), },
{ EColor::TextSubmitted, ImGui::ColorConvertFloat4ToU32({ float(0xD7)/256.0f, float(0xDA)/256.0f, float(0xDC)/256.0f, 1.00f }), },
{ EColor::Background, ImGui::ColorConvertFloat4ToU32({ float(0x12)/256.0f, float(0x12)/256.0f, float(0x13)/256.0f, 1.00f }), },
{ EColor::PendingBorder, ImGui::ColorConvertFloat4ToU32({ float(0x56)/256.0f, float(0x57)/256.0f, float(0x58)/256.0f, 1.00f }), },
{ EColor::PendingFill, ImGui::ColorConvertFloat4ToU32({ float(0x56)/256.0f, float(0x57)/256.0f, float(0x58)/256.0f, 0.00f }), },
{ EColor::EmptyBorder, ImGui::ColorConvertFloat4ToU32({ float(0x3A)/256.0f, float(0x3A)/256.0f, float(0x3C)/256.0f, 1.00f }), },
{ EColor::EmptyFill, ImGui::ColorConvertFloat4ToU32({ float(0x00)/256.0f, float(0x00)/256.0f, float(0x00)/256.0f, 0.00f }), },
{ EColor::AbsentBorder, ImGui::ColorConvertFloat4ToU32({ float(0x3A)/256.0f, float(0x3A)/256.0f, float(0x3A)/256.0f, 1.00f }), },
{ EColor::AbsentFill, ImGui::ColorConvertFloat4ToU32({ float(0x3A)/256.0f, float(0x3A)/256.0f, float(0x3A)/256.0f, 1.00f }), },
{ EColor::PresentBorder, ImGui::ColorConvertFloat4ToU32({ float(0xB5)/256.0f, float(0x9F)/256.0f, float(0x3B)/256.0f, 1.00f }), },
{ EColor::PresentFill, ImGui::ColorConvertFloat4ToU32({ float(0xB5)/256.0f, float(0x9F)/256.0f, float(0x3B)/256.0f, 1.00f }), },
{ EColor::CorrectBorder, ImGui::ColorConvertFloat4ToU32({ float(0x53)/256.0f, float(0x8D)/256.0f, float(0x4E)/256.0f, 1.00f }), },
{ EColor::CorrectFill, ImGui::ColorConvertFloat4ToU32({ float(0x53)/256.0f, float(0x8D)/256.0f, float(0x4E)/256.0f, 1.00f }), },
{ EColor::KeyboardUnused, ImGui::ColorConvertFloat4ToU32({ float(0x81)/256.0f, float(0x83)/256.0f, float(0x84)/256.0f, 1.00f }), },
},
},
};
// used for the fade in/out effects
const ImVec4 kColorFade = { float(0x00)/256.0f, float(0x00)/256.0f, float(0x00)/256.0f, 0.50f };
// special keys
const auto kInputEnter = ICON_FA_CHECK;
const auto kInputBackspace = ICON_FA_BACKSPACE;
const std::vector<std::string> kAlphabet = {
"А", "Б", "В", "Г", "Д", "Е", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ь", "Ю", "Я",
};
// the keyboard layouts on the screen
enum class EKeyboardType {
Phonetic,
BDS,
};
using TKeyboard = std::vector<std::vector<std::string>>;
const TKeyboard kKeyboardBDS = {
{ "У", "Е", "И", "Ш", "Щ", "К", "С", "Д", "З", "Ц", "Б", },
{ "Ь", "Я", "А", "О", "Ж", "Г", "Т", "Н", "В", "М", "Ч", },
{ kInputEnter, "Ю", "Й", "Ъ", "Ф", "Х", "П", "Р", "Л", kInputBackspace, },
};
const TKeyboard kKeyboardPhonetic = {
{ "Я", "В", "Е", "Р", "Т", "Ъ", "У", "И", "О", "П", "Ю", },
{ "А", "С", "Д", "Ф", "Г", "Х", "Й", "К", "Л", "Ш", "Щ", },
{ kInputEnter, "З", "Ь", "Ц", "Ж", "Б", "Н", "М", "Ч", kInputBackspace, },
};
const std::map<EKeyboardType, TKeyboard> kKeyboards = {
{ EKeyboardType::Phonetic, kKeyboardPhonetic, },
{ EKeyboardType::BDS, kKeyboardBDS, },
};
// emojis for sharing results
const std::map<TColor, std::string> kGridEmojis = {
{ kColorThemes.at(EColorTheme::Light).at(EColor::AbsentFill), "⬜" },
{ kColorThemes.at(EColorTheme::Light).at(EColor::PresentFill), "🟨" },
{ kColorThemes.at(EColorTheme::Light).at(EColor::CorrectFill), "🟩" },
{ kColorThemes.at(EColorTheme::Dark).at(EColor::AbsentFill), "⬛" },
{ kColorThemes.at(EColorTheme::Dark).at(EColor::PresentFill), "🟨" },
{ kColorThemes.at(EColorTheme::Dark).at(EColor::CorrectFill), "🟩" },
};
namespace {
// poor-man's handling of cyrillic strings:
// get i'th character from utf-8 string
std::string utf8_ch(const std::string & str, int i) {
return { str[2*i + 0], str[2*i + 1] };
}
// compare i'th character from str0 with j'th character in str1
bool utf8_cmp(const std::string & str0, int i, const std::string & str1, int j) {
return str0[2*i + 0] == str1[2*j + 0] && str0[2*i + 1] == str1[2*j + 1];
}
// erase last utf-8 char
void utf8_erase_back(std::string & str) {
str.pop_back();
str.pop_back();
}
// number of utf-8 letters
std::size_t utf8_size(const std::string & str) {
return str.size()/2;
}
// map a time point t with period T to [0, 1]
float I(float t, float T) {
return std::max(0.0f, std::min(1.0f, t/T));
}
// is t within [t0, t0 + T]
bool within(float t, float t0, float T) {
return (t0 <= t) && (t <= t0 + T);
}
//
// JS interface
//
// initialize initial puzzle
std::function<bool()> g_doPuzzleInit;
// initialize the game state
std::function<bool()> g_doGameInit;
// set new window size
std::function<void(int, int)> g_setWindowSize;
// main game loop
std::function<bool()> g_mainUpdate;
// provide pressed keys
std::function<void(const std::string & )> g_input;
// called from JS to get the ID of the current puzzle
std::function<int()> g_getPuzzleId;
// set attempted words so far for a puzzle
// called at the start of the game to initialize data from the localStorage
std::function<void(int, const std::string & )> g_setAttempts;
// called from JS to query for any new recorder attempts
// returns empty string if there are no new attempts
std::function<std::string()> g_getAttempts;
// set the accumulated statistics for the current player
// called at the start of the game to initialize data from the localStorage
std::function<void(const std::string & )> g_setStatistics;
// called from JS to query for any new player statistics
// returns empty string if there are no changes to the player's stats
std::function<std::string()> g_getStatistics;
// called at the start of the game to initialize settings from the localStorage
std::function<void(const std::string & )> g_setSettings;
// called from JS to get any changes to the settings
// returns empty string if no changes to the settings have ocurred
std::function<std::string()> g_getSettings;
// called from JS to check if the "Share" button has been pressed
// returns a string with emojies representing the player's attempts to guess the word
std::function<std::string()> g_getClipboard;
// called from JS to show/hide the "Results copied to clipboard" text
std::function<void(bool)> g_setClipboardTextVisible;
// called from JS to check if an URL has been clicked
// returns a string with the URL address
std::function<std::string()> g_getURL;
// set the initial timestamp at which the game was started
std::function<void(int64_t)> g_setTimestamp;
#ifdef __EMSCRIPTEN__
// need this wrapper of the main loop for the emscripten_set_main_loop_arg() call
void mainUpdate(void *) {
g_mainUpdate();
}
// These functions are used to pass data back and forth between the JS and the C++ code
EMSCRIPTEN_BINDINGS(wordle) {
emscripten::function("do_puzzle_init", emscripten::optional_override([]() -> int { return g_doPuzzleInit(); }));
emscripten::function("do_game_init", emscripten::optional_override([]() -> int { return g_doGameInit(); }));
emscripten::function("set_window_size", emscripten::optional_override([](int sizeX, int sizeY) { g_setWindowSize(sizeX, sizeY); }));
emscripten::function("input", emscripten::optional_override([](const std::string & input) { g_input(input); }));
emscripten::function("get_puzzle_id", emscripten::optional_override([]() -> int { return g_getPuzzleId(); }));
emscripten::function("set_attempts", emscripten::optional_override([](int puzzleId, const std::string & input) { g_setAttempts(puzzleId, input); }));
emscripten::function("get_attempts", emscripten::optional_override([]() -> std::string { return g_getAttempts(); }));
emscripten::function("set_statistics", emscripten::optional_override([](const std::string & input) { g_setStatistics(input); }));
emscripten::function("get_statistics", emscripten::optional_override([]() -> std::string { return g_getStatistics(); }));
emscripten::function("set_settings", emscripten::optional_override([](const std::string & input) { g_setSettings(input); }));
emscripten::function("get_settings", emscripten::optional_override([]() -> std::string { return g_getSettings(); }));
emscripten::function("get_clipboard", emscripten::optional_override([]() -> std::string { return g_getClipboard(); }));
emscripten::function("set_clipboard_text_visible", emscripten::optional_override([](bool visible) { g_setClipboardTextVisible(visible); }));
emscripten::function("get_url", emscripten::optional_override([]() -> std::string { return g_getURL(); }));
emscripten::function("set_timestamp", emscripten::optional_override([](double input) { g_setTimestamp(input); }));
}
#endif
}
//
// Core
//
// common variables used for rendering stuff on the screen
struct Rendering {
// elapsed time since the program start - used for rendering animations
float T;
// total window size
ImVec2 wSize;
};
// a grid cell containing a single letter
struct Cell {
enum Type {
Empty,
Pending,
Absent,
Present,
Correct,
};
// the time at which the contents of the cell were submitted
float tSubmit = -100.0f;
Type type = Empty;
// the actual contents of the cell - a single utf-8 character
std::string data;
bool submitted() const { return tSubmit >= 0.0f && type != Pending; }
bool pending() const { return type == Pending; }
// return <fill, border> colors
std::pair<TColor, TColor> col(float iFlip, const TColorTheme & colors) const {
auto colFill = colors.at(EColor::EmptyFill);
auto colBorder = colors.at(EColor::EmptyBorder);
if (iFlip > 0.5f || submitted() == false) {
switch (type) {
case Cell::Empty:
{
colFill = colors.at(EColor::EmptyFill);
colBorder = colors.at(EColor::EmptyBorder);
} break;
case Cell::Pending:
{
colFill = colors.at(EColor::PendingFill);
colBorder = colors.at(EColor::PendingBorder);
} break;
case Cell::Absent:
{
colFill = colors.at(EColor::AbsentFill);
colBorder = colors.at(EColor::AbsentBorder);
} break;
case Cell::Present:
{
colFill = colors.at(EColor::PresentFill);
colBorder = colors.at(EColor::PresentBorder);
} break;
case Cell::Correct:
{
colFill = colors.at(EColor::CorrectFill);
colBorder = colors.at(EColor::CorrectBorder);
} break;
};
}
return { colFill, colBorder, };
}
};
// general window vars
struct Window {
bool showWindow = false; // show the window on the screen
// used for fade animations
float tShow = -100.0f;
float tHide = -100.0f;
// is the window currently visible?
bool visible(float T) const {
return showWindow && T > tShow;
}
};
// puzzles window vars
struct Puzzles : public Window {
int puzzleId = -1; // selected puzzle ID
// holding arrow buttons
bool isLeftHeld = false; // is the left arrow being held?
bool isRightHeld = false; // is the right arrow being held?
float nextChangeTime = 0.f; // timestamp of when the ID should next change
};
// statistics for the games that the player has played so far
struct Statistics : public Window {
int nPlayed = 0; // number of rounds played
int streakCur = 0; // current winning streak
int streakMax = 0; // longest winning streak
std::vector<int> guesses; // distribution of the number of attempts to guess a word
// percentage of games the player has won
float winPercentage() const {
if (nPlayed == 0) return 0.0f;
int nGuessed = 0;
for (const auto & n : guesses) nGuessed += n;
return float(100.0f*nGuessed)/nPlayed;
}
// the number of attempts after which the player has guessed most words
int maxGuesses() const {
int result = 0;
for (const auto & cur : guesses) {
result = std::max(result, cur);
}
return std::max(1, result);
}
};
// settings window vars
struct Settings : public Window {
float tKeyboardSwitched = -100.0f;
EKeyboardType keyboardType = EKeyboardType::Phonetic;
EKeyboardType keyboardTypeNew = keyboardType;
TKeyboard keyboard = kKeyboards.at(keyboardType);
EColorTheme colorTheme = EColorTheme::Light;
EColorTheme colorThemeNew = colorTheme;
TColorTheme colors = kColorThemes.at(colorTheme);
bool rectRounding = true;
bool rectRoundingNew = rectRounding;
bool addHashtag = true;
bool addHashtagNew = addHashtag;
bool addURL = true;
bool addURLNew = addURL;
};
// global variable containing the entire game state
struct State {
// rendering
int nUpdates = 60;
bool newInput = true;
bool isAnimating = false;
Rendering rendering;
// rules
static const int nLettersPerWord = 5;
static const int nAttemptsTotal = 6;
// words
std::vector<std::string> words;
std::vector<std::string> wordsDailyPool;
// logic + animations
int64_t timestamp = 0; // timestamp of when the current game started
float tShared = -100.0f; // timestamp of when player clicked on Share button
bool textClipboardVisible = true; // should the "Results copied to clipboard" text be shown?
// popup windows
Window help;
Puzzles puzzlesWnd;
Window advert;
Statistics statistics;
Settings settings;
// layout
float heightTitle = 50.0f;
float heightKeyboard = 200.0f;
// keyboard
float keyboardMinX = 0.0f;
float keyboardMaxX = 0.0f;
bool keyboardPressHandled = false;
// JS interface
std::string dataStatistics;
std::string dataClipboard;
std::string dataSettings;
std::string dataURL;
// Stores the data of a puzzle.
// Individual for each puzzle ID.
struct Puzzle {
int id = -1; // the ID of the puzzle
std::string answer; // puzzle answer
std::string attemptCur; // current attempt
std::vector<std::string> attempts; // past, submitted attempts
bool countTowardsStats = false; // should this puzzle, on finish, be counted towards statistics?
// logic
bool isInitialized = false; // has the puzzle been updated in State::update() before?
bool isGuessed = false; // has the player guessed the correct word?
bool isFinished = false; // has the current round finished (guessed word or ran out of attempts) ?
float tFinished = -100.0f; // timestamp of when the current round finished
float tIncorrect = -100.0f; // timestamp of last incorrect input
// type of incorrect input
enum class TypeIncorrect {
NotAWord,
NotEnoughLetters,
} eIncorrect;
// grid
std::vector<std::vector<Cell>> grid;
// keyboard
std::map<std::string, Cell::Type> keys;
// JS interface
std::string dataAttempts;
};
std::vector<std::unique_ptr<Puzzle>> puzzles;
Puzzle* currentPuzzle;
//
// helper methods
//
// create a puzzle with a certain ID.
Puzzle* createPuzzle(int puzzleId) {
auto puzzle = std::make_unique<Puzzle>();
// Initialize answer
if (wordsDailyPool.empty()) {
// select a random word, regardless of puzzleId
srand(std::time(nullptr));
puzzle->answer = words[rand() % words.size()];
} else {
// select a word, based on puzzId
puzzle->id = std::max(0, puzzleId);
printf("Puzzle ID: %d\n", puzzle->id);
// the daily pool list is already randomized:
puzzle->answer = wordsDailyPool[puzzle->id % wordsDailyPool.size()];
}
// Initialize grid
puzzle->grid.resize(nAttemptsTotal);
for (auto& row : puzzle->grid) {
row.resize(nLettersPerWord);
}
Puzzle* puzzlePtr = puzzle.get();
puzzles.push_back(std::move(puzzle));
return puzzlePtr;
}
// searches for a saved puzzle with a certain ID and returns a pointer to it.
// if a saved puzzle with a certain ID does not exist, it's created.
Puzzle* getPuzzle(int puzzleId) {
auto it = std::find_if(puzzles.begin(), puzzles.end(), [puzzleId](const auto& puzzle) { return puzzle->id == puzzleId; });
if (it == puzzles.end()) {
return createPuzzle(puzzleId);
}
return it->get();
}
// switches the current puzzle
void switchPuzzle(int puzzId) {
const int latestPuzzleId = puzzleId();
currentPuzzle = getPuzzle(std::min(puzzId, latestPuzzleId));
// currently unneeded, as the latest puzzle can't change, because the used timestamp is taken once at the start of the game
//currentPuzzle->countTowardsStats = currentPuzzle->id == latestPuzzleId; // if the latest puzzle has changed, count the new latest puzzle towards statistics as well
// play quick cell flip animation
for (auto& row : currentPuzzle->grid) {
for (int x = 0; x < nLettersPerWord; ++x) {
if (row[x].submitted()) {
row[x].tSubmit = ImGui::GetTime() + 0.2f*x*kTimeFlip;
}
}
}
// perform an update on the new puzzle
newInput = true;
}
// is any of the popup windows enabled?
bool hasPopup() const {
return help.showWindow ||
puzzlesWnd.showWindow ||
advert.showWindow ||
statistics.showWindow ||
settings.showWindow;
}
// call this at the start of each frame to initialize helper variables
void initRendering() {
isAnimating = false;
rendering.T = ImGui::GetTime();
rendering.wSize = ImGui::GetContentRegionAvail();
}
// when there is an active animation, call this method to disable any framerate throttling that may occur
// the argument i is an interpolation factor of the animation
// - if it is within (0, 1) then the animation is in progress
// - if it is >= 1 then the animation has finished
// - if it is < 0 then the animation will start soon
// - if it is == 0 then the animation is disabled
//
void animation(float i) {
isAnimating |= (i != 0.0f && i < 1.0f);
}
// add any logic that should happen upon window resize
void onWindowResize() {
}
// compute the current puzzle Id based on the timestamp of loading the game
// - each puzzle lasts 24 hours
// - the first puzzle started on kTimestamp0
//
int puzzleId() const {
return std::max(0, (int)((timestamp - kTimestamp0)/(24*3600)));
}
// compute the timestamp of the next puzzle
int64_t nextPuzzleTimestamp() const {
return kTimestamp0 + 24*3600*(puzzleId() + 1);
}
// compute how much time has left for the current puzzle
// returns a string formatted as hh:mm:ss
std::string timeLeft(const double T) const {
const int64_t t = std::max(0.0, nextPuzzleTimestamp() - (timestamp + T));
const int h = t/3600;
const int m = (t - h*3600)/60;
const int s = (t - h*3600 - m*60);
const std::string sh = h >= 10 ? std::to_string(h) : "0" + std::to_string(h);
const std::string sm = m >= 10 ? std::to_string(m) : "0" + std::to_string(m);
const std::string ss = s >= 10 ? std::to_string(s) : "0" + std::to_string(s);
return sh + ":" + sm + ":" + ss;
}
// has the game finished ?
bool finished(float T) const {
return currentPuzzle->isFinished && T > currentPuzzle->tFinished &&
(currentPuzzle->isGuessed == false || currentPuzzle->tFinished + kTimeGuessed > T);
}
// helper method to determine the color of the key on the on-screen keyboard
// <Foreground, Background>
std::pair<TColor, TColor> colKey(const std::string & ch, const TColorTheme & colors) {
if (currentPuzzle->keys.find(ch) == currentPuzzle->keys.end()) return { colors.at(EColor::Text), colors.at(EColor::KeyboardUnused), };
switch (currentPuzzle->keys.at(ch)) {
case Cell::Absent: return { colors.at(EColor::TextSubmitted), colors.at(EColor::AbsentFill), };
case Cell::Present: return { colors.at(EColor::TextSubmitted), colors.at(EColor::PresentFill), };
case Cell::Correct: return { colors.at(EColor::TextSubmitted), colors.at(EColor::CorrectFill), };
default: return { colors.at(EColor::TextSubmitted), colors.at(EColor::KeyboardUnused), };
}
return { colors.at(EColor::Text), colors.at(EColor::KeyboardUnused), };
}
// do the attempts so far satisfy the Hard Mode rules?
bool isHardMode() {
struct Limit {
int lower; // known minimum number of occurances of the letter
int upper; // known maximum number of occurances of the letter
// the letter cannot be in the following positions:
std::vector<bool> np;
};
// initialize the known limits for each letter
std::map<std::string, Limit> limits;
for (auto ch : kAlphabet) {
limits[ch] = { 0, nLettersPerWord, std::vector<bool>(nLettersPerWord, false) };
}
const int nAttempts = currentPuzzle->attempts.size();
for (int y = 0; y < nAttempts; ++y) {
if (y > 0) {
for (int x = 0; x < nLettersPerWord; ++x) {
// once correctly guess, the letter should remain correct for the rest of the attempts
if (currentPuzzle->grid[y-1][x].type == Cell::Correct && currentPuzzle->grid[y][x].type != Cell::Correct) {
return false;
}
}
}
for (int x = 0; x < nLettersPerWord; ++x) {
// check if we known that the letter ch cannot be at position x
if (limits[currentPuzzle->grid[y][x].data].np[x]) {
return false;
}
if (currentPuzzle->grid[y][x].type != Cell::Correct) {
limits[currentPuzzle->grid[y][x].data].np[x] = true;
}
}
std::map<std::string, std::pair<int, int>> cnt;
// count how many times the letter occurs in current attempt
// also, count the number of times the letter was marked as Present or Correct (i.e. non-Absent)
for (int x = 0; x < nLettersPerWord; ++x) {
const auto & ch = currentPuzzle->grid[y][x].data;
auto & nInput = cnt[ch].first;
auto & nNonAbsent = cnt[ch].second;
nInput++;
if (currentPuzzle->grid[y][x].type != Cell::Absent) nNonAbsent++;
}
// limits check - each letter in the new attempt must be within the currently known limits
for (const auto & [ch, c] : cnt) {
const auto & nInput = c.first;
if (nInput < limits[ch].lower || nInput > limits[ch].upper) {
return false;
}
}
// if we know a letter is present in the answer, it must be played in the new attempt
for (const auto & [ch, limit] : limits) {
if (limit.lower > 0 && cnt.find(ch) == cnt.end()) {
return false;
}
}
// update the limits based on the current attempt results
for (const auto & [ch, c] : cnt) {
const auto & nInput = c.first;
const auto & nNonAbsent = c.second;
// update the lower limit for the occurances of ch
limits[ch].lower = nNonAbsent;
// we know an upper limit for the occurances of ch
// for example: input contains ch 2 times and only one is Correct or Present => there is only one ch in the answer
if (nInput > nNonAbsent) {
limits[ch].upper = nNonAbsent;
}
}
}
return true;
}
// update the state of the game:
// - grid cell colors
// - keyboard colors
// - has the game finished?
//
// must be called on every frame
//
void update(const float T) {
if (newInput == false) return;
//currentPuzzle->isGuessed = false;
const bool wasFinished = currentPuzzle->isFinished;
const int nAttempts = currentPuzzle->attempts.size();
for (int y = 0; y < nAttemptsTotal; ++y) {
if (y < nAttempts) {
const auto & curAttempt = currentPuzzle->attempts[y];
std::vector<bool> used(nLettersPerWord, false);
std::vector<Cell::Type> guesses(nLettersPerWord, Cell::Absent);
int nCorrect = 0;
for (int x = 0; x < nLettersPerWord; ++x) {
// initialize used keys as Absent
if (currentPuzzle->keys.find(::utf8_ch(curAttempt, x)) == currentPuzzle->keys.end()) {
currentPuzzle->keys[::utf8_ch(curAttempt, x)] = Cell::Absent;
}
// first detect Correct letters/keys
if (::utf8_cmp(curAttempt, x, currentPuzzle->answer, x)) {
currentPuzzle->keys[::utf8_ch(curAttempt, x)] = Cell::Correct;
guesses[x] = Cell::Correct;
used[x] = true;
++nCorrect;
}
}
// we have a guessed word -> end the game and update stats
if (currentPuzzle->isFinished == false && nCorrect == nLettersPerWord) {
if (currentPuzzle->isInitialized && currentPuzzle->countTowardsStats) {
statistics.guesses[y]++;
statistics.nPlayed++;
statistics.streakCur++;
if (statistics.streakMax < statistics.streakCur) {
statistics.streakMax = statistics.streakCur;
}
}
currentPuzzle->isGuessed = true;
currentPuzzle->isFinished = true;
}
// next detect Present letters/keys
for (int x = 0; x < nLettersPerWord; ++x) {
if (guesses[x] != Cell::Absent) continue;
for (int i = 0; i < nLettersPerWord; ++i) {
if (x == i) continue;
if (used[i]) continue;
if (::utf8_cmp(curAttempt, x, currentPuzzle->answer, i)) {
if (currentPuzzle->keys[::utf8_ch(curAttempt, x)] < Cell::Correct) {
currentPuzzle->keys[::utf8_ch(curAttempt, x)] = Cell::Present;
}
guesses[x] = Cell::Present;
used[i] = true;
break;
}
}
}
// fill in the cells on the current row with the corresponding states and trigger animations
for (int x = 0; x < nLettersPerWord; ++x) {
auto & curCell = currentPuzzle->grid[y][x];
if (curCell.submitted() == false) {
curCell.data = ::utf8_ch(curAttempt, x);
curCell.type = guesses[x];
if (currentPuzzle->isInitialized) {
curCell.tSubmit = T + 1.0f*x*kTimeFlip;
if (x == 0) updateDataAttempts();
} else {
curCell.tSubmit = T + 0.2f*x*kTimeFlip;
}
}
}
}
if (y == nAttempts) {
const auto & curAttempt = currentPuzzle->attemptCur;
// number of letters provided so far
const int n = ::utf8_size(curAttempt);
// mark the provided cells as Pending
for (int x = 0; x < n; ++x) {
auto & curCell = currentPuzzle->grid[y][x];
if (curCell.type == Cell::Empty) {
curCell.tSubmit = T;
}
curCell.data = ::utf8_ch(curAttempt, x);
curCell.type = Cell::Pending;
}
if (n == nLettersPerWord) {
// if the pending word exists - color the Enter key to give a hint
bool found = false;
for (const auto & word : words) {
if (word == currentPuzzle->attemptCur) {
found = true;
break;
}
}
if (found) {
currentPuzzle->keys[kInputEnter] = Cell::Correct;
} else {
currentPuzzle->keys[kInputEnter] = Cell::Empty;
}
} else {
// mark the cells without input as Empty
for (int x = n; x < nLettersPerWord; ++x) {
auto & curCell = currentPuzzle->grid[y][x];
curCell.data = "";
curCell.type = Cell::Empty;
}
currentPuzzle->keys[kInputEnter] = Cell::Empty;
}
}
}
// failed to guess the word -> end the game + update stats
if (currentPuzzle->isFinished == false) {
currentPuzzle->isFinished = nAttemptsTotal == nAttempts;
if (currentPuzzle->isFinished) {
if (currentPuzzle->isInitialized && currentPuzzle->countTowardsStats) {
statistics.nPlayed++;
statistics.streakCur = 0;
}
}
}
// the game ended during the current update call -> queue Statistics window to be shown automatically
if (currentPuzzle->isFinished && wasFinished == false && currentPuzzle->countTowardsStats) {
if (currentPuzzle->isInitialized) {
statistics.showWindow = true;
statistics.tShow = T + (1.0f*nLettersPerWord)*kTimeFlip + 1.0f*kTimeGuessed;
} else {
statistics.showWindow = true;
statistics.tShow = T + (0.2f*nLettersPerWord)*kTimeFlip + 2.0f*kTimeFlip;
}
}
// the game has ended -> send new Statistics data to the JS layer
// it will be stored in the browser's localStorage in order to be persisted for the next round
if (currentPuzzle->isInitialized && currentPuzzle->isFinished && !wasFinished) {
currentPuzzle->tFinished = T + 1.0f*nLettersPerWord*kTimeFlip;
updateDataStatistics();
}
currentPuzzle->isInitialized = true;
newInput = false;
}
// error string upon incorrect input
const char * textIncorrect() const {
switch (currentPuzzle->eIncorrect) {
case Puzzle::TypeIncorrect::NotAWord: return "Непозната дума";
case Puzzle::TypeIncorrect::NotEnoughLetters: return "Недостатъчно букви";
};
return "";
}
// strings upon completion of the game
const char * textFinished() const {
// success strings
if (currentPuzzle->isGuessed) {
if (currentPuzzle->attempts.size() == 1) return "Гений";
if (currentPuzzle->attempts.size() == 2) return "Невероятно";
if (currentPuzzle->attempts.size() == 3) return "Отлично";
if (currentPuzzle->attempts.size() == 4) return "Браво";
if (currentPuzzle->attempts.size() == 5) return "Не е зле";
if (currentPuzzle->attempts.size() == 6) return "За малко";
return "Браво"; // fallback - should never happen
}
// upon failure -> show the answer
return currentPuzzle->answer.c_str();
}
// update the dataAttempts member - to be consumed by the JS layer
void updateDataAttempts() {
for (const auto & cur : currentPuzzle->attempts) {
currentPuzzle->dataAttempts += cur;
currentPuzzle->dataAttempts += " ";
}
currentPuzzle->dataAttempts.pop_back();
}
// update the dataStatistics member - to be consumed by the JS layer
void updateDataStatistics() {
dataStatistics = std::to_string(statistics.nPlayed);
dataStatistics += " ";
dataStatistics += std::to_string(statistics.streakCur);
dataStatistics += " ";
dataStatistics += std::to_string(statistics.streakMax);
dataStatistics += " ";
dataStatistics += std::to_string(nAttemptsTotal);
dataStatistics += " ";
for (int i = 0; i < nAttemptsTotal; ++i) {
dataStatistics += std::to_string(statistics.guesses[i]);
dataStatistics += " ";
}
dataStatistics.pop_back();
}
// update the dataClipboard member - to be consumed by the JS layer
void updateDataClipboard(const TColorTheme & colors) {
const int n = currentPuzzle->attempts.size();
const std::string special = isHardMode() ? "*" : "";
const std::string tries = currentPuzzle->isGuessed ? std::to_string(n) : "X";
dataClipboard = std::string(kTitleClipboard) + " " + (currentPuzzle->id < 0 ? "\"" + currentPuzzle->answer + "\"" : std::to_string(currentPuzzle->id))
+ " " + tries + "/" + std::to_string(nAttemptsTotal) + special + "\n\n";
for (int y = 0; y < n; ++y) {
for (int x = 0; x < nLettersPerWord; ++x) {
switch (currentPuzzle->grid[y][x].type) {
case Cell::Absent: dataClipboard += kGridEmojis.at(colors.at(EColor::AbsentFill)); break;
case Cell::Present: dataClipboard += kGridEmojis.at(colors.at(EColor::PresentFill)); break;
case Cell::Correct: dataClipboard += kGridEmojis.at(colors.at(EColor::CorrectFill)); break;
default: dataClipboard += kGridEmojis.at(colors.at(EColor::AbsentFill)); break;
};
}
dataClipboard += "\n";
}
dataClipboard += "\n";