#导入库并赋值
import turtle as t
import copy as c
import random as r
#初始化
#建立一个蛇的位置列表
snake = [[0,0]]
#下一步将移动的位置,“5”是一节蛇的边长
aim = [0,5]
#创建食物的随机位置
food = [r.randrange(-25,25)*5,r.randrange(-25,25)*5]
#调整下一步的自制函数
def change_direction(x,y):
aim[0]=x
aim[1]=y
#画出方块(蛇、食物)
def square(x,y,color):
t.penup()#抬笔
t.goto(x,y)#移动到要画方块(蛇、食物)的地方
t.pendown()#落笔
t.color(color) #设置画笔颜色
t.begin_fill() #开始填充
for i in range(4):#画方块
t.forward(5)
t.left(90)
t.end_fill()#结束填充
#判断是否触碰边界
def inside(head):
if head[0]>250:
head[0]-=250*2
elif head[0]<-250:
head[0]+=250*2
if head[1]>250:
head[1]-=250*2
elif head[1]<-250:
head[1]+=250*2
return head
#移动方式:头部添加方块,尾巴消除一个方块
#头:最后画的、最上面的方块
#画头
def move_snake():
#画头
head=c.deepcopy(snake[-1]) #复制一份头部坐标
#确定方向
head=[head[0]+aim[0],head[1]+aim[1]] #确定新头的坐标
if head in snake:#判断是否会死
square(head[0],head[1],5,'yellow')
#边界判断
inside(head)
#蛇的移动
if head==food:#吃到食物
food[0]=r.randrange(-24,24)*5
food[1]=r.randrange(-24,24)*5
else:
snake.pop(0) #去尾巴
snake.append(head) #添加头
#删除之前的动画
t.clear()
#画食物
square(food[0],food[1],'red')
#画蛇
for i in snake:
square(i[0],i[1],'blue')
#循环执行
t.update() #刷新
t.ontimer(move_snake,100) #递归
t.tracer(False)#除去动画效果
t.hideturtle() #隐藏箭头
#监听键盘
t.listen()
t.onkey(lambda :change_direction(0,5),'Up')#↑
t.onkey(lambda :change_direction(0,-5),'Down')#↓
t.onkey(lambda :change_direction(5,0),'Right')#→
t.onkey(lambda :change_direction(-5,0),'Left')#←
#设定屏幕大小
t.setup(500,500)
#运行
move_snake()
t.done() #暂停屏幕
贪吃蛇(python小海龟)
最新推荐文章于 2025-03-25 19:59:39 发布