#5 Print single line tail

This commit is contained in:
Sacha Ligthert 2023-11-24 21:38:48 +01:00
parent 44f2c5a41d
commit 53e6bfdf4d

View File

@ -35,6 +35,8 @@ func initSnake(snakex *int, snakey *int) Snake {
func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
var tail []rune
// Reverse tail, chop of the excesses,
snake.tail = ReverseSlice(snake.tail)
if len(snake.tail) > snake.length {
@ -43,9 +45,32 @@ func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
// reverse it back to the original order, replace the tail in `snake`
snake.tail = ReverseSlice(snake.tail)
for i, j := range snake.tail {
// The Tail end
if i == 0 {
left := getDirection(j, snake.tail[i+1])
right := getDirection(j, snake.tail[i+1])
tail = append(tail, getLineType(left, right))
// The Bit behind the head
} else if i == len(snake.tail)-1 {
left := getDirection(j, snake.tail[i-1])
right := getDirection(j, snake.head)
tail = append(tail, getLineType(left, right))
// The body of the snake
} else {
left := getDirection(j, snake.tail[i-1])
right := getDirection(j, snake.tail[i+1])
tail = append(tail, getLineType(left, right))
}
}
// Draw the body
for _, segment := range snake.tail {
screen.SetContent(segment.x, segment.y, '+', nil, style)
for i, segment := range snake.tail {
screen.SetContent(segment.x, segment.y, tail[i], nil, style)
}
// Draw the head, make sure it is on top of everything
@ -109,3 +134,41 @@ func validateDirection(snake *Snake, direction int) bool {
return true
}
}
func getDirection(from Position, to Position) int {
var direction int
if from.x-to.x == 1 {
direction = Left
} else if from.x-to.x == -1 {
direction = Right
} else if from.y-to.y == 1 {
direction = Up
} else if from.y-to.y == -1 {
direction = Down
}
return direction
}
func getLineType(from int, to int) rune {
var lineType rune
if (from == Left && to == Down) || (from == Down && to == Left) {
lineType = '┐'
} else if (from == Up && to == Right) || (from == Right && to == Up) {
lineType = '└'
} else if (from == Left && to == Right) || (from == Right && to == Left) {
lineType = '─'
} else if (from == Left && to == Up) || (from == Up && to == Left) {
lineType = '┘'
} else if (from == Right && to == Down) || (from == Down && to == Right) {
lineType = '┌'
} else if (from == Up && to == Down) || (from == Down && to == Up) {
lineType = '│'
}
return lineType
}