import turtle
from random import randrange
import time
screen = turtle.Screen()
screen.title('Snake with turtle module')
screen.bgcolor('orange')
screen.setup(650, 650)
# draw a field border
border = turtle.Turtle()
border.hideturtle()
border.speed(0)
border.penup()
border.goto(-311, 311)
border.pendown()
border.goto(311, 311)
border.goto(311, -311)
border.goto(-311, -311)
border.goto(-311, 311)
# draw the head of a snake
snake = turtle.Turtle()
snake.shape('square')
snake.speed(0)
snake.penup()
snake = [snake]
# draw a food for the snake
food = turtle.Turtle()
food.speed(0)
food.shape('circle')
food.color('blue')
food.penup()
food.goto(randrange(-300, 300, 20), randrange(-300, 300, 20))
# snake control
screen.onkeypress(lambda: snake[0].setheading(90), 'Up')
screen.onkeypress(lambda: snake[0].setheading(270), 'Down')
screen.onkeypress(lambda: snake[0].setheading(180), 'Left')
screen.onkeypress(lambda: snake[0].setheading(0), 'Right')
screen.listen()
while True:
# creating a new segment of the snake body
if snake[0].distance(food) < 9:
food.goto(randrange(-300, 300, 20), randrange(-300, 300, 20))
snake_segment = turtle.Turtle()
snake_segment.shape('square')
snake_segment.color('gray')
snake_segment.speed(0)
snake_segment.penup()
snake.append(snake_segment)
# snake body movement
if len(snake) > 1:
for i in range(len(snake)-1, 0, -1):
x = snake[i-1].xcor()
y = snake[i-1].ycor()
snake[i].goto(x, y)
snake[0].forward(20)
# snake collision with border
x_cor = snake[0].xcor()
if x_cor > 300 or x_cor < -300:
break
y_cor = snake[0].ycor()
if y_cor > 300 or y_cor < -300:
break
time.sleep(0.3)
screen.mainloop()