使用Python自带模块编写一个贪吃蛇程序
时间: 2023-12-09 11:13:57 浏览: 28
好的,下面是一个简单的贪吃蛇程序,使用Python自带的turtle模块实现。
```python
import turtle
import time
import random
delay = 0.1
# 设置窗口大小
win = turtle.Screen()
win.title("贪吃蛇")
win.setup(width=600, height=600)
win.bgcolor("black")
win.tracer(0)
# 创建蛇头
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
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 = []
# 分数
score = 0
high_score = 0
# 显示分数
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
# 移动函数
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 == "right":
x = head.xcor()
head.setx(x + 20)
if 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"
# 键盘绑定
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_right, "Right")
win.onkeypress(go_left, "Left")
# 循环
while True:
win.update()
# 碰到边界
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 隐藏蛇身
for segment in segments:
segment.goto(1000, 1000)
# 清空蛇身列表
segments.clear()
# 分数归零
score = 0
# 更新分数
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# 碰到食物
if head.distance(food) < 20:
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# 添加蛇身
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# 增加分数
score += 10
if score > high_score:
high_score = score
# 更新分数
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# 移动蛇身
for i in range(len(segments) - 1, 0, -1):
x = segments[i-1].xcor()
y = segments[i-1].ycor()
segments[i].goto(x, y)
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
move()
# 碰到自己
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# 隐藏蛇身
for segment in segments:
segment.goto(1000, 1000)
# 清空蛇身列表
segments.clear()
# 分数归零
score = 0
# 更新分数
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
win.mainloop()
```
这个程序使用turtle模块绘制贪吃蛇和食物,通过键盘绑定控制蛇的方向,实现了基本的贪吃蛇游戏功能。