Made game harder, beeeeeches.
[naja.git] / naja / widgets / text.py
1 import pygame
2 import pygame.locals as pgl
3
4 from naja.constants import FONT, FONT_SIZE, EIGHT_BIT_SCALE, PALETTE, KEYS
5 from naja.resources import resources
6 from naja.resources.mutators import EIGHT_BIT, R180, blender
7 from naja.utils import convert_colour
8 from naja.widgets.base import Widget
9
10
11 MARKUP_MAP = {
12     'NORTH': ('glyphs/arrow_up.png', None),
13     'SOUTH': ('glyphs/arrow_down.png', None),
14     'EAST': ('glyphs/arrow_right.png', None),
15     'WEST': ('glyphs/arrow_left.png', None),
16     'HEALTH': ('glyphs/health.png', PALETTE.DARK_RED),
17     'WINTOKEN': ('glyphs/win.png', PALETTE.DARK_OLIVE),
18     'KEY': ('glyphs/key.png', None),
19     'MSB': ('glyphs/msb.png', None),
20     'RED': ('glyphs/key.png', PALETTE.ORANGE),
21     'GREEN': ('glyphs/key.png', PALETTE.GREEN),
22     'BLUE': ('glyphs/key.png', PALETTE.BLUE),
23     'CLOCKWISE': ('glyphs/clockwise.png', None),
24     'ANTICLOCKWISE': ('glyphs/anticlockwise.png', None),
25     'SHIFT_LEFT': ('glyphs/shift_left.png', None),
26     'SHIFT_RIGHT': ('glyphs/shift_right.png', None),
27     'COUNTDOWN': ('glyphs/countdown_4.png', PALETTE.DARK_VIOLET),
28
29     'HEALTH_NOCOLOUR': ('glyphs/health.png', None),
30     'WINTOKEN_NOCOLOUR': ('glyphs/win.png', None),
31 }
32
33
34 class Glyph(object):
35     def __init__(self, markup_text, glyph_keys, suffix=''):
36         self.markup_text = markup_text
37         self.glyph_keys = glyph_keys
38         self.text = ' ' * len(self.glyph_keys) + suffix
39
40
41 class TextWidget(Widget):
42
43     VIEW_PORT_DY = 50
44
45     def __init__(self, pos, text, fontname=None, fontsize=None,
46                  colour=None, unselectable_colour=None, view_port=None,
47                  centre=False, border=0, border_colour=PALETTE.GREY,
48                  padding=2):
49         super(TextWidget, self).__init__(pos)
50
51         self.text = text
52         self.fontname = fontname or FONT
53         self.fontsize = (fontsize or FONT_SIZE) // EIGHT_BIT_SCALE
54         self.colour = convert_colour(colour or PALETTE.BLACK)
55         if unselectable_colour is not None:
56             unselectable_colour = convert_colour(unselectable_colour)
57         self.unselectable_colour = unselectable_colour
58         self.view_port = (
59             pygame.Rect((0, 0), view_port) if view_port is not None else None)
60         self.centre = centre
61         self.centre_pos = pos
62         self.border = border
63         self.border_colour = convert_colour(border_colour)
64         self.padding = padding
65
66     def render_line(self, text):
67         colour = self.colour
68         if not self.is_selectable() and self.unselectable_colour is not None:
69             colour = self.unselectable_colour
70         text_surf = self.font.render(text, True, colour)
71         text_rect = text_surf.get_rect()
72         return pygame.transform.scale(
73             text_surf, (text_rect.width * EIGHT_BIT_SCALE,
74                         text_rect.height * EIGHT_BIT_SCALE))
75
76     def render_border(self, surface):
77         if not self.border or not self.border_colour:
78             return
79         rect = surface.get_rect()
80         rect = rect.inflate(- self.border / 2, - self.border / 2)
81         pygame.draw.rect(surface, self.border_colour, rect, self.border)
82
83     def update_size(self):
84         if self.view_port is not None:
85             self.size = self.view_port.size
86         else:
87             self.size = self.surface.get_rect().size
88         if self.centre:
89             self.pos = (self.centre_pos[0] - self.size[0] // 2,
90                         self.centre_pos[1])
91
92     def prepare(self):
93         self.font = resources.get_font(self.fontname, self.fontsize)
94         self.surface = self.render_line(self.text)
95         self.render_border(self.surface)
96         self.update_size()
97
98     def handle_event(self, ev):
99         if self.view_port is None:
100             return super(TextWidget, self).handle_event(ev)
101         if ev.type == pgl.KEYDOWN:
102             if ev.key in KEYS.DOWN:
103                 self.view_port.move_ip(0, self.VIEW_PORT_DY)
104                 if self.view_port.bottom > self.surface.get_rect().bottom:
105                     self.view_port.bottom = self.surface.get_rect().bottom
106                 return True
107             elif ev.key in KEYS.UP:
108                 self.view_port.move_ip(0, -self.VIEW_PORT_DY)
109                 if self.view_port.top < 0:
110                     self.view_port.top = 0
111                 return True
112         return super(TextWidget, self).handle_event(ev)
113
114     def draw(self, surface):
115         if self.view_port is None:
116             rect = self.rect
117             area = None
118         else:
119             rect = self.pos
120             area = self.view_port
121         surface.blit(self.surface, rect, area)
122         if self.view_port is not None:
123             self.draw_arrows(surface)
124
125     def draw_arrows(self, surface):
126         if self.view_port.top > 0:
127             up = resources.get_image('bits', 'arrow_on.png',
128                                      transforms=(EIGHT_BIT,))
129             icon_size = up.get_rect().height
130             pos = (self.pos[0] + self.view_port.width - icon_size, self.pos[1])
131             surface.blit(up, pos)
132         if self.view_port.bottom < self.surface.get_rect().bottom:
133             down = resources.get_image('bits', 'arrow_on.png',
134                                        transforms=(R180, EIGHT_BIT))
135             icon_size = down.get_rect().height
136             pos = (self.pos[0] + self.view_port.width - icon_size,
137                    self.pos[1] + self.view_port.height - icon_size)
138             surface.blit(down, pos)
139
140
141 class TextBoxWidget(TextWidget):
142     def __init__(self, *args, **kwargs):
143         self.bg_colour = convert_colour(kwargs.pop('bg_colour',
144                                                    PALETTE.LIGHT_VIOLET))
145         self.box_width = kwargs.pop('box_width', 0)
146         self.full_width = kwargs.pop('full_width', True)
147         kwargs.setdefault('padding', 4)
148
149         super(TextBoxWidget, self).__init__(*args, **kwargs)
150
151     def lines(self, image_map):
152         if self.box_width != 0:
153             return self._wrapped_lines(image_map)
154         else:
155             return self.text.splitlines()
156
157     def _prepare_glyph(self, image_map, glyph, current_words, lines):
158         size = self.font.size(' '.join(current_words[:-1] + ['']))
159         x = size[0] * EIGHT_BIT_SCALE + self.padding
160         y = size[1] * lines * EIGHT_BIT_SCALE + self.padding
161         for glyph_key in glyph.glyph_keys:
162             image_name, colour = MARKUP_MAP[glyph_key]
163             if colour is None:
164                 colour = self.colour
165             image = resources.get_image(
166                 image_name, transforms=(EIGHT_BIT, blender(colour)))
167             image_map[(x, y)] = image
168             x += image.get_width()
169
170     def _check_markup(self, word):
171         suffix = ''
172         if word[-1] in '.,':
173             suffix = word[-1]
174             word = word[:-1]
175
176         if not word:
177             return None
178         if word[0] == '{' and word[-1] == '}':
179             subwords = word[1:-1].split(',')
180             if all(subword in MARKUP_MAP for subword in subwords):
181                 return Glyph(word + suffix, subwords, suffix)
182
183         return None
184
185     def _wrapped_lines(self, image_map):
186         def words_fit(words):
187             words_line = ' '.join(words)
188             width = self.font.size(words_line)[0] * EIGHT_BIT_SCALE
189             if width < self.box_width:
190                 return True
191             elif len(words) == 1:
192                 Exception("Word %r too long for box." % (words[0],))
193             return False
194
195         line_count = 0
196         for line in self.text.splitlines():
197             line = line.strip()
198             if not line:
199                 line_count += 1
200                 yield line
201                 continue
202             current_words = []
203             remaining_words = line.split()
204             while remaining_words:
205                 word = remaining_words.pop(0)
206                 glyph = self._check_markup(word)
207                 if glyph is not None:
208                     word = glyph.text
209                 current_words.append(word)
210                 if words_fit(current_words):
211                     if glyph is not None:
212                         self._prepare_glyph(
213                             image_map, glyph, current_words, line_count)
214                 else:
215                     line_count += 1
216                     yield ' '.join(current_words[:-1])
217                     current_words = []
218                     if glyph is not None:
219                         word = glyph.markup_text
220                     remaining_words.insert(0, word)
221             if current_words and words_fit(current_words):
222                 line_count += 1
223                 yield ' '.join(current_words)
224
225     def prepare(self):
226         self.font = resources.get_font(self.fontname, self.fontsize)
227         image_map = {}
228         rendered_lines = []
229         width, height = self.padding * 2, self.padding * 2
230         for line in self.lines(image_map):
231             line_surface = self.render_line(line)
232             line_rect = line_surface.get_rect()
233             rendered_lines.append(line_surface)
234             width = max(width, line_rect.width + self.padding * 2)
235             height += line_rect.height
236
237         if self.full_width:
238             width = max(width, self.box_width)
239
240         self.surface = pygame.surface.Surface((width, height),
241                                               pygame.locals.SRCALPHA)
242         self.surface.fill(self.bg_colour)
243         self.update_size()
244
245         x, y = self.padding, self.padding
246         for line_surface in rendered_lines:
247             if self.centre:
248                 x = (width - line_surface.get_rect().width) / 2
249                 x += self.padding
250             self.surface.blit(line_surface, (x, y))
251             y += line_surface.get_rect().height
252         for pos, img in image_map.items():
253             self.surface.blit(img, pos)
254
255         self.render_border(self.surface)