snake.go 2.1 KB

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