-
Notifications
You must be signed in to change notification settings - Fork 22
/
model.go
465 lines (409 loc) · 11.3 KB
/
model.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
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
package main
import (
"bytes"
"fmt"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
const (
// numGuesses is the maximum number of guesses you can make.
numGuesses = 6
// numChars is the word size in characters.
numChars = 5
)
type model struct {
score int
word [numChars]byte
gameOver bool
errors []error
keyStates map[byte]keyState
status string
statusPending int
height int
width int
grid [numGuesses][numChars]byte
gridRow int
gridCol int
}
var _ tea.Model = (*model)(nil)
func (m *model) Init() tea.Cmd {
m.keyStates = make(map[byte]keyState, 26)
return m.withDb(func(db *db) {
m.score = db.score()
m.reset()
})
}
func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case msgResetStatus:
// If there is more than one pending status message, that means
// something else is currently displaying a status message, so we don't
// want to overwrite it.
m.statusPending--
if m.statusPending == 0 {
m.resetStatus()
}
return m, nil
case tea.KeyMsg:
// If any key is pressed, reset the status message.
m.resetStatus()
switch msg.Type {
case tea.KeyCtrlC:
return m, m.doExit()
case tea.KeyCtrlR:
m.reset()
return m, nil
case tea.KeyBackspace:
return m, m.doDeleteChar()
case tea.KeyEnter:
if m.gameOver {
m.reset()
return m, nil
}
return m, m.doAcceptWord()
case tea.KeyRunes:
if len(msg.Runes) == 1 {
return m, m.doAcceptChar(msg.Runes[0])
}
}
// If the window is resized, store its new dimensions.
case tea.WindowSizeMsg:
return m, m.doResize(msg)
}
return m, nil
}
func (m *model) View() string {
status := m.viewStatus()
grid := m.viewGrid()
keyboard := m.viewKeyboard()
// Truncate the status if it is too long.
if len(status) > m.width && m.width > 3 {
status = status[:m.width-3] + "..."
}
// Drop the keyboard if it doesn't fit.
height := lipgloss.Height(status) + lipgloss.Height(grid) + lipgloss.Height(keyboard)
width := lipgloss.Width(keyboard)
if width < lipgloss.Width(status) || width < lipgloss.Width(grid) {
width = 0
}
if m.height < height || m.width < width {
keyboard = ""
}
game := lipgloss.JoinVertical(lipgloss.Center, status, grid, keyboard, _controls)
return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, game)
}
func (m *model) reset() {
// Unlock and reset the grid.
m.gameOver = false
m.gridCol = 0
m.gridRow = 0
// Clear the key state.
for k := range m.keyStates {
delete(m.keyStates, k)
}
// Set the puzzle word.
word := getWord()
copy(m.word[:], word)
// Reset the status message.
m.resetStatus()
}
// setStatus sets the status message, and returns a tea.Cmd that restores the
// default status message after a delay.
func (m *model) setStatus(msg string, duration time.Duration) tea.Cmd {
m.status = msg
if duration > 0 {
m.statusPending++
return tea.Tick(duration, func(time.Time) tea.Msg {
return msgResetStatus{}
})
}
return nil
}
// resetStatus immediately resets the status message to its default value.
func (m *model) resetStatus() {
m.status = fmt.Sprintf("Score: %d", m.score)
}
// doAcceptWord accepts the current word.
func (m *model) doAcceptWord() tea.Cmd {
if m.gameOver {
return nil
}
// Only accept a word if it is complete.
if m.gridCol != numChars {
return m.setStatus("Your guess must be a 5-letter word.", 1*time.Second)
}
// Check if the input word is valid.
word := m.grid[m.gridRow]
if !isWord(string(word[:])) {
return m.setStatus("That's not a valid word.", 1*time.Second)
}
// Update the state of the used letters.
success := true
for i := 0; i < numChars; i++ {
key := word[i]
keyStatus := keyStateAbsent
if key == m.word[i] {
keyStatus = keyStateCorrect
} else {
success = false
if bytes.IndexByte(m.word[:], key) != -1 {
keyStatus = keyStatePresent
}
}
if m.keyStates[key] < keyStatus {
m.keyStates[key] = keyStatus
}
}
// Move to the next row.
m.gridRow++
m.gridCol = 0
// Check if the game is over.
if success {
return m.doWin()
} else if m.gridRow == numGuesses {
return m.doLoss()
}
return nil
}
// doAcceptChar adds one input character to the current word.
func (m *model) doAcceptChar(ch rune) tea.Cmd {
// Only accept a character if the current word is incomplete.
if m.gameOver || !(m.gridRow < numGuesses && m.gridCol < numChars) {
return nil
}
ch = toAsciiUpper(ch)
if isAsciiUpper(ch) {
m.grid[m.gridRow][m.gridCol] = byte(ch)
m.gridCol++
}
return nil
}
// doDeleteChar deletes the last character in the current word.
func (m *model) doDeleteChar() tea.Cmd {
if !m.gameOver && m.gridCol > 0 {
m.gridCol--
}
return nil
}
// doExit exits the program.
func (*model) doExit() tea.Cmd {
return tea.Quit
}
// doResize updates the size of the window.
func (m *model) doResize(msg tea.WindowSizeMsg) tea.Cmd {
m.height = msg.Height
m.width = msg.Width
return nil
}
// doWin is called when the user has guessed the word correctly.
func (m *model) doWin() tea.Cmd {
m.gameOver = true
return tea.Sequentially(
m.withDb(func(db *db) {
db.addWin(m.gridRow)
m.score = db.score()
}),
m.setStatus("You win!", 0),
)
}
// doLoss is called when the user has used up all their guesses.
func (m *model) doLoss() tea.Cmd {
m.gameOver = true
msg := fmt.Sprintf("The word was %s. Better luck next time!", string(m.word[:]))
return tea.Sequentially(
m.withDb(func(db *db) {
db.addLoss()
m.score = db.score()
}),
m.setStatus(msg, 0),
)
}
// viewStatus renders the status line.
func (m *model) viewStatus() string {
return lipgloss.NewStyle().Foreground(colorPrimary).Render(m.status)
}
// viewGrid renders the grid.
func (m *model) viewGrid() string {
var rows [numGuesses]string
for i := 0; i < numGuesses; i++ {
if i < m.gridRow {
rows[i] = m.viewGridRowFilled(m.grid[i])
} else if i == m.gridRow && !m.gameOver {
rows[i] = m.viewGridRowCurrent(m.grid[i], m.gridCol)
} else {
rows[i] = m.viewGridRowEmpty()
}
}
return lipgloss.JoinVertical(lipgloss.Left, rows[:]...)
}
// viewGridRowFilled renders a filled-in grid row. It chooses the appropriate
// color for each key.
func (m *model) viewGridRowFilled(word [numChars]byte) string {
var keyStates [numChars]keyState
letters := m.word
// Mark keyStatusAbsent.
for i := 0; i < numChars; i++ {
keyStates[i] = keyStateAbsent
}
// Mark keyStatusCorrect.
for i := 0; i < numChars; i++ {
if word[i] == m.word[i] {
keyStates[i] = keyStateCorrect
letters[i] = 0
}
}
// Mark keyStatusPresent.
for i := 0; i < numChars; i++ {
if keyStates[i] == keyStateCorrect {
continue
}
if foundIdx := bytes.IndexByte(letters[:], word[i]); foundIdx != -1 {
keyStates[i] = keyStatePresent
letters[foundIdx] = 0
}
}
// Render keys.
var keys [numChars]string
for i := 0; i < numChars; i++ {
keys[i] = m.viewKey(string(word[i]), keyStates[i].color())
}
return lipgloss.JoinHorizontal(lipgloss.Bottom, keys[:]...)
}
// viewGridRowCurrent renders the current grid row. It renders an "_" character
// for the letter being currently input.
func (m *model) viewGridRowCurrent(row [numChars]byte, rowIdx int) string {
var keys [numChars]string
for i := 0; i < numChars; i++ {
var key string
if i < rowIdx {
key = string(row[i])
} else if i == rowIdx {
key = "_"
} else {
key = " "
}
keys[i] = m.viewKey(key, colorPrimary)
}
return lipgloss.JoinHorizontal(lipgloss.Bottom, keys[:]...)
}
// viewGridRowEmpty renders an empty grid row. If the grid is locked, the keys
// are grayed out.
func (m *model) viewGridRowEmpty() string {
keyState := keyStateUnselected
if m.gameOver {
keyState = keyStateAbsent
}
key := m.viewKey(" ", keyState.color())
keys := [numChars]string{key, key, key, key, key}
return lipgloss.JoinHorizontal(lipgloss.Bottom, keys[:]...)
}
// viewKeyboard renders the entire keyboard, including a border. It chooses the
// appropriate color for keys that have been guessed before.
func (m *model) viewKeyboard() string {
topRow := m.viewKeyboardRow([]string{"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"})
midRow := m.viewKeyboardRow([]string{"A", "S", "D", "F", "G", "H", "J", "K", "L"})
botRow := m.viewKeyboardRow([]string{"ENTER", "Z", "X", "C", "V", "B", "N", "M", "DELETE"})
keys := lipgloss.JoinVertical(
lipgloss.Left,
lipgloss.NewStyle().Padding(0, 2).Render(topRow),
lipgloss.NewStyle().Padding(0, 4).Render(midRow),
botRow,
)
return lipgloss.NewStyle().
Border(lipgloss.NormalBorder()).
BorderForeground(keyStateUnselected.color()).
Padding(0, 1).
Render(keys)
}
// viewKeyboardRow renders a single row of the keyboard. It chooses the
// appropriate color for keys that have been guessed before.
func (m *model) viewKeyboardRow(keys []string) string {
keysRendered := make([]string, len(keys))
for _, key := range keys {
status := keyStateUnselected
if len(key) == 1 {
key := key[0]
status = m.keyStates[key]
}
keysRendered = append(keysRendered, m.viewKey(key, status.color()))
}
return lipgloss.JoinHorizontal(lipgloss.Bottom, keysRendered...)
}
// viewKey renders a key with the given name and color.
func (*model) viewKey(key string, color lipgloss.TerminalColor) string {
return lipgloss.NewStyle().
Padding(0, 1).
Border(lipgloss.NormalBorder()).
BorderForeground(color).
Foreground(color).
Render(key)
}
// withDb runs a function in the context of the database. The database is
// automatically saved at the end.
func (m *model) withDb(f func(db *db)) tea.Cmd {
db, err := loadDb()
if err != nil {
return m.reportError(err, "Error loading database.")
}
f(db)
if err := db.save(); err != nil {
return m.reportError(err, "Error saving database.")
}
return nil
}
// reportError stores the given error and prints a message to the status line.
func (m *model) reportError(err error, msg string) tea.Cmd {
m.errors = append(m.errors, err)
return m.setStatus(msg, 3*time.Second)
}
// msgResetStatus is sent when the status line should be reset.
type msgResetStatus struct{}
const (
colorPrimary = lipgloss.Color("#d7dadc")
colorSecondary = lipgloss.Color("#626262")
colorSeparator = lipgloss.Color("#9c9c9c")
colorYellow = lipgloss.Color("#b59f3b")
colorGreen = lipgloss.Color("#538d4e")
)
// keyState represents the state of a key.
type keyState int
const (
keyStateUnselected keyState = iota
keyStateAbsent
keyStatePresent
keyStateCorrect
)
// color returns the appropriate dark mode color for the given key state.
func (s keyState) color() lipgloss.Color {
switch s {
case keyStateUnselected:
return colorPrimary
case keyStateAbsent:
return colorSecondary
case keyStatePresent:
return colorYellow
case keyStateCorrect:
return colorGreen
default:
panic("invalid key status")
}
}
var _controls = fmt.Sprintf("%s %s %s %s %s",
lipgloss.NewStyle().Foreground(colorPrimary).Render("ctrl+c"),
lipgloss.NewStyle().Foreground(colorSecondary).Render("quit"),
lipgloss.NewStyle().Foreground(colorSeparator).Render("//"),
lipgloss.NewStyle().Foreground(colorPrimary).Render("ctrl+r"),
lipgloss.NewStyle().Foreground(colorSecondary).Render("restart"),
)
// isAsciiUpper checks if a rune is between A-Z.
func isAsciiUpper(r rune) bool {
return 'A' <= r && r <= 'Z'
}
// toAsciiUpper converts a rune to uppercase if it is between A-Z.
func toAsciiUpper(r rune) rune {
if 'a' <= r && r <= 'z' {
r -= 'a' - 'A'
}
return r
}