0

So I'm currently creating a sort of snake game, which uses OOP, and now I've created a Snake Class, which you can see here below.

from turtle import Turtle
#Create the Snake Body and Class, starting with 3 white squares.
STARTING_POSITIONS = [(0,0),(-20,0),(-40,0)]
MOVE_DISTANCE = 20
#make segments list and snake object for snake body, that will get appended with each new body part
class Snake:

    def __init__(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 then I import it into the main python file, using the turtle module to visualize it.

from turtle import Screen, Turtle
from snake import Snake
import time

#setup screen, widths, and heights)
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Armand's Snake game!")
#tracer function to turn animation on/off)
screen.tracer(0)
screen.textinput(title="Start!",prompt="Type Anything to Start Playing the Snake Game: ")


snake = Snake()

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


screen.exitonclick()

Now it should run fine, I've made this based on following a Udemy Course, but there's still this AttributeError:

Traceback (most recent call last):
  File "c:\Users\Armand S\Desktop\Python Files\D20 The Snake Game.py", line 16, in <module>
    snake = Snake()
  File "c:\Users\Armand S\Desktop\Python Files\snake.py", line 10, in __init__
    self.create_snake()
AttributeError: 'Snake' object has no attribute 'create_snake'

I don't quite fully understand the problem. Any help and criticism would be appreciated

1 Answers1

-1

You don't need to define this function using self. class Snake:

    def __init__(self):
        self.segments = []
        self.create_snake() <----------------#This one need not to be here. Below function is enough. Remove this and see.

        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)
        ```