changeset 136:1e9599e48d7b

Simplistic text wrapping
author Stefano Rivera <stefano@rivera.za.net>
date Tue, 05 Apr 2011 00:50:42 +0200
parents ae90ef45115c
children 8a54d966a508
files skaapsteker/cutscene.py skaapsteker/widgets/text.py
diffstat 2 files changed, 33 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/skaapsteker/cutscene.py	Tue Apr 05 00:18:56 2011 +0200
+++ b/skaapsteker/cutscene.py	Tue Apr 05 00:50:42 2011 +0200
@@ -14,7 +14,7 @@
         self._game_state = game_state
         self.text = text
         self.text_widget = Text(text, pygame.Rect(20, 20, 800-40, 600-40),
-                                size=24)
+                                size=24, wrap=True)
         self.background = data.load_image('backgrounds/' + background)
         self.start_time = pygame.time.get_ticks()
         self.run_time = 60000 # ms
--- a/skaapsteker/widgets/text.py	Tue Apr 05 00:18:56 2011 +0200
+++ b/skaapsteker/widgets/text.py	Tue Apr 05 00:50:42 2011 +0200
@@ -37,7 +37,8 @@
 
 
 class Text(Widget):
-    def __init__(self, text, pos, font='sans', size=16, color='black'):
+    def __init__(self, text, pos, font='sans', size=16, color='black',
+                 wrap=False):
         self.text = text
         if isinstance(pos, pygame.Rect):
             self.rect = pos
@@ -45,12 +46,41 @@
             self.rect = pygame.Rect(pos, (0, 0))
         self.font = load_font(font, size)
         self.color = pygame.Color(color)
-        # TODO: Wrapping
+        if wrap:
+            if not isinstance(pos, pygame.Rect):
+                raise Exception("Cannot wrap without dimensions")
+            self._wrap()
+
         self.surfaces = [self.font.render(line, True, self.color)
                          for line in self.text.split('\n')]
         self.rect.width = max(line.get_width() for line in self.surfaces)
         self.rect.height = self.font.get_linesize() * len(self.surfaces)
 
+
+    def _wrap(self):
+        unwrapped = self.text.split('\n\n')
+        text = []
+        for paragraph in unwrapped:
+            paragraph = paragraph.replace('\n', ' ')
+            words = paragraph.split(' ')
+            nwords = len(words)
+            from_ = 0
+            to = 0
+            while to < nwords:
+                to += 1
+                line = ' '.join(words[from_:to])
+                if self.font.size(line)[0] <= self.rect.width:
+                    continue
+                if to - from_ > 1:
+                    to -= 1
+                text.append(' '.join(words[from_:to]))
+                from_ = to
+            text.append(' '.join(words[from_:to]))
+            text.append('')
+        if text:
+            text.pop(-1)
+        self.text = '\n'.join(text)
+
     def draw(self, surface):
         pos = self.rect
         for line in self.surfaces: