这次用Python实现的是一个接球打砖块的小游戏,最核心的就是:碰撞检测的数学模型
程序运行截图

其实,编程问题到最后就是数学问题,这个游戏涉及到2D圆形与矩形的碰撞检测问题:

碰撞检测原理:通过找出矩形上离圆心最近的点,然后通过判断该点与圆心的距离是否小于圆的半径,若小于则为碰撞。
那如何找出矩形上离圆心最近的点呢?下面我们从 x 轴、y 轴两个方向分别进行寻找。为了方便描述,我们先约定以下变量:

(1)矩形上离圆心最近的点为变量:closestpoint = [x, y]
(2)矩形 rect = [x, y, l, w] 左上角与长宽 length,wide
(3)圆形 circle = [x, y, r] 圆心与半径

首先是 x 轴:
如果圆心在矩形的左侧(if circle_x < rect_x),那么 closestpoint_x = rect_x。
如果圆心在矩形的右侧(elif circle_x > rect_x + rect_l),那么 closestpoint_x = rect_x + rect_l。
如果圆心在矩形的正上下方(else),那么 closestpoint_x = circle_x。

同理,对于 y 轴:
如果圆心在矩形的上方(if circle_y < rect_y),那么 closestpoint_y = rect_y。
如果圆心在矩形的下方(elif circle_y > rect_y + rect_w)),那么 closestpoint_y = rect_y + rect_w。
圆形圆心在矩形的正左右两侧(else),那么 closestpoint_y = circle_y。

因此,通过上述方法即可找出矩形上离圆心最近的点了,然后通过“两点之间的距离公式”得出“最近点”与“圆心”的距离,最后将其与圆的半径相比,即可判断是否发生碰撞。
distance=math.sqrt(math.pow(closestpoint_x-circle_x,2)+math.pow(closestpoint_y-circle_y,2))

if distance < circle.r :
return True – 发生碰撞
else :
return False – 未发生碰撞

完整程序


