Extending the sprite pygame class

So I'm writing a python game with pygame, and I have separate classes (like pygame.sprite.Sprite) for my different sprites - however they all share a lot of common physics code. How can I extend the base sprite class so that the general physics stuff is written once and I just add the class to each sprite class?

eg. Change this:

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

      

In that

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

      

+3


source to share


1 answer


Just inherit your intermediate class from Sprite

and inherit after that:

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

class ShipSprite(my_custom_class):
    ...

      

If you want to add your "custom_class" stuff to a somewhat abstract class that shouldn't behave like Sprite and can be used in other contexts, you can also use Multiple Inheritance -



class my_custom_class(object):
    def common_physics_stuff()
        pass

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

      

But this will probably be overkill - in either of these two cases, in any method you override in your game classes, just remember to call the correct uisng ancestor method super

in Python.

(In my small game projects, I usually make a base GameObject class for all my objects that inherit from Pygame Sprite)

+2


source







All Articles