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()
100行内用Python写个贪吃蛇
最新推荐文章于 2024-08-20 13:04:52 发布