382e7c77555edaf0f60e633dab9042c2aa584173
[naja.git] / naja / resources / mutators.py
1 '''Mutations to apply to images'''
2
3 from pygame.transform import flip, rotate, scale
4
5 from naja.constants import EIGHT_BIT_SCALE
6
7
8 class Mutator(object):
9     def __init__(self, func, *args):
10         self._func = func
11         self._args = tuple(args)
12
13     def __call__(self, image):
14         return self._func(image, *self._args)
15
16     def __hash__(self):
17         return hash((self._func, self._args))
18
19     def __eq__(self, other):
20         if not isinstance(other, Mutator):
21             return NotImplemented
22         return (self._func == other._func) and (self._args == other._args)
23
24     def __repr__(self):
25         return '<%s %r>' % (self.__class__.__name__, self._args)
26
27
28 def rotator(angle):
29     return Mutator(rotate, angle)
30
31
32 def scaler(size):
33     return Mutator(scale, size)
34
35
36 def scale_multiplier(image, factor):
37     size = image.get_width() * factor, image.get_height() * factor
38     return scale(image, size)
39
40
41 # Identity mutator
42 NULL = Mutator(lambda x: x)
43
44 # Rotation
45 R90 = rotator(90)
46 R180 = rotator(180)
47 R270 = rotator(-90)
48
49 FLIP_H = Mutator(flip, True, False)
50 FLIP_V = Mutator(flip, False, True)
51
52 EIGHT_BIT = Mutator(scale_multiplier, EIGHT_BIT_SCALE)