source: nagslang/mutators.py @ 519:ddd86cb25945

Last change on this file since 519:ddd86cb25945 was 519:ddd86cb25945, checked in by Jeremy Thurgood <firxen@…>, 7 years ago

Updated hangar.

File size: 2.2 KB
Line 
1'''Mutations to apply to images'''
2
3import pygame
4from pygame.transform import rotate, flip, scale
5
6
7class Mutator(object):
8    def __init__(self, func, *args):
9        self._func = func
10        self._args = tuple(args)
11
12    def __call__(self, image):
13        return self._func(image, *self._args)
14
15    def __hash__(self):
16        return hash((self._func, self._args))
17
18    def __eq__(self, other):
19        if not isinstance(other, Mutator):
20            return NotImplemented
21        return (self._func is other._func) and (self._args == other._args)
22
23    def __repr__(self):
24        return '<%s %r>' % (self.__class__.__name__, self._args)
25
26
27class Colour(Mutator):
28    '''Overlay a colour onto an image'''
29    def __init__(self, colour, blend=pygame.locals.BLEND_RGBA_MULT):
30        super(Colour, self).__init__(Colour.colour, colour, blend)
31
32    @classmethod
33    def colour(self, image, colour, blend):
34        image = image.copy()
35        overlay = pygame.surface.Surface(image.get_size(),
36                                         pygame.locals.SRCALPHA, image)
37        overlay.fill(colour)
38        image.blit(overlay, (0, 0), None, blend)
39        return image
40
41
42class ImageOverlay(Mutator):
43    '''Overlay another image onto an image'''
44    def __init__(self, image, offset=(0, 0), halfsize=True, blend=0):
45        super(ImageOverlay, self).__init__(
46            ImageOverlay.overlay, image, offset, halfsize, blend)
47
48    @classmethod
49    def overlay(self, image, overlay, offset, halfsize, blend):
50        image = image.copy()
51        if halfsize:
52            new_size = (overlay.get_width() / 2, overlay.get_height() / 2)
53            overlay = scale(overlay, new_size)
54        offset_x = image.get_width() / 2 - overlay.get_width() / 2 + offset[0]
55        offset_y = image.get_width() / 2 - overlay.get_width() / 2 + offset[1]
56        image.blit(overlay, (offset_x, offset_y), None, blend)
57        return image
58
59
60def rotator(angle):
61    return Mutator(rotate, angle)
62
63
64# Identity mutator
65NULL = Mutator(lambda x: x)
66
67# Rotation
68R90 = rotator(90)
69R180 = rotator(180)
70R270 = rotator(-90)
71
72FLIP_H = Mutator(flip, True, False)
73FLIP_V = Mutator(flip, False, True)
74
75# Colour
76RED = Colour((255, 0, 0))
77GREEN = Colour((0, 255, 0))
78BLUE = Colour((0, 0, 255))
Note: See TracBrowser for help on using the repository browser.