from turtle import *
from random import randrange
from time import sleep
snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]]
apple_x = randrange(-20,20)*10
apple_y = randrange(-20,20)*10
aim_x = 10
aim_y = 0
def squre(x,y,size,color_name):
up()
goto(x,y)
down()
color(color_name)
begin_fill()
forward(size)
left(90)
forward(size)
left(90)
forward(size)
left(90)
forward(size)
left(90)
end_fill()
def change(x,y):
global aim_x,aim_y
aim_x = x;
aim_y = y;
def inside():
if -210 <= snake[-1][0]<=200 and -210 <= snake[-1][1]<=200:
return True
else:
return False
def gameLoop():
global apple_x,apple_y,aim_x,aim_y,snake
snake.append([snake[-1][0]+aim_x,snake[-1][1]+aim_y])
if not inside():
sleep(2)
return
if snake[-1][0] != apple_x or snake[-1][1]!=apple_y:
snake.pop(0)
else:
apple_x = randrange(-20,20)*10
apple_y = randrange(-20,20)*10
clear()
squre(apple_x,apple_y,10,'red')
for n in range(len(snake)):
squre(snake[n][0],snake[n][1],10,'black')
ontimer(gameLoop,100)
update()
setup(420,420,0,0)
hideturtle()
tracer(False)
listen()
onkey(lambda: change(0,10), "w")
onkey(lambda: change(0,-10), "s")
onkey(lambda: change(-10,0), "a")
onkey(lambda: change(10,0), "d")
gameLoop()
done()