-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypingMaster.cpp
More file actions
940 lines (859 loc) · 33.7 KB
/
TypingMaster.cpp
File metadata and controls
940 lines (859 loc) · 33.7 KB
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
// TypingMaster.cpp
#include "TypingMaster.h"
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <thread>
#ifdef _WIN32
#include <windows.h>
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
#endif
#ifndef _WIN32
#include <unistd.h>
#endif
#ifdef _WIN32
#define SLEEP_MS(ms) Sleep(ms)
#else
#define SLEEP_MS(ms) usleep((ms) * 1000)
#endif
TypingMaster::TypingMaster() //initializer list
: caseSensitive(false), //not treat capital and small letters differently
colorsEnabled(true), //sets colors enable to true. The program will use colored text in console
unicodeUI(true), //This makes the UI look more modern By using emojis,accented letters etc.
soundEnabled(true), //The typing tutor will play beeps, clicks or success sounds if implemented.If the user disables sound, this becomes false.
currentLevelIndex(0); //The user starts at level 0 when the program begins
// Basic rule-of-thumb to enable/disable ANSI colors
// Respect NO_COLOR if set
if (std::getenv("NO_COLOR")) //standard library file reads environment variables from OS. if environment exist then it returns a pointer to its value
{
colorsEnabled = false;
}
if (std::getenv("NO_SOUND")) //only executes next line if variable exists
{
soundEnabled = false;
}
configureConsoleCapabilities();//Ensures the console behaves correctly on Windows and Linux/macOS.
initLevels(); //Initializes typing levels.Loading text passages.Setting speed/difficulty parameters.
resetSessionStats(); //Resets all typing statistics for a new session. Ensures each typing session starts fresh.
// Load users DB (dummy CSV)
loadDatabase(); //Loads user data from a file (CSV file which stores data in tabular form including user names,high scores, past session statistics).
}
void TypingMaster::run() //main driver function,load settings
{
if (currentUser.empty()) {
loginOrRegister();
}
while (true) {
clearScreen();
showWelcome();
int choice = showMainMenu();
if (choice == 1) {
startGame();
} else if (choice == 2) {
int sel = showLevelSelect();
if (sel >= 0 && sel < static_cast<int>(levels.size())) {
currentLevelIndex = sel;
startGame();
}
} else if (choice == 3) {
showStatistics();
std::cout << "\nPress Enter to return to menu...";
std::string tmp;
std::getline(std::cin, tmp);
} else if (choice == 4) {
showHowToPlay();
std::cout << "\nPress Enter to return to menu...";
std::string tmp;
std::getline(std::cin, tmp);
} else if (choice == 5) {
showUserProfile();
std::cout << "\nPress Enter to return to menu...";
std::string tmp;
std::getline(std::cin, tmp);
} else if (choice == 6) {
loginOrRegister();
} else if (choice == 7) {
startMultiplayer();
} else if (choice == 8) {
clearScreen();
std::cout << "Goodbye! Keep practicing! ⌨️\n";
saveDatabase();
break;
}
}
}
// ---------- UI helpers ----------
void TypingMaster::clearScreen() const {
#ifdef _WIN32
std::system("cls");
#else
std::system("clear");//for operating system other than windows
#endif
}
void TypingMaster::drawBorder(int width) const {
std::cout << borderTopLeft();
for (int i = 0; i < width - 2; ++i) std::cout << borderHorizontal();
std::cout << borderTopRight() << "\n";
}
void TypingMaster::printCentered(const std::string& text, int width) const {
int pad = (width - static_cast<int>(text.size())) / 2;
if (pad < 0) pad = 0;
std::cout << borderVertical() << std::string(pad, ' ') << text
<< std::string(std::max(0, width - 2 - pad - static_cast<int>(text.size())), ' ')
<< borderVertical() << "\n";
}
void TypingMaster::printHeader(const std::string& title, const std::string& subtitle) const {
const int width = 76;
drawBorder(width);
printCentered(std::string("Typing Master ") + emojiOr("🎯", "[*]"), width);
printCentered(title, width);
if (!subtitle.empty()) printCentered(subtitle, width);
std::cout << borderSeparatorLeft();
for (int i = 0; i < width - 2; ++i) std::cout << borderHorizontal();
std::cout << borderSeparatorRight() << "\n";
}
std::string TypingMaster::progressBar(double ratio, int width) const {
if (ratio < 0.0) ratio = 0.0;
if (ratio > 1.0) ratio = 1.0;
int filled = static_cast<int>(ratio * width + 0.5);
std::string bar = "[";
for (int i = 0; i < width; ++i) {
bar += (i < filled) ? (unicodeUI ? "█" : "#") : (unicodeUI ? "░" : ".");
}
bar += "] ";
int percent = static_cast<int>(ratio * 100.0 + 0.5);
bar += std::to_string(percent) + "%";
return bar;
}
std::string TypingMaster::colorGreen() const { return colorsEnabled ? "\x1b[32m" : ""; }
std::string TypingMaster::colorRed() const { return colorsEnabled ? "\x1b[31m" : ""; }
std::string TypingMaster::colorYellow() const { return colorsEnabled ? "\x1b[33m" : ""; }
std::string TypingMaster::colorCyan() const { return colorsEnabled ? "\x1b[36m" : ""; }
std::string TypingMaster::colorBlue() const { return colorsEnabled ? "\x1b[34m" : ""; }
std::string TypingMaster::colorMagenta() const { return colorsEnabled ? "\x1b[35m" : ""; }
std::string TypingMaster::colorReset() const { return colorsEnabled ? "\x1b[0m" : ""; }
std::string TypingMaster::borderTopLeft() const { return unicodeUI ? "╔" : "+"; }
std::string TypingMaster::borderTopRight() const { return unicodeUI ? "╗" : "+"; }
std::string TypingMaster::borderBottomLeft() const { return unicodeUI ? "╚" : "+"; }
std::string TypingMaster::borderBottomRight() const { return unicodeUI ? "╝" : "+"; }
std::string TypingMaster::borderHorizontal() const { return unicodeUI ? "═" : "-"; }
std::string TypingMaster::borderVertical() const { return unicodeUI ? "║" : "|"; }
std::string TypingMaster::borderSeparatorLeft() const { return unicodeUI ? "╠" : "+"; }
std::string TypingMaster::borderSeparatorRight() const { return unicodeUI ? "╣" : "+"; }
std::string TypingMaster::emojiOr(const std::string& emoji, const std::string& ascii) const {
return unicodeUI ? emoji : ascii;
}
// ---------- Sound helpers ----------
void TypingMaster::playKeyClick(int count) const {
if (!soundEnabled) return;
#ifdef _WIN32
for (int i = 0; i < count; ++i) {
Beep(1200, 35);
SLEEP_MS(5);
}
#else
for (int i = 0; i < count; ++i) {
std::cout << '\a' << std::flush;
SLEEP_MS(20);
}
#endif
}
void TypingMaster::playBackspaceClick(int count) const {
if (!soundEnabled) return;
#ifdef _WIN32
for (int i = 0; i < count; ++i) {
Beep(600, 25);
SLEEP_MS(5);
}
#else
for (int i = 0; i < count; ++i) {
std::cout << '\a' << std::flush;
SLEEP_MS(25);
}
#endif
}
void TypingMaster::playSuccessTone() const {
if (!soundEnabled) return;
#ifdef _WIN32
Beep(1400, 60);
Beep(1700, 80);
#else
std::cout << '\a' << std::flush;
#endif
}
void TypingMaster::playErrorTone() const {
if (!soundEnabled) return;
#ifdef _WIN32
Beep(400, 120);
#else
std::cout << '\a' << std::flush;
#endif
}
// ---------- Screens ----------
void TypingMaster::showWelcome() const {
std::string subtitle = "Educational Typing Game";
if (!currentUser.empty()) subtitle += " | User: " + currentUser;
printHeader("Welcome to Typing Master ⌨️", subtitle);
std::cout << borderVertical() << " " << colorCyan() << "Practice levels:" << colorReset() << "\n";
std::cout << borderVertical() << " 1) Home Row - Left Hand (A S D F)\n";
std::cout << borderVertical() << " 2) Home Row - Both Hands (A S D F J K L ;)\n";
std::cout << borderVertical() << " 3) Top Row & Numbers (1-5, Q-P)\n";
std::cout << borderVertical() << " 4) Full Keyboard Mastery\n";
std::cout << borderVertical() << " 5) Speed Challenge (Sentences)\n";
std::cout << borderVertical() << "\n";
std::cout << borderVertical() << " " << colorYellow() << "Scoring:" << colorReset()
<< " 10 points per correct word. Accuracy influences rating.\n";
std::cout << borderVertical() << " " << colorYellow() << "Tips:" << colorReset()
<< " Keep your fingers on home row. Focus on accuracy, then speed.\n";
std::cout << borderBottomLeft();
for (int i = 0; i < 74; ++i) std::cout << borderHorizontal();
std::cout << borderBottomRight() << "\n\n";
}
void TypingMaster::showHowToPlay() const {
clearScreen();
printHeader("How to Play 📝", "Keyboard Positioning & Tips");
std::cout << borderVertical() << " Place your fingers on the " << colorCyan() << "home row" << colorReset()
<< ": A S D F (left) and J K L ; (right).\n";
std::cout << borderVertical() << " Each level shows target keys/words. Type the shown item and press Enter.\n";
std::cout << borderVertical() << " You have a " << colorYellow() << "time limit" << colorReset()
<< " per level. Results include accuracy, WPM estimate, and score.\n";
std::cout << borderVertical() << " Feedback is " << colorGreen() << emojiOr("✅","OK")
<< " correct" << colorReset() << " or "
<< colorRed() << "❌ incorrect" << colorReset() << ".\n";
std::cout << borderVertical() << " Keep posture relaxed. Aim for " << colorYellow() << "accuracy first" << colorReset()
<< ", then increase speed.\n";
std::cout << borderBottomLeft();
for (int i = 0; i < 74; ++i) std::cout << borderHorizontal();
std::cout << borderBottomRight() << "\n";
}
void TypingMaster::showStatistics() const {
clearScreen();
printHeader("Session Statistics 📊");
std::cout << std::fixed << std::setprecision(2);
std::cout << borderVertical() << " Words Attempted: " << sessionStats.wordsAttempted << "\n";
std::cout << borderVertical() << " Correct Words: " << sessionStats.wordsCorrect << "\n";
std::cout << borderVertical() << " Wrong Words: " << sessionStats.wordsWrong << "\n";
std::cout << borderVertical() << " Accuracy: " << sessionStats.accuracy << "%\n";
std::cout << borderVertical() << " Total Time: " << sessionStats.totalTimeSeconds << "s\n";
double wpm = computeWpm(sessionStats.wordsAttempted, sessionStats.totalTimeSeconds);
std::cout << borderVertical() << " Speed (WPM): " << wpm << "\n";
std::cout << borderVertical() << " Score: " << sessionStats.score << "\n";
std::cout << borderVertical() << " Rating: " << performanceStars(sessionStats.accuracy) << "\n";
std::cout << borderBottomLeft();
for (int i = 0; i < 74; ++i) std::cout << borderHorizontal();
std::cout << borderBottomRight() << "\n";
}
int TypingMaster::showMainMenu() {
std::cout << "1) Start Game ▶\n";
std::cout << "2) Select Level 🎯\n";
std::cout << "3) View Statistics 📈\n";
std::cout << "4) How to Play 📚\n";
std::cout << "5) View Profile 👤\n";
std::cout << "6) Switch User 🔐\n";
std::cout << "7) Multiplayer Duel 🆚\n";
std::cout << "8) Exit 🚪\n\n";
std::cout << "Enter choice: ";
std::string line;
std::getline(std::cin, line);
if (line.empty()) return 1;
int c = std::atoi(line.c_str());
if (c < 1 || c > 8) c = 1;
return c;
}
int TypingMaster::showLevelSelect() {
clearScreen();
printHeader("Select Level 🎯");
for (size_t i = 0; i < levels.size(); ++i) {
std::cout << (i + 1) << ") " << levels[i].name << " - " << levels[i].description << "\n";
}
std::cout << "\nEnter level number (1-" << levels.size() << ", or 0 to cancel): ";
std::string line;
std::getline(std::cin, line);
int pick = std::atoi(line.c_str());
if (pick <= 0 || pick > static_cast<int>(levels.size())) return currentLevelIndex;
return pick - 1;
}
// ---------- Game flow ----------
void TypingMaster::initLevels() {
levels.clear();
// Level 1
levels.push_back(LevelConfig{
1,
"Level 1: Home Row - Left Hand",
"Keys: A S D F. Build left-hand muscle memory.",
{'a','s','d','f'},
{
"a","s","d","f","as","sa","ad","da","af","fa","sad","dad","fad","saf","ads"
},
10,
30,
false
});
// Level 2
levels.push_back(LevelConfig{
2,
"Level 2: Home Row - Both Hands",
"Keys: A S D F J K L ;. Extend to right hand.",
{'a','s','d','f','j','k','l',';'},
{
"sad","ask","all","fall","jazz","lad","ask","sass","flask","skid",
"askal","salad","alls","dusk","flak"
},
10,
30,
false
});
// Level 3
levels.push_back(LevelConfig{
3,
"Level 3: Top Row & Numbers",
"Keys: 1-5, Q W E R T Y U I O P. Add top row.",
{'1','2','3','4','5','q','w','e','r','t','y','u','i','o','p'},
{
"quiet","tweet","query","type","riot","twerp","quip5","3tier","worry","piety",
"4you","tryout","equip","power","trio"
},
10,
30,
false
});
// Level 4
levels.push_back(LevelConfig{
4,
"Level 4: Full Keyboard Mastery",
"Keys: Full keyboard. Complex 7-8 letter words.",
{
// representative set; validation remains template-driven for learning
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9',
';',',','.','/','\'','[',']','\\','-','='
},
{
"balance","keyboard","accurate","practice","develop","compute","program","clarity",
"rhythm","sustain","iterate","resolve","texture","journey","academy"
},
10,
30,
false
});
// Level 5
levels.push_back(LevelConfig{
5,
"Level 5: Speed Challenge",
"Sentences and phrases. Focus on speed and accuracy.",
{
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9',' ',',','.',';','\'','-'
},
{
"Practice makes perfect, keep your fingers on home row",
"Accuracy first then speed will naturally improve",
"Type with rhythm and breathe steadily as you go",
"Keep posture upright and relax your shoulders",
"Challenge yourself but celebrate small progress"
},
5,
60,
true
});
}
void TypingMaster::startGame() {
resetSessionStats();
// Play from selected level through all following levels
for (int i = currentLevelIndex; i < static_cast<int>(levels.size()); ++i) {
playLevel(i);
std::cout << "\nPress Enter to continue...";
std::string tmp;
std::getline(std::cin, tmp);
}
}
void TypingMaster::printLevelIntro(const LevelConfig& level) const {
clearScreen();
printHeader(level.name, level.description);
std::cout << "║ " << colorYellow() << "Items:" << colorReset() << " " << level.itemCount
<< " " << colorYellow() << "Time Limit:" << colorReset() << " "
<< level.timeLimitSeconds << "s "
<< colorYellow() << "Case:" << colorReset() << " "
<< (caseSensitive ? "Sensitive" : "Insensitive") << "\n";
std::cout << "║ Keep fingers on home row. Type each item, then press Enter.\n";
std::cout << "╚";
for (int i = 0; i < 74; ++i) std::cout << borderHorizontal();
std::cout << "╝\n\n";
}
void TypingMaster::playLevel(int levelIndex) {
const LevelConfig& level = levels[levelIndex];
printLevelIntro(level);
// Prepare templates
std::vector<std::string> items = level.templates;
shuffleVector(items); // randomize order
if (static_cast<int>(items.size()) > level.itemCount) {
items.resize(level.itemCount);
}
Stats levelStats;
auto startTime = std::chrono::steady_clock::now();
for (int i = 0; i < static_cast<int>(items.size()); ++i) {
if (timeExceeded(startTime, level.timeLimitSeconds)) {
std::cout << colorRed() << emojiOr("⏱️","[TIMER]") << " Time's up!" << colorReset() << "\n";
break;
}
double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - startTime).count();
double remain = std::max(0.0, static_cast<double>(level.timeLimitSeconds) - elapsed);
double ratio = static_cast<double>(i) / static_cast<double>(items.size());
std::cout << colorBlue() << "Progress " << progressBar(ratio) << colorReset()
<< " " << colorMagenta() << emojiOr("⏱️","[T]") << " " << static_cast<int>(remain) << "s" << colorReset() << "\n";
std::cout << "Target: " << colorCyan() << items[i] << colorReset() << "\n";
std::cout << "Type : ";
std::string typed;
std::getline(std::cin, typed);
typed = trim(typed);
playKeyClick(static_cast<int>(typed.size()));
++levelStats.wordsAttempted;
bool ok = equals(typed, items[i], caseSensitive);
if (ok) {
++levelStats.wordsCorrect;
levelStats.score += 10;
std::cout << colorGreen() << emojiOr("✅","OK") << " Correct!" << colorReset() << "\n\n";
playSuccessTone();
} else {
++levelStats.wordsWrong;
std::cout << colorRed() << (unicodeUI ? "❌" : "X") << " Incorrect" << colorReset()
<< " Expected: " << colorCyan() << items[i] << colorReset() << "\n\n";
playBackspaceClick(2);
playErrorTone();
}
}
auto endTime = std::chrono::steady_clock::now();
levelStats.totalTimeSeconds = std::chrono::duration<double>(endTime - startTime).count();
if (levelStats.wordsAttempted > 0) {
levelStats.accuracy = 100.0 * static_cast<double>(levelStats.wordsCorrect) / static_cast<double>(levelStats.wordsAttempted);
}
// Show results
std::cout << "──────── Level Results ────────\n";
std::cout << "Attempted: " << levelStats.wordsAttempted
<< " | Correct: " << levelStats.wordsCorrect
<< " | Wrong: " << levelStats.wordsWrong << "\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << "Accuracy: " << levelStats.accuracy << "% | "
<< "Time: " << levelStats.totalTimeSeconds << "s | ";
double levelWpm = computeWpm(levelStats.wordsAttempted, levelStats.totalTimeSeconds);
std::cout << "WPM: " << levelWpm << " | "
<< "Score: " << levelStats.score << "\n";
std::cout << "Rating: " << performanceStars(levelStats.accuracy) << " "
<< encouragement(levelStats.accuracy) << "\n";
if (levelWpm < 25.0) {
std::cout << colorYellow() << "Tip: " << speedSuggestion(levelWpm, levelStats.accuracy) << colorReset() << "\n";
}
accumulateSessionStats(levelStats);
updateUserWithLevelStats(levelStats);
}
void TypingMaster::playLevelWithItems(int levelIndex, const std::vector<std::string>& itemsIn, Stats& levelStats) {
const LevelConfig& level = levels[levelIndex];
printLevelIntro(level);
std::vector<std::string> items = itemsIn;
auto startTime = std::chrono::steady_clock::now();
for (int i = 0; i < static_cast<int>(items.size()); ++i) {
if (timeExceeded(startTime, level.timeLimitSeconds)) {
std::cout << colorRed() << emojiOr("⏱️","[TIMER]") << " Time's up!" << colorReset() << "\n";
break;
}
double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - startTime).count();
double remain = std::max(0.0, static_cast<double>(level.timeLimitSeconds) - elapsed);
double ratio = static_cast<double>(i) / static_cast<double>(items.size());
std::cout << colorBlue() << "Progress " << progressBar(ratio) << colorReset()
<< " " << colorMagenta() << emojiOr("⏱️","[T]") << " " << static_cast<int>(remain) << "s" << colorReset() << "\n";
std::cout << "Target: " << colorCyan() << items[i] << colorReset() << "\n";
std::cout << "Type : ";
std::string typed;
std::getline(std::cin, typed);
typed = trim(typed);
playKeyClick(static_cast<int>(typed.size()));
++levelStats.wordsAttempted;
bool ok = equals(typed, items[i], caseSensitive);
if (ok) {
++levelStats.wordsCorrect;
levelStats.score += 10;
std::cout << colorGreen() << emojiOr("✅","OK") << " Correct!" << colorReset() << "\n\n";
playSuccessTone();
} else {
++levelStats.wordsWrong;
std::cout << colorRed() << (unicodeUI ? "❌" : "X") << " Incorrect" << colorReset()
<< " Expected: " << colorCyan() << items[i] << colorReset() << "\n\n";
playBackspaceClick(2);
playErrorTone();
}
}
auto endTime = std::chrono::steady_clock::now();
levelStats.totalTimeSeconds = std::chrono::duration<double>(endTime - startTime).count();
if (levelStats.wordsAttempted > 0) {
levelStats.accuracy = 100.0 * static_cast<double>(levelStats.wordsCorrect) / static_cast<double>(levelStats.wordsAttempted);
}
std::cout << "──────── Level Results ────────\n";
std::cout << "Attempted: " << levelStats.wordsAttempted
<< " | Correct: " << levelStats.wordsCorrect
<< " | Wrong: " << levelStats.wordsWrong << "\n";
std::cout << std::fixed << std::setprecision(2);
std::cout << "Accuracy: " << levelStats.accuracy << "% | "
<< "Time: " << levelStats.totalTimeSeconds << "s | ";
double levelWpm = computeWpm(levelStats.wordsAttempted, levelStats.totalTimeSeconds);
std::cout << "WPM: " << levelWpm << " | "
<< "Score: " << levelStats.score << "\n";
std::cout << "Rating: " << performanceStars(levelStats.accuracy) << " "
<< encouragement(levelStats.accuracy) << "\n";
if (levelWpm < 25.0) {
std::cout << colorYellow() << "Tip: " << speedSuggestion(levelWpm, levelStats.accuracy) << colorReset() << "\n";
}
}
std::vector<std::string> TypingMaster::generateLevelItems(int levelIndex, unsigned int seed) const {
const LevelConfig& level = levels[levelIndex];
std::vector<std::string> items = level.templates;
std::mt19937 gen(seed);
std::shuffle(items.begin(), items.end(), gen);
if (static_cast<int>(items.size()) > level.itemCount) {
items.resize(level.itemCount);
}
return items;
}
// ---------- Utilities ----------
std::string TypingMaster::trim(const std::string& s) {
size_t start = 0;
while (start < s.size() && std::isspace(static_cast<unsigned char>(s[start]))) ++start;
size_t end = s.size();
while (end > start && std::isspace(static_cast<unsigned char>(s[end - 1]))) --end;
return s.substr(start, end - start);
}
std::string TypingMaster::toLower(const std::string& s) {
std::string out;
out.reserve(s.size());
for (char c : s) out.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));
return out;
}
bool TypingMaster::equals(const std::string& a, const std::string& b, bool caseSensitive_) {
if (caseSensitive_) return a == b;
return toLower(a) == toLower(b);
}
void TypingMaster::shuffleVector(std::vector<std::string>& v) {
// Modern replacement for deprecated random_shuffle
std::random_device rd;
std::mt19937 gen(rd());
std::shuffle(v.begin(), v.end(), gen);
}
bool TypingMaster::timeExceeded(const std::chrono::steady_clock::time_point& start, int limitSeconds) {
double elapsed = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
return elapsed >= static_cast<double>(limitSeconds);
}
std::string TypingMaster::performanceStars(double accuracy) const {
if (accuracy >= 90.0) return "⭐⭐⭐⭐⭐ Excellent";
if (accuracy >= 80.0) return "⭐⭐⭐⭐ Very Good";
if (accuracy >= 70.0) return "⭐⭐⭐ Good";
if (accuracy >= 60.0) return "⭐⭐ Fair";
return "⭐ Keep Practicing";
}
std::string TypingMaster::encouragement(double accuracy) const {
if (accuracy >= 90.0) return "Superb consistency! 🎉";
if (accuracy >= 80.0) return "Great work—keep it up! 💪";
if (accuracy >= 70.0) return "Solid! Aim for fewer errors. 👍";
if (accuracy >= 60.0) return "You're getting there—focus on accuracy. 👀";
return "Keep going—practice builds skill! 🚀";
}
double TypingMaster::computeWpm(int wordsAttempted, double timeSeconds) {
if (timeSeconds <= 0.0) return 0.0;
double minutes = timeSeconds / 60.0;
return wordsAttempted / minutes;
}
std::string TypingMaster::speedSuggestion(double wpm, double accuracy) const {
// Simple, readable suggestions
if (wpm < 10.0) {
if (accuracy < 85.0) {
return "Slow and inaccurate—focus on accuracy first: keep eyes on text, use home row.";
}
return "Very slow—practice short bursts on home row (ASDF JKL;), keep a steady rhythm.";
}
if (wpm < 18.0) {
if (accuracy < 85.0) {
return "Tighten accuracy: type smaller chunks, reduce backspaces, and keep fingers anchored.";
}
return "Build speed with metronome: aim for even key presses and avoid looking at keyboard.";
}
if (wpm < 25.0) {
if (accuracy < 90.0) {
return "Accuracy dips—slow slightly, prioritize clean strokes, then ramp up speed.";
}
return "Good accuracy—push speed with timed drills and top-row practice (QWERTY).";
}
return "Keep it up! Increase difficulty or try the Speed Challenge.";
}
// ---------- Stats helpers ----------
void TypingMaster::resetSessionStats() {
sessionStats = Stats{};
}
void TypingMaster::accumulateSessionStats(const Stats& levelStats) {
sessionStats.wordsAttempted += levelStats.wordsAttempted;
sessionStats.wordsCorrect += levelStats.wordsCorrect;
sessionStats.wordsWrong += levelStats.wordsWrong;
sessionStats.score += levelStats.score;
sessionStats.totalTimeSeconds += levelStats.totalTimeSeconds;
if (sessionStats.wordsAttempted > 0) {
sessionStats.accuracy = 100.0 * static_cast<double>(sessionStats.wordsCorrect) / static_cast<double>(sessionStats.wordsAttempted);
} else {
sessionStats.accuracy = 0.0;
}
}
// ---------- Platform capabilities ----------
void TypingMaster::configureConsoleCapabilities() {
// Allow opt-out via environment
if (std::getenv("NO_UNICODE")) {
unicodeUI = false;
}
#ifdef _WIN32
// Try to enable UTF-8 output and VT sequences for colors
bool vtOk = false;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hOut != INVALID_HANDLE_VALUE && hOut != nullptr) {
DWORD mode = 0;
if (GetConsoleMode(hOut, &mode)) {
DWORD newMode = mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (SetConsoleMode(hOut, newMode)) {
vtOk = true;
}
}
}
// Set UTF-8 codepage (best-effort)
BOOL cpOk = SetConsoleOutputCP(CP_UTF8);
if (!cpOk) {
unicodeUI = false;
}
// If VT enabling failed, keep colors but many older consoles won't render them;
// user can disable via NO_COLOR
(void)vtOk;
#endif
}
// ---------- Auth/DB ----------
void TypingMaster::loadDatabase() {
std::ifstream in(dbFilePath);
if (!in) return;
std::string line;
while (std::getline(in, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
UserProfile p;
std::string field;
// CSV: username,passwordHash,gamesPlayed,totalWords,totalCorrect,totalTimeSeconds,highScore,bestAccuracy,bestWpm
std::getline(ss, p.username, ',');
std::getline(ss, field, ',');
if (!field.empty()) p.passwordHash = static_cast<std::size_t>(std::stoull(field));
std::getline(ss, field, ',');
p.gamesPlayed = field.empty() ? 0 : std::atoi(field.c_str());
std::getline(ss, field, ',');
p.totalWords = field.empty() ? 0 : std::atoi(field.c_str());
std::getline(ss, field, ',');
p.totalCorrect = field.empty() ? 0 : std::atoi(field.c_str());
std::getline(ss, field, ',');
p.totalTimeSeconds = field.empty() ? 0.0 : std::atof(field.c_str());
std::getline(ss, field, ',');
p.highScore = field.empty() ? 0 : std::atoi(field.c_str());
std::getline(ss, field, ',');
p.bestAccuracy = field.empty() ? 0.0 : std::atof(field.c_str());
std::getline(ss, field, ',');
p.bestWpm = field.empty() ? 0.0 : std::atof(field.c_str());
if (!p.username.empty()) {
users[p.username] = p;
}
}
}
void TypingMaster::saveDatabase() const {
std::ofstream out(dbFilePath, std::ios::trunc);
for (const auto& kv : users) {
const UserProfile& p = kv.second;
out << p.username << ","
<< static_cast<unsigned long long>(p.passwordHash) << ","
<< p.gamesPlayed << ","
<< p.totalWords << ","
<< p.totalCorrect << ","
<< p.totalTimeSeconds << ","
<< p.highScore << ","
<< p.bestAccuracy << ","
<< p.bestWpm << "\n";
}
}
void TypingMaster::loginOrRegister() {
clearScreen();
printHeader("Authentication 🔐", "Login or Register");
std::cout << "Username: ";
std::string uname;
std::getline(std::cin, uname);
uname = trim(uname);
if (uname.empty()) {
currentUser.clear();
return;
}
auto it = users.find(uname);
if (it == users.end()) {
// Register
std::cout << "Create Password: ";
std::string pw;
std::getline(std::cin, pw);
UserProfile p;
p.username = uname;
p.passwordHash = hashPassword(pw);
users[uname] = p;
currentUser = uname;
saveDatabase();
std::cout << colorGreen() << "User registered." << colorReset() << "\n";
} else {
// Login
std::cout << "Password: ";
std::string pw;
std::getline(std::cin, pw);
if (verifyPassword(uname, pw)) {
currentUser = uname;
std::cout << colorGreen() << "Login successful." << colorReset() << "\n";
} else {
std::cout << colorRed() << "Login failed." << colorReset() << "\n";
currentUser.clear();
}
}
}
bool TypingMaster::verifyPassword(const std::string& username, const std::string& password) const {
auto it = users.find(username);
if (it == users.end()) return false;
return it->second.passwordHash == hashPassword(password);
}
std::size_t TypingMaster::hashPassword(const std::string& password) {
// Dummy hash for demo purposes. For real systems, use bcrypt/argon2.
return std::hash<std::string>{}(password);
}
void TypingMaster::updateUserWithLevelStats(const Stats& levelStats) {
if (currentUser.empty()) return;
auto it = users.find(currentUser);
if (it == users.end()) return;
UserProfile& p = it->second;
p.gamesPlayed += 1;
p.totalWords += levelStats.wordsAttempted;
p.totalCorrect += levelStats.wordsCorrect;
p.totalTimeSeconds += levelStats.totalTimeSeconds;
if (levelStats.score > p.highScore) p.highScore = levelStats.score;
if (levelStats.accuracy > p.bestAccuracy) p.bestAccuracy = levelStats.accuracy;
double levelWpm = computeWpm(levelStats.wordsAttempted, levelStats.totalTimeSeconds);
if (levelWpm > p.bestWpm) p.bestWpm = levelWpm;
saveDatabase();
}
void TypingMaster::showUserProfile() const {
clearScreen();
printHeader("User Profile 👤", currentUser.empty() ? "No user" : currentUser);
if (currentUser.empty()) {
std::cout << "No user logged in.\n";
return;
}
auto it = users.find(currentUser);
if (it == users.end()) {
std::cout << "User not found.\n";
return;
}
const UserProfile& p = it->second;
std::cout << std::fixed << std::setprecision(2);
std::cout << borderVertical() << " Games Played: " << p.gamesPlayed << "\n";
std::cout << borderVertical() << " Total Words: " << p.totalWords << "\n";
std::cout << borderVertical() << " Total Correct: " << p.totalCorrect << "\n";
double overallAcc = p.totalWords > 0 ? 100.0 * (static_cast<double>(p.totalCorrect) / p.totalWords) : 0.0;
double overallWpm = computeWpm(p.totalWords, p.totalTimeSeconds);
std::cout << borderVertical() << " Overall Acc: " << overallAcc << "%\n";
std::cout << borderVertical() << " Overall WPM: " << overallWpm << "\n";
std::cout << borderVertical() << " Best Accuracy: " << p.bestAccuracy << "%\n";
std::cout << borderVertical() << " Best WPM: " << p.bestWpm << "\n";
std::cout << borderVertical() << " High Score: " << p.highScore << "\n";
std::cout << borderBottomLeft();
for (int i = 0; i < 74; ++i) std::cout << borderHorizontal();
std::cout << borderBottomRight() << "\n";
}
// ---------- Multiplayer ----------
std::string TypingMaster::selectExistingUser(const std::string& prompt, const std::string& exclude) const {
std::vector<std::string> names;
names.reserve(users.size());
for (const auto& kv : users) {
if (!exclude.empty() && kv.first == exclude) continue;
names.push_back(kv.first);
}
if (names.empty()) return "";
std::cout << prompt << "\n";
for (size_t i = 0; i < names.size(); ++i) {
std::cout << (i + 1) << ") " << names[i] << "\n";
}
std::cout << "Enter number (or 0 to cancel): ";
std::string line;
std::getline(std::cin, line);
int pick = std::atoi(line.c_str());
if (pick <= 0 || pick > static_cast<int>(names.size())) return "";
return names[static_cast<size_t>(pick - 1)];
}
void TypingMaster::startMultiplayer() {
if (currentUser.empty()) {
loginOrRegister();
if (currentUser.empty()) return;
}
int lvl = showLevelSelect();
if (lvl < 0 || lvl >= static_cast<int>(levels.size())) return;
// Pick opponent
std::cout << "\nSelect opponent user:\n";
std::string opponent = selectExistingUser("Available users:", currentUser);
if (opponent.empty()) {
std::cout << "No opponent selected. You can create one now.\n";
loginOrRegister();
opponent = currentUser;
if (opponent.empty()) return;
// Ensure opponent differs; if same, cancel
if (opponent == currentUser) {
std::cout << "Need a different user.\n";
return;
}
}
// Generate shared items with a fixed seed so both get same sequence
unsigned int seed = static_cast<unsigned int>(std::time(nullptr)) & 0xFFFFu;
std::vector<std::string> items = generateLevelItems(lvl, seed);
// Play for Player 1 (currentUser)
std::string originalUser = currentUser;
Stats p1;
playLevelWithItems(lvl, items, p1);
updateUserWithLevelStats(p1);
std::cout << "\nPress Enter to switch to opponent (" << opponent << ")...";
{
std::string tmp;
std::getline(std::cin, tmp);
}
// Play for Player 2 (opponent)
currentUser = opponent;
Stats p2;
playLevelWithItems(lvl, items, p2);
updateUserWithLevelStats(p2);
// Restore current user
currentUser = originalUser;
// Compare
double p1Wpm = computeWpm(p1.wordsAttempted, p1.totalTimeSeconds);
double p2Wpm = computeWpm(p2.wordsAttempted, p2.totalTimeSeconds);
std::cout << "\n──────── Multiplayer Results ────────\n";
std::cout << "Player 1 (" << originalUser << "): "
<< "Score " << p1.score << ", Acc " << std::fixed << std::setprecision(2) << p1.accuracy
<< "%, WPM " << p1Wpm << "\n";
std::cout << "Player 2 (" << opponent << "): "
<< "Score " << p2.score << ", Acc " << std::fixed << std::setprecision(2) << p2.accuracy
<< "%, WPM " << p2Wpm << "\n";
// Winner by score, then accuracy, then WPM
std::string winner;
if (p1.score != p2.score) winner = (p1.score > p2.score) ? originalUser : opponent;
else if (p1.accuracy != p2.accuracy) winner = (p1.accuracy > p2.accuracy) ? originalUser : opponent;
else if (p1Wpm != p2Wpm) winner = (p1Wpm > p2Wpm) ? originalUser : opponent;
else winner = "Tie";
if (winner == "Tie") {
std::cout << colorYellow() << "Result: It's a tie!" << colorReset() << "\n";
} else {
std::cout << colorGreen() << "Winner: " << winner << " 🎉" << colorReset() << "\n";
}
std::cout << "Press Enter to return to menu...";
{
std::string tmp;
std::getline(std::cin, tmp);
}
}