用Python写一个贪吃蛇程序

写贪吃蛇程序是一个不错的练习项目,你可以使用 Python 来实现这个游戏。

这是一份简单的贪吃蛇游戏的代码示例:

import turtle
import time

# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇游戏")

# 设置蛇头的初始位置
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"

# 设置食物的初始位置
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)

# 初始化蛇身列表
segments = []

# 设置游戏移动速度
delay = 0.1

# 定义向上移动的函数
def go_up():
    head.direction = "up"

# 定义向下移动的函数
def go_down():
    head.direction = "down"

# 定义向左移动的函数
def go_left():
    head.direction = "left"

# 定义向右移动的函数
def go_right():
    head.direction = "right"

# 定义游戏控制函数
def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)
    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)
    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

# 绑定键盘事件
turtle.listen()
turtle.onkeypress(go_up, "Up")
turtle.onkeypress(go_down, "Down")
turtle.onkeypress(go_left, "Left")
turtle.onkeypress(go_right, "Right")

# 游戏主循环
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值