added pausing to night and moved reset tool after other tools
[tabakrolletjie.git] / tabakrolletjie / widgets.py
1 # Simple widgets
2 # This just unifies some logic.
3 # There is no implied container / window system (yet)
4
5 import pygame.locals as pgl
6
7 from .loader import loader
8 from .constants import FONTS
9 from .transforms import NullTransform
10
11
12 class Button(object):
13
14     def __init__(self, size, name=None, pos=None, padding=10):
15         self._size = size
16         self._padding = padding
17         self.position = pos
18         self.name = name
19
20     @property
21     def position(self):
22         return self._pos
23
24     @position.setter
25     def position(self, pos):
26         self._pos = pos
27         if pos is not None:
28             self._min_x = pos[0] - self._padding
29             self._max_x = pos[0] + self._size[0] + self._padding
30             self._min_y = pos[1] - self._padding
31             self._max_y = pos[1] + self._size[1] + self._padding
32
33     def get_width(self):
34         return self._size[0]
35
36     def get_height(self):
37         return self._size[1]
38
39     def render(self, surface):
40         pass
41
42     def pressed(self, ev):
43         if self._pos is None:
44             # Unplaced buttons can't be pressed
45             return False
46         if ev.type == pgl.MOUSEBUTTONDOWN and ev.button == 1:
47             if self._min_x < ev.pos[0] < self._max_x:
48                 if self._min_y < ev.pos[1] < self._max_y:
49                     return True
50         return False
51
52
53 class TextButton(Button):
54
55     def __init__(self, text, colour, name=None, pos=None, padding=10):
56         font = loader.load_font(FONTS['sans'], size=24)
57         self._text = font.render(text, True, colour)
58         super(TextButton, self).__init__(self._text.get_size(), name,
59                                          pos, padding)
60
61     def render(self, surface):
62         surface.blit(self._text, self._pos, None)
63
64
65 class ImageButton(Button):
66
67     def __init__(self, *imgparts, **kwargs):
68         transform = kwargs.pop("transform", NullTransform())
69         self._img = kwargs.pop("image", None)
70         if self._img is None:
71             self._img = loader.load_image(*imgparts, transform=transform)
72         name = kwargs.get('name')
73         pos = kwargs.get('pos')
74         padding = kwargs.get('padding', 0)
75         super(ImageButton, self).__init__(self._img.get_size(), name,
76                                           pos, padding)
77
78     def update_image(self, *imgparts, **kwargs):
79         transform = kwargs.pop("transform", NullTransform())
80         self._img = loader.load_image(*imgparts, transform=transform)
81         
82     def render(self, surface):
83         surface.blit(self._img, self._pos, None)