Image Objects as (PyRo)Sprite Models - skytreader/PyGame-Objects GitHub Wiki

What are Images for (image.Image in components) when PyGame already has built-in support for sprites? Images can serve as models (in the MVC sense) for sprites, as this document will discuss. By having a draw() method, Images also adapt PyGame sprites for the general scheme of the framework.

Also, we'll see what sprite.PyRoSprite is for, given that PyGame already has it's own sprite class.

Creating an Image object

The constructor for Images takes in a filename to the image file to be loaded. Image, for the main part, encapsulates a PyGame Surface created from a pygame.image.

Images also have a position property which is a shapes.Point object, describing where in a canvas is this Image's upper left corner. Images also have width and height properties which, together with position can be used to establish an Image's bounding rectangle.

Lastly, note that, unlike PointShapes, Images are not scalable. Thus, if you plan to vary the size of your window, it might be wise to have size-varying versions of an Image.

Feed it to the sprite!

How then, do we use it as a model for sprites? First, create your own sprite class that extends from both pygame.sprite.Sprite and subscriber_pattern.Observer, declared in that order. Make sure that you subscribe to the Image instance that serves as a model for your sprite and override Observer.notify to...

Tedious? PyRoSprite already takes care of the above for you. Constructing PyRoSprite only requires an instance of Image. Whenever something changes in the model Image, PyRoSprite automatically adapts.