comparison pyntnclick/resources.py @ 571:20e296d4a3a5 pyntnclick

Add load_image to Resources.
author Jeremy Thurgood <firxen@gmail.com>
date Sat, 11 Feb 2012 15:48:04 +0200
parents e207dfad0d9e
children 970cdc219e15
comparison
equal deleted inserted replaced
570:9c3528c2cbe5 571:20e296d4a3a5
1 # -*- test-case-name: pyntnclick.tests.test_resources -*- 1 # -*- test-case-name: pyntnclick.tests.test_resources -*-
2 2
3 import os 3 import os
4 from pkg_resources import resource_filename 4 from pkg_resources import resource_filename
5
6 import pygame
5 7
6 8
7 class ResourceNotFound(Exception): 9 class ResourceNotFound(Exception):
8 pass 10 pass
9 11
10 12
11 class Resources(object): 13 class Resources(object):
12 DEFAULT_RESOURCE_MODULE = "pyntnclick.data" 14 DEFAULT_RESOURCE_MODULE = "pyntnclick.data"
15 CONVERT_ALPHA = True
13 16
14 def __init__(self, resource_module, language=None): 17 def __init__(self, resource_module, language=None):
15 self.resource_module = resource_module 18 self.resource_module = resource_module
16 self.language = language 19 self.language = language
20 self._image_cache = {}
17 21
18 def get_resource_path(self, resource_name): 22 def get_resource_path(self, *resource_path_fragments):
23 resource_name = os.path.join(*resource_path_fragments)
19 for path in self.get_paths(resource_name): 24 for path in self.get_paths(resource_name):
20 if os.path.exists(path): 25 if os.path.exists(path):
21 return path 26 return path
22 raise ResourceNotFound(resource_name) 27 raise ResourceNotFound(resource_name)
23 28
27 if self.language: 32 if self.language:
28 fn = os.path.join(self.language, resource_path) 33 fn = os.path.join(self.language, resource_path)
29 paths.append(resource_filename(module, fn)) 34 paths.append(resource_filename(module, fn))
30 paths.append(resource_filename(module, resource_path)) 35 paths.append(resource_filename(module, resource_path))
31 return paths 36 return paths
37
38 def load_image(self, image_name):
39 image_path = self.get_resource_path('images', image_name)
40 if image_path not in self._image_cache:
41 image = pygame.image.load(image_path)
42 if self.CONVERT_ALPHA:
43 image = image.convert_alpha(pygame.display.get_surface())
44 self._image_cache[image_path] = image
45 return self._image_cache[image_path]