#!/usr/bin/env python3
"""Render Chess's flat pieces to assets/chess/pieces/*.png.
The pieces are drawn here as SVG in a 100 x 100 box, in the app's palette:
ivory pieces outlined in earth brown, pine pieces with sky-blue details, and
the light orange accent only on the king's cross and the queen's top jewel.
Pass --preview FILE to also write one image of every piece on board squares.
"""
from pathlib import Path
import argparse
import io
import cairosvg
from PIL import Image
ROOT = Path(__file__).resolve().parent.parent
OUTPUT = ROOT / 'assets/chess/pieces'
SIZE = 160
COLORS = {
'white': {'fill': '#f6f1e7', 'edge': '#6e4c36', 'detail': '#6e4c36'},
'black': {'fill': '#1e4a40', 'edge': '#10302a', 'detail': '#a8c8d2'},
}
ACCENT = '#f2a65e'
SHADOW = ''
BASE = ''
# Each piece: body shapes (filled and outlined), then detail lines.
PIECES = {
'pawn': [
'',
'',
'',
BASE,
],
'rook': [
'',
'',
'',
BASE,
'',
],
'knight': [
'',
BASE,
'',
'',
'',
],
'bishop': [
'',
'',
'',
'',
BASE,
'',
],
'queen': [
'',
'',
'',
'',
'',
'',
'',
'',
BASE,
],
'king': [
'',
'',
'',
'',
BASE,
'',
],
}
def svg(color, kind):
palette = COLORS[color]
style = (
f'.body{{fill:{palette["fill"]};stroke:{palette["edge"]};stroke-width:3;stroke-linejoin:round}}'
f'.detail{{fill:none;stroke:{palette["detail"]};stroke-width:2.4;stroke-linecap:round}}'
f'.eye{{fill:{palette["detail"]}}}'
f'.accent{{fill:{ACCENT};stroke:{palette["edge"]};stroke-width:2.4;stroke-linejoin:round}}'
)
shapes = ''.join(PIECES[kind])
return (f'')
def render(color, kind):
data = cairosvg.svg2png(bytestring=svg(color, kind).encode(), output_width=SIZE, output_height=SIZE)
image = Image.open(io.BytesIO(data))
image.load()
return image
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--preview')
arguments = parser.parse_args()
OUTPUT.mkdir(parents=True, exist_ok=True)
rendered = {}
for color in COLORS:
for kind in PIECES:
image = render(color, kind)
rendered[(color, kind)] = image
# Fixed PNG settings keep repeated renders byte-identical.
image.save(OUTPUT / f'{color}-{kind}.png', optimize=True)
if arguments.preview:
cell = SIZE
sheet = Image.new('RGBA', (cell * 6, cell * 2), '#dde9e5')
for row, color in enumerate(COLORS):
for column, kind in enumerate(PIECES):
square = '#dde9e5' if (row + column) % 2 == 0 else '#7fa69a'
tile = Image.new('RGBA', (cell, cell), square)
tile.alpha_composite(rendered[(color, kind)])
sheet.paste(tile, (column * cell, row * cell))
sheet.save(arguments.preview)
if __name__ == '__main__':
main()