snake/snake.go

103 lines
2.1 KiB
Go

package main
import (
"github.com/gdamore/tcell/v2"
)
func initSnake(snakex *int, snakey *int) Snake {
var x, y int = *snakex, *snakey
snake := Snake{
head: Position{
x: x,
y: y,
},
tail: []Position{
{
x: x - 1,
y: y,
},
{
x: x - 2,
y: y,
},
{
x: x - 3,
y: y,
},
},
length: 3,
direction: 1,
}
return snake
}
func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
// Reverse tail, chop of the excesses,
snake.tail = ReverseSlice(snake.tail)
if len(snake.tail) > snake.length {
snake.tail = snake.tail[:snake.length]
}
// reverse it back to the original order, replace the tail in `snake`
snake.tail = ReverseSlice(snake.tail)
// Draw the body
for _, segment := range snake.tail {
screen.SetContent(segment.x, segment.y, '+', nil, style)
}
// Draw the head, make sure it is on top of everything
screen.SetContent(snake.head.x, snake.head.y, '0', nil, style)
}
func snakeDirection(press int, snake *Snake) {
if press == Left {
if snake.direction != Right {
snake.head.x--
snake.tail = append(snake.tail, Position{x: snake.head.x + 1, y: snake.head.y})
snake.direction = press
}
} else if press == Right {
if snake.direction != Left {
snake.head.x++
snake.tail = append(snake.tail, Position{x: snake.head.x - 1, y: snake.head.y})
snake.direction = press
}
} else if press == Up {
if snake.direction != Down {
snake.head.y--
snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y + 1})
snake.direction = press
}
} else if press == Down {
if snake.direction != Up {
snake.head.y++
snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y - 1})
snake.direction = press
}
}
}
// Check if a pos hits the tail
func hitsTail(snake *Snake, x int, y int) bool {
var hit bool = false
for _, segment := range snake.tail {
if segment.x == x && segment.y == y {
hit = true
}
}
return hit
}
func ReverseSlice[T comparable](s []T) []T {
var r []T
for i := len(s) - 1; i >= 0; i-- {
r = append(r, s[i])
}
return r
}