100行内用Python写个贪吃蛇

import turtle
from random import randrange

snake = [[0, 0]]
aim = [0, 10]
food = [-10, 0]

#设置方向
def change_direction(x, y):
    aim[0] = x
    aim[1] = y

# 坐标,长度,颜色名称
def sqaure(x, y, size, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    turtle.begin_fill()
    turtle.color(color)

    for i in range(4):
        turtle.forward(size)
        turtle.left(90)

    turtle.end_fill()


import copy

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

    # 如果蛇头吃到了食物,我们就不删除蛇的尾巴最后一个方块
    if head == food:
        print("snake的长度", len(snake))
        food[0] = randrange(-15, 15) * 10
        food[1] = randrange(-15, 15) * 10
    else:
        snake.pop(0) #蛇的尾部,去除一个方块
    snake.append(head) #蛇的头部添加这个新的方块
    turtle.clear() #清除方块
    sqaure(food[0], food[1], 10, "green")

    # 重新画一遍蛇的整个身子
    for body in snake:
        sqaure(body[0], body[1], 10, "black")

    turtle.update() #更新动画
    turtle.ontimer(snake_move, 300)

turtle.hideturtle()
turtle.tracer(False)

turtle.setup(500,500)

def inside(head):
    return -250<head[0]<250 and -250 <head[1] <250

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), "Left") #左
turtle.onkey(lambda: change_direction(10, 0), "Right") #右

snake_move()
turtle.done()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值