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