猫史档案馆


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

用户:周子乔周子乔查看:0 回复:1 评论:0 创建时间:2021-03-14T20:12:46


【作品展示】

center_image

 

【作品介绍】

贪吃蛇(上下左右键)

 

【作品源代码】

#####################引用数据库与函数#####################
import turtle as t
import random as r
import time
#########################定义变量#########################
# **********贪吃蛇列表**********
snake = [[0, 0], [0, 10], [0, 20]]

# 苹果
apple_x = r.randrange(-20, 18)*10
apple_y = r.randrange(-19, 19)*10
# 步长
aim_x = 0
aim_y = 10
#########################定义函数#########################

def change(x, y):
    global aim_x, aim_y
    aim_x = x
    aim_y = y

# 绘制正方形

def 喵(x, y, size, color):
    # 抬笔
    t.up()
    # 去到固定位置
    t.goto(x, y)
    # 落笔
    t.down()
    # 设置画笔颜色
    t.pencolor(color)
    # 设置填充颜色
    t.fillcolor(color)
    # 开始填充
    t.begin_fill()
    # 使用for循环绘制填充图形
    for i in range(4):
        # 画线段
        t.forward(size)
        # 旋转90度
        t.left(90)
    # 结束填充
    t.end_fill()

def inside_snake():
    for n in range(len(snake)-1):
        if snake[-1][0] == snake[n][0] and snake[-1][1] == snake[n][1]:
            return True

    return False

def inside_map():
    if -200 <= snake[-1][0] <= 180 and -190 <= snake[-1][1] <= 190:
        return True
    else:
        return False

def gameLoop():
    global apple_x, apple_y, aim_x, aim_y, snake
    # **********贪吃蛇增加蛇头形成前进效果**********
    snake.append([snake[-1][0] + aim_x, snake[-1][1] + aim_y])

    # **********判断是否吃掉了食物**********
    if snake[-1][0] != apple_x or snake[-1][1] != apple_y:
        snake.pop(0)
    else:
        apple_x = r.randrange(-20, 18)*10
        apple_y = r.randrange(-19, 19)*10

    if (not inside_map()) or inside_snake():
        喵(snake[-1][0], snake[-1][1], 10, "red")
        t.update()
        time.sleep(2)
        snake = [[0, 0], [10, 0], [20, 0], [30, 0], [40, 0], [50, 0]]
        apple_x = randrange(-20, 18)*10
        apple_y = randrange(-19, 19)*10
        aim_x = 0
        aim_y = 10

    # 清除画板
    t.clear()
    # 绘制边框
    喵(-210, -200, 410, "black")
    喵(-200, -190, 390, "white")
    # 画食物苹果
    喵(apple_x, apple_y, 10, "red")
    # 绘制贪吃蛇
    for n in range(len(snake)):
        喵(snake[n][0], snake[n][1], 10, "black")
    t.update()
    t.ontimer(gameLoop, 200)

##########################主程序##########################
t.setup(420, 420, 0, 0)
t.hideturtle()
t.tracer(False)
# **********监听**********
t.listen()
# **********上下左右**********
t.onkey(lambda: change(0, 10), 'Up')
t.onkey(lambda: change(0, -10), 'Down')
t.onkey(lambda: change(-10, 0), 'Left')
t.onkey(lambda: change(10, 0), 'Right')

gameLoop()
t.done()

 

【提示】

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

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
听风说梦_LXYZ听风说梦_LXYZ

你可以来我们工作室吗

点赞0


评论