#8 Added a function to validate if something is a valid move.
This commit is contained in:
parent
65ccadb6d8
commit
1a9d75574b
6
game.go
6
game.go
@ -65,8 +65,10 @@ func gameDirector(screen tcell.Screen, style tcell.Style, keypresses chan int, g
|
||||
// Take input or sleep
|
||||
select {
|
||||
case press := <-keypresses:
|
||||
snakeDirection(press, &snake)
|
||||
lastpress = press
|
||||
if validateDirection(&snake, press) {
|
||||
snakeDirection(press, &snake)
|
||||
lastpress = press
|
||||
}
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
snakeDirection(lastpress, &snake)
|
||||
}
|
||||
|
48
snake.go
48
snake.go
@ -55,29 +55,21 @@ func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
|
||||
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
snake.head.y++
|
||||
snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y - 1})
|
||||
snake.direction = press
|
||||
}
|
||||
}
|
||||
|
||||
@ -101,3 +93,19 @@ func ReverseSlice[T comparable](s []T) []T {
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user