Source

pymissile / resource.py

import pygame

from constants import WHITE, BLACK

_fonts = {}

_font_cache = {}

def render_cached(font=None, text=' ', color=WHITE, drop_shadow=True):
  if not font: 
    font = 'small'
  
  if not _fonts:
    _fonts['big'] = pygame.font.Font('m40.TTF', 36)
    _fonts['small'] = pygame.font.Font('m40.TTF', 18)
  
  font = _fonts[font]
  
  key = (font, text, color)
  if not key in _font_cache:
    tmp = font.render(text, True, color)
    
    offset = 2 if drop_shadow else 0
    
    surf = pygame.surface.Surface((tmp.get_width() + offset, tmp.get_height() + offset))
    
    surf.set_colorkey((0,0,0))
    
    if drop_shadow:
      shadow = font.render(text, True, (1,1,1))
      surf.blit(shadow, (offset, offset))
    surf.blit(tmp, (0, 0))

    try: 
      surf.set_alpha(color[3])
    except IndexError: pass
    
    _font_cache[key] = surf
  return _font_cache[key]