snake.go 803 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package snakesimulator
  2. func (p Point) Copy() (pCopy *Point) {
  3. pCopy = &Point{
  4. X: p.X,
  5. Y: p.Y,
  6. }
  7. return
  8. }
  9. func (s *Snake) NewHead(direction Direction) (newHead *Point) {
  10. newHead = s.Points[0].Copy()
  11. switch direction {
  12. case Direction_Up:
  13. newHead.Y -= 1
  14. case Direction_Down:
  15. newHead.Y += 1
  16. case Direction_Right:
  17. newHead.X += 1
  18. case Direction_Left:
  19. newHead.X -= 1
  20. }
  21. return
  22. }
  23. func (s *Snake) Move(newHead *Point) {
  24. s.Points = s.Points[:len(s.Points)-1]
  25. s.Points = append([]*Point{newHead}, s.Points...)
  26. }
  27. func (s *Snake) Feed(food *Point) {
  28. s.Points = append([]*Point{food}, s.Points...)
  29. }
  30. func (s *Snake) SelfCollision(head *Point) int {
  31. for index, point := range s.Points[:len(s.Points)-1] {
  32. if point.X == head.X && point.Y == head.Y {
  33. return index
  34. }
  35. }
  36. return 0
  37. }