source: nagslang/mutators.py@ 364:72a91d64c088

Last change on this file since 364:72a91d64c088 was 364:72a91d64c088, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

Keycard doors.

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
60# Identity mutator
61NULL = Mutator(lambda x: x)
62
63# Rotation
64R90 = Mutator(rotate, 90)
65R180 = Mutator(rotate, 180)
66R270 = Mutator(rotate, -90)
67
68FLIP_H = Mutator(flip, True, False)
69FLIP_V = Mutator(flip, False, True)
70
71# Colour
72RED = Colour((255, 0, 0))
73GREEN = Colour((0, 255, 0))
74BLUE = Colour((0, 0, 255))
Note: See TracBrowser for help on using the repository browser.