Image loading
[tabakrolletjie.git] / tabakrolletjie / loader.py
1 """ Utilities for loading resource files. """
2
3 import json
4 import os
5
6 import pygame.image
7 import pygame.display
8
9
10 class Loader(object):
11     """ Load data files from beneath a prefix. """
12
13     def __init__(self, prefix):
14         self._prefix = prefix
15         self._cache = {}
16
17     def full_path(self, *parts):
18         path = "/".join(parts)
19         rel_path = os.path.join(*path.split("/"))
20         abs_path = os.path.join(self._prefix, rel_path)
21         print abs_path
22         return abs_path
23
24     def open_file(self, *parts):
25         return file(self.full_path(*parts), "rb")
26
27     def load_station(self, *parts):
28         with self.open_file("stations", *parts) as f:
29             return json.load(f)
30
31     def load_image(self, *parts):
32         """Return a pygame surface of the requested image."""
33         fn = self.full_path("images", *parts)
34         img = self._cache.get(fn, None)
35         if img is None:
36             img = pygame.image.load(fn)
37             # We assume pygame.display has been initialised
38             # Fix this if that changes
39             img.convert_alpha(pygame.display.get_surface())
40             self._cache[fn] = img
41         return img
42
43
44 _DATA_PREFIX = os.path.abspath(
45     os.path.join(os.path.dirname(__file__), "..", "data"))
46
47 loader = Loader(_DATA_PREFIX)