See the code (map.py)
"""Day 10 · Prompting only — A world of little wonders.
Run: python days/10-prompting-only/map.py
Builds a standalone, offline-capable map.html from country geometry, the
editorial creature catalogue and original SVG pixel art. No paid APIs or keys.
The existing build.py embeds it in the Day 10 page and copies the CSV download.
"""
from __future__ import annotations
import csv
import html
import json
import sys
from pathlib import Path
from urllib.request import urlretrieve
from pyproj import Transformer
from shapely.geometry import shape
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from wildlife_art import sprite_defs, sprite_ids
from roaming import RouteBuilder
from portraits import portrait_defs
SPRITE_IDS = sprite_ids(json.loads((HERE / "creatures.json").read_text()))
GEOMETRY_URL = 'https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_50m_admin_0_countries.geojson'
PROJECTION = Transformer.from_crs('EPSG:4326', 'EPSG:8857', always_xy=True)
XMAX, YMAX = 17243959.06221695, 8392927.59846645
def project(lon: float, lat: float) -> tuple[float, float]:
"""Equal Earth projection, fitted to the atlas's 1600 × 900 drawing space."""
x, y = PROJECTION.transform(lon, lat)
return (800 + x / XMAX * 748, 450 - y / YMAX * 412)
def load_creatures() -> list[dict]:
records = json.loads((HERE / 'creatures.json').read_text())
ids = set()
for record in records:
if record['id'] in ids or record['sprite'] not in SPRITE_IDS:
raise ValueError(f'Invalid creature: {record}')
ids.add(record['id'])
conservation_path = HERE / 'conservation.json'
conservation = json.loads(conservation_path.read_text()) if conservation_path.exists() else {}
photos_path=HERE / 'photos.json'
photos=json.loads(photos_path.read_text()) if photos_path.exists() else {}
for record in records:
record['photo']=photos.get(record['sprite'])
record['conservation'] = conservation.get(record['sprite'], {
'category': None, 'label': 'Not applicable' if record['kind'] == 'myth' else 'Not verified',
'verified': False})
if sum(r['scope'] == 'country' for r in records) != 195:
raise ValueError('The country catalogue must include all 195 UN members and observers.')
return records
def line_path(points, close=False):
coords = [project(*p[:2]) for p in points]
return 'M' + 'L'.join(f'{x:.2f},{y:.2f}' for x, y in coords) + ('Z' if close else '')
def country_paths():
cache = HERE / 'data' / 'countries.geojson'
if not cache.exists():
cache.parent.mkdir(exist_ok=True)
print('Downloading public-domain Natural Earth country boundaries…')
urlretrieve(GEOMETRY_URL, cache)
data = json.loads(cache.read_text())
fills = {'Africa':'#e8c69a','Asia':'#d7dba5','Europe':'#dcc9ac',
'North America':'#c9d4a3','South America':'#c5d1aa',
'Oceania':'#e5c392','Antarctica':'#f6f3df','Seven seas (open ocean)':'#d7dac0'}
result = []
areas = {}
for feature in data['features']:
p = feature['properties']
geom = shape(feature['geometry']).simplify(.045, preserve_topology=True)
polys = list(geom.geoms) if geom.geom_type == 'MultiPolygon' else [geom]
path = ''.join(line_path(poly.exterior.coords, True) + ''.join(line_path(r.coords, True) for r in poly.interiors) for poly in polys)
iso = p.get('ADM0_A3', p.get('SOV_A3', ''))
areas[iso] = geom.area
name = html.escape(p.get('ADMIN', ''), quote=True)
result.append(f'<path class="country" data-country="{html.escape(iso)}" aria-label="{name}" d="{path}" fill="{fills.get(p.get("CONTINENT"), "#d9d5b3")}"/>')
return ''.join(result), areas
def build_map(output: Path = HERE / 'map.html'):
records = load_creatures()
land, areas = country_paths()
routes = RouteBuilder(json.loads((HERE / 'data' / 'countries.geojson').read_text()))
outline = line_path([(180, n) for n in range(90, -91, -2)] + [(-180, n) for n in range(-90, 91, 2)], True)
graticules = ''.join(f'<path d="{line_path([(lon,lat) for lon in range(-180,181,3)])}"/>' for lat in range(-60, 61, 30))
graticules += ''.join(f'<path d="{line_path([(lon,lat) for lat in range(-90,91,3)])}"/>' for lon in range(-150, 180, 30))
special = ['CHN','AUS','BRA','CAN','USA','RUS','IND','GBR','KEN','ZAF','ATA','ARC','GRL','JPN','BTN','IRL','NZL','IDN','PER','MEX','EGY','WLS','SCT']
markers = []
marker_data = []
for i, r in enumerate(records):
x, y = project(r['lon'], r['lat'])
priority = 10000 - special.index(r['id']) * 20 if r['id'] in special else areas.get(r['id'], 0)
route = routes.route_for(r, x, y)
x, y = route['points'][0]
rr = {**r, 'x':x, 'y':y, 'priority':priority, 'route':route['points'], 'roamZone':route['zone']}
marker_data.append(rr)
label = html.escape(f'{r["name"]} · {r["creature"]}', quote=True)
motion = r.get('motion', 'walk')
star_visibility = '' if r["kind"] == "myth" else 'display="none"'
markers.append(f'<g class="resident" data-creature="{r["id"]}" tabindex="0" role="img" aria-label="{label}" transform="translate({x:.3f} {y:.3f})" style="--delay:-{i%23*.37:.2f}s;--duration:{2.4+i%7*.21:.2f}s"><title>{label}</title><ellipse class="shadow" cx="0" cy="12" rx="11" ry="2.7"/><g class="trail trail-{motion}" aria-hidden="true"><path d="M-16 10q-5 4-10 0m12 5q-5 4-10 0"/><ellipse cx="-13" cy="13" rx="2" ry="1"/><ellipse cx="-19" cy="10" rx="2" ry="1"/></g><g class="critter {motion}"><g class="facing"><use href="#sprite-{r["sprite"]}" x="-20" y="-24" width="40" height="40"/></g></g><circle class="myth-star" cx="15" cy="-17" r="2" {star_visibility}/><rect class="hit" x="-20" y="-25" width="40" height="43" rx="10"/></g>')
countries = sum(r['scope'] == 'country' for r in records)
text = (HERE / 'atlas.html').read_text().replace('@@SCRIPT@@', (HERE / 'atlas.js').read_text())
for token, value in {'SPRITES':sprite_defs(records)+portrait_defs(), 'LAND':land, 'OUTLINE':outline,
'GRATICULES':graticules, 'MARKERS':''.join(markers),
'CATALOGUE':json.dumps(marker_data, ensure_ascii=False).replace('</','<\\/'),
'COUNTRY_COUNT':str(countries), 'CREATURE_COUNT':str(len(records))}.items():
text = text.replace('@@' + token + '@@', value)
output.write_text(text, encoding='utf-8')
if output.resolve() == (HERE / 'map.html').resolve():
exported = []
for r in records:
status = r['conservation']
row = {k:v for k,v in r.items() if k not in {'conservation','photo'}}
row.update(iucnCategory=status.get('category') or '', iucnLabel=status.get('label','Not verified'),
iucnSource=status.get('sourceURL',''), iucnProvider=status.get('provider',''),
iucnCheckedDate=status.get('checkedDate',''))
exported.append(row)
fields = list(dict.fromkeys(k for row in exported for k in row))
with (HERE / 'creatures.csv').open('w',newline='',encoding='utf-8') as f:
writer=csv.DictWriter(f,fieldnames=fields,lineterminator='\n');writer.writeheader();writer.writerows(exported)
return output
if __name__ == '__main__':
print('Saved', build_map())