-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanagram-render.py
1503 lines (1274 loc) · 48.3 KB
/
anagram-render.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pygame
from pygame.color import Color
from pygame.font import Font
from pygame.locals import (
K_LEFT, K_RIGHT, K_UP, K_DOWN,
K_SPACE, K_RETURN,
KEYDOWN, KEYUP,
Rect, SRCALPHA, QUIT,
)
from pygame.sprite import Sprite
from pygame.surface import Surface
from pygame.time import Clock
from collections import Counter
from dataclasses import dataclass
from difflib import Match, SequenceMatcher
import hashlib
import numpy as np
import numpy.typing as npt
import os
import shutil
import textwrap
from typing import (
Any, Callable, Generator, get_args, Literal, NamedTuple, Optional, Sequence
)
# Text alignment
Alignment = Literal["L", "R", "C"]
# Modes for rendering video
RenderModeID = Literal["kf_vid", "vid", "vid_loop"]
KEYFRAME_VIDEO, SINGLE_VIDEO, LOOPED_VIDEO = get_args(RenderModeID)
# GUI value with label
@dataclass
class LabelledValue:
id: str
label: str
value: Any | Callable[..., Any]
# Set of dimensions, for different aspect ratios
class Dimension(NamedTuple):
name: Optional[str]
width: int
height: int
# Rendering mode
class RenderMode(NamedTuple):
label: str
id: RenderModeID
# Type hints from Pygame (I could not figure out how to import them)
_RgbaOutput = tuple[int, int, int, int]
_ColorValue = (
Color | int | str | tuple[int, int, int] | list[int] | _RgbaOutput
)
ROOT_DIR = os.path.realpath(os.path.dirname(__file__))
BLACK = (0, 0, 0)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TAN = (236, 231, 201)
BROWN = (110, 69, 47)
DARK_GREEN = (32, 40, 32)
LINE_SPACING = -2
def normalize_phrase(s: str) -> str:
"""
Modify a string into a normalized version with capital letters,
spaces, and newlines.
Parameters
----------
s : str
String to normalize.
Returns
-------
str
Normalized string.
"""
return "\n".join(
" ".join(
"".join(
c.upper()
for c in word if c.isalpha()
)
for word in line.split()
)
for line in s.strip().split("\n")
)
def is_anagram(x: str, y: str) -> bool:
"""
Check whether two strings are anagrams.
Parameters
----------
x : str
First phrase.
y : str
Second phrase.
Returns
-------
bool
True if `x` and `y` are anagrams.
"""
return Counter(
c.upper() for c in x if c.isalpha()
) == Counter(
c.upper() for c in y if c.isalpha()
)
# Algorithm from Chrobak et al. (2004)
# https://kam.mff.cuni.cz/~kolman/papers/mcsp.pdf
# There is an algorithm from He (2007) that is reportedly faster, but
# the speed difference isn't too noticeable from limited testing
# https://link.springer.com/chapter/10.1007/978-3-540-72031-7_40
def partition_anagram(s: str, t: str) -> tuple[list[str], list[str]]:
"""
Find a ("near") minimum common substring partition of two anagrams.
The Minimum Common Substring Partition problem (MCSP) is the problem
of finding a partition of two strings which are anagrams, such that
the parts of one can be reordered into the parts of the other. This
problem is known to be NP-hard to solve optimally. A greedy
algorithm is used here instead which runs in polynomial time.
Note that while the greedy algorithm does not necessarily find the
best solution, and has a bad worst-case approximation factor, in
practice it finds decent solutions for English anagrams.
Parameters
----------
s : str
Source string.
t : str
Target string.
Returns
-------
tuple of (list of str, list of str)
Two lists of strings which give the original strings when
joined, and which can be rearranged to match each other.
"""
assert is_anagram(s, t)
# Both strings will use only uppercase letters and newlines
s = "".join(c.upper() for c in s if c.isalpha() or c == "\n")
t = "".join(c.upper() for c in t if c.isalpha() or c == "\n")
# Newlines serve as pre-existing markers to avoid overlap between lines
s_unmarked = set(i for i, c in enumerate(s) if c != "\n")
t_unmarked = set(i for i, c in enumerate(t) if c != "\n")
# Partition tables map indices to substrings
s_partition: dict[int, str] = {}
t_partition: dict[int, str] = {}
# Helper function to get unmarked substrings and their indices
def get_unmarked_substrings(
x: str,
x_unmarked: set[int]
) -> dict[int, str]:
x_strings: dict[int, str] = {}
partial = ""
index = 0
for i, c in enumerate(x):
if i in x_unmarked:
partial += c
else:
if partial:
x_strings[index] = partial
partial = ""
index = i + 1
if partial:
x_strings[index] = partial
return x_strings
# While there are unmarked symbols in S or T
while s_unmarked or t_unmarked:
# Get all unmarked substrings from S and T
s_strings = get_unmarked_substrings(s, s_unmarked)
t_strings = get_unmarked_substrings(t, t_unmarked)
# Find the longest common substring over all pairs of substrings
lcs = Match(0, 0, 0)
lcs_string = ""
for i, ss in s_strings.items():
for j, st in t_strings.items():
# Skip if both strings are shorter than LCS
if len(ss) < lcs.size or len(st) < lcs.size:
continue
match = SequenceMatcher(None, ss, st).find_longest_match()
if match.size > lcs.size:
lcs_string = ss[match.a:match.a + match.size]
lcs = Match(i + match.a, j + match.b, match.size)
# Add substring to partitions
s_partition[lcs.a] = lcs_string
t_partition[lcs.b] = lcs_string
# Mark symbols of substring in S and T
for i in range(lcs.size):
s_unmarked.remove(lcs.a + i)
t_unmarked.remove(lcs.b + i)
# Return partitions as a tuple of lists of strings
return (
list(dict(sorted(s_partition.items())).values()),
list(dict(sorted(t_partition.items())).values())
)
def create_font(fonts: str | Sequence[str], *args: Any, **kwargs: Any) -> Font:
"""
Create a `pygame.font.Font` object, choosing the first available
font from a list of fonts.
Parameters
----------
fonts : str or array-like of str
List of fonts (or a single font) to try creating.
*args
These parameters will be passed to the `pygame.font.Font`
constructor.
**kwargs
These parameters will be passed to the `pygame.font.Font`
constructor.
"""
if isinstance(fonts, str):
fonts = [fonts]
available = pygame.font.get_fonts()
choices = map(lambda s: s.lower().replace(" ", ""), fonts)
for choice in choices:
if choice in available:
return pygame.font.SysFont(choice, *args, **kwargs)
return pygame.font.Font(None, *args, **kwargs)
def word_wrap_text(
surface: Surface,
text: str,
color: _ColorValue,
rect: Rect | tuple[float, float, float, float] | list[float],
font: Font,
anti_alias: bool = False,
bg_color: Optional[_ColorValue] = None,
align: Alignment = "L"
) -> tuple[str, int]:
"""
Render some text onto a certain area of a surface, wrapping words
automatically.
Parameters
----------
surface : pygame.Surface
Surface to render text onto.
text : str
Text to render.
color : pygame.color.Color
Color to render text with.
rect : pygame.rect.Rect
Area to render text in on `surface`.
font : pygame.font.Font
Font to render text with.
anti_alias : bool, default False
If true, apply anti-aliasing.
bg_color : pygame.color.Color, optional
Background color to render text with.
align : str, default "L"
Alignment of text (any of "L", "R", or "C").
Returns
-------
tuple of (str, int)
Text that was not rendered, and Y-value of the line after the
last.
"""
_rect = Rect(rect)
y = _rect.top
font_height = font.size("Tg")[1]
while text:
i = 1
# If this row is outside our area, quit
if y + font_height > _rect.bottom:
break
# Determine maximum width of line
while font.size(text[:i])[0] < _rect.width and i < len(text):
if text[i - 1] == "\n":
break
i += 1
j = i
# If we're not past the end of the line
if i < len(text):
# Find end of last word
j = i - 1
while not text[j].isspace() and j >= 0:
j -= 1
# Adjust wrap to end of last word if found
if j > 0:
i = j
j += 1
else:
j = i
# Render the line
if bg_color:
image = font.render(text[:i], True, color, bg_color)
image.set_colorkey(bg_color)
else:
image = font.render(text[:i], anti_alias, color)
match align:
case "L": # left-align
x = _rect.left
case "R": # right-align
x = _rect.right - image.get_width()
case "C": # center-align
x = _rect.centerx - image.get_width() // 2
case _: # just in case
x = _rect.left
# Blit the line to the surface
surface.blit(image, (x, y))
y += font_height + LINE_SPACING
text = text[j:]
return text, y
class Tile(Sprite):
LETTER_HEIGHT_TO_TILE_SIDE = 7.2 / 12.5
# *4 to make the border radius more visible; remove for realistic value
BORDER_RADIUS_TO_TILE_SIDE = .3 / 12.5 * 4
LETTER_HEIGHT_TO_FONT_SIZE = 16 / 12
FONT_SIZE_TO_TILE_SIDE = (
LETTER_HEIGHT_TO_FONT_SIZE * LETTER_HEIGHT_TO_TILE_SIDE
)
ANIM_SMOOTHNESS = 2.75
Z_FACTOR = 1 / 3.75
def __init__(
self,
letter: str,
side: int | float,
x: int | float,
y: int | float,
):
"""
Create a Bananagrams-style letter tile sprite.
Parameters
----------
letter : str
Letter displayed on the tile.
side : int or float
Side length of the tile in pixels.
x : int or float
X position of the tile.
y : int or float
Y position of the tile.
"""
super(Tile, self).__init__()
assert letter
assert letter[0].isalpha()
self.letter = letter[0].upper()
self.side = int(side)
self.font = create_font(
"Arial",
int(self.side * self.FONT_SIZE_TO_TILE_SIDE)
)
# Image for rendering the tile
self.render_image = Surface((self.side, self.side), flags=SRCALPHA)
# Image used for blitting the tile to the screen
self.image = Surface((self.side, self.side), flags=SRCALPHA)
self.rect: Rect = self.image.get_rect()
# Source position
self.pos: tuple[int | float, int | float] = (x, y)
# Destination position
self.dest: tuple[int | float, int | float] = (x, y)
# Is the tile following a path to the destination?
self.following_path = False
# Progress along path, from 0 to 1
self.path_t: float = 0
# Path progress delta
self.path_dt = 0.05
# Is the tile moving up or down?
self.going_up = False
# "Height" of the tile (used to scale image)
self.z: float = 0
self.rect.center = (int(x), int(y))
self.draw()
def update(self, *args: Any, **kwargs: Any):
x: int | float
y: int | float
x, y = self.pos
# If this tile is following a path
if self.following_path:
dx, dy = self.dest
# If path progress is non-negative
if self.path_t >= 0:
# This tile will follow some cubic Bezier curve
# with control points related to its source and destination
# Calculate how much the path should arc upwards
# (the greater the X distance, the greater the arc)
pdy = abs(x - dx) / 1.5
# If the arc height is greater than the Y distance
if pdy > abs(y - dy):
max_pdy = 3 * self.side
# Cap arc height to maximum allowed arc height,
# but only if it's still greater than the Y distance
if pdy > max_pdy > abs(y - dy):
pdy = max_pdy
# Arc goes down by default; switch direction if necessary
if self.going_up:
pdy *= -1
# The Y inflection point is the Y plus the arc height
py = y + pdy
# If the Y distance is not less than the arc height
else:
# The Y inflection point is halfway between the Y values
py = (y + dy) / 2
# Create control points of Bezier curve
P0: npt.NDArray[np.float32] = np.array( # type: ignore
[x, y], dtype=np.float32
)
P1: npt.NDArray[np.float32] = np.array( # type: ignore
[x, py], dtype=np.float32
)
P2: npt.NDArray[np.float32] = np.array( # type: ignore
[dx, py], dtype=np.float32
)
P3: npt.NDArray[np.float32] = np.array( # type: ignore
[dx, dy], dtype=np.float32
)
# Ease T value with polynomial curve (this works, trust me)
t = (
((2 * self.path_t) ** self.ANIM_SMOOTHNESS) / 2
if self.path_t < .5 else
1 - ((2 - 2 * self.path_t) ** self.ANIM_SMOOTHNESS) / 2
)
mt = 1 - t
# Calculate point along Bezier curve using the polynomial form
vector: npt.NDArray[np.float32] = (
mt ** 3 * P0
+ 3 * t * mt ** 2 * P1
+ 3 * t ** 2 * mt * P2
+ t ** 3 * P3
)
x, y = vector
# Set Z based on distance between our point and the destination
origin_vector: npt.NDArray[np.float32] = vector - P3
dist = np.sqrt(
origin_vector.dot(origin_vector) # type: ignore
) / self.side
self.z = t * mt * dist * self.Z_FACTOR
# Step path progress forward
self.path_t += self.path_dt
# If path is done
if self.path_t >= 1:
# Set position to the destination
x, y = dx, dy
self.pos = (x, y)
# Reset path variables
self.z = 0
self.following_path = False
self.path_t = 0
# Re-render sprite
self.draw()
# Set position of sprite
self.rect.center = (int(x), int(y))
def draw(self):
# Fill with transparency
self.render_image.fill((0, 0, 0, 0))
# Draw rectangle with tile color
pygame.draw.rect(
self.render_image,
TAN,
(0, 0, self.side, self.side),
border_radius=int(self.side * self.BORDER_RADIUS_TO_TILE_SIDE),
)
# Draw border around tile
pygame.draw.rect(
self.render_image,
BLACK,
(0, 0, self.side, self.side),
width=int(self.side * self.BORDER_RADIUS_TO_TILE_SIDE / 1.25),
border_radius=int(self.side * self.BORDER_RADIUS_TO_TILE_SIDE),
)
# Render letter
letter_surface = self.font.render(self.letter, True, BLACK)
letter_w, letter_h = letter_surface.get_size()
# Stretch letter horizontally
letter_surface = pygame.transform.smoothscale(
letter_surface,
(letter_w * 1.25, letter_h)
)
# Blit letter to center of image
letter_rect = letter_surface.get_rect()
letter_rect.center = (self.side // 2, self.side // 2)
self.render_image.blit(letter_surface, letter_rect)
self.image = self.render_image
# If tile is following path, scale it by Z
if self.following_path:
if self.path_t >= 0:
self.image = pygame.transform.smoothscale(
self.render_image,
(self.side * (1 + self.z), self.side * (1 + self.z)),
)
class Game:
FPS = 30
TILE_GAP_TO_TILE_SIDE = 1 / 15
TILE_SPACE_TO_TILE_SIDE = 1 / 2
OPTIONS_WIDTH_PROPORTION = 1.0
LABELS_WIDTH_PROPORTION = 0.6
DIMENSIONS = [
Dimension("1:1", 1080, 1080),
Dimension("9:16", 1080, 1920),
Dimension("16:9", 1920, 1080),
]
RENDER_NAME_FORMATS: dict[RenderModeID, str] = {
KEYFRAME_VIDEO: "{hash}_{kf}",
SINGLE_VIDEO: "{hash}_full",
LOOPED_VIDEO: "{hash}_loop",
}
def __init__(self, anagrams: list[list[str]]):
"""
Create a GUI for an anagram animation renderer.
Parameters
----------
anagrams : list of list of str
List of anagrams to load into renderer, each of which are
represented as lists of phrases which are anagrams.
"""
pygame.init()
self.RENDER_MODES = [
RenderMode("Keyframes + videos", KEYFRAME_VIDEO),
RenderMode("Single video (start to end)", SINGLE_VIDEO),
RenderMode("Single video (loop)", LOOPED_VIDEO),
]
# Listed options and properties
# (this isn't really the best way to do this)
self.OPTIONS: list[LabelledValue] = [
LabelledValue("ana", "Anagram", lambda: self.anagrams_i + 1),
LabelledValue("tpl", "Tiles per line", lambda: self.line_width),
LabelledValue("pad", "Padding", lambda: self.side_padding),
LabelledValue("len", "Animation length (seconds)", lambda: (
self.anim_length
)),
LabelledValue("pau", "Animation pause (seconds)", lambda: (
self.anim_pause
)),
LabelledValue("rat", "Aspect ratio", lambda: (
self.DIMENSIONS[self.dimension_i].name
)),
LabelledValue("mod", "Render mode", lambda: (
self.RENDER_MODES[self.render_mode_i].label
)),
]
self.PROPERTIES: list[LabelledValue] = [
LabelledValue("rdd", "Rendered", lambda: (
"Yes"
if any(
os.path.isfile(os.path.join(
self.VIDEOS, fmt.format(
hash=self.get_phrases_hash(),
kf=0
) + ".mp4"
))
for fmt in self.RENDER_NAME_FORMATS.values()
)
else "No"
)),
LabelledValue("rdn", "Rendering", lambda: (
"Yes" if self.rendering else "No"
)),
LabelledValue("fps", "FPS", lambda: round(self.clock.get_fps(), 3)),
]
# List of anagrams passed into game
self.anagrams: list[list[str]] = anagrams
self.texts_i: int = 0
# Option values
self.anagrams_i: int = 0
self.option_i: int = 0
self.dimension_i: int = 0
self.render_mode_i: int = 0
self.anim_length: float = 2.0
self.anim_pause: float = 3.0
self.side_padding: int = 4
# Set initial window dimensions
self.set_window_dimensions()
# Load font
self.font_size: int = int(
min(self.WINDOW_WIDTH, self.WINDOW_HEIGHT) / 27
)
self.font: Font = create_font(
("Segoe UI", "Tahoma", "Lucida Grande", "Arial"),
self.font_size,
bold=True
)
# Clock for regulating FPS
self.clock: Clock = pygame.time.Clock()
# Title of game window
pygame.display.set_caption("Anagram Animator")
# Directories
self.FRAMES = os.path.join(ROOT_DIR, "frames")
self.KEYFRAMES = os.path.join(ROOT_DIR, "keyframes")
self.VIDEOS = os.path.join(ROOT_DIR, "videos")
# Keyboard states
self.keys_down: list[int] = []
self.keys_up: list[int] = []
self.keys_pressed: list[int] = []
def run(self) -> bool:
self.init()
# Main loop
while True:
# Update frame and draw
should_quit = self.update()
self.draw()
pygame.display.update()
# Tick one frame
if not self.rendering:
self.clock.tick(self.FPS)
if should_quit:
pygame.quit()
return False
# Set up keyboard state lists
prev_keys_down: list[int] = self.keys_down.copy()
self.keys_down.clear()
self.keys_up.clear()
self.keys_pressed.clear()
# Process Pygame events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return True
if event.type == KEYDOWN:
self.keys_down.append(event.key)
if event.key not in prev_keys_down:
self.keys_pressed.append(event.key)
if event.type == KEYUP:
self.keys_up.append(event.key)
def init(self):
# Set variables to be reset upon init
self.line_width = 0 # temp value; this is corrected
# Set up surfaces
self.render_surface = Surface(
(self.RENDER_WIDTH, self.RENDER_HEIGHT), flags=SRCALPHA
)
self.options_surface: Surface = Surface(
(self.OPTIONS_WIDTH, self.OPTIONS_HEIGHT), flags=SRCALPHA
)
# Set up animation
self.setup_animation()
self.rendering = False
self.animating = False
# Create tiles
self.texts_i = 0
self.tiles: list[Tile] = self.phrase_to_tiles(
self.get_nth_phrase(self.texts_i)
)
# Set up pseudo-coroutine
self.update_iter: Optional[Generator[Any, None, None]] = None
# Clear keyboard state
self.keys_down.clear()
self.keys_up.clear()
self.keys_pressed.clear()
def update(self) -> bool:
# If pseudo-coroutine is active, try stepping it forward
should_return: bool = False
if self.update_iter is not None:
try:
should_return = next(self.update_iter)
except StopIteration:
self.update_iter = None
return should_return
# Check whether LEFT and RIGHT were pressed
left_pressed = K_LEFT in self.keys_pressed
right_pressed = K_RIGHT in self.keys_pressed
should_setup = False
should_create_tiles = False
should_init = False
should_set_dims = False
# Handle updating for the current option (based on option ID)
match self.OPTIONS[self.option_i].id:
case "ana": # Anagram
if left_pressed:
self.anagrams_i -= 1
should_init = True
if right_pressed:
self.anagrams_i += 1
should_init = True
self.anagrams_i %= len(self.anagrams)
case "tpl": # Tiles per line
if left_pressed:
if self.line_width > self.MIN_LINE_WIDTH:
self.line_width -= 1
should_setup = True
should_create_tiles = True
if right_pressed:
if self.line_width < self.MAX_LINE_WIDTH:
self.line_width += 1
should_setup = True
should_create_tiles = True
case "pad": # Padding
if left_pressed:
if self.side_padding > 0:
self.side_padding -= 1
should_setup = True
should_create_tiles = True
if right_pressed:
if self.side_padding < 16:
self.side_padding += 1
should_setup = True
should_create_tiles = True
case "len": # Animation length (seconds)
if left_pressed:
if self.anim_length > 1:
self.anim_length -= 0.125
if right_pressed:
if self.anim_length < 3:
self.anim_length += 0.125
case "pau": # Animation pause (seconds)
if left_pressed:
if self.anim_pause > 1:
self.anim_pause -= 0.125
if right_pressed:
if self.anim_pause < 10:
self.anim_pause += 0.125
case "rat": # Aspect ratio
if left_pressed:
self.dimension_i -= 1
should_init = True
should_set_dims = True
if right_pressed:
self.dimension_i += 1
should_init = True
should_set_dims = True
self.dimension_i %= len(self.DIMENSIONS)
case "mod": # Render mode
if left_pressed:
self.render_mode_i -= 1
if right_pressed:
self.render_mode_i += 1
self.render_mode_i %= len(self.RENDER_MODES)
case _: # just in case
pass
# Call functions that need to be called after setting options
if should_set_dims:
self.set_window_dimensions()
if should_setup:
self.setup_animation()
if should_create_tiles:
self.tiles = self.phrase_to_tiles(
self.get_nth_phrase(self.texts_i)
)
if should_init:
self.init()
# UP and DOWN to change which option is selected
if K_UP in self.keys_pressed:
self.option_i = max(self.option_i - 1, 0)
if K_DOWN in self.keys_pressed:
self.option_i = min(self.option_i + 1, len(self.OPTIONS) - 1)
# SPACE to animate to next phrase
if K_SPACE in self.keys_pressed:
self.update_iter = iter(self.functional_animate())
# RETURN to render
if K_RETURN in self.keys_pressed:
self.update_iter = iter(self.functional_render(
self.RENDER_MODES[self.render_mode_i].id
))
return should_return
def render_tiles(self):
"""
Render tiles onto rendering surface.
"""
self.render_surface.fill(GREEN)
# Blit Z-sorted tiles
for tile in sorted(self.tiles, key=lambda s: s.z):
assert tile.image is not None
assert tile.rect is not None
self.render_surface.blit(tile.image, tile.rect)
def draw(self):
# Render to render surface
if not self.rendering:
self.render_tiles()
# Render to options surface
# Fill background
self.options_surface.fill(DARK_GREEN)
# Set some useful constants
padding = int(self.font_size / 2)
font_height = self.font.size("Tg")[1]
# Set some more useful constants
full_width = self.OPTIONS_WIDTH - padding * 2
labels_plus_values_width = full_width - padding
labels_width = int(
labels_plus_values_width * self.LABELS_WIDTH_PROPORTION
)
values_width = int(labels_plus_values_width - labels_width)
max_label_height = (font_height + LINE_SPACING) * 3 - LINE_SPACING
x, y = padding, padding
# Loop through each option
for i, option in enumerate(self.OPTIONS):
# Display the option's label
_, lty = word_wrap_text(
self.options_surface,
option.label,
WHITE if i == self.option_i else GRAY,
(x, y, labels_width, max_label_height),
self.font, True, align="R"
)
# Convert option's value to string
# (calling it as a function if necessary)
if isinstance(option.value, Callable):
value_str = str(option.value())
else:
value_str = str(option.value)
# Display the option's value
_, vty = word_wrap_text(
self.options_surface,
value_str,
WHITE,
(
x + labels_width + padding, y,
values_width, max_label_height
),
self.font, True, align="C"
)
# x, y = x, ty
x, y = x, max(lty, vty)
x, y = x, y + font_height + LINE_SPACING
# Loop through each property
for prop in self.PROPERTIES:
# Display the property's label
_, ty = word_wrap_text(
self.options_surface,
prop.label,
WHITE,
(x, y, labels_width, max_label_height),
self.font, True, align="R"
)
# Convert property's value to string
# (calling it as a function if necessary)
if isinstance(prop.value, Callable):
value_str = str(prop.value())
else:
value_str = str(prop.value)
# Display the property's value
word_wrap_text(
self.options_surface,
value_str,
WHITE,
(
x + labels_width + padding, y,
values_width, ty - y - LINE_SPACING
),
self.font, True, align="C"
)
x, y = x, ty
# Render some extra instructional text
x, y = x, y + font_height + LINE_SPACING
for line in (
"UP/DOWN to go through options",
"LEFT/RIGHT to change value",
"SPACE to preview animation",
"ENTER to render",
):
_, ty = word_wrap_text(
self.options_surface,
line,
WHITE, (x, y, full_width, max_label_height),
self.font, True
)
x, y = x, ty
# Render to window
# Blit scaled version of rendering surface
self.surface.blit(
pygame.transform.smoothscale(
self.render_surface, (self.PREVIEW_WIDTH, self.PREVIEW_HEIGHT)
),
(0, 0)
)
# Blit options surface
self.surface.blit(self.options_surface, (self.PREVIEW_WIDTH, 0))
def functional_animate(self) -> Generator[Any, None, None]:
# Set up animation
self.setup_animation()
self.animating = True