python实现贪吃蛇小游戏
时间: 2023-08-28 16:06:25 浏览: 107
好的,以下是一个简单的 Python 贪吃蛇小游戏的实现示例。
```
import turtle
import time
import random
delay = 0.1
# 初始化窗口
win = turtle.Screen()
win.title("贪吃蛇小游戏")
win.bgcolor("green")
win.setup(width=600, height=600)
# 初始化蛇头
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 = []
# 定义蛇头移动函数
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()
# 判断蛇头是否吃到食物
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)
# 移动蛇尾
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(
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)