# 导入模块
import pygame
from pygame.locals import *
import sys, random, time, mathclass GameWindow(object):'''创建游戏窗口类'''def __init__(self, *args, **kw):self.window_length = 600self.window_wide = 500# 绘制游戏窗口,设置窗口尺寸self.game_window = pygame.display.set_mode((self.window_length, self.window_wide))# 设置游戏窗口标题pygame.display.set_caption("打砖块-Python代码大全")# 定义游戏窗口背景颜色参数self.window_color = (135, 206, 250)def backgroud(self):# 绘制游戏窗口背景颜色self.game_window.fill(self.window_color)class Ball(object):'''创建球类'''def __init__(self, *args, **kw):# 设置球的半径、颜色、移动速度参数self.ball_color = (255, 215, 0)self.move_x = 1self.move_y = 1self.radius = 10def ballready(self):# 设置球的初始位置、self.ball_x = self.mouse_xself.ball_y = self.window_wide - self.rect_wide - self.radius# 绘制球,设置反弹触发条件pygame.draw.circle(self.game_window, self.ball_color, (self.ball_x, self.ball_y), self.radius)def ballmove(self):# 绘制球,设置反弹触发条件pygame.draw.circle(self.game_window, self.ball_color, (self.ball_x, self.ball_y), self.radius)self.ball_x += self.move_xself.ball_y -= self.move_y# 调用碰撞检测函数self.ball_window()self.ball_rect()# 每接5次球球速增加一倍if self.distance < self.radius:self.frequency += 1if self.frequency == 5:self.frequency = 0self.move_x += self.move_xself.move_y += self.move_yself.point += self.point# 设置游戏失败条件if self.ball_y > 520:self.gameover = self.over_font.render("Game Over", False, (0, 0, 0))self.game_window.blit(self.gameover, (100, 130))self.over_sign = 1class Rect(object):'''创建球拍类'''def __init__(self, *args, **kw):# 设置球拍颜色参数self.rect_color = (255, 0, 0)self.rect_length = 100self.rect_wide = 10def rectmove(self):# 获取鼠标位置参数self.mouse_x, self.mouse_y = pygame.mouse.get_pos()# 绘制球拍,限定横向边界if self.mouse_x >= self.window_length - self.rect_length // 2:self.mouse_x = self.window_length - self.rect_length // 2if self.mouse_x <= self.rect_length // 2:self.mouse_x = self.rect_length // 2pygame.draw.rect(self.game_window, self.rect_color, ((self.mouse_x - self.rect_length // 2), (self.window_wide - self.rect_wide), self.rect_length, self.rect_wide))class Brick(object):def __init__(self, *args, **kw):# 设置砖块颜色参数self.brick_color = (139, 126, 102)self.brick_list = [[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1]]self.brick_length = 80self.brick_wide = 20def brickarrange(self):for i in range(5):for j in range(6):self.brick_x = j * (self.brick_length + 24)self.brick_y = i * (self.brick_wide + 20) + 40if self.brick_list[i][j] == 1:# 绘制砖块pygame.draw.rect(self.game_window, self.brick_color,(self.brick_x, self.brick_y, self.brick_length, self.brick_wide))# 调用碰撞检测函数self.ball_brick()if self.distanceb < self.radius:self.brick_list[i][j] = 0self.score += self.point# 设置游戏胜利条件if self.brick_list == [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0]]:self.win = self.win_font.render("You Win", False, (0, 0, 0))self.game_window.blit(self.win, (100, 130))self.win_sign = 1class Score(object):'''创建分数类'''def __init__(self, *args, **kw):# 设置初始分数self.score = 0# 设置分数字体self.score_font = pygame.font.SysFont('arial', 20)# 设置初始加分点数self.point = 1# 设置初始接球次数self.frequency = 0def countscore(self):# 绘制玩家分数my_score = self.score_font.render(str(self.score), False, (255, 255, 255))self.game_window.blit(my_score, (555, 15))class GameOver(object):'''创建游戏结束类'''def __init__(self, *args, **kw):# 设置Game Over字体self.over_font = pygame.font.SysFont('arial', 80)# 定义GameOver标识self.over_sign = 0class Win(object):'''创建游戏胜利类'''def __init__(self, *args, **kw):# 设置You Win字体self.win_font = pygame.font.SysFont('arial', 80)# 定义Win标识self.win_sign = 0class Collision(object):'''碰撞检测类'''# 球与窗口边框的碰撞检测def ball_window(self):if self.ball_x <= self.radius or self.ball_x >= (self.window_length - self.radius):self.move_x = -self.move_xif self.ball_y <= self.radius:self.move_y = -self.move_y# 球与球拍的碰撞检测def ball_rect(self):# 定义碰撞标识self.collision_sign_x = 0self.collision_sign_y = 0if self.ball_x < (self.mouse_x - self.rect_length // 2):self.closestpoint_x = self.mouse_x - self.rect_length // 2self.collision_sign_x = 1elif self.ball_x > (self.mouse_x + self.rect_length // 2):self.closestpoint_x = self.mouse_x + self.rect_length // 2self.collision_sign_x = 2else:self.closestpoint_x = self.ball_xself.collision_sign_x = 3if self.ball_y < (self.window_wide - self.rect_wide):self.closestpoint_y = (self.window_wide - self.rect_wide)self.collision_sign_y = 1elif self.ball_y > self.window_wide:self.closestpoint_y = self.window_wideself.collision_sign_y = 2else:self.closestpoint_y = self.ball_yself.collision_sign_y = 3# 定义球拍到圆心最近点与圆心的距离self.distance = math.sqrt(math.pow(self.closestpoint_x - self.ball_x, 2) + math.pow(self.closestpoint_y - self.ball_y, 2))# 球在球拍上左、上中、上右3种情况的碰撞检测if self.distance < self.radius and self.collision_sign_y == 1 and (self.collision_sign_x == 1 or self.collision_sign_x == 2):if self.collision_sign_x == 1 and self.move_x > 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_x == 1 and self.move_x < 0:self.move_y = - self.move_yif self.collision_sign_x == 2 and self.move_x < 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_x == 2 and self.move_x > 0:self.move_y = - self.move_yif self.distance < self.radius and self.collision_sign_y == 1 and self.collision_sign_x == 3:self.move_y = - self.move_y# 球在球拍左、右两侧中间的碰撞检测if self.distance < self.radius and self.collision_sign_y == 3:self.move_x = - self.move_x# 球与砖块的碰撞检测def ball_brick(self):# 定义碰撞标识self.collision_sign_bx = 0self.collision_sign_by = 0if self.ball_x < self.brick_x:self.closestpoint_bx = self.brick_xself.collision_sign_bx = 1elif self.ball_x > self.brick_x + self.brick_length:self.closestpoint_bx = self.brick_x + self.brick_lengthself.collision_sign_bx = 2else:self.closestpoint_bx = self.ball_xself.collision_sign_bx = 3if self.ball_y < self.brick_y:self.closestpoint_by = self.brick_yself.collision_sign_by = 1elif self.ball_y > self.brick_y + self.brick_wide:self.closestpoint_by = self.brick_y + self.brick_wideself.collision_sign_by = 2else:self.closestpoint_by = self.ball_yself.collision_sign_by = 3# 定义砖块到圆心最近点与圆心的距离self.distanceb = math.sqrt(math.pow(self.closestpoint_bx - self.ball_x, 2) + math.pow(self.closestpoint_by - self.ball_y, 2))# 球在砖块上左、上中、上右3种情况的碰撞检测if self.distanceb < self.radius and self.collision_sign_by == 1 and (self.collision_sign_bx == 1 or self.collision_sign_bx == 2):if self.collision_sign_bx == 1 and self.move_x > 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_bx == 1 and self.move_x < 0:self.move_y = - self.move_yif self.collision_sign_bx == 2 and self.move_x < 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_bx == 2 and self.move_x > 0:self.move_y = - self.move_yif self.distanceb < self.radius and self.collision_sign_by == 1 and self.collision_sign_bx == 3:self.move_y = - self.move_y# 球在砖块下左、下中、下右3种情况的碰撞检测if self.distanceb < self.radius and self.collision_sign_by == 2 and (self.collision_sign_bx == 1 or self.collision_sign_bx == 2):if self.collision_sign_bx == 1 and self.move_x > 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_bx == 1 and self.move_x < 0:self.move_y = - self.move_yif self.collision_sign_bx == 2 and self.move_x < 0:self.move_x = - self.move_xself.move_y = - self.move_yif self.collision_sign_bx == 2 and self.move_x > 0:self.move_y = - self.move_yif self.distanceb < self.radius and self.collision_sign_by == 2 and self.collision_sign_bx == 3:self.move_y = - self.move_y# 球在砖块左、右两侧中间的碰撞检测if self.distanceb < self.radius and self.collision_sign_by == 3:self.move_x = - self.move_xclass Main(GameWindow, Rect, Ball, Brick, Collision, Score, Win, GameOver):'''创建主程序类'''def __init__(self, *args, **kw):super(Main, self).__init__(*args, **kw)super(GameWindow, self).__init__(*args, **kw)super(Rect, self).__init__(*args, **kw)super(Ball, self).__init__(*args, **kw)super(Brick, self).__init__(*args, **kw)super(Collision, self).__init__(*args, **kw)super(Score, self).__init__(*args, **kw)super(Win, self).__init__(*args, **kw)# 定义游戏开始标识start_sign = 0while True:self.backgroud()self.rectmove()self.countscore()if self.over_sign == 1 or self.win_sign == 1:break# 获取游戏窗口状态for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()if event.type == MOUSEBUTTONDOWN:pressed_array = pygame.mouse.get_pressed()if pressed_array[0]:start_sign = 1if start_sign == 0:self.ballready()else:self.ballmove()self.brickarrange()# 更新游戏窗口pygame.display.update()# 控制游戏窗口刷新频率time.sleep(0.010)if __name__ == '__main__':pygame.init()pygame.font.init()catchball = Main()

