Home > OS >  Getting AttributeError in Python, unable to figure out why
Getting AttributeError in Python, unable to figure out why

Time:07-17

I am currently doing a python course on Udemy and I am stuck on lesson about creating a snake game. My indentations are correct and i even copied the code from the course and it's still not working. I am unable to figure out why this error occurs.

Here is the file with class Snake:

from turtle import Turtle

STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20


class Snake:

    def __int__(self):
        self.segments = []
        self.create_snake()

    def create_snake(self):
        for position in STARTING_POSITIONS:
            new_segment = Turtle("square")
            new_segment.color("white")
            new_segment.penup()
            new_segment.goto(position)
            self.segments.append(new_segment)

    def move(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.segments[0].forward(MOVE_DISTANCE)

And here is the main file:

from turtle import Screen
from snake import Snake
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.title("Snake Game")
screen.bgcolor("black")
screen.tracer(0)

snake = Snake()

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

screen.exitonclick()

It throws an error:

Traceback (most recent call last):
  File "C:\PythonProjects\snake_game\main.py", line 17, in <module>
    snake.move()
  File "C:\PythonProjects\snake_game\snake.py", line 22, in move
    for seg_num in range(len(self.segments) - 1, 0, -1):
AttributeError: 'Snake' object has no attribute 'segments'

CodePudding user response:

is it because you have a typo? (constructor signature)

def __int__(self):

instead of:

def __init__(self):

?

  • Related