from turtle import Turtle

class Snake:
    def __init__(self):
        self.segments = []
        self.length = 3
        self.extend_snake = False
        for i in range(self.length):
            turtle = Turtle(shape="square")
            turtle.color("white")
            turtle.pu()
            x_pos = -i *20
            turtle.teleport(x=x_pos)
            self.segments.append(turtle)
        
    def move(self):
        tail_position = self.segments[-1].position()

        for i in range(len(self.segments) - 1, 0, -1):
            self.segments[i].goto(self.segments[i-1].position())
        self.segments[0].forward(20)

        if self.extend_snake == True:
            turtle = Turtle(shape="square")
            turtle.color("white")
            turtle.pu()
            turtle.goto(tail_position)
            self.segments.append(turtle)
            self.extend_snake = False

    def up(self):
        if self.segments[0].heading() != 270:
            for segment in self.segments:
                segment.setheading(90)

    def right(self):
        if self.segments[0].heading() != 180:
            for segment in self.segments:
                segment.setheading(0)

    def down(self):
        if self.segments[0].heading() != 90:
            for segment in self.segments:
                segment.setheading(270)

    def left(self):
        if self.segments[0].heading() != 0:
            for segment in self.segments:
                segment.setheading(180)

    def get_head_position(self):
        return self.segments[0].xcor(), self.segments[0].ycor()
    
    def tailbite(self):
        for i in range(len(self.segments) - 1, 0, -1):
            if self.segments[0].position() == self.segments[i].position():
                return True
        return False
    
    def extend(self):
        self.extend_snake = True