金字塔

大家好,我是涵子。是不是很久没有更新了呢?今天,我要来为大家带来——倒塌金字塔!

百度网盘:链接: https://pan.baidu.com/s/1qTjJ0JXwYgQiF_SAAkBFDQ 提取码: kvqn

Csdn文库:链接:python-pygame与pymunk-倒塌解压金字塔-其他文档类资源-CSDN文库


目录

一、提前准备

二、中间代码

三、最后程序

四、完整代码

五、效果图

五、总结

六、花絮


一、提前准备

今天,我们要特殊一点了:

# -coding utf-8 -
# author: BruceCodeFarmer
# article:csdn
# py file:csdn
# time: 2022/7/18
# name:code-5-2-10_pygame_FallingBlocks
# version: 1.20
"""
We use pygame, pymunk, pymunk.pygame_util, sys and Vec2d.
Please pip first.
Open setup.bat can pip all packages.Path:
Open Zip, and open setup.bat, click enter when system needs
Or open cmd, then pip all the things you need.Packages:
Pygame, Pymunk, sys, mathNeed Pip First:
Pygame, PymunkTips for everyone:
# do not transshipment my code or article if you haven't got my permission
# if you want transshipment, please talk with me on csdn
# if you want have code or zip, please download by csdn '涵子码农-什么语言都想学的程序员'
# if you see anyone transshipment my article or code, please tell me
#i f you see anything cannot read or know, you can ask me.@ csdn BruceCodeFarmer 涵子码农-什么语言都想学的程序员
You can get my permission in 2022/7/25 to 2023/7/25
"""
# import pygame ,pymunk, pymunk.pygame_util, Vec2d and sys
import pygame as pg
import pymunk as pm
import pymunk.pygame_util as pu
import sys
import math
from pymunk import Vec2d# we didn't use init again
# set screen
screen = pg.display.set_mode((600, 600)) # cannot change the size of the screen# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 900)# points
points = [(-10,-10),(-10,10),(10,10),(10,-10)]# position

是不是很难。首先,我们不用pygame.init()了,因为我们现在用的是pymunk与pygame的结合体,也就是pymunk.pygame_util了。

然后就是Vec2d,这就是向量!

二、中间代码

这里更是像苦痛之路。

# def main
def main():# global firstglobal draw_options"""In mathematics, a vector (also known as a Euclidean vector, geometric vector, or vector), is a quantity with magnitude and direction.It can be visually represented as a line segment with an arrow.Arrow points to: represents the direction of the vector; Segment length: represents the size of the vector.The quantity corresponding to a vector is called a quantity (scalar in physics), and a quantity (or scalar) has only magnitude and no direction.Vector notation: Printed as bold letters (such as A, B, U, V), with a small arrow "→" at the top of the letter.If A vector is given its starting point (A) and ending point (B), we can call the vector AB (and add → to the top).Vectors can also be expressed as pairs of numbers in the spatial cartesian coordinate system, for example in the xOy plane (2,3) is a vector.In physics and engineering, geometric vectors are more commonly referred to as vectors.Many physical quantities are vectors, such as the displacement of an object, the force exerted on a ball when it hits a wall, and so on.The opposite of this is a scalar, a quantity that has magnitude but no direction.Some vector-related definitions are also closely related to physical concepts, for example,vector potential corresponds to potential energy in physics.The concept of geometric vectors is abstracted in linear algebra to give rise to the more general concept of vectors.Here vectors are defined as elements of vector space.It should be noted that these abstract vectors are not necessarily represented by pairs of numbers,nor do the concepts of size and direction apply.Therefore, it is necessary to distinguish the concept of "vector" according to the context in daily reading.However, it is still possible to find a basis for a vector space to set the coordinate system, and it is also possible,by choosing an appropriate definition, to introduce the norm and inner product on the vector space,which allows us to compare abstract vectors to concrete geometric vectors.---From BaiduBaike---Website path: https://baike.baidu.com/item/%E5%90%91%E9%87%8F/1396519?fr=aladdin---Translate by YouDao translater"""# pm.Segmentground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)# frictionground.friction = 1# add groundspace.add(ground)# inputdraw_options = pu.DrawOptions(screen)# use Vec2da = Vec2d(540,490)dx = Vec2d(10,20)dy = Vec2d(20,0)# it is difficult here.# draw a pyramid by rangefor i in range(25):b = Vec2d(*a)for j in range(25-i):# create body!body = pm.Body(1,2000)body.position = brect = pm.Poly(body,points)rect.friction = 1# add bodyspace.add(body,rect)# check posb -= dx# check pos againa-=dy"""steps:1. create body2. set body's pos3. create poly4. set poly's friction5. add these things into pymunk's spacethese steps can use to make a thing has gravityVec2d is a difficult step."""# these steps must remind# def draw
def draw():# fillscreen.fill((255,255,255))# debug_drawspace.debug_draw(draw_options)# stepspace.step(1/60)# displaypg.display.update()# def dis
# use the pythagorean theorem again
def dis(a, b):return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5# also can use math.sqrt# def click
def click():# get pressedif pg.mouse.get_pressed()[0]:# mPosmPos = pg.mouse.get_pos()# use rangefor i in range(len(space.bodies)):# check if touch rect...# analogy and ignoresif dis(mPos, space.bodies[i].position) < 10:# remove bodies and shapesspace.remove(space.bodies[i])# need i + 1space.remove(space.shapes[i+1])# need breakbreak

