1 '''Simple data loader module.
3 Loads data files from the "data" directory shipped with a game.
5 Enhancing this to handle caching etc. is left as an exercise for the reader.
7 Note that pyglet users should probably just add the data directory to the
8 pyglet.resource search path.
12 from kivy.core.image import ImageLoader
13 from kivy.core.audio import SoundLoader
14 from kivy.cache import Cache
16 data_py = os.path.abspath(os.path.dirname(__file__))
17 data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
18 imageloader = ImageLoader()
19 soundloader = SoundLoader()
20 Cache.register('bane', limit=200)
23 def filepath(filename):
24 '''Determine the path to a file in the data directory.
26 filename = os.path.join(*filename.split('/'))
27 return os.path.join(data_dir, filename)
30 def load(filename, mode='rb'):
31 '''Open a file in the data directory.
33 "mode" is passed as the second arg to open().
35 return open(filepath(filename), mode)
38 def _cache_load(filename, loader):
39 '''Load an object either from disk or from the cache.
41 We rely on kivy's caching infrastructure'''
42 path = filepath(filename)
43 obj = Cache.get('bane', path)
45 obj = loader.load(path)
46 Cache.append('bane', path, obj)
50 def load_image(filename):
51 return _cache_load(filename, imageloader)
54 def load_sound(filename):
55 return _cache_load(filename, soundloader)