Skip to content

Instantly share code, notes, and snippets.

@erap129
Created September 27, 2022 13:10
Show Gist options
  • Save erap129/f634ae00281362ee17e0357f875ccf95 to your computer and use it in GitHub Desktop.
Save erap129/f634ae00281362ee17e0357f875ccf95 to your computer and use it in GitHub Desktop.
Snake Part 3 - main.go
package main
import (
"log"
"os"
"github.com/gdamore/tcell"
)
func main() {
screen, err := tcell.NewScreen()
if err != nil {
log.Fatalf("%+v", err)
}
if err := screen.Init(); err != nil {
log.Fatalf("%+v", err)
}
defStyle := tcell.StyleDefault.Background(tcell.ColorBlack).Foreground(tcell.ColorWhite)
screen.SetStyle(defStyle)
game := Game{
Screen: screen,
}
go game.Run()
for {
switch event := game.Screen.PollEvent().(type) {
case *tcell.EventResize:
game.Screen.Sync()
case *tcell.EventKey:
if event.Key() == tcell.KeyEscape || event.Key() == tcell.KeyCtrlC {
game.Screen.Fini()
os.Exit(0)
} else if event.Key() == tcell.KeyUp && game.snakeBody.Yspeed == 0 {
game.snakeBody.ChangeDir(-1, 0)
} else if event.Key() == tcell.KeyDown && game.snakeBody.Yspeed == 0 {
game.snakeBody.ChangeDir(1, 0)
} else if event.Key() == tcell.KeyLeft && game.snakeBody.Xspeed == 0 {
game.snakeBody.ChangeDir(0, -1)
} else if event.Key() == tcell.KeyRight && game.snakeBody.Xspeed == 0 {
game.snakeBody.ChangeDir(0, 1)
} else if event.Rune() == 'y' && game.GameOver {
go game.Run()
} else if event.Rune() == 'n' && game.GameOver {
game.Screen.Fini()
os.Exit(0)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment