Advertisement
nux95

PyGame Font Rendering Engine - Very Very Simple

Jan 9th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.46 KB | None | 0 0
  1. # coding: utf-8
  2.  
  3. import pygame
  4. import argparse
  5.  
  6. def rint(x):
  7.     if x % 1 >= 0.5:
  8.         x += 1
  9.     return int(x)
  10.  
  11. text = """Hello,
  12.  
  13. Welcome to may world. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."""
  14.  
  15. class Node(object):
  16.  
  17.     width = 0
  18.     height = 0
  19.     margin_x = 0
  20.     margin_y = 0
  21.     x = 0
  22.     y = 0
  23.     background = None
  24.  
  25.     def get_real_size(self):
  26.         return self.width + self.margin_x * 2, self.height + self.margin_y * 2
  27.  
  28.     def add(self, node):
  29.         return False
  30.  
  31.     def layout(self):
  32.         pass
  33.  
  34.     def paint(self, rel_x, rel_y, screen):
  35.         x, y = self.x + self.margin_x + rel_x, self.y + self.margin_y + rel_y
  36.         w, h = self.width, self.height
  37.         if self.background:
  38.             screen.fill(self.background, pygame.Rect(x, y, w, h))
  39.  
  40. class ContainerNode(Node):
  41.  
  42.     def __init__(self):
  43.         super(ContainerNode, self).__init__()
  44.         self.nodes = []
  45.  
  46.     def layout(self):
  47.         for node in self.nodes:
  48.             node.layout()
  49.  
  50.     def paint(self, rel_x, rel_y, screen):
  51.         super(ContainerNode, self).paint(rel_x, rel_y, screen)
  52.         for node in self.nodes:
  53.             node.paint(rel_x + self.x, rel_y + self.y, screen)
  54.  
  55. class TextNode(Node):
  56.  
  57.     def __init__(self, word, color, font, antialias=True):
  58.         self.word = word
  59.         self.color = color
  60.         self.antialias = antialias
  61.         self.font = font
  62.  
  63.         self.width, self.height = font.size(word)
  64.         self.margin_x = font.size(' ')[0] / 2.0
  65.         self.margin_y = 2
  66.  
  67.     def add(self, node):
  68.         raise NotImplementedError
  69.  
  70.     def paint(self, rel_x, rel_y, screen):
  71.         super(TextNode, self).paint(rel_x, rel_y, screen)
  72.         rel_x += self.x + self.margin_x
  73.         rel_y += self.y + self.margin_y
  74.         label = self.font.render(self.word, self.antialias, self.color)
  75.         screen.blit(label, (rint(rel_x), rint(rel_y)))
  76.  
  77. class InlineNodeRow(ContainerNode):
  78.  
  79.     def __init__(self, maxwidth=None, justify='left'):
  80.         super(InlineNodeRow, self).__init__()
  81.         self.maxwidth = maxwidth
  82.         self.justify = justify
  83.  
  84.     def add(self, node):
  85.         w, h = node.get_real_size()
  86.         if self.maxwidth and self.width + w > self.maxwidth:
  87.             return False
  88.  
  89.         self.width += w
  90.         if h > self.height:
  91.             self.height = h
  92.  
  93.         self.nodes.append(node)
  94.         return True
  95.  
  96.     def layout(self):
  97.         if not self.nodes:
  98.             return
  99.  
  100.         justify = self.justify
  101.         if justify not in ['left', 'right', 'block', 'center']:
  102.             raise ValueError('invalid justify value %s' % justify)
  103.         if justify in ['right', 'center'] and not self.maxwidth:
  104.             raise RuntimeError('for %s justification, a maxwidth must have been set.' % justify)
  105.         if justify == 'block' and not self.maxwidth:
  106.             justify = 'left'
  107.  
  108.         if justify == 'center':
  109.             last_x = (self.maxwidth - self.width) * 0.5
  110.         else:
  111.             last_x = 0
  112.  
  113.         if justify == 'block':
  114.             free_space = self.maxwidth - self.width
  115.         else:
  116.             free_space = 0
  117.  
  118.         if len(self.nodes) > 1:
  119.             free_space_partial = float(free_space) / (len(self.nodes) - 1)
  120.         else:
  121.             free_space_partial = 0
  122.  
  123.         for node in self.nodes:
  124.             w, h = node.get_real_size()
  125.             node.x = last_x
  126.             last_x = last_x + w + free_space_partial
  127.  
  128.             if justify == 'right':
  129.                 node.x += (self.maxwidth - self.width)
  130.  
  131.             free_space_h = self.height - h
  132.             node.y = free_space_h * 0.5
  133.  
  134.         super(InlineNodeRow, self).layout()
  135.  
  136. class NodeBox(ContainerNode):
  137.  
  138.     def add(self, node):
  139.         w, h = node.get_real_size()
  140.         if self.width < w:
  141.             self.width = w
  142.         self.height += h
  143.         self.nodes.append(node)
  144.         return True
  145.  
  146.     def layout(self):
  147.         last_y = 0
  148.         for node in self.nodes:
  149.             w, h = node.get_real_size()
  150.             node.x = 0
  151.             node.y = last_y
  152.             last_y += h
  153.  
  154.         super(NodeBox, self).layout()
  155.  
  156.  
  157. def draw_text(screen, text, color, font, justify='left', maxwidth=None, x=0, y=0,
  158.               colorize=False):
  159.     lines = text.split('\n')
  160.     box = NodeBox()
  161.     if colorize:
  162.         box.background = (30, 100, 255)
  163.  
  164.     def make_row():
  165.         row = InlineNodeRow(maxwidth, justify=justify)
  166.         if colorize:
  167.             row.background = (255, 80, 50)
  168.         return row
  169.  
  170.     pushed_words = []
  171.     for line in lines:
  172.         words = line.split()
  173.         row = make_row()
  174.  
  175.         for word in words:
  176.             node = TextNode(word, color, font)
  177.             if colorize:
  178.                 node.background = (240, 190, 20)
  179.  
  180.             added = row.add(node)
  181.             if not added:
  182.                 box.add(row)
  183.                 row = make_row()
  184.                 row.add(node)
  185.  
  186.         if justify == 'block':
  187.             row.justify = 'left'
  188.         box.add(row)
  189.  
  190.     box.layout()
  191.     box.paint(x, y, screen)
  192.  
  193. def main():
  194.     parser = argparse.ArgumentParser()
  195.     parser.add_argument('justify', choices=['left', 'right', 'center', 'block'])
  196.     parser.add_argument('-c', '--colorize', action='store_true')
  197.     args = parser.parse_args()
  198.  
  199.     pygame.init()
  200.     pygame.font.init()
  201.  
  202.     screen = pygame.display.set_mode((600, 400))
  203.     pygame.display.set_caption('Font Drawing Test')
  204.  
  205.     font = pygame.font.SysFont("monospace", 15)
  206.     justify = args.justify
  207.  
  208.     clock = pygame.time.Clock()
  209.     running = True
  210.     while running:
  211.         clock.tick(10)
  212.         screen.fill((255, 255, 255))
  213.         draw_text(screen, text, (0, 0, 0), font, justify, maxwidth=600, colorize=args.colorize)
  214.  
  215.         for event in pygame.event.get():
  216.             if event.type == pygame.QUIT:
  217.                 running = False
  218.  
  219.         pygame.display.flip()
  220.  
  221. if __name__ == '__main__':
  222.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement