# -*- coding: utf-8 -*-
# *************** DEL 01 - WHAT THIS IS, AND WHAT IS LEFT TO DO *************
#
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH - code, comments, variable names,
# error messages.  The text the player reads comes from the language files
# (Helpfiles\Dino_World\Lang\<code>.txt, DEL 10); only English is built in.
#
# Dino_World (Swedish: "Dinovärlden") - a toy world for the youngest.
#
#   1. PICK A WORLD.  A castle with a moat, a forest with a cliff, a big island with palms, a
#      volcano with lava, a desert with quicksand.  The program makes the world up by itself
#      (a random number = "seed"), so every press on the same button gives another layout.
#   2. PUT OUT DINOSAURS.  Pick a dinosaur, tap the world.  The arrow button turns the
#      dinosaur left or right.  Tap a dinosaur to pick it up again (turn it, move it, remove it).
#   3. SAVE and/or RUN.  When you run, every dinosaur starts to walk (or fly, or swim) the way it
#      faces.  What happens on the way:
#         * a wall, a tree, a rock         -> it bumps into it, sees stars and STOPS
#         * the edge of a cliff            -> it falls FAST and is gone
#         * water, lava, quicksand         -> it sinks SLOWLY and is gone
#         * two dinosaurs meet             -> a cloud of dust, then both shoot up to the top and are gone
#         * a flying dinosaur              -> flies over everything and out of the picture
#      It ends when everybody is gone or has stopped.
#   4. (1.1) ROCKETS AND FIREWORKS.  Besides dinosaurs the player can put out
#         * a ROCKET - alone, or with any dinosaur sitting in its window.  When you run it shakes, smokes, and LIFTS OFF
#           and flies out of the top of the picture (a dinosaur on board goes with it).  A dinosaur that walks into a
#           rocket that has not left yet bumps into it like into a tree.
#         * FIREWORKS - a launcher that shoots three shells, each bursting in colours high in the picture while the
#           world goes a bit dark.
#      They live in the same list as the dinosaurs (types "rocket" and "fireworks", a rocket has "r" = the dinosaur
#      on board or ""), so saving, opening, dragging and removing work the same.  The phone app does NOT know them yet.
#
#   The same program exists as a tile in the Android app "Kids Games" (Kids_Android: dw_engine.js, dw.js).
#   Both make EXACTLY the same worlds and the same runs from the same numbers: tools\export_dino.py
#   records them from THIS file and tools\dw_check.js compares the app's engine with the recording.
#   A saved world (.json, DEL 16) is the same on the phone and here.
#
#   NOT A GAME IN THE SENSE OF 40_games.md: nobody to play against, nothing to win - so no AI
#   opponents, no scoring, no Full rules file.  Help, About, the language files and the Player
#   text popup are here.
#
# ============================================================================
# ToDo - WHAT COULD BE ADDED NEXT
# ============================================================================
#   ToDo - more dinosaurs (one line in DW_TYPES + one picture in the art, DEL 11), more worlds (one generator in DEL 05).
#   ToDo - sounds: a roar for every dinosaur (now only simple beeps, DEL 16).
#   ToDo - sending a world to the phone (the .json files are the same; copy by hand for now).
#   ToDo - the Components list of 40_games.md is not here (it is a toy, not a game); add it if Lars wants the counts anyway.
#
#   NEEDS Pillow (pip install pillow) for the pictures.  Command line:  --selftest [--nowindow] [--sheet picture.png]   --export-lang

import os
import re
import sys
import json
import math
import time
import queue
import random
import ctypes
import platform
import datetime
import threading
import tkinter as tk
import tkinter.font as tkfont

try:
    from PIL import Image, ImageDraw, ImageTk, ImageChops
    HAVE_PIL = True
except ImportError:          # the program says so and stops (DEL 18)
    HAVE_PIL = False

# *************** DEL 02 - PROGRAM HOME (WHERE MY DATA LIVES) *****************
def _find_home(start):
    """Walk up (at most 4 levels) to the first folder that contains Helpfiles."""
    d = start
    for _ in range(4):
        if os.path.isdir(os.path.join(d, "Helpfiles")):
            return d
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    # BOOTSTRAP: before Helpfiles exists the walk finds nothing, and returning
    # `start` would create Helpfiles as a CHILD of Py - every later run would
    # then find that wrong one first and never correct itself.  Py and
    # Folder-exe\<Name> are always direct children of the home, so their names
    # are enough to place the home correctly.
    if os.path.basename(start).lower() == "py":
        return os.path.dirname(start)
    up_one = os.path.dirname(start)
    if os.path.basename(up_one).lower() == "folder-exe":
        return os.path.dirname(up_one)
    return start


def _program_home():
    if getattr(sys, "frozen", False):
        return _find_home(os.path.dirname(os.path.abspath(sys.executable)))
    return _find_home(os.path.dirname(os.path.abspath(__file__)))


PROGRAM_HOME_AWARE = True   # Tower scans for this line

# Name of this program = name of the .py (or of the .exe when built).  It is
# also the name of the data folder and of the icon, and it is computed so that
# a renamed file can never go out of sync with them.
PROGRAM_NAME = os.path.splitext(os.path.basename(
    sys.executable if getattr(sys, "frozen", False)
    else os.path.abspath(__file__)))[0]

BASE_DIR       = _program_home()
HELPFILES_DIR  = os.path.join(BASE_DIR, "Helpfiles")
PROGRAM_HF_DIR = os.path.join(HELPFILES_DIR, PROGRAM_NAME)   # own data
LOG_DIR        = os.path.join(HELPFILES_DIR, "0---Empty")    # logs ONLY
ICON_DIR       = os.path.join(BASE_DIR, "Icons")             # <PROGRAM_NAME>.ico

# *************** DEL 03 - THE NUMBERS THE WHOLE PROGRAM RUNS ON *****************
# A world is a grid of cells, one letter per cell:
#   .  ground            s  sand / beach       b  bridge (walkable over water or a ravine)
#   w  water  (SINKS)    q  quicksand (SINKS)  l  lava (SINKS)      c  ravine / cliff drop (FALLS)
#   t  tree or cactus    p  palm               r  rock / boulder    # wall   T tower   K keep   V volcano
# "t p r # T K V" are SOLID: a walking dinosaur stops at them.
DW_VERSION = "1.1"
DW_SHAPES = {"P": (12, 18), "L": (18, 12)}          # portrait (phone held upright) and landscape (tablet, PC)
DW_THEMES = ["castle", "nature", "island", "volcano", "desert"]
DW_SOLID = "tprK#TV"
DW_SINK = {"c": 0.9, "w": 2.6, "q": 4.4, "l": 3.2}   # seconds from the first step into it until the dinosaur is gone
DW_DT = 1.0 / 30.0                                   # one step of the run (a "tick")
DW_POOF_TIME = 0.45                                  # seconds in the dust cloud before the dinosaurs shoot up
DW_MAX_TICKS = 30 * 150                              # a run is never longer than this (it ends long before)

# size = width of the picture in cells, speed = cells per second, kind = walk | fly | swim
DW_TYPES = {
    "trex":   {"kind": "walk", "size": 2.0, "speed": 1.5},
    "trike":  {"kind": "walk", "size": 1.9, "speed": 1.0},
    "stego":  {"kind": "walk", "size": 2.0, "speed": 0.75},
    "bronto": {"kind": "walk", "size": 2.6, "speed": 0.65},
    "anky":   {"kind": "walk", "size": 1.7, "speed": 0.6},
    "raptor": {"kind": "walk", "size": 1.5, "speed": 2.6},
    "para":   {"kind": "walk", "size": 1.9, "speed": 1.2},
    "ptero":  {"kind": "fly",  "size": 2.0, "speed": 2.2},
    "plesio": {"kind": "swim", "size": 1.9, "speed": 1.1},
    "baby":   {"kind": "walk", "size": 1.1, "speed": 1.7},
}
DW_TYPE_ORDER = ["trex", "trike", "stego", "bronto", "anky", "raptor", "para", "ptero", "plesio", "baby"]

# Things that are not dinosaurs (1.1).  size = width in cells, hh = height in cells (for picking them with the mouse).
DW_THINGS = {
    "rocket":    {"kind": "rocket", "size": 1.4, "hh": 2.7},
    "fireworks": {"kind": "fw", "size": 1.0, "hh": 1.0},
}
DW_ALL = dict(DW_TYPES)                       # every kind of put-out item: dinosaurs and things
DW_ALL.update(DW_THINGS)
DW_PUT_MODES = ("dino", "rocket", "rocketdino", "fw")     # what a click on the world puts out
DW_ROCKET_COUNT = 1.6                         # seconds from the start of the run until the first rocket lifts off
DW_ROCKET_STAGGER = 0.3                       # every further rocket waits this much longer
DW_ROCKET_ACC = 5.0                           # cells per second per second while it climbs
DW_ROCKET_SMOKE = 0.9                         # the engine lights this long before lift-off (flame, smoke, shaking)
DW_FW_START = 0.4                             # first launcher shoots after this many seconds; each further one 0.35 s later
DW_FW_STAGGER = 0.35
DW_FW_SHOOT = 0.65                            # seconds a shell takes up to its burst
DW_FW_BURST = 1.5                             # seconds a burst glows
DW_FW_ROUNDS = 3                              # shells per launcher
# (core, edge) colours of the bursts
DW_FW_COLORS = [("#fff3b0", "#ffb300"), ("#ffd6d6", "#ff3b3b"), ("#d6ebff", "#3b8bff"), ("#d9ffd6", "#2fc45f"),
                ("#ffd9f3", "#ff4fb8"), ("#eadcff", "#9b5cff")]


# *************** DEL 04 - THE RANDOM NUMBERS (mulberry32, the same in the app) *****************
class DwRng(object):
    """mulberry32: a 32-bit seed makes the same series in Python and in JavaScript."""

    def __init__(self, seed):
        self.a = int(seed) & 0xFFFFFFFF

    def next(self):
        self.a = (self.a + 0x6D2B79F5) & 0xFFFFFFFF
        a = self.a
        t = ((a ^ (a >> 15)) * (1 | a)) & 0xFFFFFFFF
        t = ((t + (((t ^ (t >> 7)) * (61 | t)) & 0xFFFFFFFF)) & 0xFFFFFFFF) ^ t
        return ((t ^ (t >> 14)) & 0xFFFFFFFF) / 4294967296.0

    def ri(self, n):
        return int(self.next() * n)


# *************** DEL 05 - MAKING A WORLD *****************
def dw_grid(cols, rows, ch):
    return [[ch] * cols for _ in range(rows)]


def dw_blob(g, cx, cy, rad, ch, only):
    """Cells whose centre is within rad of (cx, cy) become ch - but only where the cell now holds one of the letters in `only`."""
    rows, cols = len(g), len(g[0])
    r2 = rad * rad
    for y in range(rows):
        for x in range(cols):
            dx = x + 0.5 - cx
            dy = y + 0.5 - cy
            if dx * dx + dy * dy <= r2 and g[y][x] in only:
                g[y][x] = ch


def dw_scatter(g, r, n, ch, only):
    rows, cols = len(g), len(g[0])
    for _ in range(n):
        x = r.ri(cols)
        y = r.ri(rows)
        if g[y][x] in only:
            g[y][x] = ch


def dw_border(g, side_ch, top_ch):
    rows, cols = len(g), len(g[0])
    for y in range(rows):
        for x in range(cols):
            if x == 0 or x == cols - 1:
                g[y][x] = side_ch
            elif y == 0 or y == rows - 1:
                g[y][x] = top_ch


