snake.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package main
  2. import (
  3. "github.com/gdamore/tcell/v2"
  4. )
  5. // initSnake Initialize the snake
  6. func initSnake(snakex *int, snakey *int) Snake {
  7. var x, y int = *snakex, *snakey
  8. snake := Snake{
  9. head: Position{
  10. x: x,
  11. y: y,
  12. },
  13. tail: []Position{
  14. {
  15. x: x - 1,
  16. y: y,
  17. },
  18. {
  19. x: x - 2,
  20. y: y,
  21. },
  22. {
  23. x: x - 3,
  24. y: y,
  25. },
  26. },
  27. length: 3,
  28. direction: 1,
  29. }
  30. return snake
  31. }
  32. func drawSnake(screen tcell.Screen, style tcell.Style, snake *Snake) {
  33. // Reverse tail, chop of the excesses,
  34. snake.tail = ReverseSlice(snake.tail)
  35. if len(snake.tail) > snake.length {
  36. snake.tail = snake.tail[:snake.length]
  37. }
  38. // reverse it back to the original order, replace the tail in `snake`
  39. snake.tail = ReverseSlice(snake.tail)
  40. // Draw the body
  41. for _, segment := range snake.tail {
  42. screen.SetContent(segment.x, segment.y, '+', nil, style)
  43. }
  44. // Draw the head, make sure it is on top of everything
  45. screen.SetContent(snake.head.x, snake.head.y, '0', nil, style)
  46. }
  47. func snakeDirection(press int, snake *Snake) {
  48. if press == Left {
  49. if snake.direction != Right {
  50. snake.head.x--
  51. snake.tail = append(snake.tail, Position{x: snake.head.x + 1, y: snake.head.y})
  52. snake.direction = press
  53. }
  54. } else if press == Right {
  55. if snake.direction != Left {
  56. snake.head.x++
  57. snake.tail = append(snake.tail, Position{x: snake.head.x - 1, y: snake.head.y})
  58. snake.direction = press
  59. }
  60. } else if press == Up {
  61. if snake.direction != Down {
  62. snake.head.y--
  63. snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y + 1})
  64. snake.direction = press
  65. }
  66. } else if press == Down {
  67. if snake.direction != Up {
  68. snake.head.y++
  69. snake.tail = append(snake.tail, Position{x: snake.head.x, y: snake.head.y - 1})
  70. snake.direction = press
  71. }
  72. }
  73. }
  74. // Check if a pos hits the tail
  75. func hitsTail(snake *Snake, x int, y int) bool {
  76. var hit bool = false
  77. for _, segment := range snake.tail {
  78. if segment.x == x && segment.y == y {
  79. hit = true
  80. }
  81. }
  82. return hit
  83. }
  84. func ReverseSlice[T comparable](s []T) []T {
  85. var r []T
  86. for i := len(s) - 1; i >= 0; i-- {
  87. r = append(r, s[i])
  88. }
  89. return r
  90. }