Python 愤怒的小鸟代码实现(1):物理引擎pymunk使用

Python 愤怒的小鸟代码实现(1):物理引擎pymunk使用

2019-10-04 16:38:47 marble_xu 阅读数 9887更多

分类专栏: python 游戏开发

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/marble_xu/article/details/102079236

python 愤怒的小鸟代码实现(1):物理引擎pymunk使用

游戏介绍

最近比较忙,国庆正好有时间写了python版本的愤怒的小鸟,使用了物理引擎pymunk,图片资源是从github上下载的,实现了一个可玩的简单版本。

功能实现如下:

  • 支持小鸟类型:红色小鸟,蓝色小鸟,黄色小鸟。
  • 支持障碍物的类型:玻璃,木头,石头。
  • 支持障碍物的形状:各种长度的长方形,正方形和圆形。
  • 使用json文件保存关卡信息,设置小猪和障碍物的位置。

游戏截图如下:
图1demo1
图2demo2
图3demo3

完整代码

游戏实现代码的github链接 愤怒的小鸟
这边是csdn的下载链接 愤怒的小鸟

Pymunk介绍

pymunk是一个2D的物理引擎, 它实际是封装了 c语言写的2D物理引擎Chipmunk,可以实现碰撞,旋转等物理运动。

安装pymunk,可以直接使用pip工具,安装最新的pymunk 5.5.0:

    pip install pymunk
  • 1

介绍下在pymunk中会使用到的四个基本的类:

  • 刚体 (pymunk.Body):一个刚体具有物体的物理属性(质量、坐标、旋转角度、速度等),它自己是没有形状的。
  • 碰撞形状 (pymunk.Circle, pymunk.Segment and pymunk.Poly):通过将形状附加到实体,你可以定义一个实体的形状。你可以将多个形状附加到单个实体上来定义一个复杂的形状,如果不需要形状,则可以不附加任何形状。
  • 约束/关节 (pymunk.constraint.PinJoint, pymunk.constraint.SimpleMotor):你可以在两个实体之间附加关节以约束它们的行为。比如在两个实体间保持一个固定的距离。
  • 空间 (pymunk.Space): 空间是pymunk中基本的模拟单元。你可以添加实体,形状和关节到空间,然后整体更新空间。pymunk会控制空间中所有的实体,形状和关节如何相互作用。

代码实现

将物理引擎相关的代码单独放在了一个文件 (source\component\physics.py)中,减少代码的耦合。
定义了一个Physics类,向外提供所有物理引擎相关的函数。
这篇文章只介绍physics.py 中pymunk相关的代码。

pymunk相关初始化

reset 函数初始化了 空间类(pm.Space), 设置了两个参数

  • gravity : 重力
  • dt (Time step length) : 表示pymunk中每次更新的时间段值,比如dt值是0.002,表示时间段是0.002秒。

setup_lines函数设置了一条直线,作为地面。
Segment类创建了一条从点a 到 点b的直线。

class pymunk.Segment(body, a, b, radius)
Bases: pymunk.shapes.Shape
A line segment shape between two point. Meant mainly as a static shape.
  • 1
  • 2
  • 3
import pymunk as pm

class Physics():
    def __init__(self):
        self.reset()

    def reset(self, level=None):
        self.level = level
        # init space: set gravity and dt
        self.space = pm.Space()
        self.space.gravity = (0.0, -700.0)
        self.dt = 0.002
        self.birds = []
        self.pigs = []
        self.blocks = []
        self.path_timer = 0
        self.check_collide = False
        self.setup_lines()
        self.setup_collision_handler()

    def setup_lines(self):
        # Static Ground
        x, y = to_pymunk(c.SCREEN_WIDTH, c.GROUND_HEIGHT)
        static_body = pm.Body(body_type=pm.Body.STATIC)
        static_lines = [pm.Segment(static_body, (0.0, y), (x, y), 0.0)]

        for line in static_lines:
            line.elasticity = 0.95
            line.friction = 1
            line.collision_type = COLLISION_LINE
        self.space.add(static_lines)
        self.static_lines = static_lines
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

