import pygame
from collections import namedtuple
from enum import Enum, auto
from math import inf
DEFAULT_WINDOW_TO_SCREEN_RATIO = 0.8
assert 0.0 < DEFAULT_WINDOW_TO_SCREEN_RATIO < 1.0
DEFAULT_WINDOW_MINIMUM_SIZE = (128, 128)
assert DEFAULT_WINDOW_MINIMUM_SIZE[0] > 0
assert DEFAULT_WINDOW_MINIMUM_SIZE[1] > 0
DEFAULT_SPASH_TEXT_FRACTION = 0.95
assert 0.5 <= DEFAULT_SPASH_TEXT_FRACTION < 1.0
class Justification(Enum):
CENTER = auto()
LEFT = auto()
FULL = auto()
class ParagraphShape(namedtuple('ParagraphShape', ('maximum_width', 'justification', 'indentation', 'hanging_indentation'))):
@property
def first_line_maximum_width(self):
return self.maximum_width - self.indentation
@property
def other_line_maximum_width(self):
return self.maximum_width - self.hanging_indentation
ALL_ONE_LINE = ParagraphShape(inf, Justification.LEFT, 0, 0)
class Font:
def __init__(self, path, baseline_skip):
self.path = path
self.baseline_skip = baseline_skip
self._pygame_font = None
@property
def pygame_font(self):
if self._pygame_font is None:
for size in range(self.baseline_skip, 0, -1):
self._pygame_font = pygame.font.Font(self.path, size)
if self._pygame_font.size('Yy')[1] <= self.baseline_skip:
break
else:
raise ValueError(f'font file {self.path} does not support a baseline_skip as small as {self.baseline_skip}')
return self._pygame_font
def _penalize(self, words, maximum_width, is_last):
width, _ = self.pygame_font.size(' '.join(words))
if width > maximum_width:
return width * width
if is_last:
return 0
excess = maximum_width - width
return excess * excess
def _render_line(self, width, justification, indentation, words, foreground, background):
if justification is Justification.FULL:
assert width < inf
word_images = [self.pygame_font.render(word, True, foreground, background) for word in words]
spacing = width - indentation - sum(word_image.get_width() for word_image in word_images)
if len(word_images) > 1:
spacing /= len(word_images) - 1
result = pygame.Surface((width, self.baseline_skip))
result.fill(background)
x = 0
for word_image in word_images:
result.blit(word_image, (x, 0))
x += word_image.get_width() + spacing
return result
unformatted = self.pygame_font.render(' '.join(words), True, foreground, background)
content_width = indentation + unformatted.get_width()
result_width = content_width if width == inf else width
shift = (result_width - content_width) // 2 if justification is Justification.CENTER else 0
result = pygame.Surface((result_width, self.baseline_skip))
result.fill(background)
result.blit(unformatted, (shift + indentation, 0))
return result
def _render_paragraph(self, paragraph, paragraph_shape, foreground, background):
words = paragraph.split()
final_line_justification = Justification.LEFT if paragraph_shape.justification is Justification.FULL else paragraph_shape.justification
if self.pygame_font.size(' '.join(words))[0] <= paragraph_shape.first_line_maximum_width:
return self._render_line(
paragraph_shape.maximum_width,
final_line_justification,
paragraph_shape.indentation,
words,
foreground,
background,
),
backpointers = [(0, None)]
while len(backpointers) <= len(words):
backpointers.append(min(
(prior_penalty + self._penalize(
words[start:len(backpointers)],
paragraph_shape.first_line_maximum_width if start == 0 else paragraph_shape.other_line_maximum_width,
len(backpointers) == len(words) and paragraph_shape.justification is not Justification.CENTER,
), start)
for (start, (prior_penalty, _)) in enumerate(backpointers)
))
results = []
index = len(words)
_, prior_index = backpointers[index]
assert prior_index
results.append(self._render_line(
paragraph_shape.maximum_width,
final_line_justification,
paragraph_shape.hanging_indentation,
words[prior_index:index],
foreground,
background,
))
index = prior_index
while index > 0:
_, prior_index = backpointers[index]
results.append(self._render_line(
paragraph_shape.maximum_width,
paragraph_shape.justification,
paragraph_shape.indentation if prior_index == 0 else paragraph_shape.hanging_indentation,
words[prior_index:index],
foreground,
background,
))
index = prior_index
results.reverse()
return results
def render(self, text, *, paragraph_shape=ALL_ONE_LINE, foreground=(255, 255, 255), background=(0, 0, 0)):
return tuple(
image
for paragraph in (text.split('\n') if isinstance(text, str) else text)
for image in self._render_paragraph(paragraph, paragraph_shape, foreground, background)
)
screen = None
def initialize(*, resolution=None, fullscreen=False,
splash_background=(0, 0, 0), splash_image_path=None,
splash_text=None, splash_font=None, splash_text_color=(255, 255, 255),
splash_text_maximum_width=inf, splash_indentation=0, splash_hanging_indentation=0):
global screen
if screen:
raise ValueError('PyGame UI already initialized')
if splash_text and not splash_font:
raise ValueError('cannot render splash text without a splash font')
pygame.init()
display_info = pygame.display.Info()
if fullscreen:
if resolution is None:
resolution = (display_info.current_w, display_info.current_h)
screen = pygame.display.set_mode(resolution, pygame.FULLSCREEN)
else:
if resolution is None:
resolution = (
round(DEFAULT_WINDOW_TO_SCREEN_RATIO * display_info.current_w),
round(DEFAULT_WINDOW_TO_SCREEN_RATIO * display_info.current_h),
)
else:
resolution = (
min(max(resolution[0], DEFAULT_WINDOW_MINIMUM_SIZE[0]), display_info.current_w),
min(max(resolution[1], DEFAULT_WINDOW_MINIMUM_SIZE[1]), display_info.current_h),
)
screen = pygame.display.set_mode(resolution)
screen.fill(splash_background)
if splash_text:
rendered_splash_text = splash_font.render(
splash_text,
paragraph_shape=ParagraphShape(
min(DEFAULT_SPASH_TEXT_FRACTION * resolution[0], splash_text_maximum_width),
Justification.CENTER,
splash_indentation,
splash_hanging_indentation,
),
foreground=splash_text_color,
background=splash_background,
)
else:
rendered_splash_text = []
y = (resolution[1] - sum(line_image.get_height() for line_image in rendered_splash_text)) // 2
if splash_image_path:
splash_image = pygame.image.load(splash_image_path).convert_alpha()
x = (resolution[0] - splash_image.get_width()) // 2
y -= splash_image.get_height() // 2
screen.blit(splash_image, (x, y))
y += splash_image.get_height()
if rendered_splash_text:
x = (resolution[0] - rendered_splash_text[0].get_width()) // 2
for line_image in rendered_splash_text:
screen.blit(line_image, (x, y))
y += line_image.get_height()
pygame.display.flip()