source: nagslang/mutators.py

Last change on this file was 604:0185d2b508c8, checked in by Stefano Rivera <stefano@…>, 8 years ago

Don't leak mutators (leading to leaked images)

File size: 2.7 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 == 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
60class ImageCentre(Mutator):
61 def __init__(self, size):
62 super(ImageCentre, self).__init__(ImageCentre.centre, size)
63
64 @classmethod
65 def centre(cls, image, size):
66 if image.get_size() == size:
67 return image
68 surf = pygame.surface.Surface(size, pygame.locals.SRCALPHA, image)
69 surf.blit(image, ((size[0] - image.get_width()) / 2,
70 (size[1] - image.get_height()) / 2))
71 return surf
72
73
74def rotator(angle):
75 return Mutator(rotate, angle)
76
77
78def scaler(size):
79 return Mutator(scale, size)
80
81
82# Identity mutator
83NULL = Mutator(lambda x: x)
84
85# Rotation
86R90 = rotator(90)
87R180 = rotator(180)
88R270 = rotator(-90)
89
90FLIP_H = Mutator(flip, True, False)
91FLIP_V = Mutator(flip, False, True)
92
93# Colour
94RED = Colour((255, 0, 0))
95GREEN = Colour((0, 255, 0))
96BLUE = Colour((0, 0, 255))
Note: See TracBrowser for help on using the repository browser.