python-pygame与pymunk-倒塌解压金字塔

32 篇文章 5 订阅
10 篇文章 1 订阅
金字塔

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

百度网盘:链接: 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, math

Need Pip First:
Pygame, Pymunk

Tips 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 first
    global 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.Segment
    ground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)
    # friction
    ground.friction = 1
    # add ground
    space.add(ground)
    # input
    draw_options = pu.DrawOptions(screen)
    # use Vec2d
    a = Vec2d(540,490)
    dx = Vec2d(10,20)
    dy = Vec2d(20,0)
    # it is difficult here.
    # draw a pyramid by range
    for i in range(25):
        b = Vec2d(*a)
        for j in range(25-i):
            # create body!
            body = pm.Body(1,2000)
            body.position = b
            rect = pm.Poly(body,points)
            rect.friction = 1
            # add body
            space.add(body,rect)
            # check pos
            b -= dx
        # check pos again
        a-=dy
        """
        steps:
        1. create body
        2. set body's pos
        3. create poly
        4. set poly's friction
        5. add these things into pymunk's space
        these steps can use to make a thing has gravity
        Vec2d is a difficult step.
        """
        # these steps must remind

# def draw
def draw():
    # fill
    screen.fill((255,255,255))
    # debug_draw
    space.debug_draw(draw_options)
    # step
    space.step(1/60)
    # display
    pg.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 pressed
    if pg.mouse.get_pressed()[0]:
        # mPos
        mPos = pg.mouse.get_pos()
        # use range
        for i in range(len(space.bodies)):
            # check if touch rect...
            # analogy and ignores
            if dis(mPos, space.bodies[i].position) < 10:
                # remove bodies and shapes
                space.remove(space.bodies[i])
                # need i + 1
                space.remove(space.shapes[i+1])
                # need break
                break

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

在数学中,向量(也称为欧几里得向量、几何向量、矢量),指具有大小(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 fps
    fps.tick(60)
    # quit events
    event = pg.event.poll()
    if event.type==pg.QUIT:
        pg.quit()
        sys.exit()
    # if pressed
    if pg.mouse.get_pressed()[2]:
        # delete
        # must use *list, or wrong
        space.remove(*space.bodies)
        space.remove(*space.shapes)
        main()
    # set title with fps:n
    # must use string
    pg.display.set_caption("fps: " + str(fps.get_fps()))
    # use draw
    draw()
    # use click
    click()

和之前的差不多,就是之前要提前用一下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, math

Need Pip First:
Pygame, Pymunk

Tips 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 first
    global 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.Segment
    ground = pm.Segment(space.static_body, (0, 500), (600, 500), 3)
    # friction
    ground.friction = 1
    # add ground
    space.add(ground)
    # input
    draw_options = pu.DrawOptions(screen)
    # use Vec2d
    a = Vec2d(540,490)
    dx = Vec2d(10,20)
    dy = Vec2d(20,0)
    # it is difficult here.
    # draw a pyramid by range
    for i in range(25):
        b = Vec2d(*a)
        for j in range(25-i):
            # create body!
            body = pm.Body(1,2000)
            body.position = b
            rect = pm.Poly(body,points)
            rect.friction = 1
            # add body
            space.add(body,rect)
            # check pos
            b -= dx
        # check pos again
        a-=dy
        """
        steps:
        1. create body
        2. set body's pos
        3. create poly
        4. set poly's friction
        5. add these things into pymunk's space
        these steps can use to make a thing has gravity
        Vec2d is a difficult step.
        """
        # these steps must remind

# def draw
def draw():
    # fill
    screen.fill((255,255,255))
    # debug_draw
    space.debug_draw(draw_options)
    # step
    space.step(1/60)
    # display
    pg.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 pressed
    if pg.mouse.get_pressed()[0]:
        # mPos
        mPos = pg.mouse.get_pos()
        # use range
        for i in range(len(space.bodies)):
            # check if touch rect...
            # analogy and ignores
            if dis(mPos, space.bodies[i].position) < 10:
                # remove bodies and shapes
                space.remove(space.bodies[i])
                # need i + 1
                space.remove(space.shapes[i+1])
                # need break
                break

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

五、效果图

金字塔

五、总结

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

六、花絮

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

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

好了,大家再见! 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值