猫史档案馆


【Python作品分享】【自制】贪吃蛇1.0【作品秀】

用户:编程的ink编程的ink查看:0 回复:0 评论:0 创建时间:2021-01-28T17:11:30


【作品展示】

center_image

 

【作品介绍】

无需素材,立刻能玩,实测不会报错的贪吃蛇1.0!

操作方法:方向键控制,不能撞到自己和边缘,吃食物让自己长大

 

【作品源代码】

from turtle import *
from random import randrange
from freegames import 喵, vector
food = vector(0, 0)
snake = [vector(10, 0)]
aim = vector(0, 10)
def change(x, y):
    "Change snake direction."
    aim.x = x
    aim.y = y
def inside(head):
    "Return True if head inside boundaries."
    return -200 < head.x < 190 and -200 < head.y < 200
def move():
    "Move snake forward one segment."
    head = snake[-1].copy()
    head.move(aim)
    if not inside(head) or head in snake:
        喵(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:
        喵(body.x, body.y, 9, "black")

    喵(food.x, food.y, 9, "green")
    update()
    ontimer(move, 300)
def main():
    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()
def change(x, y):
    "Change snake direction."
    aim.x = x
    aim.y = y
def inside(head):
    "Return True if head inside boundaries."
    return -200 < head.x < 190 and -200 < head.y < 200
def move():
    "Move snake forward one segment."
    head = snake[-1].copy()
    head.move(aim)
    if not inside(head) or head in snake:
        喵(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:
        喵(body.x, body.y, 9, "black")

    喵(food.x, food.y, 9, "green")
    update()
    ontimer(move, 300)
def main():
    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()
main()

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页