-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
310 lines (279 loc) · 6.93 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
package main
import (
"github.com/gdamore/tcell"
"math/rand"
"os"
"sync"
"time"
)
type Status string
type GameMode int64
const (
EASY GameMode = iota
MEDIUM
HARD
)
const (
height = 25
width = 80
UP = "UP"
DOWN = "DOWN"
RIGHT = "RIGHT"
LEFT = "LEFT"
GAME_OVER Status = "GAME OVER"
NOT_STARTED Status = "NOT STARTED"
STARTED Status = "STARTED"
)
type Game struct {
Snake
Screen tcell.Screen
Event chan string
mu sync.Mutex
mode GameMode
food Food
status Status
}
type Food struct {
FoodPosition *Position
}
func newFood(x, y int) Food {
return Food{FoodPosition: &Position{x, y}}
}
func (game *Game) printFood() {
game.Screen.SetContent(game.food.FoodPosition.X, game.food.FoodPosition.Y, '🍔', nil, tcell.StyleDefault)
}
func (game *Game) printSnake() {
snakeStyle := tcell.StyleDefault.Background(tcell.ColorGreen)
for _, pos := range *game.Snake.Positions {
game.Screen.SetContent(pos.X, pos.Y, tcell.RuneCkBoard, nil, snakeStyle)
}
game.printFood()
}
func main() {
rand.Seed(time.Now().UnixNano())
screen, err := tcell.NewScreen()
if err != nil {
panic(err)
}
err = screen.Init()
screen.SetStyle(tcell.StyleDefault.Background(tcell.ColorBlack).Foreground(tcell.ColorWhite).Bold(true))
if err != nil {
panic(err)
}
game := Game{
NewSnake(),
screen,
make(chan string, 10),
sync.Mutex{},
MEDIUM,
newFood(rand.Intn(width), rand.Intn(height)),
NOT_STARTED,
}
mode := make(chan GameMode, 1)
go game.listenEvent(mode)
go game.setGameMode(mode)
defer close(game.Event)
ticker := time.NewTicker(game.speed())
defer ticker.Stop()
for {
game.Screen.Clear()
select {
case event := <-game.Event:
game.Screen.Clear()
game.UpdateSnakePosition(event)
case <-ticker.C:
game.updateScreen()
ticker.Reset(game.speed())
}
}
}
func (game *Game) speed() time.Duration {
//fmt.Printf("Speed \n", game.mode)
switch game.mode {
case EASY:
return 800 * time.Millisecond
case MEDIUM:
return 500 * time.Millisecond
case HARD:
return 100 * time.Millisecond
default:
return 500 * time.Millisecond
}
}
func (game *Game) UpdateSnakePosition(dir string) {
existingPosition := *game.Snake.Positions
len := len(existingPosition)
isValid := verifyValidMovement(dir, game.Snake.Direction)
if !isValid {
return
}
game.Direction = dir
newX := 0
newY := 0
if dir == UP {
newY = -1
} else if dir == LEFT {
newX = -1
} else if dir == RIGHT {
newX = 1
} else {
newY = 1
}
newPosition := &Position{existingPosition[len-1].X + newX, existingPosition[len-1].Y + newY}
if game.isGameOver(newPosition) {
game.endGame()
}
existingPosition = append(existingPosition, *newPosition)
if game.canEatFood(newPosition) {
game.food = newFood(rand.Intn(width), rand.Intn(height))
} else {
existingPosition = existingPosition[1:]
}
game.Snake.Positions = &existingPosition
game.printSnake()
}
func (game *Game) canEatFood(position *Position) bool {
return game.food.FoodPosition.X == position.X && game.food.FoodPosition.Y == position.Y
}
func verifyValidMovement(direction string, snakeDir string) bool {
if (direction == RIGHT && snakeDir == LEFT) || (direction == LEFT && snakeDir == RIGHT) {
return false
}
if (direction == UP && snakeDir == DOWN) || (direction == DOWN && snakeDir == UP) {
return false
}
return true
}
func (game *Game) listenEvent(modeChan chan GameMode) {
for {
event := game.Screen.PollEvent()
switch e := event.(type) {
case *tcell.EventResize:
game.Screen.Sync()
case *tcell.EventKey:
if game.status == NOT_STARTED {
//fmt.Printf(" \nUPDATED %s \n", e.Name())
if e.Key() == tcell.KeyUp && game.mode == MEDIUM {
modeChan <- EASY
} else if e.Key() == tcell.KeyUp && game.mode == HARD {
modeChan <- MEDIUM
} else if e.Key() == tcell.KeyDown && game.mode == EASY {
modeChan <- MEDIUM
} else if e.Key() == tcell.KeyDown && game.mode == MEDIUM {
modeChan <- HARD
} else if e.Key() == tcell.KeyEscape || e.Key() == tcell.KeyEnter {
game.status = STARTED
game.UpdateSnakePosition(game.Direction)
close(modeChan)
continue
}
continue
}
if e.Key() == tcell.KeyEscape || e.Key() == tcell.KeyCtrlC {
game.Screen.Fini()
os.Exit(0)
} else if e.Key() == tcell.KeyUp {
game.Event <- UP
} else if e.Key() == tcell.KeyDown {
game.Event <- DOWN
} else if e.Key() == tcell.KeyLeft {
game.Event <- LEFT
} else if e.Key() == tcell.KeyRight {
game.Event <- RIGHT
}
}
}
}
func (game *Game) updateScreen() {
game.Screen.Clear()
game.setBorder()
game.loadGame()
game.UpdateFoodAndSnakePosition()
game.printOver()
game.Screen.Show()
}
func (game *Game) setBorder() {
boardStyle := tcell.StyleDefault.Background(tcell.ColorBlack).Foreground(tcell.ColorWhite)
game.Screen.SetContent(0, 0, tcell.RuneULCorner, nil, boardStyle)
game.Screen.SetContent(0, height, tcell.RuneLLCorner, nil, boardStyle)
for i := 1; i < height; i++ {
game.Screen.SetContent(0, i, tcell.RuneVLine, nil, boardStyle)
game.Screen.SetContent(width, i, tcell.RuneVLine, nil, boardStyle)
}
for i := 1; i < width; i++ {
game.Screen.SetContent(i, height, tcell.RuneHLine, nil, boardStyle)
game.Screen.SetContent(i, 0, tcell.RuneHLine, nil, boardStyle)
}
game.Screen.SetContent(width, height, tcell.RuneLRCorner, nil, boardStyle)
game.Screen.SetContent(width, 0, tcell.RuneURCorner, nil, boardStyle)
}
func (game *Game) loadGame() {
if game.status != NOT_STARTED {
return
}
x := width / 10
y := height / 10
displayWords := []string{"Select Game Mode : ", "EASY", "MEDIUM", "HARD", " Press ENTER To Continue"}
for _, word := range displayWords {
y++
if game.isCurrentGameMode(word) {
word = "> " + word
} else {
word = " " + word
}
for i, ch := range word {
game.Screen.SetContent(x+i, y, ch, nil, tcell.StyleDefault)
}
}
}
func (game *Game) setGameMode(modeChan chan GameMode) {
for {
select {
case x, ok := <-modeChan:
if !ok {
return
} else {
game.mu.Lock()
game.mode = x
game.mu.Unlock()
game.updateScreen()
}
}
}
}
func (game *Game) isCurrentGameMode(mode string) bool {
switch game.mode {
case EASY:
return mode == "EASY"
case MEDIUM:
return mode == "MEDIUM"
case HARD:
return mode == "HARD"
}
return false
}
func (game *Game) UpdateFoodAndSnakePosition() {
if game.status != STARTED {
return
}
game.printFood()
game.UpdateSnakePosition(game.Direction)
}
func (game *Game) isGameOver(position *Position) bool {
if game.status == GAME_OVER {
return true
}
return position != nil && (position.X == 0 || position.X == width || position.Y == height || position.Y == 0)
}
func (game *Game) endGame() {
game.mu.Lock()
defer game.mu.Unlock()
game.status = GAME_OVER
}
func (game *Game) printOver() {
if game.isGameOver(nil) {
for i, ch := range "GAME OVER" {
game.Screen.SetContent(width/5+i, height/5, ch, nil, tcell.StyleDefault)
}
}
}