view nagslang/data.py @ 32:0e49648f8d74

Arbitrary function condition.
author Jeremy Thurgood <firxen@gmail.com>
date Sun, 01 Sep 2013 16:39:13 +0200
parents b0644173d0aa
children
line wrap: on
line source

'''Simple data loader module.

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

import os

import pygame

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


def filepath(filename):
    '''Determine the path to a file in the data directory.
    '''
    # Allow using / as separator in filenames
    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(os.path.join(data_dir, filename), mode)


IMAGES = {}
MUTATED_IMAGES = {}


def load_image(filename, mutators=()):
    if filename not in IMAGES:
        image = pygame.image.load(filepath(filename))
        image = image.convert_alpha(pygame.display.get_surface())
        IMAGES[filename] = image

    key = (filename, mutators)
    if key not in MUTATED_IMAGES:
        image = IMAGES[filename]
        for mutator in mutators:
            image = mutator(image)
        MUTATED_IMAGES[key] = image

    return MUTATED_IMAGES[key]