更多Python代码请微信关注公众号:Python代码大全,

Python打砖块小游戏源代码相关推荐

  1. Python版见缝插针小游戏源代码,球球旋转大作战源程序

    见缝插针游戏是一款非常考验玩家手眼协调能力的休闲益智虐心虐脑小游戏,玩法很简单,但要过关却很有挑战性哟! 主要是将一系列的小球,插入到旋转的摩天轮转盘当中,插入过程中不能碰到旋转的摩天轮上的其他小球, ...

  2. Python魂斗罗小游戏源代码

    Python魂斗罗小游戏源代码源程序,主程序Contra.py,游戏简易使用说明:A:向左,D:向右,W:跳起,S:趴下,J:射击,P:退出程序. 程序运行截图: Contra.py ''' 公众号: ...

  3. bat小游戏代码大全_Python打砖块小游戏源代码

    这次用Python实现的是一个接球打砖块的小游戏,最核心的就是:碰撞检测的数学模型 程序运行截图: 其实,编程问题到最后就是数学问题,这个游戏涉及到2D圆形与矩形的碰撞检测问题: 碰撞检测原理:通过找 ...

  4. python推箱子小游戏源代码_Python制作推箱子小游戏

    开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Python自带的模块. 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可. 原理简介 游戏简介 ...

  5. python打字游戏增加开始页面_Python实践项目大全之Python打字练习小游戏源代码

    from tkinter import *import randomimport stringfrom datetime import datetimeroot = Tk()root.title(&q ...

  6. python小游戏代码大全-Python实现打砖块小游戏代码实例

    这次用Python实现的是一个接球打砖块的小游戏,需要导入pygame模块,有以下两条经验总结: 1.多父类的继承2.碰撞检测的数学模型 知识点稍后再说,我们先看看游戏的效果和实现: 一.游戏效果 二 ...

  7. python双手打字_Python打字练习小游戏源代码

    Python打字练习小游戏源代码 Python代码狂人 Python代码大全 Python打字练习小游戏源程序,随机产生一串字符,可对打字练习的正确率和时间进行统计,运行截图如下: from tkin ...

  8. Python地雷战小游戏源代码

    Python版地道战小游戏源代码,游戏中寻找所需要的五种合成地雷的原材料,并躲避敌人的抓捕,雷可以炸死敌方.程序运行截图: 主要程序代码: tunnel_war_game.py import pyga ...

  9. JS打砖块小游戏 canvas绘制

    html5 canvas绘制打砖块小游戏 源代码 github源码下载地址 项目展示 下面放上主要代码 index.js代码 var game = {canvas : document.getElem ...

最新文章

  1. python基本判断语句_python基础4 - 判断(if)语句
  2. 面向搜索引擎的内容管理系统(CMS)设计
  3. 一次有趣的面试经历,当前端面试碰到后端面试官会发生什么?
  4. java 内部类 单例_确保对象的唯一性——单例模式 (四):一种更好的单例实现方法(静态内部类)...
  5. mysql5.5启动报错:The server quit without updating PID file ([FAILED]localhost.localdomain.pid)....
  6. php 加载库文件_php 如何调用dll文件内接口,求大神帮忙谢谢。
  7. U盘病毒“替身”大量交叉感染 打印店电脑助扩散
  8. html相册 自动,ACDSee的HTML相册生成
  9. matlab神经网络训练结果常用评价指标
  10. ICMP协议(网际报文控制协议)详解
  11. java 同比数据怎么算的_如何计算同比的计算公式?
  12. netkeeper显示651_关于电信Netkeeper客户端升级的通知
  13. android textview字体为宋体,安卓开发--textView的字体样式设置(设置宋体,微软雅黑等)...
  14. QIIME 2教程. 03老司机上路指南Experience(2021.2)
  15. 双月报8.24-10.23
  16. div完成田字格布局
  17. 计算机二级c语言程序设计改错,2017年计算机二级C语言上机改错题考点总结
  18. 利用黑客手段一台手机“变”出千万台,新型诈骗技术曝光
  19. PostgreSQL分区
  20. 美的地产竞得石家庄50亩地块 美的布局开始

热门文章

  1. 某乎x-zse-96
  2. Python matplotlib入门级绘制图形(一)--利用plot()绘制简单图形
  3. 5G路由器值得买吗?它有什么优点
  4. 笔记:如何永久关闭vscode的安全提示
  5. Windows基本的安全加固策略
  6. LaTeX技巧009:去掉图片标题中的‘:’号
  7. autocad全国计算机考试试题,2015年职称计算机考试试题:AutoCAD模拟题及答案
  8. 小米电视微信投屏服务器出错,同一wifi下无法投屏怎么办 小米电视不能投屏的解决方法...
  9. ###vuex###
  10. python俄罗斯方块代码turtle_Python:游戏:300行代码实现俄罗斯方块