Hide loader path print behind debug
[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 from .constants import DEBUG
10
11
12 class Loader(object):
13     """ Load data files from beneath a prefix. """
14
15     def __init__(self, prefix):
16         self._prefix = prefix
17         self._cache = {}
18
19     def full_path(self, *parts):
20         path = "/".join(parts)
21         rel_path = os.path.join(*path.split("/"))
22         abs_path = os.path.join(self._prefix, rel_path)
23         if DEBUG:
24             print abs_path
25         return abs_path
26
27     def open_file(self, *parts):
28         return file(self.full_path(*parts), "rb")
29
30     def load_station(self, *parts):
31         with self.open_file("stations", *parts) as f:
32             return json.load(f)
33
34     def load_image(self, *parts):
35         """Return a pygame surface of the requested image."""
36         fn = self.full_path("images", *parts)
37         img = self._cache.get(fn, None)
38         if img is None:
39             img = pygame.image.load(fn)
40             # We assume pygame.display has been initialised
41             # Fix this if that changes
42             img.convert_alpha(pygame.display.get_surface())
43             self._cache[fn] = img
44         return img
45
46
47 _DATA_PREFIX = os.path.abspath(
48     os.path.join(os.path.dirname(__file__), "..", "data"))
49
50 loader = Loader(_DATA_PREFIX)