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)
# 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
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') ## x y 位置 图形大小 颜色
for n in range(len(snake)):
squre(snake[n][0],snake[n][1],10,'black')
ontimer(gameLoop,100) #每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()