Reputation: 13
In my snake code project, I need to set the tracer to 0 and then use the update method to render a snake game like animation for my turtles. Here is my code:
# setup screen
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Welcome to the snake game!")
screen.tracer(0)
# create a snake body, aka three white turtles
starting_pos = [(0,0), (-20,0), (-40,0)]
segments = []
for position in starting_pos:
new_seg = Turtle("square")
new_seg.color("white")
new_seg.penup()
new_seg.goto(position)
segments.append(new_seg)
# move the snake
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
for seg_num in range(len(segments) - 1, 0, -1):
new_x = segments[seg_num - 1].xcor
new_y = segments[seg_num - 1].ycor
segments[seg_num].goto(new_x, new_y)
Here is the error it gives:
TypeError: unsupported operand type(s) for +: 'method' and 'float'
What should I do?
Upvotes: 1
Views: 365
Reputation: 41872
Your immediate problem is these two lines:
new_x = segments[seg_num - 1].xcor
new_y = segments[seg_num - 1].ycor
xcor
and ycor
are methods, not properties and so should be invoked:
new_x = segments[seg_num - 1].xcor()
new_y = segments[seg_num - 1].ycor()
However, this fix alone won't get your snake moving, the segments will just pile up on each other. You also need to move the head forward. Below is my rework of your code that tosses while True:
which has no place in an event-driven world like turtle:
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=600, height=600)
screen.title("Welcome to the snake game!")
screen.bgcolor('black')
screen.tracer(0)
# create a snake body, aka three white turtles
starting_pos = [(0, 0), (-20, 0), (-40, 0)]
segments = []
for position in starting_pos:
segment = Turtle('square')
segment.color('white')
segment.penup()
segment.goto(position)
segments.append(segment)
# move the snake
game_is_on = True
def move():
if game_is_on:
for seg_num in range(len(segments) - 1, 0, -1):
new_position = segments[seg_num - 1].position()
segments[seg_num].goto(new_position)
segments[0].forward(20)
screen.update()
screen.ontimer(move, 100) # milliseconds
move()
screen.mainloop()
Upvotes: 1