Add simple save method
[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 import os
8 import sys
9 import json
10
11 from .constants import DEBUG
12 from .loader import loader
13
14
15 def debug_timer(label, debug=False):
16     """ A decorator for printing how long a function took if debug is true.
17     """
18     def debug_inner(f):
19         @functools.wraps(f)
20         def wrapper(*args, **kw):
21             start_time = time.time()
22             try:
23                 return f(*args, **kw)
24             finally:
25                 duration = time.time() - start_time
26                 if DEBUG or debug:
27                     print "%s [%g seconds]" % (label, duration)
28         return wrapper
29     return debug_inner
30
31
32 class DetailedTimer(object):
33     """ A detailed timer for overly complex functions.
34     """
35     def __init__(self, title, debug=False):
36         if DEBUG or debug:
37             self.title = title
38             self.times = []
39         else:
40             # fast funtions with the correct signature
41             self.start = int
42             self.show = str
43             self.lap = str
44             self.end = int
45
46     def start(self):
47         print "---- %s ----" % self.title
48         self.times.append(time.time())
49
50     def lap(self, label):
51         now = time.time()
52         print "  %s: %s" % (label, now - self.times[-1])
53         self.times.append(now)
54
55     def show(self, text):
56         print "  %s" % text
57
58     def end(self):
59         print "  %s: %s" % ("total", time.time() - self.times[0])
60         print "---- ----"
61
62
63 def shadowed_text(text, font_name, size, offset=4):
64     font_black = loader.load_font(font_name, size=size)
65     font_white = loader.load_font(font_name, size=size)
66     background = font_black.render(text, True, (0, 0, 0))
67     foreground = font_white.render(text, True, (255, 255, 255))
68     new_size = (background.get_width() + offset,
69                 background.get_height() + offset)
70     base = pygame.surface.Surface(new_size, pgl.SWSURFACE).convert_alpha()
71     base.fill((0, 0, 0, 0))
72     base.blit(background, (offset, offset), None)
73     base.blit(foreground, (0, 0), None)
74     return base
75
76
77 def save_location():
78     """Return the directory for the save location."""
79     app = "tabakrolletjie"
80     if sys.platform.startswith('win'):
81         if 'APPDATA' in os.environ:
82             return os.path.join(os.environ['APPDATA'], app)
83         return os.path.join(os.path.expanduser('~'), '.' + app)
84     elif 'XDG_DATA_HOME' in os.environ:
85         return os.path.join(os.environ['XDG_DATA_HOME'], app)
86     return os.path.join(os.path.expanduser('~'), '.local', 'share', app)
87
88
89 def get_save_file_name():
90     return os.path.join(save_location(), 'savegame.json')
91
92
93 def save_file_exists():
94     savefile = get_save_file_name()
95     return os.path.isfile(savefile)
96
97
98 def write_save_file(json_data):
99     save_dir = save_location()
100     if not os.path.exists(save_dir):
101         os.makedirs(save_dir)
102     savefile = get_save_file_name()
103     with open(savefile, 'wb') as f:
104         json.dump(json_data, f, indent=3)