请用python实现一个贪吃蛇游戏
时间: 2024-05-10 19:21:33 浏览: 83
下面是一份实现贪吃蛇游戏的 Python 代码示例:
```
import turtle
import time
# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪吃蛇游戏")
# 创建画笔
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
# 设置分数
score = 0
# 显示分数
def show_score(color, x, y):
pen.color(color)
pen.goto(x, y)
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 画边框
def draw_border():
pen.penup()
pen.goto(-290, 290)
pen.pendown()
pen.pensize(3)
for side in range(4):
pen.fd(580)
pen.lt(90)
pen.penup()
# 生成食物
food = turtle.Turtle()
food.speed(0)
food.color("red")
food.penup()
food.shape("circle")
food.shapesize(0.5, 0.5)
food.goto(0, 100)
# 生成蛇头
head = turtle.Turtle()
head.speed(0)
head.color("green")
head.penup()
head.shape("square")
head.shapesize(1.5, 1.5)
head.goto(0, 0)
head.direction = "stop"
# 生成身体列表
body = []
# 改变蛇头方向
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)
# 设置按键
def go_up():
head.direction = "up"
def go_down():
head.direction = "down"
def go_left():
head.direction = "left"
def go_right():
head.direction = "right"
# 监听键盘事件
turtle.listen()
turtle.onkeypress(go_up, "Up
阅读全文