#8 Added a function to validate if something is a valid move.

This commit is contained in:
Sacha Ligthert 2023-11-23 23:45:55 +01:00
parent 65ccadb6d8
commit 1a9d75574b
2 changed files with 32 additions and 22 deletions

View File

@ -65,8 +65,10 @@ func gameDirector(screen tcell.Screen, style tcell.Style, keypresses chan int, g
// Take input or sleep // Take input or sleep
select { select {
case press := <-keypresses: case press := <-keypresses:
if validateDirection(&snake, press) {
snakeDirection(press, &snake) snakeDirection(press, &snake)
lastpress = press lastpress = press
}
case <-time.After(500 * time.Millisecond): case <-time.After(500 * time.Millisecond):
snakeDirection(lastpress, &snake) snakeDirection(lastpress, &snake)
} }

View File

@ -55,31 +55,23 @@ func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
func snakeDirection(press int, snake *Snake) { func snakeDirection(press int, snake *Snake) {
if press == Left { if press == Left {
if snake.direction != Right {
snake.head.x-- snake.head.x--
snake.tail = append(snake.tail, Position{x: snake.head.x + 1, y: snake.head.y}) snake.tail = append(snake.tail, Position{x: snake.head.x + 1, y: snake.head.y})
snake.direction = press snake.direction = press
}
} else if press == Right { } else if press == Right {
if snake.direction != Left {
snake.head.x++ snake.head.x++
snake.tail = append(snake.tail, Position{x: snake.head.x - 1, y: snake.head.y}) snake.tail = append(snake.tail, Position{x: snake.head.x - 1, y: snake.head.y})
snake.direction = press snake.direction = press
}
} else if press == Up { } else if press == Up {
if snake.direction != Down {
snake.head.y-- snake.head.y--
snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y + 1}) snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y + 1})
snake.direction = press snake.direction = press
}
} else if press == Down { } else if press == Down {
if snake.direction != Up {
snake.head.y++ snake.head.y++
snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y - 1}) snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y - 1})
snake.direction = press snake.direction = press
} }
} }
}
// Check if a pos hits the tail // Check if a pos hits the tail
func hitsTail(snake *Snake, x int, y int) bool { func hitsTail(snake *Snake, x int, y int) bool {
@ -101,3 +93,19 @@ func ReverseSlice[T comparable](s []T) []T {
} }
return r return r
} }
func validateDirection(snake *Snake, direction int) bool {
if snake.direction == direction {
return true
} else if snake.direction == Left && direction == Right {
return false
} else if snake.direction == Right && direction == Left {
return false
} else if snake.direction == Up && direction == Down {
return false
} else if snake.direction == Down && direction == Up {
return false
} else {
return true
}
}