贪吃蛇(python小海龟)

#导入库并赋值
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() #暂停屏幕
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值