Mercurial > rinkhals
comparison gamelib/imagecache.py @ 41:6055a8a8678d
Add image cache (with support for modified versions of an image).
author | Simon Cross <hodgestar@gmail.com> |
---|---|
date | Mon, 31 Aug 2009 16:47:54 +0000 |
parents | |
children | f20dd3dcb118 |
comparison
equal
deleted
inserted
replaced
40:678421bd58ee | 41:6055a8a8678d |
---|---|
1 """Central image cache to avoid loading images multiple times.""" | |
2 | |
3 import pygame | |
4 import data | |
5 | |
6 class ImageCache(object): | |
7 """Create an image cache with a list of modifiers.""" | |
8 | |
9 def __init__(self): | |
10 # (image name, ordered modifiers tuple) -> pygame surface | |
11 self._cache = {} | |
12 self._modifiers = {} | |
13 | |
14 def register_modifier(self, name, function): | |
15 """Register a post-load modifying function.""" | |
16 if name in self._modifiers: | |
17 raise ValueError("Attempt to re-register and existing modifier function.") | |
18 self._modifiers[name] = function | |
19 | |
20 def load_image(self, name, modifiers=None): | |
21 """Load an image from disk or return a cached image. | |
22 | |
23 name: image name relative to data path. | |
24 modifers: ordered list of modifiers to apply. | |
25 """ | |
26 # convert lists to tuples | |
27 if modifiers is not None: | |
28 modifiers = tuple(modifiers) | |
29 | |
30 # convert empty tuples to None | |
31 if not modifiers: | |
32 modifiers = None | |
33 | |
34 # look for modified image | |
35 key = (name, modifiers) | |
36 if key in self._cache: | |
37 return self._cache[key] | |
38 | |
39 # look for unmodified image | |
40 base_key = (name, None) | |
41 if base_key in self._cache: | |
42 image = self._cache[base_key] | |
43 else: | |
44 image = pygame.image.load(data.filepath(name)) | |
45 self._cache[base_key] = image | |
46 | |
47 # handle unmodified case | |
48 if modifiers is None: | |
49 return image | |
50 | |
51 for mod in modifiers: | |
52 image = self._modifiers[mod](image) | |
53 | |
54 self._cache[key] = image | |
55 return image | |
56 | |
57 # modifiers | |
58 | |
59 from pygame.locals import BLEND_RGBA_MULT | |
60 NIGHT_COLOUR = (100.0, 100.0, 200.0, 255.0) | |
61 | |
62 def convert_to_night(image): | |
63 """Convert a day tile to a night tile.""" | |
64 night_image = image.copy() | |
65 night_image.fill(NIGHT_COLOUR, None, BLEND_RGBA_MULT) | |
66 return night_image | |
67 | |
68 # globals | |
69 | |
70 cache = ImageCache() | |
71 cache.register_modifier("night", convert_to_night) | |
72 load_image = cache.load_image |