6be4469ecf8b404fc8032cb3f2bddb8dcacf0250
[tabakrolletjie.git] / tabakrolletjie / utils.py
1 """ Tabakutilities. """
2
3 import functools
4 import time
5 import pygame.surface
6 import pygame.locals as pgl
7
8 from .constants import DEBUG
9 from .loader import loader
10
11
12 def debug_timer(label, debug=False):
13     """ A decorator for printing how long a function took if debug is true.
14     """
15     def debug_inner(f):
16         @functools.wraps(f)
17         def wrapper(*args, **kw):
18             start_time = time.time()
19             try:
20                 return f(*args, **kw)
21             finally:
22                 duration = time.time() - start_time
23                 if DEBUG or debug:
24                     print "%s [%g seconds]" % (label, duration)
25         return wrapper
26     return debug_inner
27
28
29 class DetailedTimer(object):
30     """ A detailed timer for overly complex functions.
31     """
32     def __init__(self, title, debug=False):
33         if DEBUG or debug:
34             self.title = title
35             self.times = []
36         else:
37             # fast funtions with the correct signature
38             self.start = int
39             self.show = str
40             self.lap = str
41             self.end = int
42
43     def start(self):
44         print "---- %s ----" % self.title
45         self.times.append(time.time())
46
47     def lap(self, label):
48         now = time.time()
49         print "  %s: %s" % (label, now - self.times[-1])
50         self.times.append(now)
51
52     def show(self, text):
53         print "  %s" % text
54
55     def end(self):
56         print "  %s: %s" % ("total", time.time() - self.times[0])
57         print "---- ----"
58
59
60 def shadowed_text(text, font_name, size, offset=4):
61     font_black = loader.load_font(font_name, size=size)
62     font_white = loader.load_font(font_name, size=size)
63     background = font_black.render(text, True, (0, 0, 0))
64     foreground = font_white.render(text, True, (255, 255, 255))
65     new_size = (background.get_width() + offset,
66                 background.get_height() + offset)
67     base = pygame.surface.Surface(new_size, pgl.SWSURFACE).convert_alpha()
68     base.fill((0, 0, 0, 0))
69     base.blit(background, (offset, offset), None)
70     base.blit(foreground, (0, 0), None)
71     return base