Source

pygamegsoc12 / alchemymadness / sprite.py

"""Sprites module"""

import pygame
from pygame.locals import Rect
from pygame.sprite import DirtySprite

class MaskedSprite(DirtySprite):
    """ Sprite with color

    rect, mask_rect, t_image should be overriden
    changed should be set to True whenever mask_rect is modified
    """
    rect = Rect(0,0,10,10)
    changed = False # True if sprite image need to be colored
    fill_flags = pygame.locals.BLEND_RGBA_MULT

    def __init__(self, color, *groups):
        """
            color - color of sprite - (r,g,b) tuple
        """
        super(MaskedSprite, self).__init__(*groups)
        self._image = pygame.Surface(self.rect.size) # Sprite colored image
        self.t_image = pygame.Surface(self.rect.size) # Sprite image
        self._color = color  # Block color
        self.mask_rect = Rect((0,0), self.rect.size)
        self.changed = True
        self.dirty = 1

    @property
    def image(self):
        if self.changed:
            self._image = self.t_image.copy()
            self._image.fill(self._color, self.mask_rect.clip(self._image.get_rect()), self.fill_flags)
        return self._image

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value
        self.changed = True