-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
348 lines (289 loc) · 8.79 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
package main
// Wordle game written in Golang with Bubbletea
import (
_ "embed"
"encoding/json"
"fmt"
"math/rand"
"os"
"slices"
"strings"
"time"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
//go:embed words.txt
var wordsString string
var whiteKeyStyle = lipgloss.NewStyle().Border(lipgloss.NormalBorder()).Padding(0, 1)
var orangeKeyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ff8100")).Border(lipgloss.NormalBorder()).BorderForeground(lipgloss.Color("#ff8100")).Padding(0, 1)
var greenKeyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")).Border(lipgloss.NormalBorder()).BorderForeground(lipgloss.Color("#04B575")).Padding(0, 1)
var greyKeyStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#666666")).Border(lipgloss.NormalBorder()).BorderForeground(lipgloss.Color("#666666")).Padding(0, 1)
var validInputStyle = lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).Width(25)
var invalidInputStyle = lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderForeground(lipgloss.Color("#ff0000")).Width(25)
type Guess struct {
Correct bool `json:"correct"`
Guess string `json:"guess"`
CorrectLettersIndex []int `json:"correctLettersIndex"`
IncorrectLettersIndex []int `json:"incorrectLettersIndex"`
}
type PlayerState string
const (
Playing PlayerState = "playing"
Win PlayerState = "win"
Lose PlayerState = "lose"
)
type game struct {
Date string `json:"date"`
Word string
State PlayerState `json:"state"`
Guesses []Guess `json:"guesses"`
Streak int `json:"streak"`
UsedLetters []string `json:"usedLetters"`
}
type Model struct {
width int
height int
game game
lastGame game
words []string
maxTries int
keyboard [][]string
guessInput textinput.Model
inputStyle lipgloss.Style
}
func checkGuess(game *game, guess string) Guess {
var g Guess
guess = strings.ToLower(guess)
g.Guess = guess
// Handle correct guess first
if strings.ToLower(game.Word) == guess {
g.Correct = true
g.CorrectLettersIndex = []int{0, 1, 2, 3, 4}
return g
}
// Handle incorrect guess
for i, l := range guess {
if l == rune(game.Word[i]) {
g.CorrectLettersIndex = append(g.CorrectLettersIndex, i)
} else if slices.Contains(strings.Split(game.Word, ""), string(l)) {
g.IncorrectLettersIndex = append(g.IncorrectLettersIndex, i)
} else if !slices.Contains(game.UsedLetters, string(l)) {
game.UsedLetters = append(game.UsedLetters, string(l))
}
}
return g
}
func checkPlayerState(guesses []Guess, maxTries int) PlayerState {
// Check if the last guess was correct
if len(guesses) > 0 && guesses[len(guesses)-1].Correct {
return Win
}
// Check if the player has run out of tries
if len(guesses) == maxTries {
return Lose
}
return Playing
}
func saveGameToFile(m Model) {
var games []game
var currentGame game
file, _ := os.ReadFile(fmt.Sprintf("%s/.tuidle.json", os.Getenv("HOME")))
json.Unmarshal([]byte(file), &games)
// Either use the last result or make new one
currentDate := time.Now().Format("2006-01-02")
if len(games) > 0 && games[len(games)-1].Date == currentDate {
currentGame = games[len(games)-1]
games = games[:len(games)-1]
} else {
currentGame = game{
Date: m.game.Date,
}
}
currentGame.State = m.game.State
currentGame.UsedLetters = m.game.UsedLetters
currentGame.Guesses = m.game.Guesses
streak, err := checkStreak(currentGame.State, m.lastGame.Streak, m.lastGame.Date, m.game.Date)
if err != nil {
fmt.Println("Error checking streak")
return
}
currentGame.Streak = streak
games = append(games, currentGame)
marshalledGames, err := json.Marshal(games)
if err != nil {
return
}
err = os.WriteFile(fmt.Sprintf("%s/.tuidle.json", os.Getenv("HOME")), marshalledGames, 0666)
if err != nil {
fmt.Println(err)
}
}
func getGameByIndex(index int) (game, error) {
file, err := os.ReadFile(fmt.Sprintf("%s/.tuidle.json", os.Getenv("HOME")))
if err != nil {
return game{}, err
}
var games []game
json.Unmarshal([]byte(file), &games)
if len(games) == 0 {
return game{}, nil
}
if len(games)+index < 0 {
return game{}, nil
}
return games[len(games)+index], nil
}
func checkStreak(state PlayerState, lastStreak int, lastDateString, todayDateString string) (int, error) {
if state == Lose {
return 0, nil
}
if state == Playing {
return lastStreak, nil
}
todayDate, err := time.Parse("2006-01-02", todayDateString)
if err != nil {
return 1, err
}
lastDate, _ := time.Parse("2006-01-02", lastDateString)
if err != nil {
return 1, err
}
if todayDate.Sub(lastDate).Hours() == 24 {
return lastStreak + 1, nil
} else {
return 1, nil
}
}
func (m Model) Init() tea.Cmd { return nil }
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c":
return m, tea.Quit
case "enter":
if m.game.State != Playing || len(m.guessInput.Value()) != 5 {
return m, nil
}
if !slices.Contains(m.words, m.guessInput.Value()) {
m.guessInput.SetValue("")
m.inputStyle = invalidInputStyle
return m, nil
}
m.inputStyle = validInputStyle
if len(m.game.Guesses) < m.maxTries {
m.game.Guesses = append(m.game.Guesses, checkGuess(&m.game, m.guessInput.Value()))
m.guessInput.SetValue("")
}
m.game.State = checkPlayerState(m.game.Guesses, m.maxTries)
saveGameToFile(m)
return m, nil
}
}
m.guessInput, cmd = m.guessInput.Update(msg)
return m, cmd
}
func (m Model) View() string {
var s string
switch m.game.State {
case Playing:
s += "Make a guess!\n\n"
case Win:
s += "You win!\n"
s += fmt.Sprintf("The word was: %s\n", m.game.Word)
s += fmt.Sprintf("You made %d guesses\n\n", len(m.game.Guesses))
case Lose:
s += "You lose!\n"
s += fmt.Sprintf("The word was: %s\n\n", m.game.Word)
}
for _, g := range m.game.Guesses {
var letters []string
for i, l := range g.Guess {
if slices.Contains(g.CorrectLettersIndex, i) {
letters = append(letters, greenKeyStyle.Render(fmt.Sprintf("%s", string(l))))
} else if slices.Contains(g.IncorrectLettersIndex, i) {
letters = append(letters, orangeKeyStyle.Render(fmt.Sprintf("%s", string(l))))
} else {
letters = append(letters, whiteKeyStyle.Render(fmt.Sprintf("%s", string(l))))
}
}
s += lipgloss.JoinHorizontal(lipgloss.Left, letters...)
s += "\n"
}
if m.game.State == Playing {
s += m.inputStyle.Render(m.guessInput.View())
s += "\n\n"
for _, row := range m.keyboard {
var keys []string
for _, key := range row {
if slices.Contains(m.game.UsedLetters, strings.ToLower(key)) {
keys = append(keys, greyKeyStyle.Render(key))
} else {
keys = append(keys, whiteKeyStyle.Render(key))
}
}
s += lipgloss.JoinHorizontal(lipgloss.Center, keys...)
s += "\n"
}
} else {
streak, _ := checkStreak(m.game.State, m.lastGame.Streak, m.lastGame.Date, m.game.Date)
s += fmt.Sprintf("Your current streak is %d\n", streak)
}
s += "\nPress Ctrl+C to quit\n"
return lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, lipgloss.JoinVertical(lipgloss.Center, s))
}
func main() {
currentTime := time.Now()
currentGame, _ := getGameByIndex(-1)
lastGameIdx := -1
if currentGame.Date == time.Now().Format("2006-01-02") {
// If game was already finished today
if currentGame.State != Playing {
fmt.Println("You've already played today, come back tomorrow for the next word!")
fmt.Println("Your current streak is", currentGame.Streak)
return
}
lastGameIdx = -2
}
lastGame, _ := getGameByIndex(lastGameIdx)
words := strings.Split(wordsString, "\n")
keyboard := [][]string{{"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"}, {"A", "S", "D", "F", "G", "H", "J", "K", "L"}, {"Z", "X", "C", "V", "B", "N", "M"}}
// Seed random generator with date and generate random word index
year, month, day := currentTime.Date()
date := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
r := rand.New(rand.NewSource(date.UnixNano()))
num := r.Intn(len(words))
textInput := textinput.New()
textInput.Focus()
textInput.Placeholder = "Guess a word"
textInput.CharLimit = 5
textInput.Width = 20
model := Model{
// Choose first word for now
words: words,
maxTries: 6,
guessInput: textInput,
inputStyle: validInputStyle,
keyboard: keyboard,
}
if currentGame.Date == time.Now().Format("2006-01-02") {
model.game = currentGame
} else {
model.game = game{
Date: date.Format("2006-01-02"),
State: Playing,
}
}
model.lastGame = lastGame
model.game.Word = words[num]
p := tea.NewProgram(model, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}