用Python写一个贪吃蛇程序
时间: 2023-03-14 10:24:00 浏览: 25
写贪吃蛇程序是一个不错的练习项目,你可以使用 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")
# 游戏主循环
阅读全文