python初学,贪吃蛇完整代码记录

跟着B站up主做的,权当是仓库记录一下,效果直接粘贴跑下就好了

import turtle
from random import randrange
snake = [[0,0],[0,10],[0,20]]
aim = [0,10]
food = [-10,0]

def change_direction(x,y):
    aim[0] = x
    aim[1] = y

def square(x,y,size,color):
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()
    turtle.color(color)
    turtle.begin_fill()
    for i in range(4):
        turtle.forward(size)
        turtle.left(90)
        turtle.end_fill()
def inside(head):
    return -250<head[0]<250 and -250<head[1]<250

import copy
def snake_move():
    head = copy.deepcopy(snake[-1])
    head = [head[0]+aim[0],head[1]+aim[1]]

    print("snake的长度", len(snake))
    if head in snake or not inside(head):
        print("game over")
        square(head[0],head[1],10,"red")
        return
    if head == food:
        food[0] = randrange(-15,15)*10
        food[1] = randrange(-15,15)*10
    else:
        snake.pop(0)
    snake.append(head)
    turtle.clear()
    square(food[0],food[1],10,"green")
    for body in snake:
       square(body[0],body[1],10,"black")
    turtle.update()
    turtle.ontimer(snake_move,200)

turtle.setup(500,500)
turtle.tracer(False)
turtle.hideturtle()
turtle.listen()
turtle.onkey(lambda :change_direction(0,10),"Up")
turtle.onkey(lambda :change_direction(0,-10),"Down")
turtle.onkey(lambda :change_direction(10,0),"Right")
turtle.onkey(lambda :change_direction(-10,0),"Left")
snake_move()
turtle.done()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天嗨嗨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值