Python----贪吃蛇游戏

# -*- coding: UTF-8 -*-
#引入turtle库,制作snake,food的动画
from turtle import *
#引入random库,使food随机出现
from random import randrange
#引入freegames库,这个库中封装了许多元素;我们可以使用正方形元素表示food,snake,用vector这个二维向量表示snake的移动
from freegames import square, vector

#初始化food,snake
food = vector(0, 0)
snake = [vector(10, 0)]
#vector(0,10)表示第一个food的位置在以snake的头为原点,横坐标为0,纵坐标为-10处
aim = vector(0, -10)

#改变方向
def change(x, y):
    aim.x = x
    aim.y = y

#判断snake有没有碰到墙壁
def inside(head):
    return -200 < head.x < 190 and -200 < head.y < 190


def move():
    head = snake[-1].copy()
    head.move(aim)

    #考虑游戏结束的两种情况,head碰到墙壁/头碰到身体
    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')
        update()
        return

    snake.append(head)

    #snake吃到food,下一个food会随机出现在画布的另一个地方
    if head == food:
        print('Snake:', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10
    # snake没有吃到food,snake列表pop(0)
    else:
        snake.pop(0)

    clear()

    for body in snake:
        square(body.x, body.y, 9, 'black')

    square(food.x, food.y, 9, 'green')
    update()
    ontimer(move, 100)

#初始画布尺寸
setup(420, 420, 370, 0)
#隐藏鼠标
hideturtle()
tracer(False)
#监听
listen()
#绑定键盘方向
onkey(lambda: change(10, 0), 'Right')
onkey(lambda: change(-10, 0), 'Left')
onkey(lambda: change(0, 10), 'Up')
onkey(lambda: change(0, -10), 'Down')
move()
done()

猜你喜欢

转载自blog.csdn.net/laughitoff1014/article/details/79964933
今日推荐