def dw_gen_castle(r, cols, rows):
    g = dw_grid(cols, rows, ".")
    cw = max(6, int(cols * 0.5 + 0.5))
    chh = max(5, int(rows * 0.42 + 0.5))
    x0 = (cols - cw) // 2 + r.ri(3) - 1
    y0 = (rows - chh) // 2 + r.ri(3) - 1
    for y in range(y0 - 1, y0 + chh + 1):                # the moat: a ring of water
        for x in range(x0 - 1, x0 + cw + 1):
            if x == x0 - 1 or x == x0 + cw or y == y0 - 1 or y == y0 + chh:
                g[y][x] = "w"
    for y in range(y0, y0 + chh):                         # the wall
        for x in range(x0, x0 + cw):
            if x == x0 or x == x0 + cw - 1 or y == y0 or y == y0 + chh - 1:
                g[y][x] = "#"
    for (x, y) in ((x0, y0), (x0 + cw - 1, y0), (x0, y0 + chh - 1), (x0 + cw - 1, y0 + chh - 1)):
        g[y][x] = "T"                                      # four corner towers
    kh = 2 if chh >= 6 else 1                              # the keep in the middle of the yard
    kx = x0 + cw // 2 - 1
    ky = y0 + (chh - kh) // 2
    for y in range(ky, ky + kh):
        for x in range(kx, kx + 2):
            g[y][x] = "K"
    free = [y for y in range(y0 + 1, y0 + chh - 1) if not (ky <= y < ky + kh)]
    mode = r.ri(3)                                         # 0 gate on the left, 1 on the right, 2 both
    if mode in (0, 2):
        gy = free[r.ri(len(free))]
        g[gy][x0] = "."
        g[gy][x0 - 1] = "b"
    if mode in (1, 2):
        gy = free[r.ri(len(free))]
        g[gy][x0 + cw - 1] = "."
        g[gy][x0 + cw] = "b"
    dw_scatter(g, r, max(4, cols * rows // 30), "t", ".")
    dw_scatter(g, r, cols * rows // 70, "r", ".")
    dw_border(g, "t", "t")
    return g


def dw_gen_nature(r, cols, rows):
    g = dw_grid(cols, rows, ".")
    bx = cols // 2 + r.ri(3) - 1
    w = 2 + r.ri(2)
    off = 0
    for y in range(rows):                                  # a ravine from top to bottom, ragged
        off += r.ri(3) - 1
        off = max(-1, min(1, off))
        for x in range(bx + off, bx + off + w):
            g[y][x] = "c"
    by = 3 + r.ri(rows - 6)                                # one log bridge across it
    for x in range(cols):
        if g[by][x] == "c":
            g[by][x] = "b"
    side = r.ri(2)                                         # a pond on one side
    if side == 0:
        pcx = bx / 2.0
    else:
        pcx = (bx + w + cols - 1) / 2.0
    pcx += r.ri(3) - 1
    pcy = 3 + r.ri(rows - 6) + 0.5
    dw_blob(g, pcx, pcy, 1.5 + 0.5 * r.ri(2), "w", ".")
    for _ in range(4):                                     # clumps of trees
        cx = 1 + r.ri(cols - 2)
        cy = 1 + r.ri(rows - 2)
        for dy in range(-2, 3):
            for dx in range(-2, 3):
                if dx * dx + dy * dy <= 3:
                    x = cx + dx
                    y = cy + dy
                    if 0 <= x < cols and 0 <= y < rows and g[y][x] == ".":
                        if r.next() < 0.6:
                            g[y][x] = "t"
    dw_scatter(g, r, cols * rows // 60, "r", ".")
    dw_border(g, "r", "t")
    return g


def dw_gen_island(r, cols, rows):
    g = dw_grid(cols, rows, "w")
    cx = cols / 2.0
    cy = rows / 2.0
    land = []
    for attempt in range(5):
        r0 = min(cols, rows) * 0.42 + 0.12 * attempt
        blobs = [(cx, cy, r0)]
        for _ in range(4):
            bx = cx + (r.next() * 2 - 1) * cols * 0.25
            by = cy + (r.next() * 2 - 1) * rows * 0.28
            br = r0 * (0.5 + 0.35 * r.next())
            blobs.append((bx, by, br))
        land = [[False] * cols for _ in range(rows)]
        count = 0
        for y in range(1, rows - 1):
            for x in range(1, cols - 1):
                f = 0.0
                for (bx, by, br) in blobs:
                    dx = x + 0.5 - bx
                    dy = y + 0.5 - by
                    d2 = dx * dx + dy * dy
                    if d2 < br * br:
                        t = 1.0 - d2 / (br * br)
                        f += t * t
                if f > 0.18:
                    land[y][x] = True
                    count += 1
        if count >= cols * rows * 0.28:
            break
    for y in range(rows):
        for x in range(cols):
            if land[y][x]:
                beach = False
                for (dx, dy) in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    if not land[y + dy][x + dx]:
                        beach = True
                g[y][x] = "s" if beach else "."
    cand = []                                              # a little lagoon inside the island
    for y in range(2, rows - 2):
        for x in range(2, cols - 3):
            ok = True
            for dy in (-1, 0, 1):
                for dx in (-1, 0, 1, 2):
                    if g[y + dy][x + dx] not in ".s":
                        ok = False
            if ok and g[y][x] == "." and g[y][x + 1] == ".":
                cand.append((x, y))
    if cand:
        (lx, ly) = cand[r.ri(len(cand))]
        g[ly][lx] = "w"
        g[ly][lx + 1] = "w"
    for y in range(rows):                                  # palms and a few rocks
        for x in range(cols):
            if g[y][x] == ".":
                v = r.next()
                if v < 0.24:
                    g[y][x] = "p"
                elif v < 0.27:
                    g[y][x] = "r"
    return g


def dw_gen_volcano(r, cols, rows):
    g = dw_grid(cols, rows, ".")
    vx = cols // 2 - 1 + r.ri(3) - 1
    vy = 1 + r.ri(2)
    for y in range(vy, vy + 3):
        for x in range(vx, vx + 3):
            g[y][x] = "V"
    nriv = 1 + r.ri(2)
    for k in range(nriv):                                  # rivers of lava from the foot of the volcano to the bottom
        x = vx + 1 + (r.ri(3) - 1) * k
        y = vy + 3
        while y < rows - 1:
            wid = 1 + r.ri(2)
            for xx in range(x, x + wid):
                if 1 <= xx <= cols - 2 and g[y][xx] == ".":
                    g[y][xx] = "l"
            x += r.ri(3) - 1
            x = max(2, min(cols - 4, x))
            y += 1
    by = vy + 5 + r.ri(max(1, rows - 3 - (vy + 5)))        # a stone bridge over the lava
    for x in range(cols):
        if g[by][x] == "l":
            g[by][x] = "b"
    pcx = 3 + r.ri(cols - 6) + 0.5
    pcy = vy + 5 + r.ri(max(1, rows - vy - 8)) + 0.5
    dw_blob(g, pcx, pcy, 1.5, "l", ".")
    dw_scatter(g, r, cols * rows // 25, "r", ".")
    dw_scatter(g, r, cols * rows // 45, "t", ".")
    dw_border(g, "r", "r")
    return g


def dw_gen_desert(r, cols, rows):
    g = dw_grid(cols, rows, ".")
    for _ in range(3 + r.ri(2)):                           # quicksand pits
        cx = 2.5 + r.next() * (cols - 5)
        cy = 2.5 + r.next() * (rows - 5)
        dw_blob(g, cx, cy, 1.0 + r.next() * 0.7, "q", ".")
    ox = 3 + r.next() * (cols - 6)                         # an oasis with palms around it
    oy = 3 + r.next() * (rows - 6)
    dw_blob(g, ox, oy, 1.6, "w", ".")
    for y in range(rows):
        for x in range(cols):
            dx = x + 0.5 - ox
            dy = y + 0.5 - oy
            d2 = dx * dx + dy * dy
            if 1.9 * 1.9 <= d2 <= 3.0 * 3.0 and g[y][x] == ".":
                if r.next() < 0.5:
                    g[y][x] = "p"
    gx = 2 + r.ri(cols - 4)                                # a crack in the ground
    gy = 1 + r.ri(max(1, rows - 7))
    for y in range(gy, gy + 4 + r.ri(2)):
        if y < rows and g[y][gx] == ".":
            g[y][gx] = "c"
    dw_scatter(g, r, cols * rows // 26, "t", ".")
    dw_scatter(g, r, cols * rows // 45, "r", ".")
    dw_border(g, "r", "r")
    return g


DW_GENERATORS = {"castle": dw_gen_castle, "nature": dw_gen_nature, "island": dw_gen_island,
                 "volcano": dw_gen_volcano, "desert": dw_gen_desert}


def dw_make_deco(theme, seed, g):
    """Small things on the ground that do nothing (flowers, shells, waves ...): [kind, x, y, variant].  Their own random series."""
    rd = DwRng((seed ^ 0x5BD1E995) & 0xFFFFFFFF)
    out = []
    rows, cols = len(g), len(g[0])
    for y in range(rows):
        for x in range(cols):
            c = g[y][x]
            v = rd.next()
            kind = ""
            if c == ".":
                if v < 0.20:
                    kind = "tuft"
                elif v < 0.30:
                    kind = "flower" if theme in ("castle", "nature", "island") else "pebble"
            elif c == "s":
                if v < 0.12:
                    kind = "bone" if theme == "desert" else "shell"
            elif c == "w":
                if v < 0.35:
                    kind = "wave"
            elif c == "l":
                if v < 0.30:
                    kind = "bubble"
            elif c == "q":
                if v < 0.60:
                    kind = "swirl"
            if kind:
                px = x + 0.15 + 0.7 * rd.next()
                py = y + 0.15 + 0.7 * rd.next()
                out.append([kind, px, py, int(rd.next() * 3)])
    return out


def dw_make_world(theme, seed, shape):
    """The world for (theme, seed, shape 'P' or 'L').  The same three things always give the same world."""
    cols, rows = DW_SHAPES[shape]
    seed = int(seed) & 0x7FFFFFFF
    r = DwRng(seed)
    g = DW_GENERATORS[theme](r, cols, rows)
    return {"theme": theme, "seed": seed, "shape": shape, "cols": cols, "rows": rows,
            "g": ["".join(row) for row in g], "deco": dw_make_deco(theme, seed, g)}


# *************** DEL 06 - PLACING DINOSAURS AND RUNNING *****************
def dw_cell(world, cx, cy):
    """The letter of a cell; outside the picture counts as a wall."""
    if cx < 0 or cy < 0 or cx >= world["cols"] or cy >= world["rows"]:
        return "#"
    return world["g"][cy][cx]


def dw_can_place(world, dinos, typ, cx, cy, ignore=-1):
    """May a dinosaur of this type stand in this cell?  (Walkers: on ground, sand or a bridge.  Swimmers: in water.  Flyers: anywhere.)"""
    if cx < 1 or cy < 1 or cx > world["cols"] - 2 or cy > world["rows"] - 2:
        return False
    kind = DW_ALL[typ]["kind"]
    c = dw_cell(world, cx, cy)
    if kind in ("walk", "rocket", "fw") and c not in ".sb":      # rockets and launchers stand on dry ground like the walkers
        return False
    if kind == "swim" and c != "w":
        return False
    hw = DW_ALL[typ]["size"] * 0.36
    for i, d in enumerate(dinos):
        if i == ignore:
            continue
        if (DW_ALL[d["t"]]["kind"] == "fly") != (kind == "fly"):
            continue
        if abs(d["x"] - cx) + 0.0 < hw + DW_ALL[d["t"]]["size"] * 0.36 and d["y"] == cy:
            return False
    return True


def dw_rocket_y(y0, tm, go):
    """Height (feet) of a rocket that stood at y0 and lifts off at time go, tm seconds after the start of the run."""
    s = tm - go
    return y0 if s <= 0 else y0 - 0.5 * DW_ROCKET_ACC * s * s


def dw_start_run(world, dinos):
    ents = []
    nth = {"rocket": 0, "fireworks": 0}
    for i, d in enumerate(dinos):
        e = {"i": i, "t": d["t"], "x": d["x"] + 0.5, "y": d["y"] + 0.5, "d": 1 if d["d"] >= 0 else -1,
             "st": "walk", "tm": 0.0, "hz": "", "vy": 0.0}
        if d["t"] in DW_THINGS:                                     # a rocket or a firework launcher waits for its turn
            k = nth[d["t"]]
            nth[d["t"]] += 1
            e["st"] = "ready"
            e["k"] = k
            e["y0"] = e["y"]
            if d["t"] == "rocket":
                e["r"] = d.get("r", "") if d.get("r", "") in DW_TYPES else ""
                e["go"] = DW_ROCKET_COUNT + DW_ROCKET_STAGGER * k
                e["ig"] = False
            else:
                e["go"] = DW_FW_START + DW_FW_STAGGER * k
                e["rd"] = 0
        ents.append(e)
    return {"world": world, "ents": ents, "tick": 0, "events": [], "done": False}


def dw_ev(sim, name, i, **kw):
    e = {"tick": sim["tick"], "e": name, "i": i}
    e.update(kw)
    sim["events"].append(e)


def dw_fw_shoot(sim, e):
    """A launcher sends up its next shell: where it will burst is fixed now (the same every run)."""
    cols = sim["world"]["cols"]
    v = (e["k"] * 2 + e["rd"] * 3) % 5
    e["st"] = "shoot"
    e["tm"] = 0.0
    e["bx"] = min(cols - 1.0, max(1.0, e["x"] + (v - 2) * 0.9))
    e["by"] = max(1.5, e["y"] - (4.0 + ((e["rd"] + e["k"]) % 3) * 1.3))
    dw_ev(sim, "shoot", e["i"], rd=e["rd"])


def dw_step_thing(sim, e):
    """One tick of a rocket or a firework launcher (e['tm'] has already been counted up)."""
    st = e["st"]
    if e["t"] == "rocket":
        if st == "ready":
            if not e["ig"] and e["tm"] >= e["go"] - DW_ROCKET_SMOKE:
                e["ig"] = True
                dw_ev(sim, "ignite", e["i"])
            if e["tm"] >= e["go"]:
                e["st"] = "lift"
                dw_ev(sim, "launch", e["i"], r=e["r"])
        elif st == "lift":
            e["y"] = dw_rocket_y(e["y0"], e["tm"], e["go"])
            if e["y"] < -(DW_THINGS["rocket"]["hh"] + 0.4):
                e["st"] = "gone"
                dw_ev(sim, "gone", e["i"])
        return
    if st == "ready":                                                  # a firework launcher: shoot, burst, three times
        if e["tm"] >= e["go"]:
            dw_fw_shoot(sim, e)
    elif st == "shoot":
        if e["tm"] >= DW_FW_SHOOT:
            e["st"] = "burst"
            e["tm"] = 0.0
            dw_ev(sim, "burst", e["i"], rd=e["rd"], x=e["bx"], y=e["by"])
    elif st == "burst":
        if e["tm"] >= DW_FW_BURST:
            e["rd"] += 1
            if e["rd"] >= DW_FW_ROUNDS:
                e["st"] = "stop"
                e["tm"] = 0.0
            else:
                dw_fw_shoot(sim, e)


def dw_step(sim):
    """One tick (1/30 s) of the run.  New events are appended to sim['events']."""
    if sim["done"]:
        return
    world = sim["world"]
    cols = world["cols"]
    sim["tick"] += 1
    dt = DW_DT
    ents = sim["ents"]
    for e in ents:
        e["tm"] += dt
        if e["t"] in DW_THINGS:
            dw_step_thing(sim, e)
            continue
        st = e["st"]
        info = DW_TYPES[e["t"]]
        size = info["size"]
        if st == "walk":
            if info["kind"] == "fly":
                e["x"] += e["d"] * info["speed"] * dt
                if e["x"] < -size or e["x"] > cols + size:
                    e["st"] = "gone"
                    dw_ev(sim, "gone", e["i"])
                continue
            nx = e["x"] + e["d"] * info["speed"] * dt
            fx = nx + e["d"] * size * 0.34
            cx = int(math.floor(fx))
            cy = int(math.floor(e["y"]))
            c = dw_cell(world, cx, cy)
            blocked = (c in DW_SOLID) if info["kind"] == "walk" else (c != "w")
            if not blocked and info["kind"] == "walk":                 # a rocket that has not left yet is in the way like a tree
                for o in ents:
                    if o["t"] == "rocket" and o["st"] == "ready" and int(math.floor(o["x"])) == cx and int(math.floor(o["y"])) == cy:
                        blocked = True
                        c = "R"
                        break
            if blocked:
                if e["d"] > 0:
                    e["x"] = cx - size * 0.34 - 1e-6
                else:
                    e["x"] = cx + 1 + size * 0.34 + 1e-6
                e["st"] = "stop"
                e["tm"] = 0.0
                dw_ev(sim, "bonk", e["i"], c=c)
            else:
                e["x"] = nx
                if info["kind"] == "walk":
                    cc = dw_cell(world, int(math.floor(nx)), cy)
                    if cc in DW_SINK:
                        e["st"] = "fall" if cc == "c" else "sink"
                        e["hz"] = cc
                        e["tm"] = 0.0
                        dw_ev(sim, e["st"], e["i"], c=cc)
        elif st == "fall" or st == "sink":
            if e["tm"] >= DW_SINK[e["hz"]]:
                e["st"] = "gone"
                dw_ev(sim, "gone", e["i"])
        elif st == "poof":
            if e["tm"] >= DW_POOF_TIME:
                e["st"] = "up"
                e["tm"] = 0.0
                e["vy"] = -2.0
        elif st == "up":
            e["vy"] -= 40.0 * dt
            e["y"] += e["vy"] * dt
            if e["y"] < -size * 1.2:
                e["st"] = "gone"
                dw_ev(sim, "gone", e["i"])
    n = len(ents)
    for i in range(n):                                     # two that meet go up in a cloud
        a = ents[i]
        if a["st"] not in ("walk", "stop") or a["t"] in DW_THINGS:
            continue
        ia = DW_TYPES[a["t"]]
        for j in range(i + 1, n):
            b = ents[j]
            if b["st"] not in ("walk", "stop") or a["st"] not in ("walk", "stop") or b["t"] in DW_THINGS:
                continue
            ib = DW_TYPES[b["t"]]
            if (ia["kind"] == "fly") != (ib["kind"] == "fly"):
                continue
            if abs(a["x"] - b["x"]) < (ia["size"] + ib["size"]) * 0.36 and abs(a["y"] - b["y"]) < 0.9:
                mx = (a["x"] + b["x"]) / 2
                my = (a["y"] + b["y"]) / 2
                for z in (a, b):
                    z["st"] = "poof"
                    z["tm"] = 0.0
                dw_ev(sim, "poof", a["i"], j=b["i"], x=mx, y=my)
    if all(e["st"] in ("stop", "gone") for e in ents) or sim["tick"] >= DW_MAX_TICKS:
        sim["done"] = True
        dw_ev(sim, "done", -1)


def dw_run_all(sim):
    while not sim["done"]:
        dw_step(sim)
    return sim


def dw_summary(sim):
    """What became of everybody: counts by how they ended."""
    out = {"stopped": 0, "fell": 0, "sank": 0, "cloud": 0, "flew": 0}
    byi = {}
    for ev in sim["events"]:
        if ev["e"] in ("bonk", "fall", "sink", "poof"):
            byi.setdefault(ev["i"], ev["e"])
            if ev["e"] == "poof":
                byi.setdefault(ev["j"], "poof")
    for e in sim["ents"]:
        if e["t"] in DW_THINGS:                       # rockets and fireworks are counted by dw_summary_things
            continue
        how = byi.get(e["i"], "")
        if how == "bonk":
            out["stopped"] += 1
        elif how == "fall":
            out["fell"] += 1
        elif how == "sink":
            out["sank"] += 1
        elif how == "poof":
            out["cloud"] += 1
        else:
            out["flew"] += 1
    return out


def dw_summary_things(sim):
    """Rockets that lifted off, dinosaurs that went with them, firework launchers that were lit."""
    out = {"rockets": 0, "riders": 0, "fireworks": 0}
    for e in sim["ents"]:
        if e["t"] == "rocket":
            out["rockets"] += 1
            if e.get("r"):
                out["riders"] += 1
        elif e["t"] == "fireworks":
            out["fireworks"] += 1
    return out


# *************** DEL 07 - UI HELPERS (NO BLINK, MODAL DIALOGS) *****************
# Copy verbatim into every program.  Rules: 01_CORE_always_read.md, section 5.
#
# NO BLINKING CURSORS ANYWHERE.  Use tk.Entry / tk.Text (never ttk.Entry) and set
# the values PER WIDGET when it is created - also in Toplevel dialogs and log
# windows.  Do not rely on option_add.
#
# Needs:  import tkinter as tk

NO_BLINK = dict(insertofftime=0, insertontime=9999999)


def new_entry(parent, **kw):
    """tk.Entry with a fixed (non-blinking) cursor."""
    return tk.Entry(parent, **{**NO_BLINK, **kw})


def new_text(parent, **kw):
    """tk.Text with a fixed (non-blinking) cursor."""
    return tk.Text(parent, **{**NO_BLINK, **kw})


def no_blink(w):
    """Fix the cursor of a widget that already exists.  Returns the widget."""
    try:
        w.configure(**NO_BLINK)
    except Exception:
        pass
    return w


def make_modal(top, on_escape=None):
    """Every Toplevel dialog: grab_set(), focus_force(), <Escape> - in that order.

    on_escape is called instead of top.destroy() when Escape is pressed.
    A dialog opened on top of another modal one takes the grab; when it is
    destroyed the grab goes back to the dialog underneath (otherwise that one
    stops answering the mouse)."""
    try:
        below = top.grab_current()    # the modal window we are about to cover
    except Exception:
        below = None
    try:
        top.grab_set()
    except Exception:
        pass                      # window not viewable yet - not fatal
    try:
        top.focus_force()
    except Exception:
        pass
    top.bind("<Escape>", lambda e: (on_escape or top.destroy)())

    def _give_back(e):
        if e.widget is top and below is not None:
            try:
                if below.winfo_exists():
                    below.grab_set()
            except Exception:
                pass
    top.bind("<Destroy>", _give_back, add="+")


def continue_button(parent, text, command, **kw):
    """The "Continue" / "OK" / "Next" button of a game: reacts to a mouse click,
    Enter (also the numpad one) AND Space - always, whichever widget has focus.

    Returns the tk.Button; the caller packs/grids it.  The keys are bound on the
    button's own window and only act while the button exists and is on screen,
    so an old Continue can never fire from a later screen.  Enter/Space are
    left alone while the player is typing (Entry, Text, Combobox ...).  The
    button takes focus and also handles the keys itself (stopping tk's own Space
    handling, so nothing fires twice); the window binding covers every other
    focus, and steps aside for a DIFFERENT focused button (Space presses that)."""

    def go(event=None):
        if not btn.winfo_exists() or not btn.winfo_ismapped():
            return
        if str(btn.cget("state")) == "disabled":
            return
        command()

    def key(event):
        w = btn.focus_get()
        cls = w.winfo_class() if w is not None else ""
        if cls in ("Entry", "Text", "TEntry", "TCombobox", "Spinbox", "Listbox"):
            return                                   # the player is typing
        if (event.keysym == "space" and w is not btn
                and cls in ("Button", "TButton", "Checkbutton", "Radiobutton")):
            return                                   # tk presses that other button
        go()
        return "break"

    btn = tk.Button(parent, text=text, command=go, **kw)
    top = btn.winfo_toplevel()
    seqs = ("<Return>", "<KP_Enter>", "<space>")
    ids = [(seq, top.bind(seq, key, add="+")) for seq in seqs]
    for seq in seqs:                     # focus on the button itself
        btn.bind(seq, lambda e: (go(), "break")[1])

    def cleanup(e):
        if e.widget is btn:
            for seq, fid in ids:
                try:
                    top.unbind(seq, fid)
                except Exception:
                    pass
    btn.bind("<Destroy>", cleanup, add="+")
    btn.focus_set()
    return btn


# *************** DEL 08 - THE TEXTS THE PLAYER READS (English built in; the rest are language files) *****************
# Every text of the window, the help and the dialogs is here once, in English.  Other languages are FILES
# (Helpfiles\Dino_World\Lang\<code>.txt, DEL 10) that override a text by its key; a missing key falls back to this English.
# The same keys are used by the phone app (lang\dw.json), so one translation serves both.
APP_TITLE = "Dino World"

STRINGS = {
    "dw_title": "Dino World",
    "dw_tagline": "Make a world, put out dinosaurs and press Run.",
    "th_random": "Surprise", "th_castle": "Castle", "th_nature": "Forest", "th_island": "Island", "th_volcano": "Volcano", "th_desert": "Desert",
    "dn_trex": "T-rex", "dn_trike": "Triceratops", "dn_stego": "Stegosaurus", "dn_bronto": "Long neck", "dn_anky": "Ankylosaurus",
    "dn_raptor": "Raptor", "dn_para": "Parasaurolophus", "dn_ptero": "Flyer", "dn_plesio": "Swimmer", "dn_baby": "Baby dino",
    "dw_run": "Run!", "dw_edit": "Edit", "dw_again": "Again", "dw_fast": "Fast", "dw_flip": "Turn", "dw_remove": "Remove", "dw_clear": "Clear",
    "dw_save": "Save", "dw_load": "Open", "dw_help": "Help", "dw_close": "Close", "dw_yes": "Yes", "dw_no": "No", "dw_new": "New world",
    "dw_sound": "Sound", "dw_notes": "My notes", "dw_about": "About", "dw_ok": "OK", "dw_cancel": "Cancel", "dw_del": "Delete",
    "dn_rocket": "Rocket", "dn_rocketdino": "Rocket + dino", "dn_fireworks": "Fireworks",
    "hint_rocket": "Click the world to put out a rocket.",
    "hint_rocketdino": "Click the world to put out a rocket with a dinosaur inside. Pick another dinosaur to change who rides.",
    "hint_fw": "Click the world to put out fireworks.",
    "sum_rockets": "Rockets launched: {n}", "sum_riders": "Dinosaurs in space: {n}", "sum_fireworks": "Fireworks lit: {n}",
    "help_more": ("Rockets and fireworks: below the dinosaurs there are three more buttons. Rocket puts out an empty rocket. "
                  "Rocket + dino puts out a rocket with the dinosaur you picked sitting in its window (pick another dinosaur to change who rides). "
                  "When you run, every rocket shakes, smokes and lifts off, and a dinosaur inside goes with it. A dinosaur that walks into a "
                  "rocket that has not left yet bumps into it. Fireworks puts out a launcher that shoots three colourful shells high up in the sky."),
    "hint_pick": "Pick a dinosaur and click the world.",
    "hint_sel": "Turn it, drag it where you want it, or remove it.",
    "hint_run": "Look!",
    "hint_nope": "It cannot stand there.",
    "hint_many": "There is no room for more.",
    "hint_saved": "Saved!",
    "done_title": "All done!",
    "sum_stopped": "{n} stopped", "sum_cloud": "{n} crashed", "sum_fell": "{n} fell down", "sum_sank": "{n} sank", "sum_flew": "{n} flew away",
    "sum_none": "There were no dinosaurs. Put some out first!",
    "ask_new": "New world? The dinosaurs you put out will be removed.",
    "ask_clear": "Remove all the dinosaurs?",
    "save_title": "Save the world", "save_name": "Name of the world:",
    "load_title": "Your worlds", "load_empty": "No saved worlds yet. Press Save.", "load_folder": "Folder",
    "help_title": "How to play",
    "help_text": ("1. Pick a world at the top: castle, forest, island, volcano or desert. Or Surprise for a random one. "
                  "Click the same one again for a new version.\n\n"
                  "2. Pick a dinosaur on the right and click the world to put it out.\n\n"
                  "3. Turn changes which way the dinosaur looks. Click a dinosaur to pick it. Then you can turn it, drag it "
                  "somewhere else or remove it (Delete key).\n\n"
                  "4. Save keeps the world with its dinosaurs. Open shows your saved worlds. They are the same files as on the phone.\n\n"
                  "5. Press Run! (or the space bar). The dinosaurs start to walk (one flies and one swims). Walls, trees and rocks stop them. "
                  "At the edge of a cliff they fall fast. In water, lava and quicksand they sink slowly. When two dinosaurs meet there is a "
                  "cloud, and both shoot up and disappear.\n\nIt ends when everybody has gone or stopped."),
    "about_text": "A toy world for the youngest: put out dinosaurs and watch what happens.",
    "about_version": "Version {v}",
    "pt_hint": "Your own text - saved by itself as Playertext-<name>.txt in the program's Helpfiles folder.  Every such file there can be picked above.",
    "pt_folder": "Folder", "pt_new": "New...", "pt_wrap": "Wrap",
    "pt_newname": "Name of the new text (ideas, drawings to try, ...):",
}

# Texts that exist ONLY in the phone's file (lang\dw.json) are not here; the keys above are the ones both use, plus the PC extras
# (dw_tagline, dw_sound, dw_notes, dw_about, dw_ok, dw_cancel, save_*, load_folder, about_*, pt_*).


# *************** DEL 09 - LANGUAGE PICKER (GLOBE ICON) *****************
# Copy verbatim into every game.  Rules: 40_games.md, "Language switch".
#
# A tiny globe (drawn on a Canvas, so it is the same size in every language and
# needs no emoji font) that sits in the main window ALWAYS - not buried in
# Settings.  Click it -> a menu with every language the game has, each under its
# OWN name in its OWN script (English, Svenska, Русский, Deutsch ...), so a
# player who ended up in a language they cannot read can still find their way
# back.  The current language carries a bullet.
#
# Needs:  import tkinter as tk
#
# Call:   pick = make_language_picker(parent, LANGS, get_lang, set_lang,
#                                     bg="#1e1e2e", fg="#e0e0e0")
#         pick.pack(side="right", padx=6)     # or .grid(...)
#   LANGS     tuple/list of language codes the game has, e.g. ("en","sv","ru")
#   get_lang  () -> current code
#   set_lang  (code) -> switch the game to that language (rebuild the texts)
# Menu labels are NEVER translated - that is the whole point.

NATIVE_LANGUAGE_NAMES = {
    "en": "English",   "sv": "Svenska",    "ru": "Русский",   "de": "Deutsch",
    "fr": "Français",  "es": "Español",    "pt": "Português", "it": "Italiano",
    "nl": "Nederlands", "da": "Dansk",     "no": "Norsk",     "fi": "Suomi",
    "pl": "Polski",    "cs": "Čeština",    "hu": "Magyar",    "tr": "Türkçe",
    "uk": "Українська", "el": "Ελληνικά",  "ja": "日本語",     "zh": "中文",
    "ko": "한국어",     "ar": "العربية",   "he": "עברית",
}

GLOBE_SIZE = 20     # px; roughly a checkbox.  Fixed, whatever the language.


def _draw_globe(cv, fg):
    """Outline globe: circle, equator, one meridian ellipse, two parallels."""
    s = GLOBE_SIZE
    m = 2
    cv.delete("all")
    cv.create_oval(m, m, s - m, s - m, outline=fg, width=1)
    cv.create_line(m, s // 2, s - m, s // 2, fill=fg)                # equator
    cv.create_oval(s // 2 - 4, m, s // 2 + 4, s - m, outline=fg)      # meridians
    cv.create_line(s // 2, m, s // 2, s - m, fill=fg)                 # axis
    cv.create_arc(m, m + 4, s - m, s - m - 4, start=0, extent=180,
                  style="arc", outline=fg)                            # parallels
    cv.create_arc(m, m + 4, s - m, s - m - 4, start=180, extent=180,
                  style="arc", outline=fg)


def make_language_picker(parent, langs, get_lang, set_lang,
                         bg="#1e1e2e", fg="#e0e0e0", hover="#89b4fa"):
    """Return the globe Canvas; the caller packs/grids it."""
    cv = tk.Canvas(parent, width=GLOBE_SIZE, height=GLOBE_SIZE, bg=bg,
                   highlightthickness=0, cursor="hand2", takefocus=0)
    _draw_globe(cv, fg)

    def popup(event=None):
        menu = tk.Menu(cv, tearoff=0)
        cur = get_lang()
        for code in langs:
            name = NATIVE_LANGUAGE_NAMES.get(code, code)
            menu.add_command(label=("\u25cf  " if code == cur else "    ") + name,
                             command=lambda c=code: set_lang(c))
        x = cv.winfo_rootx()
        y = cv.winfo_rooty() + GLOBE_SIZE + 2
        try:
            menu.tk_popup(x, y)
        finally:
            menu.grab_release()

    cv.bind("<Button-1>", popup)
    cv.bind("<Enter>", lambda e: _draw_globe(cv, hover))
    cv.bind("<Leave>", lambda e: _draw_globe(cv, fg))
    return cv


# *************** DEL 10 - LANGUAGE FILES (Lang\<code>.txt) *****************
# block_language_files.py - copied from Speed_Circuit.py DEL 04b (2026-10-02).
# Rules: 40_games.md, "Languages are FILES in a language folder".
#
# ONLY ENGLISH IS BUILT IN (2026-10-03): the STRINGS table holds one English
# text per key, {key: "text"}.  A tuple is still read, so an old game keeps the
# columns it already has - set BUILTIN_LANGS to those codes IN COLUMN ORDER,
# e.g. ("en", "sv", "ru").  Every other language - SWEDISH INCLUDED in a new
# game - is a FILE  Helpfiles\<Program>\Lang\<code>.txt  made by HTTP-Claude,
# never by Code-Claude.  The globe menu (block_language_picker.py) iterates LANGS, which
# looks at the folder again every time, so dropping in de.txt adds German with
# no code change.  A file overrides the built-in text; a missing file, key or
# line falls back to the built-in text (English): the game never fails.
#
# The program must already have, ABOVE this block:
#   import os, re
#   PROGRAM_HF_DIR      (block_home.py)         APP_TITLE
#   STRINGS             {key: "English text"}    NATIVE_LANGUAGE_NAMES (block_language_picker.py)
# and must call:  LANG = Language(saved code)  -  tr("key", a=1)  everywhere
# (replace the old tr/LANG pair), and in main():
#   if "--export-lang" in sys.argv[1:]:
#       for p in export_lang_files(): print(p)
#       sys.exit(0)
# --export-lang writes Lang\en.txt (one file per code in BUILTIN_LANGS): the
# template Lars gives to HTTP-Claude for sv/ru/<designer's language>.  Texts built from pieces in code must be
# templates with {placeholders} (grammar differs between languages).

BUILTIN_LANGS = ("en",)
LANG_DIR = os.path.join(PROGRAM_HF_DIR, "Lang")
_LANG_CODE_RE = re.compile(r"^[a-z]{2,3}$")


def _row(key):
    """STRINGS[key] as a tuple - a plain English string becomes a 1-tuple."""
    row = STRINGS.get(key)
    if row is None:
        return ()
    if isinstance(row, str):
        return (row,)
    return tuple(row)


def _unescape(t):
    return re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), t)


def _escape(t):
    return t.replace("\\", "\\\\").replace("\n", "\\n")


def read_lang_file(code):
    """-> ({key: text}, native name or None).  Never raises."""
    texts, name = {}, None
    try:
        with open(os.path.join(LANG_DIR, code + ".txt"), encoding="utf-8-sig", errors="replace") as fh:
            for raw in fh:
                line = raw.rstrip("\r\n")
                if not line.strip() or line.lstrip().startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                k, v = k.strip(), _unescape(v.strip())
                if k == "name":
                    name = v
                elif k and v:
                    texts[k] = v
    except Exception:
        pass
    return texts, name


def scan_langs():
    """Codes of every language the game has: the built-in ones plus every Lang/<code>.txt."""
    codes = list(BUILTIN_LANGS)
    try:
        for n in sorted(os.listdir(LANG_DIR)):
            c = os.path.splitext(n)[0].lower()
            if n.lower().endswith(".txt") and _LANG_CODE_RE.match(c) and c not in codes:
                codes.append(c)
                nm = read_lang_file(c)[1]
                if nm:
                    NATIVE_LANGUAGE_NAMES.setdefault(c, nm)
    except OSError:
        pass
    return codes


class LangList(object):
    """What the globe menu iterates: looked at again every time it opens."""

    def __iter__(self):
        return iter(scan_langs())

    def __len__(self):
        return len(scan_langs())

    def __contains__(self, c):
        return c in scan_langs()


LANGS = LangList()


class Language(object):
    """The current language; tr() reads it."""

    def __init__(self, code="en"):
        self.code = "en"
        self.idx = 0
        self.ext = {}
        self.set(code)

    def set(self, code):
        if code not in scan_langs():
            code = "en"
        self.code = code
        self.idx = BUILTIN_LANGS.index(code) if code in BUILTIN_LANGS else 0
        self.ext = read_lang_file(code)[0]


LANG = Language("en")


def tr(key, **kw):
    row = _row(key)
    text = LANG.ext.get(key)
    if text is None:
        if not row:
            return key
        text = row[LANG.idx] if LANG.idx < len(row) else row[0]
    if kw:
        try:
            text = text.format(**kw)
        except Exception:
            try:
                text = (row[0] if row else key).format(**kw)
            except Exception:
                pass
    return text


def t_en(key, **kw):
    """The same string, always in English - this is what the FILE gets."""
    row = _row(key)
    if not row:
        return key
    text = row[0]
    if kw:
        try:
            text = text.format(**kw)
        except Exception:
            pass
    return text


def export_lang_files():
    """Writes the built-in languages as Lang/<code>.txt (templates for translators)."""
    os.makedirs(LANG_DIR, exist_ok=True)
    out = []
    for i, code in enumerate(BUILTIN_LANGS):
        path = os.path.join(LANG_DIR, code + ".txt")
        with open(path, "w", encoding="utf-8", newline="\n") as fh:
            fh.write("# %s - interface texts (%s).  One text per line: key = text\n" % (APP_TITLE, code))
            fh.write("# Keep the keys and every {placeholder}; \\n is a line break; # starts a comment.\n")
            fh.write("name = %s\n" % NATIVE_LANGUAGE_NAMES.get(code, code))
            for k in STRINGS:
                row = _row(k)
                fh.write("%s = %s\n" % (k, _escape(row[i] if i < len(row) else row[0])))
        out.append(path)
    return out


# *************** DEL 11 - THE PICTURES AS SHAPES (made by tools\dw_art.py --embed in Kids_Android: change them THERE) *****************
# Lists of shapes in unit coordinates (0..1, y down), the same data as the phone's dw_art.js.  Dinosaurs face right, feet at y = 0.95.
# ART-BEGIN
DW_ART_JSON = r'''{"dino":{"trex":[{"kind":"oval","box":[0.44,0.5,0.62,0.8],"fill":"#b8542a","w":2.2},{"kind":"poly","pts":[[0.48,0.8],[0.61,0.8],[0.63,0.89],[0.71,0.94],[0.47,0.94],[0.48,0.88]],"fill":"#b8542a","w":2.2},{"kind":"poly","pts":[[0.03,0.71],[0.14,0.63],[0.26,0.55],[0.38,0.44],[0.5,0.38],[0.6,0.36],[0.65,0.28],[0.75,0.21],[0.88,0.22],[0.96,0.29],[0.96,0.37],[0.88,0.41],[0.8,0.42],[0.74,0.46],[0.71,0.54],[0.69,0.64],[0.62,0.74],[0.5,0.79],[0.38,0.77],[0.25,0.72],[0.12,0.73]],"fill":"#e0703a","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.5,0.77],[0.62,0.73],[0.68,0.64],[0.7,0.56],[0.66,0.58],[0.58,0.64],[0.52,0.7]],"fill":"#f6dca8","w":0,"line":""},{"kind":"oval","box":[0.32,0.46,0.38,0.52],"fill":"#b8542a","w":0,"line":""},{"kind":"oval","box":[0.44,0.41,0.5,0.47],"fill":"#b8542a","w":0,"line":""},{"kind":"oval","box":[0.2,0.58,0.25,0.63],"fill":"#b8542a","w":0,"line":""},{"kind":"oval","box":[0.42,0.53,0.66,0.84],"fill":"#e0703a","w":2.2},{"kind":"poly","pts":[[0.47,0.82],[0.62,0.82],[0.64,0.89],[0.74,0.94],[0.45,0.94],[0.47,0.89]],"fill":"#e0703a","w":2.2},{"kind":"poly","pts":[[0.69,0.56],[0.77,0.6],[0.81,0.66],[0.77,0.68],[0.73,0.64],[0.67,0.62]],"fill":"#e0703a","w":2.2},{"kind":"line","pts":[[0.8,0.4],[0.88,0.37],[0.95,0.36]],"w":1.6},{"kind":"poly","pts":[[0.84,0.39],[0.865,0.385],[0.855,0.43]],"fill":"#ffffff","w":1.0},{"kind":"poly","pts":[[0.89,0.375],[0.915,0.37],[0.905,0.415]],"fill":"#ffffff","w":1.0},{"kind":"line","pts":[[0.72,0.24],[0.8,0.22]],"w":2.2},{"kind":"oval","box":[0.764,0.244,0.836,0.316],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.7974,0.2638,0.8334,0.2998],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.8136,0.2674,0.8226,0.2764],"fill":"#ffffff","w":0,"line":""}],"trike":[{"kind":"oval","box":[0.18,0.66,0.32,0.92],"fill":"#47709f","w":2.2},{"kind":"oval","box":[0.5,0.66,0.64,0.92],"fill":"#47709f","w":2.2},{"kind":"poly","pts":[[0.06,0.66],[0.14,0.52],[0.28,0.42],[0.48,0.39],[0.62,0.43],[0.7,0.53],[0.7,0.67],[0.62,0.77],[0.4,0.81],[0.22,0.77],[0.14,0.72]],"fill":"#5d8fcf","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.08,0.66],[0.02,0.74],[0.1,0.72]],"fill":"#5d8fcf","w":2.0},{"kind":"poly","pts":[[0.3,0.76],[0.5,0.79],[0.64,0.74],[0.68,0.66],[0.6,0.7],[0.44,0.72]],"fill":"#f1e1b0","w":0,"line":""},{"kind":"oval","box":[0.2,0.66,0.36,0.94],"fill":"#5d8fcf","w":2.2},{"kind":"oval","box":[0.52,0.66,0.68,0.94],"fill":"#5d8fcf","w":2.2},{"kind":"oval","box":[0.18,0.9,0.38,0.96],"fill":"#47709f","w":1.6},{"kind":"oval","box":[0.5,0.9,0.7,0.96],"fill":"#47709f","w":1.6},{"kind":"oval","box":[0.57,0.14,0.84,0.56],"fill":"#e8789a","w":2.2},{"kind":"oval","box":[0.572,0.172,0.628,0.228],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.652,0.122,0.708,0.178],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.742,0.142,0.798,0.198],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.802,0.212,0.858,0.268],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.812,0.312,0.868,0.368],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.802,0.412,0.858,0.468],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.762,0.492,0.818,0.548],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.572,0.472,0.628,0.528],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.552,0.352,0.608,0.408],"fill":"#f6c25a","w":1.4},{"kind":"oval","box":[0.552,0.252,0.608,0.308],"fill":"#f6c25a","w":1.4},{"kind":"poly","pts":[[0.7,0.43],[0.88,0.4],[0.96,0.48],[0.96,0.6],[0.84,0.64],[0.72,0.6]],"fill":"#5d8fcf","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.86,0.4],[0.96,0.22],[0.92,0.44]],"fill":"#f6efd2","w":1.8},{"kind":"poly","pts":[[0.78,0.38],[0.88,0.2],[0.85,0.41]],"fill":"#fff8e1","w":1.8},{"kind":"poly","pts":[[0.94,0.52],[0.99,0.46],[0.98,0.58]],"fill":"#f6efd2","w":1.6},{"kind":"oval","box":[0.808,0.468,0.872,0.532],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.8388,0.4856,0.8708,0.5176],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.8532,0.4888,0.8612,0.4968],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.9,0.6],[0.95,0.58]],"w":1.4}],"stego":[{"kind":"oval","box":[0.22,0.66,0.36,0.92],"fill":"#4a8a38","w":2.2},{"kind":"oval","box":[0.56,0.66,0.7,0.92],"fill":"#4a8a38","w":2.2},{"kind":"poly","pts":[[0.15,0.66],[0.22,0.44],[0.29,0.66]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.23,0.56],[0.3,0.3],[0.37,0.56]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.33,0.5],[0.4,0.22],[0.47,0.5]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.44,0.47],[0.51,0.19],[0.58,0.47]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.55,0.49],[0.62,0.23],[0.69,0.49]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.64,0.55],[0.71,0.33],[0.78,0.55]],"fill":"#f0922c","w":2.0},{"kind":"poly","pts":[[0.04,0.78],[0.12,0.72],[0.22,0.62],[0.34,0.48],[0.5,0.42],[0.64,0.46],[0.74,0.56],[0.82,0.62],[0.92,0.66],[0.95,0.72],[0.87,0.76],[0.76,0.75],[0.66,0.79],[0.5,0.81],[0.34,0.79],[0.22,0.8],[0.1,0.82]],"fill":"#62a84a","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.08,0.78],[-0.02,0.68],[0.14,0.72]],"fill":"#f6efd2","w":1.6},{"kind":"poly","pts":[[0.12,0.8],[0.0,0.78],[0.16,0.76]],"fill":"#f6efd2","w":1.6},{"kind":"oval","box":[0.18,0.68,0.38,0.94],"fill":"#62a84a","w":2.2},{"kind":"oval","box":[0.52,0.68,0.72,0.94],"fill":"#62a84a","w":2.2},{"kind":"oval","box":[0.18,0.9,0.4,0.96],"fill":"#4a8a38","w":1.6},{"kind":"oval","box":[0.52,0.9,0.74,0.96],"fill":"#4a8a38","w":1.6},{"kind":"poly","pts":[[0.34,0.78],[0.5,0.8],[0.62,0.76],[0.5,0.74]],"fill":"#dbeeb4","w":0,"line":""},{"kind":"oval","box":[0.83,0.63,0.89,0.69],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.8595,0.6465,0.8895,0.6765],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.873,0.6495,0.8805,0.657],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.9,0.72],[0.95,0.71]],"w":1.4}],"bronto":[{"kind":"poly","pts":[[0.26,0.66],[0.38,0.66],[0.38,0.94],[0.26,0.94]],"fill":"#34827d","w":2.2},{"kind":"poly","pts":[[0.6,0.66],[0.72,0.66],[0.72,0.94],[0.6,0.94]],"fill":"#34827d","w":2.2},{"kind":"oval","box":[0.24,0.9,0.4,0.97],"fill":"#34827d","w":1.6},{"kind":"oval","box":[0.58,0.9,0.74,0.97],"fill":"#34827d","w":1.6},{"kind":"poly","pts":[[0.18,0.66],[0.32,0.66],[0.32,0.95],[0.18,0.95]],"fill":"#46a39d","w":2.2},{"kind":"poly","pts":[[0.52,0.66],[0.68,0.66],[0.68,0.95],[0.52,0.95]],"fill":"#46a39d","w":2.2},{"kind":"oval","box":[0.15,0.9,0.35,0.97],"fill":"#34827d","w":1.6},{"kind":"oval","box":[0.49,0.9,0.71,0.97],"fill":"#34827d","w":1.6},{"kind":"poly","pts":[[0.01,0.8],[0.1,0.72],[0.22,0.62],[0.34,0.54],[0.5,0.5],[0.6,0.52],[0.64,0.42],[0.66,0.3],[0.7,0.19],[0.78,0.11],[0.9,0.08],[0.97,0.12],[0.96,0.19],[0.88,0.21],[0.83,0.28],[0.83,0.44],[0.8,0.58],[0.74,0.68],[0.66,0.78],[0.5,0.83],[0.34,0.82],[0.2,0.82],[0.1,0.84]],"fill":"#46a39d","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.36,0.8],[0.52,0.82],[0.66,0.78],[0.74,0.68],[0.62,0.7],[0.48,0.72]],"fill":"#bfe8e2","w":0,"line":""},{"kind":"oval","box":[0.31,0.55,0.37,0.61],"fill":"#34827d","w":0,"line":""},{"kind":"oval","box":[0.43,0.53,0.49,0.59],"fill":"#34827d","w":0,"line":""},{"kind":"oval","box":[0.53,0.57,0.59,0.63],"fill":"#34827d","w":0,"line":""},{"kind":"oval","box":[0.86,0.11,0.92,0.17],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.8895,0.1265,0.9195,0.1565],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.903,0.1295,0.9105,0.137],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.92,0.19],[0.96,0.18]],"w":1.4}],"anky":[{"kind":"oval","box":[0.2,0.7,0.34,0.94],"fill":"#76603c","w":2.2},{"kind":"oval","box":[0.56,0.7,0.7,0.94],"fill":"#76603c","w":2.2},{"kind":"poly","pts":[[0.14,0.7],[0.22,0.56],[0.4,0.48],[0.6,0.48],[0.76,0.56],[0.84,0.66],[0.86,0.76],[0.7,0.82],[0.4,0.84],[0.22,0.8]],"fill":"#9a7b4f","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.16,0.7],[0.08,0.7],[0.04,0.66],[0.06,0.78],[0.16,0.78]],"fill":"#9a7b4f","w":2.2},{"kind":"oval","box":[0.0,0.62,0.18,0.82],"fill":"#76603c","w":2.2},{"kind":"poly","pts":[[0.01,0.66],[-0.03,0.62],[0.04,0.63]],"fill":"#e9dfc4","w":1.6},{"kind":"poly","pts":[[0.01,0.8],[-0.03,0.83],[0.04,0.79]],"fill":"#e9dfc4","w":1.6},{"kind":"poly","pts":[[0.23,0.59],[0.28,0.45],[0.33,0.59]],"fill":"#e9dfc4","w":1.8},{"kind":"poly","pts":[[0.35,0.54],[0.4,0.4],[0.45,0.54]],"fill":"#e9dfc4","w":1.8},{"kind":"poly","pts":[[0.47,0.54],[0.52,0.4],[0.57,0.54]],"fill":"#e9dfc4","w":1.8},{"kind":"poly","pts":[[0.59,0.58],[0.64,0.44],[0.69,0.58]],"fill":"#e9dfc4","w":1.8},{"kind":"oval","box":[0.26,0.605,0.34,0.675],"fill":"#76603c","w":1.2},{"kind":"oval","box":[0.38,0.585,0.46,0.655],"fill":"#76603c","w":1.2},{"kind":"oval","box":[0.5,0.585,0.58,0.655],"fill":"#76603c","w":1.2},{"kind":"oval","box":[0.62,0.625,0.7,0.695],"fill":"#76603c","w":1.2},{"kind":"oval","box":[0.32,0.685,0.4,0.755],"fill":"#76603c","w":1.2},{"kind":"oval","box":[0.46,0.685,0.54,0.755],"fill":"#76603c","w":1.2},{"kind":"poly","pts":[[0.8,0.62],[0.9,0.58],[0.98,0.64],[0.96,0.74],[0.84,0.76],[0.78,0.7]],"fill":"#9a7b4f","w":2.2,"smooth":true},{"kind":"oval","box":[0.22,0.7,0.38,0.95],"fill":"#9a7b4f","w":2.2},{"kind":"oval","box":[0.54,0.7,0.72,0.95],"fill":"#9a7b4f","w":2.2},{"kind":"oval","box":[0.2,0.91,0.4,0.97],"fill":"#76603c","w":1.6},{"kind":"oval","box":[0.52,0.91,0.74,0.97],"fill":"#76603c","w":1.6},{"kind":"oval","box":[0.87,0.62,0.93,0.68],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.8995,0.6365,0.9295,0.6665],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.913,0.6395,0.9205,0.647],"fill":"#ffffff","w":0,"line":""}],"raptor":[{"kind":"oval","box":[0.46,0.54,0.62,0.78],"fill":"#6e4fa0","w":2.2},{"kind":"poly","pts":[[0.52,0.76],[0.6,0.74],[0.61,0.88],[0.7,0.94],[0.48,0.94],[0.54,0.88]],"fill":"#6e4fa0","w":2.2},{"kind":"poly","pts":[[0.02,0.54],[0.14,0.54],[0.28,0.52],[0.42,0.46],[0.54,0.4],[0.62,0.32],[0.68,0.24],[0.8,0.22],[0.95,0.27],[0.96,0.33],[0.86,0.36],[0.76,0.38],[0.7,0.46],[0.66,0.56],[0.6,0.66],[0.5,0.7],[0.38,0.68],[0.24,0.6],[0.12,0.58]],"fill":"#8e6bbf","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.42,0.68],[0.54,0.7],[0.62,0.64],[0.66,0.54],[0.58,0.58],[0.5,0.62]],"fill":"#e6dcf5","w":0,"line":""},{"kind":"poly","pts":[[0.2,0.54],[0.3,0.47],[0.34,0.52],[0.24,0.6]],"fill":"#3fc2b3","w":0,"line":""},{"kind":"poly","pts":[[0.32,0.54],[0.42,0.47],[0.46,0.52],[0.36,0.6]],"fill":"#3fc2b3","w":0,"line":""},{"kind":"poly","pts":[[0.44,0.54],[0.54,0.47],[0.58,0.52],[0.48,0.6]],"fill":"#3fc2b3","w":0,"line":""},{"kind":"oval","box":[0.42,0.54,0.64,0.8],"fill":"#8e6bbf","w":2.2},{"kind":"poly","pts":[[0.48,0.76],[0.58,0.76],[0.6,0.88],[0.72,0.94],[0.46,0.94],[0.5,0.88]],"fill":"#8e6bbf","w":2.2},{"kind":"poly","pts":[[0.68,0.9],[0.78,0.87],[0.72,0.95]],"fill":"#fff4cf","w":1.4},{"kind":"poly","pts":[[0.66,0.48],[0.74,0.52],[0.78,0.58],[0.74,0.59],[0.7,0.55],[0.64,0.54]],"fill":"#8e6bbf","w":2.2},{"kind":"poly","pts":[[0.7,0.24],[0.62,0.18],[0.64,0.28]],"fill":"#f6a04d","w":1.6},{"kind":"poly","pts":[[0.76,0.22],[0.7,0.14],[0.7,0.24]],"fill":"#f6a04d","w":1.6},{"kind":"line","pts":[[0.76,0.36],[0.86,0.33],[0.94,0.32]],"w":1.5},{"kind":"oval","box":[0.756,0.246,0.824,0.314],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.7881,0.2647,0.8221,0.2987],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.8034,0.2681,0.8119,0.2766],"fill":"#ffffff","w":0,"line":""}],"para":[{"kind":"oval","box":[0.46,0.52,0.62,0.8],"fill":"#c08d22","w":2.2},{"kind":"poly","pts":[[0.48,0.8],[0.6,0.8],[0.62,0.89],[0.7,0.94],[0.46,0.94],[0.48,0.88]],"fill":"#c08d22","w":2.2},{"kind":"poly","pts":[[0.02,0.72],[0.14,0.66],[0.26,0.58],[0.38,0.46],[0.52,0.4],[0.6,0.4],[0.64,0.3],[0.7,0.22],[0.8,0.2],[0.92,0.24],[0.97,0.28],[0.96,0.33],[0.86,0.33],[0.78,0.34],[0.74,0.42],[0.72,0.54],[0.68,0.66],[0.62,0.75],[0.5,0.8],[0.38,0.78],[0.24,0.74],[0.12,0.76]],"fill":"#e8b53c","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.5,0.78],[0.62,0.74],[0.68,0.66],[0.7,0.56],[0.64,0.6],[0.56,0.68]],"fill":"#fbe7a8","w":0,"line":""},{"kind":"poly","pts":[[0.74,0.2],[0.62,0.08],[0.44,0.06],[0.38,0.1],[0.5,0.14],[0.62,0.2],[0.72,0.3]],"fill":"#4aae6a","w":2.0,"smooth":true},{"kind":"oval","box":[0.42,0.54,0.66,0.84],"fill":"#e8b53c","w":2.2},{"kind":"poly","pts":[[0.46,0.82],[0.62,0.82],[0.64,0.89],[0.74,0.94],[0.44,0.94],[0.46,0.89]],"fill":"#e8b53c","w":2.2},{"kind":"poly","pts":[[0.7,0.56],[0.78,0.6],[0.82,0.66],[0.78,0.68],[0.74,0.64],[0.68,0.62]],"fill":"#e8b53c","w":2.2},{"kind":"oval","box":[0.798,0.218,0.862,0.282],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.8288,0.2356,0.8608,0.2676],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.8432,0.2388,0.8512,0.2468],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.9,0.32],[0.96,0.31]],"w":1.4}],"ptero":[{"kind":"poly","pts":[[0.44,0.46],[0.26,0.04],[0.14,0.3],[0.08,0.52],[0.26,0.5],[0.38,0.58]],"fill":"#bd7e4d","w":2.0},{"kind":"poly","pts":[[0.34,0.56],[0.22,0.66],[0.18,0.78],[0.3,0.7],[0.4,0.64]],"fill":"#b9674a","w":1.8},{"kind":"poly","pts":[[0.22,0.56],[0.4,0.52],[0.56,0.5],[0.66,0.44],[0.74,0.36],[0.78,0.44],[0.72,0.56],[0.6,0.64],[0.44,0.68],[0.3,0.66]],"fill":"#e88f86","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.7,0.42],[0.98,0.48],[0.98,0.51],[0.72,0.54]],"fill":"#f3b45a","w":1.8},{"kind":"poly","pts":[[0.7,0.36],[0.54,0.24],[0.6,0.4]],"fill":"#f3b45a","w":1.8},{"kind":"oval","box":[0.64,0.36,0.8,0.56],"fill":"#e88f86","w":2.2},{"kind":"poly","pts":[[0.54,0.52],[0.56,0.06],[0.36,0.24],[0.18,0.42],[0.04,0.58],[0.24,0.56],[0.4,0.62]],"fill":"#d1905a","w":2.2},{"kind":"line","pts":[[0.54,0.52],[0.56,0.08]],"w":1.6},{"kind":"line","pts":[[0.54,0.52],[0.36,0.24]],"w":1.4},{"kind":"line","pts":[[0.54,0.52],[0.18,0.44]],"w":1.4},{"kind":"poly","pts":[[0.46,0.66],[0.5,0.8],[0.56,0.8],[0.54,0.66]],"fill":"#f3b45a","w":1.6},{"kind":"oval","box":[0.69,0.39,0.75,0.45],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.7195,0.4065,0.7495,0.4365],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.733,0.4095,0.7405,0.417],"fill":"#ffffff","w":0,"line":""}],"plesio":[{"kind":"poly","pts":[[0.04,0.7],[0.14,0.64],[0.26,0.62],[0.36,0.56],[0.44,0.5],[0.5,0.4],[0.56,0.26],[0.64,0.16],[0.76,0.12],[0.86,0.16],[0.88,0.24],[0.8,0.24],[0.72,0.28],[0.68,0.4],[0.7,0.56],[0.66,0.66],[0.54,0.72],[0.4,0.74],[0.24,0.76],[0.12,0.76]],"fill":"#3b9bc4","w":2.2,"smooth":true},{"kind":"poly","pts":[[0.36,0.66],[0.54,0.72],[0.66,0.66],[0.66,0.58],[0.54,0.62]],"fill":"#bfe4f2","w":0,"line":""},{"kind":"poly","pts":[[0.38,0.64],[0.3,0.8],[0.46,0.78],[0.5,0.68]],"fill":"#2d7ba0","w":2.0},{"kind":"poly","pts":[[0.54,0.62],[0.5,0.84],[0.66,0.8],[0.66,0.66]],"fill":"#2d7ba0","w":2.0},{"kind":"oval","box":[0.75,0.15,0.81,0.21],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.7795,0.1665,0.8095,0.1965],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.793,0.1695,0.8005,0.177],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.8,0.24],[0.86,0.23]],"w":1.4},{"kind":"line","pts":[[0.02,0.76],[0.14,0.78],[0.28,0.76],[0.44,0.8],[0.6,0.77],[0.78,0.8],[0.96,0.77]],"w":2.4,"line":"#ffffff","smooth":true},{"kind":"line","pts":[[0.1,0.84],[0.24,0.86],[0.4,0.84],[0.58,0.87],[0.76,0.85]],"w":1.8,"line":"#d9f1fb","smooth":true}],"baby":[{"kind":"poly","pts":[[0.08,0.76],[0.02,0.7],[0.06,0.82],[0.2,0.84]],"fill":"#7ccf5a","w":2.0},{"kind":"oval","box":[0.18,0.4,0.7,0.9],"fill":"#7ccf5a","w":2.2},{"kind":"oval","box":[0.34,0.66,0.62,0.9],"fill":"#d9f2b5","w":0,"line":""},{"kind":"poly","pts":[[0.26,0.54],[0.3,0.46],[0.36,0.52],[0.42,0.44],[0.48,0.51],[0.54,0.44],[0.58,0.52]],"fill":"#58a63e","w":0,"line":""},{"kind":"poly","pts":[[0.16,0.76],[0.24,0.7],[0.28,0.78],[0.36,0.7],[0.42,0.8],[0.5,0.72],[0.56,0.82],[0.64,0.74],[0.72,0.78],[0.74,0.9],[0.6,0.96],[0.3,0.96],[0.16,0.9]],"fill":"#fff8e8","w":2.0},{"kind":"oval","box":[0.44,0.14,0.92,0.62],"fill":"#7ccf5a","w":2.2},{"kind":"oval","box":[0.7,0.36,0.94,0.58],"fill":"#d9f2b5","w":0,"line":""},{"kind":"poly","pts":[[0.54,0.16],[0.58,0.06],[0.64,0.16]],"fill":"#58a63e","w":1.8},{"kind":"poly","pts":[[0.66,0.14],[0.72,0.05],[0.76,0.16]],"fill":"#58a63e","w":1.8},{"kind":"oval","box":[0.572,0.282,0.688,0.398],"fill":"#ffffff","w":1.6},{"kind":"oval","box":[0.6197,0.3139,0.6777,0.3719],"fill":"#1b1b1b","w":0,"line":""},{"kind":"oval","box":[0.6458,0.3197,0.6603,0.3342],"fill":"#ffffff","w":0,"line":""},{"kind":"line","pts":[[0.8,0.52],[0.88,0.5]],"w":1.6},{"kind":"oval","box":[0.74,0.38,0.77,0.41],"fill":"#58a63e","w":0,"line":""},{"kind":"oval","box":[0.34,0.9,0.52,0.97],"fill":"#58a63e","w":1.6},{"kind":"oval","box":[0.52,0.9,0.7,0.97],"fill":"#58a63e","w":1.6}]},"thing":{"pine":{"w":1.5,"h":1.9,"prims":[{"kind":"poly","pts":[[0.44,0.8],[0.56,0.8],[0.56,0.99],[0.44,0.99]],"fill":"#7a4a2a","w":2.0},{"kind":"poly","pts":[[0.5,0.03],[0.3,0.34],[0.7,0.34]],"fill":"#2f8f4e","w":2.0},{"kind":"poly","pts":[[0.5,0.2],[0.22,0.58],[0.78,0.58]],"fill":"#36a057","w":2.0},{"kind":"poly","pts":[[0.5,0.38],[0.14,0.84],[0.86,0.84]],"fill":"#3fb062","w":2.0},{"kind":"line","pts":[[0.34,0.62],[0.5,0.52]],"w":1.4,"line":"#2f8f4e"}]},"oak":{"w":1.5,"h":1.7,"prims":[{"kind":"poly","pts":[[0.43,0.6],[0.57,0.6],[0.6,0.99],[0.4,0.99]],"fill":"#7a4a2a","w":2.0},{"kind":"oval","box":[0.06,0.22,0.52,0.66],"fill":"#4faa44","w":2.2},{"kind":"oval","box":[0.44,0.2,0.94,0.66],"fill":"#4faa44","w":2.2},{"kind":"oval","box":[0.2,0.02,0.8,0.52],"fill":"#5cc050","w":2.2},{"kind":"oval","box":[0.3,0.14,0.5,0.3],"fill":"#7bd96c","w":0,"line":""},{"kind":"oval","box":[0.62,0.36,0.78,0.5],"fill":"#3f9138","w":0,"line":""}]},"dead":{"w":1.4,"h":1.6,"prims":[{"kind":"poly","pts":[[0.42,0.99],[0.46,0.6],[0.4,0.38],[0.46,0.4],[0.52,0.56],[0.58,0.4],[0.56,0.3],[0.62,0.34],[0.64,0.5],[0.58,0.66],[0.6,0.99]],"fill":"#5a463c","w":2.0},{"kind":"line","pts":[[0.44,0.52],[0.24,0.36],[0.14,0.22]],"w":3.0,"line":"#5a463c"},{"kind":"line","pts":[[0.24,0.36],[0.14,0.4]],"w":2.2,"line":"#5a463c"},{"kind":"line","pts":[[0.6,0.44],[0.78,0.26],[0.86,0.14]],"w":3.0,"line":"#5a463c"},{"kind":"line","pts":[[0.78,0.26],[0.88,0.3]],"w":2.2,"line":"#5a463c"}]},"cactus":{"w":1.3,"h":1.7,"prims":[{"kind":"poly","pts":[[0.4,0.98],[0.4,0.22],[0.46,0.08],[0.56,0.08],[0.62,0.22],[0.62,0.98]],"fill":"#4aa05a","w":2.2},{"kind":"poly","pts":[[0.4,0.62],[0.24,0.62],[0.22,0.4],[0.28,0.4],[0.3,0.54],[0.4,0.54]],"fill":"#4aa05a","w":2.2},{"kind":"poly","pts":[[0.62,0.5],[0.78,0.5],[0.8,0.28],[0.74,0.28],[0.72,0.42],[0.62,0.42]],"fill":"#4aa05a","w":2.2},{"kind":"line","pts":[[0.51,0.14],[0.51,0.92]],"w":1.2,"line":"#2f7a3e"},{"kind":"line","pts":[[0.45,0.2],[0.45,0.9]],"w":1.0,"line":"#2f7a3e"},{"kind":"line","pts":[[0.57,0.2],[0.57,0.9]],"w":1.0,"line":"#2f7a3e"},{"kind":"oval","box":[0.46,0.04,0.56,0.12],"fill":"#f26b8a","w":1.2}]},"palm":{"w":1.9,"h":2.1,"prims":[{"kind":"poly","pts":[[0.46,0.99],[0.49,0.7],[0.52,0.44],[0.62,0.22],[0.66,0.22],[0.58,0.46],[0.56,0.7],[0.58,0.99]],"fill":"#a9743c","w":2.0},{"kind":"line","pts":[[0.52,0.8],[0.58,0.78]],"w":1.2,"line":"#7a4a2a"},{"kind":"line","pts":[[0.51,0.64],[0.57,0.62]],"w":1.2,"line":"#7a4a2a"},{"kind":"line","pts":[[0.53,0.5],[0.59,0.48]],"w":1.2,"line":"#7a4a2a"},{"kind":"poly","pts":[[0.64,0.22],[0.4,0.06],[0.14,0.14],[0.3,0.14],[0.46,0.2]],"fill":"#3fa956","w":1.8,"smooth":true},{"kind":"poly","pts":[[0.64,0.22],[0.88,0.04],[0.98,0.16],[0.82,0.12],[0.7,0.24]],"fill":"#3fa956","w":1.8,"smooth":true},{"kind":"poly","pts":[[0.64,0.22],[0.84,0.22],[0.98,0.38],[0.8,0.32],[0.66,0.28]],"fill":"#3fa956","w":1.8,"smooth":true},{"kind":"poly","pts":[[0.64,0.22],[0.44,0.26],[0.22,0.4],[0.42,0.34],[0.6,0.28]],"fill":"#3fa956","w":1.8,"smooth":true},{"kind":"poly","pts":[[0.64,0.22],[0.56,0.0],[0.64,0.04],[0.7,0.18]],"fill":"#55c06c","w":1.8},{"kind":"oval","box":[0.58,0.22,0.66,0.3],"fill":"#7a4a2a","w":1.4},{"kind":"oval","box":[0.65,0.24,0.72,0.31],"fill":"#7a4a2a","w":1.4}]},"rock":{"w":1.2,"h":0.95,"prims":[{"kind":"poly","pts":[[0.06,0.92],[0.04,0.7],[0.14,0.46],[0.34,0.28],[0.58,0.24],[0.8,0.38],[0.94,0.62],[0.96,0.9]],"fill":"#a9a9b0","w":2.4,"smooth":true},{"kind":"poly","pts":[[0.18,0.56],[0.34,0.36],[0.56,0.32],[0.46,0.46],[0.3,0.62]],"fill":"#c9c9d0","w":0,"line":""},{"kind":"poly","pts":[[0.62,0.92],[0.78,0.7],[0.92,0.8],[0.92,0.92]],"fill":"#85858c","w":0,"line":""},{"kind":"line","pts":[[0.4,0.7],[0.5,0.84]],"w":1.6,"line":"#85858c"}]},"rock_dark":{"w":1.2,"h":0.95,"prims":[{"kind":"poly","pts":[[0.06,0.92],[0.04,0.7],[0.14,0.46],[0.34,0.28],[0.58,0.24],[0.8,0.38],[0.94,0.62],[0.96,0.9]],"fill":"#5d5558","w":2.4,"smooth":true},{"kind":"poly","pts":[[0.18,0.56],[0.34,0.36],[0.56,0.32],[0.46,0.46],[0.3,0.62]],"fill":"#7a7074","w":0,"line":""},{"kind":"poly","pts":[[0.62,0.92],[0.78,0.7],[0.92,0.8],[0.92,0.92]],"fill":"#443d40","w":0,"line":""},{"kind":"line","pts":[[0.4,0.7],[0.5,0.84]],"w":1.6,"line":"#443d40"}]},"rock_sand":{"w":1.2,"h":0.95,"prims":[{"kind":"poly","pts":[[0.06,0.92],[0.04,0.7],[0.14,0.46],[0.34,0.28],[0.58,0.24],[0.8,0.38],[0.94,0.62],[0.96,0.9]],"fill":"#c9a45e","w":2.4,"smooth":true},{"kind":"poly","pts":[[0.18,0.56],[0.34,0.36],[0.56,0.32],[0.46,0.46],[0.3,0.62]],"fill":"#e0c283","w":0,"line":""},{"kind":"poly","pts":[[0.62,0.92],[0.78,0.7],[0.92,0.8],[0.92,0.92]],"fill":"#a58443","w":0,"line":""},{"kind":"line","pts":[[0.4,0.7],[0.5,0.84]],"w":1.6,"line":"#a58443"}]},"tower":{"w":1.5,"h":2.6,"prims":[{"kind":"poly","pts":[[0.26,0.99],[0.28,0.38],[0.72,0.38],[0.74,0.99]],"fill":"#b9b4a8","w":2.2},{"kind":"poly","pts":[[0.5,0.38],[0.72,0.38],[0.74,0.99],[0.5,0.99]],"fill":"#9d988c","w":0,"line":""},{"kind":"poly","pts":[[0.24,0.4],[0.5,0.04],[0.76,0.4]],"fill":"#d6513e","w":2.2},{"kind":"poly","pts":[[0.5,0.04],[0.76,0.4],[0.6,0.4]],"fill":"#b13e2d","w":0,"line":""},{"kind":"line","pts":[[0.5,0.04],[0.5,-0.08]],"w":1.8},{"kind":"poly","pts":[[0.5,-0.08],[0.66,-0.03],[0.5,0.02]],"fill":"#f6c031","w":1.4},{"kind":"poly","pts":[[0.44,0.52],[0.56,0.52],[0.56,0.66],[0.44,0.66]],"fill":"#35302c","w":1.6},{"kind":"line","pts":[[0.28,0.8],[0.72,0.8]],"w":1.2,"line":"#8d887c"},{"kind":"line","pts":[[0.28,0.62],[0.72,0.62]],"w":1.2,"line":"#8d887c"}]},"keep1":{"w":2.3,"h":2.0,"prims":[{"kind":"poly","pts":[[0.08,0.99],[0.08,0.3],[0.92,0.3],[0.92,0.99]],"fill":"#c6bfae","w":2.4},{"kind":"poly","pts":[[0.5,0.3],[0.92,0.3],[0.92,0.99],[0.5,0.99]],"fill":"#a8a190","w":0,"line":""},{"kind":"poly","pts":[[0.02,0.34],[0.5,0.02],[0.98,0.34]],"fill":"#c9483a","w":2.4},{"kind":"poly","pts":[[0.5,0.02],[0.98,0.34],[0.7,0.34]],"fill":"#a63a2e","w":0,"line":""},{"kind":"poly","pts":[[0.4,0.99],[0.4,0.76],[0.5,0.66],[0.6,0.76],[0.6,0.99]],"fill":"#6b4428","w":2.0},{"kind":"poly","pts":[[0.18,0.44],[0.3,0.44],[0.3,0.6],[0.18,0.6]],"fill":"#3a4a6a","w":1.6},{"kind":"poly","pts":[[0.7,0.44],[0.82,0.44],[0.82,0.6],[0.7,0.6]],"fill":"#3a4a6a","w":1.6},{"kind":"line","pts":[[0.08,0.84],[0.92,0.84]],"w":1.2,"line":"#8d887c"},{"kind":"line","pts":[[0.08,0.7],[0.92,0.7]],"w":1.2,"line":"#8d887c"},{"kind":"line","pts":[[0.5,0.02],[0.5,-0.1]],"w":1.8},{"kind":"poly","pts":[[0.5,-0.1],[0.68,-0.04],[0.5,0.01]],"fill":"#3b82d6","w":1.4}]},"keep2":{"w":2.3,"h":3.0,"prims":[{"kind":"poly","pts":[[0.08,0.99],[0.08,0.36],[0.92,0.36],[0.92,0.99]],"fill":"#c6bfae","w":2.4},{"kind":"poly","pts":[[0.5,0.36],[0.92,0.36],[0.92,0.99],[0.5,0.99]],"fill":"#a8a190","w":0,"line":""},{"kind":"poly","pts":[[0.02,0.4],[0.5,0.02],[0.98,0.4]],"fill":"#c9483a","w":2.4},{"kind":"poly","pts":[[0.5,0.02],[0.98,0.4],[0.7,0.4]],"fill":"#a63a2e","w":0,"line":""},{"kind":"poly","pts":[[0.4,0.99],[0.4,0.76],[0.5,0.66],[0.6,0.76],[0.6,0.99]],"fill":"#6b4428","w":2.0},{"kind":"poly","pts":[[0.18,0.5],[0.3,0.5],[0.3,0.66],[0.18,0.66]],"fill":"#3a4a6a","w":1.6},{"kind":"poly","pts":[[0.7,0.5],[0.82,0.5],[0.82,0.66],[0.7,0.66]],"fill":"#3a4a6a","w":1.6},{"kind":"line","pts":[[0.08,0.84],[0.92,0.84]],"w":1.2,"line":"#8d887c"},{"kind":"line","pts":[[0.08,0.76],[0.92,0.76]],"w":1.2,"line":"#8d887c"},{"kind":"line","pts":[[0.5,0.02],[0.5,-0.1]],"w":1.8},{"kind":"poly","pts":[[0.5,-0.1],[0.68,-0.04],[0.5,0.01]],"fill":"#3b82d6","w":1.4}]},"volcano":{"w":3.4,"h":3.4,"prims":[{"kind":"poly","pts":[[0.0,0.99],[0.22,0.44],[0.34,0.26],[0.66,0.26],[0.78,0.44],[1.0,0.99]],"fill":"#6b5048","w":2.6},{"kind":"poly","pts":[[0.5,0.26],[0.66,0.26],[0.78,0.44],[1.0,0.99],[0.62,0.99]],"fill":"#58403a","w":0,"line":""},{"kind":"poly","pts":[[0.34,0.26],[0.4,0.18],[0.6,0.18],[0.66,0.26],[0.5,0.32]],"fill":"#ff8a1e","w":2.2},{"kind":"poly","pts":[[0.4,0.22],[0.5,0.16],[0.6,0.22],[0.5,0.28]],"fill":"#ffd34e","w":0,"line":""},{"kind":"poly","pts":[[0.48,0.3],[0.44,0.52],[0.5,0.7],[0.46,0.99],[0.56,0.99],[0.58,0.66],[0.52,0.48],[0.54,0.32]],"fill":"#ff7a18","w":1.6},{"kind":"poly","pts":[[0.3,0.4],[0.36,0.58],[0.32,0.8],[0.38,0.99],[0.3,0.99],[0.24,0.7]],"fill":"#ff9a2e","w":0,"line":""},{"kind":"oval","box":[0.42,0.02,0.58,0.16],"fill":"#cfc7c4","w":1.4},{"kind":"oval","box":[0.52,-0.08,0.7,0.06],"fill":"#e3dcd9","w":1.4}]},"wall":{"w":1.0,"h":1.5,"prims":[{"kind":"poly","pts":[[0.0,0.0],[1.0,0.0],[1.0,0.667],[0.0,0.667]],"fill":"#cfc9b9","w":0,"line":""},{"kind":"poly","pts":[[0.0,0.667],[1.0,0.667],[1.0,1.0],[0.0,1.0]],"fill":"#9f998a","w":0,"line":""},{"kind":"line","pts":[[0.0,0.667],[1.0,0.667]],"w":1.6,"line":"#6f6a5e"},{"kind":"line","pts":[[0.0,0.99],[1.0,0.99]],"w":2.2,"line":"#4a463e"},{"kind":"line","pts":[[0.0,0.83],[1.0,0.83]],"w":1.0,"line":"#6f6a5e"},{"kind":"line","pts":[[0.34,0.667],[0.34,0.83]],"w":1.0,"line":"#6f6a5e"},{"kind":"line","pts":[[0.7,0.83],[0.7,0.99]],"w":1.0,"line":"#6f6a5e"},{"kind":"line","pts":[[0.14,0.22],[0.86,0.22]],"w":1.0,"line":"#b0aa9a"},{"kind":"line","pts":[[0.14,0.46],[0.86,0.46]],"w":1.0,"line":"#b0aa9a"}]},"bridge":{"w":1.0,"h":1.0,"prims":[{"kind":"poly","pts":[[0.0,0.06],[1.0,0.06],[1.0,0.94],[0.0,0.94]],"fill":"#a8743c","w":0,"line":""},{"kind":"line","pts":[[0.0,0.2],[1.0,0.2]],"w":1.6,"line":"#6b4428"},{"kind":"line","pts":[[0.0,0.36],[1.0,0.36]],"w":1.6,"line":"#6b4428"},{"kind":"line","pts":[[0.0,0.52],[1.0,0.52]],"w":1.6,"line":"#6b4428"},{"kind":"line","pts":[[0.0,0.68],[1.0,0.68]],"w":1.6,"line":"#6b4428"},{"kind":"line","pts":[[0.0,0.84],[1.0,0.84]],"w":1.6,"line":"#6b4428"},{"kind":"line","pts":[[0.0,0.06],[1.0,0.06]],"w":3.2,"line":"#5a3a1e"},{"kind":"line","pts":[[0.0,0.94],[1.0,0.94]],"w":3.2,"line":"#5a3a1e"}]}},"ground":{"tuft":[[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#3f8f2e"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#3f8f2e"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#3f8f2e"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#3f8f2e"}]],"tuft_sand":[[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#b08d3c"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#b08d3c"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#b08d3c"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#b08d3c"}]],"tuft_ash":[[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#4e433f"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#4e433f"}],[{"kind":"line","pts":[[0.2,0.8],[0.14,0.4]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.5,0.84],[0.5,0.28]],"w":2.2,"line":"#4e433f"},{"kind":"line","pts":[[0.8,0.8],[0.88,0.42]],"w":2.2,"line":"#4e433f"}]],"flower":[[{"kind":"oval","box":[0.36,0.08,0.64,0.38],"fill":"#ff6f91","w":1.0},{"kind":"oval","box":[0.36,0.62,0.64,0.92],"fill":"#ff6f91","w":1.0},{"kind":"oval","box":[0.08,0.36,0.38,0.64],"fill":"#ff6f91","w":1.0},{"kind":"oval","box":[0.62,0.36,0.92,0.64],"fill":"#ff6f91","w":1.0},{"kind":"oval","box":[0.38,0.38,0.62,0.62],"fill":"#ffb703","w":1.0}],[{"kind":"oval","box":[0.36,0.08,0.64,0.38],"fill":"#ffd23f","w":1.0},{"kind":"oval","box":[0.36,0.62,0.64,0.92],"fill":"#ffd23f","w":1.0},{"kind":"oval","box":[0.08,0.36,0.38,0.64],"fill":"#ffd23f","w":1.0},{"kind":"oval","box":[0.62,0.36,0.92,0.64],"fill":"#ffd23f","w":1.0},{"kind":"oval","box":[0.38,0.38,0.62,0.62],"fill":"#ffb703","w":1.0}],[{"kind":"oval","box":[0.36,0.08,0.64,0.38],"fill":"#ffffff","w":1.0},{"kind":"oval","box":[0.36,0.62,0.64,0.92],"fill":"#ffffff","w":1.0},{"kind":"oval","box":[0.08,0.36,0.38,0.64],"fill":"#ffffff","w":1.0},{"kind":"oval","box":[0.62,0.36,0.92,0.64],"fill":"#ffffff","w":1.0},{"kind":"oval","box":[0.38,0.38,0.62,0.62],"fill":"#ffb703","w":1.0}]],"pebble":[[{"kind":"oval","box":[0.1,0.4,0.56,0.8],"fill":"#b4aca8","w":1.4},{"kind":"oval","box":[0.52,0.52,0.9,0.84],"fill":"#9d948f","w":1.4}],[{"kind":"oval","box":[0.1,0.4,0.56,0.8],"fill":"#b4aca8","w":1.4},{"kind":"oval","box":[0.52,0.52,0.9,0.84],"fill":"#9d948f","w":1.4}],[{"kind":"oval","box":[0.1,0.4,0.56,0.8],"fill":"#b4aca8","w":1.4},{"kind":"oval","box":[0.52,0.52,0.9,0.84],"fill":"#9d948f","w":1.4}]],"shell":[[{"kind":"poly","pts":[[0.5,0.9],[0.1,0.5],[0.24,0.22],[0.5,0.12],[0.76,0.22],[0.9,0.5]],"fill":"#f9d5cf","w":1.6},{"kind":"line","pts":[[0.5,0.9],[0.5,0.16]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.28,0.24]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.72,0.24]],"w":1.2,"line":"#d99a90"}],[{"kind":"poly","pts":[[0.5,0.9],[0.1,0.5],[0.24,0.22],[0.5,0.12],[0.76,0.22],[0.9,0.5]],"fill":"#f9d5cf","w":1.6},{"kind":"line","pts":[[0.5,0.9],[0.5,0.16]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.28,0.24]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.72,0.24]],"w":1.2,"line":"#d99a90"}],[{"kind":"poly","pts":[[0.5,0.9],[0.1,0.5],[0.24,0.22],[0.5,0.12],[0.76,0.22],[0.9,0.5]],"fill":"#f9d5cf","w":1.6},{"kind":"line","pts":[[0.5,0.9],[0.5,0.16]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.28,0.24]],"w":1.2,"line":"#d99a90"},{"kind":"line","pts":[[0.5,0.9],[0.72,0.24]],"w":1.2,"line":"#d99a90"}]],"bone":[[{"kind":"line","pts":[[0.18,0.62],[0.82,0.38]],"w":5.0,"line":"#ffffff"},{"kind":"oval","box":[0.06,0.52,0.24,0.7],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.1,0.62,0.28,0.78],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.72,0.24,0.9,0.42],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.78,0.34,0.96,0.5],"fill":"#ffffff","w":1.2}],[{"kind":"line","pts":[[0.18,0.62],[0.82,0.38]],"w":5.0,"line":"#ffffff"},{"kind":"oval","box":[0.06,0.52,0.24,0.7],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.1,0.62,0.28,0.78],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.72,0.24,0.9,0.42],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.78,0.34,0.96,0.5],"fill":"#ffffff","w":1.2}],[{"kind":"line","pts":[[0.18,0.62],[0.82,0.38]],"w":5.0,"line":"#ffffff"},{"kind":"oval","box":[0.06,0.52,0.24,0.7],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.1,0.62,0.28,0.78],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.72,0.24,0.9,0.42],"fill":"#ffffff","w":1.2},{"kind":"oval","box":[0.78,0.34,0.96,0.5],"fill":"#ffffff","w":1.2}]],"wave":[[{"kind":"line","pts":[[0.06,0.55],[0.26,0.38],[0.5,0.55],[0.74,0.38],[0.94,0.55]],"w":2.0,"line":"#ffffff","smooth":true}],[{"kind":"line","pts":[[0.06,0.55],[0.26,0.38],[0.5,0.55],[0.74,0.38],[0.94,0.55]],"w":2.0,"line":"#ffffff","smooth":true}],[{"kind":"line","pts":[[0.06,0.55],[0.26,0.38],[0.5,0.55],[0.74,0.38],[0.94,0.55]],"w":2.0,"line":"#ffffff","smooth":true}]],"bubble":[[{"kind":"oval","box":[0.24,0.24,0.72,0.72],"fill":"#ffb347","w":2.0,"line":"#fff1b0"},{"kind":"oval","box":[0.4,0.38,0.54,0.5],"fill":"#fff1b0","w":0,"line":""}],[{"kind":"oval","box":[0.24,0.24,0.72,0.72],"fill":"#ffb347","w":2.0,"line":"#fff1b0"},{"kind":"oval","box":[0.4,0.38,0.54,0.5],"fill":"#fff1b0","w":0,"line":""}],[{"kind":"oval","box":[0.24,0.24,0.72,0.72],"fill":"#ffb347","w":2.0,"line":"#fff1b0"},{"kind":"oval","box":[0.4,0.38,0.54,0.5],"fill":"#fff1b0","w":0,"line":""}]],"swirl":[[{"kind":"line","pts":[[0.5,0.5],[0.6,0.48],[0.62,0.58],[0.48,0.64],[0.36,0.54],[0.4,0.36],[0.6,0.28],[0.8,0.4],[0.78,0.64],[0.56,0.82]],"w":2.0,"line":"#b88a3a","smooth":true}],[{"kind":"line","pts":[[0.5,0.5],[0.6,0.48],[0.62,0.58],[0.48,0.64],[0.36,0.54],[0.4,0.36],[0.6,0.28],[0.8,0.4],[0.78,0.64],[0.56,0.82]],"w":2.0,"line":"#b88a3a","smooth":true}],[{"kind":"line","pts":[[0.5,0.5],[0.6,0.48],[0.62,0.58],[0.48,0.64],[0.36,0.54],[0.4,0.36],[0.6,0.28],[0.8,0.4],[0.78,0.64],[0.56,0.82]],"w":2.0,"line":"#b88a3a","smooth":true}]]}}'''
# ART-END
DW_ART = json.loads(DW_ART_JSON)


# *************** DEL 12 - THE PICTURES: DRAWING THE WORLD AND THE DINOSAURS (Pillow) *****************
# The same shapes and the same drawing order as the phone (dw_render.js).  Tk's canvas cannot rotate, fade or clip a picture,
# so a whole frame is painted with Pillow into one image and shown on the canvas.  Every picture is painted once at 3 times the
# size and shrunk (smooth edges) and kept in a cache; a frame is only the pasting of cached pictures + a few small effects.
DW_INK = "#3e2723"
DW_PAL = {
    "castle":  {"g1": "#93d75f", "g2": "#89cd56", "sand": "#f1dc9d", "water": "#4aa8e0", "halo": "#9bddf5", "frame": "#2e5d2b"},
    "nature":  {"g1": "#83cd55", "g2": "#7ac34d", "sand": "#f1dc9d", "water": "#4aa8e0", "halo": "#9bddf5", "frame": "#2b4f28"},
    "island":  {"g1": "#93d75f", "g2": "#89cd56", "sand": "#f4e0a2", "water": "#37a2d8", "halo": "#84d3ee", "frame": "#2a77a8"},
    "volcano": {"g1": "#7d6d68", "g2": "#736360", "sand": "#8d7b74", "water": "#4aa8e0", "halo": "#9bddf5", "frame": "#2f2624"},
    "desert":  {"g1": "#efd58c", "g2": "#e8ca7b", "sand": "#f4e2a8", "water": "#42b2de", "halo": "#8fdcf0", "frame": "#8d6e30"},
}
DW_TERRAIN = {"q": "#d8b35d", "qHalo": "#c79f48", "lava": "#ff7a1a", "lavaHalo": "#8c3220", "lavaIn": "#ffc53a",
              "chasm": "#43362f", "chasmRim": "#9b8a7e", "chasmIn": "#241b19"}
DW_SPR = {}          # cache of painted pictures: (key, w, h, flipped) -> {"img", "pad", "w", "h"}
DW_SS = 3            # painted at this many times the size, then shrunk


def _hex(c):
    return (int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16))


def _mix(c, other, a):
    """Colour c with a part a (0..1) of colour `other` mixed in."""
    return tuple(int(round(c[i] * (1 - a) + other[i] * a)) for i in range(3))


def dw_smooth(pts, closed, steps=6):
    """Catmull-Rom curve through the points (the 'smooth' flag of a shape)."""
    n = len(pts)
    if n < 3:
        return list(pts)
    seq = ([pts[n - 1]] + list(pts) + [pts[0], pts[1]]) if closed else ([pts[0]] + list(pts) + [pts[n - 1]])
    out = []
    for i in range(len(seq) - 3):
        p0, p1, p2, p3 = seq[i], seq[i + 1], seq[i + 2], seq[i + 3]
        for s in range(steps):
            t = s / float(steps)
            t2 = t * t
            t3 = t2 * t
            out.append([0.5 * ((2 * p1[k]) + (-p0[k] + p2[k]) * t + (2 * p0[k] - 5 * p1[k] + 4 * p2[k] - p3[k]) * t2
                               + (-p0[k] + 3 * p1[k] - 3 * p2[k] + p3[k]) * t3) for k in (0, 1)])
    if not closed:
        out.append(list(pts[n - 1]))
    return out


def dw_draw_prims(dr, prims, x0, y0, w, h, flip, k):
    """Paint a list of shapes (unit coordinates, y down) into the box x0,y0,w,h.  k = the painting is k times bigger than the result."""
    base = min(w, h) / float(k)
    for pr in prims:
        kind = pr["kind"]
        pw = pr.get("w", 2)
        lw = 0 if pw <= 0 else max(1, int(round(pw * base / 100.0)))
        line_col = pr["line"] if "line" in pr else DW_INK
        stroke = line_col if (lw > 0 and line_col) else ""
        lws = lw * k
        fill = pr.get("fill", "") or None

        def f(p):
            return (x0 + ((1 - p[0]) if flip else p[0]) * w, y0 + p[1] * h)
        if kind in ("poly", "line"):
            pts = pr["pts"]
            if len(pts) < 2:
                continue
            if pr.get("smooth") and len(pts) >= 3:
                pts = dw_smooth(pts, kind == "poly")
            q = [f(p) for p in pts]
            if kind == "poly":
                if fill:
                    dr.polygon(q, fill=fill)
                if stroke:
                    dr.line(q + [q[0], q[1]], fill=stroke, width=lws, joint="curve")
            elif stroke:
                dr.line(q, fill=stroke, width=lws, joint="curve")
                r = lws / 2.0
                for (px, py) in (q[0], q[-1]):                       # round line ends
                    dr.ellipse((px - r, py - r, px + r, py + r), fill=stroke)
        elif kind == "oval":
            a = f(pr["box"][:2])
            b = f(pr["box"][2:])
            box = [min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1])]
            if fill:
                dr.ellipse(box, fill=fill)
            if stroke:
                r = lws / 2.0
                dr.ellipse([box[0] - r, box[1] - r, box[2] + r, box[3] + r], outline=stroke, width=lws)


def dw_sprite(key, prims, w, h, flip=False):
    """A picture painted once (with a margin for tails and flags) and kept."""
    w = max(1, int(round(w)))
    h = max(1, int(round(h)))
    ck = (key, w, h, bool(flip))
    s = DW_SPR.get(ck)
    if s:
        return s
    k = DW_SS
    pad = int(math.ceil(max(w, h) * 0.14))
    W, H = w + 2 * pad, h + 2 * pad
    img = Image.new("RGBA", (W * k, H * k), _hex(DW_INK) + (0,))
    dr = ImageDraw.Draw(img)
    dw_draw_prims(dr, prims, pad * k, pad * k, w * k, h * k, flip, k)
    img = img.resize((W, H), Image.LANCZOS)
    s = {"img": img, "pad": pad, "w": w, "h": h}
    DW_SPR[ck] = s
    return s


def dw_forget_sprites():
    DW_SPR.clear()


def dw_put(frame, spr, x, y, rot=0.0, sc=1.0, alpha=1.0, clip_bottom=None):
    """Paste a picture so that its feet point (the bottom middle of its box) lands on x, y - turned by rot radians (clockwise), scaled, faded,
    and cut off below clip_bottom (the dinosaur that sinks)."""
    img = spr["img"]
    ax = spr["pad"] + spr["w"] / 2.0
    ay = spr["pad"] + spr["h"] * 0.95
    if sc != 1.0:
        nw = max(1, int(round(img.width * sc)))
        nh = max(1, int(round(img.height * sc)))
        img = img.resize((nw, nh), Image.BILINEAR)
        ax *= sc
        ay *= sc
    if abs(rot) > 0.004:
        r = int(math.ceil(math.hypot(max(ax, img.width - ax), max(ay, img.height - ay)))) + 2
        big = Image.new("RGBA", (2 * r, 2 * r), _hex(DW_INK) + (0,))
        big.paste(img, (int(round(r - ax)), int(round(r - ay))))
        img = big.rotate(-math.degrees(rot), resample=Image.BICUBIC)
        ax = ay = r
    if alpha < 0.999:
        a = img.getchannel("A").point(lambda v: int(v * alpha))
        img = img.copy()
        img.putalpha(a)
    px = int(round(x - ax))
    py = int(round(y - ay))
    if clip_bottom is not None:
        keep = int(round(clip_bottom)) - py
        if keep <= 0:
            return
        if keep < img.height:
            img = img.crop((0, 0, img.width, keep))
    frame.paste(img, (px, py), img)


# ---- small effects: painted on a patch at 3x, shrunk, blended on the frame ----
class DwPatch(object):
    """A transparent square where one effect is painted with world coordinates (pixels of the frame); put() blends it in."""

    def __init__(self, cx, cy, rx, ry, k=3):
        self.x0 = int(math.floor(cx - rx)) - 1
        self.y0 = int(math.floor(cy - ry)) - 1
        self.w = int(math.ceil(2 * rx)) + 3
        self.h = int(math.ceil(2 * ry)) + 3
        self.k = k
        self.img = Image.new("RGBA", (self.w * k, self.h * k), (255, 255, 255, 0))
        self.dr = ImageDraw.Draw(self.img)

    def _box(self, cx, cy, rx, ry, grow=0.0):
        k = self.k
        return [(cx - rx - grow - self.x0) * k, (cy - ry - grow - self.y0) * k, (cx + rx + grow - self.x0) * k, (cy + ry + grow - self.y0) * k]

    def ellipse(self, cx, cy, rx, ry, fill=None, outline=None, width=1.0):
        k = self.k
        lw = max(1, int(round(width * k)))
        if fill:
            self.dr.ellipse(self._box(cx, cy, rx, ry), fill=fill)
        if outline:
            self.dr.ellipse(self._box(cx, cy, rx, ry, width / 2.0), outline=outline, width=lw)

    def ring_dashed(self, cx, cy, rx, ry, col, width, dashes=16):
        k = self.k
        lw = max(1, int(round(width * k)))
        box = self._box(cx, cy, rx, ry, width / 2.0)
        for i in range(dashes):
            a = i * 360.0 / dashes
            self.dr.arc(box, a, a + 360.0 / dashes * 0.6, fill=col, width=lw)

    def polygon(self, pts, fill, outline=None, width=1.0):
        k = self.k
        q = [((x - self.x0) * k, (y - self.y0) * k) for (x, y) in pts]
        self.dr.polygon(q, fill=fill)
        if outline:
            self.dr.line(q + [q[0], q[1]], fill=outline, width=max(1, int(round(width * k))), joint="curve")

    def star(self, cx, cy, r, col):
        pts = []
        for i in range(10):
            a = -math.pi / 2 + i * math.pi / 5
            rr = r * 0.45 if i % 2 else r
            pts.append((cx + math.cos(a) * rr, cy + math.sin(a) * rr))
        self.polygon(pts, col, "#a66b00", max(1.0, r * 0.16))

    def put(self, frame, alpha=1.0):
        img = self.img.resize((self.w, self.h), Image.LANCZOS)
        if alpha < 0.999:
            a = img.getchannel("A").point(lambda v: int(v * max(0.0, alpha)))
            img.putalpha(a)
        frame.paste(img, (self.x0, self.y0), img)


def dw_glow(frame, cx, cy, rx, ry, c_in, c_out, alpha):
    """A soft round glow (the lava round a sinking dinosaur)."""
    w = max(2, int(rx * 2))
    h = max(2, int(ry * 2))
    g0 = Image.radial_gradient("L")                                        # 0 in the middle, 255 in the corners
    edge = float(max(1, g0.getpixel((0, 128))))                            # the value in the middle of an edge (181 in Pillow 13, 255 in older ones): there the glow must be gone
    g = g0.resize((w, h), Image.BILINEAR)
    t = g.point(lambda v: v)
    col = Image.merge("RGB", [Image.eval(t, lambda v, i=i: int(c_in[i] + (c_out[i] - c_in[i]) * min(1.0, v / edge))) for i in range(3)])
    mask = g.point(lambda v: int(max(0.0, 255 - v * 255.0 / edge) * alpha))
    frame.paste(col, (int(cx - rx), int(cy - ry)), mask)


# *************** DEL 13 - THE GROUND (painted once per world and size) *****************
def dw_hash(x, y):
    return ((x * 73856093) ^ (y * 19349663)) & 0xFFFFFFFF


def dw_under(world, x, y):
    """What a bridge crosses: the first of water, ravine, lava among its four neighbours."""
    for (dx, dy) in ((-1, 0), (1, 0), (0, -1), (0, 1)):
        c = dw_cell(world, x + dx, y + dy)
        if c in "wcl":
            return c
    return "w"


def dw_eff(world, x, y):
    c = dw_cell(world, x, y)
    return dw_under(world, x, y) if c == "b" else c


def dw_class_layer(dr, world, ch, cell, grow, rad, color, k):
    """All cells of one kind in one colour: neighbours melt together, corners that stick out are rounded."""
    for y in range(world["rows"]):
        for x in range(world["cols"]):
            if dw_eff(world, x, y) != ch:
                continue
            n = dw_eff(world, x, y - 1) == ch
            s = dw_eff(world, x, y + 1) == ch
            w = dw_eff(world, x - 1, y) == ch
            e = dw_eff(world, x + 1, y) == ch
            L = int(round((x * cell - grow) * k))
            T = int(round((y * cell - grow) * k))
            R = int(round(((x + 1) * cell + grow) * k)) - 1
            B = int(round(((y + 1) * cell + grow) * k)) - 1
            if R <= L or B <= T:
                continue
            r = int(min(rad * cell * k, (R - L) // 2 - 2, (B - T) // 2 - 2))
            corners = (not n and not w, not n and not e, not s and not e, not s and not w)
            if r >= 1 and any(corners):
                dr.rounded_rectangle([L, T, R, B], radius=r, fill=color, corners=corners)
            else:
                dr.rectangle([L, T, R, B], fill=color)


def dw_make_ground(world, cell):
    """The picture of the ground (RGB, cols*cell x rows*cell): grass, sand, water, lava, ravines, flowers, bridges."""
    pal = DW_PAL[world["theme"]]
    cols, rows = world["cols"], world["rows"]
    W, H = cols * cell, rows * cell
    k = 3 if W * 3 <= 3600 else 2
    g1, g2 = _hex(pal["g1"]), _hex(pal["g2"])
    img = Image.new("RGB", (W * k, H * k), g1)
    dr = ImageDraw.Draw(img)
    for y in range(rows):                                                   # a quiet checkered texture
        for x in range(cols):
            c = g2 if (x + y) % 2 == 0 else g1
            hs = dw_hash(x, y) % 5
            if hs == 0:
                c = _mix(c, (0, 0, 0), 0.05)
            elif hs == 1:
                c = _mix(c, (255, 255, 255), 0.06)
            if c != g1:
                dr.rectangle([x * cell * k, y * cell * k, (x + 1) * cell * k - 1, (y + 1) * cell * k - 1], fill=c)
    T = DW_TERRAIN
    lay = lambda ch, grow, rad, col: dw_class_layer(dr, world, ch, cell, grow, rad, _hex(col), k)
    lay("s", 0.0, 0.0, pal["sand"])
    lay("q", cell * 0.08, 0.35, T["qHalo"])
    lay("q", 0, 0.35, T["q"])
    lay("w", cell * 0.17, 0.5, pal["halo"])
    lay("w", 0, 0.5, pal["water"])
    lay("l", cell * 0.14, 0.45, T["lavaHalo"])
    lay("l", 0, 0.45, T["lava"])
    lay("l", -cell * 0.2, 0.3, T["lavaIn"])
    lay("c", cell * 0.13, 0.4, T["chasmRim"])
    lay("c", 0, 0.4, T["chasm"])
    lay("c", -cell * 0.22, 0.3, T["chasmIn"])
    img = img.resize((W, H), Image.LANCZOS)
    sizes = {"tuft": 0.5, "flower": 0.34, "pebble": 0.4, "shell": 0.34, "bone": 0.5, "wave": 0.7, "bubble": 0.3, "swirl": 0.8}
    for d in world["deco"]:
        kind = d[0]
        size = sizes.get(kind, 0.4)
        if kind == "tuft":
            kind = "tuft_sand" if world["theme"] == "desert" else "tuft_ash" if world["theme"] == "volcano" else "tuft"
        lst = DW_ART["ground"].get(kind)
        if not lst:
            continue
        sp = dw_sprite("g_" + kind + str(d[3]), lst[d[3] % len(lst)], size * cell, size * cell)
        img.paste(sp["img"], (int(round((d[1] - size / 2) * cell - sp["pad"])), int(round((d[2] - size / 2) * cell - sp["pad"]))), sp["img"])
    for y in range(rows):                                                   # bridges lie on the ground level
        for x in range(cols):
            if world["g"][y][x] == "b":
                sp = dw_sprite("o_bridge", DW_ART["thing"]["bridge"]["prims"], cell, cell)
                img.paste(sp["img"], (x * cell - sp["pad"], y * cell - sp["pad"]), sp["img"])
    return img


def dw_build_statics(world, cell):
    """Trees, rocks, walls, towers, keeps, volcanoes: [{y, name, x, top, w, h}] sorted back to front."""
    out = []
    seen = set()
    th = world["theme"]
    g = world["g"]

    def thing(name, cx, bottom, s):
        t = DW_ART["thing"][name]
        w = t["w"] * s * cell
        h = t["h"] * s * cell
        out.append({"y": bottom, "name": name, "x": cx * cell - w / 2.0, "top": bottom * cell - h, "w": w, "h": h})
    for y in range(world["rows"]):
        for x in range(world["cols"]):
            c = g[y][x]
            hs = dw_hash(x, y)
            sc = 0.92 + 0.16 * ((hs % 5) / 4.0)
            if c == "t":
                thing("oak" if th == "castle" else "pine" if th == "nature" else "dead" if th == "volcano" else "cactus", x + 0.5, y + 1, sc)
            elif c == "p":
                thing("palm", x + 0.5, y + 1, sc)
            elif c == "r":
                thing("rock_dark" if th == "volcano" else "rock_sand" if th == "desert" else "rock", x + 0.5, y + 1, sc * 1.05)
            elif c == "#":
                thing("wall", x + 0.5, y + 1, 1)
            elif c == "T":
                thing("tower", x + 0.5, y + 1, 1)
            elif c in "KV" and (x, y) not in seen:                          # a keep / a volcano = one picture over all its cells
                x1, y1 = x, y
                while x1 + 1 < world["cols"] and g[y][x1 + 1] == c:
                    x1 += 1
                while y1 + 1 < world["rows"] and g[y1 + 1][x] == c:
                    y1 += 1
                for yy in range(y, y1 + 1):
                    for xx in range(x, x1 + 1):
                        seen.add((xx, yy))
                thing("volcano" if c == "V" else ("keep2" if y1 - y >= 1 else "keep1"), (x + x1 + 1) / 2.0, y1 + 1, 1)
    out.sort(key=lambda s: s["y"])
    return out


def dw_make_view(world, w, h, force_cell=None):
    """The size of one cell for a stage of w x h pixels, the ground and the standing things."""
    cell = force_cell or max(6, int(min(w // world["cols"], h // world["rows"])))
    return {"world": world, "cell": cell, "cw": w, "ch": h,
            "ox": (w - world["cols"] * cell) // 2, "oy": (h - world["rows"] * cell) // 2,
            "ground": dw_make_ground(world, cell), "statics": dw_build_statics(world, cell)}


# *************** DEL 14 - THE DINOSAURS AND THE EFFECTS (a frame of the picture) *****************
def dw_draw_dino(frame, e, cell, t, top):
    """One dinosaur of the run (e = an entity of dw_start_run) or one standing in the editor (st 'idle').  top = things drawn last."""
    info = DW_TYPES[e["t"]]
    sz = info["size"] * cell
    flip = e["d"] < 0
    spr = dw_sprite("d_" + e["t"], DW_ART["dino"][e["t"]], sz, sz, flip)
    fx = e["x"] * cell
    fy = e["y"] * cell
    st = e["st"]
    if st == "poof":
        return
    if st == "up":                                                          # shot up to the top, spinning
        top.append(lambda: dw_put(frame, spr, fx, fy, e["d"] * e["tm"] * 11, 0.9, 1.0))
        return
    if info["kind"] == "fly":
        bob = math.sin(t * 5 + e["i"]) * 0.08 * cell

        def fly():
            p = DwPatch(fx, fy + 0.2 * cell, sz * 0.32, sz * 0.09)
            p.ellipse(fx, fy + 0.2 * cell, sz * 0.32, sz * 0.09, fill="#000000")
            p.put(frame, 0.22)
            dw_put(frame, spr, fx, fy - 0.9 * cell + bob, math.sin(t * 5 + e["i"]) * 0.05 * e["d"], 1.0, 1.0)
        top.append(fly)
        return
    if st == "fall":                                                        # over the edge: smaller and smaller, tumbling down
        p = min(1.0, e["tm"] / DW_SINK["c"])
        dw_put(frame, spr, fx, fy + p * p * 1.6 * cell, e["d"] * p * 6, 1 - 0.85 * p, 1 - 0.5 * p)
        return
    if st == "sink":                                                        # slowly into water / lava / quicksand
        dur = DW_SINK[e["hz"]]
        p = min(1.0, e["tm"] / dur)
        wob = math.sin(e["tm"] * 14) * 0.03 * cell if e["hz"] == "q" else 0.0
        dw_put(frame, spr, fx + wob, fy + p * 0.98 * sz * 0.9, math.sin(e["tm"] * 9) * 0.06 if e["hz"] == "q" else 0.0, 1.0, 1.0, clip_bottom=fy + 2)
        lw = max(1.5, cell * 0.06)
        if e["hz"] == "w":
            pt = DwPatch(fx, fy - sz * 0.3, sz * 0.7, sz * 0.7)
            for i in range(3):
                q = (e["tm"] * 0.9 + i / 3.0) % 1.0
                pr = DwPatch(fx, fy, sz * 0.6, sz * 0.2)
                pr.ellipse(fx, fy, sz * (0.15 + 0.4 * q), sz * (0.05 + 0.13 * q), outline="#ffffff", width=lw)
                pr.put(frame, 0.85 * (1 - q))
            for i in range(4):
                q = (e["tm"] * 0.7 + i * 0.27) % 1.0
                rr = cell * (0.06 + 0.05 * (i % 2))
                pt.ellipse(fx + math.sin(i * 2.3 + q * 4) * sz * 0.25, fy - q * sz * 0.6, rr, rr, fill="#ffffff")
            pt.put(frame, 0.9)
        elif e["hz"] == "l":
            dw_glow(frame, fx, fy, sz * 0.5, sz * 0.2, (255, 200, 60), (255, 90, 10), 0.75)
            for i in range(3):
                q = (e["tm"] * 0.5 + i / 3.0) % 1.0
                rr = cell * (0.18 + 0.3 * q)
                cx = fx + math.sin(i * 3 + q * 3) * sz * 0.15
                cy = fy - sz * 0.25 - q * sz * 0.7
                pm = DwPatch(cx, cy, rr + 1, rr + 1)
                pm.ellipse(cx, cy, rr, rr, fill="#463c3c")
                pm.put(frame, 0.33 * (1 - q))
        else:
            for i in range(2):
                q = (e["tm"] * 0.5 + i / 2.0) % 1.0
                pq = DwPatch(fx, fy, sz * 0.6, sz * 0.2)
                pq.ellipse(fx, fy, sz * (0.18 + 0.32 * q), sz * (0.06 + 0.11 * q), outline="#966e28", width=max(1.5, cell * 0.07))
                pq.put(frame, 0.8 * (1 - q))
        return
    lift = rot = 0.0                                                        # standing or walking
    if st == "walk":
        ph = t * info["speed"] * 3.2 + e["i"] * 0.37
        lift = abs(math.sin(ph * math.pi)) * 0.07 * cell
        rot = math.sin(ph * math.pi) * 0.04 * (-1 if flip else 1)
    if info["kind"] == "swim":
        ph = t * 2 + e["i"]
        lift = math.sin(ph) * 0.04 * cell
        for i in range(2):
            q = (t * 0.6 + i / 2.0) % 1.0
            pw = DwPatch(fx, fy + 0.04 * cell, sz * 0.55, sz * 0.15)
            pw.ellipse(fx, fy + 0.04 * cell, sz * (0.3 + 0.2 * q), sz * (0.07 + 0.05 * q), outline="#ffffff", width=max(1.5, cell * 0.05))
            pw.put(frame, 0.8 * (1 - q))
    dw_put(frame, spr, fx, fy - lift, rot, 1.0, 1.0)
    if st == "stop" and e["tm"] < 2.2:                                       # stars round the head: it bumped into something
        a = 1.0 if e["tm"] < 1.7 else (2.2 - e["tm"]) / 0.5

        def stars():
            ps = DwPatch(fx, fy - sz * 0.9, sz * 0.4, sz * 0.2)
            for i in range(3):
                ang = e["tm"] * 5 + i * math.pi * 2 / 3
                ps.star(fx + math.cos(ang) * sz * 0.22, fy - sz * 0.9 + math.sin(ang) * sz * 0.05, max(4.0, cell * 0.2), "#ffd23f")
            ps.put(frame, max(0.0, a))
        top.append(stars)


def dw_draw_cloud(frame, cx, cy, p, cell):
    """The cloud of dust where two dinosaurs met.  p = 0..1 (0 = just now)."""
    grow = min(1.0, p / 0.35)
    fade = 1.0 if p < 0.6 else max(0.0, 1 - (p - 0.6) / 0.4)
    if fade <= 0:
        return
    R = cell * 3.2
    pc = DwPatch(cx, cy - cell * 0.6, R, R)
    puffs = [[0, 0, 1.0], [-0.8, 0.1, 0.8], [0.8, 0.1, 0.8], [-0.4, -0.55, 0.8], [0.45, -0.55, 0.8], [-0.35, 0.5, 0.7], [0.4, 0.5, 0.7],
             [0, -0.9, 0.55], [-1.1, -0.35, 0.5], [1.1, -0.35, 0.5]]
    cols = ("#ffffff", "#eef0f6", "#dfe3ee")
    for i, q in enumerate(puffs):
        r = cell * 0.62 * q[2] * (0.35 + 0.65 * grow)
        wob = math.sin(p * 18 + i) * 0.04 * cell
        pc.ellipse(cx + q[0] * cell * 0.9 * grow + wob, cy - cell * 0.6 + q[1] * cell * 0.8 * grow, r, r, fill=cols[i % 3], outline="#b9bfd0", width=max(1.5, cell * 0.06))
    for i in range(6):                                                      # stars burst out of it
        a = i * math.pi / 3 + 0.4
        d = cell * (0.8 + 1.6 * grow)
        pc.star(cx + math.cos(a) * d, cy - cell * 0.6 + math.sin(a) * d * 0.8, max(4.0, cell * 0.2 * (1 - 0.4 * grow)), "#ffd23f" if i % 2 else "#ff8fb1")
    pc.put(frame, fade)


# ---- rockets and fireworks (1.1): the same kind of shapes as the dinosaurs, plus flames, smoke and bursts painted on small patches ----
DW_ROCKET_BACK = [        # the rocket: fins, nozzle, body, stripe, nose and the glass of the window (unit box 1.4 x 2.7 cells; feet at 0.95)
    {"kind": "poly", "pts": [[0.18, 0.56], [0.02, 0.80], [0.02, 0.93], [0.20, 0.86]], "fill": "#e53935", "w": 3},
    {"kind": "poly", "pts": [[0.82, 0.56], [0.98, 0.80], [0.98, 0.93], [0.80, 0.86]], "fill": "#e53935", "w": 3},
    {"kind": "poly", "pts": [[0.36, 0.85], [0.64, 0.85], [0.68, 0.93], [0.32, 0.93]], "fill": "#6d6d7a", "w": 3},
    {"kind": "poly", "pts": [[0.5, 0.02], [0.68, 0.10], [0.80, 0.26], [0.85, 0.46], [0.85, 0.70], [0.80, 0.82], [0.62, 0.86], [0.38, 0.86],
                             [0.20, 0.82], [0.15, 0.70], [0.15, 0.46], [0.20, 0.26], [0.32, 0.10]], "smooth": True, "fill": "#f4f6fb", "w": 4},
    {"kind": "poly", "pts": [[0.15, 0.60], [0.85, 0.60], [0.85, 0.67], [0.15, 0.67]], "fill": "#4a7fe0", "w": 0},
    {"kind": "poly", "pts": [[0.5, 0.02], [0.68, 0.10], [0.79, 0.22], [0.50, 0.245], [0.21, 0.22], [0.32, 0.10]], "smooth": True, "fill": "#e53935", "w": 4},
    {"kind": "oval", "box": [0.25, 0.265, 0.75, 0.535], "fill": "#8fd3ff", "w": 0},
]
DW_ROCKET_RIM = [{"kind": "oval", "box": [0.25, 0.265, 0.75, 0.535], "fill": "", "line": "#8a93a8", "w": 6}]
DW_FW_PRIMS = [           # a firework launcher: a wooden foot, a red tube with a yellow band and a fuse (unit box 1 x 1 cell)
    {"kind": "poly", "pts": [[0.12, 0.80], [0.88, 0.80], [0.94, 0.95], [0.06, 0.95]], "fill": "#8d6e63", "w": 3},
    {"kind": "poly", "pts": [[0.36, 0.82], [0.64, 0.82], [0.70, 0.22], [0.30, 0.22]], "fill": "#e53935", "w": 3},
    {"kind": "poly", "pts": [[0.34, 0.50], [0.66, 0.50], [0.675, 0.62], [0.325, 0.62]], "fill": "#ffd45e", "w": 0},
    {"kind": "oval", "box": [0.27, 0.14, 0.73, 0.30], "fill": "#8e1b1b", "w": 3},
    {"kind": "line", "pts": [[0.5, 0.18], [0.58, 0.05]], "line": "#5d4037", "w": 4},
]


def dw_rocket_sprite(w, h, passenger="", flip=False):
    """The rocket painted once (and kept); `passenger` = a dinosaur type that sits in the round window, '' = empty."""
    w = max(1, int(round(w)))
    h = max(1, int(round(h)))
    ck = ("rocket", w, h, passenger, bool(flip))
    s = DW_SPR.get(ck)
    if s:
        return s
    k = DW_SS
    pad = int(math.ceil(max(w, h) * 0.14))
    W, H = w + 2 * pad, h + 2 * pad
    ink = _hex(DW_INK) + (0,)
    img = Image.new("RGBA", (W * k, H * k), ink)
    dr = ImageDraw.Draw(img)
    dw_draw_prims(dr, DW_ROCKET_BACK, pad * k, pad * k, w * k, h * k, False, k)
    if passenger in DW_ART["dino"]:                       # the dinosaur, cut round like the window
        cx, cy = (pad + 0.5 * w) * k, (pad + 0.40 * h) * k
        R = 0.25 * w * k
        S = 0.5 * w * 1.15 * k
        layer = Image.new("RGBA", img.size, ink)
        dw_draw_prims(ImageDraw.Draw(layer), DW_ART["dino"][passenger], cx - S / 2, cy - S / 2 + 0.015 * w * k, S, S, flip, k)
        mask = Image.new("L", img.size, 0)
        ImageDraw.Draw(mask).ellipse([cx - R * 0.94, cy - R * 0.94, cx + R * 0.94, cy + R * 0.94], fill=255)
        layer.putalpha(ImageChops.multiply(layer.getchannel("A"), mask))
        img.alpha_composite(layer)
    dw_draw_prims(dr, DW_ROCKET_RIM, pad * k, pad * k, w * k, h * k, False, k)
    img = img.resize((W, H), Image.LANCZOS)
    s = {"img": img, "pad": pad, "w": w, "h": h}
    DW_SPR[ck] = s
    return s


def dw_put_pic(key, passenger="trex", size=44):
    """The little picture of a palette button: key = 'rocket', 'rocketdino' (rocket + the dinosaur beside it) or 'fw'."""
    if key == "fw":
        return dw_sprite("pal_fw", DW_FW_PRIMS, size, size)["img"].copy()
    h = size
    w = int(round(size * 1.4 / 2.7))
    rk = dw_rocket_sprite(w, h, passenger if key == "rocketdino" else "")["img"]
    if key == "rocket":
        return rk.copy()
    dp = dw_sprite("pal_" + passenger, DW_ART["dino"][passenger], 28, 28)["img"]
    out = Image.new("RGBA", (rk.width + dp.width - 12, max(rk.height, dp.height)), (0, 0, 0, 0))
    out.alpha_composite(rk, (0, out.height - rk.height))
    out.alpha_composite(dp, (rk.width - 12, out.height - dp.height))
    return out


def dw_rgba(col, a):
    r, g, b = _hex(col)
    return (r, g, b, max(0, min(255, int(a * 255))))


def dw_rocket_fx(frame, e, cell, t):
    """Smoke, smoke trail and flame of a rocket that is about to lift off or is climbing."""
    c = cell
    fx = e["x"] * c
    tm, go = e["tm"], e["go"]
    lifting = e["st"] == "lift"
    s = tm - go
    hh = DW_THINGS["rocket"]["hh"] * c
    y0 = e["y0"] * c
    age = tm - (go - DW_ROCKET_SMOKE)                                 # seconds since the engine lit
    if 0 < age < 4.2:                                                 # the cloud on the ground
        grow = min(1.0, age / 1.6)
        fade = 1.0 if age < 2.8 else max(0.0, 1 - (age - 2.8) / 1.4)
        pg = DwPatch(fx, y0 - c * 0.4, c * 2.6, c * 1.1, 2)
        for i in range(10):
            side = -1 if i % 2 else 1
            r = c * (0.24 + 0.09 * (i % 3)) * (0.4 + 0.6 * grow)
            px = fx + side * c * (0.12 + 0.2 * (i // 2)) * (0.3 + 0.7 * grow)
            py = y0 - c * (0.05 + 0.09 * ((i * 7) % 4)) * (0.4 + 0.6 * grow) - c * 0.07 * min(age, 2.0) * (1 + i % 3)
            pg.ellipse(px, py, r, r * 0.8, fill="#f1f3f8", outline="#b9bfd0", width=max(1.2, c * 0.05))
        pg.put(frame, 0.92 * fade)
    if lifting and s > 0.03:                                          # the trail of smoke behind a climbing rocket
        pos = []
        for j in range(7):
            sj = s - 0.09 * (j + 1)
            if sj > 0:
                pos.append((dw_rocket_y(e["y0"], go + sj, go) * c, j))
        if pos:
            ymin = min(p[0] for p in pos)
            ymax = max(p[0] for p in pos)
            pt = DwPatch(fx, (ymin + ymax) / 2 + c * 0.2, c * 1.0, (ymax - ymin) / 2 + c * 0.9, 2)
            for (yj, j) in pos:
                r = c * (0.2 + 0.07 * j)
                col = dw_rgba("#f1f3f8", 0.85 * (1 - j / 7.0))
                pt.ellipse(fx + math.sin(j * 2.1 + e["i"]) * c * 0.08, yj + c * 0.1, r, r, fill=col)
            pt.put(frame)
    inten = 1.0 if lifting else max(0.0, min(1.0, age / DW_ROCKET_SMOKE))
    if inten <= 0:
        return
    ny = (e["y"] * c if lifting else y0) - 0.02 * hh                  # the nozzle
    fl = 1 + 0.12 * math.sin(tm * 55 + e["i"] * 1.7)
    ln = c * (0.35 + 0.9 * inten + (min(1.6, s * 1.2) if lifting else 0.0)) * fl
    wd = c * 0.30 * (0.6 + 0.4 * inten)
    dw_glow(frame, fx, ny + ln * 0.25, c * 0.9, c * 0.6 + ln * 0.15, (255, 240, 170), (255, 120, 30), 0.55 * inten)
    pf = DwPatch(fx, ny + ln / 2, wd + c * 0.3, ln / 2 + c * 0.3, 2)
    for (scale, col) in ((1.0, "#ff8a1f"), (0.65, "#ffd23f"), (0.35, "#fffbe0")):
        w2, l2 = wd * scale, ln * scale
        pf.polygon([(fx - w2, ny), (fx - w2 * 0.7, ny + l2 * 0.45), (fx, ny + l2), (fx + w2 * 0.7, ny + l2 * 0.45), (fx + w2, ny)], col)
    pf.put(frame)


def dw_fw_fx(frame, e, cell, t):
    """The fuse spark, the climbing shell and the burst of a firework launcher."""
    c = cell
    st = e["st"]
    fx, fy = e["x"] * c, e["y"] * c
    if st == "ready":
        if e["tm"] > e["go"] - 0.5:                                    # the fuse sparkles just before the shot
            pf = DwPatch(fx + 0.08 * c, fy - 0.9 * c, c * 0.3, c * 0.3, 2)
            pf.star(fx + 0.08 * c, fy - 0.9 * c, c * (0.1 + 0.05 * math.sin(e["tm"] * 40)), "#ffd23f")
            pf.put(frame)
        return
    col = DW_FW_COLORS[(e["k"] * 2 + e["rd"]) % len(DW_FW_COLORS)]
    if st == "shoot":
        p = e["tm"] / DW_FW_SHOOT
        q = 1 - (1 - p) * (1 - p)
        x0, y0 = fx, fy - 0.95 * c
        bx, by = e["bx"] * c, e["by"] * c
        pt = DwPatch((x0 + bx) / 2, (y0 + by) / 2, abs(bx - x0) / 2 + c * 0.4, abs(by - y0) / 2 + c * 0.4, 2)
        for m in range(6):
            pm = max(0.0, q - 0.05 * m)
            px, py = x0 + (bx - x0) * pm, y0 + (by - y0) * pm
            r = c * (0.075 - 0.009 * m)
            pt.ellipse(px, py, r, r, fill=dw_rgba(col[0], 1 - m / 6.0))
        pt.put(frame)
        return
    if st != "burst":
        return
    p = e["tm"] / DW_FW_BURST
    style = (e["k"] + e["rd"]) % 3
    cx, cy = e["bx"] * c, e["by"] * c
    R = c * (1.9 + 0.35 * ((e["k"] + e["rd"] * 2) % 3))
    g = 2.3 if style == 2 else 0.9
    if style == 0:
        parts = [(2 * math.pi * j / 24, 1.0) for j in range(24)]
    elif style == 1:
        parts = [(2 * math.pi * j / 20, 1.0) for j in range(20)] + [(2 * math.pi * (j + 0.5) / 10, 0.55) for j in range(10)]
    else:
        parts = [(2 * math.pi * j / 26 + 0.1 * math.sin(j * 7.0), 0.75 + 0.25 * ((j * 5) % 4) / 3.0) for j in range(26)]
    thr = 0.7 if style == 2 else 0.55
    fade = 1.0 if p < thr else max(0.0, (1 - p) / (1 - thr))
    if p < 0.14:
        dw_glow(frame, cx, cy, c * 1.3, c * 1.3, (255, 255, 255), _hex(col[1]), 0.8 * (1 - p / 0.14))
    if fade <= 0:
        return
    pb = DwPatch(cx, cy + g * c * 0.5, R + c * 0.6, R + c * 0.6 + g * c * 0.5, 2)
    for (ang, sp) in parts:
        for m in (3, 2, 1, 0):                                         # a short tail behind every spark, the head last
            pm = max(0.0, p - 0.035 * m)
            ease = 1 - (1 - pm) ** 2.2
            px = cx + math.cos(ang) * R * sp * ease
            py = cy + math.sin(ang) * R * sp * ease + g * c * pm * pm
            r = c * 0.075 * (1 - 0.5 * pm) * (1 - 0.18 * m)
            a = fade * (1 - 0.28 * m)
            pb.ellipse(px, py, r, r, fill=dw_rgba(col[1], a))
            if m == 0:
                pb.ellipse(px, py, r * 0.5, r * 0.5, fill=dw_rgba(col[0], a))
    pb.put(frame)


def dw_draw_thing(frame, e, cell, t, top, glow):
    """A rocket or a firework launcher: standing in the editor (st 'idle') or in a run.  top / glow = things drawn last."""
    info = DW_THINGS[e["t"]]
    c = cell
    fx, fy = e["x"] * c, e["y"] * c
    st = e["st"]
    if e["t"] == "fireworks":
        spr = dw_sprite("fw_launcher", DW_FW_PRIMS, c * info["size"], c * info["hh"])
        dw_put(frame, spr, fx, fy)
        if st != "idle":
            glow.append(lambda: dw_fw_fx(frame, e, c, t))
        return
    spr = dw_rocket_sprite(c * info["size"], c * info["hh"], e.get("r", ""), e["d"] < 0)
    if st == "idle":
        dw_put(frame, spr, fx, fy)
        return
    if st == "ready":                                                         # shaking harder and harder
        amp = max(0.0, min(1.0, (e["tm"] - (e["go"] - DW_ROCKET_SMOKE)) / DW_ROCKET_SMOKE))
        dw_put(frame, spr, fx + math.sin(e["tm"] * 62 + e["i"]) * amp * 0.035 * c, fy + math.sin(e["tm"] * 83 + e["i"] * 2) * amp * 0.02 * c)
    else:                                                                     # climbing: in front of everything
        top.append(lambda: dw_put(frame, spr, fx, fy))
    glow.append(lambda: dw_rocket_fx(frame, e, c, t))


def dw_night_level(ents):
    """0..1: how dark the world is for the fireworks (it dims while a launcher is shooting and brightens when they are done)."""
    lv = 0.0
    for e in ents:
        if e["t"] != "fireworks":
            continue
        st = e["st"]
        if st in ("shoot", "burst"):
            lv = 1.0
        elif st == "ready":
            lv = max(lv, min(1.0, e["tm"] / 0.5))
        elif st == "stop":
            lv = max(lv, max(0.0, 1.0 - e["tm"] / 0.8))
    return lv


def dw_edit_ents(dinos):
    """The dinosaurs (and rockets, fireworks) of the editor as drawable entities (they stand still)."""
    out = []
    for i, d in enumerate(dinos):
        e = {"i": i, "t": d["t"], "x": d["x"] + 0.5, "y": d["y"] + 0.5, "d": 1 if d["d"] >= 0 else -1, "st": "idle", "tm": 0.0, "hz": "", "vy": 0.0}
        if d["t"] == "rocket":
            e["r"] = d.get("r", "")
        out.append(e)
    return out


def dw_render_scene(view, ents, t=0.0, sel=-1, clouds=()):
    """One whole picture of the world (RGB, cols*cell x rows*cell): ground, standing things and dinosaurs back to front, effects on top."""
    cell = view["cell"]
    frame = view["ground"].copy()
    items = []
    for s in view["statics"]:
        items.append((s["y"], s))
    for i, e in enumerate(ents):
        if e["st"] != "gone":
            items.append((e["y"] + 0.001 * i, e))
    items.sort(key=lambda it: it[0])
    top = []
    glow = []
    for _, it in items:
        if "name" in it:
            sp = dw_sprite("o_" + it["name"], DW_ART["thing"][it["name"]]["prims"], it["w"], it["h"])
            frame.paste(sp["img"], (int(round(it["x"] - sp["pad"])), int(round(it["top"] - sp["pad"]))), sp["img"])
        elif it["t"] in DW_THINGS:
            dw_draw_thing(frame, it, cell, t, top, glow)
        else:
            dw_draw_dino(frame, it, cell, t, top)
    if 0 <= sel < len(ents):                                                # the picked dinosaur: a ring and an arrow in front of it
        e = ents[sel]
        info = DW_ALL[e["t"]]
        fx, fy = e["x"] * cell, e["y"] * cell
        rr = max(info["size"] * cell * 0.34, cell * 0.6)
        ps = DwPatch(fx + e["d"] * rr * 0.5, fy, rr * 1.9, rr * 0.6)
        ps.ring_dashed(fx, fy + cell * 0.05, rr, rr * 0.36, "#ffd45e", max(3.0, cell * 0.12))
        ax = fx + e["d"] * (rr + cell * 0.2)
        ay = fy + cell * 0.05
        ps.polygon([(ax + e["d"] * cell * 0.42, ay), (ax - e["d"] * cell * 0.05, ay - cell * 0.3), (ax - e["d"] * cell * 0.05, ay + cell * 0.3)], "#ffd45e")
        ps.put(frame)
    night = dw_night_level(ents)                                            # fireworks: the world dims a little
    if night > 0.01:
        frame.paste(Image.blend(frame, Image.new("RGB", frame.size, (10, 12, 44)).convert(frame.mode), 0.36 * night))
    for fn in top:
        fn()
    for fn in glow:                                                         # flames, smoke and bursts shine on top of everything
        fn()
    for c in clouds:
        dw_draw_cloud(frame, c["x"] * cell, c["y"] * cell, c["p"], cell)
    return frame


def dw_thumb(world, dinos, width=220):
    """A small picture of a world with its dinosaurs (for the list of saved worlds)."""
    cell = max(4, width // world["cols"])
    v = dw_make_view(world, cell * world["cols"], cell * world["rows"], cell)
    return dw_render_scene(v, dw_edit_ents(dinos))


def dw_palette_pic(typ, size):
    """The little picture of a dinosaur on its palette button."""
    sp = dw_sprite("pal_" + typ, DW_ART["dino"][typ], size, size)
    bg = Image.new("RGBA", sp["img"].size, (0, 0, 0, 0))
    bg.alpha_composite(sp["img"])
    return bg


# *************** DEL 15 - TOOL POPUPS: MOVABLE, ZOOMABLE, NON-MODAL (Player text) *****************
# block_popups.py - copy verbatim into a program (needs: import os, tkinter as tk,
# tkinter.font as tkfont).  Two parts:
#
#   ToolPopup   a window beside the main window that you can DRAG, ZOOM (the
#               [-] 100% [+] bar, or Ctrl+mouse wheel), and close with Esc.
#               Position, zoom and "is it open" live in the PROGRAM'S OWN
#               settings dict (`store`), under three key names the program
#               picks - so they survive a restart.  Subclass it and write
#               build(self, s): s is the zoom as a float (1.0 = 100 %).  Draw
#               into self.body, or call self.canvas_area(w, h) and draw on the
#               canvas it returns (it gets a scrollbar by itself when the
#               screen is too small for the whole thing).
#
#   PlayerTextPopup  the PLAYER'S OWN TEXT, written and saved inside the program
#               (tactics, house rules, "good to remember").  Every file
#               <Helpfiles>\<program>\Playertext-<name>.txt is one text; what
#               follows the prefix is what the drop-down offers; the chosen text
#               is shown in a box with scrollbars + mouse wheel and can be edited
#               right there (saved by itself a second after the last key, and
#               when the popup closes or another text is picked).  [New...]
#               starts another text.  Nothing is ever deleted by the program.
#               An empty text never creates a file.  Call .save_now() from the
#               program's own on_close.
#
# The program supplies:
#   store      its settings dict (mutated in place)
#   keys       (show_key, pos_key, zoom_key) for a ToolPopup, e.g. ("show_aid","popup_pos","popup_zoom");
#              (show_key, pos_key, zoom_key, sel_key) for PlayerTextPopup, e.g.
#              ("show_playertext","playertext_pos","playertext_zoom","playertext_sel")
#              NB: pick names that do not collide with a text-key prefix the
#              program's self-test scans for (a "aid_*" setting broke one).
#   on_change  callable that saves the settings (e.g. lambda: save_settings(S))
#   theme      dict: bg panel fg dim accent btn btnfg field field_fg
#   on_closed  callable run after the popup closed itself (tick boxes off ...)
#   on_key     optional; Space/Enter forwarded to the game ("Play").  NEVER for
#              the notes popup - it is typed into.
#
# Open it once at start-up for a game's aid (show_key true), open the player
# text from a menu / button.  The main window keeps working: nothing here grabs input.

POPUP_ZOOMS = (50, 60, 70, 80, 90, 100, 115, 130, 150)


def popup_lines(font, texts, width):
    """How many lines the LONGEST of `texts` needs at `width` px (greedy word
    wrap).  Gives a label one fixed height whatever the language
    (01_CORE item 6)."""
    best = 1
    for t in texts:
        lines = 0
        for para in t.split("\n"):
            cur, n = "", 1
            for w in para.split():
                trial = (cur + " " + w).strip()
                if cur and font.measure(trial) > width:
                    n += 1
                    cur = w
                else:
                    cur = trial
            lines += n
        best = max(best, lines)
    return best


class ToolPopup(object):
    resizable = False

    def __init__(self, root, store, keys, on_change, theme, title,
                 on_closed=None, on_key=None):
        self.root, self.store, self.theme = root, store, theme
        self.k_show, self.k_pos, self.k_zoom = keys
        self.on_change, self.on_closed = on_change, on_closed
        self.move_job = None
        self._cv = self._bar = None
        self._full_h = 0
        top = self.top = tk.Toplevel(root)
        top.title(title)
        top.configure(bg=theme["bg"])
        top.resizable(self.resizable, self.resizable)
        top.transient(root)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.bind("<Escape>", lambda e: self.close())
        top.bind("<Control-MouseWheel>",
                 lambda e: self.step(1 if e.delta > 0 else -1))
        if on_key:
            for key in ("<Return>", "<KP_Enter>", "<space>"):
                top.bind(key, lambda e: on_key())
        bar = self.toolbar = tk.Frame(top, bg=theme["panel"])
        bar.pack(fill="x")
        self._btn(bar, u"−", lambda: self.step(-1)).pack(
            side="left", padx=(6, 0), pady=3)
        self.lbl_zoom = tk.Label(bar, width=5, bg=theme["panel"],
                                 fg=theme["fg"], font=("Segoe UI", 9, "bold"))
        self.lbl_zoom.pack(side="left")
        self._btn(bar, "+", lambda: self.step(1)).pack(side="left")
        self._btn(bar, "100%", lambda: self.set_zoom(100), w=5).pack(
            side="left", padx=(6, 0))
        self.extra_toolbar(bar)
        self.body = tk.Frame(top, bg=theme["bg"])
        self.body.pack(fill="both", expand=True)
        self._rebuild()
        self._place(store.get(self.k_pos))
        top.bind("<Configure>", self._configured)

    # ---- for subclasses ------------------------------------------------------
    def build(self, s):
        raise NotImplementedError

    def extra_toolbar(self, bar):
        pass

    def before_rebuild(self):
        pass

    def before_close(self):
        pass

    # ---- zoom ----------------------------------------------------------------
    def zoom(self):
        z = self.store.get(self.k_zoom, 100)
        return z if z in POPUP_ZOOMS else 100

    def step(self, d):
        i = POPUP_ZOOMS.index(self.zoom()) + d
        self.set_zoom(POPUP_ZOOMS[max(0, min(len(POPUP_ZOOMS) - 1, i))])

    def set_zoom(self, z):
        if z == self.zoom():
            return
        self.store[self.k_zoom] = z
        self.on_change()
        self._rebuild()
        self._place(self._where())          # the size changed: stay on screen

    def _btn(self, parent, text, cmd, w=3):
        th = self.theme
        return tk.Button(parent, text=text, command=cmd, width=w, bd=0,
                         relief="flat", bg=th["btn"], fg=th["btnfg"],
                         activebackground=th["accent"], takefocus=0,
                         cursor="hand2", font=("Segoe UI", 9, "bold"))

    def _rebuild(self):
        self.before_rebuild()
        for w in self.body.winfo_children():
            w.destroy()
        self._cv = None
        self.lbl_zoom.configure(text="%d%%" % self.zoom())
        self.build(self.zoom() / 100.0)
        self.top.update_idletasks()
        self._fit()

    # ---- a canvas that scrolls only when the screen is too small --------------
    def canvas_area(self, w, h):
        th = self.theme
        frame = tk.Frame(self.body, bg=th["bg"])
        frame.pack(padx=6)
        cv = tk.Canvas(frame, width=w, height=h, bg=th["bg"], bd=0,
                       highlightthickness=0, scrollregion=(0, 0, w, h))
        cv.pack(side="left")
        bar = tk.Scrollbar(frame, command=cv.yview, bg=th["panel"])
        cv.configure(yscrollcommand=bar.set)
        cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(
            -1 if e.delta > 0 else 1, "units"))
        self._cv, self._bar, self._full_h = cv, bar, h
        return cv

    def resize_canvas(self, h):
        """The drawing is finished and turned out `h` px high."""
        h = int(h)
        w = int(self._cv.cget("width"))
        self._cv.configure(height=h, scrollregion=(0, 0, w, h))
        self._full_h = h

    def _fit(self):
        cv = self._cv
        if cv is None:
            return
        cv.configure(height=self._full_h)
        self._bar.pack_forget()
        self.top.update_idletasks()
        excess = self.top.winfo_reqheight() - (self.top.winfo_screenheight() - 90)
        if excess > 0:
            cv.configure(height=max(240, self._full_h - excess))
            self._bar.pack(side="left", fill="y")

    # ---- position ------------------------------------------------------------
    def _where(self):
        return [self.top.winfo_x(), self.top.winfo_y()]

    def _place(self, pos):
        top, root = self.top, self.root
        top.update_idletasks()
        sw, sh = top.winfo_screenwidth(), top.winfo_screenheight()
        w, h = top.winfo_reqwidth(), top.winfo_reqheight()
        ok = (isinstance(pos, (list, tuple)) and len(pos) == 2
              and all(isinstance(v, int) for v in pos)
              and -w + 60 < pos[0] < sw - 60 and 0 <= pos[1] < sh - 60)
        if ok:
            x, y = pos
            x = min(x, max(0, sw - w)) if x + w > sw + 40 else x
        else:                               # default: right of the main window
            root.update_idletasks()
            x = root.winfo_x() + root.winfo_width() + 8
            y = root.winfo_y()
            if x + w > sw:                  # no room: hug the screen edge
                x = max(0, sw - w)
            y = max(0, min(y, sh - h - 40))
        top.geometry("+%d+%d" % (x, y))

    def _configured(self, event):
        if event.widget is not self.top:
            return
        if self.move_job:
            self.top.after_cancel(self.move_job)
        self.move_job = self.top.after(400, self._moved)

    def _moved(self):
        self.move_job = None
        try:
            self.store[self.k_pos] = [int(v) for v in self._where()]
            self.on_change()
        except Exception:
            pass

    def retitle(self, title):
        self.top.title(title)

    def close(self):
        try:
            self.before_close()
        except Exception:
            pass
        if self.move_job:
            try:
                self.top.after_cancel(self.move_job)
            except Exception:
                pass
        try:
            self.top.destroy()
        except Exception:
            pass
        self.store[self.k_show] = False
        self.on_change()
        if self.on_closed:
            self.on_closed()


PLAYERTEXT_PREFIX = "Playertext-"
PLAYERTEXT_DEFAULT_LABELS = {
    "hint": "Your own text - saved by itself as Playertext-<name>.txt in the "
            "program's Helpfiles folder.  Every such file there can be picked above.",
    "folder": "Folder", "new": "New...", "wrap": "Wrap",
    "newname": "Name of the new text (tactics, remember, house rules ...):",
    "ok": "OK", "cancel": "Cancel"}


def playertext_names(folder):
    """The <name> of every Playertext-<name>.txt in `folder`, sorted.  A
    Notes.txt from the first version of this block becomes Playertext-Notes.txt."""
    try:
        old, new = (os.path.join(folder, "Notes.txt"),
                    os.path.join(folder, PLAYERTEXT_PREFIX + "Notes.txt"))
        if os.path.isfile(old) and not os.path.exists(new):
            os.replace(old, new)
    except OSError:
        pass
    out = []
    try:
        for n in os.listdir(folder):
            if (n.lower().startswith(PLAYERTEXT_PREFIX.lower())
                    and n.lower().endswith(".txt")
                    and len(n) > len(PLAYERTEXT_PREFIX) + 4):
                out.append(n[len(PLAYERTEXT_PREFIX):-4])
    except OSError:
        pass
    return sorted(out, key=lambda s: s.lower())


def playertext_clean(name):
    """A name that is safe in a file name (no \\ / : * ? " < > |)."""
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


class PlayerTextPopup(ToolPopup):
    """The player's own text, written and saved INSIDE the program: tactics,
    house rules, things to remember.  Every file
    <Helpfiles>/<program>/Playertext-<name>.txt is one text; the part after
    the prefix is what the drop-down offers, and the chosen one is shown in a
    box with a scrollbar and mouse-wheel scrolling (and a horizontal bar when
    "Wrap" is off).  Typing saves by itself a second later and on close/switch.
    [New...] starts another text.  Nothing is ever deleted by the program.
    keys = (show_key, pos_key, zoom_key, selected_name_key)
    labels() -> dict with any of PLAYERTEXT_DEFAULT_LABELS' keys (a language
    switch calls relabel() which asks again).  Call .save_now() from the
    program's own on_close."""
    resizable = True

    def __init__(self, root, store, keys, on_change, theme, title, folder,
                 labels, on_closed=None, default_name="Notes"):
        self.folder, self.labels = folder, labels
        self.k_sel = keys[3]
        self.txt = self.hbar = self.btn_folder = self.lbl_status = None
        self.save_job = None
        self.dirty = False
        self.saved = None                   # None = no file yet
        names = playertext_names(folder)
        sel = store.get(self.k_sel)
        self.name = sel if sel in names else (names[0] if names else default_name)
        self.content = self._read(self.name)
        self.wrap = None
        ToolPopup.__init__(self, root, store, keys[:3], on_change, theme,
                           title, on_closed)
        self.wrap = self.wrap or tk.BooleanVar(value=True)
        self.top.after(80, self._focus)

    def _l(self, key):
        try:
            return self.labels().get(key) or PLAYERTEXT_DEFAULT_LABELS[key]
        except Exception:
            return PLAYERTEXT_DEFAULT_LABELS[key]

    def _path(self, name=None):
        return os.path.join(self.folder,
                            PLAYERTEXT_PREFIX + (name or self.name) + ".txt")

    def _focus(self):
        try:
            self.txt.focus_set()
        except Exception:
            pass

    def _read(self, name):
        self.saved = None
        self.dirty = False
        try:
            if os.path.isfile(self._path(name)):
                with open(self._path(name), encoding="utf-8-sig",
                          errors="replace") as fh:
                    text = fh.read()
                self.saved = text
                return text
        except Exception:
            pass
        return ""

    def extra_toolbar(self, bar):
        self.btn_folder = self._btn(bar, self._l("folder"), self._open_folder,
                                    w=8)
        self.btn_folder.pack(side="right", padx=6)

    def _open_folder(self):
        try:
            os.makedirs(self.folder, exist_ok=True)
            os.startfile(self.folder)
        except Exception:
            pass

    def before_rebuild(self):
        if self.txt is not None:
            try:
                self.content = self.txt.get("1.0", "end-1c")
            except Exception:
                pass

    def build(self, s):
        th = self.theme
        if self.wrap is None:
            self.wrap = tk.BooleanVar(value=True)
        row = tk.Frame(self.body, bg=th["bg"])
        row.pack(fill="x", padx=6, pady=(6, 0))
        tk.Label(row, text=PLAYERTEXT_PREFIX, bg=th["bg"], fg=th["dim"],
                 font=("Segoe UI", 9)).pack(side="left")
        names = playertext_names(self.folder)
        if self.name not in names:
            names = sorted(names + [self.name], key=lambda x: x.lower())
        self.var_name = tk.StringVar(value=self.name)
        om = tk.OptionMenu(row, self.var_name, *names, command=self._picked)
        om.configure(bg=th["btn"], fg=th["btnfg"], activebackground=th["accent"],
                     highlightthickness=0, bd=0, relief="flat", takefocus=0,
                     font=("Segoe UI", 9, "bold"), cursor="hand2")
        om["menu"].configure(bg=th["btn"], fg=th["btnfg"],
                             activebackground=th["accent"],
                             font=("Segoe UI", 9))
        om.pack(side="left")
        self._btn(row, self._l("new"), self._new, w=8).pack(side="left", padx=6)
        tk.Checkbutton(row, text=self._l("wrap"), variable=self.wrap,
                       command=self._wrap_changed, bg=th["bg"], fg=th["fg"],
                       selectcolor=th["panel"], activebackground=th["bg"],
                       activeforeground=th["accent"], highlightthickness=0,
                       takefocus=0, font=("Segoe UI", 9)).pack(side="right")
        box = tk.Frame(self.body, bg=th["panel"])
        box.pack(fill="both", expand=True, padx=6, pady=(4, 2))
        box.grid_rowconfigure(0, weight=1)
        box.grid_columnconfigure(0, weight=1)
        vbar = tk.Scrollbar(box, orient="vertical", bg=th["panel"])
        self.hbar = tk.Scrollbar(box, orient="horizontal", bg=th["panel"])
        self.txt = tk.Text(
            box, width=46, height=18, undo=True, bd=0, highlightthickness=0,
            padx=8, pady=6, bg=th["field"], fg=th["field_fg"],
            insertbackground=th["field_fg"], insertofftime=0,
            insertontime=1000,                           # no blinking cursor
            wrap="word" if self.wrap.get() else "none",
            font=("Segoe UI", max(7, int(round(10 * s)))),
            yscrollcommand=vbar.set, xscrollcommand=self.hbar.set)
        self.txt.grid(row=0, column=0, sticky="nsew")
        vbar.grid(row=0, column=1, sticky="ns")
        vbar.configure(command=self.txt.yview)
        self.hbar.configure(command=self.txt.xview)
        self._wrap_changed()
        self.txt.insert("1.0", self.content)
        self.txt.edit_modified(False)
        self.txt.edit_reset()

        def modified(e):
            if self.txt.edit_modified():
                self.txt.edit_modified(False)
                self._changed()
        self.txt.bind("<<Modified>>", modified)
        self.lbl_status = tk.Label(self.body, anchor="w", justify="left",
                                   bg=th["bg"], fg=th["dim"],
                                   font=("Segoe UI", 8), wraplength=420,
                                   text=self._l("hint"))
        self.lbl_status.pack(fill="x", padx=8, pady=(0, 4))

    def _wrap_changed(self):
        on = self.wrap.get()
        self.txt.configure(wrap="word" if on else "none")
        if on:
            self.hbar.grid_forget()
        else:
            self.hbar.grid(row=1, column=0, sticky="ew")

    def _picked(self, name):
        if name != self.name:
            self._switch(name)

    def _switch(self, name):
        self.save_now()
        self.txt = None                     # do not cache the old text
        self.name = name
        self.content = self._read(name)
        self.store[self.k_sel] = name
        self.on_change()
        self._rebuild()
        self._focus()

    def _new(self):
        th = self.theme
        self.save_now()
        dlg = tk.Toplevel(self.top)
        dlg.title(self._l("new"))
        dlg.transient(self.top)
        dlg.configure(bg=th["bg"])
        dlg.resizable(False, False)
        tk.Label(dlg, text=self._l("newname"), bg=th["bg"], fg=th["fg"],
                 font=("Segoe UI", 9)).pack(padx=14, pady=(12, 4))
        var = tk.StringVar()
        ent = tk.Entry(dlg, textvariable=var, width=30, bd=0,
                       bg=th["field"], fg=th["field_fg"],
                       insertbackground=th["field_fg"], insertofftime=0,
                       insertontime=1000, font=("Segoe UI", 10))
        ent.pack(padx=14, ipady=3)

        def ok(event=None):
            nm = playertext_clean(var.get())
            dlg.destroy()
            if nm:
                existing = {n.lower(): n for n in playertext_names(self.folder)}
                self._switch(existing.get(nm.lower(), nm))
        row = tk.Frame(dlg, bg=th["bg"])
        row.pack(pady=10)
        self._btn(row, self._l("ok"), ok, w=8).pack(side="left", padx=4)
        self._btn(row, self._l("cancel"), dlg.destroy, w=8).pack(side="left",
                                                                  padx=4)
        dlg.bind("<Return>", ok)
        dlg.bind("<Escape>", lambda e: dlg.destroy())
        dlg.update_idletasks()
        dlg.geometry("+%d+%d" % (self.top.winfo_x() + 40, self.top.winfo_y() + 80))
        dlg.grab_set()
        ent.focus_force()

    def _changed(self):
        self.dirty = True
        if self.save_job:
            self.top.after_cancel(self.save_job)
        self.save_job = self.top.after(1000, self.save_now)

    def save_now(self):
        if self.save_job:
            try:
                self.top.after_cancel(self.save_job)
            except Exception:
                pass
            self.save_job = None
        if self.txt is None or not self.dirty:
            return
        try:
            text = self.txt.get("1.0", "end-1c")
        except Exception:
            return
        self.content = text
        if self.saved is None and not text.strip():
            self.dirty = False              # an empty text never makes a file
            return
        try:
            os.makedirs(self.folder, exist_ok=True)
            tmp = self._path() + ".tmp"
            with open(tmp, "w", encoding="utf-8") as fh:
                fh.write(text)
            os.replace(tmp, self._path())
            self.saved, self.dirty = text, False
        except Exception:
            pass

    def before_close(self):
        self.save_now()

    def relabel(self, title):
        self.retitle(title)
        self.btn_folder.configure(text=self._l("folder"))
        self._rebuild()


# *************** DEL 16 - SETTINGS, SAVED WORLDS, LOG AND SOUND *****************
SETTINGS_PATH = os.path.join(PROGRAM_HF_DIR, "settings.json")
WORLDS_DIR = os.path.join(PROGRAM_HF_DIR, "Worlds")          # one <name>.json (+ <name>.jpg picture) per saved world; the same files as on the phone
LOG_PATH = os.path.join(LOG_DIR, PROGRAM_NAME + ".log")
DW_MAX_DINOS = 16

DEFAULT_SETTINGS = {"lang": "en", "theme": "random", "type": "trex", "put": "dino", "dir": 1, "sound": True, "speed": 1, "n": 0, "geometry": "",
                    "cur": None, "show_playertext": False, "playertext_pos": None, "playertext_zoom": 100, "playertext_sel": "Notes"}


def dw_set_dirs(base):
    """Point every folder of the program at `base` (the self-test uses a temporary one so it never touches the real data)."""
    global PROGRAM_HF_DIR, LANG_DIR, SETTINGS_PATH, WORLDS_DIR, LOG_PATH
    PROGRAM_HF_DIR = os.path.join(base, "Helpfiles", PROGRAM_NAME)
    LANG_DIR = os.path.join(PROGRAM_HF_DIR, "Lang")
    SETTINGS_PATH = os.path.join(PROGRAM_HF_DIR, "settings.json")
    WORLDS_DIR = os.path.join(PROGRAM_HF_DIR, "Worlds")
    LOG_PATH = os.path.join(base, "Helpfiles", "0---Empty", PROGRAM_NAME + ".log")


def load_settings():
    s = dict(DEFAULT_SETTINGS)
    try:
        with open(SETTINGS_PATH, encoding="utf-8-sig") as fh:
            data = json.load(fh)
        if isinstance(data, dict):
            s.update(data)
    except Exception:
        pass
    return s


def save_settings(s):
    try:
        os.makedirs(PROGRAM_HF_DIR, exist_ok=True)
        tmp = SETTINGS_PATH + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(s, fh, ensure_ascii=False, indent=1)
        os.replace(tmp, SETTINGS_PATH)
    except Exception:
        pass


def log(msg):
    """One line in the program's log (Helpfiles\\0---Empty); never raises.  The log is cut when it grows past 300 KB."""
    try:
        os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True)
        if os.path.isfile(LOG_PATH) and os.path.getsize(LOG_PATH) > 300000:
            os.replace(LOG_PATH, LOG_PATH + ".old")
        with open(LOG_PATH, "a", encoding="utf-8") as fh:
            fh.write("%s  %s\n" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg))
    except Exception:
        pass


def dw_clean_name(name):
    bad = '<>:"/\\|?*'
    name = "".join(c for c in name if c not in bad and ord(c) >= 32)
    return name.strip().strip(".")[:40]


def dw_clean_dinos(raw):
    """A list of dinosaurs from a file: only known types, whole-number cells, direction -1 or 1, at most DW_MAX_DINOS."""
    out = []
    for d in raw if isinstance(raw, list) else []:
        try:
            if d["t"] in DW_ALL and len(out) < DW_MAX_DINOS:
                item = {"t": d["t"], "x": int(d["x"]), "y": int(d["y"]), "d": 1 if int(d.get("d", 1)) >= 0 else -1}
                if d["t"] == "rocket":                       # the dinosaur on board ("" = an empty rocket)
                    item["r"] = d.get("r", "") if d.get("r", "") in DW_TYPES else ""
                out.append(item)
        except Exception:
            continue
    return out


def dw_world_from_data(data):
    """(world, dinos) from a saved-world dict (a file of ours or of the phone), or None when it is not a usable world."""
    try:
        theme, shape, seed = data["theme"], data["shape"], int(data["seed"])
        if theme not in DW_THEMES or shape not in DW_SHAPES:
            return None
        return dw_make_world(theme, seed, shape), dw_clean_dinos(data.get("dinos", []))
    except Exception:
        return None


def save_world_file(name, world, dinos):
    """Writes Worlds\\<name>.json and its picture <name>.jpg.  Returns the path of the .json, or "" when it failed."""
    name = dw_clean_name(name) or "World"
    try:
        os.makedirs(WORLDS_DIR, exist_ok=True)
        data = {"app": "Dino_World", "name": name, "theme": world["theme"], "seed": world["seed"], "shape": world["shape"],
                "dinos": [dict({"t": d["t"], "x": d["x"], "y": d["y"], "d": d["d"]}, **({"r": d.get("r", "")} if d["t"] == "rocket" else {})) for d in dinos],
                "when": int(time.time() * 1000)}
        path = os.path.join(WORLDS_DIR, name + ".json")
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump(data, fh, ensure_ascii=False)
        os.replace(tmp, path)
        try:
            dw_thumb(world, dinos).save(os.path.join(WORLDS_DIR, name + ".jpg"), quality=75)
        except Exception:
            pass
        return path
    except Exception:
        return ""


def list_world_files():
    """[(path, data)] of every readable world in Worlds\\, the newest first."""
    out = []
    try:
        for n in os.listdir(WORLDS_DIR):
            if n.lower().endswith(".json"):
                p = os.path.join(WORLDS_DIR, n)
                try:
                    with open(p, encoding="utf-8-sig") as fh:
                        data = json.load(fh)
                    if isinstance(data, dict) and dw_world_from_data(data):
                        data.setdefault("name", os.path.splitext(n)[0])
                        out.append((os.path.getmtime(p), p, data))
                except Exception:
                    continue
    except OSError:
        pass
    out.sort(key=lambda r: -r[0])
    return [(p, d) for (_, p, d) in out]


def next_world_name(theme, n):
    """A free name like 'Island 3' (the number counts up; a name that is taken is skipped)."""
    while True:
        n += 1
        name = "%s %d" % (tr("th_" + theme), n)
        if not os.path.isfile(os.path.join(WORLDS_DIR, dw_clean_name(name) + ".json")):
            return name, n


# ---- sound: short beeps in a helper thread (Windows only; silent elsewhere) ----
try:
    import winsound
except ImportError:
    winsound = None

DW_SOUNDS = {
    "place": [(660, 60), (880, 80)], "flip": [(620, 40), (470, 50)], "bonk": [(140, 120), (95, 150)],
    "fall": [(900, 60), (760, 60), (620, 60), (480, 60), (360, 60), (260, 60), (180, 80)],
    "water": [(300, 100), (220, 160)], "lava": [(110, 320)], "sand": [(90, 320)],
    "poof": [(200, 130), (520, 90), (780, 130)], "done": [(523, 110), (659, 110), (784, 220)], "miss": [(220, 90)],
    "ignite": [(120, 90), (150, 90), (180, 90)],
    "launch": [(260, 40), (340, 40), (440, 40), (560, 40), (720, 40), (920, 40), (1180, 40), (1500, 50)],
    "shoot": [(700, 35), (950, 35), (1300, 45)],
    "burst": [(2200, 20), (1100, 35), (600, 55)],
}


class DwSound(object):
    """Plays the beeps one after the other in a daemon thread; what piles up is dropped."""

    def __init__(self):
        self.on = True
        self.q = queue.Queue()
        if winsound is not None:
            threading.Thread(target=self._worker, daemon=True).start()

    def _worker(self):
        while True:
            name = self.q.get()
            try:
                for (f, ms) in DW_SOUNDS.get(name, ()):
                    winsound.Beep(int(f), int(ms))
            except Exception:
                pass

    def play(self, name):
        if self.on and winsound is not None and self.q.qsize() < 4:
            self.q.put(name)


# *************** DEL 17 - WINDOW ICON (EXTERNAL .ICO) *****************
# Copy verbatim into every program.  Rules and pitfalls: 10_icons.md
#
# The icon is an EXTERNAL file:  <home>\Icons\<PROGRAM_NAME>.ico
# It is never embedded in the program and never generated by it.  If the file
# is missing the program just runs with the default icon.
#
# Needs:  import ctypes, os, platform
#         block_home.py  (PROGRAM_NAME, ICON_DIR)
#
# In main():
#     _set_app_id()                                   # BEFORE tk.Tk()
#     root = tk.Tk()
#     root.title("...")
#     ... build the UI ...
#     root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
#     root.mainloop()


def _set_app_id():
    """Own taskbar group and icon for this program.  Call BEFORE tk.Tk()."""
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "MyOrg." + PROGRAM_NAME + ".1")
    except Exception:
        pass


def _find_icon_path() -> str:
    """<home>\\Icons\\<name>.ico, else the old place next to the .py, else ""."""
    name = PROGRAM_NAME + ".ico"
    here = os.path.dirname(os.path.abspath(globals().get("__file__", "")))
    for d in (ICON_DIR, os.path.join(here, "Icons")):
        p = os.path.join(d, name)
        if os.path.isfile(p):
            return p
    return ""


def _set_window_icon(root) -> None:
    if platform.system() != "Windows":
        return
    ico_path = _find_icon_path()
    if not ico_path:
        return

    # Channel 1: tkinter's own API
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass

    # Channel 2: WM_SETICON via Win32 (taskbar and Alt-Tab)
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080

        # winfo_id() is tkinter's inner frame; its PARENT is the real Win32
        # window.  FindWindowW by title is the fallback (it can pick the wrong
        # window if two windows share a title).
        hwnd = user32.GetParent(root.winfo_id()) or \
               user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON, 0, 0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig:
            user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml:
            user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


# *************** DEL 18 - THE WINDOW *****************
BG = "#1e1e2e"
PANEL = "#252535"
FG = "#e0e0e0"
DIM = "#9090a8"
ACCENT = "#89b4fa"
BTN = "#3a3a4e"
GREEN = "#40a070"
GOLD = "#ffd45e"
THEME = dict(bg=BG, panel=PANEL, fg=FG, dim=DIM, accent=ACCENT, btn=BTN, btnfg=FG, field="#11111b", field_fg=FG)
THEME_ORDER = ["random"] + DW_THEMES


def dw_plain(s):
    """A text of the language files without its picture symbol in front (the phone shows emoji there; Tk's labels should not)."""
    return re.sub(r"^[^\w{]+", "", s)


def dw_btn(parent, text="", command=None, width=10, bg=BTN, fg=FG, font=("Segoe UI", 10, "bold"), **kw):
    """A flat button of fixed width (the text never changes its size) that never takes the keyboard focus."""
    return tk.Button(parent, text=text, command=command, width=width, bd=0, relief="flat", bg=bg, fg=fg, activebackground=ACCENT,
                     activeforeground="#11111b", disabledforeground="#5a5a70", font=font, cursor="hand2", takefocus=0, **kw)


class DinoWorldApp(object):
    """The Dino World window: theme buttons on top, the world in the middle, the dinosaurs on the right, the buttons below."""

    def __init__(self, root, settings=None):
        self.root = root
        self.S = settings if settings is not None else load_settings()
        LANG.set(self.S.get("lang", "en"))
        self.sound = DwSound()
        self.sound.on = bool(self.S.get("sound", True))
        self.world = None
        self.view = None
        self.dinos = []
        self.sel = -1
        self.mode = "edit"
        self.sim = None
        self.speed = 2 if self.S.get("speed", 1) > 1 else 1
        self.theme_key = self.S.get("theme", "random") if self.S.get("theme") in THEME_ORDER else "random"
        self.timer = None
        self.resize_job = None
        self.hint_job = None
        self.pt = None
        self.photo = None
        self.img_id = None
        self.drag = None
        self.banner = False
        self.banner_lines = []
        self.view = None
        self.clouds = []
        self.acc = 0.0
        self.last = 0.0
        self.end_at = 0.0
        self.ev_idx = 0
        self.pal_imgs = {}
        self.put = self.S.get("put", "dino") if self.S.get("put") in DW_PUT_MODES else "dino"     # what a click on the world puts out
        self.S["show_playertext"] = False
        self._build()
        root.after(80, self._first)

    # ---- building the window ----------------------------------------------------------------------------------------
    def _build(self):
        root = self.root
        root.configure(bg=BG)
        root.minsize(820, 710)                      # the palette (dinosaurs + the three extra buttons) needs this much height
        root.geometry(self.S.get("geometry") or "1080x760")
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        root.grid_rowconfigure(1, weight=1)
        root.grid_columnconfigure(0, weight=1)
        bar = tk.Frame(root, bg=BG)
        bar.grid(row=0, column=0, columnspan=2, sticky="ew", padx=8, pady=(8, 4))
        self.lbl_title = tk.Label(bar, width=14, anchor="w", bg=BG, fg=GOLD, font=("Segoe UI", 15, "bold"))
        self.lbl_title.pack(side="left", padx=(0, 10))
        self.theme_btns = {}
        for key in THEME_ORDER:
            b = dw_btn(bar, width=9, command=lambda k=key: self.pick_theme(k))
            b.pack(side="left", padx=2)
            self.theme_btns[key] = b
        self.btn_help = dw_btn(bar, width=8, command=self.show_help)
        self.btn_help.pack(side="right", padx=2)
        self.btn_about = dw_btn(bar, width=8, command=self.show_about)
        self.btn_about.pack(side="right", padx=2)
        self.lang_pick = make_language_picker(bar, LANGS, lambda: LANG.code, self.set_lang, bg=BG, fg=FG, hover=ACCENT)
        self.lang_pick.pack(side="right", padx=8)
        self.cv = tk.Canvas(root, bg=BG, highlightthickness=0, cursor="hand2")
        self.cv.grid(row=1, column=0, sticky="nsew", padx=(8, 4), pady=2)
        self.cv.bind("<Configure>", self._cv_configured)
        self.cv.bind("<ButtonPress-1>", self.on_down)
        self.cv.bind("<B1-Motion>", self.on_move)
        self.cv.bind("<ButtonRelease-1>", self.on_up)
        pal = tk.Frame(root, bg=PANEL)
        pal.grid(row=1, column=1, sticky="ns", padx=(4, 8), pady=2)
        self.pal_btns = {}
        for i, typ in enumerate(DW_TYPE_ORDER):
            img = ImageTk.PhotoImage(dw_palette_pic(typ, 56))
            self.pal_imgs[typ] = img
            b = tk.Button(pal, image=img, compound="top", width=104, height=92, bd=0, relief="flat", bg=BTN, fg=FG, activebackground=ACCENT,
                          activeforeground="#11111b", disabledforeground="#5a5a70", font=("Segoe UI", 8, "bold"), cursor="hand2", takefocus=0,
                          command=lambda t=typ: self.pick_type(t))
            b.grid(row=i // 2, column=i % 2, padx=3, pady=3)
            self.pal_btns[typ] = b
        extra = tk.Frame(pal, bg=PANEL)                  # rocket, rocket with a dinosaur, fireworks
        extra.grid(row=(len(DW_TYPE_ORDER) + 1) // 2, column=0, columnspan=2, pady=(6, 3))
        self.put_btns = {}
        self.rd_pic_for = ""
        for j, key in enumerate(("rocket", "rocketdino", "fw")):
            b = tk.Button(extra, compound="top", width=68, height=82, wraplength=64, justify="center", bd=0, relief="flat", bg=BTN, fg=FG,
                          activebackground=ACCENT, activeforeground="#11111b", disabledforeground="#5a5a70", font=("Segoe UI", 8, "bold"),
                          cursor="hand2", takefocus=0, command=lambda k=key: self.pick_put(k))
            b.grid(row=0, column=j, padx=2)
            self.put_btns[key] = b
        self.put_pics()
        self.lbl_hint = tk.Label(root, anchor="w", width=10, bg=BG, fg=DIM, font=("Segoe UI", 11))
        self.lbl_hint.grid(row=2, column=0, columnspan=2, sticky="ew", padx=12, pady=(2, 0))
        bottom = tk.Frame(root, bg=BG, height=46)
        bottom.grid(row=3, column=0, columnspan=2, sticky="ew", padx=8, pady=(4, 8))
        bottom.grid_propagate(False)
        self.fr_edit = tk.Frame(bottom, bg=BG)
        self.fr_run = tk.Frame(bottom, bg=BG)
        self.fr_edit.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.fr_run.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.btn_flip = dw_btn(self.fr_edit, width=11, command=self.flip)
        self.btn_remove = dw_btn(self.fr_edit, width=9, command=self.remove)
        self.btn_clear = dw_btn(self.fr_edit, width=7, command=self.clear)
        self.btn_save = dw_btn(self.fr_edit, width=7, command=self.save_world)
        self.btn_load = dw_btn(self.fr_edit, width=7, command=self.show_load)
        self.btn_notes = dw_btn(self.fr_edit, width=10, command=self.open_notes)
        self.var_sound = tk.BooleanVar(value=self.sound.on)
        self.chk_sound = tk.Checkbutton(self.fr_edit, variable=self.var_sound, command=self.toggle_sound, bg=BG, fg=FG, selectcolor=PANEL,
                                        activebackground=BG, activeforeground=ACCENT, highlightthickness=0, takefocus=0, font=("Segoe UI", 10))
        self.btn_run = dw_btn(self.fr_edit, width=12, bg=GREEN, command=self.run, font=("Segoe UI", 12, "bold"))
        for w in (self.btn_flip, self.btn_remove, self.btn_clear):
            w.pack(side="left", padx=2, pady=3)
        tk.Frame(self.fr_edit, bg=BG, width=14).pack(side="left")
        for w in (self.btn_save, self.btn_load, self.btn_notes):
            w.pack(side="left", padx=2, pady=3)
        self.btn_run.pack(side="right", padx=2, pady=3)
        self.chk_sound.pack(side="right", padx=10)
        self.btn_edit = dw_btn(self.fr_run, width=10, command=self.stop_run)
        self.btn_again = dw_btn(self.fr_run, width=10, bg=GREEN, command=self.run)
        self.btn_fast = dw_btn(self.fr_run, width=10, command=self.toggle_fast)
        for w in (self.btn_edit, self.btn_again, self.btn_fast):
            w.pack(side="left", padx=2, pady=3)
        root.bind("<Delete>", lambda e: self.remove())
        root.bind("<space>", self._space)
        self.relabel()

    def _space(self, event=None):
        """The space bar runs (or runs again) - unless the player is typing."""
        try:
            w = self.root.focus_get()
            if w is not None and w.winfo_class() in ("Entry", "Text"):
                return
        except Exception:
            pass
        self.run()

    def relabel(self):
        """Every text of the window again, in the current language."""
        self.root.title(tr("dw_title"))
        self.lbl_title.configure(text=tr("dw_title"))
        for key, b in self.theme_btns.items():
            b.configure(text=tr("th_" + key))
        for typ, b in self.pal_btns.items():
            b.configure(text=tr("dn_" + typ))
        for key, b in self.put_btns.items():
            b.configure(text=tr({"rocket": "dn_rocket", "rocketdino": "dn_rocketdino", "fw": "dn_fireworks"}[key]))
        self.btn_help.configure(text=tr("dw_help"))
        self.btn_about.configure(text=tr("dw_about"))
        self.btn_remove.configure(text=tr("dw_remove"))
        self.btn_clear.configure(text=tr("dw_clear"))
        self.btn_save.configure(text=tr("dw_save"))
        self.btn_load.configure(text=tr("dw_load"))
        self.btn_notes.configure(text=tr("dw_notes"))
        self.chk_sound.configure(text=tr("dw_sound"))
        self.btn_run.configure(text="▶ " + tr("dw_run"))
        self.btn_edit.configure(text="✎ " + tr("dw_edit"))
        self.btn_again.configure(text="▶ " + tr("dw_again"))
        self.btn_fast.configure(text=tr("dw_fast"))
        self.controls()

    def controls(self):
        """Which buttons work now, which way the arrow points, which hint is shown."""
        edit = self.mode == "edit"
        if edit:
            self.fr_run.lower()
            self.fr_edit.lift()
        else:
            self.fr_edit.lower()
            self.fr_run.lift()
        d = self.dinos[self.sel]["d"] if 0 <= self.sel < len(self.dinos) else self.S.get("dir", 1)
        self.btn_flip.configure(text=(tr("dw_flip") + " ▶") if d > 0 else ("◀ " + tr("dw_flip")))
        fw_sel = 0 <= self.sel < len(self.dinos) and self.dinos[self.sel]["t"] == "fireworks"     # a launcher has no front to turn
        self.btn_flip.configure(state="disabled" if fw_sel else "normal")
        self.btn_remove.configure(state="normal" if (edit and self.sel >= 0) else "disabled")
        self.put_pics()
        for typ, b in self.pal_btns.items():             # during a run the palette stays (the world keeps its size) but is quiet; pick_type ignores the click
            on = typ == self.S.get("type", "trex") and self.put in ("dino", "rocketdino")      # with a rocket + dino the lit dinosaur is the passenger
            b.configure(state="normal", bg=(ACCENT if on else BTN) if edit else PANEL, fg=("#11111b" if on else FG) if edit else DIM,
                        cursor="hand2" if edit else "arrow")
        for key, b in self.put_btns.items():
            on = key == self.put
            b.configure(state="normal", bg=(ACCENT if on else BTN) if edit else PANEL, fg=("#11111b" if on else FG) if edit else DIM,
                        cursor="hand2" if edit else "arrow")
        for key, b in self.theme_btns.items():
            on = key == self.theme_key
            b.configure(state="normal" if edit else "disabled", bg=ACCENT if on else BTN, fg="#11111b" if on else FG)
        self.btn_fast.configure(bg=ACCENT if self.speed > 1 else BTN, fg="#11111b" if self.speed > 1 else FG)
        self.set_hint(self.idle_hint())

    def idle_hint(self):
        """The hint line when nothing special happened: what to do next."""
        if self.mode != "edit":
            return tr("hint_run")
        if self.sel >= 0:
            return tr("hint_sel")
        return tr({"dino": "hint_pick", "rocket": "hint_rocket", "rocketdino": "hint_rocketdino", "fw": "hint_fw"}[self.put])

    def put_pics(self):
        """The pictures of the three extra palette buttons (the rocket + dino one shows the dinosaur that is picked)."""
        typ = self.S.get("type", "trex")
        if typ not in DW_TYPES:
            typ = "trex"
        if self.rd_pic_for == typ:
            return
        self.rd_pic_for = typ
        for key, b in self.put_btns.items():
            img = ImageTk.PhotoImage(dw_put_pic(key, typ, 44))
            self.pal_imgs["put_" + key] = img
            b.configure(image=img)

    def set_hint(self, text):
        self.lbl_hint.configure(text=text)

    def hint(self, text, ms=2200):
        """A short message in the hint line; the normal hint comes back after a while."""
        self.set_hint(text)
        if self.hint_job:
            self.root.after_cancel(self.hint_job)
        self.hint_job = self.root.after(ms, self._hint_back)

    def _hint_back(self):
        self.hint_job = None
        self.set_hint(self.idle_hint())

    # ---- worlds ----------------------------------------------------------------------------------------------------------
    def stage_size(self):
        return max(100, self.cv.winfo_width()), max(100, self.cv.winfo_height())

    def shape_now(self):
        w, h = self.stage_size()
        return "L" if w / float(h) >= 1.15 else "P"

    def _first(self):
        cur = self.S.get("cur")
        data = cur if isinstance(cur, dict) else None
        got = dw_world_from_data(data) if data else None
        if got:
            self.world, self.dinos = got
            self.theme_key = self.S.get("theme") if self.S.get("theme") in THEME_ORDER else self.world["theme"]
            self.after_world()
        else:
            self.new_world("random")

    def new_world(self, key):
        theme = random.choice(DW_THEMES) if key == "random" else key
        self.theme_key = key
        self.S["theme"] = key
        self.world = dw_make_world(theme, random.randint(1, 2147483000), self.shape_now())
        self.dinos = []
        self.sel = -1
        self.mode = "edit"
        log("new world: %s (seed %d, %s)" % (theme, self.world["seed"], self.world["shape"]))
        self.after_world()

    def after_world(self):
        self.sim = None
        self.clear_banner()
        self.rebuild()
        self.render()
        self.keep_current()
        self.controls()

    def keep_current(self):
        w = self.world
        if w:
            self.S["cur"] = {"theme": w["theme"], "seed": w["seed"], "shape": w["shape"], "dinos": [dict(d) for d in self.dinos]}
            save_settings(self.S)

    def pick_theme(self, key):
        if self.mode != "edit":
            return
        if self.dinos and not self.ask_yes_no(tr("dw_new"), tr("ask_new")):
            return
        self.new_world(key)

    def pick_type(self, typ):
        if self.mode != "edit":
            return
        self.S["type"] = typ
        if self.put in ("rocket", "fw"):                  # a dinosaur button means "put out dinosaurs"; with rocket + dino it only changes who rides
            self.put = "dino"
        self.S["put"] = self.put
        save_settings(self.S)
        self.controls()

    def pick_put(self, key):
        """Rocket / Rocket + dino / Fireworks: what the next click on the world puts out."""
        if self.mode != "edit":
            return
        self.put = key
        self.S["put"] = key
        save_settings(self.S)
        self.sel = -1
        self.controls()
        self.render()

    # ---- drawing -----------------------------------------------------------------------------------------------------------
    def _cv_configured(self, event):
        if self.resize_job:
            self.root.after_cancel(self.resize_job)
        self.resize_job = self.root.after(220, self._resized)

    def _resized(self):
        self.resize_job = None
        if self.world:
            self.rebuild()
            self.render_now()
            if self.banner and self.sim and self.sim["done"] and self.mode == "run":
                self.show_banner()

    def rebuild(self):
        if not self.world:
            return
        w, h = self.stage_size()
        old = self.view["cell"] if self.view else 0
        self.view = dw_make_view(self.world, w, h)
        if old != self.view["cell"]:
            dw_forget_sprites()                      # pictures of the old size are not needed any more
        self.cv.configure(bg=DW_PAL[self.world["theme"]]["frame"])
        self.cv.delete("all")
        self.img_id = self.cv.create_image(self.view["ox"], self.view["oy"], anchor="nw")
        self.photo = None

    def render(self, clouds=(), t=0.0):
        if not self.view:
            return
        ents = self.sim["ents"] if (self.mode == "run" and self.sim) else dw_edit_ents(self.dinos)
        img = dw_render_scene(self.view, ents, t, self.sel if self.mode == "edit" else -1, clouds)
        self.photo = ImageTk.PhotoImage(img)
        self.cv.itemconfigure(self.img_id, image=self.photo)

    def render_now(self):
        if self.mode == "run" and self.sim:
            t_sim = self.sim["tick"] * DW_DT
            self.render([], t_sim)
        else:
            self.render()

    # ---- the mouse ------------------------------------------------------------------------------------------------------------
    def world_point(self, ev):
        v = self.view
        return (ev.x - v["ox"]) / float(v["cell"]), (ev.y - v["oy"]) / float(v["cell"])

    def hit(self, wx, wy):
        """Which put-out dinosaur is under the pointer (the front one first)."""
        best, by = -1, -1.0
        for i, d in enumerate(self.dinos):
            info = DW_ALL[d["t"]]
            fy = d["y"] + 0.5
            lift = 0.9 if info["kind"] == "fly" else 0.0
            height = info.get("hh", info["size"]) * 0.92                                    # a rocket is much taller than it is wide
            if (abs(wx - (d["x"] + 0.5)) <= info["size"] * 0.42 and fy - height - lift <= wy <= fy + 0.45 and fy >= by):
                best, by = i, fy
        return best

    def on_down(self, ev):
        self.cv.focus_set()
        if self.mode != "edit" or not self.view:
            return
        wx, wy = self.world_point(ev)
        hit = self.hit(wx, wy)
        if hit >= 0:
            self.sel = hit
            self.drag = {"i": hit, "sx": ev.x, "sy": ev.y, "moved": False}
        else:
            self.drag = None
            cx, cy = int(math.floor(wx)), int(math.floor(wy))
            typ = self.S.get("type", "trex")
            direction = 1 if self.S.get("dir", 1) >= 0 else -1
            if self.put == "rocket":
                item = {"t": "rocket", "x": cx, "y": cy, "d": direction, "r": ""}
            elif self.put == "rocketdino":
                item = {"t": "rocket", "x": cx, "y": cy, "d": direction, "r": typ}
            elif self.put == "fw":
                item = {"t": "fireworks", "x": cx, "y": cy, "d": 1}
            else:
                item = {"t": typ, "x": cx, "y": cy, "d": direction}
            if len(self.dinos) >= DW_MAX_DINOS:
                self.hint(tr("hint_many"))
                return
            if dw_can_place(self.world, self.dinos, item["t"], cx, cy):
                self.dinos.append(item)
                self.sel = len(self.dinos) - 1
                self.sound.play("place")
                self.keep_current()
            else:
                self.hint(tr("hint_nope"))
                self.sound.play("miss")
        self.controls()
        self.render()

    def on_move(self, ev):
        dr = self.drag
        if not dr or self.mode != "edit":
            return
        if not dr["moved"] and math.hypot(ev.x - dr["sx"], ev.y - dr["sy"]) < 8:
            return
        dr["moved"] = True
        wx, wy = self.world_point(ev)
        cx, cy = int(math.floor(wx)), int(math.floor(wy))
        d = self.dinos[dr["i"]] if dr["i"] < len(self.dinos) else None
        if not d or (cx == d["x"] and cy == d["y"]):
            return
        if dw_can_place(self.world, self.dinos, d["t"], cx, cy, dr["i"]):
            d["x"], d["y"] = cx, cy
            self.render()

    def on_up(self, ev):
        if self.drag and self.drag["moved"]:
            self.keep_current()
            self.sound.play("place")
        self.drag = None

    # ---- the buttons of the editor -------------------------------------------------------------------------------------------
    def flip(self):
        if self.mode != "edit":
            return
        if 0 <= self.sel < len(self.dinos):
            d = self.dinos[self.sel]
            if d["t"] == "fireworks":                      # a launcher has no front
                return
            d["d"] = -d["d"]
            self.S["dir"] = d["d"]
        else:
            self.S["dir"] = -self.S.get("dir", 1)
        self.sound.play("flip")
        self.keep_current()
        self.controls()
        self.render()

    def remove(self):
        if self.mode != "edit" or not (0 <= self.sel < len(self.dinos)):
            return
        del self.dinos[self.sel]
        self.sel = -1
        self.sound.play("miss")
        self.keep_current()
        self.controls()
        self.render()

    def clear(self):
        if self.mode != "edit" or not self.dinos:
            return
        if self.ask_yes_no(tr("dw_clear"), tr("ask_clear")):
            self.dinos = []
            self.sel = -1
            self.keep_current()
            self.controls()
            self.render()

    def toggle_sound(self):
        self.sound.on = bool(self.var_sound.get())
        self.S["sound"] = self.sound.on
        save_settings(self.S)

    def toggle_fast(self):
        self.speed = 1 if self.speed > 1 else 2
        self.S["speed"] = self.speed
        save_settings(self.S)
        self.controls()

    # ---- the run -----------------------------------------------------------------------------------------------------------------
    def run(self):
        if not self.world:
            return
        if self.timer:
            self.root.after_cancel(self.timer)
            self.timer = None
        self.sel = -1
        self.sim = dw_start_run(self.world, [dict(d) for d in self.dinos])
        self.mode = "run"
        self.ev_idx = 0
        self.clouds = []
        self.acc = 0.0
        self.end_at = 0.0
        self.last = time.time()
        self.clear_banner()
        log("run: %d dinosaurs, %s world %d" % (len(self.dinos), self.world["theme"], self.world["seed"]))
        self.controls()
        self.tick()

    def tick(self):
        self.timer = None
        if self.mode != "run" or not self.sim:
            return
        now = time.time()
        sim = self.sim
        self.acc += min(0.2, now - self.last) * self.speed
        self.last = now
        n = 0
        while self.acc >= DW_DT and not sim["done"] and n < 12:
            dw_step(sim)
            self.acc -= DW_DT
            n += 1
            self.handle_events()
        t_sim = sim["tick"] * DW_DT + (0.0 if sim["done"] else self.acc)
        clouds = [{"x": c["x"], "y": c["y"], "p": (t_sim - c["t0"]) / 1.0} for c in self.clouds]
        clouds = [c for c in clouds if c["p"] < 1]
        self.render(clouds, t_sim)
        if sim["done"] and not self.end_at:
            self.end_at = now + 0.9 / self.speed
        if self.end_at and now >= self.end_at and not clouds:
            self.finish()
            return
        self.timer = self.root.after(max(1, 33 - int((time.time() - now) * 1000)), self.tick)

    def handle_events(self):
        sim = self.sim
        t_sim = sim["tick"] * DW_DT
        while self.ev_idx < len(sim["events"]):
            ev = sim["events"][self.ev_idx]
            self.ev_idx += 1
            if ev["e"] == "poof":
                self.clouds.append({"x": ev["x"], "y": ev["y"], "t0": t_sim})
                self.sound.play("poof")
            elif ev["e"] == "ignite":
                self.sound.play("ignite")
            elif ev["e"] == "launch":
                self.sound.play("launch")
            elif ev["e"] == "shoot":
                self.sound.play("shoot")
            elif ev["e"] == "burst":
                self.sound.play("burst")
            elif ev["e"] == "bonk":
                self.sound.play("bonk")
            elif ev["e"] == "fall":
                self.sound.play("fall")
            elif ev["e"] == "sink":
                self.sound.play("water" if ev["c"] == "w" else "lava" if ev["c"] == "l" else "sand")

    def stop_run(self):
        if self.timer:
            self.root.after_cancel(self.timer)
            self.timer = None
        self.mode = "edit"
        self.sim = None
        self.clouds = []
        self.clear_banner()
        self.controls()
        self.render()

    def finish(self):
        self.timer = None
        self.sound.play("done")
        log("run done after %d ticks: %s %s" % (self.sim["tick"], dw_summary(self.sim), dw_summary_things(self.sim)))
        self.banner_lines = self.summary_lines()
        self.show_banner()

    def summary_lines(self):
        """The lines of the 'All done!' banner: how every dinosaur ended, then the rockets and fireworks."""
        sm = dw_summary(self.sim)
        pairs = [("stopped", "sum_stopped"), ("cloud", "sum_cloud"), ("fell", "sum_fell"), ("sank", "sum_sank"), ("flew", "sum_flew")]
        lines = [dw_plain(tr(k, n=sm[c])) for (c, k) in pairs if sm[c] > 0]
        th = dw_summary_things(self.sim)
        lines += [dw_plain(tr(k, n=th[c])) for (c, k) in (("rockets", "sum_rockets"), ("riders", "sum_riders"), ("fireworks", "sum_fireworks")) if th[c] > 0]
        return lines or [tr("sum_none")]

    def show_banner(self):
        self.cv.delete("banner")
        cw, ch = self.stage_size()
        lines = self.banner_lines
        w = 380
        h = 80 + 32 * len(lines)
        x0, y0 = (cw - w) // 2, (ch - h) // 2
        self.cv.create_rectangle(x0, y0, x0 + w, y0 + h, fill=BG, outline=GOLD, width=4, tags="banner")
        self.cv.create_text(cw // 2, y0 + 36, text=tr("done_title"), fill=GOLD, font=("Segoe UI", 22, "bold"), tags="banner")
        for i, text in enumerate(lines):
            self.cv.create_text(cw // 2, y0 + 80 + 32 * i, text=text, fill=FG, font=("Segoe UI", 14), width=w - 30, tags="banner")
        self.banner = True

    def clear_banner(self):
        self.cv.delete("banner")
        self.banner = False

    # ---- dialogs ---------------------------------------------------------------------------------------------------------------
    def center(self, top):
        top.update_idletasks()
        r = self.root
        x = r.winfo_x() + (r.winfo_width() - top.winfo_reqwidth()) // 2
        y = r.winfo_y() + (r.winfo_height() - top.winfo_reqheight()) // 3
        top.geometry("+%d+%d" % (max(0, x), max(0, y)))

    def _dialog(self, title):
        top = tk.Toplevel(self.root)
        top.title(title)
        top.configure(bg=BG)
        top.resizable(False, False)
        top.transient(self.root)
        return top

    def ask_yes_no(self, title, text):
        top = self._dialog(title)
        result = {"v": False}

        def done(v):
            result["v"] = v
            top.destroy()
        tk.Label(top, text=text, bg=BG, fg=FG, font=("Segoe UI", 11), wraplength=360, justify="left").pack(padx=22, pady=(20, 12))
        row = tk.Frame(top, bg=BG)
        row.pack(pady=(0, 16))
        dw_btn(row, tr("dw_yes"), lambda: done(True), width=10, bg=GREEN).pack(side="left", padx=6)
        dw_btn(row, tr("dw_no"), lambda: done(False), width=10).pack(side="left", padx=6)
        top.protocol("WM_DELETE_WINDOW", lambda: done(False))
        self.center(top)
        top.update()
        make_modal(top, on_escape=lambda: done(False))
        top.wait_window()
        return result["v"]

    def ask_name(self, title, text, default):
        top = self._dialog(title)
        result = {"v": None}
        var = tk.StringVar(value=default)

        def done(v):
            result["v"] = v
            top.destroy()
        tk.Label(top, text=text, bg=BG, fg=FG, font=("Segoe UI", 11)).pack(padx=22, pady=(18, 6))
        ent = new_entry(top, textvariable=var, width=30, bd=0, bg="#11111b", fg=FG, insertbackground=FG, font=("Segoe UI", 12))
        ent.pack(padx=22, ipady=4)
        row = tk.Frame(top, bg=BG)
        row.pack(pady=14)
        dw_btn(row, tr("dw_ok"), lambda: done(var.get()), width=10, bg=GREEN).pack(side="left", padx=6)
        dw_btn(row, tr("dw_cancel"), lambda: done(None), width=10).pack(side="left", padx=6)
        top.bind("<Return>", lambda e: done(var.get()))
        top.protocol("WM_DELETE_WINDOW", lambda: done(None))
        self.center(top)
        top.update()
        make_modal(top, on_escape=lambda: done(None))
        ent.focus_force()
        ent.select_range(0, "end")
        top.wait_window()
        return result["v"]

    def show_help(self):
        top = self._dialog(tr("help_title"))
        top.resizable(True, True)
        txt = new_text(top, width=62, height=22, wrap="word", bd=0, bg="#11111b", fg=FG, padx=12, pady=10, font=("Segoe UI", 11))
        sb = tk.Scrollbar(top, command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        row = tk.Frame(top, bg=BG)
        row.pack(side="bottom", pady=8)
        dw_btn(row, tr("dw_close"), top.destroy, width=10).pack()
        sb.pack(side="right", fill="y")
        txt.pack(side="left", fill="both", expand=True)
        txt.insert("1.0", tr("help_text") + "\n\n" + tr("help_more"))
        txt.configure(state="disabled")
        self.center(top)
        top.update()
        make_modal(top)

    def show_about(self):
        top = self._dialog(tr("dw_about") + " " + tr("dw_title"))
        pic = ImageTk.PhotoImage(dw_palette_pic("trex", 96))
        lab = tk.Label(top, image=pic, bg=BG)
        lab.image = pic
        lab.pack(pady=(18, 0))
        tk.Label(top, text=tr("dw_title"), bg=BG, fg=GOLD, font=("Segoe UI", 20, "bold")).pack()
        tk.Label(top, text=tr("about_version", v=DW_VERSION), bg=BG, fg=DIM, font=("Segoe UI", 9, "italic")).pack(pady=(2, 8))
        tk.Label(top, text=tr("about_text"), bg=BG, fg=FG, font=("Segoe UI", 10), wraplength=320, justify="center").pack(padx=24, pady=(0, 6))
        dw_btn(top, tr("dw_close"), top.destroy, width=10).pack(pady=(10, 16))
        self.center(top)
        top.update()
        make_modal(top)

    # ---- saving and opening ----------------------------------------------------------------------------------------------------
    def save_world(self):
        if not self.world or self.mode != "edit":
            return
        name, n = next_world_name(self.world["theme"], int(self.S.get("n", 0)))
        got = self.ask_name(tr("save_title"), tr("save_name"), name)
        if not got or not dw_clean_name(got):
            return
        path = save_world_file(got, self.world, self.dinos)
        if path:
            self.S["n"] = n
            save_settings(self.S)
            self.sound.play("done")
            self.hint(tr("hint_saved"), 1800)
            log("saved world %s" % path)

    def show_load(self):
        if self.mode != "edit":
            return
        top = self._dialog(tr("load_title"))
        top.resizable(True, True)
        worlds = list_world_files()
        outer = tk.Frame(top, bg=BG)
        outer.pack(fill="both", expand=True)
        row = tk.Frame(top, bg=BG)
        row.pack(side="bottom", pady=8)
        dw_btn(row, tr("dw_close"), top.destroy, width=10).pack(side="left", padx=6)
        dw_btn(row, tr("load_folder"), lambda: self._open_folder(WORLDS_DIR), width=10).pack(side="left", padx=6)
        keep = []

        def reload():
            top.destroy()
            self.show_load()

        def chosen(data):
            top.destroy()
            self.load_world(data)

        def delete(path, name):
            if self.ask_yes_no(tr("dw_del"), name):
                for p in (path, os.path.splitext(path)[0] + ".jpg"):
                    try:
                        os.remove(p)
                    except OSError:
                        pass
                reload()
        if not worlds:
            tk.Label(outer, text=tr("load_empty"), bg=BG, fg=FG, font=("Segoe UI", 11), wraplength=360).pack(padx=30, pady=30)
        else:
            cv = tk.Canvas(outer, bg=BG, highlightthickness=0, width=720, height=420)
            sb = tk.Scrollbar(outer, command=cv.yview)
            cv.configure(yscrollcommand=sb.set)
            sb.pack(side="right", fill="y")
            cv.pack(side="left", fill="both", expand=True)
            grid = tk.Frame(cv, bg=BG)
            cv.create_window(0, 0, window=grid, anchor="nw")
            for i, (path, data) in enumerate(worlds[:60]):
                jpg = os.path.splitext(path)[0] + ".jpg"
                pic = None
                try:
                    if not os.path.isfile(jpg):
                        w, dn = dw_world_from_data(data)
                        dw_thumb(w, dn).save(jpg, quality=75)
                    pic = ImageTk.PhotoImage(Image.open(jpg))
                except Exception:
                    pic = None
                keep.append(pic)
                cell = tk.Frame(grid, bg=PANEL)
                cell.grid(row=i // 3, column=i % 3, padx=6, pady=6)
                lab = tk.Label(cell, image=pic, bg=PANEL, cursor="hand2", width=224, height=150)
                lab.pack(padx=4, pady=(4, 0))
                lab.bind("<Button-1>", lambda e, d=data: chosen(d))
                bot = tk.Frame(cell, bg=PANEL)
                bot.pack(fill="x", padx=4, pady=2)
                tk.Label(bot, text="%s · %d" % (data.get("name", ""), len(data.get("dinos", []))), bg=PANEL, fg=FG, anchor="w",
                         font=("Segoe UI", 9), width=24).pack(side="left")
                tk.Button(bot, text="✖", command=lambda p=path, n=data.get("name", ""): delete(p, n), bd=0, bg=PANEL, fg=DIM,
                          activebackground=ACCENT, cursor="hand2", takefocus=0, font=("Segoe UI", 9)).pack(side="right")
            grid.update_idletasks()
            cv.configure(scrollregion=(0, 0, grid.winfo_reqwidth(), grid.winfo_reqheight()))
            cv.bind("<MouseWheel>", lambda e: cv.yview_scroll(-1 if e.delta > 0 else 1, "units"))
        top.keep_images = keep
        self.center(top)
        top.update()
        make_modal(top)

    def _open_folder(self, path):
        try:
            os.makedirs(path, exist_ok=True)
            os.startfile(path)
        except Exception:
            pass

    def load_world(self, data):
        got = dw_world_from_data(data)
        if not got:
            return
        self.world, self.dinos = got
        self.theme_key = self.world["theme"]
        self.S["theme"] = self.theme_key
        self.sel = -1
        self.mode = "edit"
        log("opened world %s" % data.get("name", ""))
        self.after_world()

    # ---- the player's own notes (block_popups.py) -----------------------------------------------------------------------------
    def pt_labels(self):
        return {"hint": tr("pt_hint"), "folder": tr("pt_folder"), "new": tr("pt_new"), "wrap": tr("pt_wrap"),
                "newname": tr("pt_newname"), "ok": tr("dw_ok"), "cancel": tr("dw_cancel")}

    def open_notes(self):
        try:
            if self.pt and self.pt.top.winfo_exists():
                self.pt.top.lift()
                return
        except Exception:
            pass
        self.S["show_playertext"] = True
        self.pt = PlayerTextPopup(self.root, self.S, ("show_playertext", "playertext_pos", "playertext_zoom", "playertext_sel"),
                                  lambda: save_settings(self.S), THEME, tr("dw_notes"), PROGRAM_HF_DIR, self.pt_labels,
                                  on_closed=self._notes_closed)

    def _notes_closed(self):
        self.pt = None

    # ---- language and closing ---------------------------------------------------------------------------------------------------
    def set_lang(self, code):
        LANG.set(code)
        self.S["lang"] = LANG.code
        save_settings(self.S)
        self.relabel()
        if self.banner and self.sim:
            self.finish_text_again()
        try:
            if self.pt and self.pt.top.winfo_exists():
                self.pt.relabel(tr("dw_notes"))
        except Exception:
            pass

    def finish_text_again(self):
        self.banner_lines = self.summary_lines()
        self.show_banner()

    def on_close(self):
        if self.timer:
            self.root.after_cancel(self.timer)
            self.timer = None
        try:
            if self.pt and self.pt.top.winfo_exists():
                self.pt.save_now()
        except Exception:
            pass
        try:
            self.S["geometry"] = self.root.geometry()
        except Exception:
            pass
        self.S["show_playertext"] = False
        save_settings(self.S)
        self.root.destroy()


# *************** DEL 19 - SELF-TEST (python Dino_World.py --selftest) *****************
# Checks the rules, the worlds, the language files, the pictures and (with a real window that is opened for a few seconds) the whole
# program, without touching Lars's own data: every folder is pointed at a temporary one.
class _Ev(object):
    def __init__(self, x, y):
        self.x, self.y = x, y


def selftest(sheet_path=""):
    import tempfile
    import shutil
    errors = []
    notes = []

    def check(cond, msg):
        if not cond:
            errors.append(msg)

    base = tempfile.mkdtemp(prefix="dino_world_test_")
    dw_set_dirs(base)
    try:
        # 1. worlds and the rules of a run
        rnd = random.Random(7)
        runs = 0
        for theme in DW_THEMES:
            for shape in "PL":
                cols, rows = DW_SHAPES[shape]
                for seed in range(1, 41):
                    w = dw_make_world(theme, seed, shape)
                    check(w["cols"] == cols and w["rows"] == rows and len(w["g"]) == rows and all(len(r) == cols for r in w["g"]), "size %s %s %d" % (theme, shape, seed))
                    check(dw_make_world(theme, seed, shape) == w, "not repeatable %s %s %d" % (theme, shape, seed))
                    free = [(x, y) for y in range(1, rows - 1) for x in range(1, cols - 1) if w["g"][y][x] in ".sb"]
                    check(len(free) >= 20, "too little ground %s %s %d" % (theme, shape, seed))
                    if seed <= 8:
                        dinos = []
                        for _ in range(8):
                            typ = rnd.choice(DW_TYPE_ORDER)
                            cx, cy = rnd.randint(1, cols - 2), rnd.randint(1, rows - 2)
                            if dw_can_place(w, dinos, typ, cx, cy):
                                dinos.append({"t": typ, "x": cx, "y": cy, "d": rnd.choice((-1, 1))})
                        sim = dw_run_all(dw_start_run(w, dinos))
                        runs += 1
                        check(sim["done"] and sim["tick"] < DW_MAX_TICKS, "run did not end %s %s %d" % (theme, shape, seed))
                        sim2 = dw_run_all(dw_start_run(w, dinos))
                        check(sim2["events"] == sim["events"], "run not repeatable %s %s %d" % (theme, shape, seed))
        notes.append("worlds + %d runs ok" % runs)
        # a dinosaur that walks into water sinks, into a wall stops, off a cliff falls, two meeting make a cloud
        w = {"theme": "nature", "seed": 1, "shape": "L", "cols": 18, "rows": 12, "deco": [],
             "g": ["tttttttttttttttttt", "t................t", "t.......w........t", "t................t", "t...c............t", "t................t",
                   "t................t", "t................t", "t................t", "t................t", "t................t", "tttttttttttttttttt"]}
        sim = dw_run_all(dw_start_run(w, [{"t": "trex", "x": 4, "y": 2, "d": 1}, {"t": "trex", "x": 2, "y": 4, "d": 1}, {"t": "trex", "x": 12, "y": 6, "d": 1},
                                          {"t": "raptor", "x": 3, "y": 8, "d": -1}, {"t": "raptor", "x": 14, "y": 9, "d": -1}]))
        sm = dw_summary(sim)
        check(sm == {"stopped": 2, "fell": 1, "sank": 1, "cloud": 0, "flew": 0} or sm["sank"] >= 1, "rules: %s" % sm)
        sim = dw_run_all(dw_start_run(w, [{"t": "trex", "x": 4, "y": 6, "d": 1}, {"t": "raptor", "x": 14, "y": 6, "d": -1}]))
        check(dw_summary(sim)["cloud"] == 2, "two meeting: %s" % dw_summary(sim))
        # rockets and fireworks (1.1)
        check(not dw_can_place(w, [], "rocket", 8, 2) and dw_can_place(w, [], "rocket", 5, 5) and not dw_can_place(w, [], "fireworks", 8, 2),
              "rockets must stand on dry ground")
        check(not dw_can_place(w, [{"t": "rocket", "x": 5, "y": 5, "d": 1, "r": ""}], "fireworks", 5, 5), "a rocket and a launcher in the same cell")
        sim = dw_run_all(dw_start_run(w, [{"t": "rocket", "x": 5, "y": 8, "d": 1, "r": "trex"}, {"t": "rocket", "x": 9, "y": 8, "d": 1, "r": ""},
                                          {"t": "raptor", "x": 1, "y": 8, "d": 1}]))
        names = [(ev["e"], ev["i"]) for ev in sim["events"]]
        check(("launch", 0) in names and ("launch", 1) in names and ("ignite", 0) in names, "rockets did not launch: %s" % names)
        check(all(e["st"] == "gone" for e in sim["ents"] if e["t"] == "rocket"), "rockets not gone")
        check(("bonk", 2) in names and sim["ents"][2]["st"] == "stop", "the raptor should bump into the rocket that has not left yet")
        sim_b = dw_run_all(dw_start_run(w, [{"t": "rocket", "x": 5, "y": 8, "d": 1, "r": "trex"}, {"t": "rocket", "x": 9, "y": 8, "d": 1, "r": ""},
                                            {"t": "raptor", "x": 1, "y": 8, "d": 1}]))
        check(sim_b["events"] == sim["events"], "rocket run not repeatable")
        check(dw_summary(sim) == {"stopped": 1, "fell": 0, "sank": 0, "cloud": 0, "flew": 0} and
              dw_summary_things(sim) == {"rockets": 2, "riders": 1, "fireworks": 0}, "summary with rockets: %s %s" % (dw_summary(sim), dw_summary_things(sim)))
        sim = dw_run_all(dw_start_run(w, [{"t": "fireworks", "x": 4, "y": 9, "d": 1}, {"t": "fireworks", "x": 12, "y": 9, "d": 1}]))
        bursts = [ev for ev in sim["events"] if ev["e"] == "burst"]
        check(len(bursts) == 2 * DW_FW_ROUNDS and all(1.0 <= ev["x"] <= 17.0 and ev["y"] >= 1.5 for ev in bursts), "fireworks bursts: %s" % bursts)
        check(all(e["st"] == "stop" for e in sim["ents"]) and sim["tick"] < DW_MAX_TICKS, "fireworks did not end")
        walkers = dw_run_all(dw_start_run(w, [{"t": "fireworks", "x": 6, "y": 6, "d": 1}, {"t": "trex", "x": 4, "y": 6, "d": 1}]))
        check(walkers["ents"][1]["x"] > 7 and not any(ev["e"] == "bonk" and ev.get("c") == "R" for ev in walkers["events"]), "a launcher must not stop a dinosaur")
        mixed = dw_clean_dinos([{"t": "rocket", "x": 3, "y": 4, "d": 1, "r": "ptero"}, {"t": "rocket", "x": 5, "y": 4, "r": "bogus"},
                                {"t": "fireworks", "x": 7, "y": 4, "d": -1}, {"t": "trex", "x": 2, "y": 2, "d": 1}])
        check(len(mixed) == 4 and mixed[0]["r"] == "ptero" and mixed[1]["r"] == "" and "r" not in mixed[3], "dw_clean_dinos with things: %s" % mixed)
        # 2. language files
        files = export_lang_files()
        check(len(files) == 1 and os.path.isfile(files[0]), "export_lang_files")
        got, name = read_lang_file("en")
        check(name == "English" and set(got) >= set(k for k in STRINGS), "en.txt misses keys: %s" % sorted(set(STRINGS) - set(got))[:5])
        sv = os.path.join(LANG_DIR, "sv.txt")
        with open(sv, "w", encoding="utf-8") as fh:
            fh.write("name = Svenska\ndw_title = Dinovärlden\nsum_cloud = 💥 {n} krockade\n")
        LANG.set("sv")
        check(tr("dw_title") == "Dinovärlden" and tr("dw_run") == "Run!" and tr("sum_cloud", n=3).endswith("3 krockade"), "language file fallback")
        check(dw_plain(tr("sum_cloud", n=3)) == "3 krockade", "dw_plain")
        LANG.set("en")
        notes.append("language files ok")
        # 3. pictures
        for theme in DW_THEMES:
            wd = dw_make_world(theme, 11, "L")
            v = dw_make_view(wd, 18 * 36, 12 * 36)
            ents = dw_edit_ents([{"t": t, "x": 3 + i % 5 * 3, "y": 4 + i // 5 * 3, "d": 1 if i % 2 else -1} for i, t in enumerate(DW_TYPE_ORDER)])
            img = dw_render_scene(v, ents, 0.3, 2, [{"x": 5, "y": 5, "p": 0.4}])
            check(img.size == (18 * 36, 12 * 36) and len(img.resize((24, 16)).getcolors(400)) > 20, "picture %s" % theme)
        for typ in DW_TYPE_ORDER:
            sp = dw_sprite("t_" + typ, DW_ART["dino"][typ], 60, 60)
            check(sp["img"].getchannel("A").getbbox() is not None, "empty picture %s" % typ)
        # every state of a dinosaur draws
        wd = dw_make_world("volcano", 3, "L")
        v = dw_make_view(wd, 18 * 30, 12 * 30)
        for hz, st in (("c", "fall"), ("w", "sink"), ("l", "sink"), ("q", "sink"), ("", "up"), ("", "stop"), ("", "walk"), ("", "poof")):
            ents = [{"i": 0, "t": t, "x": 6.5 + k * 1.5, "y": 6.5, "d": 1, "st": st, "tm": 0.5, "hz": hz, "vy": 0.0} for k, t in enumerate(("trex", "ptero", "plesio"))]
            dw_render_scene(v, ents, 1.0)
        # every state of a rocket and of a firework launcher draws (the picture must really change)
        ref_img = dw_render_scene(v, dw_edit_ents([{"t": "rocket", "x": 8, "y": 9, "d": 1, "r": "stego"}, {"t": "fireworks", "x": 3, "y": 9, "d": 1}]), 0.0)
        check(ref_img.getbbox() is not None, "rocket picture")
        for t_run in (0.0, 0.8, 1.2, 1.7, 2.2, 3.0, 4.0):
            sim = dw_start_run(wd, [{"t": "rocket", "x": 8, "y": 9, "d": -1, "r": "trex"}, {"t": "rocket", "x": 11, "y": 9, "d": 1, "r": ""},
                                    {"t": "fireworks", "x": 3, "y": 9, "d": 1}, {"t": "fireworks", "x": 5, "y": 9, "d": 1}])
            while sim["tick"] * DW_DT < t_run and not sim["done"]:
                dw_step(sim)
            img = dw_render_scene(v, sim["ents"], sim["tick"] * DW_DT)
            check(img.size == ref_img.size, "frame size at %.1f s" % t_run)
            check(img.tobytes() != ref_img.tobytes(), "the run looks like the editor at %.1f s" % t_run)
        for typ in ("trex", "ptero", "baby"):
            sp = dw_rocket_sprite(40, 78, typ, False)
            check(sp["img"].getchannel("A").getbbox() is not None, "rocket with %s" % typ)
        check(dw_rocket_sprite(40, 78, "trex", False)["img"].tobytes() != dw_rocket_sprite(40, 78, "", False)["img"].tobytes(), "the dinosaur is not in the window")
        for key in ("rocket", "rocketdino", "fw"):
            check(dw_put_pic(key, "raptor", 44).getchannel("A").getbbox() is not None, "palette picture %s" % key)
        t0 = time.time()
        ents = dw_edit_ents([{"t": t, "x": 2 + i * 1, "y": 3 + i % 4, "d": 1} for i, t in enumerate(DW_TYPE_ORDER)])
        for _ in range(10):
            dw_render_scene(v, ents, 0.5)
        per = (time.time() - t0) / 10.0
        notes.append("a frame takes %d ms" % int(per * 1000))
        check(per < 0.06, "frame too slow: %d ms" % int(per * 1000))
        if sheet_path:
            sheet = Image.new("RGB", (3 * 18 * 24, 2 * 12 * 24), "#222222")
            for i, theme in enumerate(DW_THEMES):
                wd = dw_make_world(theme, 20 + i, "L")
                dn = []
                for t in ("trex", "stego", "raptor", "ptero", "plesio", "baby", "trike", "anky"):
                    for _ in range(40):
                        cx, cy = rnd.randint(1, 16), rnd.randint(1, 10)
                        if dw_can_place(wd, dn, t, cx, cy):
                            dn.append({"t": t, "x": cx, "y": cy, "d": rnd.choice((-1, 1))})
                            break
                sheet.paste(dw_thumb(wd, dn, 18 * 24), ((i % 3) * 18 * 24, (i // 3) * 12 * 24))
            sheet.save(sheet_path)
            notes.append("sheet written: " + sheet_path)
        # 4. the saved-world files
        wd = dw_make_world("island", 5, "L")
        p = save_world_file("Test world", wd, [{"t": "trex", "x": 5, "y": 5, "d": 1}])
        check(p and os.path.isfile(p) and os.path.isfile(os.path.splitext(p)[0] + ".jpg"), "save_world_file")
        lst = list_world_files()
        check(len(lst) == 1 and dw_world_from_data(lst[0][1])[0] == wd and len(dw_clean_dinos(lst[0][1]["dinos"])) == 1, "list_world_files")
        check(len(dw_clean_dinos([{"t": "bogus", "x": 1, "y": 1, "d": 1}, {"t": "trex", "x": "2", "y": 3}, "x"])) == 1, "dw_clean_dinos")
        p = save_world_file("Space world", wd, [{"t": "rocket", "x": 5, "y": 5, "d": 1, "r": "trex"}, {"t": "fireworks", "x": 7, "y": 5, "d": 1}])
        got = dw_world_from_data(json.load(open(p, encoding="utf-8")))
        check(got and got[1][0].get("r") == "trex" and got[1][1]["t"] == "fireworks", "rocket not saved with its dinosaur")
        check(dw_world_from_data({"theme": "moon", "seed": 1, "shape": "L"}) is None, "bad world accepted")
        notes.append("saved-world files ok")
        # 5. the whole window
        if "--nowindow" not in sys.argv:
            root = tk.Tk()
            root.geometry("1000x700+20+20")
            S = dict(DEFAULT_SETTINGS)
            S["sound"] = False
            app = DinoWorldApp(root, S)
            for _ in range(30):
                root.update()
                time.sleep(0.02)
            check(app.world is not None and app.view is not None, "window: no world")
            app.pick_theme("castle")
            root.update()
            check(app.world["theme"] == "castle" and app.world["shape"] == "L", "window: castle %s" % app.world["shape"])
            v = app.view
            placed = 0
            for (cx, cy, typ) in ((2, 2, "trex"), (14, 2, "raptor"), (2, 9, "baby"), (15, 9, "ptero")):
                app.pick_type(typ)
                before = len(app.dinos)
                app.on_down(_Ev(v["ox"] + (cx + 0.5) * v["cell"], v["oy"] + (cy + 0.6) * v["cell"]))
                app.on_up(_Ev(0, 0))
                placed += len(app.dinos) - before
            check(placed >= 3, "window: placed %d" % placed)
            d0 = app.dinos[0]["d"]
            app.sel = 0
            app.flip()
            check(app.dinos[0]["d"] == -d0, "window: flip")
            app.on_down(_Ev(v["ox"] + (app.dinos[0]["x"] + 0.5) * v["cell"], v["oy"] + (app.dinos[0]["y"] + 0.5) * v["cell"]))
            app.on_move(_Ev(v["ox"] + 8.5 * v["cell"], v["oy"] + 6.5 * v["cell"]))
            app.on_up(_Ev(0, 0))
            n_before = len(app.dinos)
            app.sel = len(app.dinos) - 1
            app.remove()
            check(len(app.dinos) == n_before - 1, "window: remove")
            # rockets and fireworks from the extra palette buttons
            def free_cell(typ):
                for cy in range(2, 10):
                    for cx in range(2, 16):
                        if dw_can_place(app.world, app.dinos, typ, cx, cy) and app.hit(cx + 0.5, cy + 0.3) < 0:
                            return cx, cy
                return 1, 1
            for key, typ in (("rocket", "rocket"), ("rocketdino", "rocket"), ("fw", "fireworks")):
                app.pick_put(key)
                if key == "rocketdino":
                    app.pick_type("ptero")
                    check(app.put == "rocketdino" and app.S["type"] == "ptero", "window: a dinosaur button must keep rocket + dino")
                cx, cy = free_cell(typ)
                before = len(app.dinos)
                app.on_down(_Ev(v["ox"] + (cx + 0.5) * v["cell"], v["oy"] + (cy + 0.3) * v["cell"]))
                app.on_up(_Ev(0, 0))
                check(len(app.dinos) == before + 1 and app.dinos[-1]["t"] == typ, "window: put out %s" % key)
                if key == "rocketdino":
                    check(app.dinos[-1].get("r") == "ptero", "window: passenger")
                if key == "rocket":
                    check(app.dinos[-1].get("r") == "", "window: empty rocket")
            app.pick_type("trex")
            check(app.put == "dino", "window: the dinosaur button must go back to dinosaurs")
            app.S["n"] = 0
            app.ask_name = lambda title, text, default: "Window test"
            app.save_world()
            check(os.path.isfile(os.path.join(WORLDS_DIR, "Window test.json")), "window: save")
            app.run()
            t_end = time.time() + 40
            while app.mode == "run" and not app.banner and time.time() < t_end:
                root.update()
                time.sleep(0.01)
            check(app.banner, "window: the run did not finish")
            notes.append("run on screen took %.1f s" % (time.time() - (t_end - 40)))
            app.stop_run()
            n_dinos = len(app.dinos)
            app.new_world("island")
            app.load_world(list_world_files()[0][1])
            check(len(app.dinos) == n_dinos and app.world["theme"] == "castle", "window: load")
            app.set_lang("sv")
            root.update()
            app.set_lang("en")
            app.open_notes()
            root.update()
            check(app.pt is not None, "window: notes")
            app.pt.close()
            root.update()
            app.on_close()
            notes.append("window ok")
    except Exception:
        import traceback
        errors.append("EXCEPTION:\n" + traceback.format_exc())
    finally:
        shutil.rmtree(base, ignore_errors=True)
    for n in notes:
        print("  " + n)
    if errors:
        print("FAILED:")
        for e in errors:
            print("  - " + e)
        return False
    print("selftest OK")
    return True


# *************** DEL 20 - START *****************
def main():
    argv = sys.argv[1:]
    if "--export-lang" in argv:
        for p in export_lang_files():
            print(p)
        return 0
    if "--selftest" in argv:
        sheet = ""
        if "--sheet" in argv:
            i = argv.index("--sheet")
            sheet = argv[i + 1] if i + 1 < len(argv) else "dino_sheet.png"
        return 0 if selftest(sheet) else 1
    if not HAVE_PIL:
        try:
            import tkinter.messagebox as mb
            r = tk.Tk()
            r.withdraw()
            mb.showerror("Dino World", "Dino World needs the Pillow package.\n\nInstall it with:  pip install pillow")
        except Exception:
            print("Dino World needs the Pillow package: pip install pillow")
        return 1
    _set_app_id()
    root = tk.Tk()
    DinoWorldApp(root)
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()
    return 0


if __name__ == "__main__":
    sys.exit(main())