首先,我们要搞懂什么是向量。下面内容又来自百度百科。

在数学中,向量(也称为欧几里得向量、几何向量、矢量),指具有大小(magnitude)和方向的量。它可以形象化地表示为带箭头的线段。箭头所指:代表向量的方向;线段长度:代表向量的大小。与向量对应的量叫做数量(物理学中称标量),数量(或标量)只有大小,没有方向。

向量的记法:印刷体记作黑体(粗体)的字母(如abuv),书写时在字母顶上加一小箭头“→”。  如果给定向量的起点(A)和终点(B),可将向量记作AB(并于顶上加→)。在空间直角坐标系中,也能把向量以数对形式表示,例如xOy平面中(2,3)是一向量。

在物理学和工程学中,几何向量更常被称为矢量。许多物理量都是矢量,比如一个物体的位移,球撞向墙而对其施加的力等等。与之相对的是标量,即只有大小而没有方向的量。一些与向量有关的定义亦与物理概念有密切的联系,例如向量势对应于物理中的势能。

几何向量的概念在线性代数中经由抽象化,得到更一般的向量概念。此处向量定义为向量空间的元素,要注意这些抽象意义上的向量不一定以数对表示,大小和方向的概念亦不一定适用。因此,平日阅读时需按照语境来区分文中所说的"向量"是哪一种概念。不过,依然可以找出一个向量空间的基来设置坐标系,也可以透过选取恰当的定义,在向量空间上介定范数和内积,这允许我们把抽象意义上的向量类比为具体的几何向量。

额,是很难。Vec就是向量,2D就是指2维平面中的向量。

然后从右下角往上画小方块。小方块的创建方法和之前的台球一样。

好了,我们接下来定义画函数。里面用了debug_draw等*@#()@)()¥*!@#¥()*

好吧,我看到了你们疑惑的眼神了。

接下来我们看看click函数

click函数可以判断是否按下左键,按下了就可以删掉球。用for循环来判断,如果判断到了附近的正方形。如果用dis函数判断到了距离在10里就删掉。然后break,否则要报错。

dis函数老相识了。就是勾股定理。这次可以用**0.5来代替math.sqrt

三、最后程序

# check fps and events
fps = pg.time.Clock()
# use main
main()
while True:# tick fpsfps.tick(60)# quit eventsevent = pg.event.poll()if event.type==pg.QUIT:pg.quit()sys.exit()# if pressedif pg.mouse.get_pressed()[2]:# delete# must use *list, or wrongspace.remove(*space.bodies)space.remove(*space.shapes)main()# set title with fps:n# must use stringpg.display.set_caption("fps: " + str(fps.get_fps()))# use drawdraw()# use clickclick()

和之前的差不多,就是之前要提前用一下main,然后在判断右键,按下了就remove所有的正方形,还要重组一遍,但要记住,在remove的时候要在前面加一个*,否则要报错。然后再给标题更改一下,改成fps:n,最后就是用draw和click。pygame.display.update()不用写了!

四、完整代码

奉上完整代码:

