view mamba/data.py @ 8:66ae99f6903e

First stab at tile/level stuff.
author Jeremy Thurgood <firxen@gmail.com>
date Sun, 11 Sep 2011 12:50:55 +0200
parents 08941f788c15
children b48c47af7801
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.

Note that pyglet users should probably just add the data directory to the
pyglet.resource search path.
'''

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.
    '''
    filename = os.path.join(filename.split('/'))
    return os.path.join(data_dir, filename)


def load_file(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 = {}


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