view gamelib/data.py @ 154:ae6dff8ff88c

Cache loaded images
author Neil Muller <drnlmuller@gmail.com>
date Fri, 11 May 2012 20:32:50 +0200
parents 53277724645b
children
line wrap: on
line source

'''Simple data loader module.

Loads data files from the "data" directory shipped with a game.

Enhancing this to handle caching etc. is left as an exercise for the reader.
'''

import os

from pygame import image


data_py = os.path.abspath(os.path.dirname(__file__))
data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
IMAGE_CACHE = {}


def filepath(filename):
    '''Determine the path to a file in the data directory.
    '''
    filename = os.path.join(*filename.split('/'))
    return os.path.join(data_dir, filename)


def load(filename, mode='rb'):
    '''Open a file in the data directory.

    "mode" is passed as the second arg to open().
    '''
    return open(filepath(filename), mode)


def load_image(filename):
    if filename in IMAGE_CACHE:
        return IMAGE_CACHE[filename]
    else:
        im = image.load(filepath(filename))
        IMAGE_CACHE[filename] = im
        return im