请用python写一个完整的可以跑起来的贪食蛇小游戏
时间: 2023-02-23 20:14:00 浏览: 103
python+pygame制作贪食蛇小游戏
这是一个贪食蛇小游戏的完整代码:
```python
import turtle
import time
import random
# 设置窗口大小和标题
turtle.setup(width=600, height=600)
turtle.title("贪食蛇")
# 设置画笔的速度
turtle.speed(10)
turtle.hideturtle()
# 设置分数
score = 0
# 画边框
turtle.penup()
turtle.goto(-290, 290)
turtle.pendown()
for i in range(4):
turtle.fd(580)
turtle.left(90)
# 创建食物
food = turtle.Turtle()
food.color("red")
food.shape("circle")
food.penup()
food.goto(random.randint(-280, 280), random.randint(-280, 280))
# 创建蛇头
head = turtle.Turtle()
head.color("green")
head.shape("square")
head.penup()
head.goto(0, 100)
head.direction = "stop"
# 创建蛇身
segments = []
# 定义方向函数
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")
turtle.onkeypress(go_down, "Down")
turtle.onkeypress(go_left, "Left")
turtle.onkeypress(go_right, "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)
# 游戏主循环
while True:
turtle.update()
# 判断是否吃到食物
if head.distance(food) < 20:
# 移动食物
x = random.randint(-280, 280)
y = random.randint(-280, 280)
food.goto(x, y)
#
阅读全文