package snakesimulator func (p Point) Copy() (pCopy *Point) { pCopy = &Point{ X: p.X, Y: p.Y, } return } func NewSnake(direction Direction, field Field) (s *Snake) { fieldCenterX := field.Width / 2 fieldCenterY := field.Height / 2 switch direction { case Direction_Left: s = &Snake{ Points: []*Point{ &Point{X: fieldCenterX - 1, Y: fieldCenterY}, &Point{X: fieldCenterX, Y: fieldCenterY}, &Point{X: fieldCenterX + 1, Y: fieldCenterY}, }, } case Direction_Right: s = &Snake{ Points: []*Point{ &Point{X: fieldCenterX + 1, Y: fieldCenterY}, &Point{X: fieldCenterX, Y: fieldCenterY}, &Point{X: fieldCenterX - 1, Y: fieldCenterY}, }, } case Direction_Down: s = &Snake{ Points: []*Point{ &Point{X: fieldCenterX, Y: fieldCenterY - 1}, &Point{X: fieldCenterX, Y: fieldCenterY}, &Point{X: fieldCenterX, Y: fieldCenterY + 1}, }, } default: s = &Snake{ Points: []*Point{ &Point{X: fieldCenterX, Y: fieldCenterY + 1}, &Point{X: fieldCenterX, Y: fieldCenterY}, &Point{X: fieldCenterX, Y: fieldCenterY - 1}, }, } } return } func (s *Snake) NewHead(direction Direction) (newHead *Point) { newHead = s.Points[0].Copy() switch direction { case Direction_Up: newHead.Y -= 1 case Direction_Down: newHead.Y += 1 case Direction_Right: newHead.X += 1 case Direction_Left: newHead.X -= 1 } return } func (s *Snake) Move(newHead *Point) { s.Points = s.Points[:len(s.Points)-1] s.Points = append([]*Point{newHead}, s.Points...) } func (s *Snake) Feed(food *Point) { s.Points = append([]*Point{food}, s.Points...) } func (s *Snake) selfCollision(head *Point, direction Direction) bool { selfCollisionIndex := -1 for index, point := range s.Points[:len(s.Points)-1] { if point.X == head.X && point.Y == head.Y { selfCollisionIndex = index break } } if selfCollisionIndex == 1 { switch direction { case Direction_Up: head.Y += 2 case Direction_Down: head.Y -= 2 case Direction_Left: head.X += 2 default: head.X -= 2 } return false } return selfCollisionIndex >= 0 } func wallCollision(head *Point, field Field) bool { return head.X >= field.Width || head.Y >= field.Height || head.X < 0 || head.Y < 0 } func foodCollision(head *Point, food *Point) bool { return head.X == food.X && head.Y == food.Y }