source: skaapsteker/data.py

Last change on this file was 343:2258c2a6dbae, checked in by Jeremy Thurgood <firxen@…>, 12 years ago

Cache get_files() stuff to avoid unnecessary filesystem operations.

File size: 1.3 KB
Line 
1'''Simple data loader module.
2
3Loads data files from the "data" directory shipped with a game.
4
5Enhancing this to handle caching etc. is left as an exercise for the reader.
6
7Note that pyglet users should probably just add the data directory to the
8pyglet.resource search path.
9'''
10
11import os
12
13import pygame.image
14import pygame.display
15
16
17data_py = os.path.abspath(os.path.dirname(__file__))
18data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
19
20
21def filepath(filename):
22 '''Determine the path to a file in the data directory.
23 '''
24 filename = os.path.join(*filename.split('/'))
25 return os.path.join(data_dir, filename)
26
27
28def load(filename, mode='rb'):
29 '''Open a file in the data directory.
30
31 "mode" is passed as the second arg to open().
32 '''
33 return open(filepath(filename), mode)
34
35
36DIR_LISTS = {}
37
38def get_files(folder):
39 """Return a sorted list of files in the given directory, with the directory stripped"""
40 if folder not in DIR_LISTS:
41 DIR_LISTS[folder] = sorted(os.listdir(filepath(folder)))
42 return DIR_LISTS[folder]
43
44
45IMAGES = {}
46
47def load_image(filename):
48 if filename not in IMAGES:
49 IMAGES[filename] = pygame.image.load(load(filename))
50 if pygame.display.get_init():
51 IMAGES[filename] = IMAGES[filename].convert_alpha(pygame.display.get_surface())
52 return IMAGES[filename]
53
Note: See TracBrowser for help on using the repository browser.