Source

jelly / jelly / resource.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pkgutil
import tempfile
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

import pygame


TILE_CACHE = {}
FONT_CACHE = {}


def load_tiles(filename, width, height):
    try:
        return TILE_CACHE[filename, width, height]
    except KeyError:
        image = load_image(filename)
        image_width, image_height = image.get_size()
        tiles = []
        for x in range(image_width/width):
            for y in range(image_height/height):
                rect = (x * width, y * height, width, height)
                tiles.append(image.subsurface(rect))
        TILE_CACHE[filename, width, height] = tiles
    return tiles


def load_image(filename):
    f = StringIO.StringIO(pkgutil.get_data('jelly', filename))
    return pygame.image.load(f, filename).convert()


def load_font(filename, size=8):
    try:
        return FONT_CACHE[filename, size]
    except KeyError:
        # XXX the "right" way causes segmentation fault
        # f = StringIO.StringIO(pkgutil.get_data('jelly', filename))
        with tempfile.NamedTemporaryFile() as f:
            data = pkgutil.get_data('jelly', filename)
            f.write(data)
            f.seek(0)
            print f.name

            font = pygame.font.Font(f.name, size)
        FONT_CACHE[filename, size] = font
    return font