-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoType.go
More file actions
503 lines (440 loc) · 12 KB
/
GoType.go
File metadata and controls
503 lines (440 loc) · 12 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
package main
import (
"encoding/csv"
"fmt"
"log"
"math"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/nsf/termbox-go"
)
// --- Configuration & State ---
// wordBank will be loaded from the dictionary file
var wordBank []string
// TestResults holds the statistics for a completed typing test.
type TestResults struct {
RawWPM float64
AdjustedWPM float64
Accuracy float64
Errors int
WordsTyped int
Timestamp string
}
// Global state for UI colors and filenames.
var (
defaultFg = termbox.ColorDefault
correctFg = termbox.ColorGreen
incorrectFg = termbox.ColorRed
defaultBg = termbox.ColorDefault
resultsCsvFilename = "gotype_results.csv"
dictionaryFilename = "dictionary.csv"
previousTest *TestResults
)
// --- Main Application Logic ---
func main() {
// Load the words from the dictionary
var err error
wordBank, err = loadWordBank(dictionaryFilename)
if err != nil {
fmt.Printf("Error: Failed to load the dictionary file.\n")
fmt.Printf("Please make sure a file named '%s' exists in the same directory as the application.\n", dictionaryFilename)
fmt.Printf("Details: %v\n", err)
// Wait for the user to read the message
fmt.Println("\nPress Enter to exit.")
var input string
fmt.Scanln(&input)
return
}
// random number
rand.Seed(time.Now().UnixNano())
// Main menu loop
for {
clearScreen()
showMainMenu()
choice := readMenuChoice()
switch choice {
case "1":
duration := selectTestDuration()
if duration > 0 {
runTestFlow(duration)
}
case "2":
showOptionsMenu()
case "3":
showCredits()
case "4":
fmt.Println("Goodbye!")
return
default:
fmt.Println("Invalid option. Please try again.")
time.Sleep(1 * time.Second)
}
}
}
// --- Menu & UI Functions ---
// navigation options.
func showMainMenu() {
fmt.Println("--- GoType ---")
fmt.Println("1. Start Typing Test")
fmt.Println("2. Options")
fmt.Println("3. Credits")
fmt.Println("4. Exit")
fmt.Print("\nEnter your choice: ")
}
// readMenuChoice reads a single line of input from the user.
func readMenuChoice() string {
var choice string
fmt.Scanln(&choice)
return strings.TrimSpace(choice)
}
// choose a test length.
func selectTestDuration() int {
clearScreen()
fmt.Println("--- Select Test Duration ---")
fmt.Println("1. 30 seconds")
fmt.Println("2. 60 seconds")
fmt.Println("3. 120 seconds")
fmt.Println("4. Back to Main Menu")
fmt.Print("\nEnter your choice: ")
for {
choice := readMenuChoice()
switch choice {
case "1":
return 30
case "2":
return 60
case "3":
return 120
case "4":
return 0 // Sentinel value for "back"
default:
fmt.Print("Invalid choice. Please enter 1, 2, 3, or 4: ")
}
}
}
// showOptionsMenu displays options for customization and data management.
func showOptionsMenu() {
for {
clearScreen()
fmt.Println("--- Options ---")
fmt.Println("1. Change Text Color (Not implemented yet)") // Placeholder
fmt.Println("2. Wipe All Saved Records")
fmt.Println("3. Back to Main Menu")
fmt.Print("\nEnter your choice: ")
choice := readMenuChoice()
switch choice {
case "1":
fmt.Println("\nColor customization is coming soon!")
time.Sleep(2 * time.Second)
case "2":
wipeAllRecords()
case "3":
return
default:
fmt.Println("Invalid option. Please try again.")
time.Sleep(1 * time.Second)
}
}
}
// showCredits displays the developer credits.
func showCredits() {
clearScreen()
fmt.Println("--- Credits ---")
fmt.Println("Lead Dev: P1NK0 \"Logan B.\"")
fmt.Println("\nPress Enter to return to the main menu...")
readMenuChoice() // Waits for user to press Enter
}
// --- Typing Test Core Logic ---
// running a test and handling the result.
func runTestFlow(duration int) {
currentResult := runTypingTest(duration)
displayResults(currentResult)
// Handle post-test options
for {
fmt.Println("\nChoose an option:")
fmt.Println("1. Save Results")
fmt.Println("2. Discard Results")
fmt.Println("3. Retry Test")
fmt.Print("\nEnter your choice: ")
choice := readMenuChoice()
switch choice {
case "1":
saveResultsToCSV(currentResult)
previousTest = nil // Clear previous
fmt.Println("Results saved!")
time.Sleep(2 * time.Second)
return
case "2":
previousTest = nil // Clear previous
fmt.Println("Results discarded.")
time.Sleep(2 * time.Second)
return
case "3":
previousTest = ¤tResult // Store current result
runTestFlow(duration) // Re-run the whole flow
return
default:
fmt.Println("Invalid option. Please choose 1, 2, or 3.")
}
}
}
// runTypingTest start and run
func runTypingTest(durationSec int) TestResults {
err := termbox.Init()
if err != nil {
log.Fatalf("Failed to initialize termbox: %v", err)
}
defer termbox.Close()
termbox.SetInputMode(termbox.InputEsc)
// words for the test
wordsToType := generateTestWords(100) // Generate more words than needed
fullText := strings.Join(wordsToType, " ")
textRunes := []rune(fullText)
// variables for the test
userInput := make([]rune, 0, len(textRunes))
currentIndex := 0
// errors := 0
totalCharsTyped := 0
// Timer
timer := time.NewTimer(time.Duration(durationSec) * time.Second)
var wg sync.WaitGroup
wg.Add(1)
//listen for the timer to finish
go func() {
defer wg.Done()
<-timer.C
termbox.Interrupt() // Stop when time is up
}()
// Main event
drawTestUI(textRunes, userInput, durationSec, 0)
startTime := time.Now()
mainloop:
for {
elapsedTime := int(time.Since(startTime).Seconds())
remainingTime := durationSec - elapsedTime
if remainingTime < 0 {
remainingTime = 0
}
drawTestUI(textRunes, userInput, remainingTime, currentIndex)
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
if ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC {
break mainloop
}
if ev.Key == termbox.KeyBackspace || ev.Key == termbox.KeyBackspace2 {
if currentIndex > 0 {
currentIndex--
userInput = userInput[:currentIndex]
}
} else if ev.Key == termbox.KeySpace {
if currentIndex < len(textRunes) {
userInput = append(userInput, ' ')
currentIndex++
totalCharsTyped++
}
} else if ev.Ch != 0 {
if currentIndex < len(textRunes) {
userInput = append(userInput, ev.Ch)
currentIndex++
totalCharsTyped++
}
}
case termbox.EventError:
panic(ev.Err)
case termbox.EventInterrupt:
break mainloop
}
}
wg.Wait() // check if timer going
//figuring out stats
correctChars := 0
finalText := userInput
if len(userInput) > len(textRunes) {
finalText = userInput[:len(textRunes)]
}
for i, char := range finalText {
if char == textRunes[i] {
correctChars++
}
}
errorCount := totalCharsTyped - correctChars
if errorCount < 0 {
errorCount = 0
}
// WPM is based on 5-character words
grossWPM := (float64(totalCharsTyped) / 5.0) / (float64(durationSec) / 60.0)
netWPM := grossWPM - (float64(errorCount) / (float64(durationSec) / 60.0))
accuracy := 0.0
if totalCharsTyped > 0 {
accuracy = (float64(correctChars) / float64(totalCharsTyped)) * 100
}
// Count typed words
typedWords := strings.Fields(string(userInput))
return TestResults{
RawWPM: grossWPM,
AdjustedWPM: math.Max(0, netWPM),
Accuracy: math.Max(0, accuracy),
Errors: errorCount,
WordsTyped: len(typedWords),
Timestamp: time.Now().Format("2006-01-02 15:04:05"),
}
}
// drawTestUI renders the typing test interface in the terminal.
func drawTestUI(textToType, userInput []rune, timeLeft, currentIndex int) {
termbox.Clear(defaultFg, defaultBg)
width, height := termbox.Size()
// Draw the text
x, y := 2, 2
for i, r := range textToType {
fg := defaultFg
if i < len(userInput) {
if userInput[i] == r {
fg = correctFg
} else {
fg = incorrectFg
}
}
termbox.SetCell(x, y, r, fg, defaultBg)
x++
if x >= width-2 {
x = 2
y++
}
}
// timer
timerStr := fmt.Sprintf("Time Left: %d s", timeLeft)
for i, r := range timerStr {
termbox.SetCell(width/2-len(timerStr)/2+i, height-2, r, defaultFg, defaultBg)
}
// Set strt position
cursorX, cursorY := 2, 2
for i := 0; i < currentIndex; i++ {
cursorX++
if cursorX >= width-2 {
cursorX = 2
cursorY++
}
}
termbox.SetCursor(cursorX, cursorY)
termbox.Flush()
}
// data paths and result showcasing
// displayResults shows stats.
func displayResults(results TestResults) {
clearScreen()
fmt.Println("--- Test Results ---")
fmt.Printf("Raw WPM: %.2f\n", results.RawWPM)
fmt.Printf("Adjusted WPM: %.2f\n", results.AdjustedWPM)
fmt.Printf("Accuracy: %.2f%%\n", results.Accuracy)
fmt.Printf("Errors: %d\n", results.Errors)
fmt.Printf("Words Typed: %d\n", results.WordsTyped)
// If there was a previous test (from a "Retry"), compare them.
if previousTest != nil {
fmt.Println("\n--- Comparison with Previous Attempt ---")
fmt.Printf("Adjusted WPM Change: %.2f (%.2f -> %.2f)\n", results.AdjustedWPM-previousTest.AdjustedWPM, previousTest.AdjustedWPM, results.AdjustedWPM)
fmt.Printf("Accuracy Change: %.2f%% (%.2f%% -> %.2f%%)\n", results.Accuracy-previousTest.Accuracy, previousTest.Accuracy, results.Accuracy)
}
}
// saveResultsToCSV saves results to record.
func saveResultsToCSV(results TestResults) {
// Check if file exists
_, err := os.Stat(resultsCsvFilename)
fileExists := !os.IsNotExist(err)
file, err := os.OpenFile(resultsCsvFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Failed to open CSV file: %v", err)
return
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
// Write header only if new
if !fileExists {
header := []string{"Timestamp", "RawWPM", "AdjustedWPM", "Accuracy", "Errors", "WordsTyped"}
if err := writer.Write(header); err != nil {
log.Printf("Failed to write CSV header: %v", err)
}
}
// Write the data record
record := []string{
results.Timestamp,
strconv.FormatFloat(results.RawWPM, 'f', 2, 64),
strconv.FormatFloat(results.AdjustedWPM, 'f', 2, 64),
strconv.FormatFloat(results.Accuracy, 'f', 2, 64),
strconv.Itoa(results.Errors),
strconv.Itoa(results.WordsTyped),
}
if err := writer.Write(record); err != nil {
log.Printf("Failed to write CSV record: %v", err)
}
}
// wipeAllRecords will wipe all records
func wipeAllRecords() {
clearScreen()
fmt.Printf("Are you sure you want to delete all saved records from '%s'? This cannot be undone. (y/n): ", resultsCsvFilename)
choice := readMenuChoice()
if strings.ToLower(choice) == "y" {
err := os.Remove(resultsCsvFilename)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("\nNo records file to delete.")
} else {
fmt.Printf("\nError deleting records file: %v\n", err)
}
} else {
fmt.Println("\nAll records have been wiped.")
}
} else {
fmt.Println("\nOperation cancelled.")
}
time.Sleep(2 * time.Second)
}
// util funcs
// da dict func - pulls rows or columns from dict file
func loadWordBank(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("could not open word file '%s': %w", filename, err)
}
defer file.Close()
reader := csv.NewReader(file)
// make game read dict whther 10 lines or 10000 lines
reader.FieldsPerRecord = -1
records, err := reader.ReadAll()
if err != nil {
return nil, fmt.Errorf("could not read records from word file: %w", err)
}
var words []string
for _, record := range records {
for _, word := range record {
// make game load non empty cells from csv
if trimmedWord := strings.TrimSpace(word); trimmedWord != "" {
words = append(words, trimmedWord)
}
}
}
if len(words) == 0 {
return nil, fmt.Errorf("no words found in '%s'", filename)
}
return words, nil
}
// makes random word group for test
func generateTestWords(count int) []string {
if len(wordBank) == 0 {
// error if dct missing or empty
return []string{"error:", "word", "bank", "is", "empty"}
}
words := make([]string, count)
for i := 0; i < count; i++ {
words[i] = wordBank[rand.Intn(len(wordBank))]
}
return words
}
// clearScreen does what is says
func clearScreen() {
fmt.Print("\033[H\033[2J")
}