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