Python实现贪吃蛇小游戏(小练习)

一、效果图

  • 通过按键盘上的上下左右键便可让"蛇"吃到"食物"
    在这里插入图片描述

二、完整代码

import turtle
from random import randrange

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


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


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


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


def snake_move():
    head = [snake[-1][0], snake[-1][1]]
    head = [head[0] + aim[0], head[1] + aim[1]]
    if head in snake or not inside(head):
        square(head[0], head[1], 10, 'red')
        turtle.update()
        return
    if head == food:
        print("snake", len(snake))
        food[0] = randrange(-15, 15) * 10
        food[1] = randrange(-15, 15) * 10
    else:
        snake.pop(0)
    snake.append(head)
    turtle.clear()
    square(food[0], food[1], 10, "green")
    for body in snake:
        square(body[0], body[1], 10, "black")
    turtle.update()
    turtle.ontimer(snake_move, 300)


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李宸净

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值