-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
237 lines (192 loc) ยท 5.04 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
package main
import (
"fmt"
"os"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
type coord struct {
x int
y int
}
type direction int
type tickMsg time.Time
type model struct {
// The coordinates of the body of the snake, ordered from tail to head.
body []coord
// The coordinates of the current food.
food coord
// The index of the current food glyph.
foodGlyphIndex int
// The heading(s) of the snake. As keys are pressed, we append to this list,
// and "play back" the changes one tick at a time.
headings []direction
// The current length of the snake
length int
tickDuration time.Duration
hasCrashed bool
highScore int
}
const (
rows = 16
cols = 16
initLength = 3
)
const (
up direction = iota
right
down
left
)
var foodGlyphs = [...]string{"๐", "๐", "๐", "๐", "๐ฐ"}
func initialModel(highScore int) model {
return model{
body: []coord{{x: 0, y: 0}},
food: coord{x: 6, y: 0},
foodGlyphIndex: 0,
headings: []direction{right},
length: initLength,
tickDuration: time.Millisecond * 150,
hasCrashed: false,
highScore: highScore,
}
}
func (m model) score() int {
return m.length - initLength
}
func (m model) Init() tea.Cmd {
return tickEvery(m.tickDuration)
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
// Is it a key press?
case tea.KeyMsg:
// Cool, what was the actual key pressed?
switch msg.String() {
// These keys should exit the program.
case "ctrl+c", "q":
// Try to persist high score
config, _ := LoadConfig()
config.HighScore = m.highScore
err := config.Save()
if err != nil {
fmt.Printf("Error saving config: %v", err)
}
return m, tea.Quit
case " ":
if m.hasCrashed {
m = initialModel(m.highScore)
return m, tickEvery(m.tickDuration)
}
case "up":
m.headings = appendHeadingIfLegal(m.headings, up)
case "down":
m.headings = appendHeadingIfLegal(m.headings, down)
case "left":
m.headings = appendHeadingIfLegal(m.headings, left)
case "right":
m.headings = appendHeadingIfLegal(m.headings, right)
}
case tickMsg:
newHead := m.body[len(m.body)-1]
if len(m.headings) > 1 {
m.headings = m.headings[1:]
}
heading := m.headings[0]
switch heading {
case up:
newHead.y--
case down:
newHead.y++
case left:
newHead.x--
case right:
newHead.x++
}
if newHead.x < 0 || newHead.x >= cols || newHead.y < 0 || newHead.y >= rows {
m.hasCrashed = true
return m, nil
}
if newHead == m.food {
m.length++
m.food = getRandomCoord(append(m.body, newHead))
m.foodGlyphIndex = (m.foodGlyphIndex + 1) % len(foodGlyphs)
}
tailStartIndex := len(m.body) - m.length + 1
if tailStartIndex < 0 {
tailStartIndex = 0
}
tail := m.body[tailStartIndex:]
if contains(tail, newHead) {
// The snake has collided with itself.
m.hasCrashed = true
return m, nil
}
m.body = append(tail, newHead)
if m.score() > m.highScore {
m.highScore = m.score()
}
return m, tickEvery(m.tickDuration)
}
// Return the updated model to the Bubble Tea runtime for processing.
// Note that we're not returning a command.
return m, nil
}
func (m model) View() string {
footerStyle := lipgloss.NewStyle().Faint(true).Width(cols * 2).Align(lipgloss.Center)
crossBar := strings.Repeat("โ", cols*2)
scoreStyle := lipgloss.NewStyle().Bold(true)
var highScoreStyle lipgloss.Style
if m.score() < m.highScore {
highScoreStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#999999"))
} else {
highScoreStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("#00ff00"))
}
var headGlyph, bodyGlyph, footerMsg string
if m.hasCrashed {
headGlyph = "๐"
bodyGlyph = "๐"
footerMsg = "Space to start, q to quit"
} else {
headGlyph = "๐"
bodyGlyph = "๐"
footerMsg = "โ โ โ โ, q to quit"
}
scoreStr := scoreStyle.Render(fmt.Sprintf(" Score: %d", m.score()))
highScoreStr := highScoreStyle.Render(fmt.Sprintf("High Score: %d ", m.highScore))
scoreSpacerWidth := cols*2 - lipgloss.Width(scoreStr) - lipgloss.Width(highScoreStr)
s := "โญ" + crossBar + "โฎ\n"
s += "โ" + scoreStyle.Render(scoreStr) + strings.Repeat(" ", scoreSpacerWidth) + highScoreStyle.Render(highScoreStr) + "โ\n"
s += "โ" + crossBar + "โค\n"
for r := 0; r < rows; r++ {
s += "โ"
for c := 0; c < cols; c++ {
pos := coord{x: c, y: r}
if pos == m.food {
s += foodGlyphs[m.foodGlyphIndex]
} else if pos == m.body[len(m.body)-1] {
s += headGlyph
} else if contains(m.body, pos) {
s += bodyGlyph
} else {
s += " "
}
}
s += "โ\n"
}
s += "โ" + crossBar + "โค\n"
s += "โ" + footerStyle.Render(footerMsg) + "โ\n"
s += "โฐ" + crossBar + "โฏ\n"
// Send the UI for rendering
return s
}
func main() {
config, _ := LoadConfig()
p := tea.NewProgram(initialModel(config.HighScore))
if _, err := p.Run(); err != nil {
fmt.Printf("Alas, there's been an error: %v", err)
os.Exit(1)
}
}