介绍

使用 Python 的 PyGame 做了一个弹球游戏,第一次使用Py做游戏,分享一下。

下载地址
下载链接:
http://101.201.112.95/2021/PyGame_Pong.zip 复制到浏览器


执行 index.py 就可以运行游戏了

.
PyGame开发游戏感觉上比H5、Unity等其他语言要反锁一点(可能刚接触不太习惯吧 _

.
分享下 HTML5 做的弹球游戏及完整源码

https://blog.csdn.net/fujian87232/article/details/115037280
.
.

制作

这里简单总结下 PyGame 开发游戏时的一些基础知识点
.

一、创建应用

1、首先,需要初始化下应用及显示窗口大小
pygame.init();  # 初始化pygame
pygame.display.set_caption("Pong") # 设置标题
2、设置游戏窗口大小并创建
size = width, height = 800, 600;  # 设置窗口大小
scene = pygame.display.set_mode(size); # 创建显示窗口

.

二、添加显示元素

1、添加图片,设置图片位置
ball = pygame.image.load(dirname + '/img/ball.jpg');
ballRect = ball.get_rect();
ballRect.centerx = 100; # 设置图片位置
ballRect.centery = 200;
scene.blit(ball, ballRect);  # 将小球图片画到场景中上
2、添加文字显示
font = pygame.font.Font(None, 100); # 创建文字,定义大小
leftScore = font.render("文字显示内容", 1, (255, 255, 255)); # 渲染并设置颜色
leftScoreRect = leftScore.get_rect();
leftScoreRect.centerx = 200; # 设置文字位置
leftScoreRect.centery = 70; # 设置文字位置
scene.blit(leftScore, leftScoreRect);  # 将文字添加到显示窗口
3、绘制图形

这里画了40个小的线段

lineColor = (255, 255, 255); # 线段颜色
for i in range(0, 40):start = (400, i * 15); # 线段开始位置end = (400, i * 15 + 10); # 线段结束位置pygame.draw.line(scene, lineColor, start, end, 4); # 绘制到窗口中

.
.

三、动画

实现动画功能时,定义一个死循环,使用PyGame的时钟让循环按照一定时间间隔执行。

1、定义一个无限循环体
fpsClock = pygame.time.Clock(); # 获得pygame的时钟
while True: # 死循环确保窗口一直显示# 这里实现动画效果fpsClock.tick(30);  # 设置pygame时钟的间隔时间
2、实现图片移动动画
# 死循环确保窗口一直显示
while True:# 小球移动ballRect.centerx += 1;ballRect.centery += 1;scene.blit(ball, ballRect);  # 将小球图片重新画到窗口上pygame.display.update();  # 更新窗口显示fpsClock.tick(30);  # 设置pygame时钟的间隔时间

.

四、添加控制

PyGame的控制都是在动画循环中实现的

1、添加键盘事件
while True: # 死循环确保窗口一直显示for event in pygame.event.get():  # 遍历所有事件if event.type == pygame.KEYDOWN: # 键盘按下事件if event.key == pygame.K_UP: # 当按下的按键是向上箭头时if event.key == pygame.K_DOWN: # 当按下的按键是向下箭头时if event.type == pygame.KEYUP: # 键盘抬起事件if event.key == pygame.K_UP:if event.key == pygame.K_DOWN:fpsClock.tick(30);  # 设置pygame时钟的间隔时间
2、添加窗口关闭按钮,退出程序
while True: # 死循环确保窗口一直显示if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出sys.exit();fpsClock.tick(30);  # 设置pygame时钟的间隔时间

.

完整代码

import pygame;
import sys;
import os;
import math;dirname, runFile = os.path.split(os.path.abspath(sys.argv[0]));pygame.init();  # 初始化pygame
pygame.display.set_caption("Pong") # 设置标题
size = width, height = 800, 600;  # 设置窗口大小# 显示窗口
scene = pygame.display.set_mode(size);
bgColor = (0, 0, 0);  # 设置颜色# 添加小球图片
ball = pygame.image.load(dirname + '/img/ball.jpg');
ballRect = ball.get_rect();# 添加左挡板图片
leftBlock = pygame.image.load(dirname + '/img/block.jpg');
leftBlockRect = leftBlock.get_rect();
leftBlockRect.centerx = 40;
leftBlockRect.centery = 300;# 添加右挡板图片
rightBlock = pygame.image.load(dirname + '/img/block.jpg');
rightBlockRect = rightBlock.get_rect();
rightBlockRect.centerx = 760;
rightBlockRect.centery = 300;#定义画中线函数
def drawLine():lineColor = (255, 255, 255);for i in range(0, 40):start = (400, i * 15);end = (400, i * 15 + 10);pygame.draw.line(scene, lineColor, start, end, 4);# 得分
leftScoreNum = 0;
rightScoreNum = 0;# 左侧分数
def leftScoreShow():font = pygame.font.Font(None, 100); # 创建字体对象leftScore = font.render(str(leftScoreNum), 1, (255, 255, 255)); # 文本与颜色leftScoreRect = leftScore.get_rect();leftScoreRect.centerx = 200;leftScoreRect.centery = 70;scene.blit(leftScore, leftScoreRect); # 将左侧得分画到场景中上# 右侧分数
def rightScoreShow():font = pygame.font.Font(None, 100); # 创建字体对象rightScore = font.render(str(rightScoreNum), 1, (255, 255, 255)); # 文本与颜色rightScoreRect = rightScore.get_rect();rightScoreRect.centerx = 600;rightScoreRect.centery = 70;scene.blit(rightScore, rightScoreRect); # 将右侧得分画到场景中上# 得分
def addScore(type):if type == 1 :global leftScoreNum;leftScoreNum = leftScoreNum + 1;else :global rightScoreNum;rightScoreNum = rightScoreNum + 1;# 重置小球
def resetBall(type):global ballRect;global ballSpeedAngle;ballRect.centerx = 400;ballRect.centery = 300;if type == 1 :ballSpeedAngle = 0;else :ballSpeedAngle = math.pi;# 挡板与球的碰撞
isLeftBlockCrash = False;
isRightBlockCrash = False;
def blockCrash(speedX):global isLeftBlockCrash;global isRightBlockCrash;global ballSpeedAngle;if (ballRect.centerx < leftBlockRect.centerx + leftBlockRect.width / 2 and ballRect.centerx > leftBlockRect.centerx - leftBlockRect.width / 2) and (ballRect.centery < leftBlockRect.centery + leftBlockRect.height / 2 and ballRect.centery > leftBlockRect.centery - leftBlockRect.height / 2) :if isLeftBlockCrash == False :if speedX > 0 :ballSpeedAngle = -(ballSpeedAngle - math.pi);else :#回弹角度增益ballSpeedAngle = (ballRect.centery - leftBlockRect.centery)/50;isLeftBlockCrash = True;else :isLeftBlockCrash = False;if (ballRect.centerx < rightBlockRect.centerx + rightBlockRect.width / 2 and ballRect.centerx > rightBlockRect.centerx - rightBlockRect.width / 2) and (ballRect.centery < rightBlockRect.centery + rightBlockRect.height / 2 and ballRect.centery > rightBlockRect.centery - rightBlockRect.height / 2) :if isRightBlockCrash == False :if speedX > 0 :ballSpeedAngle = -(ballSpeedAngle - math.pi);else :#回弹角度增益ballSpeedAngle = (ballRect.centery - rightBlockRect.centery)/50;isRightBlockCrash = True;else :isRightBlockCrash = False;# 获得pygame的时钟
fpsClock = pygame.time.Clock();#定义小球移动速度
ballSpeed = 15;
#定义小球移动方向
ballSpeedAngle = 1/4 * math.pi;#定义横杆移动速度
leftMoveSpeed = 0;
rightMoveSpeed = 0;# 死循环确保窗口一直显示
while True:# 计算小球移动速度speedX = math.cos(ballSpeedAngle) * ballSpeed;speedY = math.sin(ballSpeedAngle) * ballSpeed;# 小球移动ballRect.centerx += speedX;ballRect.centery += speedY;# 左横杆移动leftBlockRect.centery += leftMoveSpeed;if(leftBlockRect.centery < 50):leftBlockRect.centery = 50;if(leftBlockRect.centery > 550):leftBlockRect.centery = 550;# 右横杆移动rightBlockRect.centery += rightMoveSpeed;if(rightBlockRect.centery < 50):rightBlockRect.centery = 50;if(rightBlockRect.centery > 550):rightBlockRect.centery = 550;# 碰撞上下边界if(ballRect.centery > 600):ballSpeedAngle = -ballSpeedAngle;if(ballRect.centery < 0):ballSpeedAngle = -ballSpeedAngle;if(ballRect.centerx > 800):ballSpeedAngle = -(ballSpeedAngle - math.pi);addScore(1); # 左边得分resetBall(1); # 重置小球并先向右发射if(ballRect.centerx < 0):ballSpeedAngle = -(ballSpeedAngle - math.pi);addScore(0);  # 右边得分resetBall(0); # 重置小球并先向左发射for event in pygame.event.get():  # 遍历所有事件if event.type == pygame.QUIT:  # 如果单击关闭窗口,则退出sys.exit();if event.type == pygame.KEYDOWN:if event.key == pygame.K_UP:rightMoveSpeed = -8;if event.key == pygame.K_DOWN:rightMoveSpeed = 8;if event.key == pygame.K_w:leftMoveSpeed = -8;if event.key == pygame.K_s:leftMoveSpeed = 8;if event.type == pygame.KEYUP:if event.key == pygame.K_UP:rightMoveSpeed = 0;if event.key == pygame.K_DOWN:rightMoveSpeed = 0;if event.key == pygame.K_w:leftMoveSpeed = 0;if event.key == pygame.K_s:leftMoveSpeed = 0;scene.fill(bgColor);  # 填充黑色背景scene.blit(ball, ballRect);  # 将小球图片画到场景中上scene.blit(leftBlock, leftBlockRect);  # 将左侧挡板图片画到场景中上scene.blit(rightBlock, rightBlockRect);  # 将右侧挡板图片画到场景中上drawLine(); # 画中心虚线leftScoreShow(); # 左侧分数显示rightScoreShow(); # 右侧分数显示blockCrash(speedX); # 碰撞检测pygame.display.update();  # 更新全部显示fpsClock.tick(30);  # 设置pygame时钟的间隔时间

PyGame游戏制作: 弹球游戏Pong(附上Python完整代码)相关推荐

  1. Html5游戏制作 弹球游戏Pong (可在线预览对战 ^_^)

    做了一个简单的 Html5 弹球游戏,模仿上古街机的游戏--(^ _ ^) . 今天更新访问地址,找个人一起对个战吧 http://h5demo.yyfuncdn.com/res/gameDemo/P ...

  2. Python——利用pygame模块制作RPG游戏(一)

    利用pygame模块制作RPG游戏(一) 需要用到的第三方库:pygame 一.构造游戏的基本框架 1.首先准备好相应的游戏素材:背景,人物动作图片,音乐,音效等. 图片均用png格式,音乐音效均用o ...

  3. # 使用Scratch 3.0制作弹球游戏(三)——游戏关卡及难度设计

    目录 使用Scratch 3.0制作弹球游戏(三)--游戏关卡及难度设计 1.第一关 1.1第一关游戏角色需求 1.2第一关游戏玩法设计 1.3角色设计--球 1.4角色设计--接球平台 1.5背景设 ...

  4. 【机器视觉案例】(5) AI视觉,手势调节物体尺寸,附python完整代码

    各位同学好,今天和大家分享一下如何使用opencv+mediapipe完成远程手势调节图片尺寸的案例.先放张图看效果.当拇指和食指竖起时,根据食指间的连线的长度自由缩放图片尺寸.图片的中点始终位于指尖 ...

  5. 【机器视觉案例】(5) AI视觉,远程手势控制虚拟计算器,附python完整代码

    各位同学好,今天和大家分享一下如何使用MediaPipe+Opencv完成虚拟计算器,先放张图看效果.FPS值为29,食指和中指距离小于规定阈值则认为点击按键,为避免重复数字出现,规定每20帧可点击一 ...

  6. 【MediaPipe】(4) AI视觉,远程手势调节电脑音量,附python完整代码

    各位同学好,今天和大家分享一下如何使用MediaPipe完成手势调节电脑音量,先放张图看效果. 注意!! 本节需要用到手部关键点的实时跟踪,我已经在之前的文章中详细写过了,本节会直接使用,有疑问的同学 ...

  7. 【深度学习】(2) 数据加载,前向传播2,附python完整代码

    生成数据集: tf.data.Dataset.from_tensor_slices(tensor变量) 创建一个数据集,其元素是给定张量的切片 生成迭代器: next(iter()) next() 返 ...

  8. 【机器学习入门】(13) 实战:心脏病预测,补充: ROC曲线、精确率--召回率曲线,附python完整代码和数据集

    各位同学好,经过前几章python机器学习的探索,想必大家对各种预测方法也有了一定的认识.今天我们来进行一次实战,心脏病病例预测,本文对一些基础方法就不进行详细解释,有疑问的同学可以看我前几篇机器学习 ...

  9. 【机器学习入门】(8) 线性回归算法:正则化、岭回归、实例应用(房价预测)附python完整代码和数据集

    各位同学好,今天我和大家分享一下python机器学习中线性回归算法的实例应用,并介绍正则化.岭回归方法.在上一篇文章中我介绍了线性回归算法的原理及推导过程:[机器学习](7) 线性回归算法:原理.公式 ...

最新文章

  1. linux 挂载网络文件系统,[arm-linux-FL2440挂载网络文件系统共享文件]
  2. (46)分析 INT 0x2E 和 sysenter
  3. mix2s android p内测,历时一个月,MIX2S成小米首款Android P公测机型
  4. Java 的这些坑,你踩到了吗?
  5. 设计模式:备忘录模式(Memento)
  6. 用python念数字_Python-数据类型之数字
  7. JavaScript 里变量名前面加了大括号代表什么含义
  8. C++子类对象隐藏了父类的同名成员函数(隐藏篇)
  9. MySQL的Limit详解
  10. matlab mingw 32,Matlab 2017b MinGW-w64 5.3安裝
  11. 人工与计算机解决问题的异同,1.1计算机解决问题的过程ppt课件 .ppt
  12. svn 中的url路径修改和 清除 svn用户名和密码
  13. 一周极客热文:看马云李彦宏马明哲等大佬手绘未来图
  14. appcan 文件下载到根目录(pdf)
  15. Android启动活动用什么方法,Android - 使用intent uri从命令行启动活动
  16. spring boot结合FastDFSClient做下载文件注意事项
  17. poscms会员等级星星
  18. 如何使用CubeMX创建STM32F105的程序
  19. (转载)JAVA小知识
  20. UINO优锘科技:数字孪生6大概念超强解析

热门文章

  1. windows7系统损坏修复_UEFI?安装纯净的 Windows 7/10 系统
  2. dac7714和dac3152两种DAC芯片FPGA控制流程记录
  3. Jetson Nano目标检测手把手实战教程(pytorch训练、tensorrt推理,含完整代码和数据)
  4. 数字孪生智慧建筑解决方案
  5. windows使用tomcat并设置环境变量
  6. 微信扫码登录(new WxLogin)-二维码样式修改
  7. GeoServer入门学习:02-安装部署
  8. Delphi进行CAD二次开发教学(1)——基础学习:运行、新建、打开图形文件
  9. sai动漫人物眼睛素描教程
  10. 创未来,享非凡,openGauss Developer Day 2022圆满举行