setup_collision_handler 函数用来设置在两种类型的物体在碰撞发生时,可以由用户使用的回调函数。
add_collision_handler 函数添加两种类型物体a和b碰撞时会调用的handler。比如小猪和小鸟这两种类型物体的注册函数就是:add_collision_handler(COLLISION_PIG, COLLISION_BIRD)

add_collision_handler(collision_type_a, collision_type_b)
Return the CollisionHandler for collisions between objects of type collision_type_a and collision_type_b.
  • 1
  • 2

我们这里只用到了 post_solve 回调函数,在两个物体碰撞结束后,获取碰撞冲击力(collision impulse)。

post_solve
Two shapes are touching and their collision response has been processed.
func(arbiter, space, data)
You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See Arbiter for more info.
  • 1
  • 2
  • 3
  • 4

比如handle_pig_collide函数在小猪和障碍物碰撞后,会根据冲击力的大小来相应减去小猪的生命。

COLLISION_BIRD = 1
COLLISION_PIG = 2
COLLISION_BLOCK = 3
COLLISION_LINE = 4

    def setup_collision_handler(self):
        def post_solve_bird_line(arbiter, space, data):
            if self.check_collide:
                bird_shape = arbiter.shapes[0]
                my_phy.handle_bird_collide(bird_shape, True)
        def post_solve_pig_bird(arbiter, space, data):
            if self.check_collide:
                pig_shape = arbiter.shapes[0]
                my_phy.handle_pig_collide(pig_shape, MAX_IMPULSE)
        def post_solve_pig_line(arbiter, space, data):
            if self.check_collide:
                pig_shape = arbiter.shapes[0]
                my_phy.handle_pig_collide(pig_shape, arbiter.total_impulse.length, True)
        def post_solve_pig_block(arbiter, space, data):
            if self.check_collide:
                if arbiter.total_impulse.length > MIN_DAMAGE_IMPULSE:
                    pig_shape = arbiter.shapes[0]
                    my_phy.handle_pig_collide(pig_shape, arbiter.total_impulse.length)
        def post_solve_block_bird(arbiter, space, data):
            if self.check_collide:
                block_shape, bird_shape = arbiter.shapes
                my_phy.handle_bird_collide(bird_shape)
                if arbiter.total_impulse.length > 1100:
                    my_phy.handle_block_collide(block_shape, arbiter.total_impulse.length)

        self.space.add_collision_handler(
            COLLISION_BIRD, COLLISION_LINE).post_solve = post_solve_bird_line

        self.space.add_collision_handler(
            COLLISION_PIG, COLLISION_BIRD).post_solve = post_solve_pig_bird

        self.space.add_collision_handler(
            COLLISION_PIG, COLLISION_LINE).post_solve = post_solve_pig_line

        self.space.add_collision_handler(
            COLLISION_PIG, COLLISION_BLOCK).post_solve = post_solve_pig_block

        self.space.add_collision_handler(
            COLLISION_BLOCK, COLLISION_BIRD).post_solve = post_solve_block_bird

    def handle_pig_collide(self, pig_shape, impulse, is_ground=False):
        for pig in self.pigs:
            if pig_shape == pig.phy.shape:
                if is_ground:
                    pig.phy.body.velocity = pig.phy.body.velocity * 0.8
                else:
                    damage = impulse // MIN_DAMAGE_IMPULSE
                    pig.set_damage(damage)

# must init as a global parameter to use in the post_solve handler
my_phy = Physics()

创建一个pymunk物体

