guildhall/tools/build_icons.py

40 lines
1.5 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""Build static/icons.svg: one SVG sprite with every glyph the game uses.
The glyphs are from game-icons.net (CC BY 3.0, see README), fetched through
the Iconify API. Run this after adding a glyph name in game.py; the sprite is
committed, so the game itself never fetches anything at runtime.
python3 tools/build_icons.py
"""
import json
import sys
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
import game # noqa: E402
names = sorted(game.all_glyphs())
url = "https://api.iconify.design/game-icons.json?icons=" + ",".join(names)
request = urllib.request.Request(url, headers={"User-Agent": "guildhall-icon-builder"})
with urllib.request.urlopen(request, timeout=30) as response:
data = json.load(response)
if data.get("not_found"):
sys.exit(f"Not on game-icons.net: {', '.join(data['not_found'])}")
size = data.get("width", 512)
symbols = []
for name in names:
icon = data["icons"][name]
width, height = icon.get("width", size), icon.get("height", data.get("height", size))
symbols.append(f'<symbol id="{name}" viewBox="0 0 {width} {height}">{icon["body"]}</symbol>')
sprite = ('<svg xmlns="http://www.w3.org/2000/svg">\n'
'<!-- Icons from game-icons.net by Lorc, Delapouite and contributors, CC BY 3.0 -->\n'
+ "\n".join(symbols) + "\n</svg>\n")
(ROOT / "static" / "icons.svg").write_text(sprite)
print(f"Wrote {len(names)} glyphs to static/icons.svg ({len(sprite) // 1024} KiB)")