Pygame python 中的乒乓球游戏
来源:dev.to
2024-12-08 20:22:04
0浏览
收藏
“纵有疾风来,人生不言弃”,这句话送给正在学习文章的朋友们,也希望在阅读本文《Pygame python 中的乒乓球游戏》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
输入
import pygame import sys
pygame 是我们用来制作游戏的模块。它为我们提供了图形、声音等工具。
sys 是 python 中的一个模块,可以帮助我们与 python 解释器交互。
初始化
pygame.init()
初始化所有 pygame 模块并使其可供使用。
常数
#dimensions width, height=800,600 #frame rate fps=60 #the paddles at the side of ping pong paddle_width, paddle_height=15,90 #the balls radius ball_radius=15 #the color of the ball and paddle white=(255, 255, 255)
- 宽度和高度:游戏窗口的尺寸。 800px 为宽度,600px 为高度
- fps:每秒帧数,控制游戏的速度和流畅度。
- paddle_width、paddle_height:桨叶的尺寸。
- ball_radius:球的半径。
- white:白色的 rgb 值,用于球拍、球和文本。
制作屏幕
screen=pygame.display.set_mode((width,height))
pygame.display.set_caption("ping pong")
您将有一个名为ping pong 的窗口,并指定了宽度和高度

桨和球设置
left_paddle=pygame.rect(50, height//2 - paddle_height //2, paddle_width, paddle_height) right_paddle=pygame.rect(width - 50 - paddle_width, height //2- paddle_height //2, paddle_width, paddle_height) ball=pygame.rect(width //2 - ball_radius, height //2 - ball_radius, ball_raduis *2, ball_radius *2)

在 pygame 中,屏幕的左上角代表坐标 (0,0)。
- pygame.rect:用于在 pygame 中创建矩形(此处用于桨和球)。
pygame.rect(x, y, width, height)
- left_paddle:位于屏幕左侧附近,垂直居中。
pygame.rect(50, height//2 - paddle_height //2, paddle_width, paddle_height)
首先,我们将左桨定位在距左侧 50px 处。
然后我们执行 height//2 - paddle_height //2 因为如果你只执行 height//2 它看起来就像图片中的样子。它从屏幕上下来。为了使其居中,我们这样做 - paddle_height //2

这就是我们为右桨使其居中所做的事情。
- right_paddle:位于屏幕右侧附近,垂直居中。
right_paddle=pygame.rect(width - 50 - paddle_width, height //2- paddle_height //2, paddle_width, paddle_height)
- 球:最初位于屏幕中央。
ball=pygame.rect(width //2 - ball_radius, height //2 - ball_radius, ball_raduis *2, ball_radius *2)
为了使球居中,我们减去半径。
速度
ball_speed_x=7 ball_speed_y=7 paddle_speed=10
ball_speed_x 和 ball_speed_y 控制球的水平和垂直速度。
paddle_speed:控制桨的移动速度。
分数变量
left_score=0 right_score=0 font=pygame.font.sysfont(none,55)
- left_score 和 right_score:跟踪玩家的分数。
- 字体:用于在屏幕上渲染乐谱文本。 none 使用默认字体,55为字体大小。
绘制所有内容的函数
def draw(): screen.fill((0,0,0)) #fill the screen with black pygame.draw.rect(screen, white, left_paddle) pygame.draw.rect(screen, white, right_paddle) pygame.draw.ellipse(screen, white, ball)
- fill((0, 0, 0)):用黑色填充屏幕(rgb:0, 0, 0)。
- pygame.draw.rect:绘制矩形桨。
- pygame.draw.ellipse:将球绘制为圆形(以矩形球为边界)。
画出中心线
pygame.draw.aaline(screen, white, (width //2, 0), (width //2, height))
- 画一条垂直中心线来划分比赛场地。
抽签分数
left_text=font.render(str(left_score),true, white) screen.blit(left_text, (width // 4 - left_text.get_width() // 2, 20)) right_text=font.render(str(right_score), true, white) screen.blit(right_text, (width * 3 // 4 - right_text.get_width() //2, 20))
渲染双方玩家的分数并将其放置在屏幕上。
更新屏幕
pygame.display.flip()
使用最新更改更新显示。
#main game loop while true:
让游戏无限期地运行。
for event in pygame.event.get():
if event.type == pygame.quitt:
pygame.quit()
sys.exit()
这将遍历 pygame 中可能发生的所有事件,如果其中一个事件正在关闭窗口,则退出 pygame 并关闭窗口。
桨控制
#paddle controls keys pygame.key.get_pressed() if keys [pygame.k_w] and left_paddle.top > 0: left_paddle.y-=paddle_speed if keys [pygame.k_s] and left_paddle.bottom < height: left_paddle.y += paddle_speed if keys [pygame.k_up] and right_paddle.top > 0: right_paddle.y -= paddle_speed if keys [pygame.k_down] and right_paddle.bottom < height: right_paddle.y += paddle_speed 66
检测按键:
-
w 和 s:上下移动左桨。
- pygame.k_w 是 w 键
- pygame.k_s 是 s 键
-
向上和向下:上下移动右桨。
- pygame.k_up 是向上键
- pygame.k_down 是向下键
- 包括防止桨移出屏幕的检查。
- left_paddle.top > 0检查桨顶部坐标是否大于 0。检查当您单击 w 时它是否击中屏幕顶部。
- left_paddle.bottom < height 检查桨底部坐标是否大于屏幕高度。检查当您单击 k 时它是否触及屏幕底部。
- right_paddle.top > 0检查桨顶部坐标是否大于 0。检查当您单击向上键时它是否击中屏幕顶部。
- right_paddle.bottom < height 检查桨底部坐标是否大于屏幕高度。检查当您单击向下键时它是否击中屏幕底部。
球运动
ball.x += ball_speed_x ball.y + ball_speed_y
通过将球的速度添加到当前位置来移动球
球与顶壁和底壁碰撞
if ball.top <= 0 or ball.bottom >= height: ball_speed_y=-ball_speed_y
如果球击中屏幕顶部或底部,则反转球的垂直方向
球与桨的碰撞
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle): ball_speed_x = -ball_speed_x
如果球与球拍碰撞,则反转球的水平方向。
评分
995546471438- 如果球出界,则更新得分。
- 将球重置到中心并反转其方向。
定时
pygame.time.clock().tick (fps)
限制游戏运行速度最高为60帧/秒,确保游戏流畅。
完整代码
import pygame
import sys
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
PADDLE_WIDTH, PADDLE_HEIGHT = 15, 90
BALL_RADIUS = 15
WHITE = (255, 255, 255)
# Setup screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
# Paddles and ball setup
left_paddle = pygame.Rect(50, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
right_paddle = pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT)
ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2)
# Speeds
ball_speed_x = 7
ball_speed_y = 7
paddle_speed = 10
# Score variables
left_score = 0
right_score = 0
font = pygame.font.SysFont(None, 55)
# Function to draw everything
def draw():
screen.fill((0, 0, 0)) # Fill screen with black
pygame.draw.rect(screen, WHITE, left_paddle)
pygame.draw.rect(screen, WHITE, right_paddle)
pygame.draw.ellipse(screen, WHITE, ball)
# Draw the center line
pygame.draw.aaline(screen, WHITE, (WIDTH // 2, 0), (WIDTH // 2, HEIGHT))
# Draw scores
left_text = font.render(str(left_score), True, WHITE)
screen.blit(left_text, (WIDTH // 4 - left_text.get_width() // 2, 20))
right_text = font.render(str(right_score), True, WHITE)
screen.blit(right_text, (WIDTH * 3 // 4 - right_text.get_width() // 2, 20))
pygame.display.flip()
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Paddle controls
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and left_paddle.top > 0:
left_paddle.y -= paddle_speed
if keys[pygame.K_s] and left_paddle.bottom < HEIGHT:
left_paddle.y += paddle_speed
if keys[pygame.K_UP] and right_paddle.top > 0:
right_paddle.y -= paddle_speed
if keys[pygame.K_DOWN] and right_paddle.bottom < HEIGHT:
right_paddle.y += paddle_speed
# Ball movement
ball.x += ball_speed_x
ball.y += ball_speed_y
# Ball collision with top and bottom walls
if ball.top <= 0 or ball.bottom >= HEIGHT:
ball_speed_y = -ball_speed_y
# Ball collision with paddles
if ball.colliderect(left_paddle) or ball.colliderect(right_paddle):
ball_speed_x = -ball_speed_x
# Scoring
if ball.left <= 0:
right_score += 1
ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2)
ball_speed_x = -ball_speed_x
if ball.right >= WIDTH:
left_score += 1
ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2)
ball_speed_x = -ball_speed_x
draw()
pygame.time.Clock().tick(FPS)

以上就是《Pygame python 中的乒乓球游戏》的详细内容,更多关于的资料请关注golang学习网公众号!
版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
如何用 CSS 混合模式实现盖章透明效果?
- 上一篇
- 如何用 CSS 混合模式实现盖章透明效果?
- 下一篇
- 高并发场景下如何高效处理单操作的并行处理?
查看更多
最新文章
-
- 文章 · python教程 | 18小时前 | python · 进程管理 · Python subprocess Popen 进程树 TimeoutExpired 超时清理
- Python subprocess 超时后清理子进程树
- 108浏览 收藏
-
- 文章 · python教程 | 1天前 | 日志 · logging · Python教程 · Python contextvars request_id LogRecord logging.Filter
- Python logging.Filter 注入请求上下文的做法
- 410浏览 收藏
-
- 文章 · python教程 | 4天前 | Python教程 · Python 鸭子类型 typing.Protocol 结构子类型
- Python typing.Protocol 约束鸭子类型接口
- 246浏览 收藏
-
- 文章 · python教程 | 4天前 | Python教程 · Python 相对路径 is_file pathlib Path.resolve
- Python pathlib 相对路径规范化与文件判断
- 144浏览 收藏
-
- 文章 · python教程 | 4天前 | python · 异步编程 · asyncio · Python CancelledError asyncio.timeout TimeoutError
- Python asyncio.timeout 嵌套取消与异常传播
- 373浏览 收藏
-
- 文章 · python教程 | 5天前 |
- Python heapq 最大堆 API 怎么避免手动取负数
- 397浏览 收藏
-
- 文章 · python教程 | 5天前 | python · Python 不可变对象 namedtuple dataclass copy.replace
- Python copy.replace 怎么更新不可变对象字段
- 245浏览 收藏
-
- 文章 · python教程 | 5天前 | python ·
- Python NamedTemporaryFile 的 delete_on_close 怎么设置
- 311浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 309次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 367次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 361次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 329次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 153次使用
查看更多
相关文章
-
- Python sqlite3 Connection serialize 怎么导出数据库快照:备份窗口、内存占用与恢复校验
- 2026-08-26 501浏览
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览
-
- TensorFlow模型部署为API的TF Serving方法
- 2026-05-26 501浏览
-
- Python字符串编码转换:encode与decode详解
- 2026-05-16 501浏览
-
- TensorFlow裁剪无用算子方法详解
- 2026-05-15 501浏览

