【问题标题】:Extending pygame sprite class扩展 pygame 精灵类
【发布时间】:2015-08-22 21:28:41
【问题描述】:

所以我正在使用 pygame 在 python 中编写游戏,并且我为我的不同精灵有单独的类(类型为 pygame.sprite.Sprite) - 但是它们都共享许多常见的物理代码。如何扩展基本精灵类,以便编写一次常见的物理内容,然后将特定于类的内容添加到所需的每个精灵类中?

例如从此改变:

class ShipSprite(pygame.sprite.Sprite):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def common_physics_stuff()
        pass

    def ship_specific_stuff()
        pass

class AsteroidSprite(pygame.sprite.Sprite):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def common_physics_stuff()
        pass

    def asteroid_specific_stuff()
        pass

进入这个

class my_custom_class()
    def common_physics_stuff()
        pass

class ShipSprite(my_custom_class):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def ship_specific_stuff()
        pass

class AsteroidSprite(my_custom_class):

    def __init__(self, start_position=(500,500)):
        # Call the sprite initialiser
        pygame.sprite.Sprite.__init__(self)

        init_stuff()

    def asteroid_specific_stuff()
        pass

【问题讨论】:

  • 你不能只使用my_custom_class(pygame.sprite.Sprite) 让你的自定义继承基类吗?

标签: python class pygame


【解决方案1】:

只需从Sprite 继承您的中间类,然后从它继承:

class my_custom_class(pygame.sprite.Sprite):
    def common_physics_stuff()
        pass

class ShipSprite(my_custom_class):
    ...

如果你想将你的“custom_class”添加到一个有点抽象的类中,它的行为不必像 Sprite,并且可以在其他上下文中使用,你也可以使用多重继承 -

class my_custom_class(object):
    def common_physics_stuff()
        pass

class ShipSprite(pygame.sprite.Sprite, my_custom_class):
    ...

但这可能有点过头了——在这两种情况下,在你覆盖游戏类的任何方法上,只要记住使用super Python 内置函数调用正确的祖先方法即可。

(在我的小型游戏项目中,我通常为所有从 Pygame 的 Sprite 继承的对象创建一个“GameObject”基类)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多