view mamba/data.py @ 256:9827ce469834

Add more validation exceptions to new map loading code. Handle trying to load when display hasn't been initiliased better
author Neil Muller <drnlmuller@gmail.com>
date Thu, 15 Sep 2011 01:34:42 +0200
parents cd5377697c9e
children 49c125e8bc2a
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 = {}
MUTATED_IMAGES = {}


def load_image(filename, mutators=()):
    if not pygame.display.get_init():
        # Just check image exists
        testfile = open(filepath(filename), 'rb')
        testfile.close()
        return None
    key = (filename, mutators)
    if key in MUTATED_IMAGES:
        return MUTATED_IMAGES[key]
    if filename in IMAGES:
        image = IMAGES[filename]
    else:
        image = pygame.image.load(filepath(filename))
        image = image.convert_alpha(pygame.display.get_surface())
        IMAGES[filename] = image
    for mutator in mutators:
        image = mutator(image)
    MUTATED_IMAGES[key] = image
    return image


def load_tile_image(image_name, tileset='common', mutators=()):
    filename = "tiles/%s/%s.png" % (tileset, image_name)
    return load_image(filename, mutators)


def check_tileset_legal(tileset):
    return os.path.isdir(os.path.join(data_dir, 'tiles', tileset))


def check_level_exists(level):
    return os.path.isfile(os.path.join(data_dir, 'levels', '%s.txt' % level))