# -coding utf-8 -
# author: BruceCodeFarmer
# article:csdn
# py file:csdn
# time: 2022/7/18
# name:code-5-2-10_pygame_FallingBlocks
# version: 1.20
"""
We use pygame, pymunk, pymunk.pygame_util, sys and Vec2d.
Please pip first.
Open setup.bat can pip all packages.Path:
Open Zip, and open setup.bat, click enter when system needs
Or open cmd, then pip all the things you need.Packages:
Pygame, Pymunk, sys, mathNeed Pip First:
Pygame, PymunkTips for everyone:
# do not transshipment my code or article if you haven't got my permission
# if you want transshipment, please talk with me on csdn
# if you want have code or zip, please download by csdn '涵子码农-什么语言都想学的程序员'
# if you see anyone transshipment my article or code, please tell me
#i f you see anything cannot read or know, you can ask me.@ csdn BruceCodeFarmer 涵子码农-什么语言都想学的程序员
You can get my permission in 2022/7/25 to 2023/7/25
"""
# import pygame ,pymunk, pymunk.pygame_util, Vec2d and sys
import pygame as pg
import pymunk as pm
import pymunk.pygame_util as pu
import sys
import math
from pymunk import Vec2d# we didn't use init again
# set screen
screen = pg.display.set_mode((600, 600)) # cannot change the size of the screen# pymunk Space
space = pm.Space()
# gravity
# gravity and speed
space.gravity = (0, 900)# points
points = [(-10,-10),(-10,10),(10,10),(10,-10)]# position# def main
def main():# global firstglobal draw_options"""In mathematics, a vector (also known as a Euclidean vector, geometric vector, or vector), is a quantity with magnitude and direction.It can be visually represented as a line segment with an arrow.Arrow points to: represents the direction of the vector; Segment length: represents the size of the vector.The quantity corresponding to a vector is called a quantity (scalar in physics), and a quantity (or scalar) has only magnitude and no direction.Vector notation: Printed as bold letters (such as A, B, U, V), with a small arrow "→" at the top of the letter.If A vector is given its starting point (A) and ending point (B), we can call the vector AB (and add → to the top).Vectors can also be expressed as pairs of numbers in the spatial cartesian coordinate system, for example in the xOy plane (2,3) is a vector.In physics and engineering, geometric vectors are more commonly referred to as vectors.Many physical quantities are vectors, such as the displacement of an object, the force exerted on a ball when it hits a wall, and so on.The opposite of this is a scalar, a quantity that has magnitude but no direction.Some vector-related definitions are also closely related to physical concepts, for example,vector potential corresponds to potential energy in physics.The concept of geometric vectors is abstracted in linear algebra to give rise to the more general concept of vectors.Here vectors are defined as elements of vector space.It should be noted that these abstract vectors are not necessarily represented by pairs of numbers,nor do the concepts of size and direction apply.Therefore, it is necessary to distinguish the concept of "vector" according to the context in daily reading.However, it is still possible to find a basis for a vector space to set the coordinate system, and it is also possible,by choosing an appropriate definition, to introduce the norm and inner product on the vector space,which allows us to compare abstract vectors to concrete geometric vectors.---From BaiduBaike---Website path: https://baike.baidu.com/item/%E5%90%91%E9%87%8F/1396519?fr=aladdin---Translate by YouDao translater"""# pm.Segmentground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)# frictionground.friction = 1# add groundspace.add(ground)# inputdraw_options = pu.DrawOptions(screen)# use Vec2da = Vec2d(540,490)dx = Vec2d(10,20)dy = Vec2d(20,0)# it is difficult here.# draw a pyramid by rangefor i in range(25):b = Vec2d(*a)for j in range(25-i):# create body!body = pm.Body(1,2000)body.position = brect = pm.Poly(body,points)rect.friction = 1# add bodyspace.add(body,rect)# check posb -= dx# check pos againa-=dy"""steps:1. create body2. set body's pos3. create poly4. set poly's friction5. add these things into pymunk's spacethese steps can use to make a thing has gravityVec2d is a difficult step."""# these steps must remind# def draw
def draw():# fillscreen.fill((255,255,255))# debug_drawspace.debug_draw(draw_options)# stepspace.step(1/60)# displaypg.display.update()# def dis
# use the pythagorean theorem again
def dis(a, b):return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5# also can use math.sqrt# def click
def click():# get pressedif pg.mouse.get_pressed()[0]:# mPosmPos = pg.mouse.get_pos()# use rangefor i in range(len(space.bodies)):# check if touch rect...# analogy and ignoresif dis(mPos, space.bodies[i].position) < 10:# remove bodies and shapesspace.remove(space.bodies[i])# need i + 1space.remove(space.shapes[i+1])# need breakbreak# check fps and events
fps = pg.time.Clock()
# use main
main()
while True:# tick fpsfps.tick(60)# quit eventsevent = pg.event.poll()if event.type==pg.QUIT:pg.quit()sys.exit()# if pressedif pg.mouse.get_pressed()[2]:# delete# must use *list, or wrongspace.remove(*space.bodies)space.remove(*space.shapes)main()# set title with fps:n# must use stringpg.display.set_caption("fps: " + str(fps.get_fps()))# use drawdraw()# use clickclick()

五、效果图

金字塔

五、总结

通过这次学习 ,我们有进一步了解了python-pymunk和pygame的宇宙和厉害。我们不仅学习了如何把这两个毫不相关的库结合在了一起。希望大家可以玩得快乐,学得更深!

六、花絮