创建物体一般有下面五个步骤

  1. moment_for_circle 函数根据质量(mass), 圆的半径 来计算出刚体的转动惯量(Moment Of Inertia),惯量就像刚体的旋转质量。

    pymunk.moment_for_circle(mass, inner_radius, outer_radius, offset=(0, 0))
    Calculate the moment of inertia for a hollow circle
    inner_radius and outer_radius are the inner and outer diameters. (A solid circle has an inner diameter of 0)

  2. 根据质量和转动惯量来创建一个刚体(pymunk.Body)。

    class pymunk.Body(mass=0, moment=0, body_type=<class 'CP_BODY_TYPE_DYNAMIC'>)
    
    • 1
  3. 根据刚体,和形状类型创建一个碰撞形状,比如圆形就是 pymunk.Circle。
    class pymunk.Circle(body, radius, offset=(0, 0))
    Bases: pymunk.shapes.Shape
    A circle shape defined by a radius

  4. 设置形状的一些属性

摩擦系数(friction)

Friction coefficient.
Pymunk uses the Coulomb friction model, a value of 0.0 is frictionless.
A value over 1.0 is perfectly fine.

弹力 (elasticity)

Elasticity of the shape.
A value of 0.0 gives no bounce, while a value of 1.0 will give a ‘perfect’ bounce. 
  1. 最后将这个刚体和碰撞形状都添加到空间中。

     pymunk.Space.add(*objs)
     Add one or many shapes, bodies or joints to the space
    
class PhyPig():
    def __init__(self, x, y, radius, space):
        mass = 5
        inertia = pm.moment_for_circle(mass, 0, radius, (0, 0))
        body = pm.Body(mass, inertia)
        body.position = x, y
        shape = pm.Circle(body, radius, (0, 0))
        shape.elasticity = 0.95
        shape.friction = 1
        shape.collision_type = COLLISION_PIG
        space.add(body, shape)
        self.body = body
        self.shape = shape

PhyPig 类的初始化函数创建了一个小猪物体,参数有物体的位置(x,y), 可以将小猪作为一个圆形物体,所以参数有圆的半径(radius), 参数space就是我们上面创建的空间类。

pymunk 状态更新

update函数是更新函数,代码只显示了小猪相关的代码。

step 函数的参数dt值就是上面设置的时间段值,表示这次调用 该空间经过了多少时间,pymunk 根据这个时间值更新空间中的所有物体的状态(比如速度,位置等)。按照pymunk 文档的说明,将dt值设小一点,每次调用多次会使得模拟更稳定和精确,所以这里每次调用5次step函数。

pymunk.Space.step(dt)
Update the space for the given time step.

遍历所有的小猪:

  • 检查小猪的状态,如果生命小于零或者y轴位置超出了范围,删除这个小猪。
  • 更新小猪的位置
    pygame 和 pymunk 中对于位置的值是不同的, y轴的坐标需要进行转换,具体看 to_pygame 函数,600是高度。pymunk 中 body.position的值是物体的中间位置,对应pygame 中 rect 的centerx 和 centery,所以需要转成[left, top]位置。
    • pygame中,以左上角的位置为(0,0)
    • pymunk中,以左下角的位置为(0,0)
def to_pygame(p):
    """Convert position of pymunk to position of pygame"""
    return int(p.x), int(-p.y+600)

    def update(self, game_info, level, mouse_pressed):
        pigs_to_remove = []

        #From pymunk doc:Performing multiple calls with a smaller dt
        #                creates a more stable and accurate simulation
        #So make five updates per frame for better stability
        for x in range(5):
            self.space.step(self.dt)
        ...
        for pig in self.pigs:
            pig.update(game_info)
            if pig.phy.body.position.y < 0 or pig.life <= 0:
                pigs_to_remove.append(pig)
            poly = pig.phy.shape
            p = to_pygame(poly.body.position)
            x, y = p
            w, h = pig.image.get_size()
            # change to [left, top] position of pygame
            x -= w * 0.5
            y -= h * 0.5
            angle_degree = math.degrees(poly.body.angle)
            pig.update_position(x, y, angle_degree)

        for pig in pigs_to_remove:
            self.space.remove(pig.phy.shape, pig.phy.shape.body)
            self.pigs.remove(pig)
            level.update_score(c.PIG_SCORE)
        ...

编译环境

python3.7 + pygame1.9 + pymunk 5.5.0

原文地址:https://www.cnblogs.com/grj001/p/12223575.html