(Python) How can the 'head' attribute use the method of the Turtle class in this code?

34 Views Asked by At
from turtle import Turtle
starting_position = [(0, 0), (-20, 0), (-40, 0)]
move_distance = 20

class Snake:

    def __init__(self):
        self.segments = []  # attribute
        self.create_snake()  # method
        self.head = self.segments[0]

    def create_snake(self):
        for _ in starting_position:
            segment = Turtle(shape="square")
            segment.penup()
            segment.color('white')
            segment.goto(_)
            self.segments.append(segment)

    def move(self):
        for seg_number in range(len(self.segments)-1, 0, -1):
            new_x_pos = self.segments[seg_number - 1].xcor()
            new_y_pos = self.segments[seg_number - 1].ycor()
            self.segments[seg_number].goto(new_x_pos, new_y_pos)
        self.head.forward(20)

    def up(self):
        self.head.setheading(90)

I'm a beginner coder, but I don't really understand how 'attributes' connect using 'self' inside the class.

In this code, "self.head = self.segments[0]", I don't understand how "self.segments" in the first place become objects in the turtle class.

Although it's a code I wrote, I don't know how "self.segments" can use the method of "turtle" class.

Can someone explain it to me?

0

There are 0 best solutions below