计算机与网络-day3-“硅与电脑的帝国”——硅谷(2)即将更新!

神秘人:你期待吗?希望我可以为你带来更多惊喜!

好了,大家再见!

python-pygame与pymunk-倒塌解压金字塔相关推荐

  1. python打包zip文件_python 解压文件,合并文件 打包成zip格式文件 生成MD5值

    #!/usr/bin/env python #_*_encoding:utf-8 # 2018/05/29 #augustyang #2.0 ''' 解压文件,合并文件 打包成zip格式文件 生成MD ...

  2. python input输入多个变量_「Python 秘籍」1.2 解压可迭代对象赋值给多个变量

    问题 需要从某个可迭代对象中分解出 N 个元素,但是这个可迭代对象的长度可能超过 N,这会导致出现"需要解包的值过多(too many values to unpack)"的异常. ...

  3. python打包出现乱码_python解压zip包中文乱码解决方法

    乱码得原因: 由于ZipFile模块导出遇到中文解码不对,windows上会出现,linux是否会出现不知道没测试过. 解决方式: 1. 搞个文件名引射表(不太方便,少量文件夹套用时候还可以) 2. ...

  4. Python特定场景数据内型“解压”操作

    背景:在特定情况下我们会取一个列表的或字符串的首个值或最后一个值,或第二个.倒数第二个值,这里讲解一种Python"解压"操作. 列表 ll = [23, 45, 67, 77, ...

  5. 【python】Python通过unrar库实现解压rar文件

    写在前面 因实际问题需要通过Python来解压rar文件,一开始是通过pip install rarfile也就是安装rarfile库来实现,但是它会报"rarfile.RarUnknown ...

  6. python压缩包zip下载后解压使用(安装pip)

    (1)下载安装脚本(注意在cmd中执行时,想把get-pip.py文件下载到哪个文件夹就cd到那个文件夹下执行该命令:curl https://bootstrap.pypa.io/get-pip.py ...

  7. Python:下载zip文件并解压zip文件数据

    以下载百度地图官方给出的中国各大城市中心经纬度压缩文件( https://mapopen-website-wiki.bj.bcebos.com/static_zip/BaiduMap_cityCent ...

  8. python 实现tar文件压缩解压的实例详解

    这里讨论使用Python解压如下五种压缩文件: .gz .tar .tgz .zip .rar 简介 gz: 即gzip,通常只能压缩一个文件.与tar结合起来就可以实现先打包,再压缩. tar: l ...

  9. Python的tgz安装包解压

    许久未安装Python了,一直以来我安装的都是exe版本的,结果今天下载发现不是tgz格式就是tar.xz,弄得有点不知所措,还好网上大神多,问题解决了,具体参考了下面这篇文章python tgz包安 ...

最新文章

  1. ORA-12518,TNS:listener could not hand off client connection
  2. “病毒防治”页面中“社区热帖”版块不显示
  3. CLR via C# 3 读书笔记(2):第1章 CLR执行模型 — 1.2 将托管模块组合为程序集
  4. decimal类型 go_Go 语言程序设计——字符串类型(2)
  5. 弹性文件服务解密 -- 应用场景区分
  6. php集合与数组的区别,php数组和链表的区别总结
  7. java LinkedList(链表)
  8. java建设银行支付_基于JAVA的建设银行账目管理系统的设计
  9. 对接湖南CA使用U_KEY登录
  10. php集成paypal接口,PayPal接口集成之:PHP集成PayPal标准支付接口
  11. win10计算机设备感叹号,win10系统设备管理中摄像头驱动显示黄色感叹号的解决办法...
  12. iphone长截图哪个软件好_这可能是 iPhone 上最好用的长截图软件,你用过吗?
  13. C盘清理方法汇总:SpaceSniffer与Windows.edb
  14. kali之破解隔壁老王wifi
  15. html表格转excel有科学计数法,table2excel生成excel表格出现科学计数法问题
  16. ERP和MES破冰之路 [普实MES升级中国“智”造]
  17. MISRA C (3)
  18. 上海房价和东京房价比较
  19. 行业级开源无人机目标追踪,高空助力抓贼!
  20. oracle 11g的企业管理器

热门文章

  1. 谈谈多线程中的Future
  2. QLabel类常用方法
  3. php html 纯文本,php – 使用纯文本回退发送HTML简报
  4. DRC设计规则设置介绍-Design Compiler(四)
  5. 微信小程序申请+开发+发布流程
  6. 企业信息化建设都包括哪些方面?
  7. android自动登录简书,android 手机号实现登录功能
  8. C#回顾学习笔记四十:三层架构
  9. 10个必须掌握的SQL常用语句
  10. conv2d原理、计算过程、pytorch使用