欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的贪食蛇游戏 python+turtle+freegames

程序员文章站 2022-07-13 08:29:14
...

就一个python文件,直接上代码:

from turtle import *
from random import randrange
from freegames import square, vector

food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, -10)


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


# 判断蛇是否在框内,参数head是一个坐标
def inside(head):
    return -200 < head.x < 190 and -200 < head.y < 190


# 主程序
def move():
    head = snake[-1].copy()
    head.move(aim)

    if not inside(head) or head in snake:
        square(head.x, head.y, 9, 'red')
        update()
        return

    snake.append(head)

    if head == food:
        print('Snake', len(snake))
        food.x = randrange(-15, 15) * 10
        food.y = randrange(-15, 15) * 10

    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, 300)


def main():
    # 设定游戏框大小
    setup(width=420, height=420, startx=210, starty=210)
    hideturtle()
    tracer(False)
    listen()
    onkey(lambda: change(10, 0), 'Right')
    onkey(lambda: change(-10, 0), 'Left')
    onkey(lambda: change(0, -10), 'Down')
    onkey(lambda: change(0, 10), 'Up')
    move()
    done()
while True:
    main()

功能比较简陋,效果如下图:

简单的贪食蛇游戏 python+turtle+freegames

相关标签: python 游戏