使用Python写贪吃蛇游戏

ops/2024/12/23 4:54:41/

贪吃蛇游戏是一款经典的小游戏,玩家通过控制蛇的移动来吃食物,蛇的身体会随着吃到的食物越来越多而变长。本文将介绍如何使用Python来创建一个简单的贪吃蛇游戏

 

 

代码解析

1. 设置窗口

首先,我们需要设置游戏窗口。使用 turtle.Screen() 创建一个窗口,并设置窗口的标题、背景颜色和大小。通过 window.tracer(0) 关闭自动更新屏幕,以提高性能。

python">import turtle
import time
import randomwindow = turtle.Screen()window.title("XXX")window.bgcolor("black")window.setup(width=800, height=600)window.tracer(0)

 

2. 创建蛇头

接下来,我们创建蛇头。使用 turtle.Turtle() 创建一个 Turtle 对象,设置其速度、形状、颜色,并将其移动到屏幕中央。

python">head = turtle.Turtle()
head.speed(0)head.shape("square")head.color("white")head.direction = "stop"

 

3. 创建蛇身体和食物

我们使用一个列表 segments 来存储蛇的身体部分。食物也是一个 Turtle 对象,随机生成在屏幕上。

python">segments = []food = turtle.Turtle()
food.speed(0)food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)

 

4. 移动函数

定义一个 move 函数来控制蛇的移动。根据蛇头的方向,更新其坐标。

python">def move():if head.direction == "up":elif head.direction == "down":elif head.direction == "left":elif head.direction == "right":

 

5. 键盘绑定

通过键盘绑定函数来控制蛇的移动方向。使用 window.listen() 和 window.onkeypress() 来监听键盘事件。

python">def go_up():if head.direction != "down":head.direction = "up"
def go_down():if head.direction != "up":head.direction = "down"
def go_left():if head.direction != "right":head.direction = "left"
def go_right():if head.direction != "left":head.direction = "right"window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")

 

6. 主循环

在主循环中,我们更新屏幕、检查边界碰撞、食物碰撞,并移动蛇的身体。通过 time.sleep(0.1 / speed) 来控制游戏速度。

python">while True:window.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()
python">if head.distance(food) < 20:food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)new_segment = turtle.Turtle()new_segment.speed(0)new_segment.shape("square")new_segment.color("grey")new_segment.penup()segments.append(new_segment)
python">for index in range(len(segments) - 1, 0, -1):x = segments[index - 1].xcor()y = segments[index - 1].ycor()segments[index].goto(x, y)
python">if len(segments) > 0:x = head.xcor()y = head.ycor()segments[0].goto(x, y)move()
python">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()time.sleep(0.1 / speed)

 

 

完整代码

python">import turtle
import time
import randomwindow = turtle.Screen()
window.title("贪吃蛇小游戏")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "stop"segments = []food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)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 == "left":x = head.xcor()head.setx(x - 20)elif head.direction == "right":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_left():if head.direction != "right":head.direction = "left"
def go_right():if head.direction != "left":head.direction = "right"window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")speed = 0.7
while True:window.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:food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)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(1)head.goto(0, 0)head.direction = "stop"for segment in segments:segment.goto(1000, 1000)segments.clear()time.sleep(0.1 / speed)

 

通过以上步骤,我们成功创建了一个简单的贪吃蛇游戏。后续可以根据需要进一步优化和扩展游戏功能,例如增加得分系统、难度级别等!

 


http://www.ppmy.cn/ops/103286.html

相关文章

【知识】缓存类型和策略

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 目录 缓存读取策略 缓存写入策略 直写缓存写入策略 回写高速缓存写入策略 回写缓存写入策略 ​​​​​​缓存替换策略 先进先出 &#xff08;F…

【生活英语】2、喜欢与讨厌

【生活英语】2、喜欢与讨厌 一、喜欢二、不喜欢三、英语对话 一、喜欢 1、I like it very much. I like it a lot. I love it. 2、I’m very fond of him. I’m fond of music. Are you into surfing? be into doing / sth. 对…感兴趣&#xff1b;极其喜欢 3、That’s my fa…

Nginx负载均衡中的并发控制:策略、配置与最佳实践

在高流量的Web应用环境中&#xff0c;合理地控制请求的并发量对于维护应用的稳定性和响应性至关重要。Nginx&#xff0c;作为一款高性能的Web服务器和反向代理&#xff0c;提供了多种并发控制机制来帮助开发者管理请求流量。本文将详细介绍如何在Nginx负载均衡中处理请求的并发…

erlang学习:用OTP构建系统3,应用程序服务器

按照书上搭建两个服务器&#xff0c;一个是质数服务器&#xff0c;一个是面积服务器 今天先按照书上的将这两个服务器的代码编写好&#xff0c;为后面监控树的学习做准备 质数服务器代码 -module(prime_server). -behaviour(gen_server).-export([new_prime/1, start_link/0]…

【#第三期实战营闯关作业##LMDeploy 量化部署进阶实践 】

今天学习了《LMDeploy 量化部署进阶实践》一课&#xff0c;&#xff0c;收获很大。以下是记录复现过程及截图&#xff1a; 创建一个名为lmdeploy的conda环境 创建成功后激活环境并安装0.5.3版本的lmdeploy及相关包。 相关包install成功 创建好的conda环境并启动InternLM2_5-7…

【需要学会的Java知识 1】Java的Map增强

使用这些你需要有以下依赖: <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><dependency><groupId>com.google.guava</grou…

android 离线的方式使用下载到本地的gradle

1、android studio在下载gradle的时候&#xff0c;特别慢&#xff0c;有的时候会下载不完的情况&#xff0c;这样我们就要离线使用了。 2、下载Gradle Gradle | Releases 或者 Releases gradle/gradle GitHub Gradle | Releases 这里我们下载8.10 complete版本&#xff0c…

milvus多个Querynode,资源消耗都打在一个节点上

milvus 查询时的原理 当读取数据时&#xff0c;MsgStream对象在以下场景中创建&#xff1a; 在 Milvus 中&#xff0c;数据必须先加载后才能读取。当代理收到数据加载请求时&#xff0c;会将请求发送给查询协调器&#xff0c;查询协调器决定如何将分片分配到不同的查询节点。…