猫史档案馆


【Python作品分享】python【作品秀】:贪吃蛇【作品秀】

用户:降魔大圣一魈降魔大圣一魈查看:0 回复:0 评论:0 创建时间:2020-10-27T20:03:07


【作品展示】

center_image

 

【作品介绍】

贪吃蛇

 

【作品源代码】

import turtle as t 
from random import randrange

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

def change_direction(x,y):
    aim[0] = x
    aim[1] = y

def 喵(x, y, size, color):
    t.penup()
    t.goto(x, y)
    t.pendown()
    
    t.begin_fill()
    for i in range(4):
        t.forward(size)
        t.left(90)
    t.end_fill()



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

import copy


def snake_move():
    head = copy.deepcopy(snake[-1])
    head = [head[0]+aim[0],head[1]+aim[1]]
    if head in snake or not  inside(head):
        print("game over")
        喵(head[0],head[1],10,'red')
        return
    if head == food:
        food[0] = randrange(-15,15)*10
        food[1] = randrange(-15,15)*10
    else:
        snake.pop(0)
    snake.append(head)
    t.clear()
    喵(food[0],food[1],10,'green')
    for body in snake: 
        喵(body[0], body[1], 10, 'blake')
    t.update()
    t.ontimer(snake_move,200)

t.setup(500,500)
t.tracer(False)
t.hideturtle()
t.listen()
t.onkey(lambda :change_direction(0, 10), "Up")
t.onkey(lambda: change_direction(0, -10), "Down")
t.onkey(lambda: change_direction(-10, 0), "Left")
t.onkey(lambda: change_direction(10, 0), "Right")
snake_move()
t.done()

 

【提示】

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

https://python.codemao.cn


回复

上一页1 页 / 共 0下一页