I have tried shifting screen.update() into different parts of the code, but the problem still persist. However, removing screen.tracer(0) and screen.update() resolves the issue. But as the snake gets longer in length, without screen.update() the animation gets clunky.
from turtle import Screen, Turtle
import time
screen = Screen()
screen.setup(width=600, height = 600)
screen.bgcolor("black")
screen.title("Snake Game")
snake_length = []
screen.tracer()
x, y = 0, 0
# TODO Setup initial snake body. Length = range(x)
for i in range(3):
snake_body = Turtle(shape="square")
snake_body.color("white")
snake_body.penup()
snake_body.teleport(x=x, y=y)
snake_body.speed("fastest")
snake_length.append(snake_body)
x -= 20
# TODO Moving the snake
def right(snake):
if snake.heading() == 90 or snake.heading() == 270:
snake.setheading(0)
print(snake.heading())
def left(snake):
if snake.heading() == 90 or snake.heading() == 270:
snake.setheading(180)
print(snake.heading())
def down(snake):
if snake.heading() == 0 or snake.heading() == 180:
snake.setheading(270)
def up(snake):
if snake.heading() == 0 or snake.heading() == 180:
snake.setheading(90)
Function for the movement of the snake.
def tracking_movement(snake_bodies):
cor_list = []
for i in snake_bodies:
x = i.xcor()
y = i.ycor()
temp_cor = [x, y]
cor_list.append(temp_cor)
# has 0, 1, 2
for i in range(1, len(snake_bodies)):
# 1 goes to 0, 2 goes to 1
snake_bodies[i].teleport(cor_list[i-1][0], cor_list[i-1][1])
screen.update()
print(i, snake_bodies[i].pos())
screen.listen()
screen.onkey(lambda: left(snake_length[0]), key="Left")
screen.onkey(lambda: right(snake_length[0]), key="Right")
screen.onkey(lambda: down(snake_length[0]), key="Down")
screen.onkey(lambda: up(snake_length[0]), key="Up")
game_is_on = True
while game_is_on:
tracking_movement(snake_length)
snake_length[0].forward(20)
screen.exitonclick()