Skip to content

Commit 81f2bc2

Browse files
committed
Cleanup sprite font script
1 parent ec3072e commit 81f2bc2

File tree

1 file changed

+37
-27
lines changed

1 file changed

+37
-27
lines changed

sprite_font.py

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,53 @@
11
"""Generate entity sprite text images."""
22
from pathlib import Path
3+
import sys
34

45
from PIL import Image, ImageChops
5-
from collections import namedtuple
6+
import attrs
67

7-
import sys
88

9-
try:
10-
text = sys.argv[1]
11-
except IndexError:
12-
text = input('Enter text to produce: ')
9+
@attrs.frozen
10+
class Char:
11+
"""A character."""
12+
img: Image.Image
13+
width: int
14+
1315

14-
golden = text.startswith("comp_")
15-
print('Gold' if golden else 'White', 'text selected')
16+
def main() -> None:
17+
"""Generate text."""
18+
try:
19+
text = sys.argv[1]
20+
except IndexError:
21+
text = input('Enter text to produce, prefix with GOLD to make it gold: ')
1622

17-
Char = namedtuple('Char', 'img width')
23+
golden = text.startswith("comp_")
24+
if text.startswith('GOLD'):
25+
golden = True
26+
text = text.removeprefix('GOLD').lstrip()
27+
print('Gold' if golden else 'White', 'text selected')
1828

19-
LETTERS = {}
29+
LETTERS: dict[str, Char] = {}
2030

21-
for file in Path('text').glob('*.png'):
22-
letter = file.name[0]
23-
img = Image.open(file)
24-
img.load()
25-
if golden:
26-
img = ImageChops.multiply(img, Image.new('RGBA', img.size, (224, 174, 0, 255)))
27-
LETTERS[letter] = Char(img, img.width-1)
31+
for file in Path('text').glob('*.png'):
32+
letter = file.name[0]
33+
img = Image.open(file)
34+
img.load()
35+
if golden:
36+
img = ImageChops.multiply(img, Image.new('RGBA', img.size, (224, 174, 0, 255)))
37+
LETTERS[letter] = Char(img, img.width-1)
2838

29-
chars = list(map(LETTERS.__getitem__, text.lower()))
39+
chars = [LETTERS[x] for x in text.lower()]
3040

31-
width = sum(c.width for c in chars) + 1
32-
height = max(c.img.height for c in chars)
41+
width = sum(c.width for c in chars) + 1
42+
height = max(c.img.height for c in chars)
3343

34-
img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
44+
img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
3545

36-
offset = 0
37-
for ch in chars:
38-
img.alpha_composite(ch.img, (offset, 0))
39-
offset += ch.width
46+
offset = 0
47+
for ch in chars:
48+
img.alpha_composite(ch.img, (offset, 0))
49+
offset += ch.width
4050

41-
img.save(text + '.png')
51+
img.save(f'{text}.png')
4252

43-
print('Done!')
53+
print('Done!')

0 commit comments

Comments
 (0)