# -*- 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.  Never Swedish.  The ONE exception is the text the player
# reads on screen, which is localized (Swedish / English / Russian) because
# this is a game; see 40_games.md.  The code around it stays English.
#
# ActivityBook - a quiet activity book for one player.  No opponent, no clock
# running against you: this is pyssel.  ONE program, SIX activities, all
# six built, chosen from the cards on the first page.
#
#   PART 1 - MAZES (DEL 10 - DEL 13)
#       "Which way does the dog go to reach the kennel instead of the water
#       tap, the cat, the puddle or a dead end?"  A real maze with one true
#       goal and several wrong ones, shown both as a sentence and as a
#       picture: [the mouse] -> [the cheese].  Trace the path with the mouse
#       (click or drag) or with the arrow keys, from the start OR from the
#       goal end (from the goal is easier), and erase smoothly with the right
#       mouse button or the DELETE key.
#
#   PART 2 - COLOURING (DEL 17 - DEL 18)
#       Ready-made pictures with NAMED PARTS: click the teeth, an eye, a
#       stone, the lava, and that part takes the colour, with its name shown
#       in three languages while hovering.  Or take the crayon and draw
#       freely - a deliberately wobbly, half-stippled line so it looks like
#       wax.  Right button and DELETE erase, "Show the colours" peeks at the
#       picture's own colours, and a finished page is saved as PNG + JSON in
#       Helpfiles\ActivityBook\Gallery.
#
#   PART 3 - JIGSAW (DEL 19)
#       The same pictures, in their own colours, cut into 6 / 12 / 24 / 48
#       pieces with real tabs and blanks, dragged onto the board where they
#       click into place.  Right button and DELETE send a piece back to the
#       pile.  This is the one part that needs Pillow; without it the view
#       says so instead of half-working, and offers to find Pillow in a
#       folder, unpack a wheel or download one - no pip (DEL 04b).
#
#   PART 4 - SPOT THE DIFFERENCES / "Finn fem fel" (DEL 19b)
#       Two copies of one picture side by side; five things are different.
#       Click each one, in either picture - a red ring goes round it in both
#       and the line at the bottom says what it was.  A puzzle is an EXISTING
#       picture (DEL 17) plus a pool of 5-10 differences, each one an
#       instruction about a named part: hide it, give it another colour, move
#       it, make it bigger or smaller, or add something on top.  A round
#       takes five of the pool at random and may swap the sides, so one puzzle
#       can be played many times.  Hint (a blinking ring) and Show answer
#       cost stars.
#
#   PART 5 - MATCHING PAIRS / "Para ihop" (DEL 19c)
#       A column of pictures and a shuffled column of partners: the dog and
#       its kennel.  Press and pull a line, or click one and then the other.
#       A right pair stays joined by a coloured line; a wrong pair jumps back
#       and counts as a miss.  A set is either `pairs` of two different
#       drawings or `shadows` - an animal and its own black shadow, which
#       costs no new art because it is the same drawing in one dark colour.
#
#   PART 6 - BEAD BOARDS / "pärlplattor" (DEL 19d)
#       A pegboard, fourteen bowls of beads, and the fun of carrying one bead
#       at a time to a peg.  Squares and animal-shaped boards (bear, dog,
#       cat ...), a faint pattern to copy, Undo / Redo, a mirror mode, ironing
#       that melts the beads into one piece, and a saved PNG (no Pillow).
#       Made gentle for the smallest: no score, no clock, nothing to get
#       wrong, everything undoable, forgiving drops.  Its texts are English
#       only (the sv / ru columns repeat it until a translator fills them).
#
#   Parts 4 and 5 arrive the same way the other content does: as packs (DEL
#   21).  The built-in puzzle and set are written in the pack format and go
#   through the very same checker, so the instruction document is not a
#   description of the program, it is the format the program is built from.
#
#   WHY THERE IS NO AI OPPONENT
#       40_games.md makes AI opponents the baseline, and that is not being
#       skipped here - there is nobody to play against.  Pyssel is one player
#       and a puzzle, like patience.  What the rule is really after, a
#       computer that plays the thing properly, is the exact solver behind
#       "Show answer": it knows the one true route at every moment and never
#       guesses, and the stars are measured against it.  Nothing is hidden
#       from anybody either - the whole maze is on the page.
#
# ============================================================================
# ToDo - WHAT COULD BE ADDED NEXT
# ============================================================================
#
#   ToDo - MORE CONTENT, WHICH IS THE CHEAP PART
#       * More maze stories: one ART entry (DEL 09), one name row (DEL 07),
#         one THEMES line (DEL 10).  The document
#         ActivityBook_instruction_for_HTTP-Claude.md describes exactly this
#         and is meant to be handed to another Claude; `--inventory` prints
#         what already exists, `--instructions` writes that list into the
#         document.
#       * More pictures (DEL 17): a picture is a list of named parts in a
#         1000 x 700 box.  Both part 2 and part 3 pick them up automatically -
#         PICTURES is the only place to add one.  Good candidates: a castle
#         with a dragon (teeth again), a rocket among the planets, a horse in
#         a meadow, a butterfly with many small cells to fill in.
#
#   ToDo - PART 2, THINGS LEFT OUT ON PURPOSE
#       * Paint by number: each part already carries its natural colour, so a
#         small number in each part and a numbered crayon box is a small step.
#         Default OFF when it comes.
#       * Opening a saved picture again.  The JSON in Gallery already holds
#         everything needed (picture key, fills, strokes with their seeds);
#         what is missing is the "open" side of it.
#       * Printing a page to paper.  This is pyssel; paper is where it
#         belongs.  Nothing here prints yet.
#
#   ToDo - PART 3, THINGS LEFT OUT ON PURPOSE
#       * Rotating pieces (a real difficulty step), and saving a half-finished
#         puzzle.  The piece positions and the seed are all that would need
#         keeping.
#       * Cutting up a picture file of Lars's own, not only the built-in
#         pictures.  That is the day this program needs the single-instance
#         receiver from 21_single_instance_receiver.md, which it does not have
#         yet because it opens no files from outside.
#
#   ToDo - PART 4 AND 5, THINGS LEFT OUT ON PURPOSE
#       * Spot the differences made from ANY picture, with the differences
#         drawn at random and then kept only if the same pixel test that
#         --selftest runs says they show.  Today every puzzle is written by
#         hand, which is why the differences are kind ones (a missing sun, not
#         a one-pixel shade).
#       * A mirrored part as a sixth kind of difference.
#       * Matching as MEMORY (turn two cards over, find the pair) using the
#         very same sets, and matching by WORD: a picture on one side, its
#         name in the player's language on the other - reading practice, and
#         the names already exist in all three languages.
#
#   ToDo - PART 6, THINGS LEFT OUT ON PURPOSE
#       * More boards as PACK data (a `beads` section: rows of letters, like
#         the shapes in DEL 19d).  Today the twelve shapes are in the code.
#       * Opening a saved picture again (the JSON in Gallery has everything),
#         printing it, and a sound when a bead drops (off by default, if so).
#       * The bead texts are English only: translate the BEAD_TEXT table and
#         BEAD_HELP (HTTP-Claude job).
#
#   ToDo - DONE IN THIS FILE
#       Maze generation (randomized Prim, with the measurements that chose it
#       in DEL 11) and an exact solver, four maze stories with hand-drawn
#       profile art, tracing with mouse and arrow keys from either end,
#       right-button and DELETE erasing everywhere, hint, stars, results,
#       three pictures with named parts, crayon and fill, jigsaw cutting with
#       interlocking edges, an activity feed that can be switched on and off
#       mid-maze, an always-on rotated log file, Swedish / English / Russian,
#       Help with the star breakdown, --selftest, --inventory, --instructions,
#       spot the differences and matching pairs (parts 4 and 5), and packs
#       that can carry puzzles and sets as well as drawings and pictures.

import ctypes
import json
import math
import os
import platform
import random
import re
import shutil
import struct
import subprocess
import sys
import threading
import time
import tkinter as tk
import webbrowser
import zlib
from datetime import date, datetime

# *************** DEL 02 - PROGRAM HOME (WHERE MY DATA LIVES) *****************
# Copied verbatim from block_home.py.  Rules and tree: 02_folder_tree_and_home.md
#
# Helpfiles, Icons and Folder-exe are SIBLINGS of Py, never children.  The home
# is COMPUTED, never hardcoded, so Py\<Name>.py and Folder-exe\<Name>\<Name>.exe
# find exactly the same data.


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

# The settings file carries TODAY'S DATE in its name (settings_2026-10-06.json):
# copying an old Helpfiles folder over a newer one then cannot overwrite the
# choices made since - the older file just sits beside the newer one, and the
# newest date is the one that is loaded.  The undated settings.json of earlier
# versions is still read, but only when no dated file exists.
SETTINGS_FILE  = os.path.join(PROGRAM_HF_DIR, "settings.json")   # legacy name
SETTINGS_KEEP  = 5          # dated settings files kept; older ones are dropped
STATS_FILE     = os.path.join(PROGRAM_HF_DIR, "stats.json")
GALLERY_DIR    = os.path.join(PROGRAM_HF_DIR, "Gallery")     # ToDo: part 2 and 3


def ensure_dirs():
    """Make our own folders if they are missing.  Never fatal."""
    for d in (PROGRAM_HF_DIR, LOG_DIR):
        try:
            os.makedirs(d, exist_ok=True)
        except Exception:
            pass


# *************** DEL 03 - LOG FILE (ALWAYS ON, ROTATED DAILY) ****************
# 40_games.md: the log file is never optional, and at most TWO files are kept -
# today's and the previous day's - so "was it doing this yesterday too?" can be
# answered without an unbounded pile of logs.  The on-screen feed (DEL 13) is a
# separate, optional thing.

LOG_KEEP = 2


def _log_path(d=None):
    return os.path.join(LOG_DIR, "%s_%s.log" % (PROGRAM_NAME,
                                                (d or date.today()).isoformat()))


def roll_logs():
    """Keep today's file and the newest previous one; drop the rest."""
    try:
        pat = re.compile(r"^%s_(\d{4}-\d{2}-\d{2})\.log$" % re.escape(PROGRAM_NAME))
        found = []
        for n in os.listdir(LOG_DIR):
            m = pat.match(n)
            if m:
                found.append(m.group(1))
        found.sort(reverse=True)               # newest first
        today = date.today().isoformat()
        keep = {today}                         # today's file always stays
        for stamp in found:                    # plus the newest previous day
            if stamp != today:
                keep.add(stamp)
                break
        for stamp in found:
            if stamp not in keep:
                try:
                    os.remove(os.path.join(LOG_DIR, "%s_%s.log"
                                           % (PROGRAM_NAME, stamp)))
                except Exception:
                    pass
    except Exception:
        pass


def log(msg):
    """One line in the log file.  Swallows every error: logging never breaks play."""
    try:
        with open(_log_path(), "a", encoding="utf-8") as fh:
            fh.write("%s  %s\n" % (datetime.now().strftime("%H:%M:%S"), msg))
    except Exception:
        pass


# *************** DEL 04 - SETTINGS AND STATS (JSON, NEVER FATAL) *************

DEFAULT_SETTINGS = {
    "language":      "sv",      # sv / en / ru
    "difficulty":    "normal",  # easy / normal / hard / giant
    "theme":         "random",  # dog / mouse / bee / penguin / rabbit / cat / random
    "begin_at":      "start",   # start / goal  (goal end is the easier one)
    "feed":          True,      # on-screen feed; toggleable mid-maze
    "path_colour":   "#ef5350",
    "thick_walls":   True,
    "animate_win":   True,
    "confirm_new":   True,      # ask before throwing away a traced path
    "picture":       "dinos",   # part 2: the picture last opened
    "crayon_colour": "#ef5350", # part 2: the crayon in hand
    "crayon_width":  "medium",  # part 2: thin / medium / thick
    "jigsaw_picture": "dinos",  # part 3: the picture last cut up
    "jigsaw_size":   "small",   # part 3: tiny / small / medium / big
    "jigsaw_ghost":  False,     # part 3: pale picture under the board
    "spot_puzzle":   "volcano", # part 4: the spot-the-difference puzzle last played
    "match_set":     "friends", # part 5: the matching set last played
    "match_pairs":   "4",       # part 5: pairs in a round (3 / 4 / 5 / 6)
    "bead_board":    "bear",    # part 6: the bead board last used
    "bead_guide":    False,     # part 6: faint pattern beads shown
    "bead_mirror":   False,     # part 6: every bead gets a twin
    "bead_areas":    False,     # part 6: the areas of the default figure shaded in greys
    "bead_colour":   "R",       # part 6: the colour in hand (a letter)
    "pillow_search": "",        # main folder to look for Pillow in (DEL 04b)
    "pillow_found":  "",        # the folder that worked last time
}

SETTINGS = dict(DEFAULT_SETTINGS)


_SETTINGS_DATED = re.compile(r"^settings_(\d{4}-\d{2}-\d{2})\.json$")


def settings_path(d=None):
    """The file the settings are saved to today."""
    return os.path.join(PROGRAM_HF_DIR, "settings_%s.json"
                        % (d or date.today()).isoformat())


def _dated_settings():
    """Dated settings files, newest first, as full paths."""
    found = []
    try:
        for n in os.listdir(PROGRAM_HF_DIR):
            m = _SETTINGS_DATED.match(n)
            if m:
                found.append((m.group(1), os.path.join(PROGRAM_HF_DIR, n)))
    except Exception:
        pass
    found.sort(reverse=True)
    return [p for _, p in found]


def load_settings():
    global SETTINGS
    SETTINGS = dict(DEFAULT_SETTINGS)
    # newest dated file first; if it is damaged try the next, then the old name
    for path in _dated_settings() + [SETTINGS_FILE]:
        try:
            with open(path, "r", encoding="utf-8") as fh:
                data = json.load(fh)
            if isinstance(data, dict):
                for k, v in data.items():
                    if k in DEFAULT_SETTINGS and isinstance(v, type(DEFAULT_SETTINGS[k])):
                        SETTINGS[k] = v
                break
        except Exception:
            continue
    return SETTINGS


def save_settings():
    try:
        ensure_dirs()
        with open(settings_path(), "w", encoding="utf-8") as fh:
            json.dump(SETTINGS, fh, indent=2)
        for old in _dated_settings()[SETTINGS_KEEP:]:
            try:
                os.remove(old)
            except Exception:
                pass
    except Exception:
        pass


STATS = {}


def load_stats():
    global STATS
    STATS = {}
    try:
        with open(STATS_FILE, "r", encoding="utf-8") as fh:
            data = json.load(fh)
        if isinstance(data, dict):
            STATS = data
    except Exception:
        pass
    return STATS


def save_stats():
    try:
        ensure_dirs()
        with open(STATS_FILE, "w", encoding="utf-8") as fh:
            json.dump(STATS, fh, indent=2)
    except Exception:
        pass


def stats_row(diff):
    row = STATS.get(diff)
    if not isinstance(row, dict):
        row = {"solved": 0, "stars": 0, "best_time": 0, "best_stars": 0}
        STATS[diff] = row
    for k in ("solved", "stars", "best_time", "best_stars"):
        if not isinstance(row.get(k), int):
            row[k] = 0
    return row


def record_solved(diff, seconds, stars):
    row = stats_row(diff)
    row["solved"] += 1
    row["stars"] += stars
    row["best_stars"] = max(row["best_stars"], stars)
    if row["best_time"] == 0 or seconds < row["best_time"]:
        row["best_time"] = int(seconds)
    save_stats()


# *************** DEL 04b - FINDING PILLOW (NO pip NEEDED) ********************
# Pillow is only needed by the jigsaw, the PNG export and the contact sheet,
# and every `from PIL import ...` in this file is done lazily.  So Pillow can
# be brought in AFTER the program has started, without restarting it: put its
# folder on sys.path and the next import finds it.
#
# Three ways in, none of them needs pip:
#   1. Drop a Pillow wheel (Pillow-*.whl) or an unpacked folder that holds
#      PIL\ into  Helpfiles\ActivityBook\Pillow  - looked at on every start.
#      A wheel that fits is really INSTALLED with `pip install --no-index`
#      (no network, so a computer with a wrong clock - 2024, https certificates
#      "not yet valid" - is no problem); if pip cannot do it, the wheel is
#      unpacked and borrowed by path as in 2 below.
#   2. Point at ANY main folder ("Search a folder...") and it is searched
#      down to seven levels for such a wheel or folder.  A wheel is just a zip:
#      it is unpacked into  Helpfiles\ActivityBook\Pillow\unpacked  (a .pyd
#      cannot be loaded from inside a zip, so the wheel cannot simply be put
#      on sys.path as it is).
#   3. "Download Pillow": asks pypi.org which wheel fits THIS Python and
#      this Windows, checks its sha256 and unpacks it.  Only on a click.
# What worked is remembered ("pillow_found"), so the next start is instant.
#
# A folder is never trusted blindly: a PIL from another Python version is
# refused BEFORE it is imported (its _imaging file has the wrong suffix), and
# if an import fails anyway the path is taken off again and the half-loaded
# PIL modules are thrown away.

PILLOW_DIR   = os.path.join(PROGRAM_HF_DIR, "Pillow")
PILLOW_CACHE = os.path.join(PILLOW_DIR, "unpacked")
PILLOW_INDEX = "https://pypi.org/pypi/pillow/json"
PILLOW_HOST  = "https://files.pythonhosted.org/"


def _pil_importable():
    try:
        from PIL import Image, ImageDraw, ImageTk    # noqa: F401
        return True
    except Exception:
        return False


def _purge_pil():
    for name in list(sys.modules):
        if name == "PIL" or name.startswith("PIL."):
            del sys.modules[name]


def _imaging_fits(pil_dir):
    """Does this PIL folder hold a compiled core for THIS Python?"""
    import importlib.machinery
    try:
        names = set(os.listdir(pil_dir))
    except Exception:
        return False
    # The WHOLE name must match: ".pyd" alone is one of the accepted suffixes
    # and would let _imaging.cp39-win_amd64.pyd through.
    return any("_imaging" + suf in names
               for suf in importlib.machinery.EXTENSION_SUFFIXES)


def _ver_key(text):
    return tuple(int(x) for x in re.findall(r"\d+", text))


def _plat_ok(tag):
    machine = platform.machine().lower()
    if sys.platform == "win32":
        if machine in ("arm64", "aarch64"):
            return tag == "win_arm64"
        return tag == ("win_amd64" if sys.maxsize > 2 ** 32 else "win32")
    if sys.platform == "darwin":
        return tag.startswith("macosx") and (
            "universal2" in tag or machine in tag)
    return ("manylinux" in tag or "musllinux" in tag) and machine in tag


def _wheel_fits(filename):
    """Pillow-12.2.0-cp313-cp313-win_amd64.whl fits cp313 on 64-bit Windows."""
    if not filename.lower().endswith(".whl"):
        return False
    parts = filename[:-4].split("-")
    if len(parts) < 5 or parts[0].lower() != "pillow":
        return False
    py, abi, plat = parts[-3], parts[-2], parts[-1]
    mine = "cp%d%d" % sys.version_info[:2]
    if getattr(sys, "abiflags", "") == "t":          # free-threaded build
        mine += "t"
    if not (py == mine and abi in (mine, "abi3")):
        m = re.match(r"^cp3(\d+)$", py)
        if not (abi == "abi3" and m and int(m.group(1)) <= sys.version_info[1]):
            return False
    return any(_plat_ok(t) for t in plat.split("."))


def _use_pil_folder(folder):
    """Put `folder` (the one that CONTAINS PIL\\) on sys.path; keep it only if
    Pillow then really imports."""
    pil_dir = os.path.join(folder, "PIL")
    if not os.path.isfile(os.path.join(pil_dir, "__init__.py")):
        return False
    if not _imaging_fits(pil_dir):
        log("pillow: %s is for another Python, skipped" % folder)
        return False
    import importlib
    added = folder not in sys.path
    if added:
        sys.path.append(folder)      # APPEND: never let it shadow anything
    importlib.invalidate_caches()
    if _pil_importable():
        log("pillow: using %s" % folder)
        SETTINGS["pillow_found"] = folder
        return True
    if added:
        try:
            sys.path.remove(folder)
        except ValueError:
            pass
    _purge_pil()
    log("pillow: %s would not import, skipped" % folder)
    return False


def _unpack_wheel(path):
    """Unzip a wheel next to the others and return the folder it went to."""
    import zipfile
    dest = os.path.join(PILLOW_CACHE, os.path.splitext(os.path.basename(path))[0])
    if not os.path.isfile(os.path.join(dest, "PIL", "__init__.py")):
        os.makedirs(dest, exist_ok=True)
        with zipfile.ZipFile(path) as zf:
            zf.extractall(dest)      # extractall already refuses ../ and drives
        log("pillow: unpacked %s" % path)
    return dest


def _real_python_exe():
    """A real python.exe (not pythonw, not a frozen build) to run pip with, or "".

    NEVER sys.executable of a frozen build: that is this program's own .exe and
    would start another copy of it (90_lessons_learned.md, the fork bomb)."""
    if getattr(sys, "frozen", False):
        return ""
    names = ("python.exe", "python3.exe") if sys.platform == "win32" else ("python3", "python")
    for name in names:
        cand = os.path.join(os.path.dirname(sys.executable), name)
        try:
            if os.path.isfile(cand) and os.path.getsize(cand) > 0:
                return cand
        except OSError:
            pass
    return ""


def pip_install_wheel(wheel, target=None, timeout=180):
    """Really INSTALL a Pillow wheel that is already on disk.  True on success.

    --no-index: pip never goes to the network, so a computer whose clock says
    2024 (every https certificate then looks "not yet valid") installs from the
    folder just as well as any other.  --no-deps: Pillow has none.  `target`
    is for the self test; the normal call installs where pip would."""
    python = _real_python_exe()
    if not python:
        log("pillow: no real python.exe to run pip with")
        return False
    cmd = [python, "-m", "pip", "install", "--no-index", "--no-deps",
           "--disable-pip-version-check", "--no-warn-script-location"]
    if target:
        cmd += ["--target", target]
    cmd.append(wheel)
    flags = 0x08000000 if sys.platform == "win32" else 0     # CREATE_NO_WINDOW
    try:
        proc = subprocess.run(cmd, capture_output=True, text=True,
                              timeout=timeout, creationflags=flags,
                              stdin=subprocess.DEVNULL)
    except Exception as exc:
        log("pillow: pip could not run: %s" % exc)
        return False
    if proc.returncode != 0:
        log("pillow: pip install of %s failed: %s"
            % (wheel, (proc.stderr or proc.stdout or "").strip()[-300:]))
        return False
    log("pillow: installed %s with pip" % os.path.basename(wheel))
    return True


def _after_pip_install():
    """A pip --user install lands in a folder this process may not know yet."""
    import importlib
    try:
        import site
        user = site.getusersitepackages()
        if user and os.path.isdir(user) and user not in sys.path:
            site.addsitedir(user)
    except Exception as exc:
        log("pillow: could not add the user site: %s" % exc)
    importlib.invalidate_caches()
    _purge_pil()
    return _pil_importable()


def _scan_for_pillow(root, depth, deadline):
    """Yield ("folder", dir-containing-PIL) and ("wheel", file) below root."""
    root = os.path.abspath(root)
    base = root.count(os.sep)
    seen = 0
    for dirpath, dirnames, filenames in os.walk(root):
        seen += 1
        if seen > 30000 or time.time() > deadline:
            log("pillow: search of %s stopped early (%d folders)" % (root, seen))
            return
        if dirpath.count(os.sep) - base >= depth:
            dirnames[:] = []
        else:
            dirnames[:] = [d for d in dirnames if not d.startswith(".")
                           and d not in ("__pycache__", "$RECYCLE.BIN",
                                         "System Volume Information")]
        if "PIL" in dirnames:
            dirnames.remove("PIL")               # do not walk INTO Pillow
            yield ("folder", dirpath)
        wheels = sorted((f for f in filenames if _wheel_fits(f)),
                        key=lambda f: _ver_key(f.split("-")[1]), reverse=True)
        for f in wheels:
            yield ("wheel", os.path.join(dirpath, f))


def locate_pillow(search_root="", budget=4.0):
    """Make `import PIL` work if it can be made to.  Returns (ok, where)."""
    if _pil_importable():
        return True, "(already installed)"
    deadline = time.time() + budget
    home = os.path.dirname(os.path.abspath(
        sys.executable if getattr(sys, "frozen", False) else __file__))
    known = SETTINGS.get("pillow_found", "")
    if known and os.path.isdir(known) and _use_pil_folder(known):
        return True, known
    roots = [(PILLOW_DIR, 6), (home, 1)]
    if search_root:
        roots.append((search_root, 7))
    for root, depth in roots:
        if not os.path.isdir(root):
            continue
        for kind, path in _scan_for_pillow(root, depth, deadline):
            try:
                # A wheel in the program's own Pillow folder is INSTALLED
                # (pip, offline); only if that fails is it just borrowed.
                if (kind == "wheel" and root == PILLOW_DIR
                        and pip_install_wheel(path) and _after_pip_install()):
                    return True, path
                folder = path if kind == "folder" else _unpack_wheel(path)
                if _use_pil_folder(folder):
                    return True, path
            except Exception as exc:
                log("pillow: %s failed: %s" % (path, exc))
    return False, ""


def search_pillow_action(root):
    """The button: look in the folder the player chose."""
    SETTINGS["pillow_search"] = root
    ok, where = locate_pillow(root, budget=25.0)
    if ok:
        return (True, "pil.found", where)
    return (False, "pil.notfound", "%d.%d" % sys.version_info[:2])


def download_pillow():
    """The other button: fetch the wheel that fits this Python from PyPI."""
    import hashlib
    import urllib.request

    def get(url, limit):
        req = urllib.request.Request(
            url, headers={"User-Agent": "ActivityBook (Pillow fetch)"})
        with urllib.request.urlopen(req, timeout=30) as resp:
            data = resp.read(limit + 1)
        if len(data) > limit:
            raise ValueError("too big")
        return data

    try:
        index = json.loads(get(PILLOW_INDEX, 20000000).decode("utf-8"))
        files = list(index.get("urls", []))
        if not any(_wheel_fits(f.get("filename", "")) for f in files):
            rel = index.get("releases", {})
            for ver in sorted((v for v in rel if re.match(r"^\d+(\.\d+)*$", v)),
                              key=_ver_key, reverse=True)[:8]:
                files = rel[ver]
                if any(_wheel_fits(f.get("filename", "")) for f in files):
                    break
        fits = [f for f in files if _wheel_fits(f.get("filename", ""))
                and not f.get("yanked")]
        if not fits:
            return (False, "pil.dlfail",
                    "no wheel for Python %d.%d on this computer"
                    % sys.version_info[:2])
        pick = fits[0]
        url = pick["url"]
        if not url.startswith(PILLOW_HOST):
            return (False, "pil.dlfail", "unexpected download address")
        data = get(url, 80000000)
        if hashlib.sha256(data).hexdigest() != pick["digests"]["sha256"]:
            return (False, "pil.dlfail", "checksum does not match")
        os.makedirs(PILLOW_DIR, exist_ok=True)
        target = os.path.join(PILLOW_DIR, os.path.basename(pick["filename"]))
        with open(target, "wb") as fh:
            fh.write(data)
        log("pillow: downloaded %s (%d bytes)" % (pick["filename"], len(data)))
    except Exception as exc:
        log("pillow: download failed: %s" % exc)
        return (False, "pil.dlfail", str(exc)[:120])
    ok, where = locate_pillow("", budget=10.0)
    if ok:
        return (True, "pil.found", where)
    return (False, "pil.notfound", "%d.%d" % sys.version_info[:2])


# *************** DEL 05 - UI HELPERS (NO BLINK, MODAL DIALOGS) ***************
# Copied verbatim from block_ui_helpers.py.  Rules: 01_CORE_always_read.md.
#
# NO BLINKING CURSORS ANYWHERE.  tk.Entry / tk.Text (never ttk.Entry), values
# set PER WIDGET at creation - also in Toplevel dialogs.

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."""
    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)())


# *************** DEL 05b - OPEN THINGS WITH MY OWN PROGRAMS ******************
# Copy verbatim.  A link, folder, PDF, log or image opened from here lands in MY
# programs, not in Edge / Explorer / Notepad / Adobe.  Rules and the reasons
# behind them: 20_open_with_my_programs.md
#
# Which program opens WHAT is decided in ONE file, never in code:
#       <tree>\Helpfiles\DefaultHub\defaults.json      (DefaultHub writes it)
# _FALLBACK_KINDS is used only when that file cannot be read.
#
# Three rules this block must never break:
#   1. It may NEVER raise (Help must open even if WhyBrowse or the table is gone).
#   2. It may NEVER hand a thing to ITSELF (that is how you build a loop).
#   3. Popen, never run() (run() would freeze this program).
# And NEVER sys.executable to start a .py: in a build that is THIS program's own
# .exe, so it starts another copy of this program (fork bomb, 2026-09-04).
#
# The table is read ONCE, the first time something is opened - not at start-up.
#
# Needs:  import os, sys, json, shutil, subprocess, webbrowser
#         block_home.py  (_program_home, PROGRAM_NAME)

MY_PROGRAM_NAME = PROGRAM_NAME

# Only used when DefaultHub's table cannot be read.  Same shape as the file.
_FALLBACK_KINDS = {
    "url":    {"match_type": "protocol", "match": ["http://", "https://"],
               "target_type": "suite", "target": "WhyBrowse"},
    "mail":   {"match_type": "protocol", "match": ["mailto:"],
               "target_type": "suite", "target": "F(re)email"},
    "folder": {"match_type": "folder", "match": [],
               "target_type": "suite", "target": "File_manager"},
    "pdf":    {"match_type": "extension", "match": [".pdf"],
               "target_type": "suite", "target": "PDFull"},
    "text":   {"match_type": "extension",
               "match": [".txt", ".log", ".md", ".csv", ".ini", ".cfg",
                         ".json", ".xml", ".py", ".nfo", ".srt", ".bat",
                         ".ps1"],
               "target_type": "suite", "target": "Meditor"},
    "image":  {"match_type": "extension",
               "match": [".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp",
                         ".tif", ".tiff", ".ico"],
               "target_type": "suite", "target": "SeeView"},
}
_HUB_KINDS = None


def _my_app_roots() -> list:
    """Trees to look in, nearest first.

    My own home is not always the tree that holds the other programs: a music
    program's home is 1---Musik, and Chess / Foul_bridge / Quiz_manager /
    Railroad_racing are their own worlds - none of those has a WhyBrowse or a
    DefaultHub.  So after its own home this walks UP, four levels, like
    _find_home."""
    roots, d = [], _program_home()
    for _ in range(4):
        roots.append(d)
        parent = os.path.dirname(d)
        if parent == d:
            break
        d = parent
    return roots


def _hub_kinds() -> dict:
    """DefaultHub's table, read once and remembered."""
    global _HUB_KINDS
    if _HUB_KINDS is not None:
        return _HUB_KINDS
    kinds = {}
    for root in _my_app_roots():
        f = os.path.join(root, "Helpfiles", "DefaultHub", "defaults.json")
        try:
            if os.path.isfile(f):
                with open(f, encoding="utf-8") as fh:
                    kinds = (json.load(fh) or {}).get("kinds") or {}
                break
        except Exception:
            pass                       # unreadable or half-written: fall back
    _HUB_KINDS = kinds if isinstance(kinds, dict) and kinds else _FALLBACK_KINDS
    return _HUB_KINDS


def _target_for(thing, is_folder: bool = False) -> str:
    """Which of my programs opens this?  "" means: let Windows decide."""
    low = str(thing).lower()
    ext = "" if is_folder else os.path.splitext(low)[1]
    for k in (_hub_kinds() or {}).values():
        try:
            mt = k.get("match_type")
            match = [str(m).lower() for m in (k.get("match") or [])]
            if mt == "folder":
                hit = is_folder
            elif mt == "protocol":
                hit = (not is_folder) and any(low.startswith(m) for m in match)
            elif mt == "extension":
                hit = bool(ext) and ext in match
            else:
                hit = False
            if hit:
                if k.get("target_type") == "suite":
                    return str(k.get("target") or "")
                return ""              # "system" - deliberately Windows' job
        except Exception:
            continue
    return ""


def _real_pythonw() -> str:
    """A REAL pythonw.exe to start one of my .py programs with, or "".

    A 0-byte file is an App Execution Alias
    (%LOCALAPPDATA%\\Microsoft\\WindowsApps\\python.exe and friends) - not an
    interpreter - and which() finds it first wherever the Store stub is on PATH."""
    cands = []
    if not getattr(sys, "frozen", False):
        cands.append(os.path.join(os.path.dirname(sys.executable),
                                  "pythonw.exe"))
        cands.append(sys.executable)
    cands.append(shutil.which("pythonw"))
    cands.append(shutil.which("python"))
    base = os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs",
                        "Python")
    try:
        for d in sorted(os.listdir(base), reverse=True):
            cands.append(os.path.join(base, d, "pythonw.exe"))
    except OSError:
        pass
    for c in cands:
        try:
            if c and os.path.isfile(c) and os.path.getsize(c) > 0:
                return c
        except OSError:
            pass
    return ""


def _launch_my_app(name: str, argument) -> bool:
    """Start one of my programs with this argument.  True when it started.

    THE .PY WINS, a build is only the fallback: the .py is the file that is
    actually edited, so it is always current, while a build can be days old
    (2026-09-05: File_manager's build had no command-line handling at all).
    A build is used only when there is no source or no interpreter."""
    if not name or name.lower() == MY_PROGRAM_NAME.lower():
        return False                      # never hand a thing to myself
    cmd = work = None
    for home in _my_app_roots():
        script = os.path.join(home, "Py", name + ".py")
        exe = os.path.join(home, "Folder-exe", name, name + ".exe")
        if os.path.isfile(script):
            pyw = _real_pythonw()
            if pyw:
                cmd, work = [pyw, script, str(argument)], os.path.dirname(script)
                break
        if os.path.isfile(exe):           # no source, or no interpreter
            cmd, work = [exe, str(argument)], os.path.dirname(exe)
            break
        if os.path.isfile(script):
            break                         # found the tree; do not look further
    if not cmd:
        return False
    try:
        subprocess.Popen(cmd, cwd=work or None)
        return True
    except Exception:
        return False


def open_url(url) -> None:
    """Open a link with MY browser (or mail client), else Windows' default."""
    u = str(url or "").strip()
    if not u:
        return
    try:
        if _launch_my_app(_target_for(u), u):
            return
    except Exception:
        pass
    try:
        webbrowser.open(u)
    except Exception:
        pass


def open_path(path) -> None:
    """Open a file or folder with MY program for it, else let Windows decide."""
    p = str(path or "")
    if not p:
        return
    try:
        if _launch_my_app(_target_for(p, os.path.isdir(p)), p):
            return
    except Exception:
        pass
    try:
        os.startfile(p)
    except Exception:
        try:
            webbrowser.open(p)
        except Exception:
            pass


# *************** DEL 06 - WINDOW ICON (EXTERNAL .ICO) ************************
# Copied verbatim from block_icon.py.  Rules and pitfalls: 10_icons.md
# The icon is an EXTERNAL file, <home>\Icons\<PROGRAM_NAME>.ico, never embedded
# and never generated by this program.  Missing file = default icon, no error.


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 07 - LANGUAGE TABLE (SWEDISH / ENGLISH / RUSSIAN) *******
# 40_games.md: the UI text is localized, the code is not.  One table, three
# columns, so a fourth language can be added without hunting through the code.
# A designer's own language would be added here too - this activity book has no
# designer to credit (see DEL 14), so it stays at the three required languages.
#
# EVERY string the player can see lives here.  --selftest greps the source for
# T("...") and fails if a key is missing or if the three columns disagree about
# their {0} {1} placeholders.

LANGS = ("en", "sv", "ru")
LANG_NAMES = {"en": "English", "sv": "Svenska", "ru": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439"}

TXT = {
    # ---- the program itself ------------------------------------------------
    "app.title":        ("Activity Book", "Pysselboken",
                         "\u041a\u043d\u0438\u0433\u0430 \u0437\u0430\u043d\u044f\u0442\u0438\u0439"),
    "app.tag":          ("Mazes, colouring and puzzles - one player, no hurry",
                         "Labyrinter, m\u00e5larbilder och pussel - en spelare, ingen br\u00e5dska",
                         "\u041b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u044b, \u0440\u0430\u0441\u043a\u0440\u0430\u0441\u043a\u0438 \u0438 \u043f\u0430\u0437\u043b\u044b - \u0434\u043b\u044f \u043e\u0434\u043d\u043e\u0433\u043e, \u0431\u0435\u0437 \u0441\u043f\u0435\u0448\u043a\u0438"),
    "app.pick":         ("Choose something to do",
                         "V\u00e4lj vad du vill g\u00f6ra",
                         "\u0412\u044b\u0431\u0435\u0440\u0438, \u0447\u0435\u043c \u0437\u0430\u043d\u044f\u0442\u044c\u0441\u044f"),

    # ---- the three activities ---------------------------------------------
    "mode.maze":        ("Mazes", "Labyrinter",
                         "\u041b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u044b"),
    "mode.maze.desc":   ("Find the way to the right place - not to the cat, the water tap or a dead end",
                         "Hitta v\u00e4gen till r\u00e4tt st\u00e4lle - inte till katten, vattenposten eller en \u00e5terv\u00e4ndsgr\u00e4nd",
                         "\u041d\u0430\u0439\u0434\u0438 \u0434\u043e\u0440\u043e\u0433\u0443 \u043a \u043d\u0443\u0436\u043d\u043e\u043c\u0443 \u043c\u0435\u0441\u0442\u0443 - \u0430 \u043d\u0435 \u043a \u043a\u043e\u0442\u0443, \u043a\u043e\u043b\u043e\u043d\u043a\u0435 \u0438\u043b\u0438 \u0432 \u0442\u0443\u043f\u0438\u043a"),
    "mode.colour":      ("Colouring", "M\u00e5larbilder",
                         "\u0420\u0430\u0441\u043a\u0440\u0430\u0441\u043a\u0438"),
    "mode.colour.desc": ("Crayon freely, or fill in one part at a time: the teeth, an eye, a stone",
                         "Rita fritt med krita, eller fyll i en del i taget: t\u00e4nderna, ett \u00f6ga, en sten",
                         "\u0420\u0438\u0441\u0443\u0439 \u043c\u0435\u043b\u043a\u043e\u043c \u0438\u043b\u0438 \u0437\u0430\u043b\u0438\u0432\u0430\u0439 \u043f\u043e \u0447\u0430\u0441\u0442\u044f\u043c: \u0437\u0443\u0431\u044b, \u0433\u043b\u0430\u0437, \u043a\u0430\u043c\u0435\u043d\u044c"),
    "mode.jigsaw":      ("Jigsaw", "Pussel", "\u041f\u0430\u0437\u043b"),
    "mode.jigsaw.desc": ("Put the cut-up picture back together, piece by piece",
                         "L\u00e4gg ihop den s\u00f6nderklippta bilden, bit f\u00f6r bit",
                         "\u0421\u043e\u0431\u0435\u0440\u0438 \u0440\u0430\u0437\u0440\u0435\u0437\u0430\u043d\u043d\u0443\u044e \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0443, \u0447\u0430\u0441\u0442\u044c \u0437\u0430 \u0447\u0430\u0441\u0442\u044c\u044e"),
    "mode.later":       ("Coming later", "Kommer senare",
                         "\u0411\u0443\u0434\u0435\u0442 \u043f\u043e\u0437\u0436\u0435"),
    "mode.notbuilt":    ("This part is not built yet - it is on its way.",
                         "Den h\u00e4r delen \u00e4r inte byggd \u00e4n - den \u00e4r p\u00e5 v\u00e4g.",
                         "\u042d\u0442\u0430 \u0447\u0430\u0441\u0442\u044c \u043f\u043e\u043a\u0430 \u043d\u0435 \u0433\u043e\u0442\u043e\u0432\u0430 - \u043e\u043d\u0430 \u0432 \u043f\u043b\u0430\u043d\u0430\u0445."),

    # ---- buttons -----------------------------------------------------------
    "btn.open":         ("Open", "\u00d6ppna", "\u041e\u0442\u043a\u0440\u044b\u0442\u044c"),
    "btn.back":         ("Back", "Tillbaka", "\u041d\u0430\u0437\u0430\u0434"),
    "btn.quit":         ("Quit", "Avsluta", "\u0412\u044b\u0445\u043e\u0434"),
    "btn.new":          ("New maze", "Ny labyrint", "\u041d\u043e\u0432\u044b\u0439 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442"),
    "btn.hint.show":    ("Show answer", "Visa svaret", "\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u043e\u0442\u0432\u0435\u0442"),
    "btn.hint.hide":    ("Hide answer", "G\u00f6m svaret", "\u0421\u043a\u0440\u044b\u0442\u044c \u043e\u0442\u0432\u0435\u0442"),
    "btn.clear":        ("Erase all", "Radera allt", "\u0421\u0442\u0435\u0440\u0435\u0442\u044c \u0432\u0441\u0451"),
    "btn.help":         ("Help", "Hj\u00e4lp", "\u0421\u043f\u0440\u0430\u0432\u043a\u0430"),
    "btn.about":        ("About", "Om", "\u041e \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0435"),
    "btn.settings":     ("Settings", "Inst\u00e4llningar", "\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438"),
    "btn.stats":        ("My results", "Mina resultat", "\u041c\u043e\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b"),
    "btn.close":        ("Close", "St\u00e4ng", "\u0417\u0430\u043a\u0440\u044b\u0442\u044c"),
    "btn.save":         ("Save", "Spara", "\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c"),
    "btn.cancel":       ("Cancel", "Avbryt", "\u041e\u0442\u043c\u0435\u043d\u0430"),
    "btn.yes":          ("Yes", "Ja", "\u0414\u0430"),
    "btn.no":           ("No", "Nej", "\u041d\u0435\u0442"),

    # ---- the maze toolbar --------------------------------------------------
    "lbl.difficulty":   ("Size", "Storlek", "\u0420\u0430\u0437\u043c\u0435\u0440"),
    "lbl.theme":        ("Picture", "Bild", "\u041a\u0430\u0440\u0442\u0438\u043d\u043a\u0430"),
    "lbl.begin":        ("Begin at", "B\u00f6rja vid", "\u041d\u0430\u0447\u0430\u0442\u044c \u0441"),
    "lbl.feed":         ("Show what happens", "Visa vad som h\u00e4nder",
                         "\u041f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0441\u043e\u0431\u044b\u0442\u0438\u044f"),
    "diff.easy":        ("Small", "Liten", "\u041c\u0430\u043b\u0435\u043d\u044c\u043a\u0438\u0439"),
    "diff.normal":      ("Medium", "Mellan", "\u0421\u0440\u0435\u0434\u043d\u0438\u0439"),
    "diff.hard":        ("Big", "Stor", "\u0411\u043e\u043b\u044c\u0448\u043e\u0439"),
    "diff.giant":       ("Giant", "J\u00e4ttestor", "\u041e\u0433\u0440\u043e\u043c\u043d\u044b\u0439"),
    "theme.dog":        ("Dog", "Hund", "\u0421\u043e\u0431\u0430\u043a\u0430"),
    "theme.mouse":      ("Mouse", "Mus", "\u041c\u044b\u0448\u043a\u0430"),
    "theme.bee":        ("Bee", "Bi", "\u041f\u0447\u0435\u043b\u0430"),
    "theme.penguin":    ("Penguin", "Pingvin", "\u041f\u0438\u043d\u0433\u0432\u0438\u043d"),
    "theme.random":     ("Surprise me", "\u00d6verraska mig", "\u041b\u044e\u0431\u0430\u044f"),
    "begin.start":      ("the animal", "djuret", "\u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0433\u043e"),
    "begin.goal":       ("the goal (easier)", "m\u00e5let (l\u00e4ttare)",
                         "\u0446\u0435\u043b\u0438 (\u043b\u0435\u0433\u0447\u0435)"),

    # ---- the task line above the maze -------------------------------------
    # Russian: the names are listed in the nominative ("\u0431\u0443\u0434\u043a\u0430", not
    # "\u043a \u0431\u0443\u0434\u043a\u0435"), so the sentence is built to take them as they are -
    # a template that needed the dative would be wrong for half the words.
    "task.line":        ("{0} wants to get to {1}. Which way?",
                         "{0} vill komma till {1}. Vilken v\u00e4g?",
                         "{0} \u0438\u0449\u0435\u0442 \u0434\u043e\u0440\u043e\u0433\u0443. \u0426\u0435\u043b\u044c - {1}. \u041a\u0430\u043a\u0438\u043c \u043f\u0443\u0442\u0451\u043c?"),

    # ---- status line -------------------------------------------------------
    "status.ready":     ("Draw with the mouse or the arrow keys. Right button or DELETE erases.",
                         "Rita med musen eller piltangenterna. H\u00f6ger musknapp eller DELETE raderar.",
                         "\u0420\u0438\u0441\u0443\u0439 \u043c\u044b\u0448\u044c\u044e \u0438\u043b\u0438 \u0441\u0442\u0440\u0435\u043b\u043a\u0430\u043c\u0438. \u041f\u0440\u0430\u0432\u0430\u044f \u043a\u043d\u043e\u043f\u043a\u0430 \u0438\u043b\u0438 DELETE \u0441\u0442\u0438\u0440\u0430\u0435\u0442."),
    "status.mustbegin": ("Begin at {0} or at {1} - then follow the corridor.",
                         "B\u00f6rja vid {0} eller vid {1} - f\u00f6lj sedan g\u00e5ngen.",
                         "\u041d\u0430\u0447\u043d\u0438 \u043e\u0442: {0} \u0438\u043b\u0438 {1} - \u0437\u0430\u0442\u0435\u043c \u0438\u0434\u0438 \u043f\u043e \u043a\u043e\u0440\u0438\u0434\u043e\u0440\u0443."),
    "status.nothere":   ("There is a wall in the way - follow the corridor.",
                         "Det \u00e4r en v\u00e4gg i v\u00e4gen - f\u00f6lj g\u00e5ngen.",
                         "\u0422\u0430\u043c \u0441\u0442\u0435\u043d\u0430 - \u0438\u0434\u0438 \u043f\u043e \u043a\u043e\u0440\u0438\u0434\u043e\u0440\u0443."),
    "status.oops":      ("That is {0}, not {1}. Erase a bit and try another way!",
                         "Det d\u00e4r \u00e4r {0}, inte {1}. Radera en bit och prova en annan v\u00e4g!",
                         "\u042d\u0442\u043e {0}, \u0430 \u043d\u0435 {1}. \u0421\u0442\u0435\u0440\u0438 \u043d\u0435\u043c\u043d\u043e\u0433\u043e \u0438 \u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439 \u0434\u0440\u0443\u0433\u043e\u0439 \u043f\u0443\u0442\u044c!"),
    "status.deadend":   ("A dead end. Erase back with the right button or DELETE.",
                         "En \u00e5terv\u00e4ndsgr\u00e4nd. Radera bak\u00e5t med h\u00f6ger knapp eller DELETE.",
                         "\u0422\u0443\u043f\u0438\u043a. \u0421\u0442\u0435\u0440\u0438 \u043d\u0430\u0437\u0430\u0434 \u043f\u0440\u0430\u0432\u043e\u0439 \u043a\u043d\u043e\u043f\u043a\u043e\u0439 \u0438\u043b\u0438 DELETE."),
    "status.cleared":   ("Erased - begin again.", "Raderat - b\u00f6rja om.",
                         "\u0421\u0442\u0451\u0440\u0442\u043e - \u043d\u0430\u0447\u043d\u0438 \u0441\u043d\u043e\u0432\u0430."),
    "status.hinton":    ("The dotted line is the answer. This maze now gives one star.",
                         "Den streckade linjen \u00e4r svaret. Den h\u00e4r labyrinten ger nu en stj\u00e4rna.",
                         "\u041f\u0443\u043d\u043a\u0442\u0438\u0440 - \u044d\u0442\u043e \u043e\u0442\u0432\u0435\u0442. \u0422\u0435\u043f\u0435\u0440\u044c \u0437\u0430 \u044d\u0442\u043e\u0442 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442 \u043e\u0434\u043d\u0430 \u0437\u0432\u0451\u0437\u0434\u0430."),
    "status.counters":  ("Steps {0}   Wrong turns {1}   Time {2}",
                         "Steg {0}   Fel v\u00e4gar {1}   Tid {2}",
                         "\u0428\u0430\u0433\u043e\u0432 {0}   \u041e\u0448\u0438\u0431\u043e\u043a {1}   \u0412\u0440\u0435\u043c\u044f {2}"),

    # ---- winning -----------------------------------------------------------
    "win.bravo":        ("Bravo!", "Bravo!", "\u041c\u043e\u043b\u043e\u0434\u0435\u0446!"),
    # Russian counts 1 / 2-4 / 5+ differently ("2 \u0448\u0430\u0433\u0430" but "5 \u0448\u0430\u0433\u043e\u0432"), so the
    # number is put AFTER the word - "\u0428\u0430\u0433\u043e\u0432: 34" is right for every count.
    "win.line":         ("{0} steps, {1}, {2} of 3 stars",
                         "{0} steg, {1}, {2} av 3 stj\u00e4rnor",
                         "\u0448\u0430\u0433\u043e\u0432: {0}, {1}, \u0437\u0432\u0451\u0437\u0434: {2} \u0438\u0437 3"),
    "win.again":        ("One more!", "En till!", "\u0415\u0449\u0451 \u0440\u0430\u0437!"),

    # ---- the on-screen feed (optional, toggleable while playing) ----------
    "feed.title":       ("What happens", "Vad som h\u00e4nder", "\u0421\u043e\u0431\u044b\u0442\u0438\u044f"),
    "feed.new":         ("New maze: {0}, {1} x {2} squares",
                         "Ny labyrint: {0}, {1} x {2} rutor",
                         "\u041d\u043e\u0432\u044b\u0439 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442: {0}, \u043a\u043b\u0435\u0442\u043e\u043a {1} x {2}"),
    "feed.begin":       ("Started at {0}", "B\u00f6rjade vid {0}",
                         "\u041d\u0430\u0447\u0430\u043b\u043e: {0}"),
    "feed.step":        ("Step {0}: {1}", "Steg {0}: {1}", "\u0428\u0430\u0433 {0}: {1}"),
    "feed.back":        ("Erased - {0} steps left", "Raderade - {0} steg kvar",
                         "\u0421\u0442\u0451\u0440\u0442\u043e - \u043e\u0441\u0442\u0430\u043b\u043e\u0441\u044c \u0448\u0430\u0433\u043e\u0432: {0}"),
    "feed.clear":       ("Erased the whole path", "Raderade hela v\u00e4gen",
                         "\u0421\u0442\u0451\u0440\u0442 \u0432\u0435\u0441\u044c \u043f\u0443\u0442\u044c"),
    "feed.decoy":       ("Came to {0} - wrong place", "Kom till {0} - fel st\u00e4lle",
                         "\u041f\u0440\u0438\u0448\u0451\u043b \u043a: {0} - \u043d\u0435 \u0442\u0443\u0434\u0430"),
    "feed.hint":        ("The answer was shown", "Svaret visades",
                         "\u041e\u0442\u0432\u0435\u0442 \u043f\u043e\u043a\u0430\u0437\u0430\u043d"),
    "feed.solved":      ("Solved! {0} steps, {1}, {2} stars",
                         "L\u00f6st! {0} steg, {1}, {2} stj\u00e4rnor",
                         "\u0413\u043e\u0442\u043e\u0432\u043e! \u0448\u0430\u0433\u043e\u0432: {0}, {1}, \u0437\u0432\u0451\u0437\u0434: {2}"),
    "dir.up":           ("up", "upp", "\u0432\u0432\u0435\u0440\u0445"),
    "dir.down":         ("down", "ner", "\u0432\u043d\u0438\u0437"),
    "dir.left":         ("left", "v\u00e4nster", "\u0432\u043b\u0435\u0432\u043e"),
    "dir.right":        ("right", "h\u00f6ger", "\u0432\u043f\u0440\u0430\u0432\u043e"),

    # ---- the drawings' names, used in the task line and the messages -------
    "name.dog":         ("the dog", "hunden", "\u0441\u043e\u0431\u0430\u043a\u0430"),
    "name.kennel":      ("the kennel", "hundkojan", "\u0431\u0443\u0434\u043a\u0430"),
    "name.tap":         ("the water tap", "vattenposten", "\u043a\u043e\u043b\u043e\u043d\u043a\u0430 \u0441 \u0432\u043e\u0434\u043e\u0439"),
    "name.cat":         ("the cat", "katten", "\u043a\u043e\u0442"),
    "name.puddle":      ("the puddle", "vattenp\u00f6len", "\u043b\u0443\u0436\u0430"),
    "name.wall":        ("the dead end", "\u00e5terv\u00e4ndsgr\u00e4nden", "\u0442\u0443\u043f\u0438\u043a"),
    "name.mouse":       ("the mouse", "musen", "\u043c\u044b\u0448\u043a\u0430"),
    "name.cheese":      ("the cheese", "osten", "\u0441\u044b\u0440"),
    "name.trap":        ("the mousetrap", "musf\u00e4llan", "\u043c\u044b\u0448\u0435\u043b\u043e\u0432\u043a\u0430"),
    "name.bee":         ("the bee", "biet", "\u043f\u0447\u0435\u043b\u0430"),
    "name.flower":      ("the flower", "blomman", "\u0446\u0432\u0435\u0442\u043e\u043a"),
    "name.web":         ("the spider web", "spindeln\u00e4tet", "\u043f\u0430\u0443\u0442\u0438\u043d\u0430"),
    "name.rain":        ("the rain cloud", "regnmolnet", "\u0434\u043e\u0436\u0434\u0435\u0432\u0430\u044f \u0442\u0443\u0447\u0430"),
    "name.penguin":     ("the penguin", "pingvinen", "\u043f\u0438\u043d\u0433\u0432\u0438\u043d"),
    "name.fish":        ("the fish", "fisken", "\u0440\u044b\u0431\u043a\u0430"),
    "name.seal":        ("the seal", "s\u00e4len", "\u0442\u044e\u043b\u0435\u043d\u044c"),
    "name.icehole":     ("the hole in the ice", "h\u00e5let i isen", "\u043f\u0440\u043e\u0440\u0443\u0431\u044c"),

    # ---- part 2: colouring -------------------------------------------------
    "lbl.picture":      ("Picture", "Bild", "Картинка"),
    "lbl.thickness":    ("Crayon", "Krita", "Мелок"),
    "thick.thin":       ("Thin", "Tunn", "Тонкий"),
    "thick.medium":     ("Medium", "Mellan", "Средний"),
    "thick.thick":      ("Thick", "Tjock", "Толстый"),
    "btn.fill":         ("Fill in", "Fyll i", "Заливка"),
    "btn.crayon":       ("Crayon", "Rita", "Рисовать"),
    "btn.eraser":       ("Rubber", "Sudd", "Ластик"),
    "btn.peek":         ("Show the colours", "Visa färgerna",
                         "Показать цвета"),
    "btn.undo":         ("Undo", "Ångra", "Отменить"),
    "btn.redo":         ("Again", "Gör om", "Вернуть"),
    "btn.clearpage":    ("Empty page", "Töm sidan",
                         "Очистить"),
    "btn.savepic":      ("Save", "Spara bilden",
                         "Сохранить"),
    "status.colour.ready":  ("Click a part to fill it, or take the crayon and draw.",
                             "Klicka på en del för att fylla i den, eller ta kritan och rita.",
                             "Нажми на часть, чтобы залить её, или рисуй мелком."),
    "status.colour.fill":   ("Fill in: click a part and it takes the colour.",
                             "Fyll i: klicka på en del så får den färgen.",
                             "Заливка: нажми на часть."),
    "status.colour.crayon": ("Crayon: hold the button down and draw.",
                             "Krita: håll ner knappen och rita.",
                             "Мелок: держи кнопку и рисуй."),
    "status.colour.eraser": ("Rubber: takes away a crayon line, or empties a part.",
                             "Sudd: tar bort ett kritstreck, eller tömmer en del.",
                             "Ластик: убирает линию или заливку."),
    "status.colour.nopart": ("Nothing to fill in just there.",
                             "Inget att fylla i just där.",
                             "Там нечего заливать."),
    "status.colour.filled": ("{0} is coloured in.", "{0} är ifylld.",
                             "{0}: готово."),
    "status.colour.emptied": ("{0} is empty again.", "{0} är tom igen.",
                              "{0}: снова пусто."),
    "status.colour.rubbed": ("Rubbed out.", "Bortsuddat.",
                             "Стёрто."),
    "status.colour.drew":   ("Drawn with the crayon.", "Ritat med kritan.",
                             "Нарисовано мелком."),
    "status.colour.undone": ("Undone. DELETE undoes one more.",
                             "Ångrat. DELETE ångrar en till.",
                             "Отменено. DELETE отменит ещё."),
    "status.colour.cleared": ("The page is empty again.",
                              "Sidan är tom igen.",
                              "Страница снова пуста."),
    "status.colour.peek":   ("This is what it looks like in its own colours.",
                             "Så här ser den ut i sina egna färger.",
                             "Вот её собственные цвета."),
    "status.colour.saved":  ("Saved as {0}.", "Sparad som {0}.",
                             "Сохранено: {0}."),
    "status.colour.savefail": ("The picture could not be saved.",
                               "Bilden gick inte att spara.",
                               "Не удалось сохранить."),
    "ask.newpicture":   ("Leave this picture and open another one?",
                         "Lämna den här bilden och öppna en annan?",
                         "Оставить эту картинку и открыть другую?"),
    "ask.clearpage":    ("Empty the whole page and start again?",
                         "Töm hela sidan och börja om?",
                         "Очистить всю страницу и начать снова?"),

    # ---- part 3: jigsaw ----------------------------------------------------
    "lbl.pieces":       ("Pieces", "Bitar", "Детали"),
    "lbl.ghost":        ("Faint picture underneath", "Blek bild under",
                         "Бледная картинка снизу"),
    "jig.tiny":         ("6 pieces", "6 bitar", "6 деталей"),
    "jig.small":        ("12 pieces", "12 bitar", "12 деталей"),
    "jig.medium":       ("24 pieces", "24 bitar", "24 детали"),
    "jig.big":          ("48 pieces", "48 bitar", "48 деталей"),
    "btn.newjigsaw":    ("Cut it up again", "Klipp sönder igen",
                         "Разрезать снова"),
    "jig.nopillow":     ("The jigsaw needs Pillow, which is not installed. "
                         "The mazes and the colouring work without it.",
                         "Pusslet behöver Pillow, som inte är installerat. "
                         "Labyrinterna och målarbilderna funkar ändå.",
                         "Для пазла нужен Pillow, а его нет. "
                         "Лабиринты и раскраски работают без него."),
    "pil.hint":         ("Drop a Pillow .whl file - or a folder that contains PIL - "
                         "into the folder below, or point at any main folder and "
                         "the program searches it. Or let it fetch Pillow itself.",
                         "Lägg en Pillow-.whl-fil - eller en mapp som innehåller PIL - "
                         "i mappen nedan, eller peka ut en huvudmapp så letar "
                         "programmet i den. Eller låt det hämta Pillow själv.",
                         "Положи файл Pillow .whl (или папку с PIL) в папку ниже "
                         "или укажи любую главную папку - программа поищет в ней. "
                         "Или пусть скачает Pillow сама."),
    "pil.download":     ("Download Pillow (about 6 MB)",
                         "Ladda ner Pillow (ca 6 MB)",
                         "Скачать Pillow (около 6 МБ)"),
    "pil.search":       ("Search a folder...", "Sök i en mapp...",
                         "Искать в папке..."),
    "pil.again":        ("Look again", "Leta igen", "Искать снова"),
    "pil.openfolder":   ("Open the Pillow folder", "Öppna Pillow-mappen",
                         "Открыть папку Pillow"),
    "pil.choose":       ("Choose the main folder to search for Pillow",
                         "Välj huvudmappen där Pillow ska letas",
                         "Выбери главную папку для поиска Pillow"),
    "pil.searching":    ("Searching...", "Letar...", "Ищу..."),
    "pil.downloading":  ("Downloading...", "Laddar ner...", "Скачиваю..."),
    "pil.found":        ("Pillow found: {0}", "Pillow hittades: {0}",
                         "Pillow найден: {0}"),
    "pil.notfound":     ("No Pillow that fits Python {0} was found.",
                         "Ingen Pillow som passar Python {0} hittades.",
                         "Pillow для Python {0} не найден."),
    "pil.dlfail":       ("The download did not work: {0}",
                         "Nedladdningen gick inte: {0}",
                         "Скачать не получилось: {0}"),
    "status.jigsaw.ready": ("Drag a piece onto the board, or next to its neighbour. It clicks on by itself.",
                            "Dra en bit till brädet, eller intill sin granne. Den snäpper fast själv.",
                            "Перетащи деталь на поле или к её соседке. Она сама прилипнет."),
    "status.jigsaw.join":  ("They stick together! Move one and the rest follow.",
                            "De satt ihop! Flyttar du en, följer de andra med.",
                            "Склеились! Двигаешь одну - едут все."),
    "status.jigsaw.locked": ("That piece is fixed on the board. Right button or DELETE takes it out.",
                             "Den biten sitter fast på brädet. Höger knapp eller DELETE tar loss den.",
                             "Эта деталь закреплена на поле. Правая кнопка или DELETE снимет её."),
    "status.jigsaw.snap":  ("There it goes!", "Där satt den!",
                            "Встала!"),
    "status.jigsaw.back":  ("Back in the tray. Right button or DELETE does that.",
                            "Tillbaka i högen. Höger knapp eller DELETE gör det.",
                            "Обратно в кучу. Правая кнопка или DELETE."),
    "status.jigsaw.count": ("{0} of {1} pieces   Time {2}",
                            "{0} av {1} bitar   Tid {2}",
                            "{0} из {1}   Время {2}"),
    "status.jigsaw.done":  ("All {0} pieces, in {1}.",
                            "Alla {0} bitar, på {1}.",
                            "Все детали: {0}, за {1}."),
    "ask.newjigsaw":    ("Cut the picture up again and start over?",
                         "Klippa sönder bilden igen och börja om?",
                         "Разрезать картинку снова и начать заново?"),

    # ---- part 4 and 5: spot the differences, matching pairs ---------------
    "mode.spot":        ("Spot the differences", "Finn fem fel",
                         "Найди отличия"),
    "mode.spot.desc":   ("Two pictures that look the same - but five things are different. Find them all",
                         "Två bilder som ser likadana ut - men fem saker är olika. Hitta alla",
                         "Две одинаковые на вид картинки - но пять отличий. Найди их все"),
    "mode.match":       ("Matching", "Para ihop", "Подбери пару"),
    "mode.match.desc":  ("Draw a line from each picture to the one that belongs with it",
                         "Dra en linje från varje bild till den som hör ihop med den",
                         "Проведи линию от каждой картинки к той, что ей подходит"),
    "lbl.set":          ("Set", "Serie", "Набор"),
    "lbl.pairs":        ("Pairs", "Par", "Пары"),
    "pairs.3":          ("3 pairs", "3 par", "3 пары"),
    "pairs.4":          ("4 pairs", "4 par", "4 пары"),
    "pairs.5":          ("5 pairs", "5 par", "5 пар"),
    "pairs.6":          ("6 pairs", "6 par", "6 пар"),
    "btn.newround":     ("New round", "Ny omgång", "Новый раунд"),
    "btn.hint":         ("Hint", "Ledtråd", "Подсказка"),
    "ask.newround":     ("Leave this round and start another one?",
                         "Lämna den här omgången och börja en ny?",
                         "Оставить этот раунд и начать новый?"),
    "stats.what":       ("Activity", "Aktivitet", "Занятие"),

    # what was different - {0} is the name of the part, in the player's language.
    # Russian puts the name AFTER the label ("Другой цвет: небо"), so the
    # sentence never has to agree in gender or case with a name.
    "spot.hide":        ("{0} is missing in one of the pictures",
                         "{0} saknas i den ena bilden",
                         "Пропало в одной из картинок: {0}"),
    "spot.colour":      ("{0} has another colour",
                         "{0} har en annan färg",
                         "Другой цвет: {0}"),
    "spot.move":        ("{0} is in another place",
                         "{0} sitter på ett annat ställe",
                         "Другое место: {0}"),
    "spot.scale":       ("{0} has another size",
                         "{0} har en annan storlek",
                         "Другой размер: {0}"),
    "spot.add":         ("{0} is only in one of the pictures",
                         "{0} finns bara i den ena bilden",
                         "Есть только в одной картинке: {0}"),
    "status.spot.ready": ("Five things are different. Click on one - in either picture.",
                          "Fem saker är olika. Klicka på en - i vilken bild som helst.",
                          "Пять отличий. Нажми на отличие - в любой из картинок."),
    "status.spot.miss": ("Not there - look again.", "Inte där - titta igen.",
                         "Здесь нет - посмотри ещё."),
    "status.spot.count": ("Found {0} of {1}   Misses {2}   Time {3}",
                          "Hittat {0} av {1}   Missar {2}   Tid {3}",
                          "Найдено {0} из {1}   Промахов {2}   Время {3}"),
    "status.spot.done": ("All {0} found, in {1}.", "Alla {0} hittade, på {1}.",
                         "Найдено всё: {0}, за {1}."),
    "status.spot.hint": ("The blue ring blinks round one of them. Hints cost stars.",
                         "Den blå ringen blinkar runt ett av felen. Ledtrådar kostar stjärnor.",
                         "Синий круг мигает вокруг одного из отличий. Подсказки стоят звёзд."),
    "status.spot.answer": ("The orange rings show the rest. This round now gives one star.",
                           "De orangea ringarna visar resten. Den här omgången ger nu en stjärna.",
                           "Оранжевые круги показывают остальные. Теперь за этот раунд одна звезда."),
    "status.match.ready.pairs": ("Draw a line from a picture to the one that belongs with it - or click one, then the other.",
                                 "Dra en linje från en bild till den som hör ihop med den - eller klicka på den ena och sedan den andra.",
                                 "Проведи линию от картинки к той, что ей подходит, - или нажми на одну, потом на другую."),
    "status.match.ready.shadows": ("Draw a line from each one to its shadow - or click one, then the other.",
                                   "Dra en linje från varje bild till dess skugga - eller klicka på den ena och sedan den andra.",
                                   "Проведи линию от каждой картинки к её тени - или нажми на одну, потом на другую."),
    "status.match.pick": ("Now click the one it belongs with.",
                          "Klicka nu på den som hör ihop med den.",
                          "Теперь нажми на подходящую."),
    "status.match.right": ("Right: {0} goes with {1}", "Rätt: {0} hör ihop med {1}",
                           "Верно: {0} - {1}"),
    "status.match.shadow": ("Right: that is the shadow of {0}",
                            "Rätt: det är skuggan av {0}",
                            "Верно: это тень, предмет - {0}"),
    "status.match.wrong": ("No, those two do not belong together. Try another.",
                           "Nej, de två hör inte ihop. Prova en annan.",
                           "Нет, эти две не подходят друг другу. Попробуй другую."),
    "status.match.count": ("Joined {0} of {1}   Misses {2}   Time {3}",
                           "Ihop {0} av {1}   Missar {2}   Tid {3}",
                           "Пар {0} из {1}   Промахов {2}   Время {3}"),
    "status.match.done": ("All {0} pairs, in {1}.", "Alla {0} par, på {1}.",
                          "Все пары: {0}, за {1}."),
    "status.match.hint": ("The blinking pair belongs together. Hints cost stars.",
                          "Paret som blinkar hör ihop. Ledtrådar kostar stjärnor.",
                          "Мигающая пара подходит друг другу. Подсказки стоят звёзд."),
    "status.match.answer": ("The dotted lines show where each one goes. This round now gives one star.",
                            "De streckade linjerna visar vart var och en hör. Den här omgången ger nu en stjärna.",
                            "Пунктир показывает, кто с кем. Теперь за этот раунд одна звезда."),

    "theme.rabbit":   ("Rabbit", "Kanin", "\u041a\u0440\u043e\u043b\u0438\u043a"),
    "theme.cat":      ("Cat", "Katt", "\u041a\u043e\u0442"),
    "name.rabbit":    ("the rabbit", "kaninen", "\u043a\u0440\u043e\u043b\u0438\u043a"),
    "name.carrot":    ("the carrot", "moroten", "\u043c\u043e\u0440\u043a\u043e\u0432\u043a\u0430"),
    "name.fox":       ("the fox", "r\u00e4ven", "\u043b\u0438\u0441\u0430"),
    "name.milkbowl":  ("the milk bowl", "mj\u00f6lksk\u00e5len", "\u043c\u0438\u0441\u043a\u0430 \u0441 \u043c\u043e\u043b\u043e\u043a\u043e\u043c"),

    # ---- dialogs -----------------------------------------------------------
    "ask.title":        ("One question", "En fr\u00e5ga", "\u041e\u0434\u0438\u043d \u0432\u043e\u043f\u0440\u043e\u0441"),
    "ask.new":          ("Throw away the path you have drawn and start a new maze?",
                         "Kasta v\u00e4gen du har ritat och b\u00f6rja en ny labyrint?",
                         "\u0421\u0442\u0435\u0440\u0435\u0442\u044c \u043d\u0430\u0440\u0438\u0441\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u043f\u0443\u0442\u044c \u0438 \u043d\u0430\u0447\u0430\u0442\u044c \u043d\u043e\u0432\u044b\u0439 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442?"),
    "set.title":        ("Settings", "Inst\u00e4llningar", "\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438"),
    "set.language":     ("Language", "Spr\u00e5k", "\u042f\u0437\u044b\u043a"),
    "set.pathcolour":   ("Crayon colour", "Kritans f\u00e4rg", "\u0426\u0432\u0435\u0442 \u043c\u0435\u043b\u043a\u0430"),
    "set.thickwalls":   ("Thick walls", "Tjocka v\u00e4ggar", "\u0422\u043e\u043b\u0441\u0442\u044b\u0435 \u0441\u0442\u0435\u043d\u044b"),
    "set.animate":      ("Let the animal walk the path when it is solved",
                         "L\u00e5t djuret g\u00e5 v\u00e4gen n\u00e4r det \u00e4r l\u00f6st",
                         "\u041f\u0443\u0441\u0442\u044c \u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0435 \u043f\u0440\u043e\u0439\u0434\u0451\u0442 \u043f\u0443\u0442\u044c \u0432 \u043a\u043e\u043d\u0446\u0435"),
    "set.confirm":      ("Ask before a new maze or round throws my work away",
                         "Fr\u00e5ga innan en ny labyrint eller omg\u00e5ng kastar mitt arbete",
                         "\u0421\u043f\u0440\u0430\u0448\u0438\u0432\u0430\u0442\u044c, \u043f\u0440\u0435\u0436\u0434\u0435 \u0447\u0435\u043c \u043d\u043e\u0432\u044b\u0439 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442 \u0438\u043b\u0438 \u0440\u0430\u0443\u043d\u0434 \u0441\u043e\u0442\u0440\u0451\u0442 \u0440\u0430\u0431\u043e\u0442\u0443"),
    "set.where":        ("My choices are saved in this file (the date is in the name):",
                         "Mina val sparas i den h\u00e4r filen (datumet ing\u00e5r i namnet):",
                         "\u041c\u043e\u0438 \u043d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438 \u0441\u043e\u0445\u0440\u0430\u043d\u044f\u044e\u0442\u0441\u044f \u0432 \u044d\u0442\u043e\u043c \u0444\u0430\u0439\u043b\u0435 (\u0434\u0430\u0442\u0430 \u0432 \u0438\u043c\u0435\u043d\u0438):"),
    "set.showfolder":   ("Show the folder", "Visa mappen",
                         "\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u043f\u0430\u043f\u043a\u0443"),
    "set.packs":        ("New drawings, pictures and puzzles go in this folder (.json packs):",
                         "Nya teckningar, bilder och pyssel l\u00e4ggs i den h\u00e4r mappen (.json-paket):",
                         "\u041d\u043e\u0432\u044b\u0435 \u0440\u0438\u0441\u0443\u043d\u043a\u0438, \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438 \u0438 \u0437\u0430\u0434\u0430\u043d\u0438\u044f \u043a\u043b\u0430\u0434\u0443\u0442\u0441\u044f \u0432 \u044d\u0442\u0443 \u043f\u0430\u043f\u043a\u0443 (\u043f\u0430\u043a\u0435\u0442\u044b .json):"),
    "stats.title":      ("My results", "Mina resultat", "\u041c\u043e\u0438 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b"),
    "stats.size":       ("Size", "Storlek", "\u0420\u0430\u0437\u043c\u0435\u0440"),
    "stats.solved":     ("Solved", "L\u00f6sta", "\u0420\u0435\u0448\u0435\u043d\u043e"),
    "stats.stars":      ("Stars", "Stj\u00e4rnor", "\u0417\u0432\u0451\u0437\u0434\u044b"),
    "stats.best":       ("Best time", "B\u00e4sta tid", "\u041b\u0443\u0447\u0448\u0435\u0435 \u0432\u0440\u0435\u043c\u044f"),
    "stats.none":       ("Nothing solved yet - your results will show up here.",
                         "Inget l\u00f6st \u00e4n - dina resultat hamnar h\u00e4r.",
                         "\u041f\u043e\u043a\u0430 \u043d\u0438\u0447\u0435\u0433\u043e \u043d\u0435 \u0440\u0435\u0448\u0435\u043d\u043e - \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442\u044b \u0431\u0443\u0434\u0443\u0442 \u0437\u0434\u0435\u0441\u044c."),
    "stats.total":      ("All sizes", "Alla storlekar", "\u0412\u0441\u0435 \u0440\u0430\u0437\u043c\u0435\u0440\u044b"),
    "help.title":       ("Help", "Hj\u00e4lp", "\u0421\u043f\u0440\u0430\u0432\u043a\u0430"),
    "about.title":      ("About", "Om", "\u041e \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0435"),
    "about.by":         ("Designed by", "Designad av", "Автор дизайна"),
    "about.doc":        ("View documentation", "Visa dokumentation",
                         "Документация"),
    "about.gift":       ("If you enjoy this program, a small gift is always "
                         "welcome!",
                         "Gillar du programmet är en liten gåva alltid "
                         "välkommen!",
                         "Если программа вам нравится, небольшой подарок "
                         "всегда приятен!"),
}


class K:
    """A text key used as an ARGUMENT to another text key.

    T("feed.step", 4, K("dir.up")) keeps the direction as a key instead of as
    finished words, so the line can be written again in another language
    later - which is exactly what the feed panel does when the language is
    switched in the middle of a maze.  en() resolves it to English for the
    log file at the same time.
    """

    __slots__ = ("key",)

    def __init__(self, key):
        self.key = key

    def __str__(self):
        return T(self.key)

    def __repr__(self):
        return "K(%r)" % self.key


def T(key, *args):
    """The one way UI text is produced.  Unknown key is loud, never silent."""
    row = TXT.get(key)
    if not row:
        return "<<%s>>" % key
    lang = SETTINGS.get("language", "sv")
    if lang not in LANGS:
        lang = "sv"
    s = row[LANGS.index(lang)]
    if args:
        try:
            s = s.format(*[T(a.key) if isinstance(a, K) else a for a in args])
        except Exception:
            pass
    return s


def en(key, *args):
    """The English column - what goes in the log file, whatever the player reads."""
    row = TXT.get(key)
    s = row[0] if row else "<<%s>>" % key
    if args:
        try:
            s = s.format(*[en(a.key) if isinstance(a, K) else a
                           for a in args])
        except Exception:
            pass
    return s


def T_all(key):
    """All three columns of a key - used to size a widget so it never resizes."""
    row = TXT.get(key)
    return list(row) if row else ["<<%s>>" % key]


def width_for(*keys):
    """Character width that fits the longest line of every language (01_CORE 6)."""
    best = 1
    for k in keys:
        for s in T_all(k):
            for line in str(s).split("\n"):
                best = max(best, len(line))
    return best


# ---- the retranslate registry ------------------------------------------------
# Widgets register themselves with the key they show.  Changing language never
# rebuilds the window (a half-traced maze must survive it) and never resizes
# anything, because every widget was sized for all three languages up front.

_I18N = []


def reg(widget, key, attr="text", *args):
    # A widget can change which key it shows (the hint button does).  Replace
    # its old entry instead of piling entries up - two entries for the same
    # widget would fight each other on every language change.
    _I18N[:] = [e for e in _I18N if not (e[0] is widget and e[2] == attr)]
    _I18N.append((widget, key, attr, args))
    try:
        widget.configure(**{attr: T(key, *args)})
    except Exception:
        pass
    return widget


def unreg_dead():
    keep = []
    for w, k, a, args in _I18N:
        try:
            if w.winfo_exists():
                keep.append((w, k, a, args))
        except Exception:
            pass
    _I18N[:] = keep


def retranslate():
    unreg_dead()
    for w, k, a, args in _I18N:
        try:
            w.configure(**{a: T(k, *args)})
        except Exception:
            pass
    for cb in list(_RETRANSLATE_HOOKS):
        try:
            cb()
        except Exception:
            pass


_RETRANSLATE_HOOKS = []


def on_retranslate(cb):
    """For things a plain configure() cannot fix - canvases, option menus."""
    _RETRANSLATE_HOOKS.append(cb)
    return cb


def cap(s):
    """First letter up.  The drawings names are written for the middle of a
    sentence ("hunden", "the dog"); the task line starts with one."""
    return (s[:1].upper() + s[1:]) if s else s


def fmt_time(seconds):
    seconds = int(max(0, seconds))
    return "%d:%02d" % (seconds // 60, seconds % 60)

# *************** DEL 08 - DRAWING PRIMITIVES (ONE FORMAT, TWO BACKENDS) ******
# All the art in this program is a plain list of primitives, and there are two
# coordinate systems for them:
#
#   UNIT art  (DEL 09)  x and y run 0.0 - 1.0, drawn centred in a box, so the
#                       same dog works at 26 pixels in a maze square and at
#                       200 in the About dialog.
#   SCENE art (DEL 17)  x and y run over a design box, e.g. 1000 x 700, drawn
#                       from a corner.  That is what the colouring pictures
#                       and the jigsaw picture use.
#
# Both go through the same two backends: tkinter's canvas (what the player
# sees) and Pillow (the contact sheet, the PNG export, the jigsaw pieces).
# Only the coordinate mapping differs, so the drawing code below is written
# once and handed a mapping function.
#
# Curves: there is no spline in Pillow, so smoothing is done HERE, in Python
# (Catmull-Rom -> short line segments) and both backends then draw plain
# polygons.  That way the canvas and the PNG cannot drift apart.

INK = "#3e2723"          # the outline colour of every drawing: warm dark brown


def poly(pts, fill=None, line=INK, w=2.0, smooth=False):
    return dict(kind="poly", pts=list(pts), fill=fill, line=line, w=w,
                smooth=smooth)


def pline(pts, line=INK, w=2.0, smooth=False):
    return dict(kind="line", pts=list(pts), line=line, w=w, smooth=smooth)


def oval(box, fill=None, line=INK, w=2.0):
    return dict(kind="oval", box=tuple(box), fill=fill, line=line, w=w)


def arc(box, start, extent, line=INK, w=2.0):
    return dict(kind="arc", box=tuple(box), start=start, extent=extent,
                line=line, w=w)


def smooth_pts(pts, closed=False, steps=6):
    """Catmull-Rom through every given point.  Returns a denser point list."""
    n = len(pts)
    if n < 3:
        return list(pts)
    p = list(pts)
    if closed:
        seq = [p[-1]] + p + [p[0], p[1]]
    else:
        seq = [p[0]] + p + [p[-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, t3 = t * t, t * t * t
            x = 0.5 * ((2 * p1[0]) + (-p0[0] + p2[0]) * t +
                       (2 * p0[0] - 5 * p1[0] + 4 * p2[0] - p3[0]) * t2 +
                       (-p0[0] + 3 * p1[0] - 3 * p2[0] + p3[0]) * t3)
            y = 0.5 * ((2 * p1[1]) + (-p0[1] + p2[1]) * t +
                       (2 * p0[1] - 5 * p1[1] + 4 * p2[1] - p3[1]) * t2 +
                       (-p0[1] + 3 * p1[1] - 3 * p2[1] + p3[1]) * t3)
            out.append((x, y))
    if not closed:
        out.append(p[-1])
    return out


def _prim_points(pr):
    """The point list a prim finally draws with (smoothed if it asked for it)."""
    pts = pr["pts"]
    if pr.get("smooth") and len(pts) >= 3:
        return smooth_pts(pts, closed=(pr["kind"] == "poly"))
    return pts


def _place(cx, cy, size, flip):
    """Unit point -> pixel.  (0.5, 0.5) lands on (cx, cy); size is the full box."""
    def f(p):
        x, y = p[0], p[1]
        if flip:
            x = 1.0 - x
        return (cx + (x - 0.5) * size, cy + (y - 0.5) * size)
    return f


def _place_scene(ox, oy, scale):
    """Scene point -> pixel: the design box's corner lands on (ox, oy)."""
    def f(p):
        return (ox + p[0] * scale, oy + p[1] * scale)
    return f


def _lw(w, size):
    # w = 0 is a real value and means NO outline - the sky in a picture has
    # no line around it.  Anything above 0 is at least one pixel wide.
    return 0 if w <= 0 else max(1, int(round(w * size / 40.0)))


# ---- the one drawing routine, twice: canvas and Pillow ----------------------

def draw_prims_at(canvas, prims, f, width_of, tags=(), fill_over=None):
    """Draw a primitive list through the mapping f.  Returns the item ids.

    fill_over, when given, is a dict {index: colour} that replaces a prim's
    own fill - that is how the colouring part paints one named part of a
    picture without touching the picture data itself."""
    items = []
    for i, pr in enumerate(prims):
        k = pr["kind"]
        wid = width_of(pr.get("w", 2.0))
        stroke = (pr.get("line") or "") if wid > 0 else ""
        fill = pr.get("fill")
        if fill_over and i in fill_over:
            fill = fill_over[i]
        if k == "line" and not stroke:
            continue                      # a stroke with no colour is nothing
        if k in ("poly", "line"):
            flat = []
            for p in _prim_points(pr):
                flat.extend(f(p))
            if len(flat) < 4:
                continue
            if k == "poly":
                items.append(canvas.create_polygon(
                    *flat, fill=(fill or ""), outline=stroke,
                    width=max(1, wid), tags=tags))
            else:
                items.append(canvas.create_line(
                    *flat, fill=stroke, width=max(1, wid),
                    capstyle="round", joinstyle="round", tags=tags))
        elif k == "oval":
            x0, y0 = f((pr["box"][0], pr["box"][1]))
            x1, y1 = f((pr["box"][2], pr["box"][3]))
            items.append(canvas.create_oval(
                x0, y0, x1, y1, fill=(fill or ""), outline=stroke,
                width=max(1, wid), tags=tags))
        elif k == "arc":
            x0, y0 = f((pr["box"][0], pr["box"][1]))
            x1, y1 = f((pr["box"][2], pr["box"][3]))
            items.append(canvas.create_arc(
                x0, y0, x1, y1, start=pr["start"], extent=pr["extent"],
                style="arc", outline=(pr.get("line") or INK), width=wid,
                tags=tags))
    return items


def draw_prims_pil_at(draw, prims, f, width_of, fill_over=None):
    """The same list through Pillow."""
    for i, pr in enumerate(prims):
        k = pr["kind"]
        wid = width_of(pr.get("w", 2.0))
        stroke = (pr.get("line") or "") if wid > 0 else ""
        fill = pr.get("fill")
        if fill_over and i in fill_over:
            fill = fill_over[i]
        if k in ("poly", "line"):
            pts = [f(p) for p in _prim_points(pr)]
            if len(pts) < 2:
                continue
            if k == "poly":
                if fill:
                    draw.polygon(pts, fill=fill)
                if stroke:
                    draw.line(pts + [pts[0]], fill=stroke,
                              width=max(1, wid), joint="curve")
            elif stroke:
                draw.line(pts, fill=stroke, width=max(1, wid),
                          joint="curve")
        elif k in ("oval", "arc"):
            x0, y0 = f((pr["box"][0], pr["box"][1]))
            x1, y1 = f((pr["box"][2], pr["box"][3]))
            box = [min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)]
            if k == "oval":
                # tkinter takes "" for "no colour", Pillow insists on None
                draw.ellipse(box, fill=(fill or None),
                             outline=(stroke or None), width=max(1, wid))
            else:
                # tkinter counts degrees counter-clockwise from 3 o'clock,
                # Pillow clockwise - mirror the angles so both look the same.
                start = -(pr["start"] + pr["extent"])
                end = -pr["start"]
                if stroke:
                    draw.arc(box, start, end, fill=stroke, width=max(1, wid))


# ---- the two coordinate systems, as thin wrappers ---------------------------

def draw_prims(canvas, prims, cx, cy, size, flip=False, tags=()):
    """UNIT art, centred on (cx, cy) in a box `size` pixels across."""
    return draw_prims_at(canvas, prims, _place(cx, cy, size, flip),
                         lambda w: _lw(w, size), tags=tags)


def draw_prims_pil(draw, prims, cx, cy, size, flip=False):
    draw_prims_pil_at(draw, prims, _place(cx, cy, size, flip),
                      lambda w: _lw(w, size))


def draw_scene(canvas, prims, ox, oy, scale, tags=(), fill_over=None):
    """SCENE art, the design box's corner at (ox, oy), scaled by `scale`."""
    return draw_prims_at(canvas, prims, _place_scene(ox, oy, scale),
                         lambda w: max(1, int(round(w * scale))), tags=tags,
                         fill_over=fill_over)


def draw_scene_pil(draw, prims, ox, oy, scale, fill_over=None):
    draw_prims_pil_at(draw, prims, _place_scene(ox, oy, scale),
                      lambda w: max(1, int(round(w * scale))),
                      fill_over=fill_over)

# *************** DEL 09 - THE DRAWINGS (PROFILE SILHOUETTES) *****************
# One entry per thing that can stand in a maze square.  Unit coordinates, drawn
# back to front: legs and tails first, then the body, then the details, so an
# overlapping outline is hidden under the shape that comes after it.
#
# Animals are drawn FULL BODY FROM THE SIDE - the silhouette is what makes a
# dog a dog at 26 pixels, not a face.  That is also why the cat has an arched
# back, upright triangular ears and a long tail while the mouse has a round
# body, huge round ears and a thin tail: at this size the outline is the whole
# message.  --selftest renders every one of them to a contact sheet.

DOG_BODY, DOG_DARK = "#c98a4b", "#a06a2c"
CAT_BODY, CAT_DARK = "#9e9e9e", "#6d6d6d"
MOUSE_BODY, MOUSE_EAR = "#bdbdbd", "#f8bbd0"
ICE_DARK, ICE_LIGHT = "#01579b", "#b3e5fc"

ART = {}

# ---- the dog: long muzzle, hanging ear, tail up ----------------------------
ART["dog"] = [
    pline([(0.15, 0.44), (0.06, 0.34), (0.09, 0.19), (0.19, 0.15)],
          line=DOG_BODY, w=5, smooth=True),                     # tail, curled
    pline([(0.27, 0.56), (0.25, 0.88)], line=DOG_DARK, w=5),    # far hind leg
    pline([(0.55, 0.56), (0.57, 0.88)], line=DOG_DARK, w=5),    # far fore leg
    pline([(0.20, 0.56), (0.18, 0.88)], line=DOG_BODY, w=7),    # near hind leg
    pline([(0.62, 0.56), (0.64, 0.88)], line=DOG_BODY, w=7),    # near fore leg
    poly([(0.14, 0.46), (0.26, 0.38), (0.46, 0.36), (0.60, 0.40),
          (0.64, 0.50), (0.56, 0.60), (0.34, 0.62), (0.18, 0.58)],
         fill=DOG_BODY, smooth=True),                           # torso
    poly([(0.56, 0.42), (0.66, 0.26), (0.78, 0.28), (0.70, 0.52)],
         fill=DOG_BODY, smooth=True),                           # neck
    poly([(0.70, 0.22), (0.80, 0.17), (0.89, 0.21), (0.99, 0.27),
          (0.99, 0.36), (0.88, 0.37), (0.80, 0.43), (0.69, 0.40),
          (0.65, 0.30)], fill=DOG_BODY, smooth=True),           # head + muzzle
    poly([(0.72, 0.21), (0.65, 0.29), (0.66, 0.42), (0.74, 0.35),
          (0.76, 0.23)], fill=DOG_DARK, smooth=True),           # hanging ear
    pline([(0.69, 0.40), (0.73, 0.50)], line="#e53935", w=3),   # collar
    oval((0.935, 0.255, 0.995, 0.315), fill=INK, line=""),      # nose
    oval((0.838, 0.238, 0.872, 0.272), fill=INK, line=""),      # eye
    pline([(0.965, 0.345), (0.895, 0.355)], w=1.5),             # mouth
]

# ---- the kennel: the right place to end up ---------------------------------
ART["kennel"] = [
    poly([(0.12, 0.46), (0.88, 0.46), (0.88, 0.92), (0.12, 0.92)],
         fill="#d7a86e"),
    poly([(0.50, 0.10), (0.97, 0.50), (0.03, 0.50)], fill="#c0392b"),
    poly([(0.36, 0.92), (0.36, 0.68), (0.43, 0.58), (0.57, 0.58),
          (0.64, 0.68), (0.64, 0.92)], fill="#5d4037", smooth=True),
    poly([(0.42, 0.50), (0.58, 0.50), (0.58, 0.56), (0.42, 0.56)],
         fill="#efe0c0"),                                       # name plate
    pline([(0.12, 0.62), (0.36, 0.62)], w=1.5),
    pline([(0.64, 0.62), (0.88, 0.62)], w=1.5),
]

# ---- the water tap (vattenpost): a wrong place to end up -------------------
ART["tap"] = [
    poly([(0.30, 0.86), (0.70, 0.86), (0.72, 0.95), (0.28, 0.95)],
         fill="#546e7a"),                                       # base
    poly([(0.42, 0.20), (0.58, 0.20), (0.58, 0.88), (0.42, 0.88)],
         fill="#5b8fa8"),                                       # post
    poly([(0.35, 0.13), (0.65, 0.13), (0.65, 0.22), (0.35, 0.22)],
         fill="#37718c"),                                       # cap
    poly([(0.58, 0.38), (0.82, 0.38), (0.82, 0.48), (0.58, 0.48)],
         fill="#5b8fa8"),                                       # spout
    pline([(0.42, 0.28), (0.22, 0.24)], line="#37718c", w=5),   # handle
    oval((0.68, 0.54, 0.78, 0.66), fill="#4fc3f7"),             # drip
    oval((0.70, 0.72, 0.77, 0.80), fill="#4fc3f7"),
]

# ---- the cat: arched back, upright ears, long tail -------------------------
ART["cat"] = [
    pline([(0.20, 0.50), (0.08, 0.40), (0.11, 0.22), (0.21, 0.19)],
          line=CAT_BODY, w=5, smooth=True),                     # tail
    pline([(0.32, 0.58), (0.30, 0.88)], line=CAT_DARK, w=4),
    pline([(0.56, 0.58), (0.58, 0.88)], line=CAT_DARK, w=4),
    pline([(0.25, 0.58), (0.23, 0.88)], line=CAT_BODY, w=5),
    pline([(0.62, 0.58), (0.64, 0.88)], line=CAT_BODY, w=5),
    poly([(0.20, 0.52), (0.32, 0.38), (0.50, 0.34), (0.64, 0.40),
          (0.67, 0.52), (0.54, 0.61), (0.34, 0.62), (0.22, 0.58)],
         fill=CAT_BODY, smooth=True),                           # arched torso
    poly([(0.71, 0.29), (0.69, 0.17), (0.79, 0.25)], fill=CAT_BODY),   # ear
    poly([(0.86, 0.27), (0.92, 0.17), (0.93, 0.31)], fill=CAT_BODY),   # ear
    poly([(0.64, 0.41), (0.70, 0.30), (0.82, 0.27), (0.92, 0.32),
          (0.93, 0.44), (0.84, 0.51), (0.71, 0.50)],
         fill=CAT_BODY, smooth=True),                           # round head
    pline([(0.40, 0.37), (0.38, 0.47)], line=CAT_DARK, w=2),    # stripes
    pline([(0.50, 0.35), (0.48, 0.46)], line=CAT_DARK, w=2),
    oval((0.845, 0.345, 0.878, 0.385), fill=INK, line=""),      # eye
    poly([(0.93, 0.38), (0.98, 0.41), (0.93, 0.44)], fill="#ef9a9a"),  # nose
    pline([(0.92, 0.42), (0.99, 0.48)], w=1.2),                 # whiskers
    pline([(0.92, 0.40), (1.00, 0.38)], w=1.2),
]

# ---- the mouse: round body, huge round ears, thin tail ---------------------
ART["mouse"] = [
    pline([(0.22, 0.68), (0.09, 0.72), (0.05, 0.56)], line=MOUSE_BODY, w=2.5,
          smooth=True),                                         # tail
    oval((0.40, 0.26, 0.68, 0.54), fill=MOUSE_BODY),            # ear
    oval((0.46, 0.32, 0.62, 0.48), fill=MOUSE_EAR, line=""),
    poly([(0.16, 0.62), (0.26, 0.46), (0.46, 0.42), (0.64, 0.46),
          (0.78, 0.58), (0.87, 0.67), (0.66, 0.75), (0.40, 0.77),
          (0.20, 0.72)], fill=MOUSE_BODY, smooth=True),         # body + snout
    pline([(0.34, 0.76), (0.33, 0.86)], line=MOUSE_BODY, w=4),
    pline([(0.56, 0.74), (0.57, 0.85)], line=MOUSE_BODY, w=4),
    oval((0.715, 0.575, 0.75, 0.61), fill=INK, line=""),        # eye
    oval((0.855, 0.645, 0.90, 0.69), fill="#ef9a9a", line=""),  # nose
    pline([(0.87, 0.66), (0.96, 0.61)], w=1.2),                 # whiskers
    pline([(0.87, 0.69), (0.95, 0.74)], w=1.2),
]

# ---- the cheese: the right place for a mouse -------------------------------
ART["cheese"] = [
    poly([(0.10, 0.36), (0.24, 0.24), (0.96, 0.66), (0.88, 0.78)],
         fill="#ffe082"),                                       # top face
    poly([(0.10, 0.36), (0.10, 0.80), (0.88, 0.80), (0.88, 0.78)],
         fill="#ffd54f"),                                       # front face
    oval((0.22, 0.52, 0.34, 0.64), fill="#f9a825", line=""),
    oval((0.44, 0.58, 0.54, 0.68), fill="#f9a825", line=""),
    oval((0.62, 0.62, 0.74, 0.74), fill="#f9a825", line=""),
    oval((0.30, 0.68, 0.38, 0.76), fill="#f9a825", line=""),
]

# ---- the mousetrap: a wrong place ------------------------------------------
ART["trap"] = [
    arc((0.16, 0.26, 0.84, 0.94), 20, 140, line="#9e9e9e", w=4),
    poly([(0.08, 0.66), (0.92, 0.66), (0.92, 0.90), (0.08, 0.90)],
         fill="#8d6e63"),
    oval((0.14, 0.54, 0.30, 0.70), fill="", line="#9e9e9e", w=3),
    oval((0.58, 0.56, 0.74, 0.66), fill="#ffd54f"),
    pline([(0.08, 0.78), (0.92, 0.78)], w=1.2),
]

# ---- the bee: wings up, stripes across ------------------------------------
ART["bee"] = [
    oval((0.30, 0.14, 0.62, 0.42), fill="#e1f5fe"),             # far wing
    oval((0.44, 0.18, 0.74, 0.44), fill="#eaf7fe"),             # near wing
    poly([(0.28, 0.48), (0.14, 0.53), (0.28, 0.60)], fill=INK), # stinger
    oval((0.26, 0.38, 0.78, 0.72), fill="#ffca28"),             # body
    pline([(0.44, 0.44), (0.43, 0.66)], w=5),                   # stripes
    pline([(0.56, 0.42), (0.55, 0.68)], w=5),
    pline([(0.68, 0.45), (0.67, 0.65)], w=5),
    pline([(0.38, 0.70), (0.34, 0.84)], w=2),                   # legs
    pline([(0.52, 0.72), (0.50, 0.86)], w=2),
    pline([(0.64, 0.70), (0.66, 0.84)], w=2),
    oval((0.70, 0.42, 0.92, 0.64), fill=INK, line=""),          # head
    oval((0.845, 0.475, 0.885, 0.515), fill="#ffffff", line=""),# eye
    pline([(0.82, 0.42), (0.88, 0.28)], w=1.5),                 # antennae
    pline([(0.74, 0.42), (0.72, 0.28)], w=1.5),
    oval((0.86, 0.24, 0.92, 0.30), fill=INK, line=""),
    oval((0.68, 0.24, 0.74, 0.30), fill=INK, line=""),
]

# ---- the flower: the right place for a bee --------------------------------
ART["flower"] = [
    pline([(0.50, 0.94), (0.50, 0.50)], line="#43a047", w=4),
    poly([(0.50, 0.76), (0.32, 0.66), (0.35, 0.83)], fill="#66bb6a",
         smooth=True),
    poly([(0.50, 0.68), (0.68, 0.60), (0.66, 0.77)], fill="#66bb6a",
         smooth=True),
    oval((0.59, 0.32, 0.75, 0.48), fill="#ec407a"),
    oval((0.505, 0.467, 0.665, 0.627), fill="#ec407a"),
    oval((0.335, 0.467, 0.495, 0.627), fill="#ec407a"),
    oval((0.25, 0.32, 0.41, 0.48), fill="#ec407a"),
    oval((0.335, 0.173, 0.495, 0.333), fill="#ec407a"),
    oval((0.505, 0.173, 0.665, 0.333), fill="#ec407a"),
    oval((0.41, 0.31, 0.59, 0.49), fill="#ffca28"),
]

# ---- the spider web: a wrong place for a bee ------------------------------
ART["web"] = [
    pline([(0.50, 0.04), (0.50, 0.92)], line="#78909c", w=1.5),
    pline([(0.10, 0.20), (0.90, 0.76)], line="#78909c", w=1.5),
    pline([(0.90, 0.20), (0.10, 0.76)], line="#78909c", w=1.5),
    pline([(0.14, 0.48), (0.86, 0.48)], line="#78909c", w=1.5),
    poly([(0.50, 0.20), (0.76, 0.34), (0.78, 0.62), (0.50, 0.76),
          (0.22, 0.62), (0.24, 0.34)], fill="", line="#78909c", w=1.5),
    poly([(0.50, 0.34), (0.64, 0.42), (0.65, 0.56), (0.50, 0.64),
          (0.36, 0.56), (0.35, 0.42)], fill="", line="#78909c", w=1.5),
    oval((0.42, 0.42, 0.58, 0.56), fill=INK, line=""),          # the spider
    pline([(0.42, 0.44), (0.32, 0.36)], w=1.2),
    pline([(0.42, 0.54), (0.32, 0.62)], w=1.2),
    pline([(0.58, 0.44), (0.68, 0.36)], w=1.2),
    pline([(0.58, 0.54), (0.68, 0.62)], w=1.2),
]

# ---- the rain cloud: another wrong place for a bee ------------------------
ART["rain"] = [
    oval((0.10, 0.26, 0.48, 0.58), fill="#b0bec5"),
    oval((0.34, 0.16, 0.74, 0.54), fill="#b0bec5"),
    oval((0.58, 0.28, 0.92, 0.58), fill="#b0bec5"),
    poly([(0.14, 0.46), (0.88, 0.46), (0.88, 0.58), (0.14, 0.58)],
         fill="#b0bec5", line=""),
    pline([(0.26, 0.64), (0.20, 0.82)], line="#4fc3f7", w=3),
    pline([(0.46, 0.64), (0.40, 0.86)], line="#4fc3f7", w=3),
    pline([(0.66, 0.64), (0.60, 0.82)], line="#4fc3f7", w=3),
    pline([(0.82, 0.64), (0.76, 0.78)], line="#4fc3f7", w=3),
]

# ---- the penguin: upright, flipper out, orange feet ----------------------
ART["penguin"] = [
    poly([(0.34, 0.88), (0.28, 0.94), (0.50, 0.94)], fill="#ffb300"),
    poly([(0.56, 0.88), (0.54, 0.94), (0.74, 0.94)], fill="#ffb300"),
    poly([(0.36, 0.22), (0.50, 0.15), (0.64, 0.22), (0.71, 0.46),
          (0.69, 0.74), (0.58, 0.88), (0.42, 0.88), (0.31, 0.74),
          (0.29, 0.46)], fill="#37474f", smooth=True),
    poly([(0.43, 0.33), (0.57, 0.31), (0.63, 0.52), (0.61, 0.74),
          (0.50, 0.83), (0.39, 0.74), (0.37, 0.52)], fill="#fafafa",
         smooth=True),
    poly([(0.68, 0.38), (0.80, 0.58), (0.66, 0.64)], fill="#37474f",
         smooth=True),                                          # flipper
    poly([(0.63, 0.27), (0.82, 0.32), (0.63, 0.37)], fill="#ffb300"),  # beak
    oval((0.555, 0.215, 0.605, 0.265), fill="#fafafa", line=""),
    oval((0.565, 0.225, 0.595, 0.255), fill=INK, line=""),
]

# ---- the fish: the right place for a penguin -----------------------------
ART["fish"] = [
    poly([(0.20, 0.50), (0.06, 0.32), (0.11, 0.50), (0.06, 0.70)],
         fill="#1e88e5"),                                       # tail
    poly([(0.42, 0.33), (0.52, 0.20), (0.62, 0.32)], fill="#1e88e5"),
    poly([(0.44, 0.67), (0.50, 0.78), (0.60, 0.66)], fill="#1e88e5"),
    poly([(0.18, 0.50), (0.36, 0.34), (0.58, 0.31), (0.74, 0.40),
          (0.84, 0.50), (0.74, 0.60), (0.56, 0.69), (0.34, 0.67)],
         fill="#42a5f5", smooth=True),                          # body
    arc((0.58, 0.34, 0.82, 0.66), 60, 120, w=1.5),              # gill
    oval((0.695, 0.425, 0.755, 0.485), fill="#fafafa", line=""),
    oval((0.715, 0.44, 0.745, 0.47), fill=INK, line=""),
    pline([(0.84, 0.52), (0.79, 0.56)], w=1.5),                 # mouth
]

# ---- the seal: a wrong place for a penguin -------------------------------
ART["seal"] = [
    poly([(0.10, 0.76), (0.03, 0.64), (0.05, 0.86)], fill="#546e7a"),
    poly([(0.09, 0.78), (0.22, 0.62), (0.48, 0.58), (0.68, 0.50),
          (0.78, 0.36), (0.90, 0.34), (0.95, 0.44), (0.86, 0.56),
          (0.80, 0.70), (0.50, 0.81), (0.20, 0.82)],
         fill="#78909c", smooth=True),
    poly([(0.60, 0.62), (0.72, 0.80), (0.50, 0.77)], fill="#546e7a",
         smooth=True),                                          # flipper
    oval((0.905, 0.395, 0.955, 0.445), fill=INK, line=""),      # snout
    oval((0.835, 0.385, 0.868, 0.418), fill=INK, line=""),      # eye
    pline([(0.92, 0.44), (0.99, 0.52)], w=1.2),
    pline([(0.90, 0.45), (0.94, 0.56)], w=1.2),
]

# ---- the hole in the ice: another wrong place ----------------------------
ART["icehole"] = [
    poly([(0.06, 0.30), (0.94, 0.26), (0.96, 0.86), (0.04, 0.90)],
         fill="#e1f5fe", line=""),
    poly([(0.16, 0.40), (0.38, 0.34), (0.66, 0.35), (0.86, 0.44),
          (0.82, 0.68), (0.56, 0.78), (0.28, 0.74), (0.14, 0.58)],
         fill=ICE_DARK, line=ICE_LIGHT, w=3, smooth=True),
    pline([(0.30, 0.50), (0.44, 0.46)], line="#4fc3f7", w=2),
    pline([(0.52, 0.62), (0.70, 0.58)], line="#4fc3f7", w=2),
    poly([(0.04, 0.24), (0.22, 0.20), (0.18, 0.32), (0.06, 0.34)],
         fill="#ffffff"),
    poly([(0.78, 0.18), (0.94, 0.16), (0.92, 0.26), (0.76, 0.28)],
         fill="#ffffff"),
]

# ---- the puddle: a wrong place in any theme ------------------------------
ART["puddle"] = [
    poly([(0.10, 0.66), (0.30, 0.54), (0.58, 0.52), (0.84, 0.58),
          (0.92, 0.70), (0.74, 0.84), (0.42, 0.86), (0.16, 0.78)],
         fill="#4fc3f7", line="#0288d1", w=2, smooth=True),
    arc((0.28, 0.60, 0.56, 0.76), 0, 180, line="#e1f5fe", w=2),
    arc((0.52, 0.64, 0.80, 0.80), 0, 180, line="#e1f5fe", w=2),
    oval((0.60, 0.36, 0.68, 0.46), fill="#4fc3f7", line="#0288d1", w=1.5),
    oval((0.34, 0.30, 0.41, 0.39), fill="#4fc3f7", line="#0288d1", w=1.5),
]

# ---- the dead end: a brick wall -----------------------------------------
ART["wall"] = [
    poly([(0.06, 0.30), (0.94, 0.30), (0.94, 0.90), (0.06, 0.90)],
         fill="#bf5f4f"),
    pline([(0.06, 0.50), (0.94, 0.50)], line="#efe0d0", w=2),
    pline([(0.06, 0.70), (0.94, 0.70)], line="#efe0d0", w=2),
    pline([(0.34, 0.30), (0.34, 0.50)], line="#efe0d0", w=2),
    pline([(0.66, 0.30), (0.66, 0.50)], line="#efe0d0", w=2),
    pline([(0.20, 0.50), (0.20, 0.70)], line="#efe0d0", w=2),
    pline([(0.50, 0.50), (0.50, 0.70)], line="#efe0d0", w=2),
    pline([(0.80, 0.50), (0.80, 0.70)], line="#efe0d0", w=2),
    pline([(0.34, 0.70), (0.34, 0.90)], line="#efe0d0", w=2),
    pline([(0.66, 0.70), (0.66, 0.90)], line="#efe0d0", w=2),
]

# ---- the rabbit: long ears, round back, cotton tail ------------------------
RABBIT_BODY, RABBIT_DARK, RABBIT_PINK = "#d7ccc8", "#a1887f", "#f8bbd0"
FOX_BODY, FOX_DARK = "#ef6c00", "#bf360c"

ART["rabbit"] = [
    oval((0.10, 0.52, 0.26, 0.68), fill="#fafafa"),             # cotton tail
    pline([(0.36, 0.66), (0.34, 0.88)], line=RABBIT_DARK, w=5),
    pline([(0.58, 0.64), (0.60, 0.88)], line=RABBIT_DARK, w=5),
    poly([(0.18, 0.56), (0.30, 0.40), (0.48, 0.36), (0.62, 0.44),
          (0.66, 0.62), (0.56, 0.78), (0.34, 0.80), (0.20, 0.70)],
         fill=RABBIT_BODY, smooth=True),                        # body
    poly([(0.69, 0.30), (0.64, 0.12), (0.73, 0.07), (0.78, 0.26)],
         fill=RABBIT_BODY, smooth=True),                        # far ear
    poly([(0.70, 0.26), (0.68, 0.14), (0.73, 0.12), (0.76, 0.24)],
         fill=RABBIT_PINK, line="", smooth=True),
    poly([(0.79, 0.28), (0.81, 0.09), (0.90, 0.13), (0.86, 0.31)],
         fill=RABBIT_BODY, smooth=True),                        # near ear
    poly([(0.81, 0.26), (0.83, 0.15), (0.87, 0.17), (0.85, 0.28)],
         fill=RABBIT_PINK, line="", smooth=True),
    poly([(0.60, 0.44), (0.68, 0.30), (0.80, 0.28), (0.90, 0.35),
          (0.90, 0.45), (0.80, 0.52), (0.66, 0.52)],
         fill=RABBIT_BODY, smooth=True),                        # head
    oval((0.795, 0.345, 0.828, 0.378), fill=INK, line=""),      # eye
    oval((0.885, 0.385, 0.925, 0.425), fill=RABBIT_PINK, line=""),
    pline([(0.91, 0.42), (0.98, 0.39)], w=1.2),                 # whiskers
    pline([(0.91, 0.44), (0.97, 0.49)], w=1.2),
]

# ---- the carrot: the rabbit's right place to end up ------------------------
ART["carrot"] = [
    poly([(0.50, 0.38), (0.34, 0.16), (0.46, 0.13)], fill="#43a047"),
    poly([(0.50, 0.36), (0.49, 0.06), (0.59, 0.11)], fill="#43a047"),
    poly([(0.52, 0.38), (0.70, 0.18), (0.68, 0.32)], fill="#43a047"),
    poly([(0.34, 0.36), (0.66, 0.36), (0.52, 0.93)], fill="#fb8c00"),
    pline([(0.40, 0.48), (0.60, 0.48)], w=1.5),
    pline([(0.43, 0.60), (0.58, 0.60)], w=1.5),
    pline([(0.46, 0.72), (0.56, 0.72)], w=1.5),
]

# ---- the fox: pointed snout, bushy tail with a white tip -------------------
ART["fox"] = [
    poly([(0.26, 0.54), (0.12, 0.44), (0.04, 0.26), (0.16, 0.22),
          (0.30, 0.40)], fill=FOX_BODY, smooth=True),           # bushy tail
    poly([(0.10, 0.31), (0.04, 0.26), (0.16, 0.22), (0.15, 0.30)],
         fill="#fafafa", smooth=True),                          # white tip
    pline([(0.34, 0.60), (0.33, 0.87)], line="#8d6e63", w=4),
    pline([(0.58, 0.60), (0.59, 0.87)], line="#8d6e63", w=4),
    pline([(0.27, 0.60), (0.26, 0.88)], line="#6d4c41", w=4),
    pline([(0.64, 0.60), (0.65, 0.88)], line="#6d4c41", w=4),
    poly([(0.20, 0.50), (0.34, 0.40), (0.52, 0.38), (0.64, 0.44),
          (0.68, 0.56), (0.52, 0.66), (0.32, 0.66), (0.22, 0.60)],
         fill=FOX_BODY, smooth=True),                           # body
    poly([(0.67, 0.31), (0.65, 0.17), (0.76, 0.27)], fill=FOX_DARK),
    poly([(0.80, 0.29), (0.87, 0.19), (0.88, 0.33)], fill=FOX_DARK),
    poly([(0.62, 0.44), (0.68, 0.30), (0.80, 0.27), (0.88, 0.33),
          (0.99, 0.41), (0.86, 0.47), (0.78, 0.53), (0.66, 0.53)],
         fill=FOX_BODY, smooth=True),                           # head + snout
    poly([(0.82, 0.47), (0.95, 0.43), (0.90, 0.50), (0.80, 0.52)],
         fill="#fafafa", line="", smooth=True),                 # white cheek
    oval((0.795, 0.335, 0.828, 0.368), fill=INK, line=""),      # eye
    oval((0.955, 0.385, 0.995, 0.425), fill=INK, line=""),      # nose
]

# ---- the milk bowl: the cat's right place to end up ------------------------
MILK_BOWL, MILK_DARK, MILK_BAND, MILK_WHITE = (
    "#5c6bc0", "#3949ab", "#c5cae9", "#fffdf7")

ART["milkbowl"] = [
    poly([(0.34, 0.84), (0.66, 0.84), (0.71, 0.95), (0.29, 0.95)],
         fill=MILK_DARK),                                       # foot
    poly([(0.08, 0.46), (0.92, 0.46), (0.86, 0.68), (0.72, 0.84),
          (0.50, 0.88), (0.28, 0.84), (0.14, 0.68)],
         fill=MILK_BOWL, smooth=True),                          # bowl
    pline([(0.13, 0.64), (0.30, 0.72), (0.50, 0.75), (0.70, 0.72),
           (0.87, 0.64)], line=MILK_BAND, w=3, smooth=True),    # band
    oval((0.06, 0.36, 0.94, 0.58), fill=MILK_DARK),             # rim
    oval((0.11, 0.395, 0.89, 0.545), fill=MILK_WHITE, line=MILK_BAND, w=1.5),
    poly([(0.60, 0.52), (0.70, 0.52), (0.70, 0.70), (0.65, 0.76),
          (0.60, 0.70)], fill=MILK_WHITE, line="", smooth=True),  # drip
    oval((0.40, 0.16, 0.50, 0.30), fill=MILK_WHITE, line=MILK_DARK, w=1.5),
    oval((0.58, 0.08, 0.65, 0.18), fill=MILK_WHITE, line=MILK_DARK, w=1.5),
    oval((0.28, 0.24, 0.34, 0.32), fill=MILK_WHITE, line=MILK_DARK, w=1.5),
]

ART_NAME_KEY = {k: "name." + k for k in ART}

# *************** DEL 10 - THE FOUR STORIES A MAZE CAN TELL ******************
# hero  = who is walking, and stands on the start square
# goal  = the one right place to end up
# decoys= the wrong places, handed out over the dead ends that branch off the
#         route.  "wall" is the plain dead end - the one the puzzle is named
#         after - and it is in every theme.  The list may be shorter than the
#         number of dead ends used; it is then cycled, so two cats in one maze
#         is normal and not a bug.

THEMES = {
    "dog": dict(hero="dog", goal="kennel",
                decoys=["tap", "cat", "puddle", "wall", "wall"]),
    "mouse": dict(hero="mouse", goal="cheese",
                  decoys=["cat", "trap", "wall", "puddle", "wall"]),
    "bee": dict(hero="bee", goal="flower",
                decoys=["web", "rain", "wall", "puddle", "web"]),
    "penguin": dict(hero="penguin", goal="fish",
                    decoys=["seal", "icehole", "wall", "seal", "icehole"]),
    "rabbit": dict(hero="rabbit", goal="carrot",
                   decoys=["fox", "wall", "puddle", "fox", "wall"]),
    "cat": dict(hero="cat", goal="milkbowl",
                decoys=["dog", "wall", "puddle", "dog", "wall"]),
}

# A LIST, not a tuple: an add-on pack (DEL 21) appends to it, and never
# rewrites it - which is what stops one helper's new story from deleting
# another's.
THEME_ORDER = ["dog", "mouse", "bee", "penguin", "rabbit", "cat"]

# The colouring and jigsaw pictures are filled in by DEL 17; packs append to
# the same list.
PICTURES = []

# *************** DEL 11 - THE MAZE ENGINE (NO TKINTER IN HERE) **************
# Pure logic, so --selftest can hammer it without opening a window.
#
# The maze is PERFECT (a spanning tree): between any two squares there is
# exactly one route.  That is what makes the puzzle fair - there is one right
# way and every other way is a dead end - and it is also what lets the mouse
# glide along a corridor (DEL 13) without the program having to guess which
# route the player meant.

BIT = {"N": 1, "E": 2, "S": 4, "W": 8}
OPP = {"N": "S", "E": "W", "S": "N", "W": "E"}
DELTA = {"N": (0, -1), "E": (1, 0), "S": (0, 1), "W": (-1, 0)}
DIR_KEY = {"N": "dir.up", "E": "dir.right", "S": "dir.down", "W": "dir.left"}

DIFFS = {                       # squares across, squares down, decoys
    "easy":   (9, 7, 3),
    "normal": (15, 11, 5),
    "hard":   (21, 15, 7),
    "giant":  (29, 21, 9),
}
DIFF_ORDER = ("easy", "normal", "hard", "giant")


class Maze:
    """A perfect maze on a w x h grid of squares."""

    def __init__(self, w, h, rng):
        self.w, self.h = int(w), int(h)
        self.cells = [[0] * self.w for _ in range(self.h)]
        self._carve(rng)

    # ---- building ---------------------------------------------------------
    def _carve(self, rng):
        """Randomized Prim - deliberately NOT depth-first.

        Depth-first carving makes long snaking corridors with few junctions.
        Measured over 120 boards of each kind on the medium size (15 x 11):

            depth-first   route 106 squares (64% of the board),
                          11 junctions on the way,  19 dead ends
            Prim          route  36 squares (22% of the board),
                          20 junctions on the way,  54 dead ends

        The depth-first route wanders through most of the board, which is a
        long job of following one corridor.  Prim's grows the maze outward
        from a random frontier instead: a short route with twice as many real
        choices on it, and plenty of short blind alleys to put the cat, the
        water tap and the brick wall in.  That is this puzzle.
        """
        start = (rng.randrange(self.w), rng.randrange(self.h))
        seen = {start}
        frontier = []

        def push(cell):
            for d, (dx, dy) in DELTA.items():
                n = (cell[0] + dx, cell[1] + dy)
                if 0 <= n[0] < self.w and 0 <= n[1] < self.h and n not in seen:
                    frontier.append((cell, d, n))

        push(start)
        while frontier:
            cur, d, nxt = frontier.pop(rng.randrange(len(frontier)))
            if nxt in seen:                  # reached from elsewhere meanwhile
                continue
            self.cells[cur[1]][cur[0]] |= BIT[d]
            self.cells[nxt[1]][nxt[0]] |= BIT[OPP[d]]
            seen.add(nxt)
            push(nxt)

    # ---- asking ----------------------------------------------------------
    def inside(self, cell):
        x, y = cell
        return 0 <= x < self.w and 0 <= y < self.h

    def is_open(self, cell, d):
        x, y = cell
        return bool(self.cells[y][x] & BIT[d])

    def step(self, cell, d):
        """The square in direction d, or None if a wall (or the edge) stops you."""
        if not self.is_open(cell, d):
            return None
        dx, dy = DELTA[d]
        nxt = (cell[0] + dx, cell[1] + dy)
        return nxt if self.inside(nxt) else None

    def neighbours(self, cell):
        out = []
        for d in ("N", "E", "S", "W"):
            n = self.step(cell, d)
            if n:
                out.append(n)
        return out

    def direction(self, a, b):
        dx, dy = b[0] - a[0], b[1] - a[1]
        for d, delta in DELTA.items():
            if delta == (dx, dy):
                return d
        return None

    def connected(self, a, b):
        """True when you can walk straight from a to b - adjacent, no wall."""
        d = self.direction(a, b)
        return bool(d) and self.is_open(a, d)

    def bfs(self, src):
        dist = {src: 0}
        prev = {src: None}
        queue = [src]
        head = 0
        while head < len(queue):
            cur = queue[head]
            head += 1
            for n in self.neighbours(cur):
                if n not in dist:
                    dist[n] = dist[cur] + 1
                    prev[n] = cur
                    queue.append(n)
        return dist, prev

    def route(self, a, b):
        """The one and only route from a to b, a and b included."""
        _, prev = self.bfs(a)
        if b not in prev:
            return []
        out = [b]
        while out[-1] != a:
            out.append(prev[out[-1]])
        out.reverse()
        return out

    def dead_ends(self):
        out = []
        for y in range(self.h):
            for x in range(self.w):
                if bin(self.cells[y][x]).count("1") == 1:
                    out.append((x, y))
        return out


class MazePuzzle:
    """A maze plus the story on top of it: who walks, where to, and the traps."""

    def __init__(self, difficulty="normal", theme=None, seed=None, rng=None):
        if difficulty not in DIFFS:
            difficulty = "normal"
        self.difficulty = difficulty
        w, h, n_decoys = DIFFS[difficulty]
        self.seed = random.randrange(1, 10 ** 9) if seed is None else int(seed)
        rng = rng or random.Random(self.seed)
        self.rng = rng
        self.theme_key = theme if theme in THEMES else rng.choice(THEME_ORDER)
        self.theme = THEMES[self.theme_key]
        self.maze = Maze(w, h, rng)
        self.w, self.h = w, h
        self._place(n_decoys, rng)

    # ---- placing the story ------------------------------------------------
    def _place(self, n_decoys, rng):
        m = self.maze
        ends = m.dead_ends() or [(0, 0)]
        # Where the two ends go.  Picking the two dead ends that are farthest
        # apart IN STEPS (the tree diameter) is the obvious choice and it is
        # the wrong one here: in a Prim maze that pair often sits in the same
        # corner of the board with a long wiggle between them, which leaves
        # two thirds of the page as decoration and puts every wrong turn in
        # the same strip.
        # So the two ends are pinned to OPPOSITE CORNERS first, and only then
        # is the farthest-in-steps dead end picked from the far half.  The
        # route crosses the whole page, and the blind alleys hanging off it -
        # where the cat and the water tap go - are spread over all of it.
        corners = [(0, 0), (self.w - 1, 0), (0, self.h - 1),
                   (self.w - 1, self.h - 1)]
        i = rng.randrange(4)
        corner_a, corner_b = corners[i], corners[3 - i]

        def reach(cell, corner):
            return abs(cell[0] - corner[0]) + abs(cell[1] - corner[1])

        self.start = min(ends, key=lambda e: reach(e, corner_a))
        dist, _ = m.bfs(self.start)
        far_half = [e for e in ends
                    if reach(e, corner_b) < reach(e, corner_a)]
        self.goal = max(far_half or ends, key=lambda e: dist.get(e, -1))
        self.solution = m.route(self.start, self.goal)
        self.on_solution = set(self.solution)

        # Decoys go in dead ends that branch OFF the route, spread along it, so
        # the tempting wrong turn does not always come at the same place.
        index_of = {cell: i for i, cell in enumerate(self.solution)}
        # One BFS from the start, then read every candidate's route out of
        # prev - a Prim maze has a hundred-odd dead ends on the big boards and
        # a BFS each would be a hundred-odd sweeps of the whole grid.
        _, prev_from_start = m.bfs(self.start)
        cands = []
        for e in ends:
            if e in (self.start, self.goal) or e in self.on_solution:
                continue
            r = [e]
            while r[-1] != self.start and prev_from_start.get(r[-1]):
                r.append(prev_from_start[r[-1]])
            r.reverse()
            div = 0
            for cell in r:
                if cell in index_of:
                    div = index_of[cell]
                else:
                    break
            cands.append((div, len(r) - div, e))     # where it branches, how deep
        self.decoys = {}
        if cands:
            n = min(n_decoys, len(cands))
            span = max(1, len(self.solution))
            picked = []
            for k in range(n):
                lo = span * k / float(n)
                hi = span * (k + 1) / float(n)
                bucket = [t for t in cands
                          if lo <= t[0] < hi and t[2] not in picked]
                if not bucket:
                    bucket = [t for t in cands if t[2] not in picked]
                if not bucket:
                    break
                bucket.sort(key=lambda t: -t[1])     # the deepest wrong turn
                picked.append(bucket[0][2])
            art = list(self.theme["decoys"])
            rng.shuffle(art)
            for i, cell in enumerate(picked):
                self.decoys[cell] = art[i % len(art)]

    # ---- what the player's drawing is allowed to do -----------------------
    def ends(self):
        return (self.start, self.goal)

    def other_end(self, cell):
        return self.goal if cell == self.start else self.start

    def is_solved(self, path):
        return (len(path) >= 2 and
                {path[0], path[-1]} == {self.start, self.goal})

    def stars(self, wrong_steps, hint_used):
        """Visible scoring - the same table is drawn in Help (40_games.md)."""
        if hint_used:
            return 1
        length = max(1, len(self.solution) - 1)
        if wrong_steps <= max(2, int(length * 0.15)):
            return 3
        if wrong_steps <= max(6, int(length * 0.60)):
            return 2
        return 1

# *************** DEL 12 - SHARED WIDGETS AND COLOURS ************************
# The look: a cream activity-book page with warm buttons.  Every widget that
# carries text is sized for the LONGEST of the three languages up front, so
# switching language never moves anything (01_CORE, item 6).

PAPER      = "#fffdf6"     # the page
CREAM      = "#fdeecd"     # toolbars
BTN        = "#ffcc80"
BTN_ON     = "#ffb74d"
BTN_OFF    = "#e8e0d0"
TEXTC      = "#3e2723"
DIMC       = "#8d6e63"
WALLC      = "#4e342e"
FEEDBG     = "#fffaf0"
CARDBG     = "#fff6e2"
GOODC      = "#2e7d32"
STARC      = "#fbc02d"

FONT_UI    = ("Segoe UI", 10)
FONT_UI_B  = ("Segoe UI", 10, "bold")
FONT_BIG   = ("Segoe UI", 15, "bold")
FONT_HUGE  = ("Segoe UI", 26, "bold")
FONT_SMALL = ("Segoe UI", 9)
FONT_FEED  = ("Segoe UI", 9)


def tbutton(parent, key, command, extra_keys=(), **kw):
    """A button whose width fits every language it can ever show."""
    w = width_for(key, *extra_keys) + 2
    b = tk.Button(parent, command=command, width=w, font=FONT_UI,
                  bg=BTN, activebackground=BTN_ON, fg=TEXTC, relief="raised",
                  bd=2, cursor="hand2", **kw)
    reg(b, key)
    return b


class KeyedOption:
    """A drop-down whose ITEMS are language keys, not strings.

    tk.OptionMenu shows whatever is in its variable, so the widget is rebuilt
    on a language change while the CHOSEN VALUE (a plain key like "normal")
    stays put.  Width is fixed for all languages, so the toolbar never jumps.
    """

    # A list longer than this is not shown as a tk.Menu: with ~50 pictures the
    # menu is taller than the screen and Tk adds two little scroll triangles
    # that only work by holding the mouse on them - the wheel does nothing.
    # A long list opens as a Listbox popup instead, which the wheel scrolls.
    LONG_LIST = 14

    def __init__(self, parent, items, value, command=None):
        self.items = list(items)              # [(value, text_key), ...]
        self.value = value
        self.command = command
        self.var = tk.StringVar(value="")
        self._pop = None                      # the open popup of a long list
        self.long = len(self.items) > self.LONG_LIST
        width = max(width_for(k) for _, k in self.items) + 2
        self.mb = tk.Menubutton(parent, textvariable=self.var, width=width,
                                font=FONT_UI, bg=BTN, activebackground=BTN_ON,
                                fg=TEXTC, relief="raised", bd=2,
                                indicatoron=True, cursor="hand2")
        self.menu = tk.Menu(self.mb, tearoff=0, font=FONT_UI)
        if self.long:
            for seq in ("<Button-1>", "<space>", "<Return>"):
                self.mb.bind(seq, self._toggle_popup)
        else:
            self.mb["menu"] = self.menu
        self.rebuild()
        on_retranslate(self.rebuild)

    def rebuild(self):
        try:
            if not self.long:
                self.menu.delete(0, "end")
                for val, key in self.items:
                    self.menu.add_command(label=T(key),
                                          command=lambda v=val: self.pick(v))
            self.var.set(self._label(self.value))
        except Exception:
            pass

    # ---- the popup of a long list ------------------------------------------
    def _toggle_popup(self, event=None):
        if self._pop is not None:
            self._close_popup()
        else:
            self._open_popup()
        return "break"

    def _close_popup(self):
        top, self._pop = self._pop, None
        if top is not None:
            try:
                top.grab_release()
            except Exception:
                pass
            try:
                top.destroy()
            except Exception:
                pass

    def _open_popup(self):
        labels = [T(k) for _, k in self.items]
        top = tk.Toplevel(self.mb)
        top.withdraw()
        top.overrideredirect(True)
        top.configure(bg=TEXTC)                     # a 1 pixel outline
        frame = tk.Frame(top, bg=PAPER)
        frame.pack(fill="both", expand=True, padx=1, pady=1)
        rows = min(len(labels), 14)
        sb = tk.Scrollbar(frame, orient="vertical")
        lb = tk.Listbox(frame, font=FONT_UI, height=rows, exportselection=False,
                        width=max(len(s) for s in labels) + 2,
                        activestyle="none", bg=PAPER, fg=TEXTC,
                        selectbackground=BTN_ON, selectforeground=TEXTC,
                        relief="flat", highlightthickness=0, bd=0,
                        yscrollcommand=sb.set)
        sb.configure(command=lb.yview)
        sb.pack(side="right", fill="y")
        lb.pack(side="left", fill="both", expand=True)
        for s in labels:
            lb.insert("end", " " + s)
        current = next((i for i, (v, _) in enumerate(self.items)
                        if v == self.value), 0)
        lb.selection_set(current)
        lb.activate(current)
        lb.see(current)

        # Where it goes: under the button, or above it if the screen is short.
        top.update_idletasks()
        per_row = max(1, lb.winfo_reqheight() // rows)
        mb = self.mb
        below = mb.winfo_rooty() + mb.winfo_height()
        room_below = mb.winfo_screenheight() - below - 50
        room_above = mb.winfo_rooty() - 10
        go_below = rows * per_row <= room_below or room_below >= room_above
        room = room_below if go_below else room_above
        lb.configure(height=max(3, min(rows, room // per_row)))
        top.update_idletasks()
        x = min(mb.winfo_rootx(),
                mb.winfo_screenwidth() - top.winfo_reqwidth() - 4)
        y = below if go_below else mb.winfo_rooty() - top.winfo_reqheight()
        top.geometry("+%d+%d" % (max(0, x), max(0, y)))
        top.deiconify()

        def wheel(e):                               # three lines per notch
            lb.yview_scroll(-3 if e.delta > 0 else 3, "units")
            return "break"

        def choose(index):
            if 0 <= index < len(self.items):
                value = self.items[index][0]
                self._close_popup()
                self.pick(value)

        def hover(e):
            i = lb.nearest(e.y)
            lb.selection_clear(0, "end")
            lb.selection_set(i)
            lb.activate(i)

        def outside(e):                             # a click beside the popup
            if not (top.winfo_rootx() <= e.x_root < top.winfo_rootx() +
                    top.winfo_width() and top.winfo_rooty() <= e.y_root <
                    top.winfo_rooty() + top.winfo_height()):
                self._close_popup()

        for w in (top, frame, lb, sb):
            w.bind("<MouseWheel>", wheel)
        lb.bind("<Motion>", hover)
        lb.bind("<ButtonRelease-1>", lambda e: choose(lb.nearest(e.y)))
        lb.bind("<Return>", lambda e: choose(
            (lb.curselection() or (current,))[0]))
        top.bind("<Button-1>", outside, add="+")
        top.bind("<Escape>", lambda e: self._close_popup())
        self._pop = top
        top.grab_set()                              # modal: grab, focus, Escape
        lb.focus_force()

    def _label(self, value):
        for val, key in self.items:
            if val == value:
                return T(key)
        return ""

    def pick(self, value):
        self.value = value
        self.var.set(self._label(value))
        if self.command:
            self.command(value)

    def set(self, value):
        self.value = value
        self.var.set(self._label(value))

    def pack(self, **kw):
        self.mb.pack(**kw)
        return self

    def grid(self, **kw):
        self.mb.grid(**kw)
        return self


def star_points(cx, cy, r):
    """The ten corners of a five-pointed star."""
    pts = []
    for i in range(10):
        ang = -math.pi / 2 + i * math.pi / 5
        rad = r if i % 2 == 0 else r * 0.45
        pts.extend([cx + rad * math.cos(ang), cy + rad * math.sin(ang)])
    return pts


def draw_stars(canvas, cx, cy, r, count, total=3, tags=()):
    """count filled stars out of total - the visible score (40_games.md)."""
    gap = r * 2.4
    x = cx - gap * (total - 1) / 2.0
    for i in range(total):
        canvas.create_polygon(*star_points(x, cy, r),
                              fill=(STARC if i < count else "#e0d6c0"),
                              outline=WALLC, width=2, tags=tags)
        x += gap


def ask_yes_no(parent, question_key):
    """A modal yes/no.  Escape means no - nothing is thrown away by accident."""
    top = tk.Toplevel(parent)
    top.title(T("ask.title"))
    top.configure(bg=PAPER)
    top.resizable(False, False)
    top.transient(parent)
    answer = {"v": False}
    tk.Label(top, text=T(question_key), bg=PAPER, fg=TEXTC, font=FONT_UI,
             wraplength=380, justify="left").pack(padx=24, pady=(22, 16))
    row = tk.Frame(top, bg=PAPER)
    row.pack(pady=(0, 18))

    def yes():
        answer["v"] = True
        top.destroy()

    tbutton(row, "btn.yes", yes).pack(side="left", padx=8)
    tbutton(row, "btn.no", top.destroy).pack(side="left", padx=8)
    make_modal(top)                      # grab_set, focus_force, Escape
    centre_on(top, parent)
    top.wait_window()
    return answer["v"]


def centre_on(win, parent):
    """Put a dialog over the middle of its parent, never off screen."""
    try:
        win.update_idletasks()
        w, h = win.winfo_width(), win.winfo_height()
        px, py = parent.winfo_rootx(), parent.winfo_rooty()
        pw, ph = parent.winfo_width(), parent.winfo_height()
        x = max(0, px + (pw - w) // 2)
        y = max(0, py + (ph - h) // 3)
        win.geometry("+%d+%d" % (x, y))
    except Exception:
        pass


def lighten(colour, factor=0.45):
    """Mix a #rrggbb colour towards white.  tk colour NAMES cannot be blended,
    so anything that is not a hex triplet is handed back untouched."""
    try:
        c = colour.strip()
        if not (len(c) == 7 and c[0] == "#"):
            return colour
        r, g, b = int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16)
        r = int(r + (255 - r) * factor)
        g = int(g + (255 - g) * factor)
        b = int(b + (255 - b) * factor)
        return "#%02x%02x%02x" % (r, g, b)
    except Exception:
        return colour


def darken(colour, factor=0.30):
    try:
        c = colour.strip()
        if not (len(c) == 7 and c[0] == "#"):
            return colour
        r, g, b = int(c[1:3], 16), int(c[3:5], 16), int(c[5:7], 16)
        f = 1.0 - factor
        return "#%02x%02x%02x" % (int(r * f), int(g * f), int(b * f))
    except Exception:
        return colour

# *************** DEL 13 - THE MAZE VIEW (WHAT THE PLAYER DRAWS ON) **********
# Tracing the path:
#   left button / drag ... walk towards the square under the mouse
#   arrow keys / WASD .... one square at a time
#   right button / drag .. erase back to the square under the mouse
#   DELETE, BACKSPACE .... erase the last step (hold it down - it repeats)
#   Ctrl+DELETE .......... erase the whole path
# The path may be started at EITHER end.  Beginning at the goal and working
# back towards the animal is the easier direction, and the "Begin at" drop-down
# says which end the arrow keys use.
#
# A drag can jump several squares when the mouse moves fast.  The maze is a
# tree, so there is exactly ONE route from the head of the path to the square
# under the mouse: walking it (up to MAX_GLIDE squares) is never a guess.  The
# limit is what keeps a single far-away click from solving half the maze.

MAX_GLIDE = 6

TASK_PIC_W, TASK_PIC_H = 178, 56      # the "hero -> goal" strip above the maze


class MazeView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.puzzle = None
        self.path = []
        self.wrong = 0
        self.hint_on = False
        self.hint_used = False
        self.solved = False
        self.started_at = None
        self.elapsed = 0
        self.cs = 20
        self.ox = self.oy = 0
        self._timers = []
        self._msg = "status.ready"
        self._msg_args = ()
        self._feed_items = []
        self._hero_cell = None     # where the animal ended up after its walk
        self._hero_flip = False
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.new_puzzle(ask=False)

    # ---- building the view ------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row1 = tk.Frame(bar, bg=CREAM)
        row1.pack(side="top", fill="x", padx=8, pady=(6, 2))
        row2 = tk.Frame(bar, bg=CREAM)
        row2.pack(side="top", fill="x", padx=8, pady=(0, 6))

        tbutton(row1, "btn.back", self.app.show_start).pack(side="left")
        tbutton(row1, "btn.new", self.new_puzzle).pack(side="left", padx=(8, 14))

        self._bar_label(row1, "lbl.difficulty")
        self.opt_diff = KeyedOption(
            row1, [(d, "diff." + d) for d in DIFF_ORDER],
            SETTINGS["difficulty"], self.on_difficulty)
        self.opt_diff.pack(side="left", padx=(2, 12))

        self._bar_label(row1, "lbl.theme")
        self.opt_theme = KeyedOption(
            row1, [("random", "theme.random")] +
                  [(t, "theme." + t) for t in THEME_ORDER],
            SETTINGS["theme"], self.on_theme)
        self.opt_theme.pack(side="left", padx=(2, 12))

        self._bar_label(row1, "lbl.begin")
        self.opt_begin = KeyedOption(
            row1, [("start", "begin.start"), ("goal", "begin.goal")],
            SETTINGS["begin_at"], self.on_begin)
        self.opt_begin.pack(side="left", padx=(2, 12))

        self.btn_hint = tbutton(row1, "btn.hint.show", self.toggle_hint,
                                extra_keys=("btn.hint.hide",))
        self.btn_hint.pack(side="left", padx=(0, 8))
        tbutton(row1, "btn.clear", self.clear_path).pack(side="left")

        self.feed_var = tk.BooleanVar(value=bool(SETTINGS["feed"]))
        cb = tk.Checkbutton(row2, variable=self.feed_var, command=self.toggle_feed,
                            bg=CREAM, activebackground=CREAM, fg=TEXTC,
                            selectcolor=PAPER, font=FONT_UI, cursor="hand2",
                            width=width_for("lbl.feed") + 2, anchor="w")
        reg(cb, "lbl.feed")
        cb.pack(side="left")

        tbutton(row2, "btn.about", lambda: show_about(self.app.root)).pack(
            side="right", padx=(6, 0))
        tbutton(row2, "btn.help", lambda: show_help(self.app.root)).pack(
            side="right", padx=6)
        tbutton(row2, "btn.settings",
                lambda: show_settings(self.app.root, self.app)).pack(
            side="right", padx=6)
        tbutton(row2, "btn.stats", lambda: show_stats(self.app.root)).pack(
            side="right", padx=6)

        # The task, twice over: as a picture and as a sentence.  A child who
        # cannot read yet gets the whole job from MOUSE -> CHEESE, and the
        # arrow is what says which of the two is the start and which is the
        # place to reach - the drawings alone would not.
        taskrow = tk.Frame(self, bg=PAPER)
        taskrow.pack(side="top", pady=(6, 2))
        self.task_pic = tk.Canvas(taskrow, width=TASK_PIC_W,
                                  height=TASK_PIC_H, bg=PAPER,
                                  highlightthickness=0)
        self.task_pic.pack(side="left", padx=(0, 16))
        self.task = tk.Label(taskrow, text="", bg=PAPER, fg=TEXTC,
                             font=FONT_BIG, width=54, anchor="w")
        self.task.pack(side="left")

        body = tk.Frame(self, bg=PAPER)
        body.pack(side="top", fill="both", expand=True)

        self.feed_frame = tk.Frame(body, bg=FEEDBG, width=236)
        self.feed_frame.pack_propagate(False)
        lab = tk.Label(self.feed_frame, bg=FEEDBG, fg=DIMC, font=FONT_UI_B,
                       width=width_for("feed.title") + 2, anchor="w")
        reg(lab, "feed.title")
        lab.pack(side="top", anchor="w", padx=10, pady=(10, 4))
        self.feed_list = tk.Listbox(self.feed_frame, bg=FEEDBG, fg=TEXTC,
                                    font=FONT_FEED, borderwidth=0,
                                    highlightthickness=0, activestyle="none",
                                    selectbackground=FEEDBG,
                                    selectforeground=TEXTC)
        self.feed_list.pack(side="top", fill="both", expand=True,
                            padx=10, pady=(0, 10))

        self.canvas = tk.Canvas(body, bg=PAPER, highlightthickness=0,
                                takefocus=1, cursor="pencil")
        self.canvas.pack(side="left", fill="both", expand=True)
        if self.feed_var.get():
            self.show_feed()

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_count = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                  font=FONT_UI, anchor="e",
                                  width=width_for("status.counters") + 2)
        self.lbl_count.pack(side="right", padx=10, pady=5)

        self.canvas.bind("<Configure>", lambda e: self.redraw())
        self.canvas.bind("<Button-1>", self.on_left)
        self.canvas.bind("<B1-Motion>", self.on_left)
        self.canvas.bind("<Button-3>", self.on_right)
        self.canvas.bind("<B3-Motion>", self.on_right)
        on_retranslate(self.retranslate_view)

    def _bar_label(self, parent, key):
        lab = tk.Label(parent, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for(key) + 1, anchor="e")
        reg(lab, key)
        lab.pack(side="left")
        return lab

    # ---- timers (a modal dialog does NOT stop after() - cancel them) ------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- a new puzzle -----------------------------------------------------
    def may_discard(self):
        """Ask before a half-drawn path is thrown away.  Answering no has to
        leave EVERYTHING as it was - including the drop-down that asked."""
        if SETTINGS["confirm_new"] and self.path and not self.solved:
            return ask_yes_no(self.app.root, "ask.new")
        return True

    def new_puzzle(self, ask=True):
        if ask and not self.may_discard():
            return
        self.cancel_timers()
        theme = SETTINGS["theme"]
        self.puzzle = MazePuzzle(SETTINGS["difficulty"],
                                 None if theme == "random" else theme)
        self.path = []
        self.wrong = 0
        self.hint_on = False
        self.hint_used = False
        self.solved = False
        self._hero_cell = None
        self._hero_flip = False
        self.started_at = None
        self.elapsed = 0
        reg(self.btn_hint, "btn.hint.show")
        self._feed_items = []
        self.refill_feed()
        p = self.puzzle
        log("---- new maze: theme=%s size=%dx%d seed=%d solution=%d steps "
            "decoys=%s" % (p.theme_key, p.w, p.h, p.seed,
                           len(p.solution) - 1,
                           ",".join(sorted(p.decoys.values())) or "-"))
        self.feed("feed.new", K("theme." + p.theme_key), p.w, p.h)
        self.set_msg("status.ready")
        self.update_task()
        self.redraw()
        self.tick()

    def update_task(self):
        p = self.puzzle
        self.task.configure(text=cap(T("task.line",
                                       T("name." + p.theme["hero"]),
                                       T("name." + p.theme["goal"]))))
        self.draw_task_pic()

    def draw_task_pic(self):
        """hero -> goal, drawn.  The same pair the sentence talks about."""
        p = self.puzzle
        c = self.task_pic
        c.delete("all")
        s = TASK_PIC_H - 6
        mid = TASK_PIC_H / 2.0
        draw_prims(c, ART[p.theme["hero"]], s / 2.0 + 2, mid, s)
        draw_prims(c, ART[p.theme["goal"]], TASK_PIC_W - s / 2.0 - 2, mid, s)
        c.create_line(s + 8, mid, TASK_PIC_W - s - 8, mid, fill=DIMC,
                      width=max(3, int(s * 0.10)), capstyle="round",
                      arrow="last", arrowshape=(15, 18, 6))

    def retranslate_view(self):
        if self.puzzle:
            self.update_task()
            self.set_msg(self._msg or "status.ready", *self._msg_args)
            self.update_counters()
            self.refill_feed()
            self.redraw()

    # ---- toolbar actions --------------------------------------------------
    def on_difficulty(self, value):
        if not self.may_discard():
            self.opt_diff.set(SETTINGS["difficulty"])     # put it back
            return
        SETTINGS["difficulty"] = value
        save_settings()
        self.new_puzzle(ask=False)

    def on_theme(self, value):
        if not self.may_discard():
            self.opt_theme.set(SETTINGS["theme"])
            return
        SETTINGS["theme"] = value
        save_settings()
        self.new_puzzle(ask=False)

    def on_begin(self, value):
        SETTINGS["begin_at"] = value
        save_settings()

    def toggle_feed(self):
        """40_games.md: the on-screen feed must be switchable WHILE playing."""
        SETTINGS["feed"] = bool(self.feed_var.get())
        save_settings()
        if SETTINGS["feed"]:
            self.show_feed()
        else:
            self.feed_frame.pack_forget()

    def show_feed(self):
        # before=canvas: the canvas expands, so anything packed after it would
        # be squeezed to nothing.
        self.feed_frame.pack(side="right", fill="y", before=self.canvas)

    def toggle_hint(self):
        self.hint_on = not self.hint_on
        if self.hint_on:
            if not self.hint_used:
                self.hint_used = True
                self.feed("feed.hint")
            self.set_msg("status.hinton")
            reg(self.btn_hint, "btn.hint.hide")
        else:
            reg(self.btn_hint, "btn.hint.show")
        self.redraw()

    def clear_path(self):
        if not self.path:
            return
        self.path = []
        self.solved = False
        self._hero_cell = None
        self._hero_flip = False
        self.feed("feed.clear")
        self.set_msg("status.cleared")
        self.redraw()

    # ---- the feed and the status line ------------------------------------
    def feed(self, key, *args):
        # The line is KEPT AS A KEY, not as finished text, so that switching
        # language rewrites the lines already in the panel instead of leaving
        # a Swedish history under a Russian heading.
        log(en(key, *args))                      # the log is always written
        self._feed_items.append((key, args))
        if len(self._feed_items) > 400:
            del self._feed_items[:100]
            self.refill_feed()
            return
        if not SETTINGS["feed"]:
            return
        try:
            self.feed_list.insert("end", T(key, *args))
            self.feed_list.see("end")
        except Exception:
            pass

    def refill_feed(self):
        try:
            self.feed_list.delete(0, "end")
            for key, args in self._feed_items:
                self.feed_list.insert("end", T(key, *args))
            self.feed_list.see("end")
        except Exception:
            pass

    def set_msg(self, key, *args):
        self._msg = key
        self._msg_args = args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def tick(self):
        if self.puzzle and not self.solved:
            if self.started_at:
                self.elapsed = time.time() - self.started_at
            self.update_counters()
            self.after_t(500, self.tick)

    def update_counters(self):
        try:
            self.lbl_count.configure(text=T("status.counters",
                                            max(0, len(self.path) - 1),
                                            self.wrong,
                                            fmt_time(self.elapsed)))
        except Exception:
            pass

    # ---- geometry ---------------------------------------------------------
    def layout(self):
        p = self.puzzle
        cw = max(50, self.canvas.winfo_width())
        ch = max(50, self.canvas.winfo_height())
        margin = 16
        cs = min((cw - 2 * margin) // p.w, (ch - 2 * margin) // p.h)
        cs = max(12, int(cs))
        self.cs = cs
        self.ox = (cw - cs * p.w) // 2
        self.oy = (ch - cs * p.h) // 2
        return cs

    def centre(self, cell):
        return (self.ox + cell[0] * self.cs + self.cs / 2.0,
                self.oy + cell[1] * self.cs + self.cs / 2.0)

    def cell_at(self, px, py):
        p = self.puzzle
        if not p or self.cs <= 0:
            return None
        x = int((px - self.ox) // self.cs)
        y = int((py - self.oy) // self.cs)
        if 0 <= x < p.w and 0 <= y < p.h:
            return (x, y)
        return None

    # ---- drawing ----------------------------------------------------------
    def redraw(self):
        if not self.puzzle:
            return
        c = self.canvas
        c.delete("all")
        p = self.puzzle
        cs = self.layout()
        x0, y0 = self.ox, self.oy
        x1, y1 = x0 + cs * p.w, y0 + cs * p.h
        c.create_rectangle(x0 - 7, y0 - 7, x1 + 7, y1 + 7, fill="#f2e3c0",
                           outline="")
        c.create_rectangle(x0 - 3, y0 - 3, x1 + 3, y1 + 3, fill=PAPER,
                           outline="#e0cfa8")

        if self.hint_on:
            self.draw_line_through(p.solution, lighten(GOODC, 0.35),
                                   max(2, cs // 9), dash=(6, 6))
        self.draw_walls()
        self.draw_path()
        self.draw_icons()
        if self.solved:
            self.draw_banner()

    def draw_walls(self):
        c = self.canvas
        p, cs = self.puzzle, self.cs
        w = max(2, cs // 7) if SETTINGS["thick_walls"] else max(1, cs // 12)
        for y in range(p.h):
            for x in range(p.w):
                px, py = self.ox + x * cs, self.oy + y * cs
                if not p.maze.is_open((x, y), "N"):
                    c.create_line(px, py, px + cs, py, fill=WALLC, width=w,
                                  capstyle="round")
                if not p.maze.is_open((x, y), "W"):
                    c.create_line(px, py, px, py + cs, fill=WALLC, width=w,
                                  capstyle="round")
        c.create_line(self.ox, self.oy + cs * p.h, self.ox + cs * p.w,
                      self.oy + cs * p.h, fill=WALLC, width=w, capstyle="round")
        c.create_line(self.ox + cs * p.w, self.oy, self.ox + cs * p.w,
                      self.oy + cs * p.h, fill=WALLC, width=w, capstyle="round")

    def draw_line_through(self, cells, colour, width, dash=None, tags=()):
        if len(cells) < 2:
            return None
        flat = []
        for cell in cells:
            flat.extend(self.centre(cell))
        kw = dict(fill=colour, width=width, capstyle="round",
                  joinstyle="round", tags=tags)
        if dash:
            kw["dash"] = dash
        return self.canvas.create_line(*flat, **kw)

    def draw_path(self):
        if not self.path:
            return
        cs = self.cs
        colour = GOODC if self.solved else SETTINGS["path_colour"]
        if len(self.path) >= 2:
            self.draw_line_through(self.path, colour, max(3, int(cs * 0.42)),
                                   tags=("path",))
            self.draw_line_through(self.path, lighten(colour, 0.45),
                                   max(1, int(cs * 0.14)), tags=("path",))
        head = self.centre(self.path[-1])
        r = cs * 0.17
        self.canvas.create_oval(head[0] - r, head[1] - r, head[0] + r,
                                head[1] + r, fill=darken(colour, 0.15),
                                outline="", tags=("path",))

    def draw_icons(self):
        p = self.puzzle
        cs = self.cs
        for cell, art_key in p.decoys.items():
            cx, cy = self.centre(cell)
            draw_prims(self.canvas, ART[art_key], cx, cy, cs * 0.88)
        gx, gy = self.centre(p.goal)
        draw_prims(self.canvas, ART[p.theme["goal"]], gx, gy, cs * 0.95)
        # Once the animal has walked home it STAYS home: a later redraw (a
        # language change, a resized window) must not teleport it back to the
        # start square it already left.
        hx, hy = self.centre(self._hero_cell or p.start)
        draw_prims(self.canvas, ART[p.theme["hero"]], hx, hy, cs * 0.95,
                   flip=self._hero_flip, tags=("hero",))

    def draw_banner(self):
        c = self.canvas
        cw = max(50, c.winfo_width())
        stars = self.puzzle.stars(self.wrong, self.hint_used)
        x, y = cw / 2.0, 46
        c.create_rectangle(x - 210, y - 34, x + 210, y + 40, fill="#fff3c4",
                           outline=STARC, width=3)
        c.create_text(x - 120, y, text=T("win.bravo"), fill=GOODC,
                      font=FONT_HUGE)
        draw_stars(c, x + 90, y - 8, 17, stars)
        c.create_text(x + 90, y + 24, text=cap(T("win.line",
                                                 max(0, len(self.path) - 1),
                                                 fmt_time(self.elapsed),
                                                 stars)),
                      fill=TEXTC, font=FONT_SMALL)

    # ---- input ------------------------------------------------------------
    def on_left(self, event):
        self.canvas.focus_set()
        self.walk_towards(self.cell_at(event.x, event.y))

    def on_right(self, event):
        self.canvas.focus_set()
        self.erase_at(self.cell_at(event.x, event.y))

    def handle_key(self, event):
        """Arrow keys and WASD walk; DELETE and BACKSPACE erase."""
        if self.solved:
            return
        sym = (event.keysym or "").lower()
        ctrl = bool(event.state & 0x0004)
        keymap = {"up": "N", "down": "S", "left": "W", "right": "E",
                  "w": "N", "s": "S", "a": "W", "d": "E",
                  "kp_up": "N", "kp_down": "S", "kp_left": "W",
                  "kp_right": "E"}
        if sym in keymap:
            self.walk_dir(keymap[sym])
        elif sym in ("delete", "backspace", "kp_delete"):
            if ctrl:
                self.clear_path()
            else:
                self.erase_last()

    def walk_dir(self, d):
        p = self.puzzle
        if not self.path:
            end = p.start if SETTINGS["begin_at"] == "start" else p.goal
            self.begin_at(end)
        head = self.path[-1]
        nxt = p.maze.step(head, d)
        if nxt is None:
            self.set_msg("status.nothere")
            return
        self.one_step(nxt)
        self.redraw()

    def begin_at(self, cell):
        p = self.puzzle
        self.path = [cell]
        self.started_at = self.started_at or time.time()
        self.feed("feed.begin", K("name." + (p.theme["hero"]
                                             if cell == p.start
                                             else p.theme["goal"])))

    def walk_towards(self, cell):
        """Left button: walk from the head of the path towards this square."""
        p = self.puzzle
        if self.solved or cell is None:
            return
        if not self.path:
            if cell in (p.start, p.goal):
                self.begin_at(cell)
                self.redraw()
            else:
                self.set_msg("status.mustbegin",
                             K("name." + p.theme["hero"]),
                             K("name." + p.theme["goal"]))
            return
        if cell == self.path[-1]:
            return
        if cell in self.path:                      # erase back to it
            i = self.path.index(cell)
            del self.path[i + 1:]
            self.feed("feed.back", max(0, len(self.path) - 1))
            self.redraw()
            return
        route = p.maze.route(self.path[-1], cell)
        if not route or len(route) - 1 > MAX_GLIDE:
            self.set_msg("status.nothere")
            return
        for nxt in route[1:]:
            self.one_step(nxt)
            if self.solved:
                break
        self.redraw()

    def one_step(self, nxt):
        """One legal square further - or one square back if that is what it is."""
        p = self.puzzle
        if len(self.path) >= 2 and nxt == self.path[-2]:
            self.path.pop()
            self.feed("feed.back", max(0, len(self.path) - 1))
            return
        if nxt in self.path:
            i = self.path.index(nxt)
            del self.path[i + 1:]
            return
        if not p.maze.connected(self.path[-1], nxt):
            self.set_msg("status.nothere")
            return
        self.path.append(nxt)
        self.started_at = self.started_at or time.time()
        d = p.maze.direction(self.path[-2], nxt)
        self.feed("feed.step", len(self.path) - 1, K(DIR_KEY[d]))
        if nxt not in p.on_solution:
            self.wrong += 1
        if nxt in p.decoys:
            art_key = p.decoys[nxt]
            self.feed("feed.decoy", K("name." + art_key))
            if art_key == "wall":
                self.set_msg("status.deadend")
            else:
                self.set_msg("status.oops", K("name." + art_key),
                             K("name." + p.theme["goal"]))
        elif len(p.maze.neighbours(nxt)) == 1 and nxt != p.goal \
                and nxt != p.start:
            self.set_msg("status.deadend")
        else:
            self.set_msg("status.ready")
        self.update_counters()
        if p.is_solved(self.path):
            self.on_solved()

    def erase_last(self):
        if not self.path:
            return
        self.path.pop()
        self.solved = False
        self._hero_cell = None
        self._hero_flip = False
        self.feed("feed.back", max(0, len(self.path) - 1))
        self.redraw()

    def erase_at(self, cell):
        """Right button: back to that square, or one step if it is off the path."""
        if not self.path or self.solved:
            return
        if cell is None or cell not in self.path:
            self.erase_last()
            return
        i = self.path.index(cell)
        if i == len(self.path) - 1:
            self.erase_last()
            return
        del self.path[i + 1:]
        self.feed("feed.back", max(0, len(self.path) - 1))
        self.redraw()

    # ---- solved -----------------------------------------------------------
    def on_solved(self):
        p = self.puzzle
        self.solved = True
        if self.started_at:
            self.elapsed = time.time() - self.started_at
        stars = p.stars(self.wrong, self.hint_used)
        steps = max(0, len(self.path) - 1)
        self.feed("feed.solved", steps, fmt_time(self.elapsed), stars)
        log("solved: theme=%s size=%dx%d seed=%d steps=%d shortest=%d wrong=%d "
            "hint=%s time=%s stars=%d"
            % (p.theme_key, p.w, p.h, p.seed, steps, len(p.solution) - 1,
               self.wrong, self.hint_used, fmt_time(self.elapsed), stars))
        record_solved(p.difficulty, self.elapsed, stars)
        self.set_msg("win.line", steps, fmt_time(self.elapsed), stars)
        self.update_counters()
        self.redraw()
        if SETTINGS["animate_win"]:
            self.walk_the_path()

    def walk_the_path(self):
        """The animal walks home along the path the player drew."""
        p = self.puzzle
        route = list(self.path)
        if route and route[0] != p.start:
            route.reverse()
        self._walk_route = route
        self._walk_i = 0
        self._walk_step()

    def _walk_step(self):
        route = getattr(self, "_walk_route", [])
        i = getattr(self, "_walk_i", 0)
        if not self.puzzle or i >= len(route) or not self.solved:
            return
        cell = route[i]
        flip = False
        if i > 0:
            flip = cell[0] < route[i - 1][0]
        cx, cy = self.centre(cell)
        self._hero_cell = cell
        self._hero_flip = flip
        try:
            self.canvas.delete("hero")
            draw_prims(self.canvas, ART[self.puzzle.theme["hero"]], cx, cy,
                       self.cs * 0.95, flip=flip, tags=("hero",))
        except Exception:
            return
        self._walk_i = i + 1
        if self._walk_i < len(route):
            self.after_t(70, self._walk_step)

# *************** DEL 14 - HARDCODED HELP (IN THE PROGRAM, NOT A FILE) *******
# 03_naming_and_language.md: every program has its Help built in, explaining
# what it does and how every function works.  40_games.md adds: show the
# player exactly what earns points - that is the star table below, not just a
# number at the end.  Closes with Escape, like About.

HELP = {
    "en": [
        ("What this is",
         "An activity book for one player. There is no opponent and nothing\n"
         "is timed against you - the clock only runs so you can beat your own\n"
         "best time if you feel like it.\n"
         "Six things to do, chosen on the first page: mazes, colouring, a\n"
         "jigsaw, spot the differences, matching pairs and bead boards."),
        ("The task",
         "The animal standing at the start wants to reach ONE particular\n"
         "place - the kennel, the cheese, the flower, the fish. Every other\n"
         "place is a wrong turn: the cat, the water tap, the puddle, the\n"
         "mousetrap, the spider web, or a plain brick wall at the end of a\n"
         "blind alley.\n"
         "There is exactly one route that goes all the way through."),
        ("Drawing the path",
         "Mouse: click on the animal (or on the goal) to begin, then click or\n"
         "drag along the corridor. You can slide the mouse quickly - the path\n"
         "follows the corridor by itself for up to six squares at a time.\n"
         "Keys: the arrow keys, or W A S D, walk one square at a time.\n"
         "Either end: you may begin at the animal OR at the goal and work\n"
         "backwards. Backwards is easier, because at the goal end there are\n"
         "far fewer ways to go wrong. \"Begin at\" decides which end the arrow\n"
         "keys start from; with the mouse, just click the end you want."),
        ("Erasing",
         "Right mouse button: erases back to the square you are pointing at.\n"
         "Hold it down and drag backwards to rub out a long stretch.\n"
         "Right-click anywhere off the path: erases the last step.\n"
         "DELETE or BACKSPACE: erases the last step - hold the key down and\n"
         "it keeps erasing.\n"
         "Ctrl+DELETE, or the \"Erase all\" button: the whole path goes."),
        ("Show answer",
         "The right route appears as a dotted line. It costs something: a\n"
         "maze solved with the answer showing gives one star, whatever else\n"
         "happens. Press the button again to hide it."),
        ("Stars - what you are scored on",
         "*** three stars   solved with no answer shown, and at most 15% of\n"
         "                  the route's length in wrong steps\n"
         "**  two stars     solved with no answer shown, and at most 60% of\n"
         "                  the route's length in wrong steps\n"
         "*   one star      solved any other way, or with the answer shown\n"
         "\n"
         "A WRONG STEP is one square walked onto that is not on the right\n"
         "route. The counter at the bottom right shows them while you play.\n"
         "Erasing a wrong step does not take it back - the stars are for the\n"
         "whole journey, not for the drawing that is left at the end.\n"
         "\"My results\" keeps the number solved, the stars and the best time\n"
         "for each size."),
        ("The side panel and the log",
         "\"Show what happens\" turns the side panel on and off, at any time,\n"
         "also in the middle of a maze.\n"
         "Whether it is showing or not, everything is written to a log file\n"
         "in Helpfiles\\0---Empty - today's file and yesterday's, no more."),
        ("Settings",
         "Language (Swedish, English, Russian), the crayon colour of the\n"
         "path, thick or thin walls, whether the animal walks the path when\n"
         "the maze is solved, and whether a new maze asks first when you have\n"
         "already drawn something."),
        ("Colouring - filling in",
         "Choose \"Fill in\", pick a crayon from the box, and click a part of\n"
         "the picture: the teeth, an eye, a stone, the lava. The name of the\n"
         "part you are pointing at shows at the bottom right, in whichever\n"
         "language the program is set to.\n"
         "\"Show the colours\" shows the whole picture in its own colours for\n"
         "a couple of seconds, and then gives you your own back."),
        ("Colouring - the crayon",
         "Choose \"Crayon\" and draw with the button held down. Thin, medium\n"
         "or thick. The line is drawn slightly wobbly on purpose, so it looks\n"
         "like wax and not like a computer.\n"
         "\"Rubber\", or the right mouse button at any time, takes away the\n"
         "crayon line it touches - or empties the part it is over.\n"
         "DELETE undoes the last thing, \"Again\" puts it back, and\n"
         "Ctrl+DELETE empties the whole page after asking.\n"
         "\"Save\" puts the picture in Helpfiles\\ActivityBook\\Gallery, as a\n"
         "PNG you can look at and print, and as a small file that keeps the\n"
         "colouring itself."),
        ("Jigsaw",
         "The same pictures, in their own colours, cut into 6, 12, 24 or 48\n"
         "pieces with real tabs and blanks. Drag a piece onto the board and\n"
         "it clicks into place by itself when it is close enough - and then\n"
         "it stays fixed there.\n"
         "Pieces are magnetic towards each other as well: drop a piece close\n"
         "to the one it belongs next to and they snap together exactly and\n"
         "become one. Grab any piece of the group and the whole group comes\n"
         "along, and a group dropped near its place locks onto the board as\n"
         "a whole.\n"
         "The right mouse button sends a piece back to the pile (just that\n"
         "piece - the rest of its group stays together), and DELETE\n"
         "sends back the one under the mouse - the same two keys that erase\n"
         "in the other two activities.\n"
         "\"Faint picture underneath\" puts a pale copy of the finished\n"
         "picture on the board to work from. It is off to begin with."),
        ("Spot the differences",
         "Two pictures that look the same, but are not: five things are\n"
         "different. Click on a difference in EITHER picture. A red ring goes\n"
         "round it in both, and the line at the bottom says what it was - a\n"
         "missing sun, a lava that has turned blue, a stone that has moved,\n"
         "something extra. A click where nothing is different is a miss.\n"
         "Every round is a new mix: the puzzle holds a bigger set of\n"
         "differences, five are picked at random, and the original may be on\n"
         "either side.\n"
         "\"Hint\" makes a blue ring blink round one that is left. \"Show\n"
         "answer\" puts orange rings round all of them.\n"
         "Stars: misses plus two for every hint. 3 or less is three stars, up\n"
         "to 8 is two, more is one. Showing the answer is always one star."),
        ("Matching",
         "A column of pictures on the left and their partners, shuffled, on\n"
         "the right: the dog and its kennel, the mouse and its cheese. Press on\n"
         "one and pull a line to the one it belongs with - or click one, then\n"
         "the other. A right pair stays joined by a coloured line. A wrong\n"
         "pair jumps back and counts as a miss, so what is on the screen is\n"
         "never wrong.\n"
         "Some sets pair an animal with its black SHADOW instead.\n"
         "\"Set\" chooses what to match, \"Pairs\" how many pairs a round has\n"
         "(3 to 6). \"Hint\" makes one right pair blink, \"Show answer\" draws\n"
         "dotted lines for the rest.\n"
         "Stars: misses plus two for every hint. At most half the number of\n"
         "pairs (and at least 1) is three stars, up to the number of pairs\n"
         "plus 2 is two, more is one. Showing the answer is always one star."),
        ("More puzzles and sets",
         "New spot-the-difference puzzles and matching sets arrive as packs: a\n"
         ".json file in Helpfiles\\ActivityBook\\Packs, the same folder as new\n"
         "drawings, maze stories and pictures. The document\n"
         "ActivityBook_instruction_for_HTTP-Claude.md describes the format."),
        ("All the keys",
         "Arrows / W A S D ... one square in a maze\n"
         "DELETE, BACKSPACE ... erase one step, undo one colour, or send one\n"
         "                      jigsaw piece back\n"
         "Ctrl+DELETE ......... erase everything on the page\n"
         "Ctrl+Z / Ctrl+Y ..... undo and redo while colouring\n"
         "Enter, Space ........ the next round, when a spot or matching round\n"
         "                      is finished\n"
         "Escape .............. closes Help, About, Settings and Results"),
    ],
    "sv": [
        ("Vad det h\u00e4r \u00e4r",
         "En pysselbok f\u00f6r en spelare. Ingen motst\u00e5ndare, ingen som tar\n"
         "tiden p\u00e5 dig - klockan g\u00e5r bara s\u00e5 att du kan sl\u00e5 din egen b\u00e4sta\n"
         "tid om du vill.\n"
         "Sex saker att göra, valda på första sidan: labyrinter,\n"
         "målarbilder, pussel, Finn fem fel, Para ihop och pärlplattor."),
        ("Uppgiften",
         "Djuret som st\u00e5r vid starten vill komma till ETT visst st\u00e4lle -\n"
         "hundkojan, osten, blomman, fisken. Alla andra st\u00e4llen \u00e4r fel v\u00e4g:\n"
         "katten, vattenposten, vattenp\u00f6len, musf\u00e4llan, spindeln\u00e4tet eller\n"
         "en tegelv\u00e4gg l\u00e4ngst in i en \u00e5terv\u00e4ndsgr\u00e4nd.\n"
         "Det finns exakt en v\u00e4g som g\u00e5r hela v\u00e4gen fram."),
        ("Rita v\u00e4gen",
         "Mus: klicka p\u00e5 djuret (eller p\u00e5 m\u00e5let) f\u00f6r att b\u00f6rja, klicka eller\n"
         "dra sedan l\u00e4ngs g\u00e5ngen. Du kan dra snabbt - v\u00e4gen f\u00f6ljer g\u00e5ngen\n"
         "sj\u00e4lv, upp till sex rutor i taget.\n"
         "Tangenter: piltangenterna, eller W A S D, g\u00e5r en ruta i taget.\n"
         "B\u00e5da h\u00e5llen: du f\u00e5r b\u00f6rja vid djuret ELLER vid m\u00e5let och g\u00e5 bakl\u00e4nges.\n"
         "Bakl\u00e4nges \u00e4r l\u00e4ttare, f\u00f6r vid m\u00e5let finns det mycket f\u00e4rre s\u00e4tt att\n"
         "g\u00e5 fel. \"B\u00f6rja vid\" best\u00e4mmer vilken \u00e4nde piltangenterna startar i;\n"
         "med musen klickar du bara p\u00e5 den \u00e4nde du vill."),
        ("Radera",
         "H\u00f6ger musknapp: raderar tillbaka till rutan du pekar p\u00e5.\n"
         "H\u00e5ll ner den och dra bak\u00e5t s\u00e5 suddas en l\u00e5ng bit bort.\n"
         "H\u00f6gerklick utanf\u00f6r v\u00e4gen: raderar sista steget.\n"
         "DELETE eller BACKSPACE: raderar sista steget - h\u00e5ll ner tangenten\n"
         "s\u00e5 forts\u00e4tter den radera.\n"
         "Ctrl+DELETE, eller knappen \"Radera allt\": hela v\u00e4gen f\u00f6rsvinner."),
        ("Visa svaret",
         "R\u00e4tt v\u00e4g dyker upp som en streckad linje. Det kostar n\u00e5got: en\n"
         "labyrint som l\u00f6ses med svaret framme ger en stj\u00e4rna, vad som \u00e4n\n"
         "h\u00e4nder i \u00f6vrigt. Tryck p\u00e5 knappen igen s\u00e5 g\u00f6ms det."),
        ("Stj\u00e4rnor - vad du bed\u00f6ms p\u00e5",
         "*** tre stj\u00e4rnor   l\u00f6st utan att svaret visats, och med h\u00f6gst 15 %\n"
         "                   av v\u00e4gens l\u00e4ngd i felsteg\n"
         "**  tv\u00e5 stj\u00e4rnor   l\u00f6st utan att svaret visats, och med h\u00f6gst 60 %\n"
         "                   av v\u00e4gens l\u00e4ngd i felsteg\n"
         "*   en stj\u00e4rna     l\u00f6st p\u00e5 n\u00e5got annat s\u00e4tt, eller med svaret framme\n"
         "\n"
         "Ett FELSTEG \u00e4r en ruta du g\u00e5r in i som inte ligger p\u00e5 r\u00e4tt v\u00e4g.\n"
         "R\u00e4knaren nere till h\u00f6ger visar dem medan du spelar. Att radera ett\n"
         "felsteg tar inte tillbaka det - stj\u00e4rnorna g\u00e4ller hela resan, inte\n"
         "teckningen som blir kvar p\u00e5 slutet.\n"
         "\"Mina resultat\" sparar antal l\u00f6sta, stj\u00e4rnor och b\u00e4sta tid f\u00f6r\n"
         "varje storlek."),
        ("Sidopanelen och loggen",
         "\"Visa vad som h\u00e4nder\" sl\u00e5r p\u00e5 och av sidopanelen, n\u00e4r som helst,\n"
         "ocks\u00e5 mitt i en labyrint.\n"
         "Oavsett om den syns eller inte skrivs allt till en loggfil i\n"
         "Helpfiles\\0---Empty - dagens fil och g\u00e5rdagens, inte fler."),
        ("Inst\u00e4llningar",
         "Spr\u00e5k (svenska, engelska, ryska), kritans f\u00e4rg p\u00e5 v\u00e4gen, tjocka\n"
         "eller tunna v\u00e4ggar, om djuret ska g\u00e5 v\u00e4gen n\u00e4r labyrinten \u00e4r l\u00f6st,\n"
         "och om en ny labyrint ska fr\u00e5ga f\u00f6rst n\u00e4r du redan ritat n\u00e5got."),
        ("M\u00e5larbilder - fylla i",
         "V\u00e4lj \"Fyll i\", ta en krita ur l\u00e5dan och klicka p\u00e5 en del av bilden:\n"
         "t\u00e4nderna, ett \u00f6ga, en sten, lavan. Namnet p\u00e5 delen du pekar p\u00e5 syns\n"
         "nere till h\u00f6ger, p\u00e5 det spr\u00e5k programmet st\u00e5r p\u00e5.\n"
         "\"Visa f\u00e4rgerna\" visar hela bilden i sina egna f\u00e4rger i ett par\n"
         "sekunder, och ger dig sedan tillbaka dina."),
        ("M\u00e5larbilder - kritan",
         "V\u00e4lj \"Rita\" och rita med knappen nertryckt. Tunn, mellan eller\n"
         "tjock. Strecket ritas med flit lite oj\u00e4mnt, s\u00e5 att det ser ut som\n"
         "vax och inte som en dator.\n"
         "\"Sudd\", eller h\u00f6ger musknapp n\u00e4r som helst, tar bort kritstrecket\n"
         "den r\u00f6r vid - eller t\u00f6mmer delen den st\u00e5r p\u00e5.\n"
         "DELETE \u00e5ngrar det sista, \"G\u00f6r om\" s\u00e4tter tillbaka det, och\n"
         "Ctrl+DELETE t\u00f6mmer hela sidan efter att ha fr\u00e5gat.\n"
         "\"Spara bilden\" l\u00e4gger den i Helpfiles\\ActivityBook\\Gallery, b\u00e5de\n"
         "som en PNG att titta p\u00e5 och skriva ut och som en liten fil som\n"
         "sparar sj\u00e4lva f\u00e4rgl\u00e4ggningen."),
        ("Pussel",
         "Samma bilder, i sina egna f\u00e4rger, s\u00f6nderklippta i 6, 12, 24 eller\n"
         "48 bitar med riktiga knoppar och urtag. Dra en bit till br\u00e4det s\u00e5\n"
         "sn\u00e4pper den p\u00e5 plats sj\u00e4lv n\u00e4r den kommer n\u00e4ra nog - och\n"
         "sitter sedan fast.\n"
         "Bitarna \u00e4r ocks\u00e5 magnetiska mot varandra: sl\u00e4pp en bit n\u00e4ra den\n"
         "den ska sitta intill s\u00e5 snäpper de ihop exakt och blir en enhet.\n"
         "Tar du tag i vilken bit som helst i gruppen f\u00f6ljer hela gruppen med,\n"
         "och en grupp som sl\u00e4pps n\u00e4ra sin plats l\u00e5ser sig p\u00e5 br\u00e4det\n"
         "som helhet.\n"
         "H\u00f6ger musknapp skickar tillbaka en bit till h\u00f6gen (bara den biten -\n"
         "resten av gruppen sitter kvar), och DELETE\n"
         "skickar tillbaka den som ligger under musen - samma tv\u00e5 tangenter\n"
         "som raderar i de andra tv\u00e5 delarna.\n"
         "\"Blek bild under\" l\u00e4gger en blek kopia av den f\u00e4rdiga bilden p\u00e5\n"
         "br\u00e4det att g\u00e5 efter. Den \u00e4r av fr\u00e5n b\u00f6rjan."),
        ("Finn fem fel",
         "Två bilder som ser likadana ut, men inte är det: fem saker är olika.\n"
         "Klicka på ett fel i VILKEN bild som helst. En röd ring läggs runt det\n"
         "i båda, och raden längst ner säger vad det var - en sol som saknas,\n"
         "en lava som blivit blå, en sten som flyttat sig, något extra. Ett\n"
         "klick där inget är olika är en miss.\n"
         "Varje omgång är ny: pusslet har en större samling fel, fem väljs på\n"
         "måfå, och originalet kan ligga på vilken sida som helst.\n"
         "\"Ledtråd\" får en blå ring att blinka runt ett som är kvar. \"Visa\n"
         "svaret\" lägger orangea ringar runt alla.\n"
         "Stjärnor: missar plus två för varje ledtråd. 3 eller färre ger tre\n"
         "stjärnor, upp till 8 två, fler en. Att visa svaret ger alltid en\n"
         "stjärna."),
        ("Para ihop",
         "En rad bilder till vänster och deras par, blandade, till höger:\n"
         "hunden och hundkojan, musen och osten. Tryck på en och dra en linje\n"
         "till den den hör ihop med - eller klicka på den ena och sedan på den\n"
         "andra. Ett rätt par blir kvar, ihopkopplat med en färgad linje. Ett\n"
         "fel par hoppar tillbaka och räknas som en miss, så det som syns är\n"
         "aldrig fel.\n"
         "Vissa serier paras ihop med djurets svarta SKUGGA i stället.\n"
         "\"Serie\" väljer vad som ska paras, \"Par\" hur många par en omgång\n"
         "har (3 till 6). \"Ledtråd\" får ett rätt par att blinka, \"Visa\n"
         "svaret\" ritar streckade linjer för resten.\n"
         "Stjärnor: missar plus två för varje ledtråd. Högst hälften av antalet\n"
         "par (minst 1) ger tre stjärnor, upp till antalet par plus 2 två, fler\n"
         "en. Att visa svaret ger alltid en stjärna."),
        ("Fler pussel och serier",
         "Nya Finn fem fel-bilder och Para ihop-serier kommer som paket: en\n"
         ".json-fil i Helpfiles\\ActivityBook\\Packs, samma mapp som nya\n"
         "teckningar, labyrinthistorier och bilder. Dokumentet\n"
         "ActivityBook_instruction_for_HTTP-Claude.md beskriver formatet."),
        ("Alla tangenter",
         "Pilar / W A S D ..... en ruta i en labyrint\n"
         "DELETE, BACKSPACE ... radera ett steg, \u00e5ngra en f\u00e4rg, eller skicka\n"
         "                      tillbaka en pusselbit\n"
         "Ctrl+DELETE ......... radera allt p\u00e5 sidan\n"
         "Ctrl+Z / Ctrl+Y ..... \u00e5ngra och g\u00f6ra om n\u00e4r du m\u00e5lar\n"
         "Enter, Blanksteg .... nästa omgång, när en Finn fem fel- eller\n"
         "                      Para ihop-omgång är klar\n"
         "Escape .............. stänger Hjälp, Om, Inställningar och Resultat"),
    ],
    "ru": [
        ("\u0427\u0442\u043e \u044d\u0442\u043e \u0442\u0430\u043a\u043e\u0435",
         "\u041a\u043d\u0438\u0433\u0430 \u0437\u0430\u043d\u044f\u0442\u0438\u0439 \u0434\u043b\u044f \u043e\u0434\u043d\u043e\u0433\u043e \u0438\u0433\u0440\u043e\u043a\u0430. \u041d\u0435\u0442 \u043d\u0438 \u0441\u043e\u043f\u0435\u0440\u043d\u0438\u043a\u0430, \u043d\u0438\n"
         "\u0441\u043f\u0435\u0448\u043a\u0438 - \u0447\u0430\u0441\u044b \u0438\u0434\u0443\u0442 \u0442\u043e\u043b\u044c\u043a\u043e \u0434\u043b\u044f \u0442\u043e\u0433\u043e, \u0447\u0442\u043e\u0431\u044b \u043c\u043e\u0436\u043d\u043e \u0431\u044b\u043b\u043e\n"
         "\u043f\u043e\u0431\u0438\u0442\u044c \u0441\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0439 \u0440\u0435\u043a\u043e\u0440\u0434, \u0435\u0441\u043b\u0438 \u0437\u0430\u0445\u043e\u0447\u0435\u0442\u0441\u044f.\n"
         "Шесть занятий, выбираются на первой странице: лабиринты,\n"
         "раскраски, пазл, поиск отличий, подбор пар и термомозаика."),
        ("\u0417\u0430\u0434\u0430\u0447\u0430",
         "\u0416\u0438\u0432\u043e\u0442\u043d\u043e\u0435 \u043d\u0430 \u0441\u0442\u0430\u0440\u0442\u0435 \u0445\u043e\u0447\u0435\u0442 \u043f\u043e\u043f\u0430\u0441\u0442\u044c \u0432 \u041e\u0414\u041d\u041e \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0451\u043d\u043d\u043e\u0435\n"
         "\u043c\u0435\u0441\u0442\u043e: \u0432 \u0431\u0443\u0434\u043a\u0443, \u043a \u0441\u044b\u0440\u0443, \u043a \u0446\u0432\u0435\u0442\u043a\u0443, \u043a \u0440\u044b\u0431\u043a\u0435. \u0412\u0441\u0435 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0435\n"
         "\u043c\u0435\u0441\u0442\u0430 - \u043d\u0435\u0432\u0435\u0440\u043d\u044b\u0439 \u043f\u0443\u0442\u044c: \u043a\u043e\u0442, \u043a\u043e\u043b\u043e\u043d\u043a\u0430, \u043b\u0443\u0436\u0430, \u043c\u044b\u0448\u0435\u043b\u043e\u0432\u043a\u0430,\n"
         "\u043f\u0430\u0443\u0442\u0438\u043d\u0430 \u0438\u043b\u0438 \u043a\u0438\u0440\u043f\u0438\u0447\u043d\u0430\u044f \u0441\u0442\u0435\u043d\u0430 \u0432 \u043a\u043e\u043d\u0446\u0435 \u0442\u0443\u043f\u0438\u043a\u0430.\n"
         "\u0421\u043a\u0432\u043e\u0437\u043d\u043e\u0439 \u043f\u0443\u0442\u044c \u0440\u043e\u0432\u043d\u043e \u043e\u0434\u0438\u043d."),
        ("\u041a\u0430\u043a \u0440\u0438\u0441\u043e\u0432\u0430\u0442\u044c \u043f\u0443\u0442\u044c",
         "\u041c\u044b\u0448\u044c: \u043d\u0430\u0436\u043c\u0438 \u043d\u0430 \u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0435 (\u0438\u043b\u0438 \u043d\u0430 \u0446\u0435\u043b\u044c), \u0437\u0430\u0442\u0435\u043c \u0432\u0435\u0434\u0438 \u043f\u043e\n"
         "\u043a\u043e\u0440\u0438\u0434\u043e\u0440\u0443. \u041c\u043e\u0436\u043d\u043e \u0432\u0435\u0441\u0442\u0438 \u0431\u044b\u0441\u0442\u0440\u043e - \u043f\u0443\u0442\u044c \u0441\u0430\u043c \u0438\u0434\u0451\u0442 \u043f\u043e \u043a\u043e\u0440\u0438\u0434\u043e\u0440\u0443,\n"
         "\u0434\u043e \u0448\u0435\u0441\u0442\u0438 \u043a\u043b\u0435\u0442\u043e\u043a \u0437\u0430 \u0440\u0430\u0437.\n"
         "\u041a\u043b\u0430\u0432\u0438\u0448\u0438: \u0441\u0442\u0440\u0435\u043b\u043a\u0438 \u0438\u043b\u0438 W A S D - \u043f\u043e \u043e\u0434\u043d\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0435.\n"
         "\u041b\u044e\u0431\u043e\u0439 \u043a\u043e\u043d\u0435\u0446: \u043c\u043e\u0436\u043d\u043e \u043d\u0430\u0447\u0430\u0442\u044c \u043e\u0442 \u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0433\u043e \u0418\u041b\u0418 \u043e\u0442 \u0446\u0435\u043b\u0438 \u0438 \u0438\u0434\u0442\u0438\n"
         "\u043d\u0430\u0437\u0430\u0434 - \u0442\u0430\u043a \u043b\u0435\u0433\u0447\u0435, \u0443 \u0446\u0435\u043b\u0438 \u043c\u0435\u043d\u044c\u0448\u0435 \u043b\u043e\u0436\u043d\u044b\u0445 \u043f\u043e\u0432\u043e\u0440\u043e\u0442\u043e\u0432.\n"
         "\"\u041d\u0430\u0447\u0430\u0442\u044c \u0441\" \u0437\u0430\u0434\u0430\u0451\u0442, \u043e\u0442\u043a\u0443\u0434\u0430 \u0441\u0442\u0430\u0440\u0442\u0443\u044e\u0442 \u0441\u0442\u0440\u0435\u043b\u043a\u0438."),
        ("\u041a\u0430\u043a \u0441\u0442\u0438\u0440\u0430\u0442\u044c",
         "\u041f\u0440\u0430\u0432\u0430\u044f \u043a\u043d\u043e\u043f\u043a\u0430 \u043c\u044b\u0448\u0438: \u0441\u0442\u0438\u0440\u0430\u0435\u0442 \u043d\u0430\u0437\u0430\u0434 \u0434\u043e \u0442\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0438, \u043d\u0430\n"
         "\u043a\u043e\u0442\u043e\u0440\u0443\u044e \u0442\u044b \u0443\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0448\u044c. \u0414\u0435\u0440\u0436\u0438 \u0435\u0451 \u0438 \u0432\u0435\u0434\u0438 \u043d\u0430\u0437\u0430\u0434 - \u0441\u043e\u0442\u0440\u0451\u0442\u0441\u044f\n"
         "\u0434\u043b\u0438\u043d\u043d\u044b\u0439 \u0443\u0447\u0430\u0441\u0442\u043e\u043a. \u0429\u0435\u043b\u0447\u043e\u043a \u0432\u043d\u0435 \u043f\u0443\u0442\u0438 \u0441\u0442\u0438\u0440\u0430\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0439 \u0448\u0430\u0433.\n"
         "DELETE \u0438\u043b\u0438 BACKSPACE: \u0441\u0442\u0438\u0440\u0430\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0438\u0439 \u0448\u0430\u0433; \u0434\u0435\u0440\u0436\u0438 \u043a\u043b\u0430\u0432\u0438\u0448\u0443 -\n"
         "\u0441\u0442\u0438\u0440\u0430\u043d\u0438\u0435 \u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0430\u0435\u0442\u0441\u044f.\n"
         "Ctrl+DELETE \u0438\u043b\u0438 \u043a\u043d\u043e\u043f\u043a\u0430 \"\u0421\u0442\u0435\u0440\u0435\u0442\u044c \u0432\u0441\u0451\": \u0438\u0441\u0447\u0435\u0437\u0430\u0435\u0442 \u0432\u0435\u0441\u044c \u043f\u0443\u0442\u044c."),
        ("\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u043e\u0442\u0432\u0435\u0442",
         "\u041f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u044b\u0439 \u043f\u0443\u0442\u044c \u043f\u043e\u044f\u0432\u0438\u0442\u0441\u044f \u043f\u0443\u043d\u043a\u0442\u0438\u0440\u043e\u043c. \u042d\u0442\u043e \u043d\u0435 \u0431\u0435\u0441\u043f\u043b\u0430\u0442\u043d\u043e:\n"
         "\u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442, \u0440\u0435\u0448\u0451\u043d\u043d\u044b\u0439 \u0441 \u043f\u043e\u043a\u0430\u0437\u0430\u043d\u043d\u044b\u043c \u043e\u0442\u0432\u0435\u0442\u043e\u043c, \u0434\u0430\u0451\u0442 \u043e\u0434\u043d\u0443 \u0437\u0432\u0435\u0437\u0434\u0443."),
        ("\u0417\u0432\u0451\u0437\u0434\u044b - \u0437\u0430 \u0447\u0442\u043e \u043e\u043d\u0438",
         "*** \u0442\u0440\u0438 \u0437\u0432\u0435\u0437\u0434\u044b   \u0431\u0435\u0437 \u043f\u043e\u043a\u0430\u0437\u0430 \u043e\u0442\u0432\u0435\u0442\u0430 \u0438 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 15 %\n"
         "                   \u0434\u043b\u0438\u043d\u044b \u043f\u0443\u0442\u0438 \u0432 \u043e\u0448\u0438\u0431\u043e\u0447\u043d\u044b\u0445 \u0448\u0430\u0433\u0430\u0445\n"
         "**  \u0434\u0432\u0435 \u0437\u0432\u0435\u0437\u0434\u044b   \u0431\u0435\u0437 \u043f\u043e\u043a\u0430\u0437\u0430 \u043e\u0442\u0432\u0435\u0442\u0430 \u0438 \u043d\u0435 \u0431\u043e\u043b\u0435\u0435 60 %\n"
         "                   \u0434\u043b\u0438\u043d\u044b \u043f\u0443\u0442\u0438 \u0432 \u043e\u0448\u0438\u0431\u043e\u0447\u043d\u044b\u0445 \u0448\u0430\u0433\u0430\u0445\n"
         "*   \u043e\u0434\u043d\u0430 \u0437\u0432\u0435\u0437\u0434\u0430   \u0432\u043e \u0432\u0441\u0435\u0445 \u043e\u0441\u0442\u0430\u043b\u044c\u043d\u044b\u0445 \u0441\u043b\u0443\u0447\u0430\u044f\u0445\n"
         "\n"
         "\u041e\u0428\u0418\u0411\u041e\u0427\u041d\u042b\u0419 \u0428\u0410\u0413 - \u043a\u043b\u0435\u0442\u043a\u0430, \u043a\u043e\u0442\u043e\u0440\u0430\u044f \u043d\u0435 \u043b\u0435\u0436\u0438\u0442 \u043d\u0430 \u0432\u0435\u0440\u043d\u043e\u043c\n"
         "\u043f\u0443\u0442\u0438. \u0421\u0447\u0451\u0442\u0447\u0438\u043a \u0432\u043d\u0438\u0437\u0443 \u0441\u043f\u0440\u0430\u0432\u0430 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0435\u0442 \u0438\u0445 \u043f\u043e \u0445\u043e\u0434\u0443 \u0438\u0433\u0440\u044b.\n"
         "\u0421\u0442\u0451\u0440\u0442\u044b\u0439 \u043e\u0448\u0438\u0431\u043e\u0447\u043d\u044b\u0439 \u0448\u0430\u0433 \u043d\u0435 \u043e\u0442\u043c\u0435\u043d\u044f\u0435\u0442\u0441\u044f: \u0437\u0432\u0451\u0437\u0434\u044b - \u0437\u0430 \u0432\u0435\u0441\u044c\n"
         "\u043f\u0443\u0442\u044c, \u0430 \u043d\u0435 \u0437\u0430 \u0442\u043e, \u0447\u0442\u043e \u043e\u0441\u0442\u0430\u043b\u043e\u0441\u044c \u043d\u0430 \u0440\u0438\u0441\u0443\u043d\u043a\u0435."),
        ("\u041f\u0430\u043d\u0435\u043b\u044c \u0441\u043e\u0431\u044b\u0442\u0438\u0439 \u0438 \u0436\u0443\u0440\u043d\u0430\u043b",
         "\"\u041f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0441\u043e\u0431\u044b\u0442\u0438\u044f\" \u0432\u043a\u043b\u044e\u0447\u0430\u0435\u0442 \u0438 \u0432\u044b\u043a\u043b\u044e\u0447\u0430\u0435\u0442 \u0431\u043e\u043a\u043e\u0432\u0443\u044e \u043f\u0430\u043d\u0435\u043b\u044c\n"
         "\u0432 \u043b\u044e\u0431\u043e\u0439 \u043c\u043e\u043c\u0435\u043d\u0442, \u0434\u0430\u0436\u0435 \u043f\u043e\u0441\u0440\u0435\u0434\u0438 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u0430. \u041d\u0435\u0437\u0430\u0432\u0438\u0441\u0438\u043c\u043e \u043e\u0442\n"
         "\u044d\u0442\u043e\u0433\u043e \u0432\u0441\u0451 \u043f\u0438\u0448\u0435\u0442\u0441\u044f \u0432 \u0436\u0443\u0440\u043d\u0430\u043b \u0432 Helpfiles\\0---Empty -\n"
         "\u0441\u0435\u0433\u043e\u0434\u043d\u044f\u0448\u043d\u0438\u0439 \u0444\u0430\u0439\u043b \u0438 \u0432\u0447\u0435\u0440\u0430\u0448\u043d\u0438\u0439, \u0431\u043e\u043b\u044c\u0448\u0435 \u043d\u0435\u0442."),
        ("\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438",
         "\u042f\u0437\u044b\u043a (\u0448\u0432\u0435\u0434\u0441\u043a\u0438\u0439, \u0430\u043d\u0433\u043b\u0438\u0439\u0441\u043a\u0438\u0439, \u0440\u0443\u0441\u0441\u043a\u0438\u0439), \u0446\u0432\u0435\u0442 \u043c\u0435\u043b\u043a\u0430, \u0442\u043e\u043b\u0441\u0442\u044b\u0435\n"
         "\u0438\u043b\u0438 \u0442\u043e\u043d\u043a\u0438\u0435 \u0441\u0442\u0435\u043d\u044b, \u043f\u0440\u043e\u0439\u0434\u0451\u0442 \u043b\u0438 \u0436\u0438\u0432\u043e\u0442\u043d\u043e\u0435 \u043f\u043e \u043f\u0443\u0442\u0438 \u0432 \u043a\u043e\u043d\u0446\u0435,\n"
         "\u0438 \u0441\u043f\u0440\u0430\u0448\u0438\u0432\u0430\u0442\u044c \u043b\u0438 \u043f\u0435\u0440\u0435\u0434 \u043d\u043e\u0432\u044b\u043c \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u043e\u043c."),
        ("\u0420\u0430\u0441\u043a\u0440\u0430\u0441\u043a\u0438 - \u0437\u0430\u043b\u0438\u0432\u043a\u0430",
         "\u0412\u044b\u0431\u0435\u0440\u0438 \"\u0417\u0430\u043b\u0438\u0432\u043a\u0430\", \u0432\u043e\u0437\u044c\u043c\u0438 \u043c\u0435\u043b\u043e\u043a \u0438\u0437 \u043a\u043e\u0440\u043e\u0431\u043a\u0438 \u0438 \u043d\u0430\u0436\u043c\u0438 \u043d\u0430 \u0447\u0430\u0441\u0442\u044c\n"
         "\u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438: \u0437\u0443\u0431\u044b, \u0433\u043b\u0430\u0437, \u043a\u0430\u043c\u0435\u043d\u044c, \u043b\u0430\u0432\u0443. \u041d\u0430\u0437\u0432\u0430\u043d\u0438\u0435 \u0447\u0430\u0441\u0442\u0438 \u043f\u043e\u0434\n"
         "\u043a\u0443\u0440\u0441\u043e\u0440\u043e\u043c \u0432\u0438\u0434\u043d\u043e \u0432\u043d\u0438\u0437\u0443 \u0441\u043f\u0440\u0430\u0432\u0430.\n"
         "\"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0446\u0432\u0435\u0442\u0430\" \u043d\u0430 \u043f\u0430\u0440\u0443 \u0441\u0435\u043a\u0443\u043d\u0434 \u043f\u043e\u043a\u0430\u0436\u0435\u0442 \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0443 \u0432 \u0435\u0451\n"
         "\u0441\u043e\u0431\u0441\u0442\u0432\u0435\u043d\u043d\u044b\u0445 \u0446\u0432\u0435\u0442\u0430\u0445, \u0430 \u043f\u043e\u0442\u043e\u043c \u0432\u0435\u0440\u043d\u0451\u0442 \u0442\u0432\u043e\u0438."),
        ("\u0420\u0430\u0441\u043a\u0440\u0430\u0441\u043a\u0438 - \u043c\u0435\u043b\u043e\u043a",
         "\u0412\u044b\u0431\u0435\u0440\u0438 \"\u0420\u0438\u0441\u043e\u0432\u0430\u0442\u044c\" \u0438 \u0432\u0435\u0434\u0438 \u0441 \u043d\u0430\u0436\u0430\u0442\u043e\u0439 \u043a\u043d\u043e\u043f\u043a\u043e\u0439. \u0422\u043e\u043d\u043a\u0438\u0439, \u0441\u0440\u0435\u0434\u043d\u0438\u0439\n"
         "\u0438\u043b\u0438 \u0442\u043e\u043b\u0441\u0442\u044b\u0439. \u041b\u0438\u043d\u0438\u044f \u043d\u0430\u0440\u043e\u0447\u043d\u043e \u0447\u0443\u0442\u044c \u043d\u0435\u0440\u043e\u0432\u043d\u0430\u044f - \u043a\u0430\u043a \u0432\u043e\u0441\u043a, \u0430 \u043d\u0435\n"
         "\u043a\u0430\u043a \u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440.\n"
         "\"\u041b\u0430\u0441\u0442\u0438\u043a\", \u0438\u043b\u0438 \u043f\u0440\u0430\u0432\u0430\u044f \u043a\u043d\u043e\u043f\u043a\u0430 \u0432 \u043b\u044e\u0431\u043e\u0439 \u043c\u043e\u043c\u0435\u043d\u0442, \u0443\u0431\u0438\u0440\u0430\u0435\u0442 \u043b\u0438\u043d\u0438\u044e\n"
         "\u0438\u043b\u0438 \u043e\u0447\u0438\u0449\u0430\u0435\u0442 \u0447\u0430\u0441\u0442\u044c \u043f\u043e\u0434 \u043d\u0438\u043c.\n"
         "DELETE \u043e\u0442\u043c\u0435\u043d\u044f\u0435\u0442 \u043f\u043e\u0441\u043b\u0435\u0434\u043d\u0435\u0435, \"\u0412\u0435\u0440\u043d\u0443\u0442\u044c\" \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442, \u0430\n"
         "Ctrl+DELETE \u043e\u0447\u0438\u0449\u0430\u0435\u0442 \u0432\u0441\u044e \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0443 \u043f\u043e\u0441\u043b\u0435 \u0432\u043e\u043f\u0440\u043e\u0441\u0430.\n"
         "\"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c\" \u043a\u043b\u0430\u0434\u0451\u0442 \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0443 \u0432 Helpfiles\\ActivityBook\\Gallery."),
        ("\u041f\u0430\u0437\u043b",
         "\u0422\u0435 \u0436\u0435 \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438, \u0432 \u0441\u0432\u043e\u0438\u0445 \u0446\u0432\u0435\u0442\u0430\u0445, \u0440\u0430\u0437\u0440\u0435\u0437\u0430\u043d\u043d\u044b\u0435 \u043d\u0430 6, 12, 24 \u0438\u043b\u0438 48\n"
         "\u0434\u0435\u0442\u0430\u043b\u0435\u0439 \u0441 \u043d\u0430\u0441\u0442\u043e\u044f\u0449\u0438\u043c\u0438 \u0437\u0430\u043c\u043a\u0430\u043c\u0438. \u041f\u0435\u0440\u0435\u0442\u0430\u0449\u0438 \u0434\u0435\u0442\u0430\u043b\u044c \u043d\u0430 \u043f\u043e\u043b\u0435 -\n"
         "она сама встанет на место, когда окажется рядом, и останется там.\n"
         "Детали притягиваются и друг к другу: брось деталь рядом с соседней - они\n"
         "точно сцепятся и станут одним целым. Возьми любую деталь группы - поедет\n"
         "вся группа, а группа, брошенная у своего места, встаёт на поле целиком.\n"
         "\u041f\u0440\u0430\u0432\u0430\u044f \u043a\u043d\u043e\u043f\u043a\u0430 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u0434\u0435\u0442\u0430\u043b\u044c \u0432 \u043a\u0443\u0447\u0443, DELETE - \u0442\u0443, \u0447\u0442\u043e \u043f\u043e\u0434\n"
         "\u043c\u044b\u0448\u044c\u044e (\u0442\u043e\u043b\u044c\u043a\u043e \u0435\u0451 - \u0433\u0440\u0443\u043f\u043f\u0430 \u043e\u0441\u0442\u0430\u0451\u0442\u0441\u044f).\n"
         "\"\u0411\u043b\u0435\u0434\u043d\u0430\u044f \u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0430 \u0441\u043d\u0438\u0437\u0443\" - \u043f\u043e\u0434\u0441\u043a\u0430\u0437\u043a\u0430 \u043d\u0430 \u043f\u043e\u043b\u0435, \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e\n"
         "\u0432\u044b\u043a\u043b\u044e\u0447\u0435\u043d\u0430."),
        ("Найди отличия",
         "Две картинки выглядят одинаково, но это не так: отличий пять.\n"
         "Нажми на отличие в ЛЮБОЙ из картинок. В обеих появится красный круг,\n"
         "а строка внизу скажет, что это было: пропавшее солнце, лава, ставшая\n"
         "синей, сдвинувшийся камень, что-то лишнее. Нажатие там, где отличий\n"
         "нет, считается промахом.\n"
         "Каждый раунд новый: в задании больше отличий, чем нужно, пять\n"
         "выбираются случайно, а оригинал может быть и справа, и слева.\n"
         "\"Подсказка\" заставляет мигать синий круг вокруг одного из\n"
         "оставшихся. \"Показать ответ\" обводит все оранжевыми кругами.\n"
         "Звёзды: промахи плюс два за каждую подсказку. До 3 - три звезды,\n"
         "до 8 - две, больше - одна. Показанный ответ всегда даёт одну звезду."),
        ("Подбери пару",
         "Слева столбец картинок, справа их пары вперемешку: собака и будка,\n"
         "мышка и сыр. Нажми на одну и протяни линию к той, что ей подходит -\n"
         "или нажми на одну, потом на другую. Верная пара остаётся соединённой\n"
         "цветной линией. Неверная возвращается назад и считается промахом,\n"
         "так что на экране никогда нет ошибки.\n"
         "В некоторых наборах к животному подбирают его чёрную ТЕНЬ.\n"
         "\"Набор\" выбирает, что подбирать, \"Пары\" - сколько пар в раунде\n"
         "(от 3 до 6). \"Подсказка\" заставляет мигать одну верную пару,\n"
         "\"Показать ответ\" рисует пунктиром остальные.\n"
         "Звёзды: промахи плюс два за каждую подсказку. Не больше половины\n"
         "числа пар (но не меньше 1) - три звезды, до числа пар плюс 2 - две,\n"
         "больше - одна. Показанный ответ всегда даёт одну звезду."),
        ("Новые задания и наборы",
         "Новые задания с отличиями и наборы пар приходят пакетами: файл .json\n"
         "в Helpfiles\\ActivityBook\\Packs, в той же папке, что и новые\n"
         "рисунки, истории лабиринтов и картинки. Формат описан в документе\n"
         "ActivityBook_instruction_for_HTTP-Claude.md."),
        ("\u0412\u0441\u0435 \u043a\u043b\u0430\u0432\u0438\u0448\u0438",
         "\u0421\u0442\u0440\u0435\u043b\u043a\u0438 / W A S D .. \u043e\u0434\u043d\u0430 \u043a\u043b\u0435\u0442\u043a\u0430 \u0432 \u043b\u0430\u0431\u0438\u0440\u0438\u043d\u0442\u0435\n"
         "DELETE, BACKSPACE ... \u0441\u0442\u0435\u0440\u0435\u0442\u044c \u0448\u0430\u0433, \u043e\u0442\u043c\u0435\u043d\u0438\u0442\u044c \u0446\u0432\u0435\u0442 \u0438\u043b\u0438 \u0432\u0435\u0440\u043d\u0443\u0442\u044c\n"
         "                      \u0434\u0435\u0442\u0430\u043b\u044c \u043f\u0430\u0437\u043b\u0430\n"
         "Ctrl+DELETE ......... \u0441\u0442\u0435\u0440\u0435\u0442\u044c \u0432\u0441\u0451 \u043d\u0430 \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0435\n"
         "Ctrl+Z / Ctrl+Y ..... \u043e\u0442\u043c\u0435\u043d\u0430 \u0438 \u0432\u043e\u0437\u0432\u0440\u0430\u0442 \u043f\u0440\u0438 \u0440\u0430\u0441\u043a\u0440\u0430\u0448\u0438\u0432\u0430\u043d\u0438\u0438\n"
         "Enter, Пробел ....... следующий раунд, когда раунд поиска\n"
         "                      отличий или подбора пар закончен\n"
         "Escape .............. закрывает любое окно"),
    ],
}


def show_help(root):
    lang = SETTINGS.get("language", "sv")
    blocks = HELP.get(lang) or HELP["en"]
    top = tk.Toplevel(root)
    top.title(T("help.title") + " - " + T("app.title"))
    top.configure(bg=PAPER)
    top.transient(root)
    top.geometry("760x620")

    head = tk.Frame(top, bg=CREAM)
    head.pack(side="top", fill="x")
    tk.Label(head, text=T("help.title"), bg=CREAM, fg=TEXTC,
             font=("Segoe UI", 16, "bold")).pack(side="left", padx=16, pady=10)
    tk.Label(head, text=T("app.tag"), bg=CREAM, fg=DIMC,
             font=FONT_SMALL).pack(side="left", padx=6)

    wrap = tk.Frame(top, bg=PAPER)
    wrap.pack(side="top", fill="both", expand=True, padx=14, pady=12)
    bar = tk.Scrollbar(wrap)
    bar.pack(side="right", fill="y")
    txt = new_text(wrap, bg=PAPER, fg=TEXTC, font=("Consolas", 10), bd=0,
                   wrap="word", yscrollcommand=bar.set, padx=10, pady=8,
                   highlightthickness=0)
    txt.pack(side="left", fill="both", expand=True)
    bar.configure(command=txt.yview)
    txt.tag_configure("h", font=("Segoe UI", 12, "bold"), foreground="#bf360c",
                      spacing1=12, spacing3=4)
    txt.tag_configure("b", font=("Consolas", 10), foreground=TEXTC,
                      spacing3=8, lmargin1=8, lmargin2=8)
    for heading, body in blocks:
        txt.insert("end", heading + "\n", "h")
        txt.insert("end", body + "\n", "b")
    txt.configure(state="disabled")

    tbutton(top, "btn.close", top.destroy).pack(side="bottom", pady=(0, 14))
    make_modal(top)
    centre_on(top, root)
    return top

# *************** DEL 15 - ABOUT (MY USUAL ABOUT: DESIGNER, DOCS, GIFTS) ******
# 30_about_dialog.md, NOT 40_games.md: Lars asked for his usual About here
# (2026-09-30) because the drawings, the stories and the design are his own -
# there is no outside designer to credit instead.  Creator line, documentation
# link and the gift links all sit below the text.  Links go through open_url()
# (DEL 05b), never webbrowser directly.

ABOUT_TEXT = {
    "en": ("An activity book, not a contest.\n\n"
           "Six things to do: mazes, colouring, a jigsaw, spot the\n"
           "differences, matching pairs and bead boards.\n\n"
           "They are classic pen-and-paper and cardboard forms. The drawings,\n"
           "the stories, the pictures and the code were all made for this\n"
           "program.\n\n"
           "Swedish, English and Russian."),
    "sv": ("En pysselbok, inte en tävling.\n\n"
           "Sex saker att göra: labyrinter, målarbilder, pussel, Finn fem fel,\n"
           "Para ihop och pärlplattor.\n\n"
           "Klassiska former på papper och kartong. Teckningarna,\n"
           "berättelserna, bilderna och koden är gjorda för det här\n"
           "programmet.\n\n"
           "Svenska, engelska och ryska."),
    "ru": ("Книга занятий, а не соревнование.\n\n"
           "Шесть занятий: лабиринты, раскраски, пазл, поиск отличий,\n"
           "подбор пар и термомозаика.\n\n"
           "Классические забавы на бумаге и картоне. Рисунки, истории,\n"
           "картинки и код сделаны для этой программы.\n\n"
           "Шведский, английский и русский."),
}


DOC_URL     = ("https://docs.google.com/document/d/"
               "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing")
REVOLUT_URL = "https://revolut.me/lars72oeh"
PAYPAL_URL  = "https://paypal.me/issusbarn"
WISE_URL    = "https://wise.com/pay/me/larsdenniso"
LINK_COLOR  = "#1a6fb0"
LINK_HOVER  = "#4a97d6"


def _about_link(parent, text, url, **pack):
    lbl = tk.Label(parent, text=text, bg=parent.cget("bg"), fg=LINK_COLOR,
                   font=("Segoe UI", 9, "underline"), cursor="hand2")
    lbl.pack(**pack)
    lbl.bind("<Button-1>", lambda e: open_url(url))
    lbl.bind("<Enter>", lambda e: lbl.configure(fg=LINK_HOVER))
    lbl.bind("<Leave>", lambda e: lbl.configure(fg=LINK_COLOR))
    return lbl


def show_about(root):
    top = tk.Toplevel(root)
    top.title(T("about.title") + " - " + T("app.title"))
    top.configure(bg=PAPER)
    top.resizable(False, False)
    top.transient(root)

    head = tk.Canvas(top, width=440, height=120, bg=CREAM,
                     highlightthickness=0)
    head.pack(side="top", fill="x")
    draw_prims(head, ART["dog"], 74, 62, 84)
    draw_prims(head, ART["kennel"], 372, 62, 76)
    head.create_text(224, 48, text=T("app.title"), fill=TEXTC,
                     font=("Segoe UI", 19, "bold"))
    head.create_text(224, 78, text=T("app.tag"), fill=DIMC,
                     font=("Segoe UI", 8, "italic"), width=210,
                     justify="center")

    tk.Label(top, text=ABOUT_TEXT.get(SETTINGS.get("language", "sv"),
                                      ABOUT_TEXT["en"]),
             bg=PAPER, fg=TEXTC, font=FONT_UI, justify="left").pack(
        padx=26, pady=(18, 10))
    tk.Frame(top, bg="#e0cfa8", height=1).pack(fill="x", padx=22)

    # Designer, documentation and gifts: my usual About (30_about_dialog.md).
    # These are my own designs, so unlike a published game they carry my name.
    tk.Label(top, text=T("about.by") + '  Lars "Issu" Olsson', bg=PAPER,
             fg=TEXTC, font=FONT_UI_B).pack(pady=(14, 0))
    _about_link(top, "\U0001F4C4  " + T("about.doc"), DOC_URL, pady=(6, 2))
    tk.Frame(top, bg="#e0cfa8", height=1).pack(fill="x", padx=22,
                                               pady=(12, 0))
    tk.Label(top, text="\u2615  " + T("about.gift"), bg=PAPER, fg=DIMC,
             font=("Segoe UI", 8, "italic"), wraplength=300,
             justify="center").pack(pady=(10, 6))
    box = tk.Frame(top, bg=CREAM, padx=16, pady=10)
    box.pack(fill="x", padx=22, pady=(0, 6))
    for text, url in (("Revolut", REVOLUT_URL), ("PayPal", PAYPAL_URL),
                      ("Wise", WISE_URL)):
        _about_link(box, text, url, pady=1)

    tk.Label(top, text=PROGRAM_NAME, bg=PAPER, fg=DIMC,
             font=FONT_SMALL).pack(pady=(4, 0))
    tbutton(top, "btn.close", top.destroy).pack(pady=(10, 18))
    make_modal(top)
    centre_on(top, root)
    return top


# *************** DEL 16 - SETTINGS AND RESULTS ******************************

CRAYONS = ["#ef5350", "#fb8c00", "#fdd835", "#43a047", "#1e88e5", "#8e24aa",
           "#6d4c41", "#37474f"]


def show_settings(root, app):
    top = tk.Toplevel(root)
    top.title(T("set.title") + " - " + T("app.title"))
    top.configure(bg=PAPER)
    top.resizable(False, False)
    top.transient(root)

    lang_var = tk.StringVar(value=SETTINGS.get("language", "sv"))
    colour_var = tk.StringVar(value=SETTINGS.get("path_colour", "#ef5350"))
    thick_var = tk.BooleanVar(value=bool(SETTINGS["thick_walls"]))
    anim_var = tk.BooleanVar(value=bool(SETTINGS["animate_win"]))
    conf_var = tk.BooleanVar(value=bool(SETTINGS["confirm_new"]))
    feed_var = tk.BooleanVar(value=bool(SETTINGS["feed"]))

    body = tk.Frame(top, bg=PAPER)
    body.pack(padx=26, pady=20)

    lab = tk.Label(body, bg=PAPER, fg=TEXTC, font=FONT_UI_B, anchor="w",
                   width=width_for("set.language") + 2)
    reg(lab, "set.language")
    lab.grid(row=0, column=0, sticky="w", pady=(0, 2))
    langrow = tk.Frame(body, bg=PAPER)
    langrow.grid(row=1, column=0, sticky="w", pady=(0, 14))
    for code in LANGS:
        tk.Radiobutton(langrow, text=LANG_NAMES[code], value=code,
                       variable=lang_var, bg=PAPER, activebackground=PAPER,
                       fg=TEXTC, selectcolor=CREAM, font=FONT_UI,
                       cursor="hand2", width=10, anchor="w").pack(side="left")

    lab = tk.Label(body, bg=PAPER, fg=TEXTC, font=FONT_UI_B, anchor="w",
                   width=width_for("set.pathcolour") + 2)
    reg(lab, "set.pathcolour")
    lab.grid(row=2, column=0, sticky="w", pady=(0, 2))
    crow = tk.Frame(body, bg=PAPER)
    crow.grid(row=3, column=0, sticky="w", pady=(0, 14))
    swatches = {}

    def pick_colour(c):
        colour_var.set(c)
        for col, btn in swatches.items():
            btn.configure(relief=("sunken" if col == c else "raised"),
                          bd=(4 if col == c else 2))

    for c in CRAYONS:
        b = tk.Button(crow, bg=c, activebackground=c, width=3, height=1,
                      relief="raised", bd=2, cursor="hand2",
                      command=lambda cc=c: pick_colour(cc))
        b.pack(side="left", padx=3)
        swatches[c] = b
    pick_colour(colour_var.get())

    def check(row, key, var):
        cb = tk.Checkbutton(body, variable=var, bg=PAPER, activebackground=PAPER,
                            fg=TEXTC, selectcolor=CREAM, font=FONT_UI,
                            cursor="hand2", anchor="w",
                            width=width_for(key) + 2)
        reg(cb, key)
        cb.grid(row=row, column=0, sticky="w")
        return cb

    check(4, "lbl.feed", feed_var)
    check(5, "set.thickwalls", thick_var)
    check(6, "set.animate", anim_var)
    check(7, "set.confirm", conf_var)

    # Where everything lives, so it can be found (and copied) without hunting.
    def where(row, key, path, folder):
        lab = tk.Label(body, bg=PAPER, fg=DIMC, font=FONT_UI, anchor="w",
                       width=width_for(key) + 2)
        reg(lab, key)
        lab.grid(row=row, column=0, sticky="w", pady=(14, 2))
        line = tk.Frame(body, bg=PAPER)
        line.grid(row=row + 1, column=0, sticky="w")
        e = new_entry(line, width=52, font=FONT_UI, relief="sunken", bd=1,
                      bg=CREAM, fg=TEXTC, readonlybackground=CREAM)
        e.insert(0, path)
        e.configure(state="readonly")
        e.xview_moveto(1.0)             # the END (the file name) is what counts
        e.pack(side="left", padx=(0, 8))
        tbutton(line, "set.showfolder",
                lambda: _show_folder(folder)).pack(side="left")

    def _show_folder(folder):
        try:
            os.makedirs(folder, exist_ok=True)
            open_path(folder)
        except Exception as exc:
            log("settings: could not open %s: %s" % (folder, exc))

    where(8, "set.where", settings_path(), PROGRAM_HF_DIR)
    where(10, "set.packs", PACKS_DIR, PACKS_DIR)

    def save():
        SETTINGS["language"] = lang_var.get()
        SETTINGS["path_colour"] = colour_var.get()
        SETTINGS["thick_walls"] = bool(thick_var.get())
        SETTINGS["animate_win"] = bool(anim_var.get())
        SETTINGS["confirm_new"] = bool(conf_var.get())
        SETTINGS["feed"] = bool(feed_var.get())
        save_settings()
        log("settings: %s" % json.dumps(SETTINGS, sort_keys=True))
        top.destroy()
        app.apply_settings()

    row = tk.Frame(top, bg=PAPER)
    row.pack(pady=(0, 18))
    tbutton(row, "btn.save", save).pack(side="left", padx=8)
    tbutton(row, "btn.cancel", top.destroy).pack(side="left", padx=8)
    make_modal(top)
    centre_on(top, root)
    return top


def _stats_rows():
    """(stats key, the text keys that make its label): mazes by size, then
    the other activities."""
    rows = [(d, ("mode.maze", "diff." + d)) for d in DIFF_ORDER]
    rows.append(("spot", ("mode.spot",)))
    rows.append(("match", ("mode.match",)))
    return rows


def show_stats(root):
    top = tk.Toplevel(root)
    top.title(T("stats.title") + " - " + T("app.title"))
    top.configure(bg=PAPER)
    top.resizable(False, False)
    top.transient(root)

    tk.Label(top, text=T("stats.title"), bg=PAPER, fg=TEXTC,
             font=("Segoe UI", 15, "bold")).pack(padx=30, pady=(18, 10))

    rows = _stats_rows()
    # the first column is as wide as the longest label in ANY language
    first_w = max(width_for("stats.what"),
                  max(len(" - ".join(TXT[k][i] for k in keys))
                      for _, keys in rows for i in range(3))) + 3
    heads = ("stats.what", "stats.solved", "stats.stars", "stats.best")
    widths = [first_w] + [width_for(k) + 3 for k in heads[1:]]
    grid = tk.Frame(top, bg=PAPER)
    grid.pack(padx=30, pady=(0, 6))
    for col, key in enumerate(heads):
        tk.Label(grid, text=T(key), bg=PAPER, fg=DIMC, font=FONT_UI_B,
                 width=widths[col],
                 anchor=("w" if col == 0 else "e")).grid(row=0, column=col,
                                                         padx=4, pady=(0, 4))
    any_row = False
    tot_solved = tot_stars = 0
    for i, (skey, keys) in enumerate(rows):
        row = STATS.get(skey) or {}
        solved = int(row.get("solved", 0) or 0)
        stars = int(row.get("stars", 0) or 0)
        best = int(row.get("best_time", 0) or 0)
        tot_solved += solved
        tot_stars += stars
        if solved:
            any_row = True
        for col, val in enumerate((" - ".join(T(k) for k in keys),
                                   str(solved), str(stars),
                                   fmt_time(best) if best else "-")):
            tk.Label(grid, text=val, bg=PAPER, fg=TEXTC, font=FONT_UI,
                     width=widths[col],
                     anchor=("w" if col == 0 else "e")).grid(
                row=1 + i, column=col, padx=4)
    sep = tk.Frame(grid, bg="#e0cfa8", height=1)
    sep.grid(row=1 + len(rows), column=0, columnspan=4, sticky="ew", pady=4)
    for col, val in enumerate((T("stats.total"), str(tot_solved),
                               str(tot_stars), "")):
        tk.Label(grid, text=val, bg=PAPER, fg=TEXTC, font=FONT_UI_B,
                 width=widths[col],
                 anchor=("w" if col == 0 else "e")).grid(
            row=2 + len(rows), column=col, padx=4)

    if not any_row:
        tk.Label(top, text=T("stats.none"), bg=PAPER, fg=DIMC,
                 font=FONT_SMALL).pack(pady=(6, 0))
    tbutton(top, "btn.close", top.destroy).pack(pady=(14, 18))
    make_modal(top)
    centre_on(top, root)
    return top

# *************** DEL 17 - THE PICTURES (COLOURING AND JIGSAW SHARE THEM) ****
# A picture is a scene in its own design box (1000 x 700 here), drawn with the
# same primitives as everything else (DEL 08) but in scene coordinates.
#
# It is cut into NAMED PARTS.  A part is one thing a child would point at -
# the teeth, an eye, a stone, the lava - and it carries:
#
#   id        a short key, unique inside the picture
#   label     its name in the three languages, shown while hovering over it
#   hint      its natural colour: what "Show the colours" peeks at, and what
#             the jigsaw picture is built from
#   fillable  True: clicking it fills it.  False: it is only a detail line
#             drawn on top, like a whisker or a crack in a stone.
#
# A fillable part starts WHITE, like a page in a colouring book, and every
# poly/oval in it takes the colour it is given - so a part must be one thing,
# not a thing plus its eye.  Put the eye in its own part.
#
# Part order is back to front: sky first, then the ground, then what stands
# on it.  That is also the order a child colours in.


def part(pid, prims, label, hint, fillable=True):
    return dict(id=pid, prims=prims, label=label, hint=hint,
                fillable=fillable)


def picture(key, name, w, h, parts):
    return dict(key=key, name=name, w=w, h=h, parts=parts)


# ---- 1: dinosaurs in front of the volcano ---------------------------------
DINOS = picture(
    "dinos",
    ("Dinosaurs at the volcano", "Dinosaurier vid vulkanen",
     "Динозавры у вулкана"),
    1000, 700,
    [
        part("sky", [poly([(0, 0), (1000, 0), (1000, 470), (0, 470)], w=0)],
             ("the sky", "himlen", "небо"), "#b3e5fc"),
        part("sun", [oval((70, 40, 210, 180), w=3)],
             ("the sun", "solen", "солнце"),
             "#ffd54f"),
        part("cloud", [oval((770, 60, 880, 128), w=3),
                       oval((830, 34, 960, 122), w=3),
                       oval((900, 66, 990, 128), w=3)],
             ("the cloud", "molnet", "облако"),
             "#ffffff"),
        part("volcano", [poly([(330, 480), (560, 130), (690, 130), (900, 480)],
                              w=3)],
             ("the volcano", "vulkanen", "вулкан"),
             "#8d6e63"),
        part("lava", [poly([(556, 132), (600, 96), (640, 130), (694, 128),
                            (676, 190), (700, 250), (660, 300), (668, 210),
                            (628, 176), (596, 240), (570, 190)], w=3,
                           smooth=True)],
             ("the lava", "lavan", "лава"), "#ff7043"),
        part("smoke", [oval((548, 30, 668, 106), w=3),
                       oval((612, 2, 716, 74), w=3)],
             ("the smoke", "röken", "дым"), "#cfd8dc"),
        part("ground", [poly([(0, 470), (1000, 470), (1000, 700), (0, 700)],
                             w=0)],
             ("the ground", "marken", "земля"),
             "#c5a86b"),
        part("hills", [poly([(0, 470), (120, 400), (250, 470)], w=3),
                       poly([(880, 470), (960, 415), (1000, 470)], w=3)],
             ("the hills", "kullarna", "холмы"),
             "#a1887f"),

        # the long-necked one, on the left, in profile facing right
        part("bronto_tail", [poly([(60, 430), (20, 380), (70, 400),
                                   (130, 420)], w=3, smooth=True)],
             ("the tail", "svansen", "хвост"),
             "#81c784"),
        part("bronto_legs", [poly([(126, 410), (178, 410), (184, 545),
                                   (196, 566), (128, 566), (136, 540)], w=3),
                             poly([(216, 410), (268, 410), (274, 545),
                                   (286, 566), (218, 566), (226, 540)], w=3)],
             ("the legs", "benen", "ноги"), "#66bb6a"),
        part("bronto", [poly([(90, 430), (130, 360), (220, 340), (290, 370),
                              (330, 320), (340, 240), (330, 170), (360, 140),
                              (400, 160), (392, 250), (372, 340), (330, 420),
                              (250, 450), (150, 455)], w=3, smooth=True)],
             ("the long-neck", "långhalsen",
              "длинная шея"),
             "#81c784"),
        part("bronto_spots", [oval((150, 370, 200, 410), w=2),
                              oval((215, 385, 260, 420), w=2),
                              oval((170, 415, 210, 445), w=2)],
             ("the spots", "plättarna",
              "пятнышки"), "#4caf50"),
        part("bronto_eye", [oval((362, 158, 380, 176), w=2)],
             ("the eye", "ögat", "глаз"), "#3e2723"),

        # the toothy one: standing on two legs, in profile facing LEFT, with
        # the tail out to the right for balance - the pose is what says
        # "dinosaur" before any colour goes on.
        part("trex_tail", [poly([(846, 330), (920, 312), (988, 296),
                                 (1000, 340), (930, 372), (858, 392)], w=3,
                                smooth=True)],
             ("the tail", "svansen", "хвост"),
             "#e57373"),
        part("trex_farleg", [poly([(806, 372), (862, 380), (858, 456),
                                   (838, 520), (860, 544), (860, 558),
                                   (788, 558), (800, 528), (820, 460),
                                   (800, 412)], w=3)],
             ("the leg behind", "benet bakom",
              "дальняя нога"),
             "#e57373"),
        part("trex", [poly([(694, 332), (700, 290), (678, 258), (702, 248),
                            (732, 276), (762, 266), (812, 272), (856, 304),
                            (866, 352), (840, 396), (780, 408), (722, 392)],
                           w=3, smooth=True)],
             ("the big one", "den stora", "большой"),
             "#ef9a9a"),
        part("trex_leg", [poly([(756, 364), (820, 372), (816, 458),
                                (792, 524), (812, 546), (812, 560),
                                (722, 560), (738, 528), (762, 462),
                                (748, 404)], w=3)],
             ("the leg", "benet", "нога"), "#ef9a9a"),
        part("trex_arm", [poly([(714, 316), (686, 348), (710, 360),
                                (734, 338)], w=3, smooth=True)],
             ("the little arm", "den lilla armen",
              "маленькая лапа"),
             "#e57373"),
        part("trex_head", [poly([(700, 246), (676, 206), (612, 192),
                                 (556, 208), (548, 244), (566, 262),
                                 (640, 268), (692, 278)], w=3, smooth=True)],
             ("the head", "huvudet",
              "голова"), "#ef9a9a"),
        part("trex_jaw", [poly([(566, 274), (624, 290), (688, 296),
                                (694, 278), (630, 272), (568, 258)], w=3,
                               smooth=True)],
             ("the jaw", "käken", "челюсть"),
             "#e57373"),
        part("trex_teeth", [poly([(572, 262), (586, 282), (600, 264),
                                  (616, 286), (632, 266), (650, 288),
                                  (666, 268), (684, 288), (692, 272),
                                  (688, 262), (572, 250)], w=2)],
             ("the teeth", "tänderna", "зубы"),
             "#ffffff"),
        part("trex_eye", [oval((628, 208, 650, 230), w=2)],
             ("the eye", "ögat", "глаз"), "#3e2723"),

        part("stone1", [oval((300, 590, 420, 660), w=3)],
             ("a stone", "en sten", "камень"),
             "#9e9e9e"),
        part("stone2", [oval((470, 620, 560, 675), w=3)],
             ("a stone", "en sten", "камень"),
             "#bdbdbd"),
        part("stone3", [oval((610, 600, 700, 655), w=3)],
             ("a stone", "en sten", "камень"),
             "#8d8d8d"),
        part("fern", [poly([(128, 676), (140, 596), (152, 676)], w=3),
                      poly([(140, 606), (60, 566), (74, 596), (126, 632)],
                           w=3, smooth=True),
                      poly([(140, 600), (86, 512), (108, 508), (140, 566)],
                           w=3, smooth=True),
                      poly([(142, 606), (222, 566), (208, 596), (156, 632)],
                           w=3, smooth=True),
                      poly([(142, 600), (196, 512), (174, 508), (142, 566)],
                           w=3, smooth=True)],
             ("the fern", "ormbunken",
              "папоротник"),
             "#43a047"),
        part("egg", [oval((830, 600, 920, 680), w=3)],
             ("the egg", "ägget", "яйцо"), "#fff3c4"),
        part("egg_dots", [oval((848, 620, 868, 640), w=2),
                          oval((884, 640, 902, 658), w=2)],
             ("the spots", "plättarna",
              "пятнышки"), "#a1887f"),
    ])


# ---- 2: under the sea -----------------------------------------------------
SEA = picture(
    "sea",
    ("Under the sea", "Under havet",
     "Под водой"),
    1000, 700,
    [
        part("water", [poly([(0, 0), (1000, 0), (1000, 620), (0, 620)], w=0)],
             ("the water", "vattnet", "вода"), "#81d4fa"),
        part("sand", [poly([(0, 620), (140, 596), (360, 626), (600, 600),
                            (820, 628), (1000, 604), (1000, 700), (0, 700)],
                           w=3, smooth=True)],
             ("the sand", "sanden", "песок"),
             "#ffe0b2"),
        part("seaweed1", [poly([(120, 660), (96, 560), (128, 470), (96, 390),
                                (140, 470), (150, 560), (164, 660)], w=3,
                               smooth=True)],
             ("the seaweed", "sångräset",
              "водоросли"),
             "#43a047"),
        part("seaweed2", [poly([(880, 664), (856, 570), (892, 500),
                                (866, 430), (910, 505), (916, 580),
                                (924, 664)], w=3, smooth=True)],
             ("the seaweed", "sångräset",
              "водоросли"),
             "#2e7d32"),
        part("rock", [poly([(600, 660), (640, 604), (700, 580), (770, 612),
                            (800, 662)], w=3, smooth=True)],
             ("the rock", "stenen", "камень"),
             "#90a4ae"),

        # the whale, in profile facing left
        part("whale_tail", [poly([(858, 300), (960, 226), (952, 300),
                                  (1000, 356), (900, 348)], w=3,
                                 smooth=True)],
             ("the tail", "stjärten",
              "хвост"), "#5c6bc0"),
        part("whale", [poly([(300, 300), (380, 228), (540, 208), (700, 232),
                             (840, 288), (872, 330), (830, 388), (680, 428),
                             (500, 428), (360, 392), (296, 342)], w=3,
                            smooth=True)],
             ("the whale", "valen", "кит"), "#7986cb"),
        part("whale_belly", [poly([(326, 348), (470, 414), (680, 416),
                                   (826, 366), (812, 420), (656, 468),
                                   (462, 464), (322, 400)], w=3,
                                  smooth=True)],
             ("the belly", "magen", "живот"),
             "#e8eaf6"),
        part("whale_fin", [poly([(560, 400), (620, 470), (700, 424)], w=3,
                                smooth=True)],
             ("the fin", "fenan", "плавник"),
             "#5c6bc0"),
        part("whale_eye", [oval((364, 292, 398, 326), w=2)],
             ("the eye", "ögat", "глаз"), "#3e2723"),
        part("whale_smile", [pline([(300, 344), (346, 364), (400, 366)], w=3,
                                   smooth=True)],
             ("the smile", "leendet",
              "улыбка"), "#3e2723",
             fillable=False),
        part("spout", [poly([(534, 208), (514, 132), (540, 74), (582, 130),
                             (594, 204)], w=3, smooth=True),
                       oval((500, 20, 582, 86), w=3)],
             ("the spout", "vattenstrålen",
              "фонтан"), "#b3e5fc"),

        # a little fish of its own
        part("fish_tail", [poly([(714, 520), (660, 480), (672, 542),
                                 (652, 596)], w=3, smooth=True)],
             ("the tail", "stjärtfenan",
              "хвост"), "#ffb300"),
        part("fish", [poly([(710, 470), (790, 456), (860, 490), (884, 534),
                            (846, 580), (770, 596), (706, 566)], w=3,
                           smooth=True)],
             ("the fish", "fisken", "рыбка"),
             "#ffca28"),
        part("fish_fin", [poly([(770, 458), (800, 414), (830, 470)], w=3,
                               smooth=True)],
             ("the fin", "fenan", "плавник"),
             "#ffb300"),
        part("fish_eye", [oval((842, 496, 872, 526), w=2)],
             ("the eye", "ögat", "глаз"), "#3e2723"),

        part("starfish", [poly([(230, 636), (258, 578), (286, 636),
                                (348, 640), (300, 680), (316, 700),
                                (258, 668), (200, 700), (216, 640)], w=3)],
             ("the starfish", "sjöstjärnan",
              "морская звезда"),
             "#ec407a"),
        part("shell", [poly([(422, 692), (430, 644), (452, 612), (470, 604),
                             (488, 612), (510, 644), (518, 692)], w=3,
                            smooth=True),
                       pline([(470, 692), (452, 622)], w=2),
                       pline([(470, 692), (470, 608)], w=2),
                       pline([(470, 692), (490, 622)], w=2)],
             ("the shell", "snäckan",
              "ракушка"), "#f8bbd0"),
        part("bubbles", [oval((160, 200, 206, 246), w=3),
                         oval((196, 130, 230, 164), w=3),
                         oval((150, 96, 176, 122), w=3)],
             ("the bubbles", "bubblorna",
              "пузырьки"), "#e1f5fe"),
    ])


# ---- 3: the dog and its kennel (the same pair as the first maze) ----------
DOGYARD = picture(
    "dogyard",
    ("The dog and its kennel", "Hunden och hundkojan",
     "Собака и её будка"),
    1000, 700,
    [
        part("sky", [poly([(0, 0), (1000, 0), (1000, 470), (0, 470)], w=0)],
             ("the sky", "himlen", "небо"), "#bbdefb"),
        part("sun", [oval((60, 40, 200, 180), w=3),
                     pline([(130, 10), (130, 34)], w=3),
                     pline([(20, 110), (48, 110)], w=3),
                     pline([(212, 110), (240, 110)], w=3)],
             ("the sun", "solen", "солнце"),
             "#ffd54f"),
        part("cloud", [oval((620, 60, 760, 140), w=3),
                       oval((700, 30, 860, 132), w=3),
                       oval((800, 70, 910, 140), w=3)],
             ("the cloud", "molnet", "облако"),
             "#ffffff"),
        part("grass", [poly([(0, 470), (1000, 470), (1000, 700), (0, 700)],
                            w=0)],
             ("the grass", "gräset", "трава"),
             "#a5d6a7"),
        part("fence", [poly([(0, 380), (1000, 380), (1000, 404), (0, 404)],
                            w=3),
                       poly([(0, 440), (1000, 440), (1000, 464), (0, 464)],
                            w=3),
                       poly([(60, 330), (110, 330), (110, 500), (60, 500)],
                            w=3),
                       poly([(300, 330), (350, 330), (350, 500), (300, 500)],
                            w=3),
                       poly([(880, 330), (930, 330), (930, 500), (880, 500)],
                            w=3)],
             ("the fence", "staketet", "забор"),
             "#bcaaa4"),
        part("tree_trunk", [poly([(540, 470), (580, 470), (588, 300),
                                  (532, 300)], w=3)],
             ("the tree", "trädet", "дерево"),
             "#8d6e63"),
        part("tree_crown", [oval((420, 130, 700, 340), w=3)],
             ("the leaves", "löven",
              "листья"), "#66bb6a"),
        part("apples", [oval((486, 200, 526, 240), w=2),
                        oval((588, 176, 628, 216), w=2),
                        oval((554, 264, 594, 304), w=2)],
             ("the apples", "äpplena",
              "яблоки"), "#ef5350"),

        part("kennel_wall", [poly([(660, 660), (660, 470), (940, 470),
                                   (940, 660)], w=3)],
             ("the kennel", "hundkojan", "будка"),
             "#d7a86e"),
        part("kennel_roof", [poly([(620, 480), (800, 366), (980, 480)], w=3)],
             ("the roof", "taket", "крыша"),
             "#c0392b"),
        part("kennel_door", [poly([(740, 660), (740, 566), (760, 528),
                                   (840, 528), (860, 566), (860, 660)], w=3,
                                  smooth=True)],
             ("the doorway", "öppningen",
              "вход"), "#6d4c41"),
        part("kennel_plate", [poly([(760, 486), (840, 486), (840, 516),
                                    (760, 516)], w=3)],
             ("the name plate", "namnskylten",
              "табличка"), "#efe0c0"),

        # the dog, in profile facing right, standing on the grass
        part("dog_tail", [poly([(196, 520), (150, 470), (166, 420),
                                (196, 434), (186, 478), (222, 512)], w=3,
                               smooth=True)],
             ("the tail", "svansen", "хвост"),
             "#c98a4b"),
        part("dog_legs", [poly([(226, 600), (266, 600), (266, 680),
                                (226, 680)], w=3),
                          poly([(300, 600), (340, 600), (340, 680),
                                (300, 680)], w=3),
                          poly([(420, 600), (460, 600), (460, 680),
                                (420, 680)], w=3),
                          poly([(480, 600), (520, 600), (520, 680),
                                (480, 680)], w=3)],
             ("the legs", "benen", "ноги"), "#a06a2c"),
        part("dog", [poly([(200, 560), (240, 500), (330, 480), (430, 486),
                           (500, 512), (520, 570), (480, 620), (360, 636),
                           (250, 624), (196, 596)], w=3, smooth=True)],
             ("the dog", "hunden", "собака"),
             "#c98a4b"),
        part("dog_head", [poly([(470, 520), (500, 452), (556, 428),
                                (606, 446), (620, 486), (660, 496),
                                (660, 536), (600, 546), (556, 570),
                                (492, 566)], w=3, smooth=True)],
             ("the head", "huvudet", "голова"),
             "#c98a4b"),
        part("dog_ear", [poly([(508, 452), (478, 500), (492, 552),
                               (534, 512), (540, 462)], w=3, smooth=True)],
             ("the ear", "örat", "ухо"), "#a06a2c"),
        part("dog_collar", [poly([(470, 512), (492, 506), (500, 568),
                                  (478, 572)], w=3, smooth=True)],
             ("the collar", "halsbandet",
              "ошейник"), "#e53935"),
        part("dog_nose", [oval((640, 492, 676, 528), w=2)],
             ("the nose", "nosen", "нос"), "#3e2723"),
        part("dog_eye", [oval((572, 462, 598, 488), w=2)],
             ("the eye", "ögat", "глаз"), "#3e2723"),
        part("bone", [poly([(120, 664), (180, 654), (196, 668), (182, 684),
                            (120, 692), (104, 678)], w=3, smooth=True),
                      oval((86, 650, 126, 686), w=3),
                      oval((176, 646, 216, 682), w=3)],
             ("the bone", "benet", "кость"),
             "#fff8e1"),
        part("ball", [oval((580, 630, 660, 700), w=3),
                      pline([(580, 664), (660, 664)], w=2),
                      pline([(600, 638), (640, 694)], w=2)],
             ("the ball", "bollen", "мяч"), "#42a5f5"),
        part("flowers", [oval((360, 686, 384, 700), w=2),
                         oval((392, 672, 416, 696), w=2),
                         oval((60, 600, 84, 624), w=2)],
             ("the flowers", "blommorna",
              "цветы"), "#ec407a"),
    ])

PICTURES = [DINOS, SEA, DOGYARD]
PICTURE_BY_KEY = {p["key"]: p for p in PICTURES}
PICTURE_ORDER = [p["key"] for p in PICTURES]

# A picture carries its own name in the three languages.  Registering
# them in the language table here means a new picture needs no second
# edit somewhere else - and the self test checks them like any other row.
for _pic in PICTURES:
    TXT["pic." + _pic["key"]] = tuple(_pic["name"])

# *************** DEL 18 - COLOURING (PART 2) *******************************
# Two ways to colour, the way a child does it on paper:
#
#   FILL    click a part and it takes the colour - the teeth, an eye, a stone.
#           Parts are named (DEL 17), and the name shows while hovering, so
#           the picture teaches a few words in three languages on the way.
#   CRAYON  draw freely on top.  The stroke is drawn as several jittered,
#           half-stippled lines instead of one clean line, because a clean
#           line looks like a computer and a child's crayon does not.
#
# Erasing is the same everywhere in this program: the right mouse button and
# DELETE.  Right button takes away the crayon stroke it touches, or empties
# the part under it; DELETE undoes the last thing; Ctrl+DELETE empties the
# whole page after asking.
#
# Everything is kept in SCENE coordinates, never pixels, so the drawing
# survives a resized window - and so the PNG that gets saved is the same
# picture, not a screenshot.

CRAYONS_24 = [
    "#000000", "#5d4037", "#8d6e63", "#bf360c", "#e53935", "#ef5350",
    "#ec407a", "#f8bbd0", "#fb8c00", "#ffa726", "#fdd835", "#fff59d",
    "#7cb342", "#43a047", "#1b5e20", "#a5d6a7", "#0288d1", "#42a5f5",
    "#b3e5fc", "#5e35b1", "#8e24aa", "#ce93d8", "#9e9e9e", "#ffffff",
]

CRAYON_WIDTHS = {"thin": 3.0, "medium": 8.0, "thick": 18.0}
WIDTH_ORDER = ("thin", "medium", "thick")


class ColourView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.picture = None
        self.fills = {}            # part id -> colour
        self.strokes = []          # dicts: colour, w, pts (scene), seed
        self.undo_stack = []
        self.redo_stack = []
        self.part_items = {}       # canvas item -> part id
        self.stroke_items = {}     # canvas item -> stroke index
        self.current = None        # the stroke being drawn right now
        self.scale = 1.0
        self.ox = self.oy = 0
        self.hover = None
        self.peeking = False
        self._timers = []
        self._msg = "status.colour.ready"
        self._msg_args = ()
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.open_picture(SETTINGS.get("picture", PICTURE_ORDER[0]))

    # ---- building ---------------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row1 = tk.Frame(bar, bg=CREAM)
        row1.pack(side="top", fill="x", padx=8, pady=(6, 2))
        row2 = tk.Frame(bar, bg=CREAM)
        row2.pack(side="top", fill="x", padx=8, pady=(0, 6))

        tbutton(row1, "btn.back", self.app.show_start).pack(side="left")
        lab = tk.Label(row1, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.picture") + 1, anchor="e")
        reg(lab, "lbl.picture")
        lab.pack(side="left", padx=(12, 2))
        self.opt_pic = KeyedOption(
            row1, [(p["key"], "pic." + p["key"]) for p in PICTURES],
            SETTINGS.get("picture", PICTURE_ORDER[0]), self.on_picture)
        self.opt_pic.pack(side="left", padx=(0, 14))

        self.tool = tk.StringVar(value="fill")
        for key, value in (("btn.fill", "fill"), ("btn.crayon", "crayon"),
                           ("btn.eraser", "eraser")):
            b = tk.Radiobutton(row1, variable=self.tool, value=value,
                               indicatoron=0, width=width_for(key) + 2,
                               font=FONT_UI, bg=BTN, fg=TEXTC,
                               selectcolor=BTN_ON, activebackground=BTN_ON,
                               relief="raised", bd=2, cursor="hand2",
                               command=self.on_tool)
            reg(b, key)
            b.pack(side="left", padx=2)

        lab = tk.Label(row1, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.thickness") + 1, anchor="e")
        reg(lab, "lbl.thickness")
        lab.pack(side="left", padx=(12, 2))
        self.opt_width = KeyedOption(
            row1, [(w, "thick." + w) for w in WIDTH_ORDER],
            SETTINGS.get("crayon_width", "medium"), self.on_width)
        self.opt_width.pack(side="left")

        tbutton(row2, "btn.peek", self.peek).pack(side="left")
        tbutton(row2, "btn.undo", self.undo).pack(side="left", padx=6)
        tbutton(row2, "btn.redo", self.redo).pack(side="left")
        tbutton(row2, "btn.clearpage", self.clear_all).pack(side="left",
                                                            padx=6)
        tbutton(row2, "btn.savepic", self.save_picture).pack(side="left")
        tbutton(row2, "btn.about",
                lambda: show_about(self.app.root)).pack(side="right",
                                                        padx=(6, 0))
        tbutton(row2, "btn.help",
                lambda: show_help(self.app.root)).pack(side="right", padx=6)
        tbutton(row2, "btn.settings",
                lambda: show_settings(self.app.root,
                                      self.app)).pack(side="right", padx=6)

        # the crayon box
        box = tk.Frame(self, bg=CREAM)
        box.pack(side="top", fill="x")
        inner = tk.Frame(box, bg=CREAM)
        inner.pack(pady=6)
        self.swatches = {}
        self.colour = SETTINGS.get("crayon_colour", "#ef5350")
        for i, c in enumerate(CRAYONS_24):
            b = tk.Button(inner, bg=c, activebackground=c, width=2, height=1,
                          relief="raised", bd=2, cursor="hand2",
                          highlightthickness=0,
                          command=lambda cc=c: self.pick_colour(cc))
            b.grid(row=i // 12, column=i % 12, padx=2, pady=2)
            self.swatches[c] = b

        self.canvas = tk.Canvas(self, bg=PAPER, highlightthickness=0,
                                takefocus=1, cursor="pencil")
        self.canvas.pack(side="top", fill="both", expand=True)

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_part = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                 font=FONT_UI_B, anchor="e", width=28)
        self.lbl_part.pack(side="right", padx=10, pady=5)

        self.canvas.bind("<Configure>", lambda e: self.redraw())
        self.canvas.bind("<Button-1>", self.on_press)
        self.canvas.bind("<B1-Motion>", self.on_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_release)
        self.canvas.bind("<Button-3>", self.on_right)
        self.canvas.bind("<B3-Motion>", self.on_right)
        self.canvas.bind("<Motion>", self.on_hover)
        self.canvas.bind("<Leave>", lambda e: self.set_part_label(None))
        self.pick_colour(self.colour)
        on_retranslate(self.retranslate_view)

    # ---- timers -----------------------------------------------------------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- opening a picture ------------------------------------------------
    def open_picture(self, key):
        self.cancel_timers()
        self.picture = PICTURE_BY_KEY.get(key) or PICTURES[0]
        SETTINGS["picture"] = self.picture["key"]
        save_settings()
        self.fills = {}
        self.strokes = []
        self.undo_stack = []
        self.redo_stack = []
        self.peeking = False
        log("---- colouring: picture=%s (%d parts)"
            % (self.picture["key"], len(self.picture["parts"])))
        self.set_msg("status.colour.ready")
        self.redraw()

    def on_picture(self, value):
        if (self.fills or self.strokes) and \
                not ask_yes_no(self.app.root, "ask.newpicture"):
            self.opt_pic.set(self.picture["key"])
            return
        self.open_picture(value)

    def on_tool(self):
        self.canvas.configure(cursor=("dotbox" if self.tool.get() == "fill"
                                      else "pencil"))
        self.set_msg("status.colour." + self.tool.get())

    def on_width(self, value):
        SETTINGS["crayon_width"] = value
        save_settings()

    def pick_colour(self, colour):
        self.colour = colour
        SETTINGS["crayon_colour"] = colour
        save_settings()
        for c, b in self.swatches.items():
            b.configure(relief=("sunken" if c == colour else "raised"),
                        bd=(4 if c == colour else 2))

    # ---- geometry ---------------------------------------------------------
    def layout(self):
        pic = self.picture
        cw = max(50, self.canvas.winfo_width())
        ch = max(50, self.canvas.winfo_height())
        self.scale = min((cw - 24) / float(pic["w"]),
                         (ch - 24) / float(pic["h"]))
        self.scale = max(0.05, self.scale)
        self.ox = (cw - pic["w"] * self.scale) / 2.0
        self.oy = (ch - pic["h"] * self.scale) / 2.0

    def to_scene(self, px, py):
        return ((px - self.ox) / self.scale, (py - self.oy) / self.scale)

    def to_px(self, p):
        return (self.ox + p[0] * self.scale, self.oy + p[1] * self.scale)

    # ---- drawing ----------------------------------------------------------
    def redraw(self):
        if not self.picture:
            return
        c = self.canvas
        c.delete("all")
        self.layout()
        self.part_items = {}
        self.stroke_items = {}
        pic = self.picture
        x0, y0 = self.ox, self.oy
        x1 = x0 + pic["w"] * self.scale
        y1 = y0 + pic["h"] * self.scale
        c.create_rectangle(x0 - 6, y0 - 6, x1 + 6, y1 + 6, fill="#efe2c4",
                           outline="")
        c.create_rectangle(x0, y0, x1, y1, fill="#ffffff",
                           outline="#e0cfa8")
        for pt in pic["parts"]:
            over = None
            if pt.get("fillable", True):
                colour = (pt["hint"] if self.peeking
                          else self.fills.get(pt["id"], "#ffffff"))
                over = {i: colour for i, pr in enumerate(pt["prims"])
                        if pr["kind"] in ("poly", "oval")}
            items = draw_scene(c, pt["prims"], self.ox, self.oy, self.scale,
                               fill_over=over)
            for it in items:
                self.part_items[it] = pt["id"]
        for i, st in enumerate(self.strokes):
            for it in self.draw_stroke(st):
                self.stroke_items[it] = i

    def draw_stroke(self, st):
        """A crayon stroke: three passes, jittered, so it looks waxy.

        The jitter comes from the stroke's own seed, never from the clock, so
        a redraw after a resize gives exactly the same stroke back."""
        if len(st["pts"]) < 2:
            p = self.to_px(st["pts"][0])
            r = max(1.0, st["w"] * self.scale / 2.0)
            return [self.canvas.create_oval(p[0] - r, p[1] - r, p[0] + r,
                                            p[1] + r, fill=st["colour"],
                                            outline="")]
        rnd = random.Random(st["seed"])
        wide = max(1, int(round(st["w"] * self.scale)))
        items = []
        flat = []
        for p in st["pts"]:
            flat.extend(self.to_px(p))
        items.append(self.canvas.create_line(
            *flat, fill=st["colour"], width=wide, capstyle="round",
            joinstyle="round"))
        jitter = max(0.8, st["w"] * self.scale * 0.22)
        for pass_no in range(2):
            flat = []
            for p in st["pts"]:
                px, py = self.to_px(p)
                flat.extend((px + rnd.uniform(-jitter, jitter),
                             py + rnd.uniform(-jitter, jitter)))
            items.append(self.canvas.create_line(
                *flat, fill=st["colour"], width=max(1, int(wide * 0.7)),
                capstyle="round", joinstyle="round", stipple="gray50"))
        return items

    # ---- what is under the mouse -----------------------------------------
    def part_at(self, px, py, fillable_only=True):
        for it in reversed(self.canvas.find_overlapping(px, py, px, py)):
            pid = self.part_items.get(it)
            if pid is None:
                continue
            if not fillable_only:
                return pid
            for pt in self.picture["parts"]:
                if pt["id"] == pid and pt.get("fillable", True):
                    return pid
        return None

    def stroke_at(self, px, py):
        for it in reversed(self.canvas.find_overlapping(px - 2, py - 2,
                                                        px + 2, py + 2)):
            if it in self.stroke_items:
                return self.stroke_items[it]
        return None

    def part_label(self, pid):
        for pt in self.picture["parts"]:
            if pt["id"] == pid:
                lang = SETTINGS.get("language", "sv")
                i = LANGS.index(lang) if lang in LANGS else 1
                return pt["label"][i]
        return ""

    def set_part_label(self, pid):
        self.hover = pid
        try:
            self.lbl_part.configure(text=cap(self.part_label(pid))
                                    if pid else "")
        except Exception:
            pass

    def on_hover(self, event):
        self.set_part_label(self.part_at(event.x, event.y))

    # ---- drawing and filling ---------------------------------------------
    def on_press(self, event):
        self.canvas.focus_set()
        tool = self.tool.get()
        if tool == "fill":
            self.do_fill(event.x, event.y)
        elif tool == "eraser":
            self.do_erase(event.x, event.y)
        else:
            self.start_stroke(event.x, event.y)

    def on_drag(self, event):
        tool = self.tool.get()
        if tool == "crayon":
            self.extend_stroke(event.x, event.y)
        elif tool == "eraser":
            self.do_erase(event.x, event.y)
        self.set_part_label(self.part_at(event.x, event.y))

    def on_release(self, event):
        if self.current is not None:
            self.finish_stroke()

    def on_right(self, event):
        """The right button always erases, whatever tool is chosen."""
        self.canvas.focus_set()
        self.do_erase(event.x, event.y)

    def do_fill(self, px, py):
        pid = self.part_at(px, py)
        if not pid:
            self.set_msg("status.colour.nopart")
            return
        old = self.fills.get(pid)
        if old == self.colour:
            return
        self.fills[pid] = self.colour
        self.push(("fill", pid, old, self.colour))
        log("colour: filled %s with %s" % (pid, self.colour))
        self.set_msg("status.colour.filled", cap(self.part_label(pid)))
        self.redraw()

    def do_erase(self, px, py):
        idx = self.stroke_at(px, py)
        if idx is not None:
            st = self.strokes.pop(idx)
            self.push(("erase_stroke", idx, st))
            self.set_msg("status.colour.rubbed")
            self.redraw()
            return
        pid = self.part_at(px, py)
        if pid and pid in self.fills:
            old = self.fills.pop(pid)
            self.push(("fill", pid, old, None))
            self.set_msg("status.colour.emptied", cap(self.part_label(pid)))
            self.redraw()

    def start_stroke(self, px, py):
        self.current = dict(colour=self.colour,
                            w=CRAYON_WIDTHS[SETTINGS.get("crayon_width",
                                                         "medium")],
                            pts=[self.to_scene(px, py)],
                            seed=random.randrange(1, 10 ** 9))

    def extend_stroke(self, px, py):
        if self.current is None:
            self.start_stroke(px, py)
            return
        p = self.to_scene(px, py)
        last = self.current["pts"][-1]
        if abs(p[0] - last[0]) + abs(p[1] - last[1]) < 1.5:
            return
        self.current["pts"].append(p)
        self.draw_stroke(self.current)      # cheap preview; redraw tidies up

    def finish_stroke(self):
        st, self.current = self.current, None
        if st is None or not st["pts"]:
            return
        self.strokes.append(st)
        self.push(("stroke", len(self.strokes) - 1, st))
        self.set_msg("status.colour.drew")
        self.redraw()

    # ---- undo, redo, clear -----------------------------------------------
    def push(self, action):
        self.undo_stack.append(action)
        self.redo_stack = []
        if len(self.undo_stack) > 400:
            del self.undo_stack[:100]

    def undo(self):
        if not self.undo_stack:
            return
        action = self.undo_stack.pop()
        self.apply_reverse(action)
        self.redo_stack.append(action)
        self.set_msg("status.colour.undone")
        self.redraw()

    def redo(self):
        if not self.redo_stack:
            return
        action = self.redo_stack.pop()
        self.apply_forward(action)
        self.undo_stack.append(action)
        self.redraw()

    def apply_reverse(self, action):
        kind = action[0]
        if kind == "fill":
            _, pid, old, new = action
            if old is None:
                self.fills.pop(pid, None)
            else:
                self.fills[pid] = old
        elif kind == "stroke":
            _, idx, st = action
            if 0 <= idx < len(self.strokes):
                self.strokes.pop(idx)
        elif kind == "erase_stroke":
            _, idx, st = action
            self.strokes.insert(min(idx, len(self.strokes)), st)
        elif kind == "clear":
            _, fills, strokes = action
            self.fills = dict(fills)
            self.strokes = list(strokes)

    def apply_forward(self, action):
        kind = action[0]
        if kind == "fill":
            _, pid, old, new = action
            if new is None:
                self.fills.pop(pid, None)
            else:
                self.fills[pid] = new
        elif kind == "stroke":
            _, idx, st = action
            self.strokes.insert(min(idx, len(self.strokes)), st)
        elif kind == "erase_stroke":
            _, idx, st = action
            if 0 <= idx < len(self.strokes):
                self.strokes.pop(idx)
        elif kind == "clear":
            self.fills = {}
            self.strokes = []

    def clear_all(self):
        if not (self.fills or self.strokes):
            return
        if not ask_yes_no(self.app.root, "ask.clearpage"):
            return
        self.push(("clear", dict(self.fills), list(self.strokes)))
        self.fills = {}
        self.strokes = []
        self.set_msg("status.colour.cleared")
        self.redraw()

    # ---- peek at the natural colours -------------------------------------
    def peek(self):
        if self.peeking:
            return
        self.peeking = True
        self.redraw()
        self.set_msg("status.colour.peek")
        self.after_t(2500, self.unpeek)

    def unpeek(self):
        self.peeking = False
        self.set_msg("status.colour.ready")
        self.redraw()

    # ---- saving -----------------------------------------------------------
    def save_picture(self):
        """The artwork as JSON (so it can be opened again) and, when Pillow
        is here, as a PNG beside it."""
        try:
            os.makedirs(GALLERY_DIR, exist_ok=True)
        except Exception:
            pass
        stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
        base = os.path.join(GALLERY_DIR, "%s_%s" % (self.picture["key"],
                                                    stamp))
        data = dict(picture=self.picture["key"], fills=self.fills,
                    strokes=[dict(colour=s["colour"], w=s["w"],
                                  seed=s["seed"],
                                  pts=[[round(x, 1), round(y, 1)]
                                       for x, y in s["pts"]])
                             for s in self.strokes])
        try:
            with open(base + ".json", "w", encoding="utf-8") as fh:
                json.dump(data, fh)
        except Exception as exc:
            log("colour: could not save json: %s" % exc)
            self.set_msg("status.colour.savefail")
            return
        png = self.save_png(base + ".png")
        log("colour: saved %s%s" % (base + ".json", " + png" if png else ""))
        self.set_msg("status.colour.saved",
                     os.path.basename(base + (".png" if png else ".json")))

    def save_png(self, path, scale=1.0):
        try:
            from PIL import Image, ImageDraw
        except ImportError:
            return False
        try:
            pic = self.picture
            img = Image.new("RGB", (int(pic["w"] * scale),
                                    int(pic["h"] * scale)), "#ffffff")
            d = ImageDraw.Draw(img)
            for pt in pic["parts"]:
                over = None
                if pt.get("fillable", True):
                    colour = self.fills.get(pt["id"], "#ffffff")
                    over = {i: colour for i, pr in enumerate(pt["prims"])
                            if pr["kind"] in ("poly", "oval")}
                draw_scene_pil(d, pt["prims"], 0, 0, scale, fill_over=over)
            for st in self.strokes:
                pts = [(x * scale, y * scale) for x, y in st["pts"]]
                wide = max(1, int(round(st["w"] * scale)))
                if len(pts) == 1:
                    r = wide / 2.0
                    d.ellipse([pts[0][0] - r, pts[0][1] - r,
                               pts[0][0] + r, pts[0][1] + r],
                              fill=st["colour"])
                else:
                    d.line(pts, fill=st["colour"], width=wide, joint="curve")
            img.save(path)
            return True
        except Exception as exc:
            log("colour: could not save png: %s" % exc)
            return False

    # ---- keys -------------------------------------------------------------
    def handle_key(self, event):
        sym = (event.keysym or "").lower()
        ctrl = bool(event.state & 0x0004)
        if sym in ("delete", "backspace", "kp_delete"):
            if ctrl:
                self.clear_all()
            else:
                self.undo()
        elif sym == "z" and ctrl:
            self.undo()
        elif sym == "y" and ctrl:
            self.redo()

    # ---- text -------------------------------------------------------------
    def set_msg(self, key, *args):
        self._msg = key
        self._msg_args = args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def retranslate_view(self):
        if self.picture:
            self.set_msg(self._msg, *self._msg_args)
            self.set_part_label(self.hover)

# *************** DEL 19 - JIGSAW (PART 3) *********************************
# The same pictures as part 2, in their own colours, cut into pieces with
# real tabs and blanks - not diced into squares.
#
# How two pieces can fit: every boundary between two neighbouring pieces is
# built ONCE, as a list of points with a knob bulging to one side, and BOTH
# pieces use that same list - one walking it forwards, the other backwards.
# The two edges are then the same curve by construction, so they cannot drift
# apart however the knob is shaped.
#
# This is the one part of the program that needs Pillow: a piece is a bitmap
# cut out of the rendered picture through a mask.  Without Pillow the view
# says so plainly instead of half-working.
#
# Erasing keeps the habit from the other two parts: the right mouse button
# sends a piece back to the tray, and DELETE sends back the one under the
# cursor.
#
# MAGNETS.  Two things pull pieces together, and both are decided when the
# mouse button is let go:
#   * A piece (or a group) dropped close to the place it belongs on the board
#     is moved EXACTLY onto it and is then locked there.
#   * A piece dropped close to its true neighbour - another loose piece that
#     is next to it in the finished picture - is moved exactly against it and
#     the two become one group.  Grab any piece of a group and the whole group
#     comes along.  Groups grow as more pieces are added, and a group that is
#     dropped near its place on the board locks down as a whole.
# "Close" is SNAP_PIXELS, measured on the offset the two pieces SHOULD have
# (their homes are known), so only a true neighbour in the right position
# attracts - never a piece that merely lies nearby.  Which pieces stick is
# kept in `links`, keyed by (row, column), so it survives the picture being cut
# again after the window was resized; anchor_groups() then puts the members back
# at their exact distance, because cutting rounds every home a little
# differently.  Pieces that are locked on the board are not dragged away by
# accident (right button / DELETE takes them out).

JIGSAW_SIZES = {"tiny": (3, 2), "small": (4, 3), "medium": (6, 4),
                "big": (8, 6)}
JIGSAW_ORDER = ("tiny", "small", "medium", "big")
SNAP_PIXELS = 22


def jigsaw_available():
    try:
        from PIL import Image, ImageDraw, ImageTk    # noqa: F401
        return True
    except Exception:
        return False


class JigsawView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.picture = None
        self.pieces = []           # dicts: r, c, home, pos, placed, img, item
        self.photos = []           # PhotoImage references, or tkinter frees them
        self.drag = None
        self.links = set()         # frozenset({(r, c), (r, c)}): pieces stuck together
        self.by_rc = {}            # (r, c) -> piece
        self.board = (0, 0, 100, 100)     # x, y, w, h of the finished picture
        self.scale = 1.0
        self.started_at = None
        self.elapsed = 0
        self.done = False
        self.mouse = (0, 0)
        self._resize_job = None
        self._timers = []
        self._msg = "status.jigsaw.ready"
        self._msg_args = ()
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.new_puzzle(ask=False)

    # ---- building ---------------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row = tk.Frame(bar, bg=CREAM)
        row.pack(side="top", fill="x", padx=8, pady=6)

        tbutton(row, "btn.back", self.app.show_start).pack(side="left")
        lab = tk.Label(row, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.picture") + 1, anchor="e")
        reg(lab, "lbl.picture")
        lab.pack(side="left", padx=(12, 2))
        self.opt_pic = KeyedOption(
            row, [(p["key"], "pic." + p["key"]) for p in PICTURES],
            SETTINGS.get("jigsaw_picture", PICTURE_ORDER[0]),
            self.on_picture)
        self.opt_pic.pack(side="left", padx=(0, 12))

        lab = tk.Label(row, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.pieces") + 1, anchor="e")
        reg(lab, "lbl.pieces")
        lab.pack(side="left", padx=(0, 2))
        self.opt_size = KeyedOption(
            row, [(k, "jig." + k) for k in JIGSAW_ORDER],
            SETTINGS.get("jigsaw_size", "small"), self.on_size)
        self.opt_size.pack(side="left", padx=(0, 12))

        tbutton(row, "btn.newjigsaw", self.new_puzzle).pack(side="left")
        self.ghost_var = tk.BooleanVar(value=bool(SETTINGS.get("jigsaw_ghost",
                                                               False)))
        cb = tk.Checkbutton(row, variable=self.ghost_var,
                            command=self.on_ghost, bg=CREAM,
                            activebackground=CREAM, fg=TEXTC,
                            selectcolor=PAPER, font=FONT_UI, cursor="hand2",
                            width=width_for("lbl.ghost") + 2, anchor="w")
        reg(cb, "lbl.ghost")
        cb.pack(side="left", padx=10)

        tbutton(row, "btn.about",
                lambda: show_about(self.app.root)).pack(side="right",
                                                        padx=(6, 0))
        tbutton(row, "btn.help",
                lambda: show_help(self.app.root)).pack(side="right", padx=6)

        self.canvas = tk.Canvas(self, bg=PAPER, highlightthickness=0,
                                takefocus=1)
        self.canvas.pack(side="top", fill="both", expand=True)

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_count = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                  font=FONT_UI, anchor="e",
                                  width=width_for("status.jigsaw.count") + 2)
        self.lbl_count.pack(side="right", padx=10, pady=5)

        self.canvas.bind("<Configure>", self.on_configure)
        self.canvas.bind("<Button-1>", self.on_press)
        self.canvas.bind("<B1-Motion>", self.on_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_release)
        self.canvas.bind("<Button-3>", self.on_right)
        self.canvas.bind("<Motion>", self.on_motion)
        on_retranslate(self.retranslate_view)

    # ---- timers -----------------------------------------------------------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- a new puzzle -----------------------------------------------------
    def new_puzzle(self, ask=True):
        if ask and self.pieces and not self.done and \
                sum(1 for p in self.pieces if p["placed"]) and \
                not ask_yes_no(self.app.root, "ask.newjigsaw"):
            return
        self.cancel_timers()
        key = SETTINGS.get("jigsaw_picture", PICTURE_ORDER[0])
        self.picture = PICTURE_BY_KEY.get(key) or PICTURES[0]
        self.seed = random.randrange(1, 10 ** 9)
        self.started_at = None
        self.elapsed = 0
        self.done = False
        cols, rows = JIGSAW_SIZES.get(SETTINGS.get("jigsaw_size", "small"),
                                      (4, 3))
        log("---- jigsaw: picture=%s pieces=%dx%d seed=%d"
            % (self.picture["key"], cols, rows, self.seed))
        self.set_msg("status.jigsaw.ready")
        self.rebuild(scatter=True)
        self.tick()

    def on_picture(self, value):
        SETTINGS["jigsaw_picture"] = value
        save_settings()
        self.new_puzzle(ask=False)

    def on_size(self, value):
        SETTINGS["jigsaw_size"] = value
        save_settings()
        self.new_puzzle(ask=False)

    def on_ghost(self):
        SETTINGS["jigsaw_ghost"] = bool(self.ghost_var.get())
        save_settings()
        self.rebuild(scatter=False)

    def on_configure(self, event):
        # Cutting the picture up again is too much work to do on every pixel
        # of a window drag, so it waits until the dragging stops.
        if self._resize_job:
            try:
                self.after_cancel(self._resize_job)
            except Exception:
                pass
        self._resize_job = self.after(250, lambda: self.rebuild(scatter=False))

    # ---- cutting the picture ---------------------------------------------
    def rebuild(self, scatter=True):
        self._resize_job = None
        if not self.picture:
            return
        c = self.canvas
        c.delete("all")
        self.photos = []
        if not jigsaw_available():
            self.draw_no_pillow()
            return
        cw = max(60, c.winfo_width())
        ch = max(60, c.winfo_height())
        pic = self.picture
        tray_w = max(170, int(cw * 0.36))
        avail_w = cw - tray_w - 40
        avail_h = ch - 40
        self.scale = max(0.05, min(avail_w / float(pic["w"]),
                                   avail_h / float(pic["h"])))
        bw = int(pic["w"] * self.scale)
        bh = int(pic["h"] * self.scale)
        bx = 20
        by = max(10, (ch - bh) // 2)
        self.board = (bx, by, bw, bh)
        self.tray = (bx + bw + 20, 10, cw - (bx + bw + 30), ch - 20)

        # Everything that is only background carries the "bg" tag, so a
        # piece can be put UNDER the other pieces without disappearing under
        # the board itself.
        c.create_rectangle(bx - 3, by - 3, bx + bw + 3, by + bh + 3,
                           fill="#efe2c4", outline="#d7c49a", tags=("bg",))
        if SETTINGS.get("jigsaw_ghost"):
            self.draw_ghost()
        c.create_rectangle(self.tray[0] - 6, self.tray[1],
                           self.tray[0] + self.tray[2] + 6,
                           self.tray[1] + self.tray[3], fill="#f7efdc",
                           outline="#e0cfa8", dash=(5, 4), tags=("bg",))

        old = {(p["r"], p["c"]): p for p in self.pieces} if not scatter else {}
        if scatter:
            self.links = set()
        self.pieces = self.cut_pieces(bw, bh)
        self.index_pieces()
        rnd = random.Random(self.seed)
        loose = [p for p in self.pieces
                 if not (old.get((p["r"], p["c"])) or {}).get("placed")]
        avg = (sum(p["size"][0] for p in self.pieces) / float(len(self.pieces)),
               sum(p["size"][1] for p in self.pieces) / float(len(self.pieces)))
        spots = self.scatter_spots(len(loose), rnd, avg)
        rnd.shuffle(loose)
        for i, p in enumerate(loose):
            p["frac"] = spots[i] if i < len(spots) else (rnd.random(),
                                                         rnd.random())
        for p in self.pieces:
            was = old.get((p["r"], p["c"]))
            if was is not None and was.get("placed"):
                p["placed"] = True
                p["pos"] = (bx + p["home"][0], by + p["home"][1])
            else:
                if was is not None and not scatter:
                    p["frac"] = was.get("frac", p["frac"])
                p["pos"] = self.tray_spot(p["frac"][0], p["frac"][1], p)
        self.anchor_groups()
        # placed pieces first, so a loose piece always lies on top
        for p in sorted(self.pieces, key=lambda q: not q["placed"]):
            self.place_item(p)
        self.update_counters()
        if self.done:
            self.draw_banner()

    def scatter_spots(self, n, rnd, avg):
        """Spread the loose pieces over the tray in a jittered grid.

        Purely random positions pile most of the pieces on top of each other
        and the child cannot see what is there; a grid with a little wobble
        looks tipped out of the box and still shows every piece."""
        if n <= 0:
            return []
        tw, th = max(1, self.tray[2]), max(1, self.tray[3])
        # How many pieces fit side by side is decided by the PIECE, not by
        # the count: six big pieces in a narrow tray must not be spread over
        # four columns that do not exist.
        cols = max(1, int(tw / max(1.0, avg[0] * 0.80)))
        cols = min(cols, n)
        rows = int(math.ceil(n / float(cols)))
        spots = []
        for i in range(n):
            cx = (i % cols) / float(max(1, cols - 1)) if cols > 1 else 0.5
            cy = (i // cols) / float(max(1, rows - 1)) if rows > 1 else 0.5
            spots.append((min(1.0, max(0.0, cx + rnd.uniform(-0.06, 0.06))),
                          min(1.0, max(0.0, cy + rnd.uniform(-0.05, 0.05)))))
        return spots

    def tray_spot(self, fx, fy, piece):
        tx, ty, tw, th = self.tray
        w, h = piece["size"]
        return (tx + fx * max(1, tw - w), ty + fy * max(1, th - h))

    def place_item(self, p):
        from PIL import ImageTk
        photo = ImageTk.PhotoImage(p["img"])
        self.photos.append(photo)
        p["photo"] = photo
        p["item"] = self.canvas.create_image(p["pos"][0], p["pos"][1],
                                             image=photo, anchor="nw")

    def draw_ghost(self):
        """A pale copy of the finished picture under the board, as an aid."""
        bx, by, bw, bh = self.board
        for pt in self.picture["parts"]:
            over = None
            if pt.get("fillable", True):
                over = {i: lighten(pt["hint"], 0.72)
                        for i, pr in enumerate(pt["prims"])
                        if pr["kind"] in ("poly", "oval")}
            prims = []
            for pr in pt["prims"]:
                q = dict(pr)
                q["line"] = "#e8dcc0"
                prims.append(q)
            draw_scene(self.canvas, prims, bx, by, self.scale,
                       tags=("bg",), fill_over=over)

    def render_source(self, bw, bh):
        """The finished picture, in its own colours, at board size."""
        from PIL import Image, ImageDraw
        img = Image.new("RGBA", (bw, bh), (255, 255, 255, 255))
        d = ImageDraw.Draw(img)
        scale = bw / float(self.picture["w"])
        for pt in self.picture["parts"]:
            over = None
            if pt.get("fillable", True):
                over = {i: pt["hint"] for i, pr in enumerate(pt["prims"])
                        if pr["kind"] in ("poly", "oval")}
            draw_scene_pil(d, pt["prims"], 0, 0, scale, fill_over=over)
        return img

    def cut_pieces(self, bw, bh):
        from PIL import Image, ImageDraw
        cols, rows = JIGSAW_SIZES.get(SETTINGS.get("jigsaw_size", "small"),
                                      (4, 3))
        src = self.render_source(bw, bh)
        rnd = random.Random(self.seed)
        pw = bw / float(cols)
        ph = bh / float(rows)
        amp = min(pw, ph) * 0.22

        # every shared boundary is built once and used by both neighbours
        hedge = {}
        for r in range(1, rows):
            for cc in range(cols):
                hedge[(r, cc)] = self.edge_points(
                    (cc * pw, r * ph), ((cc + 1) * pw, r * ph),
                    rnd.choice((-1, 1)), amp)
        vedge = {}
        for cc in range(1, cols):
            for r in range(rows):
                vedge[(r, cc)] = self.edge_points(
                    (cc * pw, r * ph), (cc * pw, (r + 1) * ph),
                    rnd.choice((-1, 1)), amp)

        pieces = []
        for r in range(rows):
            for cc in range(cols):
                x0, y0 = cc * pw, r * ph
                x1, y1 = (cc + 1) * pw, (r + 1) * ph
                path = []
                path += (hedge[(r, cc)] if r > 0 else [(x0, y0), (x1, y0)])
                path += (vedge[(r, cc + 1)] if cc < cols - 1
                         else [(x1, y0), (x1, y1)])
                path += (list(reversed(hedge[(r + 1, cc)]))
                         if r < rows - 1 else [(x1, y1), (x0, y1)])
                path += (list(reversed(vedge[(r, cc)])) if cc > 0
                         else [(x0, y1), (x0, y0)])
                xs = [p[0] for p in path]
                ys = [p[1] for p in path]
                pad = 2
                bx0 = max(0, int(min(xs)) - pad)
                by0 = max(0, int(min(ys)) - pad)
                bx1 = min(bw, int(max(xs)) + pad + 1)
                by1 = min(bh, int(max(ys)) + pad + 1)
                local = [(p[0] - bx0, p[1] - by0) for p in path]
                mask = Image.new("L", (bx1 - bx0, by1 - by0), 0)
                ImageDraw.Draw(mask).polygon(local, fill=255)
                piece = Image.new("RGBA", mask.size, (0, 0, 0, 0))
                piece.paste(src.crop((bx0, by0, bx1, by1)), (0, 0), mask)
                ImageDraw.Draw(piece).line(local + [local[0]],
                                           fill=(62, 39, 35, 255), width=2,
                                           joint="curve")
                pieces.append(dict(r=r, c=cc, img=piece,
                                   size=mask.size, home=(bx0, by0),
                                   pos=(0, 0), placed=False, item=None,
                                   frac=(0.5, 0.5)))
        return pieces

    def edge_points(self, a, b, tab, amp):
        """One boundary: a straight run, a knob, a straight run.

        The knob sticks out to whichever side `tab` says.  Both pieces that
        meet here are given this very list, so they interlock exactly."""
        dx, dy = b[0] - a[0], b[1] - a[1]
        length = max(1.0, (dx * dx + dy * dy) ** 0.5)
        ux, uy = dx / length, dy / length          # along the edge
        nx, ny = -uy, ux                           # across it
        shape = [(0.00, 0.00), (0.34, 0.00), (0.36, 0.22), (0.28, 0.42),
                 (0.42, 0.56), (0.58, 0.56), (0.72, 0.42), (0.64, 0.22),
                 (0.66, 0.00), (1.00, 0.00)]
        pts = []
        for t, n in shape:
            off = n * amp * tab
            pts.append((a[0] + ux * length * t + nx * off,
                        a[1] + uy * length * t + ny * off))
        return smooth_pts(pts, closed=False, steps=3)

    def draw_no_pillow(self):
        self.drop_pillow_panel()
        panel = tk.Frame(self.canvas, bg=PAPER)
        self._pil_panel = panel
        wide = max(300, min(720, self.canvas.winfo_width() - 80))
        for key, font, fg in (("jig.nopillow", FONT_BIG, TEXTC),
                              ("pil.hint", FONT_UI, DIMC)):
            lab = tk.Label(panel, bg=PAPER, fg=fg, font=font,
                           wraplength=wide, justify="center")
            reg(lab, key)
            lab.pack(pady=(0, 12))
        self._pil_buttons = []
        row = tk.Frame(panel, bg=PAPER)
        row.pack(pady=4)
        for key, cmd in (("pil.download", self.pil_download),
                         ("pil.search", self.pil_search),
                         ("pil.again", self.pil_again)):
            btn = tbutton(row, key, cmd)
            btn.pack(side="left", padx=5)
            self._pil_buttons.append(btn)
        tbutton(panel, "pil.openfolder", self.pil_open_folder).pack(pady=(8, 2))
        tk.Label(panel, text=PILLOW_DIR, bg=PAPER, fg=DIMC,
                 font=("Consolas", 9), wraplength=wide).pack()
        self._pil_msg = tk.Label(panel, bg=PAPER, fg=TEXTC, font=FONT_UI_B,
                                 wraplength=wide, justify="center", text="")
        self._pil_msg.pack(pady=(12, 0))
        tk.Label(panel, text="pip install pillow", bg=PAPER, fg=DIMC,
                 font=("Consolas", 11)).pack(pady=(10, 0))
        cw = max(60, self.canvas.winfo_width())
        ch = max(60, self.canvas.winfo_height())
        self.canvas.create_window(cw / 2, ch / 2, window=panel, anchor="center")

    def drop_pillow_panel(self):
        panel = getattr(self, "_pil_panel", None)
        self._pil_panel = None
        if panel is not None:
            try:
                panel.destroy()
            except Exception:
                pass

    # ---- bringing Pillow in while the program runs (DEL 04b) --------------
    def _pil_run(self, busy_key, work):
        """Run `work` on a thread (a download must not freeze the window)."""
        for btn in self._pil_buttons:
            btn.configure(state="disabled")
        self._pil_msg.configure(text=T(busy_key))
        box = {}

        def job():
            try:
                box["r"] = work()
            except Exception as exc:
                box["r"] = (False, "pil.dlfail", str(exc)[:120])

        th = threading.Thread(target=job, daemon=True)
        th.start()

        def poll():
            try:
                if not self.winfo_exists():
                    return
                if th.is_alive():
                    self.after(150, poll)
                    return
                self._pil_done(box.get("r", (False, "pil.dlfail", "?")))
            except tk.TclError:
                pass

        poll()

    def _pil_done(self, result):
        ok, key, arg = result
        save_settings()
        if ok:
            log("pillow: ready via %s" % arg)
            self.drop_pillow_panel()
            self.rebuild(scatter=True)
            return
        try:
            self._pil_msg.configure(text=T(key, arg))
            for btn in self._pil_buttons:
                btn.configure(state="normal")
        except tk.TclError:
            pass

    def pil_download(self):
        self._pil_run("pil.downloading", download_pillow)

    def pil_search(self):
        from tkinter import filedialog
        start = SETTINGS.get("pillow_search") or os.path.expanduser("~")
        root = filedialog.askdirectory(parent=self, title=T("pil.choose"),
                                       initialdir=start)
        if root:
            self._pil_run("pil.searching",
                          lambda: search_pillow_action(os.path.normpath(root)))

    def pil_again(self):
        self._pil_run("pil.searching", lambda: search_pillow_action(
            SETTINGS.get("pillow_search", "")))

    def pil_open_folder(self):
        try:
            os.makedirs(PILLOW_DIR, exist_ok=True)
            open_path(PILLOW_DIR)
        except Exception as exc:
            log("pillow: could not open %s: %s" % (PILLOW_DIR, exc))

    # ---- groups: pieces that stick together -------------------------------
    def index_pieces(self):
        self.by_rc = {(p["r"], p["c"]): p for p in self.pieces}

    def neighbours(self, p):
        """The pieces that lie next to this one in the finished picture."""
        out = []
        for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            q = self.by_rc.get((p["r"] + dr, p["c"] + dc))
            if q is not None:
                out.append(q)
        return out

    def group_of(self, p):
        """Every piece stuck to this one, directly or through others (the
        piece itself is always in the list)."""
        nb = {}
        for link in self.links:
            x, y = tuple(link)
            nb.setdefault(x, []).append(y)
            nb.setdefault(y, []).append(x)
        start = (p["r"], p["c"])
        seen = {start}
        todo = [start]
        while todo:
            for k in nb.get(todo.pop(), ()):
                if k not in seen:
                    seen.add(k)
                    todo.append(k)
        return [self.by_rc[k] for k in sorted(seen) if k in self.by_rc]

    def unlink(self, group):
        keys = set((q["r"], q["c"]) for q in group)
        self.links = set(l for l in self.links if not (set(l) & keys))

    def move_group(self, group, dx, dy):
        for q in group:
            q["pos"] = (q["pos"][0] + dx, q["pos"][1] + dy)
            self.canvas.coords(q["item"], q["pos"][0], q["pos"][1])

    def anchor_groups(self):
        """Put every group's pieces back at their exact distance from each
        other.  Cutting the picture again (a resized window) rounds each home
        to whole pixels differently, and a group has no business being a pixel
        off.  The piece with the lowest (row, column) keeps its place."""
        seen = set()
        for p in self.pieces:
            if p["placed"] or id(p) in seen:
                continue
            grp = self.group_of(p)
            for q in grp:
                seen.add(id(q))
            if len(grp) < 2:
                continue
            a = grp[0]
            for q in grp[1:]:
                q["pos"] = (a["pos"][0] + q["home"][0] - a["home"][0],
                            a["pos"][1] + q["home"][1] - a["home"][1])

    def snap_to_board(self, group):
        """If any piece of the group is close to its own place on the board,
        move the WHOLE group so that piece sits exactly there and lock it.
        The group is internally exact, so all the others fall into place too."""
        bx, by = self.board[0], self.board[1]
        best = None
        for q in group:
            tx, ty = bx + q["home"][0], by + q["home"][1]
            dx, dy = tx - q["pos"][0], ty - q["pos"][1]
            d = max(abs(dx), abs(dy))
            if d <= SNAP_PIXELS and (best is None or d < best[0]):
                best = (d, dx, dy)
        if best is None:
            return False
        self.move_group(group, best[1], best[2])
        for q in group:
            q["placed"] = True
            self.canvas.tag_raise(q["item"], "bg")    # under the loose pieces,
                                                      # but above the board
        self.unlink(group)
        return True

    def join(self, group):
        """Stick the group to any loose neighbour that it was dropped next to.
        Moves the group so the closest such pair lines up exactly, then links
        every neighbouring pair that is lined up.  Returns how many links were
        made."""
        members = set((q["r"], q["c"]) for q in group)
        best = None
        for a in group:
            for b in self.neighbours(a):
                if (b["r"], b["c"]) in members or b["placed"]:
                    continue
                dx = (b["pos"][0] - a["pos"][0]) - (b["home"][0] - a["home"][0])
                dy = (b["pos"][1] - a["pos"][1]) - (b["home"][1] - a["home"][1])
                d = max(abs(dx), abs(dy))
                if d <= SNAP_PIXELS and (best is None or d < best[0]):
                    best = (d, dx, dy)
        if best is None:
            return 0
        self.move_group(group, best[1], best[2])
        made = 0
        for a in group:
            for b in self.neighbours(a):
                if (b["r"], b["c"]) in members or b["placed"]:
                    continue
                dx = (b["pos"][0] - a["pos"][0]) - (b["home"][0] - a["home"][0])
                dy = (b["pos"][1] - a["pos"][1]) - (b["home"][1] - a["home"][1])
                if abs(dx) < 1.0 and abs(dy) < 1.0:
                    self.links.add(frozenset(((a["r"], a["c"]),
                                              (b["r"], b["c"]))))
                    made += 1
        return made

    # ---- dragging ---------------------------------------------------------
    def piece_at(self, px, py):
        """The topmost piece with a visible pixel under the point (a piece's
        box is bigger than the piece: its corners are see-through)."""
        for item in reversed(self.canvas.find_overlapping(px, py, px, py)):
            for p in self.pieces:
                if p["item"] == item:
                    lx = int(px - p["pos"][0])
                    ly = int(py - p["pos"][1])
                    w, h = p["img"].size
                    if 0 <= lx < w and 0 <= ly < h and \
                            p["img"].getpixel((lx, ly))[3] > 0:
                        return p
                    break
        return None

    def on_motion(self, event):
        self.mouse = (event.x, event.y)

    def on_press(self, event):
        self.canvas.focus_set()
        self.mouse = (event.x, event.y)
        p = self.piece_at(event.x, event.y)
        if p is None or self.done:
            return
        if p["placed"]:
            self.set_msg("status.jigsaw.locked")
            return
        grp = self.group_of(p)
        self.drag = dict(group=grp, press=(event.x, event.y),
                         start=[q["pos"] for q in grp])
        for q in grp:
            self.canvas.tag_raise(q["item"])
        self.started_at = self.started_at or time.time()

    def on_drag(self, event):
        self.mouse = (event.x, event.y)
        if not self.drag:
            return
        ddx = event.x - self.drag["press"][0]
        ddy = event.y - self.drag["press"][1]
        for q, (sx, sy) in zip(self.drag["group"], self.drag["start"]):
            q["pos"] = (sx + ddx, sy + ddy)
            self.canvas.coords(q["item"], q["pos"][0], q["pos"][1])

    def on_release(self, event):
        if not self.drag:
            return
        grp = self.drag["group"]
        self.drag = None
        if self.snap_to_board(grp):
            self.set_msg("status.jigsaw.snap")
            log("jigsaw: %d piece(s) placed" % len(grp))
        else:
            made = self.join(grp)
            merged = self.group_of(grp[0])
            for q in merged:
                self.canvas.tag_raise(q["item"])
            self.remember_spot(merged)
            if made:
                self.set_msg("status.jigsaw.join")
                log("jigsaw: joined, group of %d" % len(merged))
            else:
                self.set_msg("status.jigsaw.ready")
        self.update_counters()
        self.check_done()

    def remember_spot(self, group):
        """Where the group lies in the tray, kept so that cutting again after
        a resize puts it back in the same place (the first piece is the
        group's anchor, see anchor_groups)."""
        group[0]["frac"] = self.frac_of(group[0])

    def frac_of(self, p):
        tx, ty, tw, th = self.tray
        w, h = p["size"]
        return (min(1.0, max(0.0, (p["pos"][0] - tx) / max(1.0, tw - w))),
                min(1.0, max(0.0, (p["pos"][1] - ty) / max(1.0, th - h))))

    def on_right(self, event):
        """The right button sends a piece back to the tray."""
        self.send_back(self.piece_at(event.x, event.y))

    def send_back(self, p):
        """Just this piece - it comes loose from its group, the rest stay."""
        if p is None or self.done:
            return
        self.unlink([p])
        rnd = random.Random()
        p["placed"] = False
        p["frac"] = (rnd.random(), rnd.random())
        p["pos"] = self.tray_spot(p["frac"][0], p["frac"][1], p)
        self.canvas.coords(p["item"], p["pos"][0], p["pos"][1])
        self.canvas.tag_raise(p["item"])
        self.set_msg("status.jigsaw.back")
        self.update_counters()

    def handle_key(self, event):
        sym = (event.keysym or "").lower()
        if sym in ("delete", "backspace", "kp_delete"):
            self.send_back(self.piece_at(*self.mouse))

    # ---- counting and finishing ------------------------------------------
    def placed_count(self):
        return sum(1 for p in self.pieces if p["placed"])

    def update_counters(self):
        try:
            self.lbl_count.configure(text=T("status.jigsaw.count",
                                            self.placed_count(),
                                            len(self.pieces),
                                            fmt_time(self.elapsed)))
        except Exception:
            pass

    def tick(self):
        if self.pieces and not self.done:
            if self.started_at:
                self.elapsed = time.time() - self.started_at
            self.update_counters()
            self.after_t(500, self.tick)

    def check_done(self):
        if self.pieces and self.placed_count() == len(self.pieces):
            self.done = True
            if self.started_at:
                self.elapsed = time.time() - self.started_at
            log("jigsaw: finished %d pieces in %s"
                % (len(self.pieces), fmt_time(self.elapsed)))
            self.set_msg("status.jigsaw.done", len(self.pieces),
                         fmt_time(self.elapsed))
            self.draw_banner()

    def draw_banner(self):
        cw = max(60, self.canvas.winfo_width())
        x, y = cw / 2.0, 44
        self.canvas.create_rectangle(x - 200, y - 32, x + 200, y + 34,
                                     fill="#fff3c4", outline=STARC, width=3)
        self.canvas.create_text(x, y - 6, text=T("win.bravo"), fill=GOODC,
                                font=FONT_HUGE)
        self.canvas.create_text(x, y + 22,
                                text=T("status.jigsaw.done",
                                       len(self.pieces),
                                       fmt_time(self.elapsed)),
                                fill=TEXTC, font=FONT_SMALL)

    # ---- text -------------------------------------------------------------
    def set_msg(self, key, *args):
        self._msg = key
        self._msg_args = args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def retranslate_view(self):
        self.set_msg(self._msg, *self._msg_args)
        self.update_counters()

# *************** DEL 19b - SPOT THE FIVE DIFFERENCES (PART 4) ***************
# Two copies of one picture side by side.  FIVE things are different between
# them, and the player clicks on each one - in either picture - until all five
# are found.
#
# WHERE THE PUZZLES COME FROM.  Not from new drawings: a puzzle is a PICTURE
# THAT ALREADY EXISTS (DEL 17, with its named parts) plus a list of
# differences, each one a small instruction about one named part:
#
#   hide     the part is missing in the other picture
#   colour   the part has another colour (only parts that can be filled in)
#   move     the part sits somewhere else (dx, dy in picture units)
#   scale    the part is bigger or smaller (factor, around its own middle)
#   add      something extra is drawn on top (its own shapes and name)
#
# A puzzle lists 5 to 10 candidate differences and every round picks FIVE of
# them at random, and also flips which picture is on the left.  That is what
# makes one puzzle worth playing many times - 252 different rounds out of ten
# candidates - and why the child cannot learn "it is always the right-hand one".
#
# HOW A CLICK IS JUDGED.  In picture units, not pixels, so it is the same at
# any window size.  A difference owns the SHAPES of its part (in the original
# AND in the changed picture, so "the sun is gone" counts where the sun used
# to be) plus SPOT_PAD of slack, because a four-year-old does not aim.  When
# several differences claim the same point the one that is drawn on top wins,
# and a click that lands on something drawn ABOVE the difference that is not
# itself a difference (the dinosaur in front of the sky) is a miss - otherwise
# clicking the dinosaur would find "the sky has another colour".
#
# The same rules are checked for every puzzle that comes in a pack (DEL 21),
# and --selftest renders both pictures and compares the PIXELS, so a
# difference that does not show, or a change that was not asked for, is found
# before a child sees it.

SPOT_COUNT = 5                  # differences a round shows (and finds)
SPOT_POOL_MIN = 5               # a puzzle lists at least this many ...
SPOT_POOL_MAX = 10              # ... and at most this many candidates
SPOT_CHANGES = ("hide", "colour", "move", "scale", "add")
SPOT_PAD = 14.0                 # slack around a shape, in picture units
SPOT_MIN_SIDE = 0.045           # a difference must be this big (of the
                                # picture's longer side) to be seen at all
SPOT_MIN_COLOUR_GAP = 110.0     # RGB distance (0..441) between two colours
SPOT_GRID = 40                  # cells across for the overlap test
RING = "#e53935"                # the circle round a difference that was found

SPOTS = []                      # the puzzles, in the order they are offered
SPOT_BY_KEY = {}


# ---- geometry on primitives (works on built-in and on pack JSON alike) ------

def prim_bbox(pr):
    if pr["kind"] in ("poly", "line"):
        pts = _prim_points(pr)
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        return (min(xs), min(ys), max(xs), max(ys))
    b = pr["box"]
    return (min(b[0], b[2]), min(b[1], b[3]), max(b[0], b[2]), max(b[1], b[3]))


def prims_bbox(prims):
    boxes = [prim_bbox(pr) for pr in prims]
    return (min(b[0] for b in boxes), min(b[1] for b in boxes),
            max(b[2] for b in boxes), max(b[3] for b in boxes))


def union_box(a, b):
    return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))


def map_prims(prims, fn):
    """A copy of a primitive list with every point run through fn."""
    out = []
    for pr in prims:
        c = dict(pr)
        if pr["kind"] in ("poly", "line"):
            c["pts"] = [fn(p) for p in pr["pts"]]
        else:
            x0, y0 = fn((pr["box"][0], pr["box"][1]))
            x1, y1 = fn((pr["box"][2], pr["box"][3]))
            c["box"] = (x0, y0, x1, y1)
        out.append(c)
    return out


def shift_prims(prims, dx, dy):
    return map_prims(prims, lambda p: (p[0] + dx, p[1] + dy))


def scale_prims(prims, factor, cx, cy):
    return map_prims(prims, lambda p: (cx + (p[0] - cx) * factor,
                                       cy + (p[1] - cy) * factor))


def prim_shapes(prims):
    """What a click can hit: ("poly", pts), ("oval", cx, cy, rx, ry) and
    ("line", pts, width).  An arc counts as its oval - generous on purpose."""
    out = []
    for pr in prims:
        k = pr["kind"]
        if k == "poly":
            out.append(("poly", list(_prim_points(pr))))
        elif k == "line":
            out.append(("line", list(_prim_points(pr)),
                        max(2.0, float(pr.get("w", 2.0)))))
        else:
            x0, y0, x1, y1 = prim_bbox(pr)
            out.append(("oval", (x0 + x1) / 2.0, (y0 + y1) / 2.0,
                        (x1 - x0) / 2.0, (y1 - y0) / 2.0))
    return out


def _in_poly(pts, x, y):
    inside = False
    n = len(pts)
    j = n - 1
    for i in range(n):
        xi, yi = pts[i][0], pts[i][1]
        xj, yj = pts[j][0], pts[j][1]
        if (yi > y) != (yj > y) and \
                x < (xj - xi) * (y - yi) / float(yj - yi) + xi:
            inside = not inside
        j = i
    return inside


def _seg_dist(px, py, ax, ay, bx, by):
    dx, dy = bx - ax, by - ay
    ln = dx * dx + dy * dy
    t = 0.0 if ln <= 0 else max(0.0, min(1.0, ((px - ax) * dx +
                                               (py - ay) * dy) / ln))
    return math.hypot(px - (ax + t * dx), py - (ay + t * dy))


def shape_hit(sh, x, y, pad=0.0):
    kind = sh[0]
    if kind == "oval":
        rx, ry = sh[3] + pad, sh[4] + pad
        if rx <= 0 or ry <= 0:
            return False
        return ((x - sh[1]) / rx) ** 2 + ((y - sh[2]) / ry) ** 2 <= 1.0
    pts = sh[1]
    if kind == "poly":
        if len(pts) >= 3 and _in_poly(pts, x, y):
            return True
        reach = pad
    else:
        reach = pad + sh[2] / 2.0
    if reach <= 0:
        return False
    n = len(pts)
    last = n if kind == "poly" else n - 1
    for i in range(last):
        a, b = pts[i], pts[(i + 1) % n]
        if _seg_dist(x, y, a[0], a[1], b[0], b[1]) <= reach:
            return True
    return False


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


def colour_gap(a, b):
    ra, rb = hex_rgb(a), hex_rgb(b)
    return math.sqrt(sum((ra[i] - rb[i]) ** 2 for i in range(3)))


# ---- a picture as the spot view draws it, and the changed copy ---------------

def spot_parts(pic):
    """The picture in its OWN colours: [dict(id, prims, hint, fillable)]."""
    return [dict(id=pt["id"], prims=pt["prims"], hint=pt.get("hint"),
                 fillable=bool(pt.get("fillable", True)))
            for pt in pic["parts"]]


def spot_apply(parts, diffs):
    """The second picture: the same parts with every difference applied."""
    out = [dict(p) for p in parts]
    where = {p["id"]: i for i, p in enumerate(out)}
    extra = []
    for k, d in enumerate(diffs):
        ch = d["change"]
        if ch == "add":
            extra.append(dict(id="+%d" % k, prims=d["prims"], hint=None,
                              fillable=False))
            continue
        i = where[d["part"]]
        if out[i] is None:
            continue
        if ch == "hide":
            out[i] = None
        elif ch == "colour":
            out[i]["hint"] = d["to"]
        elif ch == "move":
            out[i]["prims"] = shift_prims(parts[i]["prims"], d["dx"], d["dy"])
        elif ch == "scale":
            x0, y0, x1, y1 = prims_bbox(parts[i]["prims"])
            out[i]["prims"] = scale_prims(parts[i]["prims"], d["factor"],
                                          (x0 + x1) / 2.0, (y0 + y1) / 2.0)
    return [p for p in out if p is not None] + extra


def shape_bbox(sh):
    if sh[0] == "oval":
        return (sh[1] - sh[3], sh[2] - sh[4], sh[1] + sh[3], sh[2] + sh[4])
    pts = sh[1]
    xs = [p[0] for p in pts]
    ys = [p[1] for p in pts]
    return (min(xs), min(ys), max(xs), max(ys))


def _covered(occluders, x, y):
    for bb, sh in occluders:
        if bb[0] <= x <= bb[2] and bb[1] <= y <= bb[3] and                 shape_hit(sh, x, y, 0.0):
            return True
    return False


def _visible_box(shapes, occluders, bbox):
    """The box round what of a difference can actually be SEEN: its shapes
    minus whatever is drawn in front of them.  The ring goes round this, so
    the lava that mostly hides behind a dinosaur gets a ring round the part
    that shows, not round the dinosaur's head."""
    bw, bh = bbox[2] - bbox[0], bbox[3] - bbox[1]
    cell = max(8.0, max(bw, bh) / 28.0)
    x0 = y0 = 10 ** 9
    x1 = y1 = -10 ** 9
    gx = bbox[0] + cell / 2.0
    while gx < bbox[2]:
        gy = bbox[1] + cell / 2.0
        while gy < bbox[3]:
            if any(shape_hit(sh, gx, gy, 0.0) for sh in shapes) and                     not _covered(occluders, gx, gy):
                x0, y0 = min(x0, gx - cell / 2.0), min(y0, gy - cell / 2.0)
                x1, y1 = max(x1, gx + cell / 2.0), max(y1, gy + cell / 2.0)
            gy += cell
        gx += cell
    if x1 < x0:
        return bbox
    return (x0, y0, x1, y1)


def spot_regions(parts, diffs):
    """Where each difference lives, for clicking, for ringing and for the
    overlap test.

    Each region: shapes (original AND changed place), z (how far up the
    drawing order it sits; an added thing is on top of everything), bbox,
    seen (the part of the bbox that is not hidden behind something) and
    occluders - the filled shapes drawn above it that are not themselves
    differences, as (bbox, shape) pairs."""
    ids = [p["id"] for p in parts]
    picked = set(d["part"] for d in diffs if d.get("part"))
    regions = []
    for d in diffs:
        ch = d["change"]
        if ch == "add":
            bb = prims_bbox(d["prims"])
            regions.append(dict(shapes=prim_shapes(d["prims"]), z=10 ** 6,
                                bbox=bb, seen=bb, occluders=[]))
            continue
        i = ids.index(d["part"])
        src = parts[i]["prims"]
        shapes = prim_shapes(src)
        bbox = prims_bbox(src)
        if ch == "move":
            moved = shift_prims(src, d["dx"], d["dy"])
            shapes += prim_shapes(moved)
            bbox = union_box(bbox, prims_bbox(moved))
        elif ch == "scale":
            cx, cy = (bbox[0] + bbox[2]) / 2.0, (bbox[1] + bbox[3]) / 2.0
            grown = scale_prims(src, d["factor"], cx, cy)
            shapes += prim_shapes(grown)
            bbox = union_box(bbox, prims_bbox(grown))
        occ = []
        for p in parts[i + 1:]:
            if p["id"] in picked:
                continue
            for s in prim_shapes(p["prims"]):
                if s[0] != "line":
                    occ.append((shape_bbox(s), s))
        regions.append(dict(shapes=shapes, z=i, bbox=bbox, occluders=occ,
                            seen=_visible_box(shapes, occ, bbox)))
    return regions


# ---- round-time variants: the same difference, a different look --------------
# ToDo: added 2026-10-23.  A puzzle's pool says WHICH part changes; each round
# now also re-rolls HOW, so ten candidates are no longer 252 rounds that all
# look alike.  The author's own values stay one of the options.  Every roll is
# held to the same rules a pack is checked against (colour gap, size, inside
# the picture, no two differences on top of each other); if no roll passes
# in SPOT_VARY_TRIES tries the round uses the author's values unchanged.

SPOT_PALETTE = ("#e53935", "#fb8c00", "#fdd835", "#43a047", "#1e88e5",
                "#8e24aa", "#ec407a", "#00acc1", "#6d4c41", "#212121",
                "#9ccc65", "#ffffff")
SPOT_SCALES = (0.45, 0.55, 0.65, 1.4, 1.6, 1.8, 2.0)
SPOT_VARY_TRIES = 12


def _vary_one(rnd, d, part, w, h):
    """One difference with its colour / distance / size re-rolled."""
    ch = d["change"]
    new = dict(d)
    own = prims_bbox(part["prims"])
    side = max(own[2] - own[0], own[3] - own[1])
    big = max(w, h)

    def inside(b):
        return b[0] >= -10 and b[1] >= -10 and b[2] <= w + 10 and b[3] <= h + 10

    if ch == "colour":
        opts = [c for c in SPOT_PALETTE
                if colour_gap(part["hint"], c) >= SPOT_MIN_COLOUR_GAP + 20]
        new["to"] = rnd.choice(opts + [d["to"]])
    elif ch == "scale":
        cx, cy = (own[0] + own[2]) / 2.0, (own[1] + own[3]) / 2.0
        opts = []
        for f in SPOT_SCALES:
            if side * f < SPOT_MIN_SIDE * big:
                continue
            if inside(prims_bbox(scale_prims(part["prims"], f, cx, cy))):
                opts.append(f)
        new["factor"] = rnd.choice(opts + [d["factor"]])
    elif ch == "move":
        need = max(0.05 * big, 0.35 * side)
        dist = rnd.uniform(need * 1.2, max(need * 1.2, 0.22 * big))
        opts = [(d["dx"], d["dy"]), (-d["dx"], d["dy"]), (dist, 0.0), (-dist, 0.0)]
        good = []
        for dx, dy in opts:
            if math.hypot(dx, dy) < need:
                continue
            if inside(prims_bbox(shift_prims(part["prims"], dx, dy))):
                good.append((dx, dy))
        if good:
            new["dx"], new["dy"] = rnd.choice(good)
    return new


def spot_vary(rnd, pic, parts, diffs):
    """The five chosen differences, re-rolled (see the note above)."""
    w, h = float(pic["w"]), float(pic["h"])
    byid = dict((p["id"], p) for p in parts)
    for _ in range(SPOT_VARY_TRIES):
        cand = [_vary_one(rnd, d, byid[d["part"]], w, h) if d.get("part")
                else d for d in diffs]
        cells = [_region_cells(rg, w, h) for rg in spot_regions(parts, cand)]
        clash = False
        for i in range(len(cells)):
            for j in range(i + 1, len(cells)):
                smaller = min(len(cells[i]), len(cells[j]))
                if smaller and len(cells[i] & cells[j]) > 0.25 * smaller:
                    clash = True
        if not clash:
            return cand
    return list(diffs)


def draw_spot_parts(canvas, parts, ox, oy, scale, tags=()):
    for pt in parts:
        over = None
        if pt["fillable"] and pt.get("hint"):
            over = {i: pt["hint"] for i, pr in enumerate(pt["prims"])
                    if pr["kind"] in ("poly", "oval")}
        draw_scene(canvas, pt["prims"], ox, oy, scale, tags=tags,
                   fill_over=over)


def draw_spot_parts_pil(draw, parts, ox, oy, scale):
    for pt in parts:
        over = None
        if pt["fillable"] and pt.get("hint"):
            over = {i: pt["hint"] for i, pr in enumerate(pt["prims"])
                    if pr["kind"] in ("poly", "oval")}
        draw_scene_pil(draw, pt["prims"], ox, oy, scale, fill_over=over)


class Lbl(object):
    """A name that exists in all three languages, shown in the current one.

    It goes into T() as an argument, so a status line that names "the sun"
    is written again in the right language when the language is switched."""

    __slots__ = ("row",)

    def __init__(self, row):
        self.row = tuple(row)

    def __str__(self):
        lang = SETTINGS.get("language", "sv")
        return self.row[LANGS.index(lang) if lang in LANGS else 1]

    def __format__(self, spec):
        return str(self)


def spot_message(pic, d):
    """(text key, name) for the line that says what the difference was."""
    if d["change"] == "add":
        return "spot.add", Lbl(d["name"])
    for pt in pic["parts"]:
        if pt["id"] == d["part"]:
            return "spot." + d["change"], Lbl(pt["label"])
    return "spot." + d["change"], Lbl(("?", "?", "?"))


class SpotRound(object):
    """One round: five differences chosen from the puzzle's pool.  No tkinter
    in here, so --selftest can play thousands of them."""

    def __init__(self, spot, seed):
        rnd = random.Random(seed)
        self.spot = spot
        self.seed = seed
        self.pic = PICTURE_BY_KEY[spot["picture"]]
        pool = spot["diffs"]
        idx = sorted(rnd.sample(range(len(pool)), SPOT_COUNT))
        picked = [pool[i] for i in idx]
        self.swap = rnd.random() < 0.5          # which picture is on the left
        self.parts_a = spot_parts(self.pic)     # the original
        self.diffs = spot_vary(rnd, self.pic, self.parts_a, picked)
        self.parts_b = spot_apply(self.parts_a, self.diffs)
        self.regions = spot_regions(self.parts_a, self.diffs)
        if self.swap:
            self.left_parts, self.right_parts = self.parts_b, self.parts_a
        else:
            self.left_parts, self.right_parts = self.parts_a, self.parts_b

    def hit_test(self, x, y):
        """Which difference (index) a click at picture point (x, y) found."""
        cands = [k for k, rg in enumerate(self.regions)
                 if any(shape_hit(sh, x, y, SPOT_PAD) for sh in rg["shapes"])]
        if not cands:
            return None
        k = max(cands, key=lambda i: self.regions[i]["z"])
        if _covered(self.regions[k]["occluders"], x, y):
            return None                  # something in front, not a difference
        return k

    @staticmethod
    def stars(misses, hints, answer_shown):
        if answer_shown:
            return 1
        penalty = misses + 2 * hints
        return 3 if penalty <= 3 else (2 if penalty <= 8 else 1)


class SpotView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.round = None
        self.found = set()
        self.misses = 0
        self.hints = 0
        self.answer = False
        self.answer_used = False
        self.done = False
        self.started_at = 0.0
        self.elapsed = 0.0
        self.rects = []                # [(ox, oy, scale)] left, right
        self._banner_btn = None
        self._timers = []
        self._msg = "status.spot.ready"
        self._msg_args = ()
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.new_round(first=True)

    # ---- building ---------------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row1 = tk.Frame(bar, bg=CREAM)
        row1.pack(side="top", fill="x", padx=8, pady=(6, 2))
        row2 = tk.Frame(bar, bg=CREAM)
        row2.pack(side="top", fill="x", padx=8, pady=(0, 6))

        tbutton(row1, "btn.back", self.app.show_start).pack(side="left")
        lab = tk.Label(row1, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.picture") + 1, anchor="e")
        reg(lab, "lbl.picture")
        lab.pack(side="left", padx=(12, 2))
        self.opt_spot = KeyedOption(
            row1, [(s["key"], "spotname." + s["key"]) for s in SPOTS],
            SETTINGS.get("spot_puzzle", SPOTS[0]["key"]), self.on_puzzle)
        self.opt_spot.pack(side="left", padx=(0, 14))
        tbutton(row1, "btn.newround", self.on_new).pack(side="left", padx=2)
        tbutton(row1, "btn.hint", self.give_hint).pack(side="left", padx=2)
        self.btn_answer = tbutton(row1, "btn.hint.show", self.toggle_answer,
                                  extra_keys=("btn.hint.hide",))
        self.btn_answer.pack(side="left", padx=2)

        self.dots = tk.Canvas(row2, width=SPOT_COUNT * 34 + 6, height=32,
                              bg=CREAM, highlightthickness=0)
        self.dots.pack(side="left")
        tbutton(row2, "btn.about",
                lambda: show_about(self.app.root)).pack(side="right",
                                                        padx=(6, 0))
        tbutton(row2, "btn.help",
                lambda: show_help(self.app.root)).pack(side="right", padx=6)
        tbutton(row2, "btn.settings",
                lambda: show_settings(self.app.root,
                                      self.app)).pack(side="right", padx=6)

        self.canvas = tk.Canvas(self, bg=PAPER, highlightthickness=0,
                                takefocus=1, cursor="crosshair")
        self.canvas.pack(side="top", fill="both", expand=True)

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_count = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                  font=FONT_UI_B, anchor="e",
                                  width=width_for("status.spot.count") + 8)
        self.lbl_count.pack(side="right", padx=10, pady=5)

        self.canvas.bind("<Configure>", lambda e: self.redraw())
        self.canvas.bind("<Button-1>", self.on_click)
        on_retranslate(self.retranslate_view)

    # ---- timers -----------------------------------------------------------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- rounds -----------------------------------------------------------
    def progress(self):
        return bool(self.found) and not self.done

    def on_new(self):
        if self.progress() and SETTINGS["confirm_new"] and \
                not ask_yes_no(self.app.root, "ask.newround"):
            return
        self.new_round()

    def on_puzzle(self, value):
        if self.progress() and SETTINGS["confirm_new"] and \
                not ask_yes_no(self.app.root, "ask.newround"):
            self.opt_spot.set(self.round.spot["key"])
            return
        SETTINGS["spot_puzzle"] = value
        save_settings()
        self.new_round()

    def new_round(self, first=False):
        self.cancel_timers()
        key = SETTINGS.get("spot_puzzle", SPOTS[0]["key"])
        spot = SPOT_BY_KEY.get(key) or SPOTS[0]
        if first:
            self.opt_spot.set(spot["key"])
        seed = random.randrange(10 ** 6)
        self.round = SpotRound(spot, seed)
        self.found = set()
        self.misses = self.hints = 0
        self.answer = self.answer_used = self.done = False
        self.started_at = 0.0
        self.elapsed = 0.0
        reg(self.btn_answer, "btn.hint.show")
        log("---- spot: puzzle=%s seed=%d differences=%s swap=%s"
            % (spot["key"], seed, ", ".join(
                "%s:%s" % (d["change"], d.get("part") or d["name"][0])
                for d in self.round.diffs), self.round.swap))
        self.set_msg("status.spot.ready")
        self.update_counters()
        self.redraw()

    # ---- geometry ---------------------------------------------------------
    def layout(self):
        r = self.round
        w, h = float(r.pic["w"]), float(r.pic["h"])
        cw = max(100, self.canvas.winfo_width())
        ch = max(100, self.canvas.winfo_height())
        pad = 14.0
        side = min((cw - 3 * pad) / (2 * w), (ch - 2 * pad) / h)
        stack = min((cw - 2 * pad) / w, (ch - 3 * pad) / (2 * h))
        if side >= stack:
            s = max(0.05, side)
            x0 = (cw - (2 * w * s + pad)) / 2.0
            y0 = (ch - h * s) / 2.0
            self.rects = [(x0, y0, s), (x0 + w * s + pad, y0, s)]
        else:
            s = max(0.05, stack)
            x0 = (cw - w * s) / 2.0
            y0 = (ch - (2 * h * s + pad)) / 2.0
            self.rects = [(x0, y0, s), (x0, y0 + h * s + pad, s)]

    def pick(self, px, py):
        w, h = self.round.pic["w"], self.round.pic["h"]
        for ox, oy, s in self.rects:
            if ox <= px <= ox + w * s and oy <= py <= oy + h * s:
                return (px - ox) / s, (py - oy) / s
        return None

    # ---- drawing ----------------------------------------------------------
    def redraw(self):
        if not self.round:
            return
        c = self.canvas
        c.delete("all")
        self.drop_banner_button()
        self.layout()
        r = self.round
        w, h = r.pic["w"], r.pic["h"]
        for (ox, oy, s), parts in zip(self.rects,
                                      (r.left_parts, r.right_parts)):
            c.create_rectangle(ox - 6, oy - 6, ox + w * s + 6, oy + h * s + 6,
                               fill="#efe2c4", outline="")
            c.create_rectangle(ox, oy, ox + w * s, oy + h * s, fill="#ffffff",
                               outline="#e0cfa8")
            draw_spot_parts(c, parts, ox, oy, s)
        for k in sorted(self.found):
            self.draw_ring(k, RING, 4, None, ("ring",))
        if self.answer:
            for k in range(SPOT_COUNT):
                if k not in self.found:
                    self.draw_ring(k, "#fb8c00", 3, (7, 4), ("ring",))
        self.draw_dots()
        if self.done:
            self.draw_banner()

    def draw_ring(self, k, colour, width, dash, tags):
        x0, y0, x1, y1 = self.round.regions[k]["seen"]
        cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0
        rx = max(34.0, (x1 - x0) / 2.0 * 1.15 + 12)
        ry = max(34.0, (y1 - y0) / 2.0 * 1.15 + 12)
        w, h = self.round.pic["w"], self.round.pic["h"]
        # keep the ring inside the picture: a tail that reaches the edge must
        # not get a ring that sticks out into the margin
        bx0, bx1 = max(2.0, cx - rx), min(w - 2.0, cx + rx)
        by0, by1 = max(2.0, cy - ry), min(h - 2.0, cy + ry)
        items = []
        for ox, oy, s in self.rects:
            kw = dict(outline=colour, width=width, tags=tags)
            if dash:
                kw["dash"] = dash
            items.append(self.canvas.create_oval(
                ox + bx0 * s, oy + by0 * s, ox + bx1 * s, oy + by1 * s, **kw))
        return items

    def draw_dots(self):
        d = self.dots
        d.delete("all")
        for i in range(SPOT_COUNT):
            x = 20 + i * 34
            on = i < len(self.found)
            d.create_oval(x - 12, 4, x + 12, 28, fill=(RING if on else "#ffffff"),
                          outline=WALLC, width=2)
            if on:
                d.create_line(x - 6, 16, x - 1, 22, x + 7, 10, fill="#ffffff",
                              width=3, capstyle="round", joinstyle="round")

    def drop_banner_button(self):
        """canvas.delete() removes the button's window ITEM, not the button."""
        if self._banner_btn is not None:
            try:
                self._banner_btn.destroy()
            except Exception:
                pass
            self._banner_btn = None

    def draw_banner(self):
        c = self.canvas
        cw = max(60, c.winfo_width())
        stars = self.round.stars(self.misses, self.hints, self.answer_used)
        x, y = cw / 2.0, 46
        c.create_rectangle(x - 190, y - 34, x + 190, y + 40, fill="#fff3c4",
                           outline=STARC, width=3)
        c.create_text(x - 100, y, text=T("win.bravo"), fill=GOODC,
                      font=("Segoe UI", 20, "bold"))
        draw_stars(c, x + 80, y - 8, 17, stars)
        c.create_text(x + 80, y + 24,
                      text=cap(T("status.spot.done", SPOT_COUNT,
                                 fmt_time(self.elapsed))),
                      fill=TEXTC, font=FONT_SMALL)
        self._banner_btn = tbutton(c, "win.again", self.new_round)
        c.create_window(x, y + 66, window=self._banner_btn)

    # ---- input ------------------------------------------------------------
    def on_click(self, event):
        self.canvas.focus_set()
        if self.done or not self.round:
            return
        got = self.pick(event.x, event.y)
        if got is None:
            return
        if not self.started_at:
            self.started_at = time.time()
            self.after_t(500, self.tick)
        k = self.round.hit_test(got[0], got[1])
        if k is None:
            self.misses += 1
            self.set_msg("status.spot.miss")
            self.flash_miss(event.x, event.y)
            self.update_counters()
            return
        if k in self.found:
            return
        self.found.add(k)
        key, name = spot_message(self.round.pic, self.round.diffs[k])
        self.set_msg(key, name)
        log("spot: found %d of %d: %s %s"
            % (len(self.found), SPOT_COUNT, self.round.diffs[k]["change"],
               name.row[0]))
        self.update_counters()
        if len(self.found) == SPOT_COUNT:
            self.finish()
        else:
            self.redraw()

    def flash_miss(self, x, y):
        c = self.canvas
        r = 11
        c.create_line(x - r, y - r, x + r, y + r, fill="#c62828", width=5,
                      capstyle="round", tags=("miss",))
        c.create_line(x - r, y + r, x + r, y - r, fill="#c62828", width=5,
                      capstyle="round", tags=("miss",))
        self.after_t(650, lambda: c.delete("miss"))

    def give_hint(self):
        if self.done or not self.round:
            return
        left = [k for k in range(SPOT_COUNT) if k not in self.found]
        if not left:
            return
        k = random.choice(left)
        self.hints += 1
        if not self.started_at:
            self.started_at = time.time()
            self.after_t(500, self.tick)
        self.set_msg("status.spot.hint")
        self.update_counters()
        items = self.draw_ring(k, "#1e88e5", 5, None, ("blink",))
        self._blink(items, 0)

    def _blink(self, items, n):
        try:
            state = "hidden" if n % 2 == 0 else "normal"
            for it in items:
                self.canvas.itemconfigure(it, state=state)
        except Exception:
            return
        if n < 9:
            self.after_t(260, lambda: self._blink(items, n + 1))
        else:
            self.canvas.delete("blink")

    def toggle_answer(self):
        if self.done or not self.round:
            return
        self.answer = not self.answer
        if self.answer:
            self.answer_used = True
            self.set_msg("status.spot.answer")
        else:
            self.set_msg("status.spot.ready")
        reg(self.btn_answer, "btn.hint.hide" if self.answer
            else "btn.hint.show")
        self.redraw()

    def handle_key(self, event):
        if self.done and (event.keysym or "").lower() in (
                "return", "kp_enter", "space"):
            self.new_round()

    # ---- counting and finishing ------------------------------------------
    def tick(self):
        if self.round and not self.done and self.started_at:
            self.elapsed = time.time() - self.started_at
            self.update_counters()
            self.after_t(500, self.tick)

    def update_counters(self):
        try:
            self.lbl_count.configure(text=T("status.spot.count",
                                            len(self.found), SPOT_COUNT,
                                            self.misses,
                                            fmt_time(self.elapsed)))
        except Exception:
            pass

    def finish(self):
        self.done = True
        self.answer = False
        if self.started_at:
            self.elapsed = time.time() - self.started_at
        stars = self.round.stars(self.misses, self.hints, self.answer_used)
        record_solved("spot", self.elapsed, stars)
        log("spot: finished puzzle=%s misses=%d hints=%d answer=%s time=%s "
            "stars=%d" % (self.round.spot["key"], self.misses, self.hints,
                          self.answer_used, fmt_time(self.elapsed), stars))
        self.set_msg("status.spot.done", SPOT_COUNT, fmt_time(self.elapsed))
        self.update_counters()
        self.redraw()

    # ---- text -------------------------------------------------------------
    def set_msg(self, key, *args):
        self._msg = key
        self._msg_args = args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def retranslate_view(self):
        self.set_msg(self._msg, *self._msg_args)
        self.update_counters()
        if self.done:
            self.redraw()


# *************** DEL 19c - MATCHING PAIRS (PART 5) ***************************
# "Para ihop": a column of pictures on the left, a shuffled column of partners
# on the right - draw a line from each one to the one that belongs with it.
# The dog and its kennel, the mouse and its cheese.  A set is either
#
#   pairs      [["dog", "kennel"], ["mouse", "cheese"], ...]  two DIFFERENT
#              drawings that belong together, or
#   shadows    ["dog", "cat", "mouse", ...]  an animal and its black SHADOW,
#              which is the very same drawing with every colour turned black -
#              so a set of shadows costs no new art at all.
#
# Every drawing is an ordinary ART drawing (DEL 09), built in or from a pack,
# so what a set can pair up grows with every pack.  Each round takes 3 to 6
# pairs at random from the set (the "Pairs" setting), shuffles BOTH columns
# (and makes sure no partner happens to stand straight across from its mate),
# so the same set can be played again and again.
#
# THE ANSWER IS CHECKED AT ONCE.  A right pair stays joined by a coloured
# line; a wrong one jumps back and counts as a miss.  That is kinder to a
# child than a page of crossed lines with a verdict at the end, and it means
# the picture on the screen is never wrong.
#
# Two ways to make a line, because a small hand and a mouse do not always
# drag: press on one picture and pull to the other, or click one picture and
# then the other.

MATCH_MIN, MATCH_MAX = 3, 8     # pairs in a set
MATCH_CHOICES = (3, 4, 5, 6)    # pairs in a round (the "Pairs" setting)
SHADOW_COLOUR = "#37474f"
PAIR_COLOURS = ["#ef5350", "#42a5f5", "#66bb6a", "#ffa726", "#ab47bc",
                "#26c6da", "#ec407a", "#8d6e63"]

MATCHES = []
MATCH_BY_KEY = {}

_SHADOWS = {}


def shadow_prims(prims):
    """The same drawing with every colour turned into one dark one."""
    out = []
    for pr in prims:
        c = dict(pr)
        if pr["kind"] in ("poly", "oval"):
            c["fill"] = SHADOW_COLOUR
        c["line"] = SHADOW_COLOUR
        out.append(c)
    return out


def art_prims(key, shadow=False):
    if not shadow:
        return ART[key]
    if key not in _SHADOWS:
        _SHADOWS[key] = shadow_prims(ART[key])
    return _SHADOWS[key]


class MatchRound(object):
    """One round of matching.  No tkinter in here either (see SpotRound)."""

    def __init__(self, mset, want, seed):
        rnd = random.Random(seed)
        self.mset = mset
        self.seed = seed
        self.kind = mset["kind"]
        pairs = list(mset["pairs"])
        n = max(1, min(max(MATCH_MIN, int(want)), len(pairs)))
        self.items = [pairs[i] for i in rnd.sample(range(len(pairs)), n)]
        self.n = n
        self.left = list(range(n))
        self.right = list(range(n))
        rnd.shuffle(self.left)
        for _ in range(200):
            rnd.shuffle(self.right)
            if n < 3 or all(self.left[i] != self.right[i] for i in range(n)):
                break
        self.matched = {}                # pair id -> True

    def art_key(self, side, pid):
        return self.items[pid][side]

    def is_shadow(self, side):
        return self.kind == "shadows" and side == 1

    def try_pair(self, side_a, pid_a, side_b, pid_b):
        """'right', 'wrong' or 'ignore' (same column, or already joined)."""
        if side_a == side_b or pid_a in self.matched or pid_b in self.matched:
            return "ignore"
        if pid_a == pid_b:
            self.matched[pid_a] = True
            return "right"
        return "wrong"

    @property
    def done(self):
        return len(self.matched) == self.n

    @staticmethod
    def stars(n, misses, hints, answer_shown):
        if answer_shown:
            return 1
        penalty = misses + 2 * hints
        if penalty <= max(1, n // 2):
            return 3
        return 2 if penalty <= n + 2 else 1


class MatchView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.round = None
        self.rects = {}                # (side, pid) -> (x0, y0, x1, y1)
        self.misses = 0
        self.hints = 0
        self.answer = False
        self.answer_used = False
        self.done = False
        self.started_at = 0.0
        self.elapsed = 0.0
        self.drag = None               # (side, pid) the press began on
        self.sel = None                # (side, pid) picked by a plain click
        self.press_xy = (0, 0)
        self.moved = False
        self._banner_btn = None
        self._timers = []
        self._msg = "status.match.ready.pairs"
        self._msg_args = ()
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.new_round(first=True)

    # ---- building ---------------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row1 = tk.Frame(bar, bg=CREAM)
        row1.pack(side="top", fill="x", padx=8, pady=(6, 2))
        row2 = tk.Frame(bar, bg=CREAM)
        row2.pack(side="top", fill="x", padx=8, pady=(0, 6))

        tbutton(row1, "btn.back", self.app.show_start).pack(side="left")
        lab = tk.Label(row1, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.set") + 1, anchor="e")
        reg(lab, "lbl.set")
        lab.pack(side="left", padx=(12, 2))
        self.opt_set = KeyedOption(
            row1, [(m["key"], "matchname." + m["key"]) for m in MATCHES],
            SETTINGS.get("match_set", MATCHES[0]["key"]), self.on_set)
        self.opt_set.pack(side="left", padx=(0, 10))
        lab = tk.Label(row1, bg=CREAM, fg=TEXTC, font=FONT_UI,
                       width=width_for("lbl.pairs") + 1, anchor="e")
        reg(lab, "lbl.pairs")
        lab.pack(side="left", padx=(6, 2))
        self.opt_pairs = KeyedOption(
            row1, [(str(n), "pairs.%d" % n) for n in MATCH_CHOICES],
            SETTINGS.get("match_pairs", "4"), self.on_pairs)
        self.opt_pairs.pack(side="left", padx=(0, 12))
        tbutton(row1, "btn.newround", self.on_new).pack(side="left", padx=2)
        tbutton(row1, "btn.hint", self.give_hint).pack(side="left", padx=2)
        self.btn_answer = tbutton(row1, "btn.hint.show", self.toggle_answer,
                                  extra_keys=("btn.hint.hide",))
        self.btn_answer.pack(side="left", padx=2)

        tbutton(row2, "btn.about",
                lambda: show_about(self.app.root)).pack(side="right",
                                                        padx=(6, 0))
        tbutton(row2, "btn.help",
                lambda: show_help(self.app.root)).pack(side="right", padx=6)
        tbutton(row2, "btn.settings",
                lambda: show_settings(self.app.root,
                                      self.app)).pack(side="right", padx=6)

        self.canvas = tk.Canvas(self, bg=PAPER, highlightthickness=0,
                                takefocus=1, cursor="hand2")
        self.canvas.pack(side="top", fill="both", expand=True)

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_count = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                  font=FONT_UI_B, anchor="e",
                                  width=width_for("status.match.count") + 8)
        self.lbl_count.pack(side="right", padx=10, pady=5)

        self.canvas.bind("<Configure>", lambda e: self.redraw())
        self.canvas.bind("<Button-1>", self.on_press)
        self.canvas.bind("<B1-Motion>", self.on_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_release)
        on_retranslate(self.retranslate_view)

    # ---- timers -----------------------------------------------------------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- rounds -----------------------------------------------------------
    def progress(self):
        return bool(self.round and self.round.matched) and not self.done

    def _ok_to_leave(self):
        return not (self.progress() and SETTINGS["confirm_new"] and
                    not ask_yes_no(self.app.root, "ask.newround"))

    def on_new(self):
        if self._ok_to_leave():
            self.new_round()

    def on_set(self, value):
        if not self._ok_to_leave():
            self.opt_set.set(self.round.mset["key"])
            return
        SETTINGS["match_set"] = value
        save_settings()
        self.new_round()

    def on_pairs(self, value):
        if not self._ok_to_leave():
            self.opt_pairs.set(str(self.want))
            return
        SETTINGS["match_pairs"] = value
        save_settings()
        self.new_round()

    def new_round(self, first=False):
        self.cancel_timers()
        key = SETTINGS.get("match_set", MATCHES[0]["key"])
        mset = MATCH_BY_KEY.get(key) or MATCHES[0]
        try:
            self.want = int(SETTINGS.get("match_pairs", "4"))
        except ValueError:
            self.want = 4
        if first:
            self.opt_set.set(mset["key"])
            self.opt_pairs.set(str(self.want))
        seed = random.randrange(10 ** 6)
        self.round = MatchRound(mset, self.want, seed)
        self.misses = self.hints = 0
        self.answer = self.answer_used = self.done = False
        self.drag = self.sel = None
        self.started_at = 0.0
        self.elapsed = 0.0
        reg(self.btn_answer, "btn.hint.show")
        log("---- matching: set=%s seed=%d pairs=%s"
            % (mset["key"], seed, ", ".join("%s-%s" % tuple(p)
                                            for p in self.round.items)))
        self.set_msg("status.match.ready." + self.round.kind)
        self.update_counters()
        self.redraw()

    # ---- geometry ---------------------------------------------------------
    def layout(self):
        r = self.round
        cw = max(100, self.canvas.winfo_width())
        ch = max(100, self.canvas.winfo_height())
        top, bottom = 16, 16
        slot = (ch - top - bottom) / float(r.n)
        art = max(34.0, min(slot - 32.0, cw * 0.20, 190.0))
        box_w = art + 40.0
        box_h = art + 26.0
        self.art = art
        self.rects = {}
        for side, order, cx in ((0, r.left, cw * 0.24), (1, r.right, cw * 0.76)):
            for row, pid in enumerate(order):
                cy = top + slot * (row + 0.5)
                self.rects[(side, pid)] = (cx - box_w / 2.0, cy - box_h / 2.0,
                                           cx + box_w / 2.0, cy + box_h / 2.0)

    def item_at(self, px, py):
        for key, (x0, y0, x1, y1) in self.rects.items():
            if x0 <= px <= x1 and y0 <= py <= y1:
                return key
        return None

    def edge(self, side, pid):
        """Where a line leaves / arrives: the middle of the facing edge."""
        x0, y0, x1, y1 = self.rects[(side, pid)]
        return ((x1 if side == 0 else x0), (y0 + y1) / 2.0)

    def centre(self, key):
        x0, y0, x1, y1 = self.rects[key]
        return ((x0 + x1) / 2.0, (y0 + y1) / 2.0)

    # ---- drawing ----------------------------------------------------------
    def redraw(self):
        if not self.round:
            return
        c = self.canvas
        c.delete("all")
        self.drop_banner_button()
        self.layout()
        r = self.round
        for pid in sorted(r.matched):
            self.draw_link(pid, PAIR_COLOURS[pid % len(PAIR_COLOURS)], 6, None)
        if self.answer:
            for pid in range(r.n):
                if pid not in r.matched:
                    self.draw_link(pid, "#9e9e9e", 4, (8, 6))
        for side in (0, 1):
            for pid in range(r.n):
                self.draw_item(side, pid)
        if self.done:
            self.draw_banner()

    def draw_link(self, pid, colour, width, dash):
        ax, ay = self.edge(0, pid)
        bx, by = self.edge(1, pid)
        kw = dict(fill=colour, width=width, capstyle="round", smooth=True,
                  tags=("link",))
        if dash:
            kw["dash"] = dash
        reach = (bx - ax) * 0.28
        self.canvas.create_line(ax, ay, ax + reach, ay, bx - reach, by, bx, by,
                                **kw)

    def draw_item(self, side, pid):
        c = self.canvas
        r = self.round
        x0, y0, x1, y1 = self.rects[(side, pid)]
        matched = pid in r.matched
        picked = self.sel == (side, pid)
        colour = PAIR_COLOURS[pid % len(PAIR_COLOURS)]
        fill = lighten(colour, 0.78) if matched else \
            ("#e3eef7" if r.is_shadow(side) else CARDBG)
        outline = colour if matched else ("#1e88e5" if picked else "#e0cfa8")
        c.create_rectangle(x0, y0, x1, y1, fill=fill, outline=outline,
                           width=(4 if (matched or picked) else 2),
                           tags=("item",))
        key = r.art_key(side, pid)
        caption = not r.is_shadow(side)
        cy = (y0 + 4 + self.art / 2.0) if caption else (y0 + y1) / 2.0
        draw_prims(c, art_prims(key, r.is_shadow(side)), (x0 + x1) / 2.0, cy,
                   self.art, tags=("item",))
        if caption:
            c.create_text((x0 + x1) / 2.0, y1 - 11, text=cap(T("name." + key)),
                          fill=TEXTC, font=FONT_SMALL, tags=("item",))

    def drop_banner_button(self):
        """canvas.delete() removes the button's window ITEM, not the button."""
        if self._banner_btn is not None:
            try:
                self._banner_btn.destroy()
            except Exception:
                pass
            self._banner_btn = None

    def draw_banner(self):
        c = self.canvas
        cw = max(60, c.winfo_width())
        r = self.round
        stars = r.stars(r.n, self.misses, self.hints, self.answer_used)
        x, y = cw / 2.0, 46
        c.create_rectangle(x - 190, y - 34, x + 190, y + 40, fill="#fff3c4",
                           outline=STARC, width=3)
        c.create_text(x - 100, y, text=T("win.bravo"), fill=GOODC,
                      font=("Segoe UI", 20, "bold"))
        draw_stars(c, x + 80, y - 8, 17, stars)
        c.create_text(x + 80, y + 24,
                      text=cap(T("status.match.done", r.n,
                                 fmt_time(self.elapsed))),
                      fill=TEXTC, font=FONT_SMALL)
        self._banner_btn = tbutton(c, "win.again", self.new_round)
        c.create_window(x, y + 66, window=self._banner_btn)

    # ---- input ------------------------------------------------------------
    def _start_clock(self):
        if not self.started_at:
            self.started_at = time.time()
            self.after_t(500, self.tick)

    def on_press(self, event):
        self.canvas.focus_set()
        if self.done or not self.round:
            return
        hit = self.item_at(event.x, event.y)
        self.press_xy = (event.x, event.y)
        self.moved = False
        self.drag = None
        if hit is None:
            if self.sel:
                self.sel = None
                self.redraw()
            return
        if hit[1] in self.round.matched:
            return
        if self.sel and self.sel[0] != hit[0]:
            first, self.sel = self.sel, None
            self.attempt(first, hit)
            return
        self.drag = hit

    def on_drag(self, event):
        if self.drag is None:
            return
        if not self.moved and math.hypot(event.x - self.press_xy[0],
                                         event.y - self.press_xy[1]) > 7:
            self.moved = True
        if self.moved:
            self.canvas.delete("rubber")
            cx, cy = self.centre(self.drag)
            self.canvas.create_line(cx, cy, event.x, event.y, fill="#1e88e5",
                                    width=5, capstyle="round",
                                    tags=("rubber",))

    def on_release(self, event):
        drag, self.drag = self.drag, None
        self.canvas.delete("rubber")
        if drag is None or self.done:
            return
        if self.moved:
            target = self.item_at(event.x, event.y)
            if target and target[0] != drag[0]:
                self.attempt(drag, target)
            return
        # a plain click: pick this one, the next click names its partner
        self.sel = None if self.sel == drag else drag
        if self.sel:
            self.set_msg("status.match.pick")
        self.redraw()

    def attempt(self, a, b):
        r = self.round
        self._start_clock()
        res = r.try_pair(a[0], a[1], b[0], b[1])
        if res == "ignore":
            self.redraw()
            return
        if res == "right":
            pid = a[1]
            ka, kb = r.items[pid]
            if r.kind == "shadows":
                self.set_msg("status.match.shadow", Lbl(TXT["name." + ka]))
            else:
                self.set_msg("status.match.right", Lbl(TXT["name." + ka]),
                             Lbl(TXT["name." + kb]))
            log("matching: joined %s - %s (%d of %d)"
                % (ka, kb, len(r.matched), r.n))
            self.update_counters()
            if r.done:
                self.finish()
            else:
                self.redraw()
            return
        self.misses += 1
        self.set_msg("status.match.wrong")
        self.update_counters()
        self.redraw()
        ax, ay = self.centre(a)
        bx, by = self.centre(b)
        self.canvas.create_line(ax, ay, bx, by, fill="#c62828", width=6,
                                capstyle="round", tags=("wrong",))
        self.after_t(500, lambda: self.canvas.delete("wrong"))

    def give_hint(self):
        if self.done or not self.round:
            return
        r = self.round
        left = [p for p in range(r.n) if p not in r.matched]
        if not left:
            return
        pid = random.choice(left)
        self.hints += 1
        self._start_clock()
        self.set_msg("status.match.hint")
        self.update_counters()
        items = []
        for side in (0, 1):
            x0, y0, x1, y1 = self.rects[(side, pid)]
            items.append(self.canvas.create_rectangle(
                x0 - 4, y0 - 4, x1 + 4, y1 + 4, outline="#1e88e5", width=6,
                tags=("blink",)))
        self._blink(items, 0)

    def _blink(self, items, n):
        try:
            state = "hidden" if n % 2 == 0 else "normal"
            for it in items:
                self.canvas.itemconfigure(it, state=state)
        except Exception:
            return
        if n < 9:
            self.after_t(260, lambda: self._blink(items, n + 1))
        else:
            self.canvas.delete("blink")

    def toggle_answer(self):
        if self.done or not self.round:
            return
        self.answer = not self.answer
        if self.answer:
            self.answer_used = True
            self.set_msg("status.match.answer")
        else:
            self.set_msg("status.match.ready." + self.round.kind)
        reg(self.btn_answer, "btn.hint.hide" if self.answer
            else "btn.hint.show")
        self.redraw()

    def handle_key(self, event):
        if self.done and (event.keysym or "").lower() in (
                "return", "kp_enter", "space"):
            self.new_round()

    # ---- counting and finishing ------------------------------------------
    def tick(self):
        if self.round and not self.done and self.started_at:
            self.elapsed = time.time() - self.started_at
            self.update_counters()
            self.after_t(500, self.tick)

    def update_counters(self):
        try:
            self.lbl_count.configure(text=T("status.match.count",
                                            len(self.round.matched),
                                            self.round.n, self.misses,
                                            fmt_time(self.elapsed)))
        except Exception:
            pass

    def finish(self):
        r = self.round
        self.done = True
        self.answer = False
        if self.started_at:
            self.elapsed = time.time() - self.started_at
        stars = r.stars(r.n, self.misses, self.hints, self.answer_used)
        record_solved("match", self.elapsed, stars)
        log("matching: finished set=%s pairs=%d misses=%d hints=%d answer=%s "
            "time=%s stars=%d" % (r.mset["key"], r.n, self.misses, self.hints,
                                  self.answer_used, fmt_time(self.elapsed),
                                  stars))
        self.set_msg("status.match.done", r.n, fmt_time(self.elapsed))
        self.update_counters()
        self.redraw()

    # ---- text -------------------------------------------------------------
    def set_msg(self, key, *args):
        self._msg = key
        self._msg_args = args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def retranslate_view(self):
        self.set_msg(self._msg, *self._msg_args)
        self.update_counters()
        self.redraw()

# *************** DEL 19d - BEAD BOARDS (PART 6) *****************************
# Fuse beads ("pärlplattor"): a pegboard, bowls of coloured beads, and the
# fun is carrying one bead at a time from a bowl to a peg.  Made to be gentle
# for a small child:
#
#   * NOTHING can go wrong.  There is no score, no clock, no "wrong" and no
#     question asking for confirmation.  Every action can be undone (Ctrl+Z or
#     the Undo button), "Erase all" included, so nothing needs guarding.
#   * Big targets.  A bead is a big round thing, a bowl is a big round thing,
#     and a drop is forgiving: let go NEAR a peg and the bead finds it.
#   * No reading.  Boards are chosen from a page of little pictures, colours
#     are bowls of beads, and the buttons are the only words.
#
# The hand: press on a bowl and carry a bead to a peg (it also selects that
# colour); press on a bead already on the board and carry it somewhere else
# (dropped on another bead they swap, dropped in a bowl it goes back, dropped
# anywhere else it simply goes home); press on an EMPTY peg and keep pressing
# while you move, and the selected colour is poured along the way - the quick
# way to fill an area.  The right mouse button and DELETE take beads away, like
# everywhere else in this program.
#
# Ironing is the finishing touch: "Iron it" slides an iron over the board and
# the beads melt into one flat piece, which "Save picture" writes as a PNG
# (no Pillow needed) next to a small JSON file in Helpfiles\ActivityBook\Gallery.
#
# BOARDS.  A board is a set of pegs.  Squares are all pegs; the animals are
# SILHOUETTES (a peg only where the animal is), the way real shaped boards are
# made.  Most animals also carry a PATTERN: the colour each peg would have, shown
# as faint ghost beads when "Show pattern" is ticked - copying it is an easy,
# calm game for the smallest.  The shapes are drawn as little character grids
# below (one letter per bead colour, "." = no peg); symmetric ones are written
# as their left half and mirrored by code, so they can never come out lopsided,
# and the round ones are drawn by formula for the same reason.

BEAD_COLOURS = [
    # letter, hex          (no names are shown: the bowls ARE the colours)
    ("W", "#f4f4ee"), ("K", "#2d2d31"), ("G", "#a3a3a8"),
    ("R", "#e53935"), ("P", "#f48fb1"), ("O", "#fb8c00"),
    ("Y", "#fdd835"), ("T", "#e8c28f"), ("N", "#8d5a3b"),
    ("L", "#8bc34a"), ("D", "#2e8b57"), ("C", "#29c6d9"),
    ("B", "#2760d8"), ("V", "#8e44ad"),
]
BEAD_HEX = dict(BEAD_COLOURS)
BEAD_LETTERS = "".join(k for k, _ in BEAD_COLOURS)


def _mirror_rows(halves):
    """Left halves (centre column last) -> whole rows, exactly symmetric."""
    return ["".join(h) + "".join(h[-2::-1]) for h in halves]


class _Grid(object):
    """A little drawing board for the shapes that are easier to compute than to
    type: discs, dots, lines."""

    def __init__(self, w, h):
        self.w, self.h = w, h
        self.cell = {}

    def put(self, c, r, ch):
        if 0 <= c < self.w and 0 <= r < self.h:
            self.cell[(c, r)] = ch

    def disc(self, cx, cy, rad, ch):
        for r in range(self.h):
            for c in range(self.w):
                if (c - cx) ** 2 + (r - cy) ** 2 <= rad * rad + 0.25:
                    self.cell[(c, r)] = ch

    def rows(self):
        return ["".join(self.cell.get((c, r), ".") for c in range(self.w))
                for r in range(self.h)]


def _shape_circle():
    g = _Grid(15, 15)
    g.disc(7, 7, 7.0, "B")
    return g.rows()


def _shape_flower():
    g = _Grid(17, 19)
    cx, cy = 8, 7
    g.disc(cx, cy, 4.6, "P")                # fills the gaps between the petals
    for k in range(8):                      # eight petals round the middle
        a = math.radians(-90 + 45 * k)
        g.disc(cx + 5.2 * math.cos(a), cy + 5.2 * math.sin(a), 1.9, "P")
    g.disc(cx, cy, 2.6, "Y")
    for r in range(13, 19):                 # stem
        g.put(8, r, "D")
    for c, r in ((7, 15), (6, 14), (5, 14), (9, 16), (10, 15), (11, 15)):
        g.put(c, r, "L")                    # two leaves, one each side
    return g.rows()


def _shape_ladybird():
    g = _Grid(15, 16)
    g.disc(7, 9.2, 6.2, "R")
    g.disc(7, 2.4, 2.2, "K")                # the head
    for r in range(5, 15):                  # the line down the back
        g.put(7, r, "K")
    for c, r in ((4, 7), (10, 7), (3, 10), (11, 10), (5, 13), (9, 13)):
        g.put(c, r, "K")                    # the spots
    for c, r in ((4, 0), (5, 1), (10, 0), (9, 1)):
        g.put(c, r, "K")                    # feelers, touching the head
    return g.rows()


def _shape_fish():
    g = _Grid(19, 11)
    cy = 5
    for r in range(11):                     # the body: an ellipse
        for c in range(19):
            if ((c - 7.5) / 7.6) ** 2 + ((r - cy) / 4.6) ** 2 <= 1.0:
                g.put(c, r, "B" if r <= cy + 1 else "C")
    for k in range(5):                      # the tail: a fan
        half = int(round(1 + k * 0.9))
        for r in range(cy - half, cy + half + 1):
            g.put(14 + k, r, "O")
    for c in range(6, 10):                  # the fin on top
        g.put(c, 0, "O")
        g.put(c, 1, "O")
    g.put(3, 4, "K")                        # the eye
    return g.rows()


def _shape_duck():
    g = _Grid(17, 15)
    for r in range(15):                     # body
        for c in range(17):
            if ((c - 9.0) / 7.0) ** 2 + ((r - 9.5) / 4.5) ** 2 <= 1.0:
                g.put(c, r, "Y")
    g.disc(4.5, 4.0, 3.2, "Y")              # head
    g.disc(5.6, 7.0, 2.6, "Y")              # neck
    for c, r in ((0, 5), (1, 5), (1, 6), (0, 4)):
        g.put(c, r, "O")                    # beak
    g.put(4, 3, "K")                        # eye
    for c, r in ((15, 7), (16, 6), (16, 7)):
        g.put(c, r, "Y")                    # tail tuft
    for c, r in ((7, 14), (8, 14), (11, 14), (12, 14)):
        g.put(c, r, "O")                    # feet
    for c in range(8, 13):                  # a wing
        g.put(c, 9, "O")
        g.put(c, 10, "O")
    return g.rows()


# Each shape: key -> dict(rows=[...]).  A "pattern" is the letters themselves.
_SHAPE_ROWS = {
    "bear": _mirror_rows([
        ".NNN....", "NNTTN...", "NNTTNNNN", ".NNNNNNN", ".NNNNNNN",
        "NNNNNNNN", "NNNKNNNN", "NNNNNNNN", "NNNNNTTK", "NNNNTTTT",
        "NNNNTTTT", "NNNNNTTT", ".NNNNNNN", "..NNNNNN", "...NNNNN"]),
    "cat": _mirror_rows([
        "O.......", "OO......", "OPO.....", "OPOOOOOO", "OOOOOOOO",
        "OOOOOOOO", "OOOKOOOO", "OOOOOOOP", "OOOOOWWW", ".OOOOWWW",
        "..OOOOOO", "...OOOOO"]),
    "rabbit": _mirror_rows([
        ".WWW....", ".WPW....", ".WPW....", ".WPW....", ".WPW....",
        ".WWW....", ".WWWWWWW", "WWWWWWWW", "WWKWWWWW", "WWWWWWWW",
        "WWWWWWWP", "WWWWWWPP", ".WWWWWWW", "..WWWWWW", "...WWWWW"]),
    "dog": _mirror_rows([
        "....TTTT", ".NNTTTTT", "NNNTTTTT", "NNNTTTTT", "NNNTKTTT",
        "NNNTTTTT", "NNNTTWWW", "NNNTWWWW", "NNNTWWWK", ".NNTWWWW",
        "..NTTWWW", "...TTWPP", ".....TTP"]),
    "butterfly": _mirror_rows([
        ".....K..", "......K.", ".VVV.VVK", "VVVVVVVK", "VVYYVVVK",
        "VVYYVVVK", "VVVVVVVK", ".VVVVVVK", "..PPPPPK", "..PPYPPK",
        "...PPPPK", ".....PPK"]),
    "heart": _mirror_rows([
        ".RRR....", "RPRRR...", "RRRRRRRR", "RRRRRRRR", "RRRRRRRR",
        ".RRRRRRR", "..RRRRRR", "...RRRRR", "....RRRR", ".....RRR",
        "......RR", ".......R"]),
    "star": _mirror_rows([
        ".......Y", "......YY", "......YY", "YYYYYYYY", ".YYYYYYY",
        "..YYYYYY", "...YYYYY", "...YYYYY", "..YYYYY.", "..YYYY..",
        ".YYY....", ".YY....."]),
    "duck": _shape_duck(),
    "fish": _shape_fish(),
    "circle": _shape_circle(),
    "flower": _shape_flower(),
    "ladybird": _shape_ladybird(),
}

# The order they are offered in.  Squares first (all pegs, no pattern).
SQUARE_BOARDS = [("sq10", 10), ("sq15", 15), ("sq20", 20), ("sq29", 29)]
SHAPE_ORDER = ["bear", "dog", "cat", "rabbit", "fish", "duck", "butterfly",
               "flower", "ladybird", "heart", "star", "circle"]
# A circle has a silhouette but nothing to copy: a plain round board.
NO_PATTERN = ("circle",)


def make_board_spec(key):
    """A board spec: key, w, h, pegs (set of (col,row)) and guide (dict
    (col,row)->letter or None).  Unknown key -> None."""
    for k, n in SQUARE_BOARDS:
        if k == key:
            return dict(key=k, w=n, h=n,
                        pegs=set((c, r) for r in range(n) for c in range(n)),
                        guide=None)
    rows = _SHAPE_ROWS.get(key)
    if not rows:
        return None
    pegs, guide = set(), {}
    for r, line in enumerate(rows):
        for c, ch in enumerate(line):
            if ch != ".":
                pegs.add((c, r))
                guide[(c, r)] = ch
    return dict(key=key, w=max(len(x) for x in rows), h=len(rows),
                pegs=pegs, guide=(None if key in NO_PATTERN else guide))


BOARD_KEYS = [k for k, _ in SQUARE_BOARDS] + SHAPE_ORDER
BOARD_SPECS = {}
for _k in BOARD_KEYS:
    BOARD_SPECS[_k] = make_board_spec(_k)


# The AREAS of a default figure: connected pegs of the same pattern colour (a dog's muzzle,
# an ear, an eye).  "Show areas" gives each area a grey background and neighbouring areas
# different greys, so a small child can see where one thing ends and the next begins; the
# areas of the colour in hand are marked in blue.  Computed once per board.
BEAD_AREA_TONES = ("#d5dde3", "#bccad4", "#e2d9cb", "#c8d3c2")
AREA_CUR = "#9fc4e8"


def bead_areas(spec):
    """dict(region_of={peg: id}, regions=[dict(letter, cells, tone, near)]) - empty for a
    board without a pattern."""
    got = spec.get("areas")
    if got is not None:
        return got
    guide = spec.get("guide") or {}
    region_of, regions = {}, []
    for start in sorted(guide, key=lambda p: (p[1], p[0])):
        if start in region_of:
            continue
        rid, cells, todo = len(regions), [], [start]
        region_of[start] = rid
        while todo:
            cur = todo.pop()
            cells.append(cur)
            for dc, dr in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                n = (cur[0] + dc, cur[1] + dr)
                if guide.get(n) == guide[start] and n not in region_of:
                    region_of[n] = rid
                    todo.append(n)
        regions.append(dict(letter=guide[start], cells=cells, tone=0, near=set()))
    for (c, r) in guide:
        for dc, dr in ((1, 0), (0, 1)):
            n = (c + dc, r + dr)
            if n in region_of and region_of[n] != region_of[(c, r)]:
                regions[region_of[(c, r)]]["near"].add(region_of[n])
                regions[region_of[n]]["near"].add(region_of[(c, r)])
    for rg in regions:
        used = set(regions[i]["tone"] for i in rg["near"])
        rg["tone"] = next((t for t in range(len(BEAD_AREA_TONES)) if t not in used), 0)
    spec["areas"] = dict(region_of=region_of, regions=regions)
    return spec["areas"]


# ---- the model: pegs, beads and a history (no tkinter in here) -------------

class BeadModel(object):
    """What is on one board: which colour sits on which peg, and the history
    that makes every action undoable.

    A history step is a copy of the whole bead dictionary taken BEFORE the
    action (begin) - at most 29 x 29 entries, so this is cheap and cannot get
    out of step with the board the way a list of small "moves" could.  An
    action that ended up changing nothing is dropped again (settle), so a
    click on nothing never makes an Undo that appears to do nothing.
    """

    HISTORY = 300

    def __init__(self, spec):
        self.spec = spec
        self.key = spec["key"]
        self.w, self.h = spec["w"], spec["h"]
        self.pegs = spec["pegs"]
        self.guide = spec["guide"]
        self.beads = {}                 # (col, row) -> colour letter
        self.undo_stack = []
        self.redo_stack = []
        self._open = False              # begin() called, settle() not yet
        self.ironed = False             # the beads are melted into one piece

    # ---- geometry --------------------------------------------------------
    def twin(self, cell):
        """The peg that mirrors this one left-right, or None."""
        t = (self.w - 1 - cell[0], cell[1])
        return t if (t != cell and t in self.pegs) else None

    def nearest_peg(self, fx, fy, reach):
        """The peg whose centre is closest to the board position (fx, fy), both
        in peg units (a peg (c, r) has its centre at (c + .5, r + .5)), but
        only when it lies within `reach` pegs - a forgiving drop."""
        best, best_d = None, reach * reach
        c0, r0 = int(math.floor(fx)), int(math.floor(fy))
        span = int(math.ceil(reach)) + 1
        for r in range(r0 - span, r0 + span + 1):
            for c in range(c0 - span, c0 + span + 1):
                if (c, r) in self.pegs:
                    d = (c + 0.5 - fx) ** 2 + (r + 0.5 - fy) ** 2
                    if d <= best_d:
                        best, best_d = (c, r), d
        return best

    # ---- history ----------------------------------------------------------
    def begin(self):
        self.undo_stack.append(dict(self.beads))
        del self.undo_stack[:-self.HISTORY]
        self.redo_stack = []
        self._open = True

    def settle(self):
        """Forget the step if nothing changed after all.  Harmless without a
        begin() before it (a click on empty paper)."""
        if self._open and self.undo_stack and self.undo_stack[-1] == self.beads:
            self.undo_stack.pop()
        self._open = False

    def undo(self):
        if not self.undo_stack:
            return False
        self.redo_stack.append(dict(self.beads))
        self.beads = self.undo_stack.pop()
        return True

    def redo(self):
        if not self.redo_stack:
            return False
        self.undo_stack.append(dict(self.beads))
        self.beads = self.redo_stack.pop()
        return True

    # ---- changing the board (call begin() first, settle() after) ----------
    def put(self, cell, letter):
        if cell not in self.pegs or letter not in BEAD_HEX:
            return False
        if self.beads.get(cell) == letter:
            return False
        self.beads[cell] = letter
        return True

    def take(self, cell):
        return self.beads.pop(cell, None)

    def clear(self):
        self.beads = {}

    # ---- the pattern ------------------------------------------------------
    def matched(self):
        """(pegs whose bead has the pattern's colour, pegs in the pattern)."""
        if not self.guide:
            return 0, 0
        ok = sum(1 for cell, ch in self.guide.items()
                 if self.beads.get(cell) == ch)
        return ok, len(self.guide)

    def complete(self):
        ok, total = self.matched()
        return bool(total) and ok == total

    # ---- saving -----------------------------------------------------------
    def to_json(self):
        return dict(board=self.key,
                    beads=[[c, r, ch] for (c, r), ch in sorted(self.beads.items())])


# ---- the picture file: a PNG written by hand (no Pillow needed) ------------

def _hex_rgb(colour):
    return (int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:7], 16))


def _shade(rgb, f):
    """f > 0 towards white, f < 0 towards black."""
    if f >= 0:
        return tuple(int(v + (255 - v) * f) for v in rgb)
    return tuple(int(v * (1.0 + f)) for v in rgb)


_STAMPS = {}


def fused_stamp(colour, size):
    """One ironed bead as a list of (dx, dy, r, g, b, alpha): a rounded square
    with a small hole and a light bevel, anti-aliased by 3 x 3 sampling.  Cached
    per colour and size - a whole board reuses fourteen of them."""
    ck = (colour, size)
    if ck in _STAMPS:
        return _STAMPS[ck]
    base = _hex_rgb(colour)
    hole = _shade(base, -0.45)
    rim = _shade(base, -0.16)
    lit = _shade(base, 0.16)
    q, rad, ss = 0.48, 0.20, 3
    out = []
    for py in range(size):
        for px in range(size):
            n = sr = sg = sb = 0
            for sy in range(ss):
                for sx in range(ss):
                    u = (px + (sx + 0.5) / ss) / size
                    v = (py + (sy + 0.5) / ss) / size
                    dx = max(abs(u - 0.5) - (q - rad), 0.0)
                    dy = max(abs(v - 0.5) - (q - rad), 0.0)
                    if dx * dx + dy * dy > rad * rad:
                        continue
                    d = math.hypot(u - 0.5, v - 0.5)
                    if d < 0.12:
                        col = hole
                    elif q - max(abs(u - 0.5), abs(v - 0.5)) < 0.04:
                        col = rim
                    elif (u - 0.5) + (v - 0.5) < -0.30:
                        col = lit
                    else:
                        col = base
                    n += 1
                    sr += col[0]
                    sg += col[1]
                    sb += col[2]
            if n:
                out.append((px, py, sr // n, sg // n, sb // n,
                            int(255 * n / float(ss * ss))))
    _STAMPS[ck] = out
    return out


def render_beads_rgb(model, size=None):
    """The ironed piece as (width, height, raw RGB bytes) on a white page."""
    if size is None:
        size = max(14, min(40, 760 // max(model.w, model.h)))
    pad = max(4, size // 3)
    width, height = model.w * size + 2 * pad, model.h * size + 2 * pad
    buf = bytearray(b"\xff" * (width * height * 3))
    for (c, r), ch in model.beads.items():
        x0, y0 = pad + c * size, pad + r * size
        for dx, dy, red, grn, blu, a in fused_stamp(BEAD_HEX[ch], size):
            i = ((y0 + dy) * width + x0 + dx) * 3
            if a >= 255:
                buf[i], buf[i + 1], buf[i + 2] = red, grn, blu
            else:
                k = a / 255.0
                buf[i] = int(buf[i] * (1 - k) + red * k)
                buf[i + 1] = int(buf[i + 1] * (1 - k) + grn * k)
                buf[i + 2] = int(buf[i + 2] * (1 - k) + blu * k)
    return width, height, bytes(buf)


def png_bytes(width, height, rgb):
    """A truecolour PNG, filter 0 on every row."""
    def chunk(tag, data):
        return (struct.pack(">I", len(data)) + tag + data +
                struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff))
    stride = width * 3
    raw = b"".join(b"\x00" + rgb[y * stride:(y + 1) * stride]
                   for y in range(height))
    return (b"\x89PNG\r\n\x1a\n" +
            chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) +
            chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b""))


def png_pixels(data):
    """Read back a PNG written by png_bytes: (width, height, rows of RGB bytes).
    Only what this program writes - it is here so the self test can prove the
    file without trusting the writer."""
    assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a PNG"
    pos, idat, width = 8, b"", 0
    while pos < len(data):
        n = struct.unpack(">I", data[pos:pos + 4])[0]
        tag, body = data[pos + 4:pos + 8], data[pos + 8:pos + 8 + n]
        crc = struct.unpack(">I", data[pos + 8 + n:pos + 12 + n])[0]
        assert crc == zlib.crc32(tag + body) & 0xffffffff, "bad CRC in %r" % tag
        if tag == b"IHDR":
            width, height = struct.unpack(">II", body[:8])
        elif tag == b"IDAT":
            idat += body
        pos += 12 + n
    raw = zlib.decompress(idat)
    stride = width * 3 + 1
    return width, height, [raw[y * stride + 1:(y + 1) * stride]
                           for y in range(height)]


# ---- texts: English only from me, the other columns repeat it -------------
# Lars's rule since 2026-10-03: Code-Claude writes English only.  This program
# is older and keeps three columns, so every key below is entered three times
# with the English text; the selftest's "three columns" check stays happy and
# until a translator replaces the sv / ru copies, the player simply reads
# English.  The keys are all named bead.* / *.bead.* so they can be pulled out
# in one go: that is the list to hand to HTTP-Claude.
BEAD_TEXT = {
    "mode.beads":        "Bead boards",
    "mode.beads.desc":   "Carry beads from the bowls to the board and make a picture - then iron it",
    "btn.bead.boards":   "Boards",
    "btn.bead.undo":     "Undo",
    "btn.bead.redo":     "Redo",
    "btn.bead.iron":     "Iron it",
    "btn.bead.uniron":   "Back to beads",
    "btn.bead.save":     "Save picture",
    "lbl.bead.pattern":  "Show pattern",
    "lbl.bead.mirror":   "Mirror",
    "lbl.bead.areas":    "Show areas",
    "bead.pick.title":   "Choose a board",
    "status.bead.ready": "Take a bead from a bowl and put it on the board. Press an empty peg and drag to pour the colour.",
    "status.bead.copy":  "Copy the pattern: the faint beads show which colour goes where.",
    "status.bead.done":  "It looks just like the pattern! Iron it, then save the picture.",
    "status.bead.empty": "Put some beads on the board first.",
    "status.bead.ironed": "Ironed! The beads have melted into one piece. Save the picture to keep it.",
    "status.bead.lock":  "The beads are ironed together. Press Back to beads to change them.",
    "status.bead.back":  "Back in the bowl.",
    "status.bead.saved": "Saved: {0}",
    "status.bead.savefail": "The picture could not be saved.",
    "status.bead.count": "Beads: {0}",
    "bead.board.sq10":   "Big beads (10 x 10)",
    "bead.board.sq15":   "Square (15 x 15)",
    "bead.board.sq20":   "Small beads (20 x 20)",
    "bead.board.sq29":   "Large board (29 x 29)",
    "bead.board.bear":   "Bear",
    "bead.board.dog":    "Dog",
    "bead.board.cat":    "Cat",
    "bead.board.rabbit": "Rabbit",
    "bead.board.fish":   "Fish",
    "bead.board.duck":   "Duck",
    "bead.board.butterfly": "Butterfly",
    "bead.board.flower": "Flower",
    "bead.board.ladybird": "Ladybird",
    "bead.board.heart":  "Heart",
    "bead.board.star":   "Star",
    "bead.board.circle": "Circle",
}
BEAD_TEXT_SV = {     # same keys as BEAD_TEXT; a missing key shows the English
    "mode.beads": "Pärlplattor",
    "mode.beads.desc": "Bär pärlor från skålarna till plattan och gör en bild - stryk den sedan",
    "btn.bead.boards": "Plattor",
    "btn.bead.undo": "Ångra",
    "btn.bead.redo": "Gör om",
    "btn.bead.iron": "Stryk",
    "btn.bead.uniron": "Till pärlorna",
    "btn.bead.save": "Spara bilden",
    "lbl.bead.pattern": "Visa mönstret",
    "lbl.bead.mirror": "Spegla",
    "lbl.bead.areas": "Visa områden",
    "bead.pick.title": "Välj en platta",
    "status.bead.ready": "Ta en pärla från en skål och lägg den på plattan. Tryck på en tom pinne och dra för att hälla ut färgen.",
    "status.bead.copy": "Kopiera mönstret: de bleka pärlorna visar vilken färg som ska vara var.",
    "status.bead.done": "Det ser precis ut som mönstret! Stryk det och spara sedan bilden.",
    "status.bead.empty": "Lägg några pärlor på plattan först.",
    "status.bead.ironed": "Struket! Pärlorna har smält ihop till en bit. Spara bilden för att behålla den.",
    "status.bead.lock": "Pärlorna är strukna ihop. Tryck på Till pärlorna för att ändra dem.",
    "status.bead.back": "Tillbaka i skålen.",
    "status.bead.saved": "Sparad: {0}",
    "status.bead.savefail": "Bilden kunde inte sparas.",
    "status.bead.count": "Pärlor: {0}",
    "bead.board.sq10": "Stora pärlor (10 x 10)",
    "bead.board.sq15": "Kvadrat (15 x 15)",
    "bead.board.sq20": "Små pärlor (20 x 20)",
    "bead.board.sq29": "Stor platta (29 x 29)",
    "bead.board.bear": "Björn",
    "bead.board.dog": "Hund",
    "bead.board.cat": "Katt",
    "bead.board.rabbit": "Kanin",
    "bead.board.fish": "Fisk",
    "bead.board.duck": "Anka",
    "bead.board.butterfly": "Fjäril",
    "bead.board.flower": "Blomma",
    "bead.board.ladybird": "Nyckelpiga",
    "bead.board.heart": "Hjärta",
    "bead.board.star": "Stjärna",
    "bead.board.circle": "Cirkel",
}
BEAD_TEXT_RU = {
    "mode.beads": "Термомозаика",
    "mode.beads.desc": "Неси бусины из мисок на доску, собери картинку - и прогладь её",
    "btn.bead.boards": "Доски",
    "btn.bead.undo": "Отменить",
    "btn.bead.redo": "Вернуть",
    "btn.bead.iron": "Прогладить",
    "btn.bead.uniron": "К бусинам",
    "btn.bead.save": "Сохранить картинку",
    "lbl.bead.pattern": "Показать узор",
    "lbl.bead.mirror": "Зеркало",
    "lbl.bead.areas": "Показать области",
    "bead.pick.title": "Выбери доску",
    "status.bead.ready": "Возьми бусину из миски и положи на доску. Нажми на пустой штырёк и потяни - так можно насыпать цвет.",
    "status.bead.copy": "Повтори узор: бледные бусины показывают, какой цвет куда.",
    "status.bead.done": "Точно как на узоре! Прогладь и сохрани картинку.",
    "status.bead.empty": "Сначала положи несколько бусин на доску.",
    "status.bead.ironed": "Готово! Бусины сплавились в одно целое. Сохрани картинку, чтобы она не пропала.",
    "status.bead.lock": "Бусины сплавлены. Нажми «К бусинам», чтобы их изменить.",
    "status.bead.back": "Обратно в миску.",
    "status.bead.saved": "Сохранено: {0}",
    "status.bead.savefail": "Не удалось сохранить картинку.",
    "status.bead.count": "Бусин: {0}",
    "bead.board.sq10": "Крупные бусины (10 x 10)",
    "bead.board.sq15": "Квадрат (15 x 15)",
    "bead.board.sq20": "Мелкие бусины (20 x 20)",
    "bead.board.sq29": "Большая доска (29 x 29)",
    "bead.board.bear": "Медведь",
    "bead.board.dog": "Собака",
    "bead.board.cat": "Кошка",
    "bead.board.rabbit": "Кролик",
    "bead.board.fish": "Рыба",
    "bead.board.duck": "Утка",
    "bead.board.butterfly": "Бабочка",
    "bead.board.flower": "Цветок",
    "bead.board.ladybird": "Божья коровка",
    "bead.board.heart": "Сердце",
    "bead.board.star": "Звезда",
    "bead.board.circle": "Круг",
}
for _k, _v in BEAD_TEXT.items():
    TXT[_k] = (_v, BEAD_TEXT_SV.get(_k, _v), BEAD_TEXT_RU.get(_k, _v))

BEAD_HELP = ("Bead boards",
             "Fuse beads on a pegboard - nothing can go wrong and everything can\n"
             "be undone.\n\n"
             "Take a bead ......... press a bowl and carry the bead to a peg\n"
             "Move a bead ......... press it and carry it somewhere else; on\n"
             "                      another bead the two swap, on a bowl it goes\n"
             "                      back, anywhere else it goes home\n"
             "Pour a colour ....... press an EMPTY peg and drag: the chosen\n"
             "                      colour (the ringed bowl) fills the pegs\n"
             "Take beads away ..... right button (drag too) or DELETE\n"
             "Undo / Redo ......... the buttons, or Ctrl+Z / Ctrl+Y\n"
             "Erase all ........... can be undone too\n"
             "Boards .............. squares, and animals made of pegs\n"
             "Show pattern ........ faint beads show the colours to copy\n"
             "Show areas .......... the figure's areas get grey backgrounds; the\n"
             "                      areas of the colour in hand are marked blue\n"
             "Mirror .............. every bead you place gets a twin on the\n"
             "                      other side\n"
             "Iron it ............. melts the beads into one flat piece\n"
             "Save picture ........ a PNG (and a small JSON) in the Gallery folder")

BEAD_HELP_BY_LANG = {
    "sv": ("Pärlplattor",
           "Lägg pärlor på en platta - inget kan bli fel och allt går att ångra.\n\nTa en pärla ......... tryck på en skål och bär pärlan till en pinne\nFlytta en pärla ..... tryck på den och bär den någon annanstans; på\n                      en annan pärla byter de två plats, i en skål\n                      går den tillbaka, annars går den hem\nHälla ut en färg .... tryck på en TOM pinne och dra: den valda\n                      färgen (skålen med ring) fyller pinnarna\nTa bort pärlor ...... högerknapp (går att dra) eller DELETE\nÅngra / Gör om ...... knapparna, eller Ctrl+Z / Ctrl+Y\nRadera allt ......... går också att ångra\nPlattor ............. kvadrater, och djur gjorda av pinnar\nVisa mönstret ....... bleka pärlor visar färgerna att kopiera\nVisa områden ........ figurens områden får gråa bottnar; områdena för\n                      färgen du håller i markeras blå\nSpegla .............. varje pärla du lägger får en tvilling på\n                      andra sidan\nStryk ............... smälter ihop pärlorna till en platt bit\nSpara bilden ........ en PNG (och en liten JSON) i mappen Gallery"),
    "ru": ("Термомозаика",
           "Собирай бусины на доске - ошибиться нельзя, всё можно отменить.\n\nВзять бусину ........ нажми на миску и неси бусину к штырьку\nПереложить .......... нажми на бусину и неси в другое место; на другую\n                      бусину - они поменяются, в миску - она вернётся\n                      в миску, а на стол - на своё место\nНасыпать цвет ....... нажми на ПУСТОЙ штырёк и веди: выбранный\n                      цвет (миска с кольцом) заполнит штырьки\nУбрать бусины ....... правая кнопка (можно вести) или DELETE\nОтмена / Возврат .... кнопки или Ctrl+Z / Ctrl+Y\nСтереть всё ......... тоже можно отменить\nДоски ............... квадраты и животные из штырьков\nПоказать узор ....... бледные бусины показывают цвета для повтора\nПоказать области .... области фигуры получают серый фон; области\n                      цвета в руке отмечены синим\nЗеркало ............. у каждой бусины появляется близнец с\n                      другой стороны\nПрогладить .......... сплавляет бусины в один плоский кусок\nСохранить ........... PNG (и небольшой JSON) в папке Gallery"),
}

BOARDC, BOARD_EDGE, PEGC ="#d6ecfa", "#6fa8d0", "#a9cde6"
TRAYC, BOWLC, BOWL_IN, SELC = "#f3e6c8", "#d9b98a", "#c4a070", "#1e88e5"
# where the seven beads of a heap lie in a bowl, in bowl radii
HEAP = [(0.0, 0.0), (-0.46, -0.10), (0.46, -0.10), (-0.24, 0.42),
        (0.26, 0.42), (-0.22, -0.48), (0.24, -0.48)]
BEAD_REACH = 0.9                  # how far from a peg a drop still finds it
IRON_STEPS, IRON_MS = 16, 42


def draw_bead(c, cx, cy, r, letter, tags=(), ghost=False, hole=PEGC):
    """One round bead: a ring with a hole, a rim a shade darker and a glint."""
    col = BEAD_HEX[letter]
    if ghost:
        c.create_oval(cx - r, cy - r, cx + r, cy + r, fill=lighten(col, 0.56),
                      outline=lighten(col, 0.18), width=max(1, int(r * 0.10)),
                      tags=tags)
        c.create_oval(cx - r * 0.34, cy - r * 0.34, cx + r * 0.34,
                      cy + r * 0.34, fill=hole, outline="", tags=tags)
        return
    rim = darken(col, 0.38)
    c.create_oval(cx - r, cy - r, cx + r, cy + r, fill=col, outline=rim,
                  width=max(1, int(r * 0.10)), tags=tags)
    c.create_oval(cx - r * 0.34, cy - r * 0.34, cx + r * 0.34, cy + r * 0.34,
                  fill=hole, outline=rim, width=1, tags=tags)
    c.create_arc(cx - r * 0.72, cy - r * 0.72, cx + r * 0.72, cy + r * 0.72,
                 start=105, extent=62, style="arc", outline=lighten(col, 0.62),
                 width=max(1, int(r * 0.13)), tags=tags)


def draw_fused(c, cx, cy, half, letter, tags=()):
    """A bead after ironing: a square that touches its neighbours."""
    col = BEAD_HEX[letter]
    c.create_rectangle(cx - half, cy - half, cx + half, cy + half, fill=col,
                       outline=darken(col, 0.14), width=1, tags=tags)
    c.create_oval(cx - half * 0.24, cy - half * 0.24, cx + half * 0.24,
                  cy + half * 0.24, fill=darken(col, 0.45), outline="",
                  tags=tags)
    c.create_line(cx - half * 0.8, cy - half * 0.8, cx + half * 0.3,
                  cy - half * 0.8, fill=lighten(col, 0.35), width=max(1, int(half * 0.14)),
                  tags=tags)


def draw_board_preview(c, spec, x, y, w, h, tags=()):
    """A whole board as little beads (pattern colours, or pale ghosts when
    there is no pattern).  Returns (cell, left, top) so a caller can add to it."""
    cell = min(w / float(spec["w"]), h / float(spec["h"]))
    ox = x + (w - cell * spec["w"]) / 2.0
    oy = y + (h - cell * spec["h"]) / 2.0
    guide = spec["guide"] or {}
    for (col, row) in sorted(spec["pegs"], key=lambda p: (p[1], p[0])):
        letter = guide.get((col, row))
        draw_bead(c, ox + (col + 0.5) * cell, oy + (row + 0.5) * cell,
                  cell * 0.46, letter or "B", tags=tags, ghost=not letter,
                  hole=PAPER)
    return cell, ox, oy


def card_art_beads(canvas, x, y, w, h):
    """A heart of beads with one bead missing and one on its way."""
    spec = BOARD_SPECS["heart"]
    cell, ox, oy = draw_board_preview(canvas, spec, x + w * 0.04, y, w * 0.60, h)
    gx, gy = ox + 9.5 * cell, oy + 4.5 * cell            # the gap, row 4 col 9
    canvas.create_oval(gx - cell * 0.62, gy - cell * 0.62, gx + cell * 0.62,
                       gy + cell * 0.62, fill=PAPER, outline="#bdae90",
                       width=2, dash=(3, 2))
    bx, by, br = x + w * 0.82, y + h * 0.26, h * 0.115
    canvas.create_oval(bx - br + 3, by - br + 5, bx + br + 3, by + br + 5,
                       fill="#cfc6b3", outline="")
    draw_bead(canvas, bx, by, br, "Y", hole=PAPER)
    bowl = h * 0.27
    canvas.create_oval(bx - bowl, y + h * 0.72 - bowl * 0.62, bx + bowl,
                       y + h * 0.72 + bowl * 0.62, fill=BOWLC,
                       outline="#8d6e63", width=2)
    for dx, dy in HEAP:
        draw_bead(canvas, bx + dx * bowl * 0.62, y + h * 0.71 + dy * bowl * 0.4,
                  bowl * 0.2, "Y", hole=BOWLC)


# ---- choosing a board from a page of pictures ------------------------------

def show_board_picker(root, current, on_pick):
    top = tk.Toplevel(root)
    top.title(T("bead.pick.title"))
    top.configure(bg=PAPER)
    top.resizable(False, False)
    top.transient(root)
    cols, tw, th = 4, 176, 158
    rows = (len(BOARD_KEYS) + cols - 1) // cols
    cv = tk.Canvas(top, width=cols * tw + 16, height=rows * th + 16, bg=PAPER,
                   highlightthickness=0, cursor="hand2")
    cv.pack(padx=8, pady=8)
    for i, key in enumerate(BOARD_KEYS):
        x0 = 8 + (i % cols) * tw
        y0 = 8 + (i // cols) * th
        tag = "t_" + key
        cv.create_rectangle(x0 + 4, y0 + 4, x0 + tw - 4, y0 + th - 4,
                            fill=BOARDC if key == current else CARDBG,
                            outline=SELC if key == current else "#e0cfa8",
                            width=4 if key == current else 2, tags=(tag, "tile"))
        draw_board_preview(cv, BOARD_SPECS[key], x0 + 16, y0 + 12, tw - 32,
                           th - 50, tags=(tag,))
        cv.create_text(x0 + tw / 2.0, y0 + th - 18, text=T("bead.board." + key),
                       fill=TEXTC, font=FONT_SMALL, tags=(tag,))

        def choose(event, k=key):
            top.destroy()
            on_pick(k)
        cv.tag_bind(tag, "<Button-1>", choose)
    make_modal(top)
    centre_on(top, root)
    return top


# *************** the view ****************************************************

class BeadView(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        self.models = {}               # board key -> BeadModel: work survives a switch
        self.model = None
        self.cur = SETTINGS.get("bead_colour", "R")
        if self.cur not in BEAD_HEX:
            self.cur = "R"
        self.carry = None              # dict(letter, src, x, y) while a bead is in hand
        self.mode = None               # "pour" / "erase" while a drag paints
        self.last_xy = None
        self.hover = (0, 0)
        self.iron_front = None         # x of the iron while the animation runs
        self.iron_step_no = 0
        self.busy = False
        self.said_done = False
        self.cell = 40.0
        self.ox = self.oy = 0.0
        self.bowls = {}
        self.tray_x = 0
        self._timers = []
        self._msg, self._msg_args = "status.bead.ready", ()
        self._build()
        self.bind("<Destroy>", lambda e: self.cancel_timers())
        self.load_board(SETTINGS.get("bead_board", "bear"), first=True)

    # ---- building ---------------------------------------------------------
    def _build(self):
        bar = tk.Frame(self, bg=CREAM)
        bar.pack(side="top", fill="x")
        row1 = tk.Frame(bar, bg=CREAM)
        row1.pack(side="top", fill="x", padx=8, pady=(6, 2))
        row2 = tk.Frame(bar, bg=CREAM)
        row2.pack(side="top", fill="x", padx=8, pady=(0, 6))

        tbutton(row1, "btn.back", self.app.show_start).pack(side="left")
        tbutton(row1, "btn.bead.boards", self.open_picker).pack(side="left", padx=(12, 2))
        tbutton(row1, "btn.bead.undo", self.undo).pack(side="left", padx=(12, 2))
        tbutton(row1, "btn.bead.redo", self.redo).pack(side="left", padx=2)
        tbutton(row1, "btn.clear", self.clear_all).pack(side="left", padx=(12, 2))
        self.btn_iron = tbutton(row1, "btn.bead.iron", self.toggle_iron,
                                extra_keys=("btn.bead.uniron",))
        self.btn_iron.pack(side="left", padx=(12, 2))
        tbutton(row1, "btn.bead.save", self.save_picture).pack(side="left", padx=2)

        self.guide_var = tk.BooleanVar(value=bool(SETTINGS.get("bead_guide")))
        self.cb_guide = self._check(row2, "lbl.bead.pattern", self.guide_var,
                                    self.toggle_guide)
        self.areas_var = tk.BooleanVar(value=bool(SETTINGS.get("bead_areas")))
        self.cb_areas = self._check(row2, "lbl.bead.areas", self.areas_var,
                                    self.toggle_areas)
        self.mirror_var = tk.BooleanVar(value=bool(SETTINGS.get("bead_mirror")))
        self._check(row2, "lbl.bead.mirror", self.mirror_var, self.toggle_mirror)
        tbutton(row2, "set.showfolder", self.show_folder).pack(side="left", padx=12)

        tbutton(row2, "btn.about",
                lambda: show_about(self.app.root)).pack(side="right", padx=(6, 0))
        tbutton(row2, "btn.help",
                lambda: show_help(self.app.root)).pack(side="right", padx=6)
        tbutton(row2, "btn.settings",
                lambda: show_settings(self.app.root, self.app)).pack(side="right", padx=6)

        self.canvas = tk.Canvas(self, bg=PAPER, highlightthickness=0,
                                takefocus=1, cursor="hand2")
        self.canvas.pack(side="top", fill="both", expand=True)

        status = tk.Frame(self, bg=CREAM)
        status.pack(side="bottom", fill="x")
        self.lbl_msg = tk.Label(status, text="", bg=CREAM, fg=TEXTC,
                                font=FONT_UI, anchor="w")
        self.lbl_msg.pack(side="left", fill="x", expand=True, padx=10, pady=5)
        self.lbl_count = tk.Label(status, text="", bg=CREAM, fg=DIMC,
                                  font=FONT_UI_B, anchor="e",
                                  width=width_for("status.bead.count") + 6)
        self.lbl_count.pack(side="right", padx=10, pady=5)

        c = self.canvas
        c.bind("<Configure>", lambda e: self.redraw())
        c.bind("<Button-1>", self.on_press)
        c.bind("<B1-Motion>", self.on_drag)
        c.bind("<ButtonRelease-1>", self.on_release)
        c.bind("<Button-3>", self.on_erase_press)
        c.bind("<B3-Motion>", self.on_erase_drag)
        c.bind("<ButtonRelease-3>", self.on_erase_release)
        c.bind("<Motion>", lambda e: setattr(self, "hover", (e.x, e.y)))
        on_retranslate(self.retranslate_view)

    def _check(self, parent, key, var, command):
        cb = tk.Checkbutton(parent, variable=var, command=command, bg=CREAM,
                            activebackground=CREAM, fg=TEXTC, selectcolor=PAPER,
                            font=FONT_UI, cursor="hand2",
                            width=width_for(key) + 3, anchor="w")
        reg(cb, key)
        cb.pack(side="left")
        return cb

    # ---- timers (same pattern as the other views) -------------------------
    def after_t(self, ms, fn):
        tid = self.after(ms, fn)
        self._timers.append(tid)
        return tid

    def cancel_timers(self):
        for tid in self._timers:
            try:
                self.after_cancel(tid)
            except Exception:
                pass
        self._timers = []

    # ---- boards ------------------------------------------------------------
    def load_board(self, key, first=False):
        spec = BOARD_SPECS.get(key) or BOARD_SPECS["bear"]
        self.cancel_timers()
        self.busy = False
        self.iron_front = None
        self.carry = self.mode = None
        if spec["key"] not in self.models:
            self.models[spec["key"]] = BeadModel(spec)
        self.model = self.models[spec["key"]]
        SETTINGS["bead_board"] = spec["key"]
        if not first:
            save_settings()
        has_guide = bool(self.model.guide)
        self.cb_guide.configure(state=("normal" if has_guide else "disabled"))
        self.cb_areas.configure(state=("normal" if has_guide else "disabled"))
        reg(self.btn_iron, "btn.bead.uniron" if self.model.ironed
            else "btn.bead.iron")
        self.said_done = self.model.complete()
        log("beads: board %s (%d beads on it)" % (spec["key"],
                                                  len(self.model.beads)))
        self.say_ready()
        self.update_count()
        self.redraw()

    def open_picker(self):
        if self.busy:
            return
        show_board_picker(self.app.root, self.model.key, self.load_board)

    def say_ready(self):
        if self.model.guide and self.guide_var.get():
            self.set_msg("status.bead.copy")
        else:
            self.set_msg("status.bead.ready")

    # ---- geometry ---------------------------------------------------------
    def layout(self):
        m = self.model
        cw = max(300, self.canvas.winfo_width())
        ch = max(300, self.canvas.winfo_height())
        tray_w = int(max(150, min(236, cw * 0.22)))
        bw = cw - tray_w
        self.cell = min((bw - 44) / float(m.w), (ch - 44) / float(m.h), 62.0)
        self.ox = (bw - self.cell * m.w) / 2.0
        self.oy = (ch - self.cell * m.h) / 2.0
        self.tray_x = bw
        self.tray_w = tray_w
        self.ch = ch
        col_w = tray_w / 2.0
        row_h = (ch - 20) / 7.0
        rad = max(16.0, min(col_w, row_h) * 0.43)
        self.bowl_r = rad
        self.bowls = {}
        for i, (letter, _hex) in enumerate(BEAD_COLOURS):
            self.bowls[letter] = (bw + col_w * (i % 2 + 0.5),
                                  10 + row_h * (i // 2 + 0.5), rad)

    def centre(self, cell):
        return (self.ox + (cell[0] + 0.5) * self.cell,
                self.oy + (cell[1] + 0.5) * self.cell)

    def cell_at(self, x, y):
        cell = (int(math.floor((x - self.ox) / self.cell)),
                int(math.floor((y - self.oy) / self.cell)))
        return cell if cell in self.model.pegs else None

    def peg_near(self, x, y):
        return self.model.nearest_peg((x - self.ox) / self.cell,
                                      (y - self.oy) / self.cell, BEAD_REACH)

    def bowl_at(self, x, y):
        for letter, (bx, by, rad) in self.bowls.items():
            if math.hypot(x - bx, y - by) <= rad * 1.12:
                return letter
        return None

    # ---- drawing ----------------------------------------------------------
    def redraw(self):
        if not self.model:
            return
        c = self.canvas
        c.delete("all")
        self.layout()
        m = self.model
        cell = self.cell
        for (col, row) in m.pegs:
            x0, y0 = self.ox + col * cell, self.oy + row * cell
            c.create_rectangle(x0, y0, x0 + cell + 0.5, y0 + cell + 0.5,
                               fill=BOARDC, outline="")
        if self.areas_var.get() and m.guide:
            self.draw_areas()
        for (col, row) in m.pegs:                # the outline of the silhouette
            x0, y0 = self.ox + col * cell, self.oy + row * cell
            for dc, dr, ax, ay, bx, by in ((0, -1, 0, 0, 1, 0), (0, 1, 0, 1, 1, 1),
                                           (-1, 0, 0, 0, 0, 1), (1, 0, 1, 0, 1, 1)):
                if (col + dc, row + dr) not in m.pegs:
                    c.create_line(x0 + ax * cell, y0 + ay * cell,
                                  x0 + bx * cell, y0 + by * cell, fill=BOARD_EDGE,
                                  width=3, capstyle="round")
        pr = max(1.5, cell * 0.12)
        for peg in m.pegs:
            cx, cy = self.centre(peg)
            c.create_oval(cx - pr, cy - pr, cx + pr, cy + pr, fill=PEGC,
                          outline="#8fb8d6")
        if self.mirror_var.get() and m.w > 1:
            ax = self.ox + m.w * cell / 2.0
            c.create_line(ax, self.oy - 8, ax, self.oy + m.h * cell + 8,
                          fill=BOARD_EDGE, dash=(5, 4), width=2)
        for peg in m.pegs:
            self.draw_cell(peg)
        self.draw_tray()
        if self.carry:
            self.draw_carry()
        if self.iron_front is not None:
            self.draw_iron()

    def draw_areas(self):
        """The areas of the default figure in greys; the colour in hand marks its areas blue."""
        c, m, cell = self.canvas, self.model, self.cell
        ar = bead_areas(m.spec)
        for rg in ar["regions"]:
            fill = AREA_CUR if rg["letter"] == self.cur else BEAD_AREA_TONES[rg["tone"]]
            for (col, row) in rg["cells"]:
                x0, y0 = self.ox + col * cell, self.oy + row * cell
                c.create_rectangle(x0, y0, x0 + cell + 0.5, y0 + cell + 0.5,
                                   fill=fill, outline="")
        for (col, row) in m.guide:               # a line wherever one area ends
            rid = ar["region_of"][(col, row)]
            x0, y0 = self.ox + col * cell, self.oy + row * cell
            for dc, dr, ax, ay, bx, by in ((0, 1, 0, 1, 1, 1), (1, 0, 1, 0, 1, 1)):
                n = (col + dc, row + dr)
                if n in m.pegs and ar["region_of"].get(n) != rid:
                    c.create_line(x0 + ax * cell, y0 + ay * cell, x0 + bx * cell,
                                  y0 + by * cell, fill="#78909c", width=2)

    def draw_cell(self, peg):
        c = self.canvas
        tag = "c%d_%d" % peg
        c.delete(tag)
        m = self.model
        cx, cy = self.centre(peg)
        letter = m.beads.get(peg)
        if letter:
            if m.ironed or (self.iron_front is not None and cx <= self.iron_front):
                draw_fused(c, cx, cy, self.cell / 2.0 + 0.5, letter, tags=(tag,))
            else:
                draw_bead(c, cx, cy, self.cell * 0.46, letter, tags=(tag,))
        elif self.guide_var.get() and m.guide and peg in m.guide:
            draw_bead(c, cx, cy, self.cell * 0.46, m.guide[peg], tags=(tag,),
                      ghost=True)
        if self.carry:
            c.tag_raise("carry")

    def draw_tray(self):
        c = self.canvas
        c.create_rectangle(self.tray_x, 0, self.tray_x + self.tray_w + 2, self.ch + 2,
                           fill=TRAYC, outline="")
        c.create_line(self.tray_x, 0, self.tray_x, self.ch, fill="#e0cfa8", width=3)
        for letter, (bx, by, rad) in self.bowls.items():
            if letter == self.cur:
                c.create_oval(bx - rad * 1.16, by - rad * 1.0, bx + rad * 1.16,
                              by + rad * 1.0, outline=SELC, width=4)
            c.create_oval(bx - rad, by - rad * 0.86, bx + rad, by + rad * 0.86,
                          fill=BOWLC, outline="#8d6e63", width=2)
            c.create_oval(bx - rad * 0.84, by - rad * 0.66, bx + rad * 0.84,
                          by + rad * 0.74, fill=BOWL_IN, outline="")
            for dx, dy in HEAP:
                draw_bead(c, bx + dx * rad * 0.62, by + dy * rad * 0.5 - rad * 0.04,
                          rad * 0.26, letter, hole=BOWL_IN)

    def draw_carry(self):
        c = self.canvas
        c.delete("carry")
        cr = self.carry
        r = self.cell * 0.56
        x, y = cr["x"], cr["y"]
        target = self.peg_near(x, y)
        if target:
            tx, ty = self.centre(target)
            c.create_oval(tx - self.cell * 0.55, ty - self.cell * 0.55,
                          tx + self.cell * 0.55, ty + self.cell * 0.55,
                          outline="#fbc02d", width=4, tags=("carry",))
        c.create_oval(x - r + 4, y - r + 7, x + r + 4, y + r + 7, fill="#cfc6b3",
                      outline="", tags=("carry",))
        draw_bead(c, x, y, r, cr["letter"], tags=("carry",), hole=PAPER)

    def draw_iron(self):
        c = self.canvas
        c.delete("iron")
        x = self.iron_front
        y = self.oy + self.model.h * self.cell / 2.0
        s = max(40.0, self.cell * 3.0)
        c.create_polygon(x - s * 0.9, y + s * 0.5, x + s * 0.3, y + s * 0.5,
                         x + s * 0.5, y + s * 0.05, x + s * 0.2, y - s * 0.25,
                         x - s * 0.9, y - s * 0.25, fill="#90a4ae",
                         outline="#455a64", width=3, tags=("iron",))
        c.create_rectangle(x - s * 0.62, y - s * 0.52, x + s * 0.05, y - s * 0.25,
                           fill="#ef5350", outline="#b71c1c", width=3, tags=("iron",))
        for k in range(3):
            c.create_oval(x - s * 0.2 + k * s * 0.22, y - s * 0.88 - k * 6,
                          x - s * 0.2 + k * s * 0.22 + s * 0.14,
                          y - s * 0.88 - k * 6 + s * 0.14, fill="#eceff1",
                          outline="", tags=("iron",))

    def update_count(self):
        self.lbl_count.configure(text=T("status.bead.count", len(self.model.beads)))

    # ---- placing and taking ----------------------------------------------
    def place(self, peg, letter, replace):
        """Put a bead on `peg` (and on its mirror twin when Mirror is on).
        An occupied peg is only touched when `replace` is true."""
        changed = []
        pegs = [peg]
        if self.mirror_var.get():
            tw = self.model.twin(peg)
            if tw:
                pegs.append(tw)
        for p in pegs:
            if p in self.model.beads and not replace:
                continue
            if self.model.put(p, letter):
                changed.append(p)
        for p in changed:
            self.draw_cell(p)
        return changed

    def remove(self, peg):
        changed = []
        pegs = [peg]
        if self.mirror_var.get():
            tw = self.model.twin(peg)
            if tw:
                pegs.append(tw)
        for p in pegs:
            if self.model.take(p) is not None:
                changed.append(p)
        for p in changed:
            self.draw_cell(p)
        return changed

    def after_change(self):
        self.update_count()
        if self.model.guide:
            if self.model.complete():
                if not self.said_done:
                    self.said_done = True
                    self.set_msg("status.bead.done")
            else:
                self.said_done = False

    def locked(self):
        """Ironed beads and the iron's animation do not take new beads."""
        if self.busy:
            return True
        if self.model.ironed:
            self.set_msg("status.bead.lock")
            return True
        return False

    # ---- the left button --------------------------------------------------
    def on_press(self, event):
        self.canvas.focus_set()
        if self.locked():
            return
        m = self.model
        self.last_xy = (event.x, event.y)
        letter = self.bowl_at(event.x, event.y)
        if letter:                                   # a bead from a bowl
            self.cur = letter
            SETTINGS["bead_colour"] = letter
            m.begin()
            self.carry = dict(letter=letter, src=None, x=event.x, y=event.y)
            self.redraw()
            return
        peg = self.cell_at(event.x, event.y)
        if peg is None:
            return
        if peg in m.beads:                           # pick a bead up
            m.begin()
            self.carry = dict(letter=m.take(peg), src=peg, x=event.x, y=event.y)
            self.draw_cell(peg)
            self.draw_carry()
            self.update_count()
            return
        m.begin()                                    # an empty peg: pour
        self.mode = "pour"
        self.place(peg, self.cur, False)
        self.after_change()

    def on_drag(self, event):
        if self.busy or self.model.ironed:
            return
        if self.carry:
            self.carry["x"], self.carry["y"] = event.x, event.y
            self.draw_carry()
        elif self.mode == "pour":
            for peg in self.cells_between(self.last_xy, (event.x, event.y)):
                self.place(peg, self.cur, False)
            self.last_xy = (event.x, event.y)
            self.after_change()

    def cells_between(self, a, b):
        """Every peg a drag from a to b crossed, so a fast stroke leaves no gaps."""
        n = max(1, int(math.hypot(b[0] - a[0], b[1] - a[1]) / (self.cell * 0.3)))
        seen = []
        for i in range(1, n + 1):
            p = self.cell_at(a[0] + (b[0] - a[0]) * i / float(n),
                             a[1] + (b[1] - a[1]) * i / float(n))
            if p and p not in seen:
                seen.append(p)
        return seen

    def on_release(self, event):
        m = self.model
        if self.carry:
            cr, self.carry = self.carry, None
            self.canvas.delete("carry")
            self.drop(cr, event.x, event.y)
        elif self.mode == "pour":
            self.mode = None
        m.settle()
        self.after_change()
        self.redraw()

    def drop(self, cr, x, y):
        """Where did the bead land?  Nothing is ever refused: it goes to the
        nearest peg, swaps with the bead there, goes back to a bowl, or returns."""
        m = self.model
        letter, src = cr["letter"], cr["src"]
        over_tray = x >= self.tray_x
        target = None if over_tray else self.peg_near(x, y)
        if target is None:
            if src is None:
                return                               # a bead from a bowl, dropped nowhere
            if over_tray:                            # a bead put back in a bowl
                self.set_msg("status.bead.back")
                if self.mirror_var.get() and m.twin(src) in m.beads:
                    m.take(m.twin(src))
                return
            m.put(src, letter)                       # dropped on the table: goes home
            return
        other = m.beads.get(target)
        if src is None:                              # new bead from a bowl
            self.place(target, letter, True)
        elif other is None:                          # a move to an empty peg
            m.put(target, letter)
        elif target == src:
            m.put(src, letter)
        else:                                        # two beads change places
            m.put(src, other)
            m.put(target, letter)
        if letter != self.cur and src is None:
            self.cur = letter

    # ---- the right button -------------------------------------------------
    def on_erase_press(self, event):
        self.canvas.focus_set()
        if self.locked():
            return
        self.model.begin()
        self.mode = "erase"
        self.last_xy = (event.x, event.y)
        peg = self.cell_at(event.x, event.y)
        if peg:
            self.remove(peg)
            self.after_change()

    def on_erase_drag(self, event):
        if self.mode != "erase":
            return
        for peg in self.cells_between(self.last_xy, (event.x, event.y)):
            self.remove(peg)
        self.last_xy = (event.x, event.y)
        self.after_change()

    def on_erase_release(self, event):
        if self.mode == "erase":
            self.mode = None
            self.model.settle()
            self.after_change()

    # ---- keys ---------------------------------------------------------------
    def handle_key(self, event):
        sym = (event.keysym or "").lower()
        ctrl = bool(event.state & 0x0004)
        if sym in ("delete", "backspace", "kp_delete"):
            if ctrl:
                self.clear_all()
            elif not self.locked():
                peg = self.cell_at(*self.hover)
                if peg:
                    self.model.begin()
                    self.remove(peg)
                    self.model.settle()
                    self.after_change()
        elif sym == "z" and ctrl:
            self.undo()
        elif sym == "y" and ctrl:
            self.redo()

    # ---- the buttons ------------------------------------------------------
    def undo(self):
        if self.busy:
            return
        if self.model.ironed:                        # first un-iron, then undo
            self.toggle_iron()
            return
        if self.model.undo():
            self.after_change()
            self.redraw()

    def redo(self):
        if self.busy or self.model.ironed:
            return
        if self.model.redo():
            self.after_change()
            self.redraw()

    def clear_all(self):
        if self.busy:
            return
        if self.model.ironed:
            self.model.ironed = False
            reg(self.btn_iron, "btn.bead.iron")
        if self.model.beads:
            self.model.begin()
            self.model.clear()
            self.model.settle()
        self.said_done = False
        self.say_ready()
        self.after_change()
        self.redraw()

    def toggle_guide(self):
        SETTINGS["bead_guide"] = bool(self.guide_var.get())
        save_settings()
        self.say_ready()
        self.redraw()

    def toggle_areas(self):
        SETTINGS["bead_areas"] = bool(self.areas_var.get())
        if self.areas_var.get() and self.model.guide and not self.guide_var.get():
            self.guide_var.set(True)
            SETTINGS["bead_guide"] = True
        save_settings()
        self.say_ready()
        self.redraw()

    def toggle_mirror(self):
        SETTINGS["bead_mirror"] = bool(self.mirror_var.get())
        save_settings()
        self.redraw()

    def show_folder(self):
        try:
            os.makedirs(GALLERY_DIR, exist_ok=True)
            open_path(GALLERY_DIR)
        except Exception as exc:
            log("beads: could not open %s: %s" % (GALLERY_DIR, exc))

    # ---- ironing ------------------------------------------------------------
    def toggle_iron(self):
        m = self.model
        if self.busy:
            return
        if m.ironed:
            m.ironed = False
            reg(self.btn_iron, "btn.bead.iron")
            self.say_ready()
            self.redraw()
            return
        if not m.beads:
            self.set_msg("status.bead.empty")
            return
        self.busy = True
        self.iron_step_no = 0
        self.iron_front = self.ox - self.cell * 2
        self.after_t(IRON_MS, self.iron_step)

    def iron_step(self):
        m = self.model
        self.iron_step_no += 1
        span = self.cell * m.w + self.cell * 4
        before = self.iron_front
        self.iron_front = self.ox - self.cell * 2 + span * self.iron_step_no / float(IRON_STEPS)
        for peg in m.beads:                          # only the beads just passed
            if before < self.centre(peg)[0] <= self.iron_front:
                self.draw_cell(peg)
        self.draw_iron()
        if self.iron_step_no < IRON_STEPS:
            self.after_t(IRON_MS, self.iron_step)
            return
        self.iron_front = None
        self.busy = False
        m.ironed = True
        reg(self.btn_iron, "btn.bead.uniron")
        self.canvas.delete("iron")
        log("beads: ironed %s (%d beads)" % (m.key, len(m.beads)))
        self.set_msg("status.bead.ironed")
        self.redraw()

    # ---- saving -------------------------------------------------------------
    def save_picture(self):
        m = self.model
        if not m.beads:
            self.set_msg("status.bead.empty")
            return
        stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
        base = os.path.join(GALLERY_DIR, "beads_%s_%s" % (m.key, stamp))
        try:
            os.makedirs(GALLERY_DIR, exist_ok=True)
            w, h, rgb = render_beads_rgb(m)
            with open(base + ".png", "wb") as fh:
                fh.write(png_bytes(w, h, rgb))
            with open(base + ".json", "w", encoding="utf-8") as fh:
                json.dump(m.to_json(), fh)
        except Exception as exc:
            log("beads: could not save: %s" % exc)
            self.set_msg("status.bead.savefail")
            return
        log("beads: saved %s.png (%d beads)" % (base, len(m.beads)))
        self.set_msg("status.bead.saved", os.path.basename(base + ".png"))

    # ---- text -------------------------------------------------------------
    def set_msg(self, key, *args):
        self._msg, self._msg_args = key, args
        try:
            self.lbl_msg.configure(text=cap(T(key, *args)))
        except Exception:
            pass

    def retranslate_view(self):
        if self.model:
            self.set_msg(self._msg, *self._msg_args)
            self.update_count()

for _lang in HELP:                    # help: English text under every language
    HELP[_lang].append(BEAD_HELP_BY_LANG.get(_lang, BEAD_HELP))



# ---- self test for part 6 (called from selftest, DEL 23) -------------------

def selftest_beads(check, notes):
    # ---- the boards ---------------------------------------------------------
    sizes = dict(sq10=100, sq15=225, sq20=400, sq29=841)
    for key in BOARD_KEYS:
        spec = BOARD_SPECS.get(key)
        if not check(spec, "bead board %s was not built" % key):
            continue
        pegs, guide = spec["pegs"], spec["guide"]
        check(("bead.board." + key) in TXT, "bead board %s has no name" % key)
        check(len(pegs) >= 50, "bead board %s has only %d pegs" % (key, len(pegs)))
        if key in sizes:
            check(len(pegs) == sizes[key] and guide is None,
                  "square %s should be %d pegs without a pattern" % (key, sizes[key]))
        rows = _SHAPE_ROWS.get(key)
        if rows:
            check(len(set(len(r) for r in rows)) == 1,
                  "bead shape %s: rows of different length" % key)
        if guide:
            check(set(guide) == pegs, "bead shape %s: pattern and pegs differ" % key)
            bad = set(guide.values()) - set(BEAD_HEX)
            check(not bad, "bead shape %s uses unknown colours %s" % (key, bad))
        # one piece, diagonals counting (feelers and tails touch corners)
        todo, seen = [min(pegs)], set()
        while todo:
            p = todo.pop()
            if p in seen:
                continue
            seen.add(p)
            for dc in (-1, 0, 1):
                for dr in (-1, 0, 1):
                    q = (p[0] + dc, p[1] + dr)
                    if q in pegs and q not in seen:
                        todo.append(q)
        check(seen == pegs, "bead board %s falls into %d pieces"
              % (key, 1 + len(pegs - seen)))
    for key in BOARD_KEYS:                       # the areas of every figure with a pattern
        spec = BOARD_SPECS[key]
        if not spec["guide"]:
            check(bead_areas(spec)["regions"] == [], "bead board %s has areas but no pattern" % key)
            continue
        ar = bead_areas(spec)
        check(set(ar["region_of"]) == set(spec["guide"]),
              "bead areas %s: some peg is in no area" % key)
        check(sum(len(r["cells"]) for r in ar["regions"]) == len(spec["guide"]),
              "bead areas %s: a peg is in two areas" % key)
        for i, rg in enumerate(ar["regions"]):
            check(all(ar["regions"][j]["tone"] != rg["tone"] for j in rg["near"]),
                  "bead areas %s: neighbouring areas share a grey" % key)
    check(len(bead_areas(BOARD_SPECS["dog"])["regions"]) >= 5, "the dog should have several areas")
    for key in ("bear", "cat", "rabbit", "dog", "butterfly", "heart", "star",
                "ladybird", "circle"):
        spec = BOARD_SPECS[key]
        g = spec["guide"] or dict((p, "x") for p in spec["pegs"])
        bad = [(c, r) for (c, r), ch in g.items()
               if g.get((spec["w"] - 1 - c, r)) != ch]
        check(not bad, "%s is not symmetric at %s" % (key, bad[:3]))
    notes.append("%d bead boards, %d colours" % (len(BOARD_KEYS), len(BEAD_COLOURS)))

    # ---- the model -----------------------------------------------------------
    m = BeadModel(BOARD_SPECS["sq10"])
    m.begin()
    check(m.put((0, 0), "R") and not m.put((0, 0), "R"), "put must report a change")
    check(not m.put((10, 10), "R"), "a bead off the board was accepted")
    check(not m.put((1, 1), "?"), "an unknown colour was accepted")
    m.settle()
    check(len(m.undo_stack) == 1, "a real action must stay in the history")
    m.begin()
    m.settle()
    check(len(m.undo_stack) == 1, "an action that changed nothing must be dropped")
    m.settle()
    check(len(m.undo_stack) == 1, "settle without begin must not pop history")
    check(m.undo() and not m.beads, "undo did not bring the board back")
    check(m.redo() and m.beads == {(0, 0): "R"}, "redo did not repeat it")
    check(not m.redo(), "redo with nothing to redo said yes")
    m.begin()
    m.clear()
    m.settle()
    check(m.undo() and (0, 0) in m.beads, "Erase all was not undoable")
    check(m.twin((0, 3)) == (9, 3) and m.twin((9, 3)) == (0, 3), "twin on sq10")
    check(BeadModel(BOARD_SPECS["sq15"]).twin((7, 3)) is None,
          "the middle peg has no twin")
    check(m.nearest_peg(0.5, 0.5, BEAD_REACH) == (0, 0), "nearest peg at a centre")
    check(m.nearest_peg(-0.3, 0.5, BEAD_REACH) == (0, 0), "a drop just off the edge")
    check(m.nearest_peg(-1.0, 0.5, BEAD_REACH) is None, "a drop far off the board")
    bear = BeadModel(BOARD_SPECS["bear"])
    check(bear.nearest_peg(0.5, 0.5, BEAD_REACH) is None,
          "a peg was found in the empty corner of the bear")
    for _ in range(BeadModel.HISTORY + 40):
        m.begin()
        m.put((5, 5), "K")
        m.take((5, 5))
        m.put((4, 4), "G" if len(m.undo_stack) % 2 else "W")
    check(len(m.undo_stack) <= BeadModel.HISTORY, "the history is not bounded")
    check(not bear.complete(), "an empty bear pattern counts as complete")
    for cell, ch in BOARD_SPECS["bear"]["guide"].items():
        bear.put(cell, ch)
    check(bear.complete() and bear.matched()[0] == bear.matched()[1],
          "a finished pattern was not recognised")
    bear.put(next(iter(bear.pegs)), "V")
    check(not bear.complete(), "a wrong bead still counted as complete")
    check(not BeadModel(BOARD_SPECS["sq10"]).complete(),
          "a square board has no pattern to complete")

    # ---- the picture file ----------------------------------------------------
    pm = BeadModel(BOARD_SPECS["sq10"])
    pm.put((0, 0), "R")
    pm.put((9, 9), "B")
    w, h, rgb = render_beads_rgb(pm, 20)
    pad = max(4, 20 // 3)
    check((w, h) == (10 * 20 + 2 * pad,) * 2, "picture size %dx%d" % (w, h))
    data = png_bytes(w, h, rgb)
    w2, h2, rows = png_pixels(data)
    check((w2, h2) == (w, h) and len(rows) == h, "PNG read back with another size")

    def px(col, row, u=0.7, v=0.7):
        x = int(pad + col * 20 + u * 20)
        y = int(pad + row * 20 + v * 20)
        return tuple(rows[y][x * 3:x * 3 + 3])
    check(px(0, 0) == _hex_rgb(BEAD_HEX["R"]), "red bead pixel is %s" % (px(0, 0),))
    check(px(9, 9) == _hex_rgb(BEAD_HEX["B"]), "blue bead pixel is %s" % (px(9, 9),))
    check(px(5, 5) == (255, 255, 255), "an empty peg must be white")
    check(px(0, 0, 0.5, 0.5) != _hex_rgb(BEAD_HEX["R"]), "the hole must show")
    try:
        from PIL import Image
        import io
        im = Image.open(io.BytesIO(data)).convert("RGB")
        check(im.size == (w, h), "Pillow reads another size")
        check(im.getpixel((int(pad + 0.7 * 20), int(pad + 0.7 * 20))) ==
              _hex_rgb(BEAD_HEX["R"]), "Pillow reads another colour")
        notes.append("bead PNG also read back by Pillow")
    except ImportError:
        notes.append("bead PNG checked by the hand-made reader only (no Pillow)")
    big = BeadModel(BOARD_SPECS["sq29"])
    for cell in big.pegs:
        big.put(cell, "G")
    t0 = time.time()
    render_beads_rgb(big)
    notes.append("29 x 29 board rendered in %.2f s" % (time.time() - t0))
    check(json.loads(json.dumps(pm.to_json()))["board"] == "sq10", "json")
    check(all(k in TXT for k in BEAD_TEXT), "bead texts missing from TXT")

# *************** DEL 20 - THE FIRST PAGE AND THE PROGRAM ITSELF ************
# The first page shows every activity as a card, three to a row.  To add one:
# a card_art_* function, a line in MODES, a show_* method on App - nothing else
# on this page changes.  The cards have a FIXED pixel size (CARD_W x CARD_H),
# so a longer sentence in another language wraps inside its card and never
# makes the page grow; two rows of them still fit the smallest window.


def card_art_maze(canvas, x, y, w, h):
    """A little maze, drawn the same way the real one is: thin walls on the
    page, the dog in one corner, the kennel in another, a crayon line between
    them."""
    cols, rows = 5, 4
    cell = min(w / float(cols), h / float(rows))
    ox = x + (w - cell * cols) / 2.0
    oy = y + (h - cell * rows) / 2.0
    wid = max(2, int(cell * 0.16))

    def seg(gx0, gy0, gx1, gy1):
        canvas.create_line(ox + gx0 * cell, oy + gy0 * cell,
                           ox + gx1 * cell, oy + gy1 * cell,
                           fill=WALLC, width=wid, capstyle="round")

    canvas.create_rectangle(ox, oy, ox + cols * cell, oy + rows * cell,
                            fill=PAPER, outline="")
    seg(0, 0, cols, 0)
    seg(0, rows, cols, rows)
    seg(0, 0, 0, rows)
    seg(cols, 0, cols, rows)
    for gx0, gy0, gx1, gy1 in ((2, 2, 2, 4), (1, 2, 3, 2), (3, 1, 3, 3),
                               (3, 1, 5, 1), (1, 0, 1, 1), (4, 2, 4, 4)):
        seg(gx0, gy0, gx1, gy1)
    canvas.create_line(ox + 0.5 * cell, oy + 3.5 * cell,
                       ox + 0.5 * cell, oy + 1.5 * cell,
                       ox + 2.5 * cell, oy + 1.5 * cell,
                       ox + 2.5 * cell, oy + 0.5 * cell,
                       ox + 4.5 * cell, oy + 0.5 * cell,
                       fill="#ef5350", width=max(3, int(cell * 0.28)),
                       capstyle="round", joinstyle="round")
    draw_prims(canvas, ART["dog"], ox + 0.5 * cell, oy + 3.5 * cell, cell)
    draw_prims(canvas, ART["kennel"], ox + 4.5 * cell, oy + 0.5 * cell, cell)


def card_art_colour(canvas, x, y, w, h):
    """A crayon over a half-coloured flower - what part 2 will be."""
    s = min(w, h)
    cx, cy = x + w / 2.0, y + h / 2.0
    draw_prims(canvas, ART["flower"], cx - s * 0.22, cy, s * 0.62)
    crayon = [
        poly([(0.20, 0.72), (0.66, 0.20), (0.82, 0.34), (0.36, 0.86)],
             fill="#43a047"),
        poly([(0.20, 0.72), (0.36, 0.86), (0.10, 0.92)], fill="#2e7d32"),
        poly([(0.44, 0.50), (0.60, 0.36), (0.72, 0.48), (0.56, 0.62)],
             fill="#c8e6c9"),
    ]
    draw_prims(canvas, crayon, cx + s * 0.26, cy - s * 0.04, s * 0.62)
    for i in range(3):
        canvas.create_line(cx - s * 0.36 + i * 6, cy + s * 0.34,
                           cx + s * 0.10 + i * 6, cy + s * 0.34,
                           fill=["#ef5350", "#fdd835", "#1e88e5"][i], width=4,
                           capstyle="round")


def card_art_jigsaw(canvas, x, y, w, h):
    """Four pieces, one of them not yet in place - what part 3 will be."""
    s = min(w, h) * 0.30
    cx, cy = x + w / 2.0, y + h / 2.0
    cols = ["#ef9a9a", "#a5d6a7", "#90caf9", "#ffe082"]
    spots = [(-0.55, -0.55), (0.45, -0.55), (-0.55, 0.45), (0.85, 0.75)]
    for (dx, dy), col in zip(spots, cols):
        px, py = cx + dx * s, cy + dy * s
        canvas.create_rectangle(px, py, px + s, py + s, fill=col,
                                outline=WALLC, width=2)
        canvas.create_oval(px + s * 0.72, py + s * 0.3, px + s * 1.18,
                           py + s * 0.76, fill=col, outline=WALLC, width=2)
        canvas.create_line(px + s * 0.78, py + s * 0.34, px + s * 0.78,
                           py + s * 0.72, fill=col, width=3)
    canvas.create_rectangle(cx - 0.55 * s + s, cy + 0.45 * s,
                            cx - 0.55 * s + 2 * s, cy + 1.45 * s,
                            fill="", outline="#bdae90", width=2, dash=(4, 3))


def card_art_spot(canvas, x, y, w, h):
    """Two copies of the dinosaur picture; the sun is missing in the second
    and ringed - drawn by the same code that plays the real puzzle."""
    pic = PICTURE_BY_KEY["dinos"]
    s = min((w - 14) / (2.0 * pic["w"]), h / float(pic["h"]))
    pw, ph = pic["w"] * s, pic["h"] * s
    x0 = x + (w - (2 * pw + 14)) / 2.0
    y0 = y + (h - ph) / 2.0
    parts_a = spot_parts(pic)
    parts_b = spot_apply(parts_a, [dict(change="hide", part="sun")])
    for k, parts in enumerate((parts_a, parts_b)):
        ox = x0 + k * (pw + 14)
        canvas.create_rectangle(ox - 2, y0 - 2, ox + pw + 2, y0 + ph + 2,
                                fill="#ffffff", outline=WALLC, width=2)
        draw_spot_parts(canvas, parts, ox, y0, s)
    sx0, sy0, sx1, sy1 = prims_bbox([pr for pt in pic["parts"]
                                     if pt["id"] == "sun"
                                     for pr in pt["prims"]])
    ox = x0 + pw + 14
    canvas.create_oval(ox + (sx0 - 22) * s, y0 + (sy0 - 22) * s,
                       ox + (sx1 + 22) * s, y0 + (sy1 + 22) * s,
                       outline=RING, width=3)


def card_art_match(canvas, x, y, w, h):
    """Three animals on the left, their partners shuffled on the right, and
    a coloured line from each one to the right partner."""
    left = ["dog", "mouse", "bee"]
    right = ["flower", "kennel", "cheese"]       # dog-kennel, mouse-cheese ...
    mate = {"dog": "kennel", "mouse": "cheese", "bee": "flower"}
    size = min(h / 3.0, 40)
    lx, rx = x + w * 0.22, x + w * 0.78
    ys = [y + h * (i + 0.5) / 3.0 for i in range(3)]
    for i, name in enumerate(left):
        j = right.index(mate[name])
        canvas.create_line(lx + size * 0.6, ys[i], rx - size * 0.6, ys[j],
                           fill=PAIR_COLOURS[i], width=4, capstyle="round")
    for i, name in enumerate(left):
        draw_prims(canvas, ART[name], lx, ys[i], size)
    for j, name in enumerate(right):
        draw_prims(canvas, ART[name], rx, ys[j], size)


MODES = [
    # key,          name key,        description key,      art,   command name
    ("maze",   "mode.maze",   "mode.maze.desc",   card_art_maze,   "show_maze"),
    ("colour", "mode.colour", "mode.colour.desc", card_art_colour,
     "show_colour"),
    ("jigsaw", "mode.jigsaw", "mode.jigsaw.desc", card_art_jigsaw,
     "show_jigsaw"),
    ("spot",   "mode.spot",   "mode.spot.desc",   card_art_spot,   "show_spot"),
    ("match",  "mode.match",  "mode.match.desc",  card_art_match,  "show_match"),
    ("beads",  "mode.beads",  "mode.beads.desc",  card_art_beads,  "show_beads"),
]

CARD_W, CARD_H = 262, 226          # pixels: every card is the same size
CARDS_PER_ROW = 3


class StartScreen(tk.Frame):

    def __init__(self, master, app):
        tk.Frame.__init__(self, master, bg=PAPER)
        self.app = app
        head = tk.Frame(self, bg=PAPER)
        head.pack(side="top", fill="x", pady=(14, 2))
        lab = tk.Label(head, bg=PAPER, fg=TEXTC, font=("Segoe UI", 22, "bold"),
                       width=width_for("app.title") + 4)
        reg(lab, "app.title")
        lab.pack()
        lab = tk.Label(head, bg=PAPER, fg=DIMC, font=FONT_UI,
                       width=width_for("app.tag") + 4)
        reg(lab, "app.tag")
        lab.pack(pady=(0, 0))
        lab = tk.Label(head, bg=PAPER, fg=TEXTC, font=FONT_UI_B,
                       width=width_for("app.pick") + 4)
        reg(lab, "app.pick")
        lab.pack(pady=(8, 0))

        foot = tk.Frame(self, bg=PAPER)
        foot.pack(side="bottom", fill="x", pady=(0, 14))
        tbutton(foot, "btn.quit", app.quit).pack(side="right", padx=18)
        tbutton(foot, "btn.about",
                lambda: show_about(app.root)).pack(side="right", padx=6)
        tbutton(foot, "btn.help",
                lambda: show_help(app.root)).pack(side="right", padx=6)
        tbutton(foot, "btn.settings",
                lambda: show_settings(app.root, app)).pack(side="right", padx=6)
        tbutton(foot, "btn.stats",
                lambda: show_stats(app.root)).pack(side="right", padx=6)

        # The cards sit in rows of CARDS_PER_ROW.  Each card has a fixed pixel
        # size, so a longer sentence in another language wraps inside it and
        # never makes a card (or a row) grow.
        cards = tk.Frame(self, bg=PAPER)
        cards.pack(side="top", expand=True)
        for first in range(0, len(MODES), CARDS_PER_ROW):
            row = tk.Frame(cards, bg=PAPER)
            row.pack(side="top")
            for key, namekey, desckey, art, cmd in MODES[first:first +
                                                         CARDS_PER_ROW]:
                self._card(row, key, namekey, desckey, art, cmd)

    def _card(self, parent, key, namekey, desckey, art, cmd):
        outer = tk.Frame(parent, bg=CARDBG, highlightthickness=2,
                         highlightbackground="#e0cfa8", width=CARD_W,
                         height=CARD_H)
        outer.pack(side="left", padx=9, pady=5)
        outer.pack_propagate(False)
        cv = tk.Canvas(outer, width=CARD_W - 24, height=96, bg=CARDBG,
                       highlightthickness=0)
        cv.pack(padx=10, pady=(8, 2))
        art(cv, 2, 2, CARD_W - 28, 92)
        lab = tk.Label(outer, bg=CARDBG, fg=TEXTC, font=("Segoe UI", 12, "bold"))
        reg(lab, namekey)
        lab.pack()
        lab = tk.Label(outer, bg=CARDBG, fg=DIMC, font=FONT_SMALL, height=3,
                       wraplength=CARD_W - 30, justify="center")
        reg(lab, desckey)
        lab.pack(padx=12, pady=(1, 4))
        if cmd:
            tbutton(outer, "btn.open",
                    getattr(self.app, cmd)).pack(pady=(0, 8))
        else:
            b = tk.Label(outer, bg=BTN_OFF, fg="#9e9e9e", font=FONT_UI,
                         width=width_for("btn.open", "mode.later") + 2,
                         relief="groove", bd=2, pady=3)
            reg(b, "mode.later")
            b.pack(pady=(0, 8))
            b.bind("<Button-1>", lambda e: self.app.not_built())


class App:
    """Holds the window, swaps the first page for an activity and back."""

    def __init__(self, root):
        self.root = root
        self.current = None
        self.start_screen = StartScreen(root, self)
        self.maze_view = None
        self.colour_view = None
        self.jigsaw_view = None
        self.spot_view = None
        self.match_view = None
        self.bead_view = None
        self.show_start()
        root.bind("<Key>", self.on_key)
        root.protocol("WM_DELETE_WINDOW", self.quit)
        on_retranslate(self.retitle)

    # ---- swapping pages ---------------------------------------------------
    def _show(self, widget):
        if self.current is widget:
            return
        if self.current is not None:
            self.current.pack_forget()
        self.current = widget
        widget.pack(fill="both", expand=True)

    def show_start(self):
        self._show(self.start_screen)
        self.retitle()

    def show_maze(self):
        if self.maze_view is None:
            self.maze_view = MazeView(self.root, self)
        self._show(self.maze_view)
        self.maze_view.canvas.focus_set()
        self.maze_view.redraw()
        self.retitle()

    def show_colour(self):
        if self.colour_view is None:
            self.colour_view = ColourView(self.root, self)
        self._show(self.colour_view)
        self.colour_view.canvas.focus_set()
        self.colour_view.redraw()
        self.retitle()

    def show_jigsaw(self):
        if self.jigsaw_view is None:
            self.jigsaw_view = JigsawView(self.root, self)
        self._show(self.jigsaw_view)
        self.jigsaw_view.canvas.focus_set()
        self.jigsaw_view.rebuild(scatter=False)
        self.retitle()

    def show_spot(self):
        if not SPOTS:
            self.not_built()
            return
        if self.spot_view is None:
            self.spot_view = SpotView(self.root, self)
        self._show(self.spot_view)
        self.spot_view.canvas.focus_set()
        self.spot_view.redraw()
        self.retitle()

    def show_match(self):
        if not MATCHES:
            self.not_built()
            return
        if self.match_view is None:
            self.match_view = MatchView(self.root, self)
        self._show(self.match_view)
        self.match_view.canvas.focus_set()
        self.match_view.redraw()
        self.retitle()

    def show_beads(self):
        if self.bead_view is None:
            self.bead_view = BeadView(self.root, self)
        self._show(self.bead_view)
        self.bead_view.canvas.focus_set()
        self.bead_view.redraw()
        self.retitle()

    def not_built(self):
        top = tk.Toplevel(self.root)
        top.title(T("app.title"))
        top.configure(bg=PAPER)
        top.resizable(False, False)
        top.transient(self.root)
        tk.Label(top, text=T("mode.notbuilt"), bg=PAPER, fg=TEXTC,
                 font=FONT_UI, wraplength=360).pack(padx=30, pady=(24, 14))
        tbutton(top, "btn.close", top.destroy).pack(pady=(0, 18))
        make_modal(top)
        centre_on(top, self.root)

    def retitle(self):
        name = T("app.title")
        if self.current is self.maze_view and self.maze_view is not None:
            name += " - " + T("mode.maze")
        elif self.current is self.colour_view and self.colour_view is not None:
            name += " - " + T("mode.colour")
        elif self.current is self.jigsaw_view and self.jigsaw_view is not None:
            name += " - " + T("mode.jigsaw")
        elif self.current is self.spot_view and self.spot_view is not None:
            name += " - " + T("mode.spot")
        elif self.current is self.match_view and self.match_view is not None:
            name += " - " + T("mode.match")
        elif self.current is self.bead_view and self.bead_view is not None:
            name += " - " + T("mode.beads")
        try:
            self.root.title(name)
        except Exception:
            pass

    # ---- settings changed in the dialog ----------------------------------
    def apply_settings(self):
        retranslate()
        mv = self.maze_view
        if mv is not None:
            mv.feed_var.set(bool(SETTINGS["feed"]))
            if SETTINGS["feed"]:
                mv.show_feed()
            else:
                mv.feed_frame.pack_forget()
            mv.opt_diff.set(SETTINGS["difficulty"])
            mv.opt_theme.set(SETTINGS["theme"])
            mv.opt_begin.set(SETTINGS["begin_at"])
            mv.redraw()
        self.retitle()

    # ---- keys go to whichever page is showing ----------------------------
    def on_key(self, event):
        view = self.current
        if view is not None and hasattr(view, "handle_key"):
            view.handle_key(event)

    def quit(self):
        log("QUIT")
        try:
            self.root.destroy()
        except Exception:
            pass

# *************** DEL 21 - ADD-ON PACKS (NEW CONTENT WITHOUT NEW CODE) ******
# A pack is ONE .json file dropped into Helpfiles\<program>\Packs.  It can
# carry new drawings, new maze stories, whole new pictures, spot-the-difference
# puzzles and matching sets, and the program reads them at startup as if they
# had always been in here.
#
# Why this exists: new content used to mean editing three places in a 5000
# line program by hand.  Handed out to several helpers at once that went
# wrong in every way it could - the same drawing arrived twice under
# different names, one story's THEME_ORDER line would have deleted another's,
# and every single one still had to be merged by hand.  A pack cannot do any
# of that:
#
#   * it is data, never code - nothing in a pack is executed;
#   * it never replaces anything.  A name that is already taken is renamed
#     (bear -> bear_2, and "Bear" -> "Bear (2)") before the pack is checked,
#     and the new name is followed through the pack's own stories, sets and
#     puzzles - so two helpers cannot overwrite each other, and a pack is no
#     longer thrown away only because somebody else also drew a bear.
#     (check_pack itself still refuses a taken name; it is the safety net);
#   * it never rewrites the order of the stories, it is appended to it;
#   * a pack with ONE bad number is refused WHOLE, so a half-loaded pack can
#     never leave the program in a state nobody has seen.
#
# The format is deliberately the same shape as the built-in data (DEL 09,
# DEL 10, DEL 17), and `--checkpack <file>` says exactly what is wrong with
# one before it is ever put in the folder.

PACKS_DIR = os.path.join(PROGRAM_HF_DIR, "Packs")
PACK_FORMAT = 1

# Guards.  Not because anyone is malicious, but because a file written by a
# machine can be wrong by a factor of a thousand and the program should say
# so instead of trying to draw it.
MAX_DRAWINGS = 60
MAX_STORIES = 30
MAX_PICTURES = 10
MAX_PRIMS = 80
MAX_POINTS = 400
MAX_PARTS = 90
MAX_SPOTS = 10
MAX_MATCHES = 10
ID_RE = re.compile(r"^[a-z][a-z0-9_]{0,23}$")
HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}$")

PACK_README = """This folder is where extra content for ActivityBook goes.

Drop a .json pack in here and start the program: new maze stories, new
drawings, new pictures, new spot-the-difference puzzles and new matching sets
appear by themselves.  Nothing in the program has to be edited, and a pack
can never overwrite what is already there.

    python ActivityBook.py --checkpack thepack.json

says whether a pack is sound, and exactly what is wrong with it if it is not.
A pack that fails is skipped whole; the rest keep working.

    python ActivityBook.py --inventory

lists everything that exists right now, built in and from packs, so the next
pack does not repeat a name that is taken.

The format is described in ActivityBook_instruction_for_HTTP-Claude.md.
"""

PACK_REPORT = []          # [(filename, ok, [problems], "what it added")]


def _num(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool)


def _colour_ok(v):
    return v is None or v == "" or (isinstance(v, str) and HEX_RE.match(v))


def check_prim_list(prims, where, box, out):
    """box = (w, h) for a picture part, or None for a 0..1 unit drawing."""
    if not isinstance(prims, list) or not prims:
        out.append("%s: there is nothing to draw" % where)
        return
    if len(prims) > MAX_PRIMS:
        out.append("%s: %d shapes, at most %d" % (where, len(prims), MAX_PRIMS))
        return
    lo_x, hi_x = (-0.2, 1.2) if box is None else (-20, box[0] + 20)
    lo_y, hi_y = (-0.2, 1.2) if box is None else (-20, box[1] + 20)
    for i, pr in enumerate(prims):
        tag = "%s, shape %d" % (where, i + 1)
        if not isinstance(pr, dict):
            out.append("%s: should be an object with a \"kind\"" % tag)
            continue
        kind = pr.get("kind")
        if kind not in ("poly", "line", "oval", "arc"):
            out.append("%s: \"kind\" is %r, expected poly, line, oval or arc"
                       % (tag, kind))
            continue
        if not _colour_ok(pr.get("fill")) or not _colour_ok(pr.get("line")):
            out.append("%s: colours must be \"#rrggbb\"" % tag)
        w = pr.get("w", 2.0)
        if not _num(w) or not (0 <= w <= 40):
            out.append("%s: \"w\" is %r, expected a line width from 0 (no "
                       "outline at all) to 40" % (tag, w))
        if kind in ("poly", "line"):
            pts = pr.get("pts")
            if not isinstance(pts, list) or len(pts) < 2:
                out.append("%s: needs at least two points" % tag)
                continue
            if len(pts) > MAX_POINTS:
                out.append("%s: %d points, at most %d"
                           % (tag, len(pts), MAX_POINTS))
                continue
            for p in pts:
                if not (isinstance(p, (list, tuple)) and len(p) == 2 and
                        _num(p[0]) and _num(p[1])):
                    out.append("%s: %r is not a point [x, y]" % (tag, p))
                    break
                if not (lo_x <= p[0] <= hi_x and lo_y <= p[1] <= hi_y):
                    out.append("%s: the point %r is outside the drawing area "
                               "(%g..%g, %g..%g)"
                               % (tag, p, lo_x, hi_x, lo_y, hi_y))
                    break
        else:
            bx = pr.get("box")
            if not (isinstance(bx, (list, tuple)) and len(bx) == 4 and
                    all(_num(v) for v in bx)):
                out.append("%s: \"box\" must be [x0, y0, x1, y1]" % tag)
                continue
            if not (lo_x <= bx[0] <= hi_x and lo_x <= bx[2] <= hi_x and
                    lo_y <= bx[1] <= hi_y and lo_y <= bx[3] <= hi_y):
                out.append("%s: the box is outside the drawing area" % tag)
            if kind == "arc" and not (_num(pr.get("start")) and
                                      _num(pr.get("extent"))):
                out.append("%s: an arc needs \"start\" and \"extent\" in "
                           "degrees" % tag)


def prims_from_json(prims):
    """JSON shapes -> the primitive dicts the rest of the program draws."""
    out = []
    for pr in prims:
        kind = pr["kind"]
        if kind in ("poly", "line"):
            pts = [(float(p[0]), float(p[1])) for p in pr["pts"]]
            if kind == "poly":
                out.append(poly(pts, fill=pr.get("fill"),
                                line=pr.get("line", INK),
                                w=float(pr.get("w", 2.0)),
                                smooth=bool(pr.get("smooth"))))
            else:
                out.append(pline(pts, line=pr.get("line", INK),
                                 w=float(pr.get("w", 2.0)),
                                 smooth=bool(pr.get("smooth"))))
        elif kind == "oval":
            out.append(oval([float(v) for v in pr["box"]],
                            fill=pr.get("fill"), line=pr.get("line", INK),
                            w=float(pr.get("w", 2.0))))
        else:
            out.append(arc([float(v) for v in pr["box"]],
                           float(pr["start"]), float(pr["extent"]),
                           line=pr.get("line", INK),
                           w=float(pr.get("w", 2.0))))
    return out


def check_name(name, where, out):
    if not (isinstance(name, (list, tuple)) and len(name) == 3 and
            all(isinstance(s, str) and s.strip() for s in name)):
        out.append("%s: \"name\" must be three non-empty strings "
                   "[English, Swedish, Russian]" % where)
        return False
    return True


def _spot_internal(d):
    """A difference as a pack writes it -> the dict the program plays with."""
    ch = d["change"]
    out = dict(change=ch, part=d.get("part"))
    if ch == "colour":
        out["to"] = d["to"]
    elif ch == "move":
        out["dx"], out["dy"] = float(d["dx"]), float(d["dy"])
    elif ch == "scale":
        out["factor"] = float(d["factor"])
    elif ch == "add":
        out["name"] = tuple(d["name"])
        out["prims"] = prims_from_json(d["prims"])
    return out


def _region_cells(rg, w, h):
    """The grid cells whose middle lies inside a difference's shapes."""
    cell = max(w, h) / float(SPOT_GRID)
    x0, y0, x1, y1 = rg["bbox"]
    cells = set()
    for gx in range(max(0, int(x0 // cell)), int(min(w, x1) // cell) + 1):
        for gy in range(max(0, int(y0 // cell)), int(min(h, y1) // cell) + 1):
            cx, cy = (gx + 0.5) * cell, (gy + 0.5) * cell
            if any(shape_hit(sh, cx, cy, 0.0) for sh in rg["shapes"]):
                cells.add((gx, gy))
    return cells


def check_spot(key, s, lookup, out):
    """Everything wrong with one spot-the-difference puzzle, in plain words.

    lookup(name) gives a picture (built in, from an earlier pack, or from this
    pack) or None.  The geometry is only judged once every field is sound."""
    where = "puzzle %r" % key
    if not ID_RE.match(str(key)):
        out.append("%s: a name is lower-case letters, digits and _, starting "
                   "with a letter" % where)
    if key in SPOT_BY_KEY:
        out.append("%s: that puzzle already exists" % where)
    if not isinstance(s, dict):
        out.append("%s: should be an object" % where)
        return
    check_name(s.get("name"), where, out)
    pic = lookup(s.get("picture"))
    if pic is None:
        out.append("%s: \"picture\" is %r, and there is no picture by that "
                   "name" % (where, s.get("picture")))
        return
    diffs = s.get("differences")
    if not (isinstance(diffs, list) and
            SPOT_POOL_MIN <= len(diffs) <= SPOT_POOL_MAX):
        out.append("%s: \"differences\" must list %d to %d of them - a round "
                   "shows %d, picked at random from the list"
                   % (where, SPOT_POOL_MIN, SPOT_POOL_MAX, SPOT_COUNT))
        return
    w, h = float(pic["w"]), float(pic["h"])
    parts = dict((pt["id"], pt) for pt in pic["parts"])
    used = set()
    problems_before = len(out)
    for i, d in enumerate(diffs):
        dw = "%s, difference %d" % (where, i + 1)
        if not isinstance(d, dict):
            out.append("%s: should be an object" % dw)
            continue
        ch = d.get("change")
        if ch not in SPOT_CHANGES:
            out.append("%s: \"change\" is %r, expected one of %s"
                       % (dw, ch, ", ".join(SPOT_CHANGES)))
            continue
        pt = None
        if ch != "add":
            pid = d.get("part")
            pt = parts.get(pid)
            if pt is None:
                out.append("%s: the picture %r has no part %r (its parts: %s)"
                           % (dw, s.get("picture"), pid,
                              ", ".join(sorted(parts))))
                continue
            if pid in used:
                out.append("%s: the part %r is used by another difference "
                           "too - one change per part" % (dw, pid))
                continue
            used.add(pid)
        if ch == "colour":
            to = d.get("to")
            if not (isinstance(to, str) and HEX_RE.match(to)):
                out.append("%s: \"to\" is the new colour, \"#rrggbb\"" % dw)
            elif not pt.get("fillable", True):
                out.append("%s: only a part that can be filled in can change "
                           "colour; %r is only a detail line" % (dw, d["part"]))
            elif colour_gap(pt["hint"], to) < SPOT_MIN_COLOUR_GAP:
                out.append("%s: %s is too close to the old colour %s - "
                           "nobody would see it; pick one that is clearly "
                           "different" % (dw, to, pt["hint"]))
        elif ch == "move":
            dx, dy = d.get("dx"), d.get("dy")
            if not (_num(dx) and _num(dy)) or max(abs(dx), abs(dy)) > max(w, h):
                out.append("%s: \"dx\" and \"dy\" are how far the part moves, "
                           "in picture units" % dw)
        elif ch == "scale":
            f = d.get("factor")
            if not _num(f) or not (0.3 <= f <= 0.75 or 1.3 <= f <= 2.5):
                out.append("%s: \"factor\" is 0.3 to 0.75 (smaller) or 1.3 to "
                           "2.5 (bigger); anything in between is too little "
                           "to see" % dw)
        elif ch == "add":
            check_name(d.get("name"), dw, out)
            check_prim_list(d.get("prims"), dw, (w, h), out)
    if len(out) > problems_before:
        return

    try:
        a_parts = spot_parts(pic)
        internal = [_spot_internal(d) for d in diffs]
        regions = spot_regions(a_parts, internal)
    except Exception as exc:
        out.append("%s: could not be checked (%s)" % (where, exc))
        return
    ids = [p["id"] for p in a_parts]
    min_side = SPOT_MIN_SIDE * max(w, h)
    cells = []
    for i, (d, rg) in enumerate(zip(internal, regions)):
        dw = "%s, difference %d" % (where, i + 1)
        if d["change"] == "add":
            own = rg["bbox"]
        else:
            own = prims_bbox(a_parts[ids.index(d["part"])]["prims"])
        side = max(own[2] - own[0], own[3] - own[1])
        if d["change"] == "scale":
            side *= d["factor"]
        if side < min_side:
            out.append("%s: it is only %d units across and would be too small "
                       "to spot - a difference needs at least %d; pick a "
                       "bigger part" % (dw, side, min_side))
        if d["change"] == "move":
            gap = math.hypot(d["dx"], d["dy"])
            need = max(0.05 * max(w, h), 0.35 * side)
            if gap < need:
                out.append("%s: it moves only %d units; at least %d is needed "
                           "to be seen" % (dw, gap, need))
        if d["change"] in ("move", "scale"):
            b = rg["bbox"]
            if b[0] < -10 or b[1] < -10 or b[2] > w + 10 or b[3] > h + 10:
                out.append("%s: the changed part would stick out of the "
                           "picture" % dw)
        cells.append(_region_cells(rg, w, h))
    for i in range(len(cells)):
        for j in range(i + 1, len(cells)):
            smaller = min(len(cells[i]), len(cells[j]))
            both = len(cells[i] & cells[j])
            if smaller and both > 0.25 * smaller:
                out.append("%s: differences %d and %d sit on top of each "
                           "other - spread them out" % (where, i + 1, j + 1))


def check_match(key, m, have, out):
    """Everything wrong with one matching set.  `have` = the drawings that
    exist (built in plus this pack's own)."""
    where = "matching set %r" % key
    if not ID_RE.match(str(key)):
        out.append("%s: a name is lower-case letters, digits and _, starting "
                   "with a letter" % where)
    if key in MATCH_BY_KEY:
        out.append("%s: that set already exists" % where)
    if not isinstance(m, dict):
        out.append("%s: should be an object" % where)
        return
    check_name(m.get("name"), where, out)
    if ("pairs" in m) == ("shadows" in m):
        out.append("%s: give EITHER \"pairs\" (two drawings that belong "
                   "together) OR \"shadows\" (animals and their black "
                   "shadows), not both and not neither" % where)
        return
    names = []
    if "pairs" in m:
        pairs = m["pairs"]
        if not (isinstance(pairs, list) and
                MATCH_MIN <= len(pairs) <= MATCH_MAX):
            out.append("%s: \"pairs\" must list %d to %d pairs"
                       % (where, MATCH_MIN, MATCH_MAX))
            return
        for i, p in enumerate(pairs):
            if not (isinstance(p, (list, tuple)) and len(p) == 2 and
                    all(isinstance(x, str) for x in p)):
                out.append("%s, pair %d: should be [\"drawing\", \"partner\"]"
                           % (where, i + 1))
                continue
            if p[0] == p[1]:
                out.append("%s, pair %d: %r is paired with itself - for an "
                           "animal and its shadow use \"shadows\""
                           % (where, i + 1, p[0]))
            names += list(p)
    else:
        sh = m["shadows"]
        if not (isinstance(sh, list) and MATCH_MIN <= len(sh) <= MATCH_MAX and
                all(isinstance(x, str) for x in sh)):
            out.append("%s: \"shadows\" must list %d to %d drawing names"
                       % (where, MATCH_MIN, MATCH_MAX))
            return
        names = list(sh)
    for n in names:
        if n not in have:
            out.append("%s: there is no drawing called %r" % (where, n))
    seen = set()
    for n in names:
        if n in seen:
            out.append("%s: the drawing %r is used twice - every picture in a "
                       "set may stand in only ONE pair, or the child cannot "
                       "tell which partner is meant" % (where, n))
        seen.add(n)


def check_pack(data, known_art, known_themes, known_pics):
    """Everything wrong with one pack, in plain words.  Empty list = sound."""
    out = []
    if not isinstance(data, dict):
        return ["the file should contain one object { ... }"]
    fmt = data.get("format", PACK_FORMAT)
    if fmt != PACK_FORMAT:
        out.append("\"format\" is %r, this program reads format %d"
                   % (fmt, PACK_FORMAT))
    if not isinstance(data.get("pack", ""), str):
        out.append("\"pack\" should be a short name for the pack")

    drawings = data.get("drawings") or {}
    stories = data.get("stories") or {}
    pictures = data.get("pictures") or []
    spots = data.get("spots") or {}
    matches = data.get("matches") or {}
    if not (drawings or stories or pictures or spots or matches):
        out.append("the pack is empty - it has no drawings, stories, "
                   "pictures, spots or matches")
    if not isinstance(spots, dict):
        out.append("\"spots\" should be an object of name -> puzzle")
        spots = {}
    if not isinstance(matches, dict):
        out.append("\"matches\" should be an object of name -> set")
        matches = {}
    if len(spots) > MAX_SPOTS or len(matches) > MAX_MATCHES:
        out.append("the pack is too big: at most %d spot puzzles and %d "
                   "matching sets" % (MAX_SPOTS, MAX_MATCHES))
    if not isinstance(drawings, dict):
        out.append("\"drawings\" should be an object of name -> drawing")
        drawings = {}
    if not isinstance(stories, dict):
        out.append("\"stories\" should be an object of name -> story")
        stories = {}
    if not isinstance(pictures, list):
        out.append("\"pictures\" should be a list")
        pictures = []
    if len(drawings) > MAX_DRAWINGS or len(stories) > MAX_STORIES or \
            len(pictures) > MAX_PICTURES:
        out.append("the pack is too big: at most %d drawings, %d stories and "
                   "%d pictures" % (MAX_DRAWINGS, MAX_STORIES, MAX_PICTURES))

    for key, d in sorted(drawings.items()):
        where = "drawing %r" % key
        if not ID_RE.match(str(key)):
            out.append("%s: a name is lower-case letters, digits and _, "
                       "starting with a letter" % where)
        if key in known_art:
            out.append("%s: that name is already taken - pick another, or "
                       "leave the drawing out and use the one that exists"
                       % where)
        if not isinstance(d, dict):
            out.append("%s: should be an object" % where)
            continue
        check_name(d.get("name"), where, out)
        check_prim_list(d.get("prims"), where, None, out)

    for key, s in sorted(stories.items()):
        where = "story %r" % key
        if not ID_RE.match(str(key)):
            out.append("%s: a name is lower-case letters, digits and _, "
                       "starting with a letter" % where)
        if key in known_themes:
            out.append("%s: that story already exists" % where)
        if not isinstance(s, dict):
            out.append("%s: should be an object" % where)
            continue
        check_name(s.get("name"), where, out)
        have = set(known_art) | set(drawings)
        for role in ("hero", "goal"):
            who = s.get(role)
            if not isinstance(who, str) or not who:
                out.append("%s: \"%s\" is missing" % (where, role))
            elif who not in have:
                out.append("%s: the %s is %r, and there is no drawing by that "
                           "name" % (where, role, who))
        if s.get("hero") and s.get("hero") == s.get("goal"):
            out.append("%s: the hero and the goal are the same drawing"
                       % where)
        decoys = s.get("decoys")
        if not (isinstance(decoys, list) and decoys):
            out.append("%s: \"decoys\" must list at least one wrong place"
                       % where)
        else:
            for who in decoys:
                if who not in have:
                    out.append("%s: the decoy %r has no drawing"
                               % (where, who))
            if "wall" not in decoys:
                out.append("%s: put \"wall\" among the decoys - the plain "
                           "dead end is what the puzzle is named after"
                           % where)

    for i, pic in enumerate(pictures):
        where = "picture %d" % (i + 1)
        if not isinstance(pic, dict):
            out.append("%s: should be an object" % where)
            continue
        key = pic.get("key")
        where = "picture %r" % key
        if not ID_RE.match(str(key or "")):
            out.append("%s: a key is lower-case letters, digits and _, "
                       "starting with a letter" % where)
        if key in known_pics:
            out.append("%s: that picture already exists" % where)
        check_name(pic.get("name"), where, out)
        w, h = pic.get("w"), pic.get("h")
        if not (_num(w) and _num(h) and 100 <= w <= 4000 and
                100 <= h <= 4000):
            out.append("%s: \"w\" and \"h\" are the size of the picture, "
                       "100..4000" % where)
            continue
        parts = pic.get("parts")
        if not (isinstance(parts, list) and parts):
            out.append("%s: a picture needs parts" % where)
            continue
        if len(parts) > MAX_PARTS:
            out.append("%s: %d parts, at most %d"
                       % (where, len(parts), MAX_PARTS))
            continue
        seen = set()
        fillable = 0
        for pt in parts:
            if not isinstance(pt, dict):
                out.append("%s: every part is an object" % where)
                continue
            pid = pt.get("id")
            pwhere = "%s, part %r" % (where, pid)
            if not ID_RE.match(str(pid or "")):
                out.append("%s: the id must be lower-case letters, digits "
                           "and _" % pwhere)
            if pid in seen:
                out.append("%s: two parts share that id" % pwhere)
            seen.add(pid)
            if not (isinstance(pt.get("label"), (list, tuple)) and
                    len(pt["label"]) == 3 and
                    all(isinstance(s, str) and s.strip()
                        for s in pt["label"])):
                out.append("%s: \"label\" must be three non-empty strings"
                           % pwhere)
            if not HEX_RE.match(str(pt.get("hint", ""))):
                out.append("%s: \"hint\" is the part's natural colour, "
                           "\"#rrggbb\"" % pwhere)
            if pt.get("fillable", True):
                fillable += 1
                if isinstance(pt.get("prims"), list) and not any(
                        isinstance(p, dict) and
                        p.get("kind") in ("poly", "oval")
                        for p in pt["prims"]):
                    out.append("%s: it can be filled in but has no shape to "
                               "fill" % pwhere)
            check_prim_list(pt.get("prims"), pwhere, (w, h), out)
        if fillable < 3:
            out.append("%s: almost nothing can be coloured in" % where)

    # spot-the-difference puzzles may use a picture of this very pack, or one
    # that already exists (built in, or from a pack that loaded earlier)
    own_pics = dict((p["key"], p) for p in pictures
                    if isinstance(p, dict) and isinstance(p.get("key"), str))

    def lookup(name):
        if not isinstance(name, str):
            return None
        return own_pics.get(name) or PICTURE_BY_KEY.get(name)

    for key, s in sorted(spots.items()):
        try:
            check_spot(key, s, lookup, out)
        except Exception as exc:
            out.append("puzzle %r: could not be checked (%s)" % (key, exc))
    have = set(known_art) | set(drawings)
    for key, m in sorted(matches.items()):
        try:
            check_match(key, m, have, out)
        except Exception as exc:
            out.append("matching set %r: could not be checked (%s)" % (key, exc))
    return out


def merge_pack(data):
    """Put a checked pack into the program's own tables.  Returns a summary."""
    added = []
    for key, d in sorted((data.get("drawings") or {}).items()):
        ART[key] = prims_from_json(d["prims"])
        TXT["name." + key] = tuple(d["name"])
        added.append("drawing " + key)
    for key, s in sorted((data.get("stories") or {}).items()):
        THEMES[key] = dict(hero=s["hero"], goal=s["goal"],
                           decoys=list(s["decoys"]))
        TXT["theme." + key] = tuple(s["name"])
        THEME_ORDER.append(key)          # appended, never rewritten
        added.append("story " + key)
    for pic in (data.get("pictures") or []):
        parts = [part(pt["id"], prims_from_json(pt["prims"]),
                      tuple(pt["label"]), pt["hint"],
                      bool(pt.get("fillable", True)))
                 for pt in pic["parts"]]
        built = picture(pic["key"], tuple(pic["name"]), float(pic["w"]),
                        float(pic["h"]), parts)
        PICTURES.append(built)
        PICTURE_BY_KEY[pic["key"]] = built
        PICTURE_ORDER.append(pic["key"])
        TXT["pic." + pic["key"]] = tuple(pic["name"])
        added.append("picture " + pic["key"])
    for key, s in sorted((data.get("spots") or {}).items()):
        built = dict(key=key, name=tuple(s["name"]), picture=s["picture"],
                     diffs=[_spot_internal(d) for d in s["differences"]])
        SPOTS.append(built)
        SPOT_BY_KEY[key] = built
        TXT["spotname." + key] = tuple(s["name"])
        added.append("puzzle " + key)
    for key, m in sorted((data.get("matches") or {}).items()):
        if "pairs" in m:
            kind, pairs = "pairs", [tuple(p) for p in m["pairs"]]
        else:
            kind, pairs = "shadows", [(k, k) for k in m["shadows"]]
        built = dict(key=key, name=tuple(m["name"]), kind=kind, pairs=pairs)
        MATCHES.append(built)
        MATCH_BY_KEY[key] = built
        TXT["matchname." + key] = tuple(m["name"])
        added.append("set " + key)
    return added


# ---- the puzzles that come with the program --------------------------------
# They are written in the pack format and go through the very same checker and
# the very same merge as a pack from the folder (below), so what the
# instruction document tells another Claude is exactly what the program itself
# is built from - and a built-in puzzle that broke the rules would be refused
# like any other.

BUILTIN_PACK = {
    "format": 1,
    "pack": "built-in",
    "spots": {
        "volcano": {
            "name": ["Dinosaurs at the volcano", "Dinosaurier vid vulkanen",
                     "Динозавры у вулкана"],
            "picture": "dinos",
            "differences": [
                {"part": "sun", "change": "hide"},
                {"part": "smoke", "change": "hide"},
                {"part": "lava", "change": "colour", "to": "#42a5f5"},
                {"part": "cloud", "change": "colour", "to": "#ce93d8"},
                {"part": "bronto_spots", "change": "colour", "to": "#fdd835"},
                {"part": "trex_tail", "change": "colour", "to": "#64b5f6"},
                {"part": "stone2", "change": "hide"},
                {"part": "stone3", "change": "move", "dx": 90, "dy": 0},
                {"part": "fern", "change": "scale", "factor": 0.6},
                {"change": "add",
                 "name": ["a bird", "en fågel", "птица"],
                 "prims": [
                     {"kind": "poly", "pts": [[262, 82], [240, 72], [244, 94]],
                      "fill": "#f9a825", "w": 3},
                     {"kind": "oval", "box": [258, 66, 322, 102],
                      "fill": "#fdd835", "w": 3},
                     {"kind": "poly", "pts": [[272, 78], [292, 50], [308, 80]],
                      "fill": "#f9a825", "w": 3},
                     {"kind": "oval", "box": [306, 52, 338, 84],
                      "fill": "#fdd835", "w": 3},
                     {"kind": "poly", "pts": [[336, 64], [354, 71], [336, 78]],
                      "fill": "#fb8c00", "w": 2},
                     {"kind": "oval", "box": [322, 60, 329, 67],
                      "fill": "#3e2723", "line": "", "w": 0}]},
            ],
        },
    },
    "matches": {
        "friends": {
            "name": ["Who belongs together?", "Vilka hör ihop?",
                     "Что к чему подходит?"],
            "pairs": [["dog", "kennel"], ["mouse", "cheese"],
                      ["bee", "flower"], ["penguin", "fish"],
                      ["seal", "icehole"]],
        },
    },
}

BUILTIN_REPORT = []          # what was wrong with them - must stay empty
_BUILTIN_DONE = [False]


def load_builtin_content():
    """Put the built-in puzzles in.  Safe to call twice; the second does nothing."""
    if _BUILTIN_DONE[0]:
        return
    _BUILTIN_DONE[0] = True
    problems = check_pack(BUILTIN_PACK, ART, THEMES, PICTURE_BY_KEY)
    if problems:
        BUILTIN_REPORT.extend(problems)
        log("BUILT-IN puzzles REFUSED (%d problems): %s"
            % (len(problems), problems[0]))
        return
    merge_pack(BUILTIN_PACK)


def read_pack_file(path):
    with open(path, "r", encoding="utf-8-sig") as fh:
        return json.load(fh)


# ToDo: the renaming below only happens for names that are TAKEN when the pack
# is read.  Two packs that both define "bear" therefore end up as bear (the
# first, in name order) and bear_2 (the second) - the order of the file names
# decides, which is why a pack that needs another pack's drawings must sort
# after it.

def _free_name(key, taken):
    """`key`, or key_2, key_3 ... - the first not in `taken`, cut so that it
    still fits ID_RE (24 characters).  Returns (name, number or 0)."""
    if key not in taken:
        return key, 0
    n = 2
    while True:
        tail = "_%d" % n
        cand = key[:24 - len(tail)] + tail
        if cand not in taken:
            return cand, n
        n += 1


def _numbered(name, n):
    """A three-language title with " (n)" added to each language."""
    if (isinstance(name, (list, tuple)) and len(name) == 3 and
            all(isinstance(s, str) for s in name)):
        return ["%s (%d)" % (s, n) for s in name]
    return name


def uniquify_pack(data):
    """Rename what a pack calls by a name that is already taken, and follow
    the new name through the pack itself.  Returns (pack, ["drawing bear ->
    bear_2", ...]).  The pack is copied, never changed.  A pack that is not
    even the right shape comes back as it is, for check_pack to describe."""
    try:
        return _uniquify_pack(data)
    except Exception as exc:
        log("pack: could not look for taken names (%s)" % exc)
        return data, []


def _uniquify_pack(data):
    if not isinstance(data, dict):
        return data, []
    drawings = data.get("drawings") or {}
    stories = data.get("stories") or {}
    pictures = data.get("pictures") or []
    spots = data.get("spots") or {}
    matches = data.get("matches") or {}
    if not (isinstance(drawings, dict) and isinstance(stories, dict) and
            isinstance(pictures, list) and isinstance(spots, dict) and
            isinstance(matches, dict)):
        return data, []
    pic_keys = [p.get("key") for p in pictures if isinstance(p, dict)]
    every = list(drawings) + list(stories) + pic_keys + list(spots) + \
        list(matches)
    if not all(isinstance(k, str) for k in every):
        return data, []
    if not (any(k in ART for k in drawings) or
            any(k in THEMES for k in stories) or
            any(k in PICTURE_BY_KEY for k in pic_keys) or
            any(k in SPOT_BY_KEY for k in spots) or
            any(k in MATCH_BY_KEY for k in matches)):
        return data, []                       # nothing clashes: leave it alone

    out = json.loads(json.dumps(data))        # a deep copy of plain data
    for section, empty in (("drawings", {}), ("stories", {}), ("pictures", []),
                           ("spots", {}), ("matches", {})):
        if not out.get(section):
            out[section] = empty              # a missing or null section
    notes = []

    def renames(keys, known, what):
        """{old: (new, n)} for every key in `keys` that `known` has taken."""
        taken = set(known) | set(keys)
        mapping = {}
        for k in keys:
            if k in known:
                new, n = _free_name(k, taken)
                taken.add(new)
                mapping[k] = (new, n)
                notes.append("%s %s -> %s" % (what, k, new))
        return mapping

    art_map = renames(list(drawings), ART, "drawing")
    story_map = renames(list(stories), THEMES, "story")
    pic_map = renames(pic_keys, PICTURE_BY_KEY, "picture")
    spot_map = renames(list(spots), SPOT_BY_KEY, "puzzle")
    match_map = renames(list(matches), MATCH_BY_KEY, "set")

    def art(name):
        return art_map[name][0] if name in art_map else name

    if art_map:
        out["drawings"] = dict((art(k), v) for k, v in out["drawings"].items())
    if art_map or story_map:
        fixed = {}
        for k, s in out["stories"].items():
            if isinstance(s, dict):
                for role in ("hero", "goal"):
                    if isinstance(s.get(role), str):
                        s[role] = art(s[role])
                if isinstance(s.get("decoys"), list):
                    s["decoys"] = [art(x) if isinstance(x, str) else x
                                   for x in s["decoys"]]
                if k in story_map:
                    s["name"] = _numbered(s.get("name"), story_map[k][1])
            fixed[story_map[k][0] if k in story_map else k] = s
        out["stories"] = fixed
    for pic in out.get("pictures") or []:
        if isinstance(pic, dict) and pic.get("key") in pic_map:
            pic["name"] = _numbered(pic.get("name"), pic_map[pic["key"]][1])
            pic["key"] = pic_map[pic["key"]][0]
    if pic_map or spot_map:
        fixed = {}
        for k, s in out["spots"].items():
            if isinstance(s, dict):
                if s.get("picture") in pic_map:
                    s["picture"] = pic_map[s["picture"]][0]
                if k in spot_map:
                    s["name"] = _numbered(s.get("name"), spot_map[k][1])
            fixed[spot_map[k][0] if k in spot_map else k] = s
        out["spots"] = fixed
    if art_map or match_map:
        fixed = {}
        for k, m in out["matches"].items():
            if isinstance(m, dict):
                if isinstance(m.get("pairs"), list):
                    m["pairs"] = [[art(x) if isinstance(x, str) else x
                                   for x in pr] if isinstance(pr, list) else pr
                                  for pr in m["pairs"]]
                if isinstance(m.get("shadows"), list):
                    m["shadows"] = [art(x) if isinstance(x, str) else x
                                    for x in m["shadows"]]
                if k in match_map:
                    m["name"] = _numbered(m.get("name"), match_map[k][1])
            fixed[match_map[k][0] if k in match_map else k] = m
        out["matches"] = fixed
    return out, notes


def load_packs(skip=None):
    """Every sound pack in the Packs folder, in name order.  Never raises.
    `skip` = a file name to leave out (--checkpack of a file in the folder)."""
    del PACK_REPORT[:]
    load_builtin_content()
    try:
        os.makedirs(PACKS_DIR, exist_ok=True)
        readme = os.path.join(PACKS_DIR, "README.txt")
        if not os.path.isfile(readme):
            with open(readme, "w", encoding="utf-8") as fh:
                fh.write(PACK_README)
    except Exception:
        return PACK_REPORT
    try:
        names = sorted(n for n in os.listdir(PACKS_DIR)
                       if n.lower().endswith(".json"))
    except Exception:
        return PACK_REPORT
    for name in names:
        if skip and name.lower() == skip.lower():
            continue
        path = os.path.join(PACKS_DIR, name)
        try:
            data = read_pack_file(path)
        except Exception as exc:
            PACK_REPORT.append((name, False, ["the file is not readable "
                                              "JSON: %s" % exc], []))
            log("pack %s REFUSED: unreadable (%s)" % (name, exc))
            continue
        data, renamed = uniquify_pack(data)
        problems = check_pack(data, ART, THEMES, PICTURE_BY_KEY)
        if problems:
            PACK_REPORT.append((name, False, problems, []))
            log("pack %s REFUSED (%d problems): %s"
                % (name, len(problems), problems[0]))
            continue
        try:
            added = merge_pack(data)
        except Exception as exc:                 # belt and braces
            PACK_REPORT.append((name, False, ["it could not be read in: %s"
                                              % exc], []))
            log("pack %s REFUSED while merging: %s" % (name, exc))
            continue
        if renamed:
            added.append("(names already taken, renamed: %s)"
                         % ", ".join(renamed))
        PACK_REPORT.append((name, True, [], added))
        log("pack %s loaded: %s" % (name, ", ".join(added)))
    return PACK_REPORT


def pack_report_text():
    if not PACK_REPORT:
        return "No packs in %s." % PACKS_DIR
    rows = []
    for name, ok, problems, added in PACK_REPORT:
        if ok:
            rows.append("OK       %s  ->  %s" % (name, ", ".join(added)))
        else:
            rows.append("REFUSED  %s" % name)
            for p in problems:
                rows.append("             %s" % p)
    return "\n".join(rows)


def check_one_pack(path):
    """--checkpack: say what is wrong with a file without loading it."""
    if not os.path.isfile(path):
        print_safe("There is no file called %s" % path)
        return 2
    try:
        data = read_pack_file(path)
    except Exception as exc:
        print_safe("%s is not readable JSON:\n  %s" % (path, exc))
        return 1
    # Judge it against what the program REALLY has when it starts: the built-in
    # content plus every other pack in the folder (it used to be only the
    # built-in content, so a pack was "sound" here and refused at start).
    load_packs(skip=os.path.basename(path))
    data, renamed = uniquify_pack(data)
    if renamed:
        print_safe("These names are already taken by the program or another "
                   "pack, so the program will give the pack's own a number:\n"
                   "  %s\n" % "\n  ".join(renamed))
    problems = check_pack(data, ART, THEMES, PICTURE_BY_KEY)
    if problems:
        print_safe("%s: %d thing%s to fix\n" % (path, len(problems),
                                                "" if len(problems) == 1
                                                else "s"))
        for p in problems:
            print_safe("  * %s" % p)
        return 1
    counts = (len(data.get("drawings") or {}), len(data.get("stories") or {}),
              len(data.get("pictures") or []), len(data.get("spots") or {}),
              len(data.get("matches") or {}))
    print_safe("%s is sound: %d drawing(s), %d story(ies), %d picture(s), "
               "%d spot puzzle(s), %d matching set(s).\n"
               "Copy it into %s and start the program."
               % ((path,) + counts + (PACKS_DIR,)))
    return 0


# *************** DEL 22 - WHAT ALREADY EXISTS (--inventory) *****************
# The instruction that goes to another Claude (HTTP-Claude) so it can add more
# stories is a hand-written document - prose does not rot.  The LIST of what
# is already in here does rot, every single time something is added, so it is
# not hand-written: this prints it.
#
#   python ActivityBook.py --inventory
#
# Paste the result into the instruction file's "what already exists" section
# (or just send it along with the file).  Whoever reads it then knows which
# names are taken and which drawings can be reused, without ever seeing the
# program.


INSTRUCTION_FILE = "%s_instruction_for_HTTP-Claude.md"
INVENTORY_START = "<!-- inventory:start -->"
INVENTORY_END = "<!-- inventory:end -->"


def find_instruction_file(explicit=None):
    """The instruction document, wherever Lars keeps it.

    Only a file that already carries the two inventory markers is ever
    written to, so this can never overwrite something it did not mean."""
    name = INSTRUCTION_FILE % PROGRAM_NAME
    here = os.path.dirname(os.path.abspath(
        sys.executable if getattr(sys, "frozen", False)
        else globals().get("__file__", ".")))
    tries = [explicit] if explicit else []
    tries += [os.path.join(here, name),
              os.path.join(os.path.dirname(here), name),
              os.path.join(BASE_DIR, name),
              os.path.join(PROGRAM_HF_DIR, name)]
    for path in tries:
        if path and os.path.isfile(path):
            try:
                with open(path, "r", encoding="utf-8") as fh:
                    body = fh.read()
            except Exception:
                continue
            if INVENTORY_START in body and INVENTORY_END in body:
                return path, body
    return None, None


def refresh_instructions(explicit=None):
    """Put today's inventory into the instruction file, between the markers."""
    path, body = find_instruction_file(explicit)
    if not path:
        return None
    head = body.split(INVENTORY_START)[0]
    tail = body.split(INVENTORY_END, 1)[1]
    new = (head + INVENTORY_START + "\n\n" + inventory_text() + "\n" +
           INVENTORY_END + tail)
    if new == body:
        return path                       # already current, nothing written
    with open(path, "w", encoding="utf-8", newline="\n") as fh:
        fh.write(new)
    return path


def print_safe(text):
    """Print text that a Windows console cannot always encode.

    The console here is cp1252: printing Russian to it raises
    UnicodeEncodeError and would kill the whole command.  The FILE is written
    as UTF-8 and keeps every letter; only what scrolls past gets the
    question marks."""
    try:
        print(text)
    except UnicodeEncodeError:
        enc = getattr(sys.stdout, "encoding", None) or "ascii"
        print(text.encode(enc, "replace").decode(enc, "replace"))


def pictures_as_pack_data():
    """Every picture that exists, in the pack format - what packtool.py reads
    as picture_data.json, so a spot-the-difference puzzle on an EXISTING
    picture can be checked and drawn by someone who does not have the
    program."""
    out = []
    for pic in PICTURES:
        out.append(dict(
            key=pic["key"], name=list(pic["name"]), w=pic["w"], h=pic["h"],
            parts=[dict(id=pt["id"], label=list(pt["label"]),
                        hint=pt["hint"],
                        fillable=bool(pt.get("fillable", True)),
                        prims=pt["prims"]) for pt in pic["parts"]]))
    return {"pictures": out}


def export_pictures(path=None):
    path = path or os.path.join(PROGRAM_HF_DIR, "picture_data.json")
    ensure_dirs()
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(pictures_as_pack_data(), fh, ensure_ascii=False,
                  separators=(",", ":"))
    return path


def inventory_text():
    out = []
    add = out.append
    add("### What already exists (generated by `%s --inventory`)" % PROGRAM_NAME)
    add("")
    add("Languages: %s. Text keys: %d, each with all three."
        % (", ".join(LANG_NAMES[c] for c in LANGS), len(TXT)))
    add("")

    add("**Maze sizes** (name, squares, how many wrong places get a drawing):")
    add("")
    for d in DIFF_ORDER:
        w, h, decoys = DIFFS[d]
        add("* `%s` - %s, %d x %d squares, %d decoys"
            % (d, TXT["diff." + d][0], w, h, decoys))
    add("")

    # Written hero -> goal, because that arrow is the only thing that says
    # which drawing the animal starts on and which one it is trying to reach.
    # The program shows the player the same pair the same way, as pictures.
    add("**Maze stories** (`THEMES`, in `THEME_ORDER`), written `hero -> goal`:")
    add("")
    for key in THEME_ORDER:
        t = THEMES[key]
        add("* `%s`:  **%s -> %s**  (past: %s)"
            % (key, t["hero"], t["goal"],
               ", ".join(sorted(set(t["decoys"])))))
    add("")

    used = {}
    for key in THEME_ORDER:
        t = THEMES[key]
        for who in [t["hero"], t["goal"]] + list(t["decoys"]):
            used.setdefault(who, set()).add(key)
    for m in MATCHES:
        for pair in m["pairs"]:
            for who in pair:
                used.setdefault(who, set()).add("matching set " + m["key"])
    add("**Drawings** (`ART`) - %d of them. Reuse these before drawing a new "
        "one, and never take a name that is already here:" % len(ART))
    add("")
    for name in sorted(ART):
        row = TXT.get("name." + name, ("?", "?", "?"))
        where = ", ".join(sorted(used.get(name, []))) or "not used by any story"
        add("* `%s` - %s / %s / %s  (%d primitives; used by: %s)"
            % (name, row[0], row[1], row[2], len(ART[name]), where))
    add("")

    if PACK_REPORT:
        add("**Add-on packs** already installed (%s):" % PACKS_DIR)
        add("")
        for name, ok, problems, added in PACK_REPORT:
            if ok:
                add("* `%s` - %s" % (name, ", ".join(added)))
            else:
                add("* `%s` - REFUSED: %s" % (name, problems[0]))
        add("")

    if PICTURES:
        add("**Pictures** (`PICTURES`, used by colouring and jigsaw):")
        add("")
        for pic in PICTURES:
            fillable = [p for p in pic["parts"] if p.get("fillable", True)]
            add("* `%s` - %s, %d x %d, %d parts (%d can be filled in)"
                % (pic["key"], pic["name"][0], pic["w"], pic["h"],
                   len(pic["parts"]), len(fillable)))
            add("  parts: %s" % ", ".join("`%s`" % p["id"]
                                          for p in pic["parts"]))
        add("")

    if SPOTS:
        add("**Spot-the-difference puzzles** (`SPOTS`): a puzzle is one of the "
            "pictures above plus %d to %d candidate differences; a round "
            "shows %d of them, picked at random. Written `kind part`:"
            % (SPOT_POOL_MIN, SPOT_POOL_MAX, SPOT_COUNT))
        add("")
        for s in SPOTS:
            add("* `%s` - %s, on picture `%s`: %s"
                % (s["key"], TXT["spotname." + s["key"]][0], s["picture"],
                   ", ".join("%s %s" % (d["change"],
                                        d.get("part") or d["name"][0])
                             for d in s["diffs"])))
        add("")
    if MATCHES:
        add("**Matching sets** (`MATCHES`): a round takes 3 to 6 of a set's "
            "pairs. A set is `pairs` (two different drawings that belong "
            "together) or `shadows` (an animal and its black shadow):")
        add("")
        for m in MATCHES:
            if m["kind"] == "shadows":
                what = "shadows of " + ", ".join(a for a, _ in m["pairs"])
            else:
                what = ", ".join("%s - %s" % tuple(p) for p in m["pairs"])
            add("* `%s` - %s: %s" % (m["key"], TXT["matchname." + m["key"]][0],
                                      what))
        add("")
    return "\n".join(out)

# *************** DEL 23 - SELF TEST (python ActivityBook.py --selftest) *****
# No window is opened.  It checks the three things that can quietly rot:
#   1. the language table   - three columns, same placeholders, no missing key
#   2. the drawings         - every one named, every primitive well formed
#   3. the mazes            - hundreds of them, every rule the puzzle relies on
# With Pillow present it also writes the contact sheet of every drawing into
# Helpfiles\<program>\art_sheet.png, because art has to be LOOKED at, not only
# measured.

KEY_CALL_PATTERNS = (
    r'\bT\(\s*"([a-z0-9_.]+)"',
    r'\ben\(\s*"([a-z0-9_.]+)"',
    r'\breg\(\s*[^,]+,\s*"([a-z0-9_.]+)"',
    r'\btbutton\(\s*[^,]+,\s*"([a-z0-9_.]+)"',
    r'\bask_yes_no\(\s*[^,]+,\s*"([a-z0-9_.]+)"',
    r'\bset_msg\(\s*"([a-z0-9_.]+)"',
    r'\bfeed\(\s*"([a-z0-9_.]+)"',
)


def _placeholders(s):
    return sorted(re.findall(r"\{\d+\}", s))


def selftest(verbose=True):
    fails = []
    notes = []

    def check(ok, msg):
        if not ok:
            fails.append(msg)
        return ok

    # ---- 1. the language table -------------------------------------------
    for key, row in sorted(TXT.items()):
        check(isinstance(row, tuple) and len(row) == 3,
              "TXT[%s] does not have three columns" % key)
        if not (isinstance(row, tuple) and len(row) == 3):
            continue
        for i, col in enumerate(row):
            check(isinstance(col, str) and col.strip(),
                  "TXT[%s] column %s is empty" % (key, LANGS[i]))
        base = _placeholders(row[0])
        for i in (1, 2):
            check(_placeholders(row[i]) == base,
                  "TXT[%s]: %s has placeholders %s, en has %s"
                  % (key, LANGS[i], _placeholders(row[i]), base))
    notes.append("%d text keys x 3 languages" % len(TXT))

    # ---- 2. every key the code asks for actually exists -------------------
    src = ""
    try:
        if not getattr(sys, "frozen", False):
            with open(os.path.abspath(__file__), "r", encoding="utf-8") as fh:
                src = fh.read()
    except Exception as exc:
        notes.append("source not readable (%s) - key scan skipped" % exc)
    if src:
        # Only the call sites that take a text key, and only whole keys: a
        # prefix like T("name." + art_key) is checked in section 3 instead.
        used = set()
        for pat in KEY_CALL_PATTERNS:
            used |= set(re.findall(pat, src))
        for group in re.findall(r"width_for\(([^)]*)\)", src):
            used |= set(re.findall(r'"([a-z0-9_.]+)"', group))
        for group in re.findall(r"extra_keys=\(([^)]*)\)", src):
            used |= set(re.findall(r'"([a-z0-9_.]+)"', group))
        # A key starts with a letter and has a dot in it; that also throws out
        # the T("...") in this file's own comment.
        used = set(k for k in used if re.match(r"^[a-z][a-z0-9_]*\.", k))
        whole = sorted(k for k in used if not k.endswith("."))
        unknown = [k for k in whole if k not in TXT]
        check(not unknown, "text keys used but not in TXT: %s" % unknown)
        notes.append("%d whole text keys referenced in the source" % len(whole))
        for pref in sorted(k for k in used if k.endswith(".")):
            check(any(k.startswith(pref) for k in TXT),
                  "nothing in TXT starts with %r" % pref)

    # ---- 3. the drawings --------------------------------------------------
    for name, prims in sorted(ART.items()):
        check(("name." + name) in TXT,
              "drawing %s has no name.%s text" % (name, name))
        check(bool(prims), "drawing %s is empty" % name)
        for i, pr in enumerate(prims):
            kind = pr.get("kind")
            check(kind in ("poly", "line", "oval", "arc"),
                  "%s prim %d: unknown kind %r" % (name, i, kind))
            if kind in ("poly", "line"):
                pts = pr.get("pts") or []
                check(len(pts) >= 2, "%s prim %d: needs 2+ points" % (name, i))
                for p in pts:
                    check(len(p) == 2 and all(-0.2 <= v <= 1.2 for v in p),
                          "%s prim %d: point %r outside the unit box"
                          % (name, i, p))
            else:
                box = pr.get("box") or ()
                check(len(box) == 4,
                      "%s prim %d: box needs 4 numbers" % (name, i))
    notes.append("%d drawings" % len(ART))

    for tkey, theme in sorted(THEMES.items()):
        check(("theme." + tkey) in TXT, "theme %s has no text" % tkey)
        for who in [theme["hero"], theme["goal"]] + list(theme["decoys"]):
            check(who in ART, "theme %s uses missing drawing %s" % (tkey, who))
    for d in DIFF_ORDER:
        check(("diff." + d) in TXT, "difficulty %s has no text" % d)
        check(d in DIFFS, "difficulty %s has no size" % d)

    # ---- 3b. the pictures (part 2 and part 3 share them) ------------------
    for pic in PICTURES:
        key = pic["key"]
        check(("pic." + key) in TXT, "picture %s has no name row" % key)
        check(pic["w"] > 0 and pic["h"] > 0, "picture %s has no size" % key)
        seen_ids = set()
        fillable = 0
        for pt in pic["parts"]:
            pid = pt["id"]
            check(pid not in seen_ids,
                  "picture %s uses the part id %s twice" % (key, pid))
            seen_ids.add(pid)
            check(len(pt["label"]) == 3 and all(str(x).strip()
                                                for x in pt["label"]),
                  "picture %s, part %s: the name is missing a language"
                  % (key, pid))
            hint = str(pt.get("hint", ""))
            check(len(hint) == 7 and hint[0] == "#",
                  "picture %s, part %s: %r is not a #rrggbb colour"
                  % (key, pid, hint))
            check(bool(pt["prims"]),
                  "picture %s, part %s: nothing to draw" % (key, pid))
            if pt.get("fillable", True):
                fillable += 1
                check(any(pr["kind"] in ("poly", "oval") for pr in pt["prims"]),
                      "picture %s, part %s can be filled but has no shape to "
                      "fill" % (key, pid))
            for pr in pt["prims"]:
                pts = pr.get("pts") or []
                for p in pts:
                    check(-20 <= p[0] <= pic["w"] + 20 and
                          -20 <= p[1] <= pic["h"] + 20,
                          "picture %s, part %s: point %r is outside the box"
                          % (key, pid, p))
        check(fillable >= 3,
              "picture %s has almost nothing to colour in" % key)
    notes.append("%d pictures, %d parts in all"
                 % (len(PICTURES),
                    sum(len(p["parts"]) for p in PICTURES)))

    # ---- 3c. the jigsaw cut: do the pieces actually interlock? ------------
    if jigsaw_available():
        class _Fake(object):
            """Just enough of the view to run the cutting code headless."""
            picture = PICTURES[0]
            seed = 12345
            edge_points = JigsawView.edge_points
            render_source = JigsawView.render_source
            cut_pieces = JigsawView.cut_pieces

        fake = _Fake()
        for size_key in JIGSAW_ORDER:
            SETTINGS["jigsaw_size"] = size_key
            cols, rows = JIGSAW_SIZES[size_key]
            pieces = fake.cut_pieces(360, 252)
            check(len(pieces) == cols * rows,
                  "%s: %d pieces cut, wanted %d"
                  % (size_key, len(pieces), cols * rows))
            for p in pieces:
                check(p["size"][0] > 4 and p["size"][1] > 4,
                      "%s: piece %d,%d came out empty"
                      % (size_key, p["r"], p["c"]))
                check(0 <= p["home"][0] < 360 and 0 <= p["home"][1] < 252,
                      "%s: piece %d,%d belongs outside the board"
                      % (size_key, p["r"], p["c"]))
            homes = set((p["r"], p["c"]) for p in pieces)
            check(len(homes) == len(pieces),
                  "%s: two pieces claim the same square" % size_key)
        # the shared edge: both neighbours must get the very same curve
        rnd = random.Random(1)
        a = fake.edge_points((0, 0), (100, 0), 1, 20)
        b = fake.edge_points((0, 0), (100, 0), 1, 20)
        check(a == b, "the same boundary came out differently twice")
        c_up = fake.edge_points((0, 0), (100, 0), 1, 20)
        c_dn = fake.edge_points((0, 0), (100, 0), -1, 20)
        check(c_up != c_dn, "the knob points the same way whatever tab says")

        class _Canvas(object):
            def coords(self, *a):
                pass

            def tag_raise(self, *a):
                pass

        class _Magnets(_Fake):
            canvas = _Canvas()
            index_pieces = JigsawView.index_pieces
            neighbours = JigsawView.neighbours
            group_of = JigsawView.group_of
            unlink = JigsawView.unlink
            move_group = JigsawView.move_group
            anchor_groups = JigsawView.anchor_groups
            snap_to_board = JigsawView.snap_to_board
            join = JigsawView.join

        SETTINGS["jigsaw_size"] = "small"
        mg = _Magnets()
        mg.pieces = mg.cut_pieces(360, 252)
        mg.links = set()
        mg.board = (20, 10, 360, 252)
        mg.index_pieces()
        P = mg.by_rc

        def put(rc, x, y):
            P[rc]["pos"] = (x, y)
            P[rc]["placed"] = False

        def rel(a, b):
            return ((P[b]["pos"][0] - P[a]["pos"][0]) - (P[b]["home"][0] - P[a]["home"][0]),
                    (P[b]["pos"][1] - P[a]["pos"][1]) - (P[b]["home"][1] - P[a]["home"][1]))

        # two true neighbours dropped a little off: they must join, exactly
        put((0, 0), 500, 40)
        put((0, 1), 500 + P[(0, 1)]["home"][0] - P[(0, 0)]["home"][0] + 9,
            40 + P[(0, 1)]["home"][1] - P[(0, 0)]["home"][1] - 7)
        check(mg.join(mg.group_of(P[(0, 0)])) >= 1, "close neighbours did not join")
        check(rel((0, 0), (0, 1)) == (0, 0), "joined pieces are not exactly aligned")
        check(len(mg.group_of(P[(0, 0)])) == 2, "the group should hold two pieces")
        # a third piece that is not close: no join, nothing moves
        put((2, 3), 40, 400)
        before = P[(2, 3)]["pos"]
        check(mg.join([P[(2, 3)]]) == 0 and P[(2, 3)]["pos"] == before,
              "a piece far from its neighbours was pulled in")
        # right neighbour, but 40 px off: too far to attract
        put((1, 1), 500 + P[(1, 1)]["home"][0] - P[(0, 0)]["home"][0] + 40,
            40 + P[(1, 1)]["home"][1] - P[(0, 0)]["home"][1])
        check(mg.join([P[(1, 1)]]) == 0, "a piece 40 px off was pulled in")
        # a DIAGONAL piece exactly where it would fit is not a neighbour
        put((1, 2), 0, 0)
        P[(1, 2)]["pos"] = (P[(0, 1)]["pos"][0] + P[(1, 2)]["home"][0] - P[(0, 1)]["home"][0],
                            P[(0, 1)]["pos"][1] + P[(1, 2)]["home"][1] - P[(0, 1)]["home"][1])
        # (1,2) IS the lower neighbour of (0,2) and the right one of (1,1) only,
        # so next to the group {(0,0),(0,1)} it is diagonal
        check(mg.join([P[(1, 2)]]) == 0, "a diagonal piece joined")
        # the group near its place on the board locks as a whole
        gx = mg.board[0] + P[(0, 0)]["home"][0]
        gy = mg.board[1] + P[(0, 0)]["home"][1]
        put((0, 0), gx + 12, gy - 9)
        put((0, 1), P[(0, 0)]["pos"][0] + P[(0, 1)]["home"][0] - P[(0, 0)]["home"][0],
            P[(0, 0)]["pos"][1] + P[(0, 1)]["home"][1] - P[(0, 0)]["home"][1])
        grp = mg.group_of(P[(0, 1)])
        check(mg.snap_to_board(grp), "a group next to its place did not snap")
        check(P[(0, 0)]["pos"] == (gx, gy) and P[(0, 0)]["placed"]
              and P[(0, 1)]["placed"], "the group did not lock onto the board")
        check(P[(0, 1)]["pos"] == (mg.board[0] + P[(0, 1)]["home"][0],
                                   mg.board[1] + P[(0, 1)]["home"][1]),
              "the second piece of the group is not on its square")
        check(not mg.links, "locked pieces kept their links")
        # a group far from the board does not snap
        put((2, 0), 600, 300)
        check(not mg.snap_to_board([P[(2, 0)]]), "a far piece snapped")
        # cutting again: members go back to their exact distance
        put((2, 0), 600, 300)
        put((2, 1), 600 + P[(2, 1)]["home"][0] - P[(2, 0)]["home"][0] + 1, 300)
        mg.links.add(frozenset(((2, 0), (2, 1))))
        mg.anchor_groups()
        check(rel((2, 0), (2, 1)) == (0, 0), "anchor_groups left a group inexact")
        notes.append("jigsaw cut checked for %d piece counts"
                     % len(JIGSAW_ORDER))
    else:
        notes.append("Pillow not installed - jigsaw cut not checked")

    # ---- 3c2. finding Pillow (DEL 04b) ------------------------------------
    mine = "cp%d%d" % sys.version_info[:2]
    plat = ("win_amd64" if sys.maxsize > 2 ** 32 else "win32")
    if sys.platform == "win32":
        check(_wheel_fits("Pillow-12.2.0-%s-%s-%s.whl" % (mine, mine, plat)),
              "the wheel for this very Python was not accepted")
        check(not _wheel_fits("Pillow-12.2.0-cp30-cp30-%s.whl" % plat),
              "a wheel for another Python was accepted")
        check(not _wheel_fits("Pillow-12.2.0-%s-%s-manylinux_2_28_x86_64.whl"
                              % (mine, mine)),
              "a Linux wheel was accepted on Windows")
    check(not _wheel_fits("Pillow-12.2.0.tar.gz"), "a source archive was taken")
    check(not _wheel_fits("numpy-2.0.0-%s-%s-%s.whl" % (mine, mine, plat)),
          "a wheel for another package was taken")
    import tempfile
    with tempfile.TemporaryDirectory() as tmp:
        fake = os.path.join(tmp, "a", "b", "PIL")
        os.makedirs(fake)
        with open(os.path.join(fake, "__init__.py"), "w") as fh:
            fh.write("raise ImportError('not really Pillow')\n")
        with open(os.path.join(fake, "_imaging.cp30-win_amd64.pyd"), "wb") as fh:
            fh.write(b"x")
        found = list(_scan_for_pillow(tmp, 7, time.time() + 10))
        check(found == [("folder", os.path.join(tmp, "a", "b"))],
              "the scan did not find a PIL folder five levels down: %r" % found)
        before = list(sys.path)
        check(not _use_pil_folder(os.path.join(tmp, "a", "b"))
              and sys.path == before,
              "a PIL folder for another Python was not refused cleanly")
        shallow = list(_scan_for_pillow(tmp, 1, time.time() + 10))
        check(shallow == [], "the depth limit was ignored")
        # a broken wheel must make pip fail quietly, never raise
        if _real_python_exe():
            bad = os.path.join(tmp, "Pillow-0.0.0-%s-%s-%s.whl" % (mine, mine, plat))
            with open(bad, "wb") as fh:
                fh.write(b"not a zip")
            check(pip_install_wheel(bad, target=os.path.join(tmp, "t")) is False,
                  "pip 'installed' a wheel that is not a wheel")
    notes.append("Pillow finder checked (wheel names, depth, wrong version)")

    # ---- 3d. the pack checker (DEL 21) -----------------------------------
    # These are the mistakes that actually arrived the first time content was
    # ordered from elsewhere, one test each.
    good_draw = {"name": ["the nut", "nöten", "орех"],
                 "prims": [{"kind": "oval", "box": [0.2, 0.3, 0.8, 0.9],
                            "fill": "#a1887f"},
                           {"kind": "line", "pts": [[0.5, 0.3], [0.5, 0.1]],
                            "w": 3}]}
    good_pack = {"format": 1, "pack": "test",
                 "drawings": {"testnut": good_draw},
                 "stories": {"testmouse": {
                     "name": ["Nut", "Nöt", "Орех"],
                     "hero": "mouse", "goal": "testnut",
                     "decoys": ["cat", "wall"]}}}
    check(check_pack(good_pack, ART, THEMES, PICTURE_BY_KEY) == [],
          "the pack checker rejects a sound pack: %s"
          % check_pack(good_pack, ART, THEMES, PICTURE_BY_KEY))

    def rejects(what, pack):
        problems = check_pack(pack, ART, THEMES, PICTURE_BY_KEY)
        check(bool(problems), "the pack checker lets %s through" % what)

    import copy as _copy
    p1 = _copy.deepcopy(good_pack)
    p1["drawings"] = {"dog": good_draw}
    rejects("a drawing that overwrites a built-in one", p1)

    p2 = _copy.deepcopy(good_pack)
    p2["stories"] = {"dog": p2["stories"]["testmouse"]}
    rejects("a story that overwrites a built-in one", p2)

    p3 = _copy.deepcopy(good_pack)
    p3["stories"]["testmouse"]["decoys"] = ["cat"]
    rejects("a story with no dead end among the decoys", p3)

    p4 = _copy.deepcopy(good_pack)
    p4["stories"]["testmouse"]["decoys"] = ["cat", "wall", "nosuchthing"]
    rejects("a decoy with no drawing", p4)

    p5 = _copy.deepcopy(good_pack)
    p5["stories"]["testmouse"]["goal"] = "mouse"
    rejects("a story that walks to itself", p5)

    p6 = _copy.deepcopy(good_pack)
    p6["drawings"]["testnut"]["name"] = ["the nut", "nöten"]
    rejects("a name with a language missing", p6)

    p7 = _copy.deepcopy(good_pack)
    p7["drawings"]["testnut"]["prims"][0]["box"] = [0.2, 0.3, 8.0, 9.0]
    rejects("a shape drawn outside the unit box", p7)

    p8 = _copy.deepcopy(good_pack)
    p8["drawings"]["testnut"]["prims"][0]["fill"] = "red"
    rejects("a colour name instead of #rrggbb", p8)

    p9 = _copy.deepcopy(good_pack)
    p9["drawings"] = {"Test Nut": good_draw}
    rejects("a key with spaces and capitals", p9)

    p10 = _copy.deepcopy(good_pack)
    p10["format"] = 99
    rejects("a pack written for a later format", p10)

    rejects("a pack that is not an object", [1, 2, 3])
    rejects("an empty pack", {"format": 1, "pack": "nothing"})

    # a picture pack, checked the same way
    pic_pack = {"format": 1, "pack": "pic", "pictures": [{
        "key": "testpic", "name": ["T", "T", "T"], "w": 100, "h": 100,
        "parts": [{"id": "a", "label": ["a", "a", "a"], "hint": "#112233",
                   "prims": [{"kind": "oval", "box": [1, 1, 50, 50]}]},
                  {"id": "b", "label": ["b", "b", "b"], "hint": "#112233",
                   "prims": [{"kind": "oval", "box": [10, 10, 60, 60]}]},
                  {"id": "c", "label": ["c", "c", "c"], "hint": "#112233",
                   "prims": [{"kind": "oval", "box": [20, 20, 70, 70]}]}]}]}
    check(check_pack(pic_pack, ART, THEMES, PICTURE_BY_KEY) == [],
          "the pack checker rejects a sound picture pack: %s"
          % check_pack(pic_pack, ART, THEMES, PICTURE_BY_KEY))
    p11 = _copy.deepcopy(pic_pack)
    p11["pictures"][0]["parts"][1]["id"] = "a"
    rejects("two parts of a picture with the same id", p11)
    p12 = _copy.deepcopy(pic_pack)
    p12["pictures"][0]["parts"][0]["hint"] = "blue"
    rejects("a part whose natural colour is a colour name", p12)

    # and it must survive being loaded for real
    before_art, before_themes = len(ART), len(THEMES)
    merge_pack(good_pack)
    check("testnut" in ART and "testmouse" in THEMES,
          "a sound pack did not go in")
    check(THEME_ORDER[-1] == "testmouse",
          "a pack's story was not appended to the end of the order")
    check(TXT.get("name.testnut") and TXT.get("theme.testmouse"),
          "a pack's names did not reach the language table")
    p = MazePuzzle("easy", theme="testmouse", seed=3)
    check(p.theme["goal"] == "testnut",
          "a maze could not be built from a pack's story")
    del ART["testnut"], THEMES["testmouse"], TXT["name.testnut"], \
        TXT["theme.testmouse"]
    THEME_ORDER.remove("testmouse")
    check(len(ART) == before_art and len(THEMES) == before_themes,
          "the test pack did not come back out again")
    notes.append("pack checker: 1 sound pack, 14 broken ones, all judged "
                 "correctly")

    # ---- 3e. spot the differences and matching (parts 4 and 5) -------------
    check(not BUILTIN_REPORT,
          "the built-in puzzles were refused by the pack checker: %s"
          % BUILTIN_REPORT)
    check(bool(SPOTS) and bool(MATCHES),
          "there is no built-in spot puzzle or matching set")
    for ch in SPOT_CHANGES:
        check(("spot." + ch) in TXT, "no text for the difference kind %s" % ch)
    for n in MATCH_CHOICES:
        check(("pairs.%d" % n) in TXT, "no text for %d pairs" % n)
    for kind in ("pairs", "shadows"):
        check(("status.match.ready." + kind) in TXT,
              "no ready line for %s sets" % kind)

    # the pack checker, one test per mistake that can be made
    dinos_ok = [{"part": "sun", "change": "hide"},
                {"part": "cloud", "change": "colour", "to": "#ce93d8"},
                {"part": "lava", "change": "colour", "to": "#42a5f5"},
                {"part": "bronto_spots", "change": "colour", "to": "#fdd835"},
                {"part": "fern", "change": "scale", "factor": 0.6}]
    sm_pack = {"format": 1, "pack": "t",
               "spots": {"testspot": {"name": ["T", "T", "T"],
                                      "picture": "dinos",
                                      "differences": dinos_ok}},
               "matches": {"testpairs": {"name": ["T", "T", "T"],
                                         "pairs": [["dog", "kennel"],
                                                   ["mouse", "cheese"],
                                                   ["bee", "flower"]]},
                           "testshadows": {"name": ["T", "T", "T"],
                                           "shadows": ["dog", "cat", "mouse"]}}}
    check(check_pack(sm_pack, ART, THEMES, PICTURE_BY_KEY) == [],
          "the pack checker rejects a sound spot/match pack: %s"
          % check_pack(sm_pack, ART, THEMES, PICTURE_BY_KEY))

    def spot_with(diffs, **extra):
        pk = _copy.deepcopy(sm_pack)
        pk["spots"]["testspot"]["differences"] = diffs
        pk["spots"]["testspot"].update(extra)
        return pk

    more = [{"part": "stone2", "change": "hide"},
            {"part": "smoke", "change": "hide"},
            {"part": "trex_tail", "change": "colour", "to": "#64b5f6"},
            {"part": "stone3", "change": "move", "dx": 90, "dy": 0},
            {"part": "egg", "change": "hide"},
            {"part": "hills", "change": "colour", "to": "#7e57c2"}]
    rejects("a spot puzzle on a picture that does not exist",
            spot_with(dinos_ok, picture="nosuchpicture"))
    rejects("a spot puzzle with four differences", spot_with(dinos_ok[:4]))
    rejects("a spot puzzle with eleven differences",
            spot_with(dinos_ok + more))
    rejects("a difference on a part the picture does not have",
            spot_with(dinos_ok[:4] + [{"part": "nosuch", "change": "hide"}]))
    rejects("one part changed twice",
            spot_with(dinos_ok[:4] + [{"part": "sun", "change": "colour",
                                       "to": "#42a5f5"}]))
    rejects("a colour that is not #rrggbb",
            spot_with(dinos_ok[:4] + [{"part": "stone2", "change": "colour",
                                       "to": "blue"}]))
    rejects("a colour too close to the old one to see",
            spot_with(dinos_ok[:4] + [{"part": "stone2", "change": "colour",
                                       "to": "#bebebe"}]))
    rejects("a part that is too small to spot",
            spot_with(dinos_ok[:4] + [{"part": "bronto_eye",
                                       "change": "hide"}]))
    rejects("a move too small to see",
            spot_with(dinos_ok[:4] + [{"part": "stone3", "change": "move",
                                       "dx": 8, "dy": 5}]))
    rejects("a scale that is hardly a change",
            spot_with(dinos_ok[:4] + [{"part": "stone3", "change": "scale",
                                       "factor": 0.9}]))
    rejects("a part that grows out of the picture",
            spot_with(dinos_ok[:4] + [{"part": "volcano", "change": "scale",
                                       "factor": 2.4}]))
    rejects("an unknown kind of change",
            spot_with(dinos_ok[:4] + [{"part": "stone2",
                                       "change": "explode"}]))
    rejects("an extra thing with no name",
            spot_with(dinos_ok[:4] + [{"change": "add", "prims": [
                {"kind": "oval", "box": [300, 60, 380, 120],
                 "fill": "#fdd835"}]}]))
    rejects("an extra thing drawn outside the picture",
            spot_with(dinos_ok[:4] + [{"change": "add",
                                       "name": ["a ball", "en boll", "мяч"],
                                       "prims": [{"kind": "oval",
                                                  "box": [900, 600, 1400, 900],
                                                  "fill": "#fdd835"}]}]))
    rejects("two differences on top of each other",
            spot_with(dinos_ok[:4] + [{"part": "ground", "change": "colour",
                                       "to": "#7e57c2"},
                                      {"part": "stone2", "change": "hide"}]))
    rejects("a spot puzzle that takes a name already taken",
            {"format": 1, "pack": "t", "spots": {
                "volcano": sm_pack["spots"]["testspot"]}})

    def match_with(**kw):
        pk = _copy.deepcopy(sm_pack)
        pk["matches"] = {"testpairs": dict(
            {"name": ["T", "T", "T"]}, **kw)}
        return pk

    rejects("a matching set with two pairs",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"]]))
    rejects("a matching set with nine pairs",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"],
                              ["bee", "flower"], ["penguin", "fish"],
                              ["seal", "icehole"], ["cat", "puddle"],
                              ["rain", "tap"], ["trap", "web"],
                              ["wall", "dog"]]))
    rejects("a drawing that stands in two pairs",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"],
                              ["dog", "flower"]]))
    rejects("a pair of a drawing and itself",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"],
                              ["bee", "bee"]]))
    rejects("a pair with a drawing that does not exist",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"],
                              ["bee", "nosuchthing"]]))
    rejects("a set with both pairs and shadows",
            match_with(pairs=[["dog", "kennel"], ["mouse", "cheese"],
                              ["bee", "flower"]],
                       shadows=["dog", "cat", "mouse"]))
    rejects("a set with neither pairs nor shadows", match_with())
    rejects("shadows that repeat an animal",
            match_with(shadows=["dog", "cat", "dog"]))
    rejects("a set that takes a name already taken",
            {"format": 1, "pack": "t", "matches": {
                "friends": sm_pack["matches"]["testpairs"]}})

    # names that are taken are renamed, not refused (DEL 21, uniquify_pack)
    clash = {"format": 1, "pack": "t",
             "drawings": {"dog": {"name": ["the dog", "hunden", "собака"],
                                  "prims": [{"kind": "oval",
                                             "box": [0.2, 0.2, 0.8, 0.8],
                                             "fill": "#ffffff"}]}},
             "stories": {"dog": {"name": ["Dog", "Hund", "Пёс"],
                                 "hero": "dog", "goal": "kennel",
                                 "decoys": ["wall", "dog"]}},
             "matches": {"friends": {
                 "name": ["Friends", "Vänner", "Друзья"],
                 "pairs": [["dog", "kennel"], ["mouse", "cheese"],
                           ["bee", "flower"]]}}}
    before_json = json.dumps(clash, sort_keys=True)
    fixed, notes = uniquify_pack(clash)
    check(json.dumps(clash, sort_keys=True) == before_json,
          "uniquify_pack changed the pack it was given")
    check(len(notes) == 3, "uniquify_pack did not rename three taken names")
    check(not check_pack(fixed, ART, THEMES, PICTURE_BY_KEY),
          "a pack with taken names was still not sound after renaming: %s"
          % check_pack(fixed, ART, THEMES, PICTURE_BY_KEY))
    check(fixed["stories"]["dog_2"]["hero"] == "dog_2" and
          fixed["stories"]["dog_2"]["name"][0] == "Dog (2)" and
          fixed["matches"]["friends_2"]["pairs"][0] == ["dog_2", "kennel"],
          "the new name was not followed through the pack")
    check(uniquify_pack(sm_pack)[0] is sm_pack,
          "a pack with no taken name was copied or changed")
    only_art = {"format": 1, "pack": "t", "drawings": clash["drawings"]}
    check(uniquify_pack(only_art)[1] == ["drawing dog -> dog_2"],
          "a pack with only drawings was not renamed (a missing section)")

    # a sound pack really goes in - including a puzzle on the pack's OWN picture
    before = (len(SPOTS), len(MATCHES))
    merge_pack(sm_pack)
    check("testspot" in SPOT_BY_KEY and "testpairs" in MATCH_BY_KEY and
          "testshadows" in MATCH_BY_KEY, "a sound spot/match pack did not go in")
    check(MATCH_BY_KEY["testshadows"]["kind"] == "shadows",
          "a shadows set was not read as shadows")
    r = SpotRound(SPOT_BY_KEY["testspot"], 5)
    check(len(r.diffs) == SPOT_COUNT, "a pack's puzzle did not make a round")
    for lst, dct, keys in ((SPOTS, SPOT_BY_KEY, ["testspot"]),
                           (MATCHES, MATCH_BY_KEY, ["testpairs", "testshadows"])):
        for k in keys:
            dct.pop(k)
            lst[:] = [x for x in lst if x["key"] != k]
    for k in ("spotname.testspot", "matchname.testpairs",
              "matchname.testshadows"):
        TXT.pop(k, None)
    check((len(SPOTS), len(MATCHES)) == before,
          "the test spot/match pack did not come back out again")
    notes.append("pack checker: spot puzzles and matching sets, 1 sound pack "
                 "and 24 broken ones judged correctly")

    # ---- 3f. every built-in spot puzzle, round after round ------------------
    pil = None
    try:
        from PIL import Image as _Im, ImageChops as _Ch, ImageDraw as _Dr
        pil = (_Im, _Ch, _Dr)
    except ImportError:
        notes.append("Pillow not installed - spot pixel test skipped")
    rounds_played = 0
    for spot in SPOTS:
        pic = PICTURE_BY_KEY[spot["picture"]]
        w, h = pic["w"], pic["h"]
        for seed in range(40):
            r = SpotRound(spot, seed)
            rounds_played += 1
            where = "spot %s seed %d" % (spot["key"], seed)
            check(len(r.diffs) == SPOT_COUNT and
                  len(set(id(d) for d in r.diffs)) == SPOT_COUNT,
                  "%s: not five different differences" % where)
            for k, rg in enumerate(r.regions):
                # something inside the visible part of each difference finds it
                x0, y0, x1, y1 = rg["seen"]
                found = False
                for gx in range(9):
                    for gy in range(9):
                        px = x0 + (x1 - x0) * (gx + 0.5) / 9.0
                        py = y0 + (y1 - y0) * (gy + 0.5) / 9.0
                        if r.hit_test(px, py) == k:
                            found = True
                check(found, "%s: no click finds difference %d (%s)"
                      % (where, k, r.diffs[k]["change"]))
            # a click well away from every difference never finds one
            step = max(w, h) / 40.0
            gx = step / 2.0
            while gx < w:
                gy = step / 2.0
                while gy < h:
                    near = any(rg["bbox"][0] - SPOT_PAD - 4 <= gx <=
                               rg["bbox"][2] + SPOT_PAD + 4 and
                               rg["bbox"][1] - SPOT_PAD - 4 <= gy <=
                               rg["bbox"][3] + SPOT_PAD + 4
                               for rg in r.regions)
                    if not near and r.hit_test(gx, gy) is not None:
                        check(False, "%s: a click at (%d, %d) far from every "
                              "difference found one" % (where, gx, gy))
                        gx = w
                        break
                    gy += step
                gx += step
            # which picture is on which side must vary, or the child learns it
            check(r.left_parts is (r.parts_b if r.swap else r.parts_a),
                  "%s: swap does not match the sides" % where)
            # the stars
            check(SpotRound.stars(0, 0, False) == 3 and
                  SpotRound.stars(0, 0, True) == 1 and
                  SpotRound.stars(99, 0, False) == 1,
                  "spot stars are wrong")
            if pil and seed < 12:
                Im, Ch, Dr = pil
                sc = 0.5
                imgs = []
                for parts in (r.parts_a, r.parts_b):
                    im = Im.new("RGB", (int(w * sc), int(h * sc)), "#ffffff")
                    draw_spot_parts_pil(Dr.Draw(im), parts, 0, 0, sc)
                    imgs.append(im)
                rr, gg, bb = Ch.difference(imgs[0], imgs[1]).split()
                mask = Ch.lighter(Ch.lighter(rr, gg), bb).point(
                    lambda v: 255 if v > 30 else 0)
                mp = mask.load()
                for k, rg in enumerate(r.regions):
                    b = rg["bbox"]
                    n = 0
                    for yy in range(max(0, int(b[1] * sc) - 4),
                                    min(mask.height, int(b[3] * sc) + 5)):
                        for xx in range(max(0, int(b[0] * sc) - 4),
                                        min(mask.width, int(b[2] * sc) + 5)):
                            if mp[xx, yy]:
                                n += 1
                    check(n >= 300, "%s: difference %d (%s %s) shows in only "
                          "%d pixels" % (where, k, r.diffs[k]["change"],
                                         r.diffs[k].get("part"), n))
                stray = 0
                for yy in range(mask.height):
                    for xx in range(mask.width):
                        if mp[xx, yy] and not any(
                                rg["bbox"][0] - 10 <= xx / sc <=
                                rg["bbox"][2] + 10 and
                                rg["bbox"][1] - 10 <= yy / sc <=
                                rg["bbox"][3] + 10 for rg in r.regions):
                            stray += 1
                check(stray == 0, "%s: %d pixels differ where no difference "
                      "is" % (where, stray))
    notes.append("%d spot rounds played%s" % (
        rounds_played, ", 12 per puzzle compared pixel by pixel" if pil
        else ""))

    # ---- 3g. matching, round after round ------------------------------------
    arts_before = {k: json.dumps(v, sort_keys=True) for k, v in ART.items()}
    match_rounds = 0
    for mset in MATCHES:
        for key_a, key_b in mset["pairs"]:
            check(key_a in ART and key_b in ART,
                  "set %s uses a missing drawing" % mset["key"])
        check(("matchname." + mset["key"]) in TXT,
              "set %s has no name text" % mset["key"])
        for want in MATCH_CHOICES:
            for seed in range(30):
                r = MatchRound(mset, want, seed)
                match_rounds += 1
                n = min(max(MATCH_MIN, want), len(mset["pairs"]))
                where = "set %s want %d seed %d" % (mset["key"], want, seed)
                check(r.n == n and len(r.items) == n,
                      "%s: %d pairs, wanted %d" % (where, r.n, n))
                check(sorted(r.left) == list(range(n)) and
                      sorted(r.right) == list(range(n)),
                      "%s: a column is not a shuffle of the pairs" % where)
                if n >= 3:
                    check(all(r.left[i] != r.right[i] for i in range(n)),
                          "%s: a partner stands straight across its mate"
                          % where)
                check(len(set(r.items)) == n, "%s: a pair twice" % where)
                # the rules of joining
                a, b = 0, (1 if n > 1 else 0)
                if n > 1:
                    check(r.try_pair(0, a, 1, b) == "wrong",
                          "%s: a wrong pair was accepted" % where)
                    check(not r.matched, "%s: a wrong pair was kept" % where)
                check(r.try_pair(0, a, 0, a) == "ignore",
                      "%s: two in one column were judged" % where)
                for pid in range(n):
                    check(r.try_pair(1, pid, 0, pid) == "right",
                          "%s: a right pair was refused" % where)
                    check(r.try_pair(0, pid, 1, pid) == "ignore",
                          "%s: a joined pair was judged again" % where)
                check(r.done, "%s: all joined but not done" % where)
                check(r.is_shadow(1) == (mset["kind"] == "shadows") and
                      not r.is_shadow(0), "%s: shadow on the wrong side"
                      % where)
    for pen in range(0, 20):
        check(MatchRound.stars(4, pen, 0, False) >=
              MatchRound.stars(4, pen + 1, 0, False),
              "match stars go UP with more mistakes")
    check(MatchRound.stars(4, 0, 0, False) == 3 and
          MatchRound.stars(4, 0, 0, True) == 1 and
          MatchRound.stars(4, 0, 3, False) < 3, "match stars are wrong")
    # a shadow is a copy: the drawing it came from must be untouched
    for k in ART:
        art_prims(k, True)
    check({k: json.dumps(v, sort_keys=True) for k, v in ART.items()} ==
          arts_before, "making shadows changed a drawing")
    for k in ART:
        for pr in art_prims(k, True):
            check(pr.get("line") == SHADOW_COLOUR and
                  (pr["kind"] not in ("poly", "oval") or
                   pr.get("fill") == SHADOW_COLOUR),
                  "the shadow of %s is not all one colour" % k)
    notes.append("%d matching rounds played, shadows checked for every "
                 "drawing" % match_rounds)

    # ---- 4. the mazes -----------------------------------------------------
    rounds = {"easy": 200, "normal": 150, "hard": 80, "giant": 40}
    made = 0
    for diff in DIFF_ORDER:
        w, h, want_decoys = DIFFS[diff]
        for n in range(rounds[diff]):
            p = MazePuzzle(diff, seed=1000 + n)
            made += 1
            m = p.maze
            # perfect maze: every square reachable, and exactly one route
            dist, _ = m.bfs((0, 0))
            if not check(len(dist) == w * h,
                         "%s seed %d: %d of %d squares reachable"
                         % (diff, p.seed, len(dist), w * h)):
                break
            edges = sum(bin(m.cells[y][x]).count("1")
                        for y in range(h) for x in range(w)) // 2
            check(edges == w * h - 1,
                  "%s seed %d: %d openings, a tree needs %d"
                  % (diff, p.seed, edges, w * h - 1))
            # the story on top of it
            check(p.start != p.goal,
                  "%s seed %d: start is the goal" % (diff, p.seed))
            check(len(m.neighbours(p.start)) == 1,
                  "%s seed %d: the animal is not in a dead end" % (diff, p.seed))
            check(len(m.neighbours(p.goal)) == 1,
                  "%s seed %d: the goal is not in a dead end" % (diff, p.seed))
            check(len(p.solution) >= 3,
                  "%s seed %d: route is only %d squares"
                  % (diff, p.seed, len(p.solution)))
            check(p.solution[0] == p.start and p.solution[-1] == p.goal,
                  "%s seed %d: route does not join the two ends"
                  % (diff, p.seed))
            for a, b in zip(p.solution, p.solution[1:]):
                if not check(m.connected(a, b),
                             "%s seed %d: route steps through a wall at %s"
                             % (diff, p.seed, (a, b))):
                    break
            # the decoys
            check(len(p.decoys) <= want_decoys,
                  "%s seed %d: %d decoys, wanted at most %d"
                  % (diff, p.seed, len(p.decoys), want_decoys))
            for cell, artkey in p.decoys.items():
                check(cell not in p.on_solution,
                      "%s seed %d: decoy %s sits on the right route"
                      % (diff, p.seed, artkey))
                check(cell not in (p.start, p.goal),
                      "%s seed %d: decoy %s sits on an end"
                      % (diff, p.seed, artkey))
                check(artkey in ART,
                      "%s seed %d: unknown decoy art %s" % (diff, p.seed, artkey))
                check(len(m.neighbours(cell)) == 1,
                      "%s seed %d: decoy %s is not in a dead end"
                      % (diff, p.seed, artkey))
            # solved / not solved, from either end
            check(p.is_solved(p.solution),
                  "%s seed %d: solution not accepted" % (diff, p.seed))
            check(p.is_solved(list(reversed(p.solution))),
                  "%s seed %d: solving from the goal end not accepted"
                  % (diff, p.seed))
            check(not p.is_solved(p.solution[:-1]),
                  "%s seed %d: half a route accepted" % (diff, p.seed))
            check(not p.is_solved([p.start]),
                  "%s seed %d: standing still accepted" % (diff, p.seed))
            # the stars a player can actually earn
            check(p.stars(0, False) == 3, "stars: a clean run is not 3")
            check(p.stars(0, True) == 1, "stars: the answer shown is not 1")
            check(p.stars(10 ** 6, False) == 1, "stars: a wandering run is not 1")
            earlier = 3
            for wrongs in range(0, len(p.solution) * 2):
                s = p.stars(wrongs, False)
                if not check(s <= earlier,
                             "stars go UP from %d wrong steps" % wrongs):
                    break
                earlier = s
    notes.append("%d mazes built and checked" % made)

    # ---- 5. walking the route the way the view does ----------------------
    p = MazePuzzle("normal", seed=7)
    path = [p.start]
    for cell in p.solution[1:]:
        check(p.maze.connected(path[-1], cell), "walk: blocked at %s" % (cell,))
        path.append(cell)
    check(p.is_solved(path), "walk: the finished walk is not a solution")
    side = None
    for cell in p.solution[1:-1]:
        for n in p.maze.neighbours(cell):
            if n not in p.on_solution:
                side = n
                break
        if side:
            break
    check(side is not None, "walk: no wrong turn to take at all")
    if side:
        check(p.maze.route(p.start, side)[-1] == side,
              "walk: the wrong turn cannot be reached")

    # ---- 6. the contact sheet, when Pillow is here -----------------------
    try:
        from PIL import Image, ImageDraw
        cols, size, pad = 6, 150, 18
        rows = (len(ART) + cols - 1) // cols
        img = Image.new("RGB", (cols * (size + pad * 2),
                                rows * (size + pad * 2 + 18)), PAPER)
        dr = ImageDraw.Draw(img)
        for i, name in enumerate(sorted(ART)):
            cx = (i % cols) * (size + pad * 2) + pad + size / 2
            cy = (i // cols) * (size + pad * 2 + 18) + pad + size / 2
            draw_prims_pil(dr, ART[name], cx, cy, size)
            dr.text((cx - size / 2, cy + size / 2 + 2), name, fill="#555555")
        ensure_dirs()
        out = os.path.join(PROGRAM_HF_DIR, "art_sheet.png")
        img.save(out)
        notes.append("contact sheet written: %s" % out)
        # the spot puzzles too: one round of each, both pictures, the rings
        # where the differences are - to be LOOKED at, like the drawings
        sc = 0.34
        rows = []
        for spot in SPOTS:
            r = SpotRound(spot, 7)
            pw, ph = int(r.pic["w"] * sc), int(r.pic["h"] * sc)
            im = Image.new("RGB", (pw * 2 + 30, ph + 30), PAPER)
            dd = ImageDraw.Draw(im)
            for k, parts in enumerate((r.left_parts, r.right_parts)):
                ox = 10 + k * (pw + 10)
                dd.rectangle([ox - 1, 9, ox + pw, 10 + ph], outline="#bbbbbb")
                draw_spot_parts_pil(dd, parts, ox, 10, sc)
                for rg in r.regions:
                    x0, y0, x1, y1 = rg["seen"]
                    dd.ellipse([ox + (x0 - 14) * sc, 10 + (y0 - 14) * sc,
                                ox + (x1 + 14) * sc, 10 + (y1 + 14) * sc],
                               outline=RING, width=2)
            rows.append(im)
        if rows:
            sheet = Image.new("RGB", (max(i.width for i in rows),
                                      sum(i.height for i in rows)), PAPER)
            y = 0
            for im in rows:
                sheet.paste(im, (0, y))
                y += im.height
            out = os.path.join(PROGRAM_HF_DIR, "spot_sheet.png")
            sheet.save(out)
            notes.append("spot sheet written: %s" % out)
    except ImportError:
        notes.append("Pillow not installed - contact sheet skipped")
    except Exception as exc:
        notes.append("contact sheet failed: %s" % exc)

    selftest_beads(check, notes)

    if verbose:
        for n in notes:
            print("  .. %s" % n)
        if fails:
            print("FAILED (%d):" % len(fails))
            for f in fails[:40]:
                print("   ! %s" % f)
        else:
            print("SELFTEST OK")
    return 1 if fails else 0

# *************** DEL 24 - START THE PROGRAM ********************************

def main():
    ensure_dirs()
    roll_logs()
    load_settings()
    load_stats()
    # Pillow may sit in a folder of its own instead of being installed (DEL 04b).
    # Quick on purpose: a wide search only happens when the player asks for it.
    try:
        locate_pillow(SETTINGS.get("pillow_search", ""), budget=3.0)
    except Exception as exc:
        log("pillow: search crashed: %s" % exc)

    load_builtin_content()          # what a pack must not repeat

    if "--checkpack" in sys.argv:
        i = sys.argv.index("--checkpack")
        if len(sys.argv) <= i + 1:
            print_safe("Say which file: --checkpack thepack.json")
            return 2
        return check_one_pack(sys.argv[i + 1])

    # Add-on packs come in before anything looks at ART, THEMES or PICTURES.
    load_packs()
    bad = [r for r in PACK_REPORT if not r[1]]
    if bad:
        print_safe("%d pack(s) were refused - run --checkpack on them, or "
                   "see the log:" % len(bad))
        print_safe(pack_report_text())

    if "--selftest" in sys.argv:
        print("%s selftest" % PROGRAM_NAME)
        return selftest()

    if "--instructions" in sys.argv:
        # Keep the hand-written instruction document, but put a freshly
        # generated list of what exists into it - that list is the only part
        # that goes stale.  A path may follow the flag.
        i = sys.argv.index("--instructions")
        where = sys.argv[i + 1] if len(sys.argv) > i + 1 else None
        path = refresh_instructions(where)
        if path:
            print_safe("instruction file brought up to date:\n  %s" % path)
        else:
            print_safe("No instruction file with the inventory markers was "
                       "found.\nLooked next to the program, one folder up, "
                       "in %s and in %s.\nHere is the inventory on its own:\n"
                       % (BASE_DIR, PROGRAM_HF_DIR))
            print_safe(inventory_text())
        return 0

    if "--export-pictures" in sys.argv:
        # The shapes of every picture, for whoever is asked to build a
        # spot-the-difference puzzle on one of them (see DEL 19b).  An
        # optional path may follow the flag.
        i = sys.argv.index("--export-pictures")
        where = sys.argv[i + 1] if len(sys.argv) > i + 1 else None
        print_safe("written: %s" % export_pictures(where))
        return 0

    if "--inventory" in sys.argv:
        # What is already in here, for whoever is asked to add more - see
        # DEL 22.  Printed, and also written next to the program's own data
        # so it can simply be attached to a chat.
        text = inventory_text()
        print_safe(text)
        try:
            ensure_dirs()
            path = os.path.join(PROGRAM_HF_DIR, "inventory.md")
            with open(path, "w", encoding="utf-8") as fh:
                fh.write(text + "\n")
            print_safe("\nwritten to: %s" % path)
        except Exception as exc:
            print_safe("\ncould not write the file: %s" % exc)
        return 0

    # The log's own path is what tells you WHICH copy of the program ran -
    # see 02_folder_tree_and_home.md.
    log("START %s  home=%s  log=%s  python=%s"
        % (PROGRAM_NAME, BASE_DIR, _log_path(), sys.version.split()[0]))

    _set_app_id()                                   # BEFORE tk.Tk()
    root = tk.Tk()
    root.title(T("app.title"))
    root.configure(bg=PAPER)
    root.geometry("1180x820")
    root.minsize(940, 660)
    App(root)
    root.after(0, lambda: _set_window_icon(root))   # after(0), never directly
    root.mainloop()
    log("END")
    return 0


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