用python3.8.1写一个贪吃蛇小游戏
时间: 2023-12-07 18:18:06 浏览: 94
好的,以下是一个简单的贪吃蛇小游戏的代码,你可以在Python3.8.1上运行它:
```python
import turtle
import time
import random
delay = 0.1
# 设置窗口
wn = turtle.Screen()
wn.title("贪吃蛇小游戏")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0)
# 蛇的头部
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 = []
# 计分板
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("得分: 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"
# 键盘绑定
wn.listen()
wn.onkeypress(go_up, "Up")
wn.onkeypress(go_down, "Down")
wn.onkeypress(go_right, "Right")
wn.onkeypress(go_left, "Left")
# 循环
while True:
wn.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("得分: {}".format(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
pen.clear()
pen.write("得分: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 移动身体
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].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("得分: {}".format(score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
wn.mainloop()
```
希望能帮助到你!
阅读全文