-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
430 lines (358 loc) · 8.99 KB
/
main.go
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/nsf/termbox-go"
)
type GameStats struct {
Stats []StatPair
}
type StatPair struct {
Label string
Value interface{}
}
type Quote struct {
Quote string `json:"q"`
Author string `json:"a"`
}
type Game struct {
db *sql.DB
currentQuote Quote
quoteY int
inputY int
userInput string
accuracy int
roundChars int
totalChars int
startedTyping bool
wordsPerMin float64
rawWPM float64
typingSpeed float64
rawSpeed float64
startTime time.Time
score int
highScore int
roundTime float64
totalTime float64
totalErrors int
}
func main() {
// Create a new game instance
game, err := NewGame()
if err != nil {
// Handle the error if initialization fails
panic(err)
}
// Start the game loop
game.Start()
}
func NewGame() (*Game, error) {
err := termbox.Init()
if err != nil {
return nil, err
}
db, err := openDatabase()
if err != nil {
return nil, err
}
return &Game{
db: db,
}, nil
}
func (g *Game) Start() {
defer termbox.Close()
g.runGameLoop()
}
func (g *Game) drawAll() {
g.drawSentenceWithAuthor()
g.drawInput()
g.drawScore()
g.drawTypingSpeed()
}
func (g *Game) runGameLoop() {
// Initialize the game state
g.initGame()
for {
err := termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
if err != nil {
log.Fatal(err)
}
g.drawAll()
termbox.Flush()
// if g.collectKeys {
ev := termbox.PollEvent()
if ev.Type == termbox.EventKey {
if ev.Key == termbox.KeyEsc {
break
} else if ev.Key == termbox.KeyBackspace || ev.Key == termbox.KeyBackspace2 {
g.handleBackspace()
} else if ev.Ch != 0 || ev.Key == termbox.KeySpace {
g.handleInputCharacter(ev)
}
}
}
}
func (g *Game) initGame() {
quote, err := getRandomQuote(g.db)
if err != nil {
log.Fatal(err)
}
quote.Quote = strings.Trim(quote.Quote, " ")
g.currentQuote = quote
g.userInput = ""
g.startedTyping = false
}
func (g *Game) handleBackspace() {
if len(g.userInput) > 0 {
g.userInput = g.userInput[:len(g.userInput)-1]
g.calculateAccuracy()
g.calculateErrors()
g.calculateWordsPerMinute()
g.calcRawSpeed()
}
}
func (g *Game) handleInputCharacter(ev termbox.Event) {
if !g.startedTyping {
g.startedTyping = true
g.startTime = time.Now()
g.roundChars = 0
g.roundTime = 0
}
g.roundChars++
if ev.Ch != 0 {
g.userInput += string(ev.Ch)
} else if ev.Key == termbox.KeySpace {
g.userInput += " "
}
g.roundTime = time.Since(g.startTime).Seconds()
g.typingSpeed = float64(len(g.userInput)) / g.roundTime
g.rawSpeed = float64(g.roundChars) / g.roundTime
g.calculateWordsPerMinute()
g.calcRawSpeed()
g.calculateAccuracy()
g.calculateErrors()
if len(g.userInput) >= len(g.currentQuote.Quote) {
g.totalTime = g.totalTime + g.roundTime
g.totalChars = g.totalChars + g.roundChars
if g.score > g.highScore {
g.highScore = g.score
}
g.initGame()
addSqlQuote(g.db, g.currentQuote.Quote, g.currentQuote.Author)
}
}
func (g *Game) calculateErrors() {
roundErrors := 0
for i := range g.userInput {
if g.currentQuote.Quote[i] != g.userInput[i] {
roundErrors += 1
}
}
g.totalErrors = roundErrors
}
func (g *Game) calcRawSpeed() {
g.rawWPM = g.rawSpeed * (60 / 5)
}
func (g *Game) calculateWordsPerMinute() {
g.wordsPerMin = g.typingSpeed * (60 / 5)
}
func (g *Game) calculateScore() {
g.score = (2 * g.accuracy) * int(g.typingSpeed)
}
func (gs *GameStats) formatTopBarStr() string {
var statStrings []string
for _, pair := range gs.Stats {
statStrings = append(statStrings, fmt.Sprintf("%s: %v", pair.Label, pair.Value))
}
return strings.Join(statStrings, " | ")
}
func (g *Game) drawTopBar() {
width, _ := termbox.Size()
g.calculateScore()
g.calculateWordsPerMinute()
g.calcRawSpeed()
// Create an array of StatPair objects
stats := []StatPair{
{"Highscore", g.highScore},
{"Score", g.score},
{"Accuracy", g.accuracy},
{"WPM", int(g.wordsPerMin)},
{"Raw", int(g.rawWPM)},
{"Time", int(g.roundTime)},
{"Errors", g.totalErrors},
}
gameStats := &GameStats{
Stats: stats,
}
// Set a maximum line length (adjust as needed)
maxLineLength := 60
// Generate the topBarStr from the GameStats struct
topBarStr := gameStats.formatTopBarStr()
// Split the string into lines
lines := wrapText(topBarStr, maxLineLength, "|")
// Calculate starting y position
y := 1
// Display each line
for _, line := range lines {
x := (width - len(line)) / 2
for i, char := range line {
termbox.SetCell(x+i, y, char, termbox.ColorDefault, termbox.ColorDefault)
}
y++
}
}
func (g *Game) drawScore() {
// Clear the top bar
width, _ := termbox.Size()
for i := 0; i < width; i++ {
termbox.SetCell(i, 1, ' ', termbox.ColorDefault, termbox.ColorDefault)
}
g.drawTopBar()
}
func (g *Game) drawInput() {
width, _ := termbox.Size()
maxLineWidth := int(float64(width) * 0.8)
g.inputY = g.quoteY + 1
delimiter := " "
// Use wrapText to get wrapped lines for user input
userInputLines := wrapText(g.userInput, maxLineWidth, delimiter)
var k int
// Draw each line of the wrapped user input
for i, line := range userInputLines {
// Calculate x based on the length of the line
x := (width - len(line)) / 2
for j, char := range line {
if g.userInput[k] == g.currentQuote.Quote[k] {
termbox.SetCell(x+j, g.inputY+i, char, termbox.ColorDefault, termbox.ColorDefault)
} else {
termbox.SetCell(x+j, g.inputY+i, char, termbox.ColorBlack, termbox.ColorRed)
}
k++
}
}
}
func wrapText(text string, maxWidth int, delimiter string) []string {
words := strings.Split(text, delimiter)
lines := []string{}
currentLine := ""
for _, word := range words {
if len(currentLine)+len(word)+1 <= maxWidth {
currentLine += word + delimiter
} else {
lines = append(lines, strings.TrimSpace(currentLine))
currentLine = word + delimiter
}
}
lines = append(lines, strings.TrimSpace(currentLine))
return lines
}
func (g *Game) drawSentenceWithAuthor() {
width, height := termbox.Size()
maxLineWidth := int(float64(width) * 0.8)
quote := g.currentQuote.Quote
delimiter := " "
lines := wrapText(quote, maxLineWidth, delimiter)
sentenceHeight := len(lines)
g.quoteY = (height - sentenceHeight) / 2
authorX := (width - len(g.currentQuote.Author)) / 2
authorY := g.quoteY - 2
for i, char := range g.currentQuote.Author {
termbox.SetCell(authorX+i, authorY, char, termbox.ColorMagenta, termbox.ColorDefault)
}
for _, line := range lines {
x := (width - len(line)) / 2
for i, char := range line {
termbox.SetCell(x+i, g.quoteY, char, termbox.ColorDefault, termbox.ColorDefault)
}
g.quoteY++
}
}
func (g *Game) drawTypingSpeed() {
// Clear the top bar
width, _ := termbox.Size()
for i := 0; i < width; i++ {
termbox.SetCell(i, 1, ' ', termbox.ColorDefault, termbox.ColorDefault)
}
g.drawTopBar()
}
func (g *Game) calculateAccuracy() {
commonLength := min(len(g.userInput), len(g.currentQuote.Quote))
correctChars := 0
for i := 0; i < commonLength; i++ {
if g.currentQuote.Quote[i] == g.userInput[i] {
correctChars++
}
}
accuracy := float64(correctChars) / float64(commonLength)
g.accuracy = int(accuracy * 100)
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func getRandomQuote(db *sql.DB) (Quote, error) {
quotes, err := getRandomQuoteFromAPI()
if err != nil {
return getRandomQuoteFromDatabase(db)
}
return quotes[0], nil
}
func getRandomQuoteFromAPI() ([]Quote, error) {
client := http.Client{}
resp, err := client.Get("https://zenquotes.io/api/random")
if err != nil {
return nil, fmt.Errorf("failed to fetch quote from API: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
var quotes []Quote
if err := json.Unmarshal(body, "es); err != nil {
return nil, fmt.Errorf("failed to parse response body: %w", err)
}
return quotes, nil
}
func getRandomQuoteFromDatabase(db *sql.DB) (Quote, error) {
var text, author string
query := "SELECT text, author FROM quotes ORDER BY RANDOM() LIMIT 1"
err := db.QueryRow(query).Scan(&text, &author)
if err != nil {
return Quote{}, fmt.Errorf("failed to fetch quote from database: %w", err)
}
return Quote{Quote: text, Author: author}, nil
}
func openDatabase() (*sql.DB, error) {
db, err := sql.Open("sqlite3", "quotes.db")
if err != nil {
return nil, err
}
// Check if the database file exists
_, err = os.Stat("quotes.db")
if os.IsNotExist(err) {
// Create the database file and any necessary tables
_, err = db.Exec("CREATE TABLE quotes (quote TEXT, author TEXT)")
if err != nil {
db.Close() // Close the connection if table creation fails
return nil, err
}
}
return db, nil
}
func addSqlQuote(db *sql.DB, quote, author string) {
_, err := db.Exec("INSERT INTO quotes (text, author) VALUES (?, ?)", quote, author)
if err != nil {
fmt.Println("failed to add quote to sql: %w", err)
}
}