123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- 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
- }
|