python-小游戏-贪吃蛇

python-小游戏-贪吃蛇

需要安装turtle

代码—game-snake.py

from turtle import *
from random import randint

gz = 22
bc = gz * 8

screen = Screen()
screen.bgcolor("darkblue")

food = Turtle()
food.color("red")
food.shape("square")
food.up()
food.speed(0)
food.goto(randint(-bc + gz, bc - gz) // gz * gz, randint(-bc + gz, bc - gz) // gz * gz)

liner = Turtle()
liner.speed(0)
liner.up()
liner.goto(-bc, bc)
liner.color("white")
liner.pensize(5)
liner.down()
for i in range(4):
    liner.fd(bc * 2)
    liner.rt(90)
liner.ht()

score = 0
judge = Turtle()
judge.speed(0)
judge.up()
judge.goto(0, bc + 20)
judge.color("white")
judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))
judge.ht()

head = Turtle()
head.speed(0)
head.up()
head.color("cyan")
head.shape("square")

snake = []
snake.append(head)
for i in range(2):
    body = head.clone()
    body.color("white")
    body.goto(head.xcor() + (i + 1) * gz, head.ycor())
    snake.append(body)

d = [-1, 0]


def move():
    last = snake.pop()
    first = snake[0]
    first.color("white")
    last.goto(first.xcor() + d[0] * gz, first.ycor() + d[1] * gz)
    last.color("cyan")
    snake.insert(0, last)

    if snake[0].xcor() == food.xcor() and snake[0].ycor() == food.ycor():
        food.ht()
        food.goto(randint(-bc + gz, bc - gz) // gz * gz, randint(-bc + gz, bc - gz) // gz * gz)
        food.st()
        body = snake[-1].clone()
        snake.append(body)
        global score
        score += 1
        judge.clear()
        judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))

    if (-bc < snake[0].xcor() < bc) and (-bc < snake[0].ycor() < bc):
        screen.ontimer(move, 500)  # 只有在边界内时才设置定时器


def up():
    global d
    if d[1] != -1:
        d = [0, 1]


def down():
    global d
    if d[1] != 1:
        d = [0, -1]


def left():
    global d
    if d[0] != 1:
        d = [-1, 0]


def right():
    global d
    if d[0] != -1:
        d = [1, 0]


def restart():
    global score, d, snake
    # 清除之前的得分和蛇
    judge.clear()
    for segment in snake:
        segment.goto(1000, 1000)  # 将蛇移到画面外,以便清除
        segment.clear()
    snake.clear()
    # 重新初始化游戏
    score = 0
    d = [-1, 0]
    judge.write("得分:{}".format(score), align="center", font=("Kai", 20, "bold"))
    head.goto(0, 0)
    snake.append(head)
    for i in range(2):
        body = head.clone()
        body.color("white")
        body.goto(head.xcor() + (i + 1) * gz, head.ycor())
        snake.append(body)
    move()


screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(restart, "space")  # 将 restart 函数绑定到空格键

screen.listen()

move()

done()  # 添加此行来保持窗口打开状态

运行代码 game-snake.py

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值