-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterminaltype.cpp
More file actions
598 lines (531 loc) · 21.2 KB
/
Copy pathterminaltype.cpp
File metadata and controls
598 lines (531 loc) · 21.2 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
#include <ncurses.h>
#include <string>
#include <vector>
#include <cctype>
#include <chrono>
#include <iomanip>
#include <sstream>
#include <random>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <ctime>
using namespace std;
// --- CONFIGURATION ---
enum GameMode { WORDS, TIME, QUOTE, BIBLE };
struct GameConfig {
GameMode mode;
int quantity;
string difficulty;
string target_text;
};
// --- DATA STRUCTURES ---
struct ScoreEntry {
time_t timestamp;
string mode_label;
int wpm;
double accuracy;
};
struct Quote {
string text;
string difficulty;
};
struct BibleVerse {
string book;
int chapter;
int verse;
string text;
};
// --- DATABASES ---
static const vector<Quote> quote_db = {
{"May the Force be with you.", "short"},
{"There's no place like home.", "short"},
{"I'll be back.", "short"},
{"Life is like a box of chocolates. You never know what you're gonna get.", "medium"},
{"I'm going to make him an offer he can't refuse.", "medium"},
{"The path of the righteous man is beset on all sides by the inequities of the selfish and the tyranny of evil men.", "long"}
};
// --- HELPER FUNCTIONS ---
bool is_separator(char c) { return ispunct(c) || isspace(c); }
bool is_word_delete(int ch) { return (ch == 8 || ch == 23); }
bool is_char_delete(int ch) { return (ch == KEY_BACKSPACE || ch == 127); }
string to_lower(string s) {
transform(s.begin(), s.end(), s.begin(), [](unsigned char c){ return tolower(c); });
return s;
}
// --- FILE I/O ---
string get_score_file_path() {
const char* home_dir = getenv("HOME");
if (!home_dir) return "terminaltype_scores.txt";
return string(home_dir) + "/.terminaltype_scores";
}
void save_score(string mode_label, int wpm, double acc) {
ofstream file(get_score_file_path(), ios::app);
if (file.is_open()) {
file << time(0) << "|" << mode_label << "|" << wpm << "|" << acc << "\n";
file.close();
}
}
vector<ScoreEntry> get_top_scores(string current_mode_label) {
vector<ScoreEntry> all_scores;
ifstream file(get_score_file_path());
if (!file.is_open()) return all_scores;
string line;
while (getline(file, line)) {
stringstream ss(line);
string segment;
vector<string> parts;
while (getline(ss, segment, '|')) parts.push_back(segment);
if (parts.size() == 4 && parts[1] == current_mode_label) {
ScoreEntry s;
s.timestamp = stol(parts[0]);
s.mode_label = parts[1];
s.wpm = stoi(parts[2]);
s.accuracy = stod(parts[3]);
all_scores.push_back(s);
}
}
file.close();
sort(all_scores.begin(), all_scores.end(), [](const ScoreEntry& a, const ScoreEntry& b) { return a.wpm > b.wpm; });
if (all_scores.size() > 3) all_scores.resize(3);
return all_scores;
}
// --- BIBLE LOADER ---
vector<BibleVerse> load_bible() {
vector<BibleVerse> bible;
vector<string> paths_to_check;
// 1. Check local directory (dev)
paths_to_check.push_back("kjv.csv");
// 2. Check Snap Environment (Production)
const char* snap = getenv("SNAP");
if (snap) {
string base = snap;
paths_to_check.push_back(base + "/bin/kjv.csv");
}
ifstream file;
for (const string& p : paths_to_check) {
file.open(p);
if (file.is_open()) break;
file.clear();
}
if (!file.is_open()) return bible;
string line;
while (getline(file, line)) {
stringstream ss(line);
string segment;
vector<string> row;
while (getline(ss, segment, ',')) {
row.push_back(segment);
}
if (row.size() >= 4) {
BibleVerse v;
v.book = row[0];
// Remove quotes if present
if (!v.book.empty() && v.book.front() == '"') v.book = v.book.substr(1, v.book.length()-2);
try {
v.chapter = stoi(row[1]);
v.verse = stoi(row[2]);
v.text = row[3];
// Handle commas inside the verse text
for (size_t i = 4; i < row.size(); i++) v.text += "," + row[i];
if (!v.text.empty() && v.text.front() == '"') v.text = v.text.substr(1, v.text.length()-2);
bible.push_back(v);
} catch (...) { continue; }
}
}
return bible;
}
// --- GENERATORS ---
string get_random_quote(string difficulty) {
vector<string> filtered;
for (const auto& q : quote_db) {
if (q.difficulty == difficulty) filtered.push_back(q.text);
}
if (filtered.empty()) return "I'll be back.";
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> distrib(0, filtered.size() - 1);
return filtered[distrib(gen)];
}
string generate_random_words(int num_words) {
static const char* word_bank[] = {
"the", "be", "of", "and", "a", "to", "in", "he", "have", "it",
"that", "for", "they", "I", "with", "as", "not", "on", "she", "at",
"by", "this", "we", "you", "do", "but", "from", "or", "which", "one",
"linux", "terminal", "code", "program", "typing", "test", "system", "computer",
"water", "fire", "earth", "air", "tree", "forest", "ocean", "river"
};
int bank_size = sizeof(word_bank) / sizeof(word_bank[0]);
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> distrib(0, bank_size - 1);
string result = "";
for (int i = 0; i < num_words; i++) {
result += word_bank[distrib(gen)];
if (i < num_words - 1) result += " ";
}
return result;
}
int parse_time_string(string input) {
if (input.find("-minute") != string::npos) {
size_t dash_pos = input.find('-');
return stoi(input.substr(0, dash_pos)) * 60;
}
else if (input.find("-second") != string::npos) {
size_t dash_pos = input.find('-');
return stoi(input.substr(0, dash_pos));
}
else {
try { return stoi(input); } catch (...) { return 60; }
}
}
GameConfig generate_random_config() {
GameConfig config;
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> mode_dist(0, 3); // 0=Words, 1=Time, 2=Quote, 3=Bible
int r_mode = mode_dist(gen);
if (r_mode == 0) {
config.mode = WORDS; config.quantity = uniform_int_distribution<>(10, 50)(gen);
}
else if (r_mode == 1) {
config.mode = TIME; config.quantity = uniform_int_distribution<>(15, 60)(gen);
}
else if (r_mode == 2) {
config.mode = QUOTE; config.difficulty = (string[]){"short", "medium", "long"}[uniform_int_distribution<>(0, 2)(gen)];
}
else {
// Random Bible Verse
config.mode = BIBLE;
vector<BibleVerse> bible = load_bible();
if (!bible.empty()) {
uniform_int_distribution<> dist(0, bible.size()-1);
BibleVerse v = bible[dist(gen)];
config.target_text = v.text;
config.difficulty = v.book + " " + to_string(v.chapter) + ":" + to_string(v.verse);
} else {
// Fallback if DB missing
config.mode = WORDS; config.quantity = 20;
}
}
return config;
}
GameConfig parse_arguments(int argc, char* argv[]) {
GameConfig config;
string cmd = argv[1];
if (cmd == "-help") {
printf("Usage:\n");
printf(" terminaltype (Random test)\n");
printf(" terminaltype word <num> (Word Count)\n");
printf(" terminaltype time <duration> (Time Trial)\n");
printf(" terminaltype quote <len> (Quote)\n");
printf(" terminaltype bible (Random Verse)\n");
printf(" terminaltype bible <book> (Random Verse from Book)\n");
printf(" terminaltype bible <book> <ch> (Full Chapter)\n");
printf(" terminaltype bible <book> <ch:v> (Specific Verse)\n");
exit(0);
}
if (cmd == "word") {
if (argc < 3) { printf("Usage: word <1-200>\n"); exit(1); }
config.mode = WORDS;
int val = stoi(argv[2]);
config.quantity = max(1, min(val, 200));
}
else if (cmd == "time") {
if (argc < 3) { printf("Usage: time <duration>\n"); exit(1); }
config.mode = TIME;
config.quantity = max(1, min(parse_time_string(argv[2]), 180));
}
else if (cmd == "quote") {
config.mode = QUOTE;
config.difficulty = (argc < 3) ? "medium" : argv[2];
}
else if (cmd == "bible") {
config.mode = BIBLE;
vector<BibleVerse> bible = load_bible();
if (bible.empty()) {
endwin();
printf("Error: kjv.csv not found.\nIt should be at $SNAP/bin/kjv.csv\n");
exit(1);
}
random_device rd;
mt19937 gen(rd());
// Case 1: "terminaltype bible" -> Random Verse from whole bible
if (argc == 2) {
uniform_int_distribution<> dist(0, bible.size()-1);
BibleVerse v = bible[dist(gen)];
config.target_text = v.text;
config.difficulty = v.book + " " + to_string(v.chapter) + ":" + to_string(v.verse);
}
else {
// Parse Book Name (might be multiple words like "1 John")
string target_book = "";
int arg_idx = 2;
while (arg_idx < argc && !isdigit(argv[arg_idx][0])) {
if (!target_book.empty()) target_book += " ";
target_book += argv[arg_idx];
arg_idx++;
}
target_book = to_lower(target_book);
// Filter by book
vector<BibleVerse> book_verses;
for (const auto& v : bible) {
if (to_lower(v.book) == target_book) book_verses.push_back(v);
}
if (book_verses.empty()) {
endwin();
printf("Book not found: %s\n", target_book.c_str());
exit(1);
}
// Case 2: "terminaltype bible psalms" -> Random verse from book
if (arg_idx >= argc) {
uniform_int_distribution<> dist(0, book_verses.size()-1);
BibleVerse v = book_verses[dist(gen)];
config.target_text = v.text;
config.difficulty = v.book + " " + to_string(v.chapter) + ":" + to_string(v.verse);
}
else {
// Parse Chapter/Verse
string ref = argv[arg_idx];
size_t colon = ref.find(':');
if (colon == string::npos) {
// Case 3: "terminaltype bible psalms 3" -> Full Chapter
int chap = stoi(ref);
string full_chapter = "";
for (const auto& v : book_verses) {
if (v.chapter == chap) {
if (!full_chapter.empty()) full_chapter += " ";
full_chapter += v.text;
}
}
if (full_chapter.empty()) { endwin(); printf("Chapter not found.\n"); exit(1); }
config.target_text = full_chapter;
config.difficulty = book_verses[0].book + " " + to_string(chap);
}
else {
// Case 4: "terminaltype bible psalms 3:1" -> Specific Verse
int chap = stoi(ref.substr(0, colon));
int verse_num = stoi(ref.substr(colon + 1));
for (const auto& v : book_verses) {
if (v.chapter == chap && v.verse == verse_num) {
config.target_text = v.text;
config.difficulty = v.book + " " + to_string(v.chapter) + ":" + to_string(v.verse);
break;
}
}
if (config.target_text.empty()) { endwin(); printf("Verse not found.\n"); exit(1); }
}
}
}
}
else { printf("Invalid command. Try 'terminaltype -help'\n"); exit(1); }
return config;
}
// --- LAYOUT ENGINE ---
void calculate_line_breaks(const string& text, int width, vector<int>& breaks) {
breaks.clear();
breaks.push_back(0);
int layout_x = 0;
for (size_t i = 0; i < text.length(); i++) {
if (text[i] == ' ') {
size_t next_space = text.find(' ', i + 1);
if (next_space == string::npos) next_space = text.length();
int word_len = next_space - i;
if (layout_x + word_len > width) {
breaks.push_back(i + 1);
layout_x = 0;
continue;
}
} else if (layout_x >= width) {
breaks.push_back(i);
layout_x = 0;
}
layout_x++;
}
breaks.push_back(text.length() + 1);
}
void draw_stats(int y, int x, GameConfig config, double seconds, double net_wpm, double accuracy) {
if (config.mode == TIME) {
double time_left = max(0.0, config.quantity - seconds);
mvprintw(y - 2, x, "Time: %.1f WPM: %.0f Acc: %.0f%% ", time_left, net_wpm, accuracy);
} else {
mvprintw(y - 2, x, "Time: %.1f WPM: %.0f Acc: %.0f%% ", seconds, net_wpm, accuracy);
}
}
void draw_text_from_cache(int start_y, int start_x, const string& text, const string& buffer, const vector<int>& breaks) {
int cursor_idx = buffer.length();
auto it = upper_bound(breaks.begin(), breaks.end(), cursor_idx);
int active_row = (it - breaks.begin()) - 1;
for(int i = 0; i < 5; i++) { move(start_y + i, 0); clrtoeol(); }
for (int r = 0; r < 4; r++) {
int current_row_idx = active_row + r;
if (current_row_idx >= (int)breaks.size() - 1) break;
int line_start = breaks[current_row_idx];
int line_end = breaks[current_row_idx + 1];
if (line_end > (int)text.length()) line_end = text.length();
else if (r < 3 && text[line_end - 1] == ' ') line_end--;
int screen_y = start_y + r;
int screen_x = start_x;
for (int i = line_start; i < line_end; i++) {
if (i >= (int)text.length()) break;
int pair = 2;
if (i >= (int)buffer.length()) pair = 3;
else if (buffer[i] == text[i]) pair = 1;
attron(COLOR_PAIR(pair)); mvaddch(screen_y, screen_x, text[i]); attroff(COLOR_PAIR(pair));
if (i == (int)buffer.length()) {
attron(COLOR_PAIR(4)); mvaddch(screen_y, screen_x, text[i]); attroff(COLOR_PAIR(4));
}
screen_x++;
}
if (buffer.length() >= line_end && buffer.length() < breaks[current_row_idx+1] && current_row_idx == active_row) {
attron(COLOR_PAIR(4)); mvaddch(screen_y, screen_x, ' '); attroff(COLOR_PAIR(4));
}
}
}
// --- MAIN ---
int main(int argc, char* argv[]) {
bool random_session = (argc == 1);
GameConfig current_config;
if (!random_session) current_config = parse_arguments(argc, argv);
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
timeout(30);
if (has_colors() == FALSE) { endwin(); printf("No color support.\n"); return 1; }
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
init_pair(3, COLOR_WHITE, COLOR_BLACK);
init_pair(4, COLOR_BLACK, COLOR_WHITE);
init_pair(5, COLOR_YELLOW, COLOR_BLACK);
bool play_again = true;
while (play_again) {
if (random_session) current_config = generate_random_config();
string target_text = "";
string mode_desc = "";
if (current_config.mode == QUOTE) {
target_text = get_random_quote(current_config.difficulty);
mode_desc = "Quote (" + current_config.difficulty + ")";
} else if (current_config.mode == WORDS) {
target_text = generate_random_words(current_config.quantity);
mode_desc = "Words (" + to_string(current_config.quantity) + ")";
} else if (current_config.mode == TIME) {
target_text = generate_random_words(current_config.quantity * 5);
mode_desc = "Time (" + to_string(current_config.quantity) + "s)";
} else if (current_config.mode == BIBLE) {
target_text = current_config.target_text;
mode_desc = current_config.difficulty;
}
string buffer = "";
buffer.reserve(target_text.length());
bool started = false;
auto start_time = chrono::steady_clock::now();
double net_wpm = 0.0, accuracy = 0.0;
bool finished = false;
bool needs_layout = true, needs_redraw = true;
int start_y = 5, start_x = 5;
int max_y, max_x;
getmaxyx(stdscr, max_y, max_x);
int wrap_width = max_x - 10;
vector<int> line_breaks;
clear();
mvprintw(1, 5, "Mode: %s", mode_desc.c_str());
if (random_session) mvprintw(2, 5, "Type text. ESC to quit. TAB for next.");
else mvprintw(2, 5, "Type text. ESC to quit. TAB to restart.");
while (!finished) {
int new_y, new_x;
getmaxyx(stdscr, new_y, new_x);
if (new_x != max_x || new_y != max_y) {
max_x = new_x; max_y = new_y;
wrap_width = max_x - 10;
clear();
mvprintw(1, 5, "Mode: %s", mode_desc.c_str());
needs_layout = true; needs_redraw = true;
}
if (needs_layout) {
calculate_line_breaks(target_text, wrap_width, line_breaks);
needs_layout = false;
}
if (started) {
auto now = chrono::steady_clock::now();
double seconds = chrono::duration<double>(now - start_time).count();
int errors = 0;
for(size_t i=0; i < buffer.length(); i++) {
if (buffer[i] != target_text[i]) errors++;
}
if (seconds > 1.0) {
double net_chars = max(0.0, (double)buffer.length() - errors);
net_wpm = (net_chars / 5.0) / (seconds / 60.0);
}
accuracy = (buffer.length() > 0) ? 100.0 * ((double)(buffer.length() - errors) / buffer.length()) : 100.0;
draw_stats(start_y, start_x, current_config, seconds, net_wpm, accuracy);
if (current_config.mode == TIME && (current_config.quantity - seconds) <= 0) finished = true;
}
if (needs_redraw) {
draw_text_from_cache(start_y, start_x, target_text, buffer, line_breaks);
needs_redraw = false;
}
refresh();
if (finished) break;
int ch = getch();
if (ch == ERR) continue;
if (ch == 27) { endwin(); return 0; }
if (ch == 9) { finished = true; break; }
if (!started && ch >= 32 && ch <= 126) {
started = true;
start_time = chrono::steady_clock::now();
}
bool changed = false;
if (is_word_delete(ch)) {
while (!buffer.empty()) {
char last_char = buffer.back();
if (is_separator(last_char)) { buffer.pop_back(); changed = true; break; }
buffer.pop_back(); changed = true;
if (!buffer.empty() && is_separator(buffer.back())) { break; }
}
}
else if (is_char_delete(ch)) {
if (!buffer.empty()) { buffer.pop_back(); changed = true; }
}
else if (ch >= 32 && ch <= 126) {
if (buffer.length() < target_text.length()) { buffer += (char)ch; changed = true; }
}
if (changed) needs_redraw = true;
if (current_config.mode != TIME && buffer.length() == target_text.length()) finished = true;
}
if (getch() == 9) continue;
save_score(mode_desc, (int)net_wpm, accuracy);
vector<ScoreEntry> best_runs = get_top_scores(mode_desc);
clear();
attron(A_BOLD); mvprintw(start_y, start_x, "TEST COMPLETE"); attroff(A_BOLD);
mvprintw(start_y + 2, start_x, "Final WPM: %.0f", net_wpm);
mvprintw(start_y + 3, start_x, "Accuracy: %.1f%%", accuracy);
attron(COLOR_PAIR(5) | A_BOLD);
mvprintw(start_y + 5, start_x, "--- YOUR BEST RUNS (%s) ---", mode_desc.c_str());
attroff(COLOR_PAIR(5) | A_BOLD);
if (best_runs.empty()) mvprintw(start_y + 6, start_x, "(No previous runs recorded)");
else {
for (size_t i = 0; i < best_runs.size(); i++) {
char time_buf[20];
struct tm* timeinfo = localtime(&best_runs[i].timestamp);
strftime(time_buf, 20, "%b %d", timeinfo);
mvprintw(start_y + 6 + i, start_x, "%d. %d WPM (%.0f%%) - %s", (int)i + 1, best_runs[i].wpm, best_runs[i].accuracy, time_buf);
}
}
int nav_y = start_y + 6 + max(1, (int)best_runs.size()) + 2;
mvprintw(nav_y, start_x, "Press TAB to restart. ESC to quit.");
timeout(-1);
while(true) {
int cmd = getch();
if (cmd == 27) { play_again = false; break; }
if (cmd == 9) { play_again = true; break; }
}
timeout(30);
}
curs_set(1);
endwin();
return 0;
}