用python写一个贪吃蛇小游戏
时间: 2023-12-07 18:51:29 浏览: 71
好的,下面是一个简单的贪吃蛇小游戏,使用 Python 语言编写。
```python
import turtle
import random
# 设置窗口大小和背景颜色
window = turtle.Screen()
window.title("贪吃蛇小游戏")
window.bgcolor("lightgreen")
window.setup(width=600, height=600)
# 创建蛇的头部和身体
head = turtle.Turtle()
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# 创建食物
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-280, 280), random.randint(-280, 280))
# 创建边界
border = turtle.Turtle()
border.hideturtle()
border.penup()
border.goto(-290, -290)
border.pendown()
border.pensize(3)
for side in range(4):
border.fd(580)
border.lt(90)
# 定义移动函数
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
elif head.direction == "down":
y = head.ycor()
head.sety(y - 20)
elif head.direction == "right":
x = head.xcor()
head.setx(x + 20)
elif head.direction == "left":
x = head.xcor()
head.setx(x - 20)
# 定义移动方向函数
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_right():
if head.direction != "left":
head.direction = "right"
def go_left():
if head.direction != "right":
head.direction = "left"
# 绑定键盘事件
window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_right, "Right")
window.onkeypress(go_left, "Left")
# 循环游戏
while True:
window.update()
# 检测蛇头和食物之间的距离
if head.distance(food) < 20:
food.goto(random.randint(-280, 280), random.randint(-280, 280))
# 创建蛇的身体
body = turtle.Turtle()
body.shape("square")
body.color("grey")
body.penup()
body.goto(0, 0)
# 移动蛇的身体
for index in range(len(heads)-1, 0, -1):
x = heads[index-1].xcor()
y = heads[index-1].ycor()
heads[index].goto(x, y)
# 移动蛇的头部
move()
# 检测蛇头和边界之间的碰撞
if head.xcor() > 280 or head.xcor() < -280 or head.ycor() > 280 or head.ycor() < -280:
turtle.write("游戏结束", align="center", font=("Courier", 24, "bold"))
break
# 检测蛇头和身体之间的碰撞
for body in heads[1:]:
if head.distance(body) < 20:
turtle.write("游戏结束", align="center", font=("Courier", 24, "bold"))
break
# 延迟
turtle.delay(0.1)
turtle.done()
```
运行以上代码,可以看到一个基本的贪吃蛇小游戏窗口,通过上下左右键控制蛇的移动,蛇头碰到边界或身体则游戏结束。
阅读全文