beetlebug
1.0.0-beta.4 BSD-2-Clause · Zig 0.17

The GUI toolkit AI can see.

Tk, rebuilt in Zig. An agent can see the window (ztk::snapshot), read each widget (ztk::tree), and click and type in it (ztk::inject). The window on the right is live: edit its code.

Tk compatible: each example on this page also runs in wish 8.6. No third-party library, on the ztcl interpreter.

AI agents write the code, the tests, and the docs of this project, on purpose. A person sets the direction. Why

set name Ada
set level 60
set wifi 1
label .title -text "Hello from ztk"
entry .name -textvariable name -width 18
button .greet -text "Greet" -command {set msg "Hello, $name!"}
set msg "Type a name, then press Return"
label .msg -textvariable msg
ttk::scale .level -from 0 -to 100 -variable level
ttk::progressbar .meter -variable level
ttk::checkbutton .wifi -text "Wi-Fi" -style Switch.TCheckbutton -variable wifi
grid .title - -sticky w -padx 12 -pady 6
grid .name .greet -sticky ew -padx 12 -pady 4
grid .msg - -sticky w -padx 12
grid .level .meter -sticky ew -padx 12 -pady 8
grid .wifi - -sticky w -padx 12
grid columnconfigure . 0 -weight 1
bind .name <Return> {.greet invoke}
hero
The window of the snippet: a greeting form, a scale that drives a progress bar, and a switch
Live

What it is

One Tk script, on every screen.

The same script runs as a native app on Linux, macOS, Windows, the web, iOS, and Android.

Lamplighter
The toy lamplighter before it runs
The code: 1445 lines of Tcl
# title: Lamplighter
# widget: ttk::notebook
# page: docs/widgets/panes.md
# pitch: Light the lamps of a hill town before the night comes. Each tab of the notebook is one street of the level.
# order: 1

# Lamplighter. Night falls on a hill town, and you carry the last flame.
# Each level is a walk through 2 or 3 streets, and each street is a tab
# of the ttk::notebook. Walk off the right edge to open the next tab.
# Touch a lamp to light it: each lamp pushes the night back. Light all
# the lamps of a level to open its gate. A click on a tab that you saw
# takes you back to its start.
#
# Touch. The game reads a tap on its canvas itself (toy(direct) tells the
# host that it needs no touch buttons). When the host sets toy(touch) to
# 1, a level starts in the auto mode: the hero walks by itself, turns
# back at the closed gate and at the left edge, and waits at a wall. A
# tap anywhere on the street jumps, always the full height. The title
# has an extra entry after the levels, the endless run: one street with
# no end, built ahead of the view by a seeded generator (see "The endless
# run" below). A tap on the left third of a title, a pause, or an end
# screen goes left or back to the title, a tap on the right third goes
# right, and a tap in the middle is A. The mark "II" at the top right
# pauses a level on a touch screen.
#
# The streets. After the five levels made by hand, the list has the
# streets of the generator of the endless run (`streets`): each one a
# seed, a length, a style, modifiers, and a theme, with a gate at its
# end. A bot that taps where the generator proved a tap walks each
# street before it ships, and tests/toys.sh walks it again. The title
# gives Continue, the picker of all levels and streets, and the endless
# run. A street opens when one of the three before it is done.

set W 472; set H 232
array set toy {sfx {} music title save {} calm 0 direct 1 orient landscape}
if {![info exists toy(touch)]} { set toy(touch) 0 }
set toy(help) "Tap to jump. The hero walks by itself."
proc sfx {name} { lappend ::toy(sfx) $name }

# The palette: dusk and night, mixed by the dark of the level.
array set dusk {sky0 #24204a sky1 #4a3366 sky2 #9a4f6e sky3 #e0885e hill #3a2c52 hill2 #2c2242 ground #241b36 edge #6f5a8f}
array set night {sky0 #080a1c sky1 #10142e sky2 #1a1d3e sky3 #262650 hill #141530 hill2 #0f1026 ground #0c0b1a edge #2e2c52}
set ink(text) #f6ecd6; set ink(dim) #a89cc4; set ink(gold) #ffd27a; set ink(flame) #ff9a3c
set ink(lampoff) #4c4466; set ink(cloak) #4a86a8; set ink(face) #f2d2ac; set ink(water) #2b3f74

proc mix {a b t} {
    scan $a #%2x%2x%2x r1 g1 b1
    scan $b #%2x%2x%2x r2 g2 b2
    set t [expr {max(0.0, min(1.0, $t))}]
    format #%02x%02x%02x [expr {int($r1 + ($r2 - $r1) * $t)}] [expr {int($g1 + ($g2 - $g1) * $t)}] [expr {int($b1 + ($b2 - $b1) * $t)}]
}
proc ease {t} { expr {$t < 0.5 ? 4 * $t * $t * $t : 1 - pow(-2 * $t + 2, 3) / 2} }

# The levels. Each street has blocks {x0 top x1} that go to the floor,
# ledges {x0 y x1} that you can jump up through, lamps {x y}, springs
# {x y}, boats {x0 y x1 dx frames} that swing, crumbling boards {x0 y x1},
# and water {x0 x1}. The gate is at the right of the last street.
set levels {
    {"Lantern Lane" {
        {Gatehouse {{0 196 472}} {} {{236 166}} {} {} {} {}}
        {Bakery {{0 196 180} {180 176 300} {300 196 472}} {} {{240 146} {420 166}} {} {} {} {}}
    }}
    {"Mill Steps" {
        {Millrace {{0 196 150} {250 196 472}} {{150 170 250}} {{200 140} {400 166}} {} {} {} {{150 250}}}
        {Mill {{0 196 472}} {{120 160 200} {230 124 310} {340 88 420}} {{380 58}} {{60 196}} {} {} {}}
        {Granary {{0 196 120} {120 150 240} {240 196 472}} {} {{180 120} {360 166}} {} {} {} {}}
    }}
    {"The Ford" {
        {Bank {{0 196 110} {390 196 472}} {} {{60 166} {430 166}} {} {{140 190 196 120 110}} {} {{110 390}}}
        {Shallows {{0 196 80} {420 196 472}} {{196 150 276}} {{236 120}} {} {{90 190 146 90 90} {300 190 356 -80 100}} {} {{80 420}}}
        {"Far Bank" {{0 196 472}} {{160 160 230} {270 128 340}} {{300 98} {440 166}} {} {} {} {}}
    }}
    {"Bell Tower" {
        {Square {{0 196 472}} {{90 166 160} {200 140 270}} {{235 110}} {{360 196}} {} {} {}}
        {Stairwell {{0 196 90} {380 196 472}} {} {{430 166}} {} {} {{100 176 160} {180 150 240} {260 124 320} {330 150 380}} {{90 380}}}
        {Belfry {{0 196 472}} {{60 160 130} {160 124 230} {270 92 340} {370 60 440}} {{405 30} {100 130}} {} {} {} {}}
    }}
    {"Hilltop" {
        {Orchard {{0 196 130} {210 176 300} {380 196 472}} {} {{255 146} {430 166}} {{100 196}} {} {} {{130 210} {300 380}}}
        {Ridge {{0 196 70} {410 196 472}} {} {{240 60}} {} {{80 186 160 100 120} {250 160 330 -110 140}} {{190 120 240}} {{70 410}}}
        {Summit {{0 196 472}} {{110 166 180} {220 136 290} {330 106 400}} {{365 76} {150 136} {40 166}} {{40 196}} {} {} {}}
    }}
}

# The notebook in the colors of the night: the tabs are the street signs.
ztk::style add {
    TNotebook { background-color: #15122a; }
    TNotebook::client { background-color: #15122a; border: 1px solid #3a3358; border-radius: 6px; }
    TNotebook::tab, TNotebook::tab-selected, TNotebook::tab-hover, TNotebook::tab-disabled { color: #8f86b0; padding: 4px 12px; }
    TNotebook::tab-selected, TNotebook::tab-hover { color: #f6ecd6; }
    TNotebook::tab-disabled { opacity: 0.4; }
    TNotebook::indicator { background-color: #ffd27a; }
}
. configure -background #15122a
ttk::notebook .nb
pack .nb -fill both -expand 1 -padx 4 -pady 4
for {set i 0} {$i < 3} {incr i} {
    canvas .nb.s$i -width $W -height $H -highlightthickness 0 -background $dusk(sky0)
}

# The state of the run.
array set g {state title level 0 scene 0 dark 0 frames 0 shake 0 freeze 0 pick 0 clear 0 msgT 0 unlocked 1 auto 0 cam 0 paused 0 picked 0}
# The best score of the endless run and the seed of the next run.
array set run {best 0 next 1}
array set best {}
array set h {x 30 y 150 vx 0 vy 0 ground 1 coyote 0 buffer 0 face 1 sx 1 sy 1 step 0 spawnS 0 spawnX 30 spawnY 150 ride -1 crumble -1}
array set hold {left 0 right 0 jump 0}
set parts {}

proc toy_restore {data} {
    global g best
    if {[catch {dict get $data unlocked} u]} return
    set g(unlocked) [expr {max(1, min(5, $u))}]
    if {![catch {dict get $data best} b]} { array set best $b }
    if {![catch {dict get $data run} r] && [string is integer -strict $r]} { set ::run(best) $r }
    if {![catch {dict get $data seed} r] && [string is integer -strict $r]} { set ::run(next) $r }
    if {![catch {dict get $data streets} r]} { catch { array set ::sbest $r } }
    title
}
proc save {} { set ::toy(save) [list unlocked $::g(unlocked) best [array get ::best] run $::run(best) seed $::run(next) streets [array get ::sbest]] }

# The entries of the title: the open levels, then the endless run.
proc picks {} { list continue levels run }
proc pickAt {d} {
    global g
    set p [picks]
    set i [expr {[lsearch -exact $p $g(pick)] + $d}]
    if {$i < 0 || $i >= [llength $p]} return
    set g(pick) [lindex $p $i]; sfx move; title
}

proc toy_input {key state} {
    global g hold h run
    set on [expr {$state eq "press"}]
    if {$g(paused)} { if {$on} { unpause }; return }
    switch $g(state) {
        title {
            if {!$on} return
            switch $key {
                left { pickAt -1 }
                right { pickAt 1 }
                a - start - up { sfx start; switch $g(pick) { run { runStart } levels { picker [continueAt] } default { playLevel [continueAt] } } }
            }
        }
        play {
            switch $key {
                left - right { set hold($key) $on; if {$on} { set g(auto) 0 } }
                a - up - b {
                    set hold(jump) $on
                    if {$on} { set h(buffer) 7 } elseif {$h(vy) < -2 && !$g(auto)} { set h(vy) [expr {$h(vy) * 0.45}] }
                }
            }
        }
        run {
            if {$on && $key in {a up b}} { set run(press) 1 }
        }
        pick {
            if {!$on} return
            switch $key { left { pickMove -1 } right { pickMove 1 } up { pickMove -5 } down { pickMove 5 } a - start { pickPlay $g(sel) } b { title } }
        }
        streetclear {
            if {$on && $key in {a start up}} { sfx start; playLevel [expr {[isOpen [expr {$g(level) + 1}]] && $g(level) + 1 < [count] ? $g(level) + 1 : [continueAt]}] } elseif {$on && $key eq "b"} { playLevel $g(level) }
        }
        runover {
            if {$on && $key in {a start up}} { sfx start; if {$run(limit)} { playLevel $g(level) } else { runStart } } elseif {$on && $key eq "b"} { title }
        }
        clear - night - done {
            if {$on && $key in {a start up}} {
                if {$g(state) eq "night"} { sfx start; start $g(level) } \
                elseif {$g(state) eq "done"} { set g(state) title; title } \
                elseif {$g(level) < 4} { sfx start; start [expr {$g(level) + 1}] } \
                else { set g(state) done; ending }
            }
        }
    }
}

# Draws one street on its canvas. The lit lamps keep their glow.
proc street {i} {
    global levels g W H dusk ink
    set c .nb.s$i
    $c delete all
    lassign [lindex $levels $g(level) 1 $i] name blocks ledges lamps springs boats crumbles water
    backdrop $c $i
    foreach wt $water { lassign $wt x0 x1; $c create rectangle $x0 206 $x1 $H -width 0 -fill $ink(water) -tags water
        for {set x [expr {$x0 + 6}]} {$x < $x1 - 6} {incr x 18} { $c create line $x 210 [expr {$x + 8}] 210 -fill #6a86c8 -width 2 -tags ripple } }
    foreach b $blocks { lassign $b x0 y x1
        $c create rectangle $x0 $y $x1 $H -width 0 -tags ground
        $c create rectangle $x0 $y $x1 [expr {$y + 3}] -width 0 -tags edge
        for {set x [expr {$x0 + 7}]} {$x < $x1 - 4} {incr x 23} { $c create line $x $y [expr {$x - 2}] [expr {$y - 4}] $x $y [expr {$x + 3}] [expr {$y - 5}] -fill #7d6aa0 -tags tuft } }
    foreach l $ledges { lassign $l x0 y x1
        $c create rectangle $x0 $y $x1 [expr {$y + 6}] -width 0 -tags ground
        $c create rectangle $x0 $y $x1 [expr {$y + 2}] -width 0 -tags edge }
    set n 0
    foreach cr $crumbles { lassign $cr x0 y x1
        $c create rectangle $x0 $y $x1 [expr {$y + 5}] -width 0 -fill #8a6a4a -tags "crumble cr$n"
        for {set x [expr {$x0 + 10}]} {$x < $x1} {incr x 12} { $c create line $x $y $x [expr {$y + 5}] -fill #5a4430 -tags "crumble cr$n" }
        incr n }
    set n 0
    foreach bt $boats { lassign $bt x0 y x1
        $c create polygon $x0 $y $x1 $y [expr {$x1 - 6}] [expr {$y + 8}] [expr {$x0 + 6}] [expr {$y + 8}] -fill #a0703c -outline #d09a5a -tags "boat bt$n"
        incr n }
    foreach s $springs { lassign $s x y
        $c create rectangle [expr {$x - 9}] [expr {$y - 5}] [expr {$x + 9}] $y -width 0 -fill #5fb27a -tags spring
        $c create rectangle [expr {$x - 9}] [expr {$y - 7}] [expr {$x + 9}] [expr {$y - 5}] -width 0 -fill #a6e6b2 -tags spring }
    set n 0
    foreach l $lamps { lassign $l x y
        foreach r {40 33 27 21 15 10} k {6 5 4 3 2 1} { $c create oval [expr {$x - $r}] [expr {$y - $r}] [expr {$x + $r}] [expr {$y + $r}] -width 0 -state hidden -tags "glow glow$n g$k" }
        $c create rectangle [expr {$x - 1}] [expr {$y + 6}] [expr {$x + 1}] [expr {$y + 30}] -width 0 -fill #1a1426 -tags post
        $c create polygon [expr {$x - 6}] [expr {$y - 4}] [expr {$x + 6}] [expr {$y - 4}] [expr {$x + 4}] [expr {$y + 6}] [expr {$x - 4}] [expr {$y + 6}] -fill $ink(lampoff) -outline #1a1426 -tags "lamp lamp$n"
        $c create polygon [expr {$x - 8}] [expr {$y - 4}] $x [expr {$y - 10}] [expr {$x + 8}] [expr {$y - 4}] -fill #1a1426 -width 0 -tags post
        incr n }
    if {$i == [llength [lindex $levels $g(level) 1]] - 1} {
        # The gate of the level: bars that go up when each lamp is lit.
        $c create rectangle 440 120 444 196 -width 0 -fill #1a1426 -tags gatepost
        $c create rectangle 466 120 470 196 -width 0 -fill #1a1426 -tags gatepost
        for {set x 446} {$x < 466} {incr x 5} { $c create rectangle $x 124 [expr {$x + 2}] 196 -width 0 -fill #8f86b0 -tags bars }
    }
    overlay $c
    paint $i
}

# The sky, the stars, the hills, and the roofs of a street.
proc backdrop {c i} {
    global g W H dusk
    # The sky in four bands, and stars that come out with the night.
    for {set k 0} {$k < 20} {incr k} { $c create rectangle 0 [expr {$k * 9}] $W [expr {$k == 19 ? $H : ($k + 1) * 9}] -width 0 -tags "sky sky$k" }
    for {set k 0} {$k < 26} {incr k} {
        set x [expr {($k * 131 + $i * 57 + $g(level) * 23) % $W}]; set y [expr {($k * 37 + $i * 11) % 40}]
        $c create rectangle $x $y [expr {$x + 2}] [expr {$y + 2}] -width 0 -fill $dusk(sky0) -tags "star"
    }
    # Two lines of hills, then the roofs of the town.
    set pts {}; for {set x 0} {$x <= $W + 40} {incr x 40} { lappend pts $x [expr {150 + 18 * sin(($x + $i * 90 + $g(level) * 40) / 70.0)}] }
    $c create polygon 0 $H {*}$pts $W $H -width 0 -tags hill
    set pts {}; for {set x 0} {$x <= $W + 30} {incr x 30} { lappend pts $x [expr {170 + 10 * sin(($x * 1.7 + $i * 40) / 50.0)}] }
    $c create polygon 0 $H {*}$pts $W $H -width 0 -tags hill2
    for {set x 10} {$x < $W} {incr x 70} {
        set w [expr {30 + ($x * 7 + $i) % 20}]; set top [expr {150 + ($x * 3 + $g(level) * 5) % 20}]
        $c create polygon $x 190 $x $top [expr {$x + $w / 2}] [expr {$top - 14}] [expr {$x + $w}] $top [expr {$x + $w}] 190 -width 0 -tags "hill2 roof"
        $c create rectangle [expr {$x + 8}] [expr {$top + 8}] [expr {$x + 13}] [expr {$top + 14}] -width 0 -fill #e8b86a -tags "window roof"
    }
}
# The hero, the particles, the HUD, and the message of a street.
proc overlay {c} {
    global W ink g toy
    # The hero: a cloak, a face, a hat, and the flame on a pole.
    $c create rectangle 0 0 1 1 -width 0 -fill $ink(cloak) -tags "hero hcloak"
    $c create rectangle 0 0 1 1 -width 0 -fill $ink(face) -tags "hero hface"
    $c create rectangle 0 0 1 1 -width 0 -fill #1a1426 -tags "hero hhat"
    $c create line 0 0 1 1 -fill #c8b088 -width 2 -tags "hero hpole"
    $c create oval 0 0 1 1 -width 0 -fill $ink(flame) -tags "hero hflame"
    $c create oval 0 0 1 1 -width 0 -fill $ink(gold) -tags "hero hcore"
    for {set k 0} {$k < 20} {incr k} { $c create rectangle -9 -9 -8 -8 -width 0 -fill $ink(gold) -tags "part p$k"; set ::pcolor($k) $ink(gold) }
    $c create text 8 6 -anchor nw -fill $ink(text) -font {TkFixedFont 10 bold} -tags hud
    $c create rectangle 360 9 464 15 -outline $ink(dim) -width 1 -tags hudbar
    $c create rectangle 361 10 463 14 -width 0 -fill $ink(gold) -tags hudfill
    $c create text [expr {$W / 2}] 92 -fill $ink(text) -font {TkFixedFont 20 bold} -tags "msg"
    $c create text [expr {$W / 2}] 122 -fill $ink(dim) -font {TkFixedFont 10 bold} -tags "msg2"
    # On a touch screen the bar of the night moves left for the mark of
    # the pause.
    if {$toy(touch) || $g(state) eq "run"} {
        $c move hudbar -28 0; $c move hudfill -28 0
        $c create rectangle 448 6 452 20 -width 0 -fill $ink(dim) -tags pausemark
        $c create rectangle 457 6 461 20 -width 0 -fill $ink(dim) -tags pausemark
    }
}

# The colors of a street for the dark of the level, from 0 to 1.
proc paint {i} {
    global dusk night g
    set c .nb.s$i
    set t [ease $g(dark)]
    # Twenty bands of the sky, mixed between the four colors of the palette.
    for {set k 0} {$k < 20} {incr k} {
        set u [expr {$k / 19.0 * 3}]; set a [expr {min(2, int($u))}]; set f [expr {$u - $a}]
        set top [mix $dusk(sky$a) $dusk(sky[expr {$a + 1}]) $f]
        set low [mix $night(sky$a) $night(sky[expr {$a + 1}]) $f]
        $c itemconfigure sky$k -fill [mix $top $low $t]
    }
    foreach k {hill hill2 ground edge} { $c itemconfigure $k -fill [mix $dusk($k) $night($k) $t] }
    $c itemconfigure star -fill [mix [mix $dusk(sky0) $night(sky0) $t] #dcd6ff [expr {($t - 0.3) * 1.6}]]
    $c configure -background [mix $dusk(sky0) $night(sky0) $t]
    # Each glow mixes the gold of the lamp into the sky behind it.
    set sky [mix $dusk(sky1) $night(sky1) $t]
    foreach k {6 5 4 3 2 1} f {0.07 0.13 0.2 0.29 0.4 0.56} { $c itemconfigure g$k -fill [mix $sky #ffd27a $f] }
}

proc lvl {} { lindex $::levels $::g(level) 1 }
# The parts of the current street, read once when you enter it.
proc loadStreet {} {
    foreach what {name blocks ledges lamps springs boats crumbles water} v [lindex [lvl] $::g(scene)] { set ::cur($what) $v }
}
proc data {what} { return $::cur($what) }

proc start {n} {
    global g h levels toy lit crumb
    array set g [list state play level $n scene 0 dark 0 frames 0 shake 0 freeze 0 clear 0 msgT 120 auto $toy(touch) cam 0 paused 0]
    array unset lit; array unset crumb
    set toy(music) play
    set scenes [lvl]
    foreach t [.nb tabs] { .nb forget $t }
    for {set i 0} {$i < [llength $scenes]} {incr i} {
        .nb add .nb.s$i -text [lindex $scenes $i 0] -state [expr {$i ? "disabled" : "normal"}]
        street $i
    }
    tabtext
    array set h {x 24 y 150 vx 0 vy 0 ground 0 coyote 0 buffer 0 face 1 sx 1 sy 1 ride -1 crumble -1}
    array set h {spawnS 0 spawnX 24 spawnY 150}
    .nb select 0
    enter 0 24
    say [lindex $levels $n 0] "Level [expr {$n + 1}] of 5"
}

# The name of each tab, with a dot for each lamp: lit or not.
proc tabtext {} {
    global lit
    set i 0
    foreach s [lvl] {
        set dots ""
        for {set k 0} {$k < [llength [lindex $s 3]]} {incr k} { append dots [expr {[info exists lit($i,$k)] ? "●" : "○"}] }
        .nb tab $i -text "[lindex $s 0] $dots"
        incr i
    }
}

proc say {a b} {
    set c .nb.s$::g(scene)
    $c itemconfigure msg -text $a
    $c itemconfigure msg2 -text $b
    set ::g(msgT) 150
}

# A click on a tab of a street that you saw takes you to its start.
bind .nb <<NotebookTabChanged>> {
    set n [.nb index current]
    if {$g(state) eq "play" && $n != $g(scene)} { enter $n 24; set h(y) 120; set h(vy) 0 }
}
proc enter {n x} {
    global g h
    foreach i {0 1 2} { if {[winfo exists .nb.s$i]} { .nb.s$i itemconfigure hero -state hidden } }
    set g(scene) $n; set h(x) $x
    loadStreet
    .nb.s$n itemconfigure hero -state normal
    paint $n
    if {[.nb index current] != $n} { .nb select $n }
}

proc burst {x y n color {up 0}} {
    global parts
    for {set k 0} {$k < $n} {incr k} {
        set a [expr {rand() * 6.283}]; set s [expr {0.6 + rand() * 1.8}]
        lappend parts [list $x $y [expr {cos($a) * $s}] [expr {sin($a) * $s - $up}] [expr {24 + int(rand() * 18)}] $color]
    }
    set parts [lrange $parts end-19 end]
}

proc hurt {} {
    global h g
    sfx hurt
    set g(shake) 10
    set g(dark) [expr {min(1.0, $g(dark) + 0.05)}]
    burst $h(x) $h(y) 12 #ff9a3c 1
    if {$h(spawnS) != $g(scene)} { enter $h(spawnS) $h(spawnX) }
    set h(x) $h(spawnX); set h(y) $h(spawnY); set h(vx) 0; set h(vy) 0; set h(face) 1
}

# The solid tops under the feet: blocks, ledges, boats, and boards.
proc floors {} {
    global g h crumb
    set out {}
    foreach b [data blocks] { lappend out [concat $b solid -1] }
    foreach l [data ledges] { lappend out [concat $l ledge -1] }
    set n 0
    foreach bt [data boats] {
        lassign $bt x0 y x1 dx per
        set off [expr {$dx * sin($g(frames) * 6.283 / $per)}]
        lappend out [list [expr {$x0 + $off}] $y [expr {$x1 + $off}] boat $n]
        incr n
    }
    set n 0
    foreach cr [data crumbles] {
        if {![info exists crumb($g(scene),$n)] || [lindex $crumb($g(scene),$n) 0] < 40} { lappend out [concat $cr crumble $n] }
        incr n
    }
    return $out
}

proc tick {} {
    global g
    after 16 tick
    if {$g(paused)} return
    if {$g(state) eq "title"} { titleTick; return }
    if {$g(freeze) > 0} { incr g(freeze) -1; return }
    if {$g(state) eq "play"} { step }
    if {$g(state) eq "run"} { runStep }
    draw
}

proc step {} {
    global g h hold lit crumb toy levels
    incr g(frames)
    # The auto mode: the hero walks the way it faces, and a jump is
    # always full.
    if {$g(auto)} { set hold(left) [expr {$h(face) < 0}]; set hold(right) [expr {$h(face) > 0}]; if {$h(ground) && $h(buffer) == 0} { set hold(jump) 0 } }
    set c .nb.s$g(scene)
    # The night comes in about 100 seconds; each lamp holds it back.
    set g(dark) [expr {min(1.0, $g(dark) + 1.0 / 6000)}]
    if {$g(frames) % 20 == 0} { paint $g(scene) }
    if {$g(dark) >= 1.0} {
        set g(state) night; set toy(music) ""; sfx lose
        say "Night fell" [expr {$toy(touch) ? "Tap to try again" : "Press A to try again"}]; return
    }
    # Run: speed up on a press, slow down on a release, less in the air.
    set dir [expr {$hold(right) - $hold(left)}]
    set acc [expr {$h(ground) ? 0.45 : 0.28}]
    if {$dir != 0} {
        set h(face) $dir
        set h(vx) [expr {max(-2.7, min(2.7, $h(vx) + $dir * $acc))}]
    } else {
        set f [expr {$h(ground) ? 0.42 : 0.12}]
        set h(vx) [expr {abs($h(vx)) <= $f ? 0 : $h(vx) - ($h(vx) > 0 ? $f : -$f)}]
    }
    # A jump: the press waits 7 frames (the buffer), and the ground
    # stays for 6 frames after the edge (coyote time).
    if {$h(buffer) > 0} { incr h(buffer) -1 }
    if {$h(ground)} { set h(coyote) 6 } elseif {$h(coyote) > 0} { incr h(coyote) -1 }
    if {$h(buffer) > 0 && $h(coyote) > 0} {
        set h(vy) -6.3; set h(buffer) 0; set h(coyote) 0; set h(ground) 0; set h(ride) -1
        set h(sx) 0.7; set h(sy) 1.35; sfx jump
        burst $h(x) [expr {$h(y) + 7}] 4 #c8b8e0
    }
    set h(vy) [expr {min(6.0, $h(vy) + ($h(vy) < 0 && ($hold(jump) || $g(auto)) ? 0.30 : 0.42))}]
    # Ride a boat: move with it.
    if {$h(ride) >= 0} {
        foreach f [floors] { lassign $f x0 y x1 kind n; if {$kind eq "boat" && $n == $h(ride)} { set h(x) [expr {$h(x) + ($x0 - $h(rideX))}]; set h(rideX) $x0 } }
    }
    set h(x) [expr {$h(x) + $h(vx)}]
    # The sides of the blocks.
    foreach b [data blocks] {
        lassign $b x0 top x1
        if {$h(y) + 7 > $top + 2 && $h(x) + 5 > $x0 && $h(x) - 5 < $x1} {
            set h(x) [expr {$h(vx) > 0 ? $x0 - 5 : $x1 + 5}]; set h(vx) 0
        }
    }
    set oy $h(y)
    set h(y) [expr {$h(y) + $h(vy)}]
    set was $h(ground)
    set h(ground) 0
    if {$h(vy) >= 0} {
        foreach f [floors] {
            lassign $f x0 y x1 kind n
            if {$oy + 7 <= $y + 1 && $h(y) + 7 >= $y && $h(x) + 4 > $x0 && $h(x) - 4 < $x1} {
                set h(y) [expr {$y - 7}]
                if {!$was && $h(vy) > 2.5} {
                    set h(sx) 1.35; set h(sy) 0.7; sfx land
                    burst $h(x) $y [expr {$h(vy) > 5 ? 8 : 4}] #c8b8e0
                    if {$h(vy) > 5.5} { set g(shake) 4 }
                }
                set h(vy) 0; set h(ground) 1
                set h(ride) [expr {$kind eq "boat" ? $n : -1}]
                if {$kind eq "boat"} { set h(rideX) $x0 }
                if {$kind eq "crumble" && ![info exists crumb($g(scene),$n)]} { set crumb($g(scene),$n) {0} }
                break
            }
        }
    }
    if {!$h(ground)} { set h(ride) -1 }
    # The boards break 40 frames after a step, and come back after 3 s.
    foreach k [array names crumb $g(scene),*] {
        set n [lindex [split $k ,] 1]
        set t [expr {[lindex $crumb($k) 0] + 1}]
        set crumb($k) $t
        if {$t == 40} { sfx crash; .nb.s$g(scene) itemconfigure cr$n -state hidden; lassign [lindex [data crumbles] $n] x0 y x1; burst [expr {($x0 + $x1) / 2}] $y 10 #8a6a4a }
        if {$t > 220} { unset crumb($k); .nb.s$g(scene) itemconfigure cr$n -state normal }
        if {$t < 40 && $t % 6 < 3} { .nb.s$g(scene) move cr$n [expr {$t % 2 ? 1 : -1}] 0 }
    }
    # A spring sends you high.
    foreach s [data springs] {
        lassign $s sx sy
        if {$h(ground) && abs($h(x) - $sx) < 10 && abs($h(y) + 7 - $sy) < 3} {
            set h(vy) -9.6; set h(ground) 0; set h(sx) 0.6; set h(sy) 1.5; sfx pop; burst $sx $sy 6 #a6e6b2 1
        }
    }
    # The lamps.
    set k 0
    foreach l [data lamps] {
        lassign $l lx ly
        if {![info exists lit($g(scene),$k)] && abs($h(x) - $lx) < 11 && abs($h(y) - 4 - $ly) < 22} {
            set lit($g(scene),$k) 1
            $c itemconfigure lamp$k -fill #ffd27a
            $c itemconfigure glow$k -state normal
            $c raise glow$k window
            $c lower glow$k post
            set g(dark) [expr {max(0.0, $g(dark) - 0.22)}]
            paint $g(scene)
            burst $lx $ly 16 #ffd27a 0.5
            set g(freeze) 4; set g(shake) 3; sfx light
            tabtext
            if {[allLit]} { sfx win; say "The gate is open" "Walk on to the right" }
        }
        incr k
    }
    # The edges of a street.
    set last [expr {[llength [lvl]] - 1}]
    if {$h(x) > $::W - 4} {
        if {$g(scene) < $last} {
            set n [expr {$g(scene) + 1}]
            .nb tab $n -state normal
            set h(spawnS) $n; set h(spawnX) 20; set h(spawnY) 150
            enter $n 8; sfx select
        } elseif {[allLit]} { finish; return } else {
            set h(x) [expr {$::W - 4}]
        }
    }
    # In the auto mode the closed gate and the left edge turn the hero, so
    # it walks back to a lamp that it missed.
    if {$g(scene) == $last && ![allLit] && $h(x) > 436} { set h(x) 436; set h(vx) 0; if {$g(auto)} { set h(face) -1 } }
    if {$h(x) < 5} {
        if {$g(scene) > 0} { enter [expr {$g(scene) - 1}] [expr {$::W - 10}] } else { set h(x) 5; if {$g(auto)} { set h(face) 1 } }
    }
    if {$h(y) > $::H + 10} { hurt }
    # Steps on the ground.
    if {$h(ground) && abs($h(vx)) > 1 && [incr h(step)] % 14 == 0} { sfx step }
}

proc allLit {} {
    global lit g
    set i 0
    foreach s [lvl] { for {set k 0} {$k < [llength [lindex $s 3]]} {incr k} { if {![info exists lit($i,$k)]} { return 0 } }; incr i }
    return 1
}

proc finish {} {
    global g best toy
    set secs [expr {$g(frames) / 60.0}]
    set n $g(level)
    set new [expr {![info exists best($n)] || $secs < $best($n)}]
    if {$new} { set best($n) [format %.1f $secs] }
    set g(unlocked) [expr {max($g(unlocked), min(5, $n + 2))}]
    save
    set g(state) clear; set toy(music) ""; sfx win
    set g(shake) 0
    say "[lindex $::levels $n 0] is lit" "[format %.1f $secs] s[expr {$new ? "  new best" : "  best $best($n) s"}]   [expr {$toy(touch) ? "Tap: next" : "A: next"}]"
}

proc ending {} {
    set c .nb.s$::g(scene)
    say "The town is lit" "Thank you for the light. [expr {$::toy(touch) ? "Tap" : "A"}]: title"
    set ::toy(music) title
}

# Moves the items of the street to the state of the frame.
proc draw {} {
    global g h parts ink
    set c .nb.s$g(scene)
    # The squash and the stretch go back to 1.
    set h(sx) [expr {$h(sx) + (1 - $h(sx)) * 0.25}]
    set h(sy) [expr {$h(sy) + (1 - $h(sy)) * 0.25}]
    set ox 0; set oy 0
    if {$g(shake) > 0 && !$::toy(calm)} {
        set ox [expr {int((rand() - 0.5) * $g(shake))}]; set oy [expr {int((rand() - 0.5) * $g(shake))}]
    }
    if {$g(shake) > 0} { incr g(shake) -1 }
    # The camera: 0 in a level, the left edge of the view in the endless run.
    set cam $g(cam)
    set x [expr {$h(x) - $cam + $ox}]; set y [expr {$h(y) + 7 + $oy}]
    set w [expr {6.5 * $h(sx)}]; set hh [expr {19 * $h(sy)}]
    set bob [expr {$h(ground) && abs($h(vx)) > 0.5 ? sin($g(frames) * 0.5) : 0}]
    $c coords hcloak [expr {$x - $w}] [expr {$y - $hh * 0.72}] [expr {$x + $w}] $y
    $c coords hface [expr {$x - $w * 0.7}] [expr {$y - $hh}] [expr {$x + $w * 0.7}] [expr {$y - $hh * 0.68 + $bob}]
    $c coords hhat [expr {$x - $w - 1}] [expr {$y - $hh - 2}] [expr {$x + $w + 1}] [expr {$y - $hh}]
    set px [expr {$x + $h(face) * 7}]; set py [expr {$y - $hh - 6}]
    $c coords hpole [expr {$x + $h(face) * 3}] [expr {$y - 4}] $px $py
    set fl [expr {2.4 + sin($g(frames) * 0.4) * 0.8}]
    $c coords hflame [expr {$px - $fl - 1}] [expr {$py - $fl - 3}] [expr {$px + $fl + 1}] [expr {$py + $fl}]
    $c coords hcore [expr {$px - 1.2}] [expr {$py - 2}] [expr {$px + 1.2}] [expr {$py + 1}]
    if {$g(frames) % 5 == 0 && $g(state) in {play run}} { lappend parts [list [expr {$px + $cam}] [expr {$py - 2}] [expr {(rand() - 0.5) * 0.4}] -0.6 30 #ffb35c] }
    # The particles: embers, dust, and sparks.
    set keep {}
    set k 0
    foreach p $parts {
        lassign $p px py vx vy life color
        if {[incr life -1] <= 0 || $k >= 20} continue
        set px [expr {$px + $vx}]; set py [expr {$py + $vy}]; set vy [expr {$vy + 0.05}]
        set s [expr {$life > 12 ? 2 : 1}]
        $c coords p$k [expr {$px - $cam}] $py [expr {$px - $cam + $s}] [expr {$py + $s}]
        if {$::pcolor($k) ne $color} { $c itemconfigure p$k -fill $color; set ::pcolor($k) $color }
        lappend keep [list $px $py $vx $vy $life $color]
        incr k
    }
    for {} {$k < 20} {incr k} { $c coords p$k -9 -9 -8 -8 }
    set parts $keep
    # The boats swing.
    set n 0
    foreach bt [data boats] {
        lassign $bt x0 y x1 dx per
        set off [expr {$dx * sin($g(frames) * 6.283 / $per)}]
        $c coords bt$n [expr {$x0 + $off}] $y [expr {$x1 + $off}] $y [expr {$x1 + $off - 6}] [expr {$y + 8}] [expr {$x0 + $off + 6}] [expr {$y + 8}]
        incr n
    }
    if {$g(state) ni {run runover} && [allLit]} { foreach id [$c find withtag bars] { lassign [$c coords $id] a b cc d; if {$b > 60} { $c coords $id $a [expr {$b - 2}] $cc [expr {$d - 2}] } } }
    if {$g(state) in {run runover streetclear}} { weatherTick $c }
    if {$g(state) eq "title"} return
    if {$g(state) in {run runover streetclear}} {
        $c itemconfigure hud -text "Lamps $::run(lit)   [expr {int($h(x) / 10)}] m"
    } else {
        $c itemconfigure hud -text "[lindex $::levels $g(level) 0]   [format %02d:%02d [expr {$g(frames) / 3600}] [expr {($g(frames) / 60) % 60}]]"
    }
    set left [expr {1 - $g(dark)}]
    set bx [expr {[lindex [$c coords hudbar] 0] + 1}]
    $c coords hudfill $bx 10 [expr {$bx + 102 * $left}] 14
    $c itemconfigure hudfill -fill [expr {$left < 0.25 && $g(frames) % 30 < 15 && !$::toy(calm) ? "#ff6a5c" : "#ffd27a"}]
    if {$g(msgT) > 0 && $g(state) in {play run} && [incr g(msgT) -1] == 0} { say "" "" }
}

# Three small stars on the canvas c, the last one ending at x: gold for
# each one of n.
proc miniStars {c x y n} {
    for {set k 0} {$k < 3} {incr k} {
        set cx [expr {$x - 5 - (2 - $k) * 11}]; set pts {}
        for {set i 0} {$i < 10} {incr i} {
            set r [expr {$i % 2 ? 2.2 : 5}]; set a [expr {-1.5708 + $i * 0.6283}]
            lappend pts [expr {$cx + $r * cos($a)}] [expr {$y + $r * sin($a)}]
        }
        $c create polygon {*}$pts -fill [expr {$k < $n ? "#ffc93c" : "#4a5a78"}] -width 0
    }
}
# The title screen: the first street of the first level, the name, and
# three entries: Continue, all levels and streets, and the endless run.
proc title {} {
    global g levels toy ink best run
    set g(state) title
    set toy(music) title
    foreach t [.nb tabs] { .nb forget $t }
    if {$g(pick) ni [picks]} { set g(pick) continue }
    set g(level) 0; set g(scene) 0; set g(dark) 0.15; set g(cam) 0
    useTheme 0
    unpause
    loadStreet
    .nb add .nb.s0 -text "Lamplighter"
    street 0
    set c .nb.s0
    $c itemconfigure hero -state normal
    $c itemconfigure hud -text ""
    $c itemconfigure hudbar -state hidden; $c itemconfigure hudfill -state hidden; $c itemconfigure pausemark -state hidden
    $c create text 236 64 -text "LAMPLIGHTER" -fill $ink(gold) -font {TkFixedFont 30 bold} -tags title
    switch $g(pick) {
        continue {
            set n [continueAt]
            set name "Continue: [expr {$n + 1}]. [levelName $n]"
            set b "[doneCount] of [count] streets lit"
        }
        levels { set name "All streets"; set b "[openCount] of [count] open" }
        run { set name "Endless street"; set b [expr {$run(best) ? "best $run(best)" : "no run yet"}] }
    }
    $c create text 236 100 -text "◀  $name  ▶" -fill $ink(text) -font {TkFixedFont 12 bold} -tags title
    $c create text 236 122 -text $b -fill $ink(dim) -font {TkFixedFont 10} -tags title
    set help [expr {$toy(touch) ? "Tap here: start      Tap a side: more" : "A or Enter: start      Left and Right: more"}]
    $c create text 236 222 -text $help -fill $ink(dim) -font {TkFixedFont 9 bold} -tags "title blink"
    array set ::h {x 60 y 189 vx 0.8 vy 0 face 1 sx 1 sy 1 ground 1}
    # The lamp of the title is lit.
    $c itemconfigure lamp0 -fill $ink(gold)
    $c itemconfigure glow0 -state normal
    $c raise glow0 window
    $c lower glow0 post
}

# The picker: ten cards on a page, each with a picture of its theme, its
# number, its stars, and the letters of its modifiers. Under the cards:
# the page before, the selected street, and the next page.
proc picker {{sel ""}} {
    global g
    set g(state) pick
    if {$sel ne ""} { set g(sel) [expr {max(0, min([count] - 1, $sel))}] }
    foreach t [.nb tabs] { .nb forget $t }
    .nb add .nb.s0 -text "Streets"
    useTheme 0
    drawPicker
}
proc drawPicker {} {
    global g
    set c .nb.s0
    set g(page) [expr {$g(sel) / 10}]
    $c delete all
    $c configure -background #15122a
    for {set i 0} {$i < 10} {incr i} {
        set n [expr {$g(page) * 10 + $i}]
        if {$n >= [count]} break
        set x0 [expr {6 + ($i % 5) * 92}]; set y0 [expr {6 + ($i / 5) * 86}]
        set open [isOpen $n]
        $c create rectangle $x0 $y0 [expr {$x0 + 88}] [expr {$y0 + 82}] -fill #221c3c \
            -outline [expr {$n == $g(sel) ? "#ffd27a" : "#3a3358"}] -width [expr {$n == $g(sel) ? 3 : 1}]
        # The picture: three bands of the sky of the theme, roofs, and the
        # ground.
        set t [themeInk [levelTheme $n]]
        set d [dict get $t dusk]; set ni [dict get $t night]
        foreach k {0 1 2} {
            set y [expr {$y0 + 4 + $k * 14}]
            $c create rectangle [expr {$x0 + 4}] $y [expr {$x0 + 84}] [expr {$y + 14}] -width 0 -fill [mix [dict get $d sky$k] [dict get $ni sky$k] 0.35]
        }
        set gy [expr {$y0 + 50}]
        for {set x [expr {$x0 + 6}]} {$x < $x0 + 78} {incr x 18} {
            set h [expr {6 + ($x * 7 + $n * 13) % 9}]
            $c create polygon $x $gy $x [expr {$gy - $h}] [expr {$x + 6}] [expr {$gy - $h - 5}] [expr {$x + 12}] [expr {$gy - $h}] [expr {$x + 12}] $gy -width 0 -fill [dict get $ni hill2]
        }
        $c create rectangle [expr {$x0 + 4}] $gy [expr {$x0 + 84}] [expr {$y0 + 56}] -width 0 -fill [dict get $d ground]
        $c create oval [expr {$x0 + 60}] [expr {$gy - 22}] [expr {$x0 + 66}] [expr {$gy - 16}] -width 0 -fill #ffd27a
        set s [stars $n]
        $c create text [expr {$x0 + 6}] [expr {$y0 + 66}] -anchor w -text [expr {$n + 1}] -fill #f6ecd6 -font {TkFixedFont 10 bold}
        miniStars $c [expr {$x0 + 86}] [expr {$y0 + 66}] $s
        $c create text [expr {$x0 + 6}] [expr {$y0 + 76}] -anchor w -text [join [lmap m [levelMods $n] { string index [dict get $::modName $m] 0 }] " "] -fill #a89cc4 -font {TkFixedFont 8 bold}
        if {!$open} {
            $c create rectangle [expr {$x0 + 4}] [expr {$y0 + 4}] [expr {$x0 + 84}] [expr {$y0 + 18}] -width 0 -fill #221c3c
            $c create text [expr {$x0 + 44}] [expr {$y0 + 11}] -text "closed" -fill #a89cc4 -font {TkFixedFont 8 bold}
        }
    }
    foreach {x0 x1 text} {6 58 "◀" 414 466 "▶"} {
        $c create rectangle $x0 182 $x1 226 -fill #2a2346 -outline #3a3358
        $c create text [expr {($x0 + $x1) / 2}] 204 -text $text -fill #f6ecd6 -font {TkFixedFont 12 bold}
    }
    set n $g(sel)
    set line "[expr {$n + 1}]. [levelName $n]"
    set more [concat [list [levelIdea $n]] [lmap m [levelMods $n] { dict get $::modName $m }]]
    $c create text 236 194 -text $line -fill #f6ecd6 -font {TkFixedFont 10 bold}
    $c create text 236 214 -text "[join $more ", "]   [themeName [levelTheme $n]][expr {[isOpen $n] ? "" : "   closed"}]" -fill #a89cc4 -font {TkFixedFont 8}
}
proc pickMove {d} {
    global g
    set n [expr {$g(sel) + $d}]
    if {$n < 0 || $n >= [count]} { sfx move; return }
    set g(sel) $n; sfx move; drawPicker
}
proc pickPlay {n} {
    if {![isOpen $n]} { sfx hurt; return }
    sfx start; playLevel $n
}
# A tap in the picker: a card plays its street on a touch screen; with a
# mouse, the first click selects it.
proc pickTap {x y} {
    global g
    if {$y > 180} {
        if {$x < 60} { pickMove -10 } elseif {$x > 412} { pickMove [expr {min(10, [count] - 1 - $g(sel))}] }
        return
    }
    set col [expr {int(($x - 6) / 92)}]; set row [expr {int(($y - 6) / 86)}]
    if {$col < 0 || $col > 4 || $row < 0 || $row > 1} return
    set n [expr {$g(page) * 10 + $row * 5 + $col}]
    if {$n >= [count]} return
    if {$n == $g(sel) || $::toy(touch)} { set g(sel) $n; pickPlay $n } else { set g(sel) $n; sfx move; drawPicker }
}

# A tap on a canvas of the game. The pointer press of a mouse comes here
# too: it plays the menus, and it jumps in the auto mode and in the run.
proc tap {x y} {
    global g W run
    set third [expr {$x < $W / 3.0 ? "left" : $x > $W * 2 / 3.0 ? "right" : "middle"}]
    if {$g(paused)} { if {$third eq "left"} { title } else { unpause }; return }
    if {$g(state) in {play run} && $x > $W - 60 && $y < 40 && ($::toy(touch) || $g(state) eq "run")} { pause; return }
    switch $g(state) {
        title {
            set g(picked) 1
            switch $third { left { pickAt -1 } right { pickAt 1 } middle { toy_input a press } }
        }
        pick { pickTap $x $y }
        streetclear { toy_input [expr {$third eq "left" ? "b" : "a"}] press }
        play { if {$g(auto)} { toy_input a press } }
        run { set run(press) 1 }
        clear - night - done - runover {
            if {$third eq "left"} { title } else { toy_input a press }
        }
    }
}
proc pause {} {
    global g W
    set g(paused) 1
    set c .nb.s$g(scene)
    $c create rectangle 0 0 $W $::H -width 0 -fill #0c0b1a -tags pausebox
    $c create text [expr {$W / 2}] 100 -text "Paused" -fill $::ink(text) -font {TkFixedFont 20 bold} -tags pausebox
    $c create text [expr {$W / 2}] 132 -text "Tap: play on      Tap the left side: title" -fill $::ink(dim) -font {TkFixedFont 10 bold} -tags pausebox
}
proc unpause {} {
    global g
    set g(paused) 0
    foreach i {0 1 2} { .nb.s$i delete pausebox }
}
for {set i 0} {$i < 3} {incr i} {
    bind .nb.s$i <ButtonPress-1> {tap %x %y}
    bind .nb.s$i <ButtonRelease-1> {if {$g(state) eq "play" && $g(auto)} {toy_input a release}}
}

proc titleTick {} {
    global g h
    incr g(frames)
    set h(x) [expr {$h(x) + 0.8}]
    if {$h(x) > 500} { set h(x) -20 }
    set h(vx) 0.8; set h(ground) 1
    if {$g(frames) % 40 == 0} { .nb.s0 itemconfigure blink -state [expr {$g(frames) % 80 ? "hidden" : "normal"}] }
    draw
}

# The endless run. One street with no end: a generator adds a piece of
# street ahead of the view, and a piece that scrolls off the left goes,
# with its canvas items. The pieces are the parts of the levels: flat
# ground, a lamp at walking height, a high lamp that a jump reaches, a
# gap of water, a step up, a step down, and a board over the water that
# breaks. The hero walks by itself at the speed of its piece, and a tap
# (or A) jumps, always the full height.
#
# The generator is seeded (run(seed)), so a seed gives the same street on
# each platform. Before it adds a piece, it proves that the piece can be
# passed: `trial` runs the physics of the run (`physics`, the code of the
# game itself) over the piece for each frame of a tap, and the piece
# needs a span of at least MINTAP frames where a tap passes it, or no tap
# at all. A piece that fails gets easier and is tried again. The middle
# of the span goes in run(taps), the taps of the bot of the tests.
#
# The night comes faster with the distance, the speed goes up from 1.7 to
# 2.6 pixels a frame, and the pieces get harder, so a run ends: the night
# falls, or the hero falls into the water. The score is 10 for each lamp
# and 1 for each 10 pixels.
set MINTAP 8
proc rnd {} {
    global run
    set run(rs) [expr {($run(rs) * 1103515245 + 12345) % 2147483648}]
    expr {$run(rs) / 2147483648.0}
}
proc speedAt {x} { expr {min(2.6 + $::run(fast), 1.7 + $::run(fast) + $x / 12000.0)} }
# The mix of the pieces of each style: the share of flat, high lamp,
# gap, step up, step down, and board, as running sums.
set styles {
    mixed {0.16 0.36 0.64 0.76 0.86 1}
    roofs {0.08 0.22 0.36 0.62 0.84 1}
    canal {0.08 0.22 0.62 0.70 0.78 1}
    orchard {0.14 0.56 0.74 0.84 0.92 1}
}

# One frame of the physics of the run on the array hv, over the floors
# segs ({x0 top x1 kind id}: kind solid goes to the bottom, crumble is a
# board). cv is the array of the boards that broke. press is 1 for a tap
# in this frame. Gives the events of the frame.
proc physics {hv segs cv v press} {
    upvar 1 $hv h $cv cr
    set ev {}
    if {$press} { set h(buffer) 7 }
    if {$h(buffer) > 0} { incr h(buffer) -1 }
    if {$h(ground)} { set h(coyote) 6 } elseif {$h(coyote) > 0} { incr h(coyote) -1 }
    if {$h(buffer) > 0 && $h(coyote) > 0} {
        set h(vy) -6.3; set h(buffer) 0; set h(coyote) 0; set h(ground) 0
        lappend ev jump
    }
    set h(vy) [expr {min(6.0, $h(vy) + ($h(vy) < 0 ? 0.30 : 0.42))}]
    set nx [expr {$h(x) + $v}]
    set h(wall) 0
    foreach s $segs {
        lassign $s x0 top x1 kind
        if {$kind eq "solid" && $h(y) + 7 > $top + 2 && $nx + 5 > $x0 && $h(x) + 5 <= $x0 + 1} { set nx [expr {$x0 - 5}]; set h(wall) 1 }
    }
    set h(x) $nx
    set oy $h(y)
    set h(y) [expr {$h(y) + $h(vy)}]
    set was $h(ground)
    set h(ground) 0
    if {$h(vy) >= 0} {
        foreach s $segs {
            lassign $s x0 top x1 kind id
            if {$kind eq "crumble" && [info exists cr($id)] && $cr($id) >= 40} continue
            if {$oy + 7 <= $top + 1 && $h(y) + 7 >= $top && $h(x) + 4 > $x0 && $h(x) - 4 < $x1} {
                set h(y) [expr {$top - 7}]
                if {!$was && $h(vy) > 2.5} { lappend ev land }
                set h(vy) 0; set h(ground) 1
                if {$kind eq "crumble" && ![info exists cr($id)]} { set cr($id) 0 }
                break
            }
        }
    }
    # A board breaks 40 frames after a step and comes back after 3 s.
    foreach id [array names cr] {
        set t [incr cr($id)]
        if {$t == 40} { lappend ev [list break $id] }
        if {$t > 220} { unset cr($id); lappend ev [list mend $id] }
    }
    return $ev
}

# Runs the hero over a piece, from the state st (an array get) and the
# boards cst, with a tap in the first frame when press is 1. Gives 1
# when the hero stands at or past x1 in time, with the lamp {x y}
# passed in reach when a lamp is given.
proc trial {segs x1 v st cst press lamp} {
    array set s $st
    array set cr $cst
    set lit [expr {$lamp eq ""}]
    set stuck 0
    set limit [expr {int(($x1 - $s(x)) / $v) + 60}]
    for {set t 0} {$t < $limit} {incr t} {
        physics s $segs cr $v [expr {$press && $t == 0}]
        if {!$lit} { lassign $lamp lx ly; if {abs($s(x) - $lx) < 11 && abs($s(y) - 4 - $ly) < 22} { set lit 1 } }
        # Feet under the lowest floor, or a stop of 12 frames at a wall:
        # no pass.
        set stuck [expr {$s(wall) ? $stuck + 1 : 0}]
        if {$s(y) + 7 > 200 || $stuck > 12} { return 0 }
        if {$s(x) >= $x1 && $s(ground)} { return $lit }
    }
    return 0
}

# The longest span of tap frames that pass a piece from x0 to the place
# x1 past its hazard, on the top top, for a tap while the hero is between
# from and to: {x count}, with x the place of the hero at the middle frame
# of the span. The walk with no tap gives the state of each frame, and a
# trial goes on from it with a tap: first at each 4th frame, which finds
# each span of 8 frames or more, then at each frame out from a hit to the
# ends of its span.
proc tapSpan {segs x0 x1 top v from to {lamp {}}} {
    array set s [list x $x0 y [expr {$top - 7}] vy 0 ground 1 coyote 0 buffer 0 wall 0]
    array set cr {}
    set states {}
    set limit [expr {int(($to - $x0) / $v) + 30}]
    while {$s(x) < $to && $s(y) < $::H && [incr limit -1] > 0} {
        if {$s(x) >= $from} { lappend states [list [array get s] [array get cr]] }
        physics s $segs cr $v 0
    }
    set n [llength $states]
    set best {0 0}
    set done -1
    for {set i 0} {$i < $n} {incr i 4} {
        if {$i <= $done} continue
        if {![trial $segs $x1 $v {*}[lindex $states $i] 1 $lamp]} continue
        set lo $i; set hi $i
        while {$lo > 0 && [trial $segs $x1 $v {*}[lindex $states [expr {$lo - 1}]] 1 $lamp]} { incr lo -1 }
        while {$hi < $n - 1 && [trial $segs $x1 $v {*}[lindex $states [expr {$hi + 1}]] 1 $lamp]} { incr hi }
        set done $hi
        if {$hi - $lo + 1 > [lindex $best 1]} {
            array set m [lindex $states [expr {($lo + $hi) / 2}] 0]
            set best [list $m(x) [expr {$hi - $lo + 1}]]
        }
    }
    return $best
}

# Makes the next piece at run(genX) and adds it to the street.
proc genPiece {} {
    global run MINTAP H
    set x $run(genX); set top $run(top); set v [speedAt $x]; set n $run(count)
    set d [expr {min(1.0, $run(diff) + $x / 15000.0)}]
    # The kind of piece: the first two teach a walk to a lamp and a gap.
    # A street has its gate after its last piece, and flat ground after
    # the gate.
    set gate 0
    if {$run(limit) && $n >= $run(limit)} {
        set kind [expr {$n == $run(limit) ? "gate" : "flat"}]
    } elseif {$n == 0} { set kind lamp } elseif {$n == 1} { set kind gap } else {
        set r [rnd]
        lassign [dict get $::styles $run(style)] a b c e f
        set kind [expr {$r < $a ? "flat" : $r < $b ? "high" : $r < $c ? "gap" : $r < $e ? "up" : $r < $f ? "down" : "board"}]
        if {$kind eq "down" && $top >= 196} { set kind up }
        if {$kind eq "up" && $top <= 140} { set kind down }
        if {$kind eq "board" && $x < ($run(style) eq "canal" ? 600 : 2000)} { set kind gap }
    }
    set p [expr {$n == 1 ? 0.0 : [rnd] * (0.35 + 0.65 * $d)}]
    for {set try 0} {1} {incr try} {
        set lead [expr {50 + int([rnd] * 40)}]
        set lamp {}; set water {}; set new $top; set need 1
        switch $kind {
            gate {
                set len 260; set need 0
                set segs [list [list $x $top [expr {$x + $len}] solid]]
                set gate [expr {$x + 120}]
            }
            flat - lamp {
                set len [expr {150 + int([rnd] * 80)}]
                # The first piece gives 4 s to read the line of the start.
                if {$n == 0} { set len 320 }
                set segs [list [list $x $top [expr {$x + $len}] solid]]
                if {$kind eq "lamp" || ([rnd] < 0.5 && !($run(limit) && $n > $run(limit)))} { set lamp [list [expr {$x + $len / 2}] [expr {$top - 30}]] }
                set need 0
            }
            high {
                set len 200
                set segs [list [list $x $top [expr {$x + $len}] solid]]
                set lamp [list [expr {$x + 120}] [expr {$top - 64 - int($p * 14)}]]
            }
            gap {
                set w [expr {24 + int($p * 50)}]
                if {$x > 4000 && [rnd] < 0.4} { set new [expr {max(140, min(196, $top + (int([rnd] * 3) - 1) * 16))}] }
                set a [expr {$x + $lead}]; set b [expr {$a + $w}]; set len [expr {$lead + $w + 90}]
                set segs [list [list $x $top $a solid] [list $b $new [expr {$x + $len}] solid]]
                set water [list $a $b]
            }
            up {
                set new [expr {max(132, $top - 18 - int($p * 22))}]
                set a [expr {$x + $lead}]; set len [expr {$lead + 110}]
                set segs [list [list $x $top $a solid] [list $a $new [expr {$x + $len}] solid]]
                if {[rnd] < 0.5} { set lamp [list [expr {$a + 60}] [expr {$new - 30}]] }
            }
            down {
                set new [expr {min(196, $top + 16 + int($p * 24))}]
                set a [expr {$x + $lead}]; set len [expr {$lead + 110}]
                set segs [list [list $x $top $a solid] [list $a $new [expr {$x + $len}] solid]]
                set need 0
            }
            board {
                # The board must be crossed in less than 40 frames.
                set w [expr {min(int(36 * $v) - 10, 50 + int($p * 40))}]
                set a [expr {$x + $lead}]; set b [expr {$a + $w}]; set len [expr {$lead + $w + 90}]
                set id [incr run(crid)]
                set segs [list [list $x $top $a solid] [list $a $top $b crumble $id] [list $b $top [expr {$x + $len}] solid]]
                set water [list $a $b]
                set need 0
            }
        }
        set x1 [expr {$x + $len}]
        set tap {}
        set walk [trial $segs [expr {$x1 - 8}] $v [list x $x y [expr {$top - 7}] vy 0 ground 1 coyote 0 buffer 0 wall 0] {} 0 {}]
        # The place of the hazard: the tap comes before it, and the
        # hero must stand past its end. A jump goes at most 110 pixels.
        set at [expr {$kind eq "high" ? [lindex $lamp 0] : $x + $lead}]
        set past [expr {$kind eq "high" ? $at + 12 : $water ne "" ? [lindex $water 1] + 6 : $at + 6}]
        set ok $walk
        if {!$walk || $kind eq "high"} {
            lassign [tapSpan $segs $x $past $top $v [expr {$at - 110}] [expr {$at + 10}] [expr {$kind eq "high" ? $lamp : ""}]] f0 cnt
            set ok [expr {$cnt >= $MINTAP}]
            if {$ok} { set tap $f0 }
            if {$kind eq "high" && !$walk} { set ok 0 }
        }
        if {$ok} break
        # Too hard at this speed: make it easier, and at the end flat.
        set p [expr {$p * 0.5}]
        if {$try > 4} { set kind flat }
    }
    incr run(count)
    set run(genX) $x1; set run(top) $new
    lappend run(pieces) [list $x $x1 $v $n]
    lappend run(segs) {*}$segs
    if {$tap ne ""} { lappend run(taps) $tap }
    if {$lamp ne ""} { lappend run(lamps) [list {*}$lamp $n]; incr run(lampsAll) }
    if {$gate} { set run(gateX) $gate }
    drawPiece $n $segs $water $lamp $gate
}

# The canvas items of a piece, tagged w (they move with the camera) and
# pc$n (they go with the piece).
proc drawPiece {n segs water lamp {gate 0}} {
    global run H ink
    set c .nb.s0
    set o $run(shift)
    set t [list w pc$n]
    set x0 [expr {[lindex $segs 0 0] - $o}]; set x1 [expr {[lindex $segs end 2] - $o}]
    # The roofs of the town behind the street.
    for {set x $x0} {$x < $x1 - 30} {set x [expr {$x + 70}]} {
        set w [expr {30 + int([rnd] * 20)}]; set top [expr {146 + int([rnd] * 22)}]
        $c create polygon $x 196 $x $top [expr {$x + $w / 2}] [expr {$top - 14}] [expr {$x + $w}] $top [expr {$x + $w}] 196 -width 0 -tags [concat $t hill2]
        $c create rectangle [expr {$x + 8}] [expr {$top + 8}] [expr {$x + 13}] [expr {$top + 14}] -width 0 -fill #e8b86a -tags [concat $t window]
    }
    if {$water ne ""} {
        lassign $water a b
        set a [expr {$a - $o}]; set b [expr {$b - $o}]
        $c create rectangle $a 206 $b $H -width 0 -fill $ink(water) -tags [concat $t water]
        for {set x [expr {$a + 6}]} {$x < $b - 6} {set x [expr {$x + 18}]} { $c create line $x 210 [expr {$x + 8}] 210 -fill #6a86c8 -width 2 -tags [concat $t ripple] }
    }
    if {$lamp ne ""} {
        lassign $lamp lx ly
        set lx [expr {$lx - $o}]
        foreach r {40 33 27 21 15 10} k {6 5 4 3 2 1} { $c create oval [expr {$lx - $r}] [expr {$ly - $r}] [expr {$lx + $r}] [expr {$ly + $r}] -width 0 -state hidden -tags [concat $t glow glow$n g$k] }
    }
    foreach s $segs {
        lassign $s a top b kind id
        set a [expr {$a - $o}]; set b [expr {$b - $o}]
        if {$kind eq "solid"} {
            $c create rectangle $a $top $b $H -width 0 -tags [concat $t ground]
            $c create rectangle $a $top $b [expr {$top + 3}] -width 0 -tags [concat $t edge]
            for {set x [expr {$a + 7}]} {$x < $b - 4} {set x [expr {$x + 23}]} { $c create line $x $top [expr {$x - 2}] [expr {$top - 4}] $x $top [expr {$x + 3}] [expr {$top - 5}] -fill #7d6aa0 -tags [concat $t tuft] }
        } else {
            $c create rectangle $a $top $b [expr {$top + 5}] -width 0 -fill #8a6a4a -tags [concat $t cr$id]
            for {set x [expr {$a + 10}]} {$x < $b} {set x [expr {$x + 12}]} { $c create line $x $top $x [expr {$top + 5}] -fill #5a4430 -tags [concat $t cr$id] }
        }
    }
    if {$lamp ne ""} {
        lassign $lamp lx ly
        set lx [expr {$lx - $o}]
        $c create rectangle [expr {$lx - 1}] [expr {$ly + 6}] [expr {$lx + 1}] [expr {$ly + 30}] -width 0 -fill #1a1426 -tags [concat $t post]
        $c create polygon [expr {$lx - 6}] [expr {$ly - 4}] [expr {$lx + 6}] [expr {$ly - 4}] [expr {$lx + 4}] [expr {$ly + 6}] [expr {$lx - 4}] [expr {$ly + 6}] -fill $ink(lampoff) -outline #1a1426 -tags [concat $t lamp$n]
        $c create polygon [expr {$lx - 8}] [expr {$ly - 4}] $lx [expr {$ly - 10}] [expr {$lx + 8}] [expr {$ly - 4}] -fill #1a1426 -width 0 -tags [concat $t post]
    }
    if {$gate} {
        # The gate at the end of a street: it is open when the street is lit.
        set gx [expr {$gate - $o}]
        set top [lindex $segs 0 1]
        $c create rectangle [expr {$gx - 14}] [expr {$top - 76}] [expr {$gx - 10}] $top -width 0 -fill #1a1426 -tags [concat $t gatepost]
        $c create rectangle [expr {$gx + 12}] [expr {$top - 76}] [expr {$gx + 16}] $top -width 0 -fill #1a1426 -tags [concat $t gatepost]
        $c create rectangle [expr {$gx - 14}] [expr {$top - 80}] [expr {$gx + 16}] [expr {$top - 76}] -width 0 -fill #1a1426 -tags [concat $t gatepost]
        $c create oval [expr {$gx - 3}] [expr {$top - 90}] [expr {$gx + 5}] [expr {$top - 82}] -width 0 -fill $ink(gold) -tags [concat $t gatestar]
    }
    $c lower pc$n hero
    paint 0
}

proc runStart {{street {}}} {
    global g h run toy W
    array set g {state run scene 0 dark 0 frames 0 shake 0 freeze 0 msgT 150 cam 0 paused 0 auto 1}
    # A street: {name seed length style mods theme diff}. The endless run
    # has no length.
    lassign [expr {[llength $street] ? $street : {"Endless street" 0 0 mixed {} 0 0}}] sname sseed slen sstyle smods stheme sdiff
    array set run [list limit $slen style $sstyle mods $smods diff $sdiff gateX 0 lampsAll 0 \
        fast [expr {"fast" in $smods ? 0.3 : 0}] night [expr {"short" in $smods ? 1.6 : 1.0}]]
    useTheme $stheme
    set toy(music) play
    if {[llength $street]} { set run(seed) $sseed } elseif {[info exists toy(seed)] && [string is integer -strict $toy(seed)]} { set run(seed) $toy(seed) } else {
        set run(seed) $run(next)
        set run(next) [expr {$run(next) % 99999 + 1}]
        save
    }
    array set run [list rs $run(seed) genX 0 top 196 count 0 segs {} lamps {} pieces {} taps {} shift 0 lit 0 press 0 crid 0]
    array unset ::crumbR
    foreach k {name blocks ledges lamps springs boats crumbles water} { set ::cur($k) {} }
    foreach t [.nb tabs] { .nb forget $t }
    .nb add .nb.s0 -text $sname
    set c .nb.s0
    $c delete all
    backdrop $c 0
    # The roofs of the run come with each piece.
    $c delete roof
    overlay $c
    $c itemconfigure hero -state normal
    paint 0
    array set h {x 30 y 189 vx 2 vy 0 ground 1 coyote 0 buffer 0 face 1 sx 1 sy 1 ride -1 wall 0}
    while {$run(genX) < $W + 200} genPiece
    if {[llength $street]} {
        say $sname [join [concat [list [dict get {mixed "The town" roofs "Roofs" canal "The canal" orchard "The orchard"} $sstyle]] [lmap m $smods { dict get $::modName $m }]] ", "]
    } else {
        say "Endless street" "Tap to jump. Light the lamps. Seed $run(seed)"
    }
}

proc runStep {} {
    global g h run toy W H
    incr g(frames)
    set c .nb.s0
    set v [speedAt 0]
    foreach p $run(pieces) { lassign $p a b pv; if {$h(x) >= $a && $h(x) < $b} { set v $pv; break } }
    set press $run(press); set run(press) 0
    set ev [physics h $run(segs) ::crumbR $v $press]
    set h(vx) $v
    foreach e $ev {
        switch [lindex $e 0] {
            jump { set h(sx) 0.7; set h(sy) 1.35; sfx jump; burst $h(x) [expr {$h(y) + 7}] 4 #c8b8e0 }
            land { set h(sx) 1.35; set h(sy) 0.7; sfx land; burst $h(x) [expr {$h(y) + 7}] 4 #c8b8e0 }
            break { sfx crash; $c itemconfigure cr[lindex $e 1] -state hidden }
            mend { $c itemconfigure cr[lindex $e 1] -state normal }
        }
    }
    # The lamps in reach light.
    set keep {}
    foreach l $run(lamps) {
        lassign $l lx ly n
        if {abs($h(x) - $lx) < 11 && abs($h(y) - 4 - $ly) < 22} {
            incr run(lit)
            $c itemconfigure lamp$n -fill #ffd27a
            $c itemconfigure glow$n -state normal
            set g(dark) [expr {max(0.0, $g(dark) - 0.18)}]
            burst $lx $ly 16 #ffd27a 0.5
            set g(freeze) 3; set g(shake) 3; sfx light
            paint 0
        } else { lappend keep $l }
    }
    set run(lamps) $keep
    # The night comes faster with the distance.
    set g(dark) [expr {min(1.0, $g(dark) + $run(night) * (1 + $h(x) / 8000.0) / 2400.0)}]
    # With the modifier every lamp, a lamp behind the hero ends the try.
    if {"every" in $run(mods) && [llength $run(lamps)] && [lindex $run(lamps) 0 0] < $h(x) - 14} { runOver lamp; return }
    if {$run(gateX) && $h(x) >= $run(gateX)} { streetDone; return }
    if {$g(frames) % 20 == 0} { paint 0 }
    if {$g(dark) >= 1.0} { runOver night; return }
    if {$h(y) > $H + 10} { runOver water; return }
    if {$h(ground) && [incr h(step)] % 14 == 0} { sfx step }
    # The camera keeps the hero at 140 pixels from the left.
    set g(cam) [expr {$h(x) - 140}]
    $c move w [expr {$run(shift) - $g(cam)}] 0
    set run(shift) $g(cam)
    # New pieces ahead, and the pieces behind the view go.
    while {$run(genX) < $g(cam) + $W + 200} genPiece
    while {[llength $run(pieces)] && [lindex $run(pieces) 0 1] < $g(cam) - 40} {
        set n [lindex $run(pieces) 0 3]
        $c delete pc$n
        set run(pieces) [lrange $run(pieces) 1 end]
    }
    set first [lindex $run(pieces) 0 0]
    set run(segs) [lmap s $run(segs) { if {[lindex $s 2] < $first} continue; set s }]
    set run(lamps) [lmap l $run(lamps) { if {[lindex $l 0] < $first} continue; set l }]
    set run(taps) [lmap t $run(taps) { if {$t < $h(x) - 20} continue; set t }]
}

proc runScore {} { expr {$::run(lit) * 10 + int($::h(x) / 10)} }
proc runOver {why} {
    global g run toy
    set g(state) runover; set toy(music) ""; sfx lose
    set score [runScore]
    set new [expr {$score > $run(best)}]
    if {$new} { set run(best) $score }
    save
    set g(shake) [expr {$why eq "water" ? 8 : 0}]
    if {$run(limit)} {
        say [dict get {night "Night fell" water "The flame went out" lamp "A lamp stayed dark"} $why] "[expr {$toy(touch) ? "Tap" : "A"}]: try again"
        set g(msgT) 0
        .nb.s0 itemconfigure pausemark -state hidden
        return
    }
    say [expr {$why eq "night" ? "Night fell" : "The flame went out"}] \
        "Score $score[expr {$new ? "  new best" : "  best $run(best)"}]   seed $run(seed)   [expr {$toy(touch) ? "Tap: again" : "A: again"}]"
    set g(msgT) 0
    .nb.s0 itemconfigure pausemark -state hidden
}

# A host can set toy(touch) after the game starts: the title shows the
# entry of a touch screen then.
trace add variable toy(touch) write {apply {{args} { if {$::g(state) eq "title" && !$::g(picked)} title }}}

# ---------------------------------------------------------------------
# Colors. `hsl` gives a color from a hue (0 to 360), a saturation, and a
# lightness (0 to 1). `contrast` gives the contrast ratio of two colors
# from their relative luminance (the formula of WCAG 2): 1 for the same
# color, 21 for black on white. A theme of a level must pass the
# contrast rules of its game.
# ---------------------------------------------------------------------
proc hsl {h s l} {
    set h [expr {fmod(fmod($h, 360.0) + 360.0, 360.0) / 60.0}]
    set c [expr {(1 - abs(2 * $l - 1)) * $s}]
    set x [expr {$c * (1 - abs(fmod($h, 2.0) - 1))}]
    set m [expr {$l - $c / 2}]
    lassign [lindex {{0 1 2} {1 0 2} {2 0 1} {2 1 0} {1 2 0} {0 2 1}} [expr {int($h) % 6}]] a b d
    set v [list $c $x 0]
    format #%02x%02x%02x {*}[lmap k [list $a $b $d] { expr {int(round(([lindex $v $k] + $m) * 255))} }]
}
proc luminance {c} {
    scan $c #%2x%2x%2x r g b
    set out 0.0
    foreach v [list $r $g $b] w {0.2126 0.7152 0.0722} {
        set v [expr {$v / 255.0}]
        set v [expr {$v <= 0.03928 ? $v / 12.92 : pow(($v + 0.055) / 1.055, 2.4)}]
        set out [expr {$out + $w * $v}]
    }
    return $out
}
proc contrast {a b} {
    set la [luminance $a]; set lb [luminance $b]
    expr {(max($la, $lb) + 0.05) / (min($la, $lb) + 0.05)}
}

# ---------------------------------------------------------------------
# The list of streets. `streets` has the streets of the generator that
# ship with the game, from easy to hard: {name seed length style mods
# theme diff}. Length is the count of pieces before the gate, diff the
# difficulty at the start (0 to 1). tools/toys-curate.tcl made the list:
# its bot walked each street with the taps of the generator, and kept
# the streets where the night stays under 80 percent at the gate.
# ---------------------------------------------------------------------
set modName {every "Every lamp" short "Short night" fast "Fast walk"}
set streets {
    {{Harbor Lanes 1} 1537 10 mixed {} 250010 0.0}
    {{Harbor Lanes 2} 2514 10 mixed {} 250010 0.0}
    {{Ember Roofs 1} 1431 14 roofs {} 20008 0.05}
    {{Ember Roofs 2} 2408 14 roofs {} 20008 0.05}
    {{Lagoon Canal 1} 1663 16 canal {} 190008 0.05}
    {{Lagoon Canal 2} 2640 16 canal {} 190008 0.05}
    {{Lagoon Canal 3} 3617 16 canal {} 190008 0.05}
    {{Moss Orchard 1} 1635 18 orchard {} 100004 0.1}
    {{Moss Orchard 2} 2612 18 orchard {} 100004 0.1}
    {{Moss Orchard 3} 3589 18 orchard {} 100004 0.1}
    {{Violet Lanes 1} 1815 18 mixed every 280012 0.1}
    {{Violet Lanes 2} 2792 18 mixed every 280012 0.1}
    {{Violet Lanes 3} 3769 18 mixed every 280012 0.1}
    {{Ember Roofs 3} 2614 20 roofs short 40001 0.15}
    {{Ember Roofs 4} 3591 20 roofs short 40001 0.15}
    {{Ember Roofs 5} 4568 20 roofs short 40001 0.15}
    {{Harbor Canal 1} 1869 22 canal every 210001 0.2}
    {{Harbor Canal 2} 2846 22 canal every 210001 0.2}
    {{Harbor Canal 3} 3823 22 canal every 210001 0.2}
    {{Mint Orchard 1} 1841 24 orchard fast 120009 0.2}
    {{Mint Orchard 2} 2818 24 orchard fast 120009 0.2}
    {{Mint Orchard 3} 3795 24 orchard fast 120009 0.2}
    {{Orchid Lanes 1} 2083 26 mixed {every short} 300005 0.25}
    {{Orchid Lanes 2} 5014 26 mixed {every short} 300005 0.25}
    {{Orchid Lanes 3} 8922 26 mixed {every short} 300005 0.25}
    {{Ember Roofs 6} 1845 28 roofs fast 4 0.3}
    {{Ember Roofs 7} 2822 28 roofs fast 4 0.3}
    {{Ember Roofs 8} 3799 28 roofs fast 4 0.3}
    {{Jade Canal 1} 5008 30 canal {short fast} 170003 0.35}
    {{Jade Canal 2} 19663 30 canal {short fast} 170003 0.35}
    {{Jade Canal 3} 38226 30 canal {short fast} 170003 0.35}
    {{Pollen Orchard 1} 2049 32 orchard {every fast} 80011 0.4}
    {{Pollen Orchard 2} 3026 32 orchard {every fast} 80011 0.4}
    {{Pollen Orchard 3} 4003 32 orchard {every fast} 80011 0.4}
    {{Orchid Roofs 1} 7246 34 roofs {every short} 330006 0.45}
    {{Orchid Roofs 2} 8223 34 roofs {every short} 330006 0.45}
    {{Iris Lanes 1} 7208 36 mixed {every short fast} 230006 0.5}
    {{Iris Lanes 2} 9162 36 mixed {every short fast} 230006 0.5}
}
array set sbest {}
proc count {} { expr {5 + [llength $::streets]} }
proc streetOf {n} { lindex $::streets [expr {$n - 5}] }
proc levelName {n} { expr {$n < 5 ? [lindex $::levels $n 0] : [lindex [streetOf $n] 0]} }
proc levelMods {n} { expr {$n < 5 ? {} : [lindex [streetOf $n] 4]} }
proc levelTheme {n} { expr {$n < 5 ? 0 : [lindex [streetOf $n] 5]} }
proc levelIdea {n} {
    if {$n < 5} { return "Made by hand" }
    dict get {mixed "The town" roofs "Roofs" canal "The canal" orchard "The orchard"} [lindex [streetOf $n] 3]
}
proc done {n} { expr {$n < 5 ? [info exists ::best($n)] : [info exists ::sbest([expr {$n - 5}])]} }
proc stars {n} {
    if {$n < 5} { return [expr {[info exists ::best($n)] ? 3 : 0}] }
    expr {[info exists ::sbest([expr {$n - 5}])] ? [lindex $::sbest([expr {$n - 5}]) 1] : 0}
}
proc doneCount {} { set k 0; for {set n 0} {$n < [count]} {incr n} { if {[done $n]} { incr k } }; return $k }
# A level opens when one of the three before it is done.
proc isOpen {n} {
    if {$n < 3} { return 1 }
    for {set k [expr {$n - 3}]} {$k < $n} {incr k} { if {[done $k]} { return 1 } }
    return 0
}
proc openCount {} { set k 0; for {set n 0} {$n < [count]} {incr n} { if {[isOpen $n]} { incr k } }; return $k }
proc continueAt {} {
    for {set n 0} {$n < [count]} {incr n} { if {[isOpen $n] && ![done $n]} { return $n } }
    return 0
}
proc playLevel {n} {
    set ::g(level) $n
    if {$n < 5} { start $n } else { runStart [streetOf $n]; set ::g(level) $n }
}
# The end of a street: the time, and the stars: one for the gate, one
# for 70 percent of the lamps, and one for each lamp.
proc streetDone {} {
    global g run toy sbest
    set g(state) streetclear; set toy(music) ""; sfx win
    set secs [format %.1f [expr {$g(frames) / 60.0}]]
    set s [expr {1 + ($run(lit) >= 0.7 * $run(lampsAll)) + ($run(lit) == $run(lampsAll))}]
    set i [expr {$g(level) - 5}]
    set new [expr {![info exists sbest($i)] || $s > [lindex $sbest($i) 1] || ($s == [lindex $sbest($i) 1] && $secs < [lindex $sbest($i) 0])}]
    if {$new} { set sbest($i) [list $secs $s] }
    save
    say "[lindex [streetOf $g(level)] 0] is lit" "Stars $s/3  $secs s  lamps $run(lit)/$run(lampsAll)   [expr {$toy(touch) ? "Tap: next" : "A: next"}]"
    set g(msgT) 0
    .nb.s0 itemconfigure pausemark -state hidden
}

# ---------------------------------------------------------------------
# Themes. Theme 0 is the dusk and the night of the levels made by hand.
# Each other theme turns the hue of each color of the two palettes by an
# angle of its seed and changes their saturation, and has a weather:
# rain, snow, fireflies, or none. `themeInk` checks the rules of
# contrast: the text and the gold of a lamp on the sky of the night, the
# cloak of the hero on the ground, and the edge of the ground on the
# hills behind it. A color that fails gets lighter until it passes.
# ---------------------------------------------------------------------
array set classicDusk [array get dusk]
array set classicNight [array get night]
proc rgb2hsl {c} {
    scan $c #%2x%2x%2x r g b
    set r [expr {$r / 255.0}]; set g [expr {$g / 255.0}]; set b [expr {$b / 255.0}]
    set mx [expr {max($r, $g, $b)}]; set mn [expr {min($r, $g, $b)}]
    set l [expr {($mx + $mn) / 2}]
    if {$mx == $mn} { return [list 0 0 $l] }
    set d [expr {$mx - $mn}]
    set s [expr {$l > 0.5 ? $d / (2 - $mx - $mn) : $d / ($mx + $mn)}]
    if {$mx == $r} { set h [expr {fmod(($g - $b) / $d + 6, 6)}] } elseif {$mx == $g} { set h [expr {($b - $r) / $d + 2}] } else { set h [expr {($r - $g) / $d + 4}] }
    list [expr {$h * 60}] $s $l
}
proc turn {c dh ds} { lassign [rgb2hsl $c] h s l; hsl [expr {$h + $dh}] [expr {min(1.0, $s * $ds)}] $l }
proc lighter {c} { lassign [rgb2hsl $c] h s l; hsl $h $s [expr {min(0.95, $l + 0.04)}] }
proc themeInk {seed} {
    variable ::themeCache
    if {[info exists themeCache($seed)]} { return $themeCache($seed) }
    if {$seed == 0} {
        set t [dict create dusk [array get ::classicDusk] night [array get ::classicNight] weather none water #2b3f74 hue 0]
        return [set themeCache($seed) $t]
    }
    set r [expr {($seed * 48271) % 2147483647}]
    set u {}
    for {set k 0} {$k < 3} {incr k} { set r [expr {($r * 48271) % 2147483647}]; lappend u [expr {$r / 2147483647.0}] }
    lassign $u a b c
    set dh [expr {$a * 360}]; set ds [expr {0.7 + $b * 0.6}]
    set d {}; set n {}
    foreach k [array names ::classicDusk] { dict set d $k [turn $::classicDusk($k) $dh $ds] }
    foreach k [array names ::classicNight] { dict set n $k [turn $::classicNight($k) $dh $ds] }
    foreach {k on want} {edge hill2 1.6 ground sky3 1.3} {
        while {[contrast [dict get $n $k] [dict get $n $on]] < $want && [lindex [rgb2hsl [dict get $n $k]] 2] < 0.9} {
            dict set n $k [lighter [dict get $n $k]]; dict set d $k [lighter [dict get $d $k]]
        }
    }
    set t [dict create dusk $d night $n weather [lindex {none rain snow fireflies} [expr {int($c * 4)}]] \
        water [turn #2b3f74 [expr {$dh / 3}] 1.0] hue [expr {fmod(250 + $dh, 360)}]]
    set themeCache($seed) $t
}
# The rules of contrast of a theme, for the tests: 1 when each passes.
proc themeOk {seed} {
    set t [themeInk $seed]
    set n [dict get $t night]
    expr {[contrast #f6ecd6 [dict get $n sky0]] >= 4.5 && [contrast #ffd27a [dict get $n sky1]] >= 6 &&
          [contrast #4a86a8 [dict get $n ground]] >= 2.5 && [contrast [dict get $n edge] [dict get $n hill2]] >= 1.6}
}
proc themeName {seed} {
    if {$seed == 0} { return "Classic" }
    set t [themeInk $seed]
    set names {Ember Amber Pollen Moss Mint Jade Lagoon Harbor Iris Violet Orchid Rose}
    set w [dict get {none "" rain ", rain" snow ", snow" fireflies ", fireflies"} [dict get $t weather]]
    return "[lindex $names [expr {int([dict get $t hue] / 30) % 12}]]$w"
}
proc useTheme {seed} {
    global dusk night ink
    set t [themeInk $seed]
    array set dusk [dict get $t dusk]
    array set night [dict get $t night]
    set ink(water) [dict get $t water]
    set ::weather [dict get $t weather]
}
set weather none
# The weather: 16 drops, flakes, or fireflies over the street.
proc weatherTick {c} {
    global weather g
    if {$weather eq "none"} { $c delete wx; return }
    if {![llength [$c find withtag wx]]} {
        for {set k 0} {$k < 16} {incr k} {
            set x [expr {($k * 131) % 472}]; set y [expr {($k * 53) % 200}]
            switch $weather {
                rain { $c create line $x $y [expr {$x - 2}] [expr {$y + 7}] -fill #8fa6d8 -tags wx }
                snow { $c create oval $x $y [expr {$x + 3}] [expr {$y + 3}] -width 0 -fill #e8ecff -tags wx }
                fireflies { $c create oval $x [expr {$y / 2 + 100}] [expr {$x + 3}] [expr {$y / 2 + 103}] -width 0 -fill #d8ff7a -tags wx }
            }
        }
    }
    set k 0
    foreach id [$c find withtag wx] {
        lassign [$c coords $id] x y
        switch $weather {
            rain { set dx -1.5; set dy 6 }
            snow { set dx [expr {sin(($g(frames) + $k * 20) / 25.0) * 0.5}]; set dy 0.8 }
            fireflies { set dx [expr {sin(($g(frames) + $k * 37) / 31.0) * 0.6}]; set dy [expr {cos(($g(frames) + $k * 23) / 27.0) * 0.4}] }
        }
        if {$y > 232 || $x < -4} { $c move $id [expr {fmod($k * 131 + $g(frames) * 7, 472) + 30 - $x}] [expr {-$y - ($k * 37) % 60}] } else { $c move $id $dx $dy }
        incr k
    }
    $c raise wx
}

title
tick
Live
Lamplighter on an iPhone in the iOS Simulator, in landscape, on its title screen.
Lamplighter on an Android phone in the emulator, in landscape, on its title screen.
One script, three screens: the game Lamplighter, docs/toys/native/lamplighter.tcl. The window runs live in this page. The phones are screenshots of iOS and Android.

On the desktop

Spreadsheet
The Spreadsheet example: a formula bar, Undo, Copy, and Paste buttons, number formats, and a grid of costs by quarter with totals and percent shares.
A spreadsheet with 10,000 rows and formulas: examples/spreadsheet.tcl. It runs live in this page: click a cell and type a value or a formula such as =sum(B2:B7).
Two windows side by side. On the left, the Vector example: a tool column, a drawing of a sun over two mountains, and a properties panel. On the right, a status board titled Print farm with three colored tiles and a list of five print jobs with status badges.
A vector drawing tool and a status board: examples/vector.tcl and examples/dashboard.tcl. Run them live below.

Write it once

One script, every screen

The same Tk script runs on Linux, macOS, Windows, the web, iOS, and Android.

A modern look

A CSS stylesheet styles each widget, in light and dark.

Fast

In zig build bench, a frame with 1,000 widgets uses 0.85 ms of CPU time at the 99th percentile.

Other languages

An app in Rust, Go, or JavaScript compiles to WebAssembly and opens a ztk window.

Check it and ship it

Made for agents

An agent can see the window, read each widget, and click in it, with no display.

Safe to run

An app from a URL runs in a sandbox with no file, network, or process access.

One command to ship

ztk bundle writes the app for each desktop and phone platform.

No third-party library

ztk uses the platform, the ztcl interpreter, and the Zig standard library.

Install

macOS and Linux
brew install beetlebugorg/tap/ztk
Windows
The .zip of a release
iOS and Android
ztk bundle writes the app from your script: On phones
Web
npm install @beetlebug/ztk

Install has the release archives for each desktop and the build from source.

Play

A balloon game, in ztk, in this page.

Tin Moon is a ztk app that runs in this frame as WebAssembly. Its burner is a ttk::scale and its fuel gauge is a ttk::progressbar. Click the frame to play, and press Escape to give the keys back. Two more games, and a tutorial for each game, are on the Games page.

The toy tinmoon before it runs
The code: 1054 lines of Tcl
# title: Tin Moon
# widget: ttk::scale
# page: docs/widgets/ttk.md
# pitch: Fly a tin balloon over a small moon. You steer only with height: each layer of the sky has its own wind, and the ttk::scale is your burner.
# order: 3

# Tin Moon. The ttk::scale on the right is the burner. More heat makes
# the balloon rise, slowly, as warm air does. You cannot steer left or
# right: each layer of the sky has a wind, and the streaks show its way.
# Climb or sink into the wind that you need, and land softly on the
# lit pad. The ttk::progressbar is the fuel. Moon motes on the way are
# extra points. Up and Down move the scale, or drag it.
#
# The skies. After the five skies made by hand, the list has the skies
# of a generator (`skies`), each with the plan of a bot that lands it.
# The title gives Continue and the picker of all skies. A sky opens when
# one of the three before it is done.
#
# Touch. The game reads its canvas itself (toy(direct) tells the host
# that it needs no touch buttons). A drag up or down anywhere on the sky
# moves the burner: 110 pixels of drag go from no heat to full heat, and
# the heat stays when the finger lifts. A bar beside the finger shows the
# heat. A tap on the mark "II" at the top right pauses. On the title and
# the end screens, a tap on the left third is Left (or B), on the right
# third Right, and in the middle A.

array set toy {sfx {} music title save {} calm 0 direct 1 orient landscape}
if {![info exists toy(touch)]} { set toy(touch) 0 }
set toy(help) "Drag up on the sky for more heat, down for less."
proc sfx {name} { lappend ::toy(sfx) $name }
set VW 420; set VH 236

# The levels: the width of the world, the winds of the layers from the
# top {top bottom speed}, the ground {x y ...}, the start, the pad
# {x0 x1 y}, the motes {x y}, and the fuel.
set levels {
    {"Drift" 900 {{0 236 1.1}}
        {0 200 160 200 260 190 420 205 600 196 700 200 900 200} {80 200} {700 780 200} {{300 140} {460 120} {560 150}} 100}
    {"Two Winds" 1100 {{0 110 1.6} {110 236 -0.6}}
        {0 205 180 205 300 170 380 200 560 186 760 200 880 200 1100 205} {90 205} {880 960 200} {{260 80} {520 60} {700 140}} 100}
    {"Back Home" 1000 {{0 90 -1.4} {90 160 0.0} {160 236 1.2}}
        {0 200 120 200 240 180 420 200 640 192 800 200 1000 200} {700 200} {120 200 200} {{560 60} {380 120} {240 70}} 90}
    {"Spires" 1300 {{0 80 1.8} {80 170 0.4} {170 236 -0.5}}
        {0 205 150 205 260 205 300 120 330 205 520 205 560 100 600 205 820 205 860 130 890 205 1060 205 1300 205} {80 205} {1100 1180 205} {{300 70} {560 50} {870 80} {700 180}} 90}
    {"Long Night" 1600 {{0 70 -1.0} {70 140 1.6} {140 236 -0.4}}
        {0 205 200 205 330 160 420 205 640 190 720 120 780 205 1000 205 1080 150 1150 205 1400 205 1600 205} {100 205} {1420 1500 205} {{420 100} {720 60} {1000 120} {1300 50} {560 160}} 85}
}

set ink(sky0) #0d1726; set ink(sky1) #1a2c47; set ink(sky2) #2a4266; set ink(moon) #f3e6c0
set ink(ground) #1b2333; set ink(ridge) #33415c; set ink(text) #f1ead8; set ink(dim) #8fa3bf
set ink(env1) #f2a541; set ink(env2) #f6e7c8; set ink(basket) #8a5a2b; set ink(pad) #6fd3a8; set ink(mote) #b9f0ff

ztk::style add {
    TScale::trough { background-color: #22324d; }
    TScale::slider { background-color: #f2a541; }
    TProgressbar::trough { background-color: #22324d; }
    TProgressbar::bar { background-color: #6fd3a8; }
}
. configure -background $ink(sky0)
canvas .c -width $VW -height $VH -background $ink(sky0) -highlightthickness 0
frame .side -background $ink(sky0)
label .side.heatT -text HEAT -background $ink(sky0) -foreground $ink(dim) -font {TkFixedFont 8 bold}
ttk::scale .side.heat -orient vertical -from 1 -to 0 -variable heat -length 150
label .side.fuelT -text FUEL -background $ink(sky0) -foreground $ink(dim) -font {TkFixedFont 8 bold}
ttk::progressbar .fuel -orient horizontal -maximum 100 -variable fuel -length $VW
grid .c -row 0 -column 0 -padx {6 4} -pady {6 2}
grid .side -row 0 -column 1 -rowspan 2 -sticky ns -pady 6
grid .fuel -row 1 -column 0 -sticky ew -padx {6 4} -pady {0 6}
pack .side.heatT -pady {4 2}
pack .side.heat -fill y -expand 1
label .side.score -background $ink(sky0) -foreground $ink(text) -font {TkFixedFont 9 bold} -text ""
pack .side.score -pady 4
set heat 0.45; set fuel 100

array set g {state title level 0 pick 0 unlocked 1 frames 0 shake 0 cam 0 hold 0 motes 0 layer -1 t 0 paused 0}
array set best {}
array set b {x 80 y 180 vx 0 vy 0 temp 0.45 sway 0 swayV 0 landed 1}
set parts {}

proc toy_restore {data} {
    global g best
    if {[catch {dict get $data unlocked} u]} return
    set g(unlocked) [expr {max(1, $u)}]
    if {![catch {dict get $data best} v]} { array set best $v }
    if {![catch {dict get $data skies} v]} { catch { array set ::sbest $v } }
    title
}
proc save {} { set ::toy(save) [list unlocked $::g(unlocked) best [array get ::best] skies [array get ::sbest]] }

proc toy_input {key state} {
    global g
    set on [expr {$state eq "press"}]
    if {$g(paused)} { if {$on} { unpause }; return }
    switch $g(state) {
        title {
            if {!$on} return
            switch $key {
                left - right { set g(pick) [expr {$g(pick) eq "continue" ? "levels" : "continue"}]; sfx move; title }
                a - start - up { sfx start; if {$g(pick) eq "levels"} { picker [continueAt] } else { start [continueAt] } }
            }
        }
        play {
            # Up and Down hold the scale: it moves while the key is down.
            if {$key in {up a}} { set g(hold) [expr {$on ? 1 : 0}] }
            if {$key in {down b}} { set g(hold) [expr {$on ? -1 : 0}] }
            if {$key eq "start" && $on} { start $g(level) }
        }
        pick {
            if {!$on} return
            switch $key { left { pickMove -1 } right { pickMove 1 } up { pickMove -5 } down { pickMove 5 } a - start { pickPlay $g(sel) } b { title } }
        }
        landed - crashed {
            if {$on && $key in {a start}} {
                if {$g(state) eq "crashed"} { start $g(level) } \
                elseif {$g(level) + 1 < [count] && [isOpen [expr {$g(level) + 1}]]} { sfx start; start [expr {$g(level) + 1}] } \
                else { start [continueAt] }
            } elseif {$on && $key eq "b"} { start $g(level) }
        }
    }
}

# A part of the level in flight, ::cur: the name, the width, the winds,
# the ground, the start, the pad, the motes, or the fuel.
set cur [lindex $levels 0]
set mods {}
proc level {what} {
    set k [lsearch {name width winds ground start pad motes fuel} $what]
    lindex $::cur $k
}

# The height of the ground at x, from the points of the level.
proc groundY {x} {
    set pts [level ground]
    foreach {x0 y0} [lrange $pts 0 end-2] {x1 y1} [lrange $pts 2 end] {
        if {$x1 eq ""} break
        if {$x >= $x0 && $x <= $x1} { return [expr {$y0 + ($y1 - $y0) * ($x - $x0) / double($x1 - $x0)}] }
    }
    return [lindex $pts end]
}
# The wind at a height: the layers blend over 14 pixels.
proc wind {y} {
    set w 0.0
    foreach l [level winds] {
        lassign $l top bot speed
        if {$y >= $top && $y < $bot} { set w $speed }
    }
    # With the modifier gusts, the wind turns back for 3 s of each 8 s.
    if {"gusts" in $::mods && $::g(frames) % 480 >= 300} { set w [expr {-0.6 * $w}] }
    return $w
}

proc world {} {
    global ink VW VH g
    .c delete all
    set W [level width]
    .c configure -scrollregion [list 0 0 $W $VH]
    # The sky: bands, stars, and the moon, which move with the camera.
    for {set k 0} {$k < 12} {incr k} {
        set t [expr {$k / 11.0}]
        .c create rectangle -40 [expr {$k * 20}] [expr {$VW + 40}] [expr {($k + 1) * 20}] -width 0 -fill [mixc $ink(sky0) $ink(sky2) $t] -tags sky
    }
    for {set k 0} {$k < 40} {incr k} {
        set x [expr {($k * 97) % $VW}]; set y [expr {($k * 53) % 150}]
        .c create rectangle $x $y [expr {$x + 1 + $k % 2}] [expr {$y + 1 + $k % 2}] -width 0 -fill [expr {$k % 3 ? "#7f93b8" : "#dfe8ff"}] -tags sky
    }
    .c create oval 300 18 352 70 -width 0 -fill $ink(moon) -tags sky
    .c create oval 312 30 322 40 -width 0 -fill #e2d3a8 -tags sky
    .c create oval 330 46 340 54 -width 0 -fill #e2d3a8 -tags sky
    # The far hills at half speed.
    set pts {}; for {set x 0} {$x <= $W / 2 + $VW} {incr x 30} { lappend pts $x [expr {175 + 18 * sin($x / 47.0) + 10 * sin($x / 13.0)}] }
    .c create polygon 0 $VH {*}$pts [expr {$W / 2 + $VW}] $VH -width 0 -fill #16213a -tags far
    # The layers of wind: a faint line at each border, and an arrow.
    foreach l [level winds] {
        lassign $l top bot speed
        if {$top > 0} { .c create line 0 $top $W $top -fill #243756 -dash {4 6} -tags layer }
        set mid [expr {($top + $bot) / 2}]
        for {set x 60} {$x < $W} {incr x 240} {
            set a [expr {$speed > 0.05 ? "▶" : $speed < -0.05 ? "◀" : "●"}]
            .c create text $x $mid -text $a -fill #2f4770 -font {TkFixedFont 9 bold} -tags layer
        }
    }
    .c create polygon 0 $VH {*}[level ground] $W $VH -width 0 -fill $ink(ground) -tags ground
    .c create line {*}[level ground] -fill $ink(ridge) -width 2 -tags ground
    lassign [level pad] x0 x1 y
    .c create rectangle $x0 [expr {$y - 4}] $x1 $y -width 0 -fill $ink(pad) -tags pad
    .c create rectangle [expr {$x0 + 4}] [expr {$y - 12}] [expr {$x0 + 6}] [expr {$y - 4}] -width 0 -fill $ink(pad) -tags pad
    .c create rectangle [expr {$x1 - 6}] [expr {$y - 12}] [expr {$x1 - 4}] [expr {$y - 4}] -width 0 -fill $ink(pad) -tags pad
    .c create oval [expr {$x0 + 2}] [expr {$y - 17}] [expr {$x0 + 8}] [expr {$y - 11}] -width 0 -fill #c8ffe6 -tags "pad padlight"
    .c create oval [expr {$x1 - 8}] [expr {$y - 17}] [expr {$x1 - 2}] [expr {$y - 11}] -width 0 -fill #c8ffe6 -tags "pad padlight"
    set k 0
    foreach m [level motes] {
        lassign $m x y
        .c create oval [expr {$x - 7}] [expr {$y - 7}] [expr {$x + 7}] [expr {$y + 7}] -width 0 -fill #1f3a55 -tags "mote m$k"
        .c create oval [expr {$x - 3}] [expr {$y - 3}] [expr {$x + 3}] [expr {$y + 3}] -width 0 -fill $ink(mote) -tags "mote m$k"
        incr k
    }
    # The wind streaks: short lines that move with the wind of their layer.
    for {set k 0} {$k < 26} {incr k} { .c create line 0 0 1 1 -fill #4c6a96 -width 1 -tags "streak s$k" }
    # The balloon: the envelope in two stripes, ropes, a basket, a flame.
    .c create oval 0 0 1 1 -width 0 -fill $ink(env1) -tags "bal benv"
    .c create polygon 0 0 1 1 2 2 -width 0 -fill $ink(env2) -tags "bal bstripe"
    .c create polygon 0 0 1 1 2 2 -width 0 -fill $ink(env1) -tags "bal bneck"
    .c create line 0 0 1 1 -fill #c9b48a -tags "bal brope1"
    .c create line 0 0 1 1 -fill #c9b48a -tags "bal brope2"
    .c create rectangle 0 0 1 1 -width 0 -fill $ink(basket) -tags "bal bbasket"
    .c create oval 0 0 1 1 -width 0 -fill #ffcf5c -state hidden -tags "bal bflame"
    for {set k 0} {$k < 18} {incr k} { .c create rectangle -9 -9 -8 -8 -width 0 -fill #ffcf5c -tags "part p$k" }
    set g(motes) 0
    set g(skyX) 0; set g(msgX) 0
}
proc mixc {a b t} {
    scan $a #%2x%2x%2x r1 g1 b1; scan $b #%2x%2x%2x r2 g2 b2
    format #%02x%02x%02x [expr {int($r1 + ($r2 - $r1) * $t)}] [expr {int($g1 + ($g2 - $g1) * $t)}] [expr {int($b1 + ($b2 - $b1) * $t)}]
}

proc start {n} {
    global g b heat fuel toy streaks cur mods got
    array set g [list state play level $n frames 0 shake 0 hold 0 layer -1 cam 0]
    set toy(music) play
    lassign [levelData $n] cur mods theme
    useTheme $theme
    array unset got
    world
    lassign [level start] x y
    array set b [list x $x y [expr {$y - 1}] vx 0 vy 0 temp 0.3 sway 0 swayV 0 landed 1]
    set heat 0.3; set fuel [level fuel]
    set streaks {}
    for {set k 0} {$k < 26} {incr k} { lappend streaks [list [expr {rand() * $::VW}] [expr {10 + rand() * 190}]] }
    .side.score configure -text "[expr {$n + 1}]/5"
    say [level name] [expr {$toy(touch) ? "Drag up: more heat. Land on the green pad." : "Up: more heat. Land on the green pad."}]
    pauseMark
}

proc say {a b2} {
    global VW
    .c delete msg
    if {$a eq "" && $b2 eq ""} return
    set x [expr {([info exists ::g(skyX)] ? $::g(skyX) : 0) + $VW / 2}]
    .c create rectangle [expr {$x - 150}] 74 [expr {$x + 150}] 136 -width 1 -outline #2f4770 -fill $::ink(sky0) -tags msg
    .c create text $x 94 -text $a -fill $::ink(text) -font {TkFixedFont 15 bold} -tags msg
    .c create text $x 120 -text $b2 -fill $::ink(dim) -font {TkFixedFont 9 bold} -tags msg
    set ::g(msgT) 180
}

proc burst {x y n color {vy 0}} {
    global parts
    for {set k 0} {$k < $n} {incr k} {
        set a [expr {rand() * 6.283}]; set s [expr {0.4 + rand() * 1.4}]
        lappend parts [list $x $y [expr {cos($a) * $s}] [expr {sin($a) * $s + $vy}] [expr {18 + int(rand() * 16)}] $color]
    }
    set parts [lrange $parts end-17 end]
}

proc tick {} {
    global g
    after 16 tick
    if {$g(paused)} return
    incr g(frames)
    if {$g(state) eq "title"} { titleTick; draw; return }
    if {$g(state) eq "play"} { step }
    draw
}

proc step {} {
    global g b heat fuel VW VH
    # The keys move the scale; the scale sets the burner.
    if {$g(hold)} { set heat [expr {max(0.0, min(1.0, $heat + $g(hold) * 0.025))}] }
    foreach e [fly] {
        switch [lindex $e 0] {
            burn { sfx burn; burst $b(x) [expr {$b(y) - 22}] 1 #ffcf5c -0.6 }
            gust { sfx gust }
            touch { sfx land; burst $b(x) $b(y) 6 #8fa3bf; if {[lindex $e 1] > 0.8} { set g(shake) 4 } }
            mote {
                set k [lindex $e 1]
                .c itemconfigure m$k -state hidden
                sfx pickup; burst {*}[lindex [level motes] $k] 10 #b9f0ff
            }
            crash { crash; return }
            pad { landed; return }
            short { say "Each mote first" "Take each mote, then land." }
        }
    }
    # The camera follows the balloon, a third of the view ahead of it.
    set W [level width]
    set want [expr {max(0, min($W - $VW, $b(x) - $VW / 2 + $b(vx) * 40))}]
    set g(cam) [expr {$g(cam) + ($want - $g(cam)) * 0.08}]
    if {[info exists g(msgT)] && $g(msgT) > 0 && [incr g(msgT) -1] == 0} { say "" "" }
}

# One frame of the flight: the burner, the lift, the wind, the ground,
# and the motes, on b, heat, fuel, g(frames), g(layer), g(motes), and
# got. It has no other effect, so the bot of the solver runs it too.
# Gives the events of the frame: burn, gust, touch, mote, crash, pad,
# and short (the pad before each mote, with the modifier motes).
proc fly {} {
    global g b heat fuel got mods
    set ev {}
    if {$fuel <= 0} { set heat 0 }
    # Warm air follows the burner with a lag: the balloon is slow to answer.
    set b(temp) [expr {$b(temp) + ($heat - $b(temp)) * 0.025}]
    set lift [expr {($b(temp) - 0.42) * ("heavy" in $mods ? 0.075 : 0.09)}]
    set b(vy) [expr {($b(vy) - $lift + 0.0) * 0.985}]
    set b(vy) [expr {max(-1.6, min(2.2, $b(vy)))}]
    set fuel [expr {max(0, $fuel - $heat * 0.045)}]
    if {$heat > 0.55 && $g(frames) % 9 == 0} { lappend ev burn }
    # The wind of the layer moves the balloon; it takes a moment to change.
    set w [wind $b(y)]
    set ax [expr {($w - $b(vx)) * 0.03}]
    if {$b(landed)} { set ax [expr {-$b(vx) * 0.3}] }
    set b(vx) [expr {$b(vx) + $ax}]
    # The basket swings when the balloon speeds up.
    set b(swayV) [expr {($b(swayV) - $ax * 2.2 - $b(sway) * 0.04) * 0.96}]
    set b(sway) [expr {$b(sway) + $b(swayV)}]
    set layer [lsearch -exact [lmap l [level winds] {expr {$b(y) >= [lindex $l 0] && $b(y) < [lindex $l 1]}}] 1]
    if {$layer != $g(layer)} { if {$g(layer) >= 0} { lappend ev gust }; set g(layer) $layer }
    set b(x) [expr {$b(x) + $b(vx)}]
    set b(y) [expr {$b(y) + $b(vy)}]
    set W [level width]
    if {$b(x) < 14} { set b(x) 14; set b(vx) 0 }
    if {$b(x) > $W - 14} { set b(x) [expr {$W - 14}]; set b(vx) 0 }
    # The envelope stays in the view: the sky has a ceiling.
    if {$b(y) < 72} { set b(y) 72; set b(vy) [expr {max(0, $b(vy))}] }
    # The ground: a soft touch lands, a fast one crashes.
    set gy [groundY $b(x)]
    if {$b(y) >= $gy} {
        # A wall of the ground, such as a spire, is a crash too.
        if {$b(vy) > 1.5 || abs($b(sway)) > 12 || $b(y) - $gy > 6} { set b(y) $gy; lappend ev crash; return $ev }
        set b(y) $gy
        if {!$b(landed) && $b(vy) > 0.3} { lappend ev [list touch $b(vy)] }
        set b(vy) 0
        set was $b(landed)
        set b(landed) 1
        lassign [level pad] x0 x1 py
        if {$b(x) > $x0 + 4 && $b(x) < $x1 - 4 && abs($gy - $py) < 3 && $g(frames) > 60} {
            # With the modifier motes, the pad counts after each mote.
            if {"motes" in $mods && $g(motes) < [llength [level motes]]} {
                if {!$was} { lappend ev short }
            } else { lappend ev pad; return $ev }
        }
    } elseif {$b(y) < $gy - 2} { set b(landed) 0 }
    # The motes.
    set k 0
    foreach m [level motes] {
        lassign $m mx my
        if {![info exists got($k)] && hypot($mx - $b(x), $my - ($b(y) - 24)) < 18} {
            set got($k) 1
            incr g(motes); lappend ev [list mote $k]
        }
        incr k
    }
    return $ev
}

proc crash {} {
    global g b toy
    set g(state) crashed; set toy(music) ""
    sfx crash; set g(shake) 12
    burst $b(x) [expr {$b(y) - 20}] 18 #f2a541
    say "Too fast" "Touch down slowly.  [expr {$toy(touch) ? "Tap: try again" : "A: try again"}]"
}
proc landed {} {
    global g b fuel best toy
    set n $g(level)
    set score [expr {int($fuel) * 10 + $g(motes) * 250}]
    # The stars of a sky: one for the landing, one for 40 percent of the
    # fuel, one for each mote.
    set s [expr {1 + ($fuel >= 0.4 * [level fuel]) + ($g(motes) == [llength [level motes]])}]
    if {$n < [llength $::levels]} {
        set new [expr {![info exists best($n)] || $score > $best($n)}]
        if {$new} { set best($n) $score }
        set top $best($n)
    } else {
        set new [expr {![info exists ::sbest($n)] || $score > [lindex $::sbest($n) 0]}]
        if {$new} { set ::sbest($n) [list $score [expr {max($s, [info exists ::sbest($n)] ? [lindex $::sbest($n) 1] : 0)}]] }
        set top [lindex $::sbest($n) 0]
    }
    set g(unlocked) [expr {max($g(unlocked), $n + 2)}]
    save
    set g(state) landed; set toy(music) ""; sfx win
    burst $b(x) [expr {$b(y) - 30}] 16 #6fd3a8
    say "Delivered: $score" "Stars $s/3. [expr {$new ? "New best" : "Best $top"}].  [expr {$toy(touch) ? "Tap: next   Left side: again" : "A: next   B: again"}]"
}

proc draw {} {
    global g b parts VW streaks heat
    set ox 0; set oy 0
    if {$g(shake) > 0} { if {!$::toy(calm)} { set ox [expr {(rand() - 0.5) * $g(shake)}]; set oy [expr {(rand() - 0.5) * $g(shake)}] }; incr g(shake) -1 }
    set W [level width]
    set cam [expr {$g(cam) + $ox}]
    # The left edge of the view, as xview sets it from the fraction.
    set cx [expr {max(0.0, min($W - $VW, $cam))}]
    .c xview moveto [expr {$cx / double($W)}]
    # The sky stays; the far hills move at half the speed.
    set d [expr {$cx - $g(skyX)}]
    .c move sky $d 0
    .c move far [expr {$d * 0.5}] 0
    set g(skyX) $cx
    .c move msg [expr {$cx - [expr {[info exists g(msgX)] ? $g(msgX) : $cx}]}] 0
    .c move pausemark [expr {$cx - [expr {[info exists g(msgX)] ? $g(msgX) : $cx}]}] 0
    set g(msgX) $cx
    # The streaks of wind.
    set out {}; set k 0
    foreach s $streaks {
        lassign $s sx sy
        set sx [expr {$sx + [wind $sy] * 1.6}]
        if {$sx > $VW + 20} { set sx -20 } elseif {$sx < -20} { set sx [expr {$VW + 20}] }
        set len [expr {abs([wind $sy]) * 9}]
        .c coords s$k [expr {$cx + $sx}] $sy [expr {$cx + $sx + ($len < 1 ? 1 : $len)}] $sy
        lappend out [list $sx $sy]; incr k
    }
    set streaks $out
    # The balloon.
    set x $b(x); set y [expr {$b(y) + $oy}]
    set top [expr {$y - 62}]
    set inflate [expr {$g(state) eq "crashed" ? 0.6 : 1.0}]
    set r [expr {19 * $inflate}]
    .c coords benv [expr {$x - $r}] $top [expr {$x + $r}] [expr {$top + 2 * $r + 4}]
    .c coords bstripe [expr {$x - 5}] [expr {$top + 1}] [expr {$x + 5}] [expr {$top + 1}] [expr {$x + 4}] [expr {$top + 2 * $r + 3}] [expr {$x - 4}] [expr {$top + 2 * $r + 3}]
    set nb [expr {$top + 2 * $r + 2}]
    .c coords bneck [expr {$x - 9}] [expr {$nb - 4}] [expr {$x + 9}] [expr {$nb - 4}] [expr {$x + 4}] [expr {$nb + 6}] [expr {$x - 4}] [expr {$nb + 6}]
    set bx [expr {$x + $b(sway)}]; set by [expr {$y - 9}]
    .c coords brope1 [expr {$x - 4}] [expr {$nb + 6}] [expr {$bx - 5}] $by
    .c coords brope2 [expr {$x + 4}] [expr {$nb + 6}] [expr {$bx + 5}] $by
    .c coords bbasket [expr {$bx - 6}] $by [expr {$bx + 6}] [expr {$y - 1}]
    set fl [expr {$heat * 6 + sin($g(frames) * 0.6) * 1.2}]
    if {$g(state) eq "play" && $heat > 0.05} {
        .c itemconfigure bflame -state normal
        .c coords bflame [expr {$x - 2.5}] [expr {$nb + 6 - $fl}] [expr {$x + 2.5}] [expr {$nb + 8}]
    } else { .c itemconfigure bflame -state hidden }
    set keep {}; set k 0
    foreach p $parts {
        lassign $p px py vx vy life color
        if {[incr life -1] <= 0 || $k >= 18} continue
        set px [expr {$px + $vx}]; set py [expr {$py + $vy}]; set vy [expr {$vy + 0.03}]
        .c coords p$k $px $py [expr {$px + 2}] [expr {$py + 2}]
        .c itemconfigure p$k -fill $color
        lappend keep [list $px $py $vx $vy $life $color]; incr k
    }
    for {} {$k < 18} {incr k} { .c coords p$k -9 -9 -8 -8 }
    set parts $keep
    weatherTick
    if {$g(frames) % 30 == 0} { .c itemconfigure padlight -fill [expr {$g(frames) % 60 ? "#c8ffe6" : "#3c8a6a"}] }
    if {$g(state) ne "title"} { .side.score configure -text "● $g(motes)" }
}

proc titleTick {} {
    global g b
    set b(x) [expr {290 + 60 * sin($g(frames) * 0.01)}]
    set b(y) [expr {176 + 8 * sin($g(frames) * 0.03)}]
    set b(sway) [expr {3 * sin($g(frames) * 0.05)}]
    set ::heat [expr {0.5 + 0.3 * sin($g(frames) * 0.03)}]
    if {$g(frames) % 40 == 0} { .c itemconfigure blink -state [expr {$g(frames) % 80 ? "hidden" : "normal"}] }
}

# Touch and the pointer: a drag moves the burner, and a press and a
# release with no drag is a tap.
array set ptr {x 0 y 0 heat 0 dragged 0 down 0}
proc ptrPress {x y} {
    global ptr heat
    array set ptr [list x $x y $y heat $heat dragged 0 down 1]
}
proc ptrMove {x y} {
    global ptr g heat
    if {!$ptr(down) || $g(state) ne "play" || $g(paused)} return
    if {!$ptr(dragged) && abs($y - $ptr(y)) < 8} return
    set ptr(dragged) 1
    set heat [expr {max(0.0, min(1.0, $ptr(heat) + ($ptr(y) - $y) / 110.0))}]
    gauge $x
}
proc ptrRelease {x y} {
    global ptr
    if {!$ptr(down)} return
    set ptr(down) 0
    .c delete gauge
    if {!$ptr(dragged) && hypot($x - $ptr(x), $y - $ptr(y)) < 12} { tap $x $y }
}
bind .c <ButtonPress-1> {ptrPress %x %y}
bind .c <B1-Motion> {ptrMove %x %y}
bind .c <ButtonRelease-1> {ptrRelease %x %y}

# The bar of the heat beside the finger, at x in the view.
proc gauge {x} {
    global heat
    .c delete gauge
    set cx [expr {[.c canvasx 0] + min(max($x - 34, 12), $::VW - 12)}]
    .c create rectangle [expr {$cx - 5}] 40 [expr {$cx + 5}] 200 -outline #f1ead8 -width 1 -fill #0d1726 -tags gauge
    .c create rectangle [expr {$cx - 4}] [expr {200 - 159 * $heat}] [expr {$cx + 4}] 199 -width 0 -fill #f2a541 -tags gauge
}

# The mark of the pause at the top right of the view.
proc pauseMark {} {
    .c delete pausemark
    if {!$::toy(touch)} return
    set x [expr {$::g(skyX) + $::VW - 22}]
    .c create rectangle $x 8 [expr {$x + 4}] 22 -width 0 -fill #8fa3bf -tags pausemark
    .c create rectangle [expr {$x + 8}] 8 [expr {$x + 12}] 22 -width 0 -fill #8fa3bf -tags pausemark
}

proc tap {x y} {
    global g VW
    set third [expr {$x < $VW / 3.0 ? "left" : $x > $VW * 2 / 3.0 ? "right" : "middle"}]
    if {$g(paused)} { unpause; return }
    switch $g(state) {
        title { toy_input [dict get {left left right right middle a} $third] press }
        pick { pickTap $x $y }
        play { if {$x > $VW - 60 && $y < 40} { pause } }
        landed { toy_input [expr {$third eq "left" ? "b" : "a"}] press }
        crashed { toy_input a press }
    }
}
proc pause {} {
    global g VW
    set g(paused) 1
    set x [expr {[.c canvasx 0] + $VW / 2}]
    .c create rectangle [expr {$x - 150}] 74 [expr {$x + 150}] 136 -width 1 -outline #2f4770 -fill #0d1726 -tags pausebox
    .c create text $x 98 -text "Paused" -fill #f1ead8 -font {TkFixedFont 15 bold} -tags pausebox
    .c create text $x 122 -text "Tap to fly on" -fill #8fa3bf -font {TkFixedFont 9 bold} -tags pausebox
}
proc unpause {} {
    set ::g(paused) 0
    .c delete pausebox
}

# A host can set toy(touch) after the game starts: the texts change.
trace add variable toy(touch) write {apply {{args} { if {$::g(state) eq "title"} title }}}


# ---------------------------------------------------------------------
# The generator of skies. A level is a seed, a style, and modifiers.
# `gen::sky` makes the level from a stream of random numbers of the
# seed: the width, the layers of wind, the ground, the start, the pad,
# the motes, and the fuel. A bot flies each level with the physics of
# the game (`fly`) and proves that it can land on the pad: a plan is a
# list of {height frames} parts, with the height "land" for the last
# part, and the bot moves the burner toward each height no faster than
# the keys do (0.025 a frame). `gen::search` finds a plan with a search
# over the heights of the layers, and the list of the game keeps it, so
# a test flies each plan again.
#
# The styles: plains (low hills), hills, spires (narrow peaks to fly
# over), and canyon (a high ground with the pad low in a valley with
# sloped walls). The
# modifiers: gusts (the wind turns back for a part of each 8 s), heavy
# (less lift), lowfuel (70 of fuel), motes (the pad counts after each
# mote).
# ---------------------------------------------------------------------
namespace eval gen { variable rs 1 }
proc gen::seed {n} { variable rs; set rs [expr {($n * 2654435761 + 12345) % 2147483648}]; if {$rs == 0} { set rs 1 } }
proc gen::rnd {} { variable rs; set rs [expr {($rs * 1103515245 + 12345) % 2147483648}]; expr {$rs / 2147483648.0} }
proc gen::pick {n} { expr {int([rnd] * $n)} }

proc gen::sky {seed style mods} {
    seed $seed
    set W [expr {900 + [pick 5] * 150}]
    set dir [expr {[rnd] < 0.5 ? 1 : -1}]
    # The layers: from 1 to 3, each with a speed; one of them goes the
    # way of the pad.
    set n [expr {1 + [pick 3]}]
    set cuts [lsort -integer [lrange [list [expr {70 + [pick 40]}] [expr {130 + [pick 40]}]] 0 [expr {$n - 2}]]]
    set tops [concat 0 $cuts]; set bots [concat $cuts 236]
    set winds {}
    set good [pick $n]
    foreach t $tops bo $bots {
        set k [llength $winds]
        set sp [expr {0.4 + [rnd] * 1.3}]
        set sp [expr {$k == $good ? $sp * $dir : ([rnd] < 0.5 ? -$sp * $dir : $sp * $dir * 0.5)}]
        lappend winds [list $t $bo [format %.2f $sp]]
    }
    # The start and the pad, at the two ends.
    set sx [expr {$dir > 0 ? 80 : $W - 80}]
    set px0 [expr {$dir > 0 ? $W - 200 + [pick 60] : 120 + [pick 60]}]
    set px1 [expr {$px0 + 80 - [pick 20]}]
    set base [expr {$style eq "canyon" ? 172 : 200}]
    set amp [dict get {plains 10 hills 30 spires 12 canyon 14} $style]
    set ground {}
    for {set x 0} {$x <= $W} {incr x [expr {60 + [pick 60]}]} {
        set y [expr {$base + int(([rnd] - 0.5) * 2 * $amp)}]
        lappend ground $x $y
    }
    # Spires: narrow peaks between the start and the pad.
    if {$style eq "spires"} {
        set pts {}
        foreach {x y} $ground { lappend pts $x $y }
        for {set k 0} {$k < 2 + [pick 3]} {incr k} {
            set x [expr {min($sx, $px0) + 120 + [pick [expr {abs($px0 - $sx) - 200}]]}]
            lappend pts [expr {$x - 20}] $base $x [expr {90 + [pick 50]}] [expr {$x + 20}] $base
        }
        set ground [flatten [lsort -integer -index 0 [pairs $pts]]]
    }
    # The pad is flat, and low in a canyon; the start is flat.
    set py [expr {$style eq "canyon" ? 205 : $base + 4}]
    set out {}
    foreach {x y} $ground {
        if {$x >= $px0 - 100 && $x <= $px1 + 100} continue
        if {abs($x - $sx) < 50} continue
        lappend out $x $y
    }
    lappend out [expr {$px0 - 30}] $py $px0 $py $px1 $py [expr {$px1 + 30}] $py
    # The walls of a canyon slope down to the pad.
    if {$style eq "canyon"} { lappend out [expr {$px0 - 90}] [expr {($base + $py) / 2}] [expr {$px1 + 90}] [expr {($base + $py) / 2}] }
    set sy [expr {$base + 2}]
    lappend out [expr {$sx - 40}] $sy $sx $sy [expr {$sx + 40}] $sy
    set ground [flatten [lsort -integer -index 0 [pairs $out]]]
    # Ends at 0 and at the width.
    if {[lindex $ground 0] > 0} { set ground [concat 0 [lindex $ground 1] $ground] }
    if {[lindex $ground end-1] < $W} { lappend ground $W [lindex $ground end] }
    set motes {}
    for {set k 0} {$k < 3 + [pick 3]} {incr k} {
        set x [expr {min($sx, $px0) + 80 + [pick [expr {max(40, abs($px0 - $sx) - 80)}]]}]
        lappend motes [list $x [expr {50 + [pick 100]}]]
    }
    set fuel [expr {"lowfuel" in $mods ? 70 : 100}]
    list "" $W $winds $ground [list $sx $sy] [list $px0 $px1 $py] $motes $fuel
}
proc gen::pairs {l} { set o {}; foreach {a b} $l { lappend o [list $a $b] }; return $o }
proc gen::flatten {l} { set o {}; foreach p $l { lappend o {*}$p }; return $o }

# The bot: one frame toward a height (or "land"), with the burner moved
# by at most 0.025, as a held key moves it.
proc gen::steer {target} {
    global b heat
    set gy [groundY $b(x)]
    if {$target eq "land"} {
        set want [expr {$gy - $b(y) > 40 ? 0.7 : 0.3}]
    } else {
        set want [expr {max(-0.8, min(0.8, ($target - $b(y)) * 0.02))}]
    }
    # The temperature that holds the speed, and a lead for the lag of
    # the warm air.
    set t [expr {0.42 + ($b(vy) - $want) * 0.6}]
    set h [expr {$t + ($t - $b(temp)) * 4}]
    set h [expr {max(0.0, min(1.0, $h))}]
    set heat [expr {$heat + max(-0.025, min(0.025, $h - $heat))}]
}
# Flies a plan from the start of the level in ::cur. Gives {result
# frames}: pad, crash, or time (no landing in the frames of the plan).
proc gen::flyPlan {plan} {
    global g b heat fuel got
    startState
    set f 0
    foreach part $plan {
        lassign $part target n
        for {set k 0} {$k < $n} {incr k} {
            incr g(frames); incr f
            steer $target
            set ev [fly]
            if {"crash" in $ev} { return [list crash $f] }
            if {"pad" in $ev} { return [list pad $f] }
        }
    }
    return [list time $f]
}
# The state of the start of a level, as `start` sets it.
proc gen::startState {} {
    global g b heat fuel got
    lassign [level start] x y
    array set b [list x $x y [expr {$y - 1}] vx 0 vy 0 temp 0.3 sway 0 swayV 0 landed 1]
    array unset got
    set heat 0.3; set fuel [level fuel]
    array set g {frames 0 layer -1 motes 0}
}
# The state of a flight, to go on from it: b, the burner, the fuel, the
# motes, and the counters of g.
proc gen::snap {} {
    global b heat fuel got g
    list [array get b] $heat $fuel [array get got] $g(frames) $g(layer) $g(motes)
}
proc gen::resume {st} {
    global b heat fuel got g
    lassign $st bb heat fuel gg g(frames) g(layer) g(motes)
    array set b $bb
    array unset got; array set got $gg
}
# Flies n frames toward a height from the state st: {result state}.
proc gen::part {st target n} {
    global g
    resume $st
    for {set k 0} {$k < $n} {incr k} {
        incr g(frames)
        steer $target
        set ev [fly]
        if {"crash" in $ev} { return [list crash {}] }
        if {"pad" in $ev} { return [list pad {}] }
    }
    list time [snap]
}
# Searches a plan: parts of 60 frames, each toward the middle of a
# layer, and a last part that lands. A beam of 5 plans goes on by the
# distance to the pad; a plan tries a landing when it is within 450
# pixels of the pad.
proc gen::search {{depth 40}} {
    lassign [level pad] x0 x1
    set pc [expr {($x0 + $x1) / 2.0}]
    set heights {}
    foreach l [level winds] { lassign $l t bo; lappend heights [expr {max(84, min(190, ($t + $bo) / 2))}] }
    lappend heights 84
    # With the modifier motes, the heights of the motes too, and the
    # beam goes by the distance to the next mote until each is taken.
    set need [expr {"motes" in $::mods}]
    if {$need} { foreach m [level motes] { lappend heights [expr {max(84, min(190, int([lindex $m 1] + 24)))}] } }
    set heights [lsort -unique $heights]
    startState
    set beam [list [list {} [snap]]]
    for {set d 0} {$d < $depth} {incr d} {
        set next {}
        foreach e $beam {
            lassign $e plan st
            foreach h $heights {
                lassign [part $st $h 60] r ns
                if {$r eq "crash"} continue
                set p [concat $plan [list [list $h 60]]]
                if {$r eq "pad"} { return $p }
                set dist [expr {abs($::b(x) - $pc)}]
                if {$need && $::g(motes) < [llength [level motes]]} {
                    set dist 1e9; set k 0
                    foreach m [level motes] {
                        if {![info exists ::got($k)]} { set dist [expr {min($dist, hypot([lindex $m 0] - $::b(x), [lindex $m 1] + 24 - $::b(y)))}] }
                        incr k
                    }
                    set dist [expr {$dist + 2000 * ([llength [level motes]] - $::g(motes))}]
                } elseif {$dist < 450 && [lindex [part $ns land 700] 0] eq "pad"} { return [concat $p [list [list land 700]]] }
                lappend next [list $dist $p $ns]
            }
        }
        if {![llength $next]} { return none }
        set beam [lmap e [lrange [lsort -real -index 0 $next] 0 4] { lrange $e 1 2 }]
    }
    return none
}

# ---------------------------------------------------------------------
# Colors. `hsl` gives a color from a hue (0 to 360), a saturation, and a
# lightness (0 to 1). `contrast` gives the contrast ratio of two colors
# from their relative luminance (the formula of WCAG 2): 1 for the same
# color, 21 for black on white. A theme of a level must pass the
# contrast rules of its game.
# ---------------------------------------------------------------------
proc hsl {h s l} {
    set h [expr {fmod(fmod($h, 360.0) + 360.0, 360.0) / 60.0}]
    set c [expr {(1 - abs(2 * $l - 1)) * $s}]
    set x [expr {$c * (1 - abs(fmod($h, 2.0) - 1))}]
    set m [expr {$l - $c / 2}]
    lassign [lindex {{0 1 2} {1 0 2} {2 0 1} {2 1 0} {1 2 0} {0 2 1}} [expr {int($h) % 6}]] a b d
    set v [list $c $x 0]
    format #%02x%02x%02x {*}[lmap k [list $a $b $d] { expr {int(round(([lindex $v $k] + $m) * 255))} }]
}
proc luminance {c} {
    scan $c #%2x%2x%2x r g b
    set out 0.0
    foreach v [list $r $g $b] w {0.2126 0.7152 0.0722} {
        set v [expr {$v / 255.0}]
        set v [expr {$v <= 0.03928 ? $v / 12.92 : pow(($v + 0.055) / 1.055, 2.4)}]
        set out [expr {$out + $w * $v}]
    }
    return $out
}
proc contrast {a b} {
    set la [luminance $a]; set lb [luminance $b]
    expr {(max($la, $lb) + 0.05) / (min($la, $lb) + 0.05)}
}

# ---------------------------------------------------------------------
# The list of skies. `skies` has the skies of the generator that ship
# with the game, from easy to hard: {name seed style mods theme plan}.
# The plan is the flight of the bot, and tests/toys.sh flies each plan
# again. tools/toys-curate.tcl made the list.
# ---------------------------------------------------------------------
set modName {gusts "Gusts" heavy "Heavy cargo" lowfuel "Low fuel" motes "Every mote"}
set skies {
    {{Glacier Plains 1} 833 plains {} 220006 {{117 60} {117 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {land 700}}}
    {{Glacier Plains 2} 1446 plains {} 220006 {{159 60} {159 60} {159 60} {159 60} {159 60} {159 60} {159 60} {159 60} {159 60} {84 60} {159 60} {84 60} {land 700}}}
    {{Glacier Plains 3} 2059 plains {} 220006 {{171 60} {171 60} {171 60} {171 60} {171 60} {84 60} {171 60} {land 700}}}
    {{Ember Hills 1} 643 hills {} 30001 {{118 60} {187 60} {187 60} {118 60} {187 60} {118 60} {187 60} {118 60} {84 60} {land 700}}}
    {{Ember Hills 2} 1869 hills {} 30001 {{169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {169 60} {84 60} {land 700}}}
    {{Ember Hills 3} 2482 hills {} 30001 {{118 60} {118 60} {118 60} {118 60} {118 60} {land 700}}}
    {{Iris Spires 1} 873 spires {} 260003 {{117 60} {189 60} {189 60} {189 60} {189 60} {117 60} {117 60} {189 60} {117 60} {189 60} {117 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {land 700}}}
    {{Iris Spires 2} 1486 spires {} 260003 {{155 60} {155 60} {84 60} {155 60} {155 60} {155 60} {155 60} {155 60} {155 60} {155 60} {84 60} {155 60} {155 60} {155 60} {155 60} {155 60} {155 60} {84 60} {84 60} {land 700}}}
    {{Iris Spires 3} 2099 spires {} 260003 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {118 60} {118 60} {118 60} {118 60} {84 60} {118 60} {84 60} {land 700}}}
    {{Violet Canyon 1} 913 canyon {} 300001 {{158 60} {158 60} {84 60} {158 60} {158 60} {land 700}}}
    {{Violet Canyon 2} 1526 canyon {} 300001 {{84 60} {170 60} {170 60} {84 60} {170 60} {170 60} {170 60} {84 60} {170 60} {170 60} {84 60} {land 700}}}
    {{Violet Canyon 3} 2139 canyon {} 300001 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {land 700}}}
    {{Lagoon Plains 1} 793 plains lowfuel 180008 {{117 60} {117 60} {117 60} {117 60} {117 60} {117 60} {117 60} {117 60} {117 60} {84 60} {land 700}}}
    {{Lagoon Plains 2} 2632 plains lowfuel 180008 {{167 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {167 60} {84 60} {land 700}}}
    {{Moss Hills 1} 1346 hills gusts 120005 {{124 60} {124 60} {124 60} {124 60} {190 60} {190 60} {190 60} {124 60} {124 60} {124 60} {124 60} {124 60} {190 60} {190 60} {124 60} {124 60} {124 60} {124 60} {124 60} {124 60} {190 60} {190 60} {190 60} {124 60} {84 60} {land 700}}}
    {{Moss Hills 2} 4411 hills gusts 120005 {{117 60} {117 60} {117 60} {117 60} {190 60} {190 60} {190 60} {117 60} {117 60} {117 60} {117 60} {117 60} {190 60} {190 60} {190 60} {117 60} {117 60} {117 60} {117 60} {117 60} {190 60} {190 60} {190 60} {117 60} {84 60} {land 700}}}
    {{Moss Hills 3} 6863 hills gusts 120005 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {118 60} {84 60} {land 700}}}
    {{Ember Spires 1} 613 spires heavy 12 {{166 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {166 60} {84 60} {land 700}}}
    {{Ember Spires 2} 3065 spires heavy 12 {{124 60} {190 60} {190 60} {190 60} {190 60} {190 60} {124 60} {190 60} {84 60} {84 60} {84 60} {84 60} {124 60} {84 60} {land 700}}}
    {{Pollen Plains 1} 673 plains motes 60003 {{109 60} {109 60} {84 60} {145 60} {170 60} {170 60} {170 60} {170 60} {170 60} {170 60} {170 60} {109 60} {109 60} {land 700}}}
    {{Pollen Plains 2} 3738 plains motes 60003 {{116 60} {84 60} {97 60} {116 60} {84 60} {164 60} {84 60} {116 60} {97 60} {97 60} {97 60} {164 60} {84 60} {116 60} {164 60} {164 60} {land 700}}}
    {{Lagoon Canyon 1} 1426 canyon gusts 200001 {{123 60} {123 60} {123 60} {123 60} {123 60} {84 60} {land 700}}}
    {{Lagoon Canyon 2} 2652 canyon gusts 200001 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {land 700}}}
    {{Moss Spires 1} 1316 spires gusts 90004 {{161 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {161 60} {84 60} {161 60} {161 60} {161 60} {84 60} {land 700}}}
    {{Moss Spires 2} 3768 spires gusts 90004 {{130 60} {190 60} {190 60} {190 60} {130 60} {130 60} {130 60} {84 60} {84 60} {84 60} {84 60} {84 60} {130 60} {130 60} {130 60} {84 60} {84 60} {84 60} {84 60} {84 60} {130 60} {130 60} {130 60} {84 60} {130 60} {84 60} {land 700}}}
    {{Mint Canyon 1} 1376 canyon motes 150006 {{101 60} {101 60} {119 60} {119 60} {127 60} {84 60} {land 700}}}
    {{Mint Canyon 2} 6280 canyon motes 150006 {{157 60} {163 60} {163 60} {144 60} {144 60} {144 60} {144 60} {144 60} {163 60} {157 60} {163 60} {157 60} {163 60} {land 700}}}
    {{Iris Hills 1} 858 hills lowfuel 245009 {{127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {127 60} {190 60} {127 60} {land 700}}}
    {{Iris Hills 2} 2697 hills lowfuel 245009 {{156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {156 60} {84 60} {land 700}}}
    {{Orchid Spires 1} 3380 spires motes 315008 {{132 60} {84 60} {164 60} {132 60} {132 60} {155 60} {132 60} {164 60} {84 60} {132 60} {164 60} {84 60} {132 60} {155 60} {140 60} {140 60} {140 60} {140 60} {84 60} {84 60} {84 60} {86 60} {132 60} {140 60} {132 60} {132 60} {132 60} {164 60} {132 60} {land 700}}}
    {{Orchid Spires 2} 3993 spires motes 315008 {{104 60} {104 60} {84 60} {134 60} {84 60} {104 60} {134 60} {155 60} {134 60} {134 60} {134 60} {134 60} {134 60} {134 60} {155 60} {149 60} {149 60} {105 60} {134 60} {155 60} {155 60} {104 60} {104 60} {land 700}}}
    {{Pollen Canyon 1} 688 canyon heavy 75009 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {land 700}}}
    {{Pollen Canyon 2} 2527 canyon heavy 75009 {{84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {land 700}}}
    {{Mint Plains 1} 748 plains gusts 135012 {{127 60} {190 60} {190 60} {190 60} {127 60} {84 60} {84 60} {190 60} {190 60} {190 60} {190 60} {127 60} {84 60} {land 700}}}
    {{Mint Plains 2} 1361 plains gusts 135012 {{163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {163 60} {84 60} {land 700}}}
    {{Rose Hills 1} 958 hills heavy 345009 {{126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {126 60} {84 60} {land 700}}}
    {{Rose Hills 2} 1571 hills heavy 345009 {{171 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {171 60} {84 60} {land 700}}}
    {{Moss Canyon 1} 718 canyon lowfuel 105010 {{84 60} {84 60} {84 60} {170 60} {84 60} {land 700}}}
    {{Moss Canyon 2} 1331 canyon lowfuel 105010 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {land 700}}}
    {{Violet Spires 1} 898 spires lowfuel 285006 {{107 60} {185 60} {185 60} {185 60} {107 60} {185 60} {107 60} {84 60} {84 60} {107 60} {107 60} {84 60} {land 700}}}
    {{Violet Spires 2} 1511 spires lowfuel 285006 {{190 60} {133 60} {133 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {133 60} {84 60} {land 700}}}
    {{Orchid Hills 1} 1556 hills {lowfuel heavy} 330002 {{123 60} {188 60} {188 60} {188 60} {123 60} {land 700}}}
    {{Orchid Hills 2} 2169 hills {lowfuel heavy} 330002 {{162 60} {162 60} {162 60} {84 60} {land 700}}}
    {{Violet Hills 1} 883 hills {gusts motes} 270012 {{117 60} {117 60} {165 60} {117 60} {165 60} {165 60} {165 60} {165 60} {165 60} {165 60} {117 60} {165 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {139 60} {117 60} {land 700}}}
    {{Violet Hills 2} 2722 hills {gusts motes} 270012 {{115 60} {115 60} {171 60} {115 60} {153 60} {171 60} {115 60} {153 60} {171 60} {153 60} {153 60} {153 60} {153 60} {153 60} {153 60} {153 60} {153 60} {153 60} {84 60} {153 60} {84 60} {84 60} {153 60} {115 60} {115 60} {115 60} {90 60} {153 60} {153 60} {115 60} {land 700}}}
    {{Ember Plains 1} 628 plains {gusts heavy} 15007 {{118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {118 60} {84 60} {84 60} {land 700}}}
    {{Ember Plains 2} 3080 plains {gusts heavy} 15007 {{171 60} {84 60} {84 60} {84 60} {171 60} {171 60} {84 60} {84 60} {84 60} {84 60} {84 60} {84 60} {171 60} {171 60} {84 60} {171 60} {84 60} {land 700}}}
    {{Jade Canyon 1} 2004 canyon {gusts lowfuel} 165001 {{120 60} {190 60} {190 60} {120 60} {120 60} {120 60} {120 60} {120 60} {120 60} {120 60} {120 60} {190 60} {190 60} {190 60} {190 60} {120 60} {190 60} {190 60} {120 60} {120 60} {190 60} {190 60} {190 60} {120 60} {120 60} {120 60} {120 60} {120 60} {120 60} {84 60} {land 700}}}
    {{Jade Canyon 2} 3230 canyon {gusts lowfuel} 165001 {{157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {157 60} {84 60} {land 700}}}
    {{Glacier Hills 1} 1431 hills {motes lowfuel} 205011 {{101 60} {101 60} {190 60} {101 60} {84 60} {101 60} {190 60} {190 60} {101 60} {land 700}}}
    {{Glacier Hills 2} 7561 hills {motes lowfuel} 205011 {{118 60} {84 60} {130 60} {130 60} {130 60} {130 60} {130 60} {84 60} {118 60} {84 60} {118 60} {91 60} {88 60} {88 60} {88 60} {88 60} {88 60} {88 60} {88 60} {88 60} {88 60} {118 60} {91 60} {land 700}}}
}
array set sbest {}
proc count {} { expr {[llength $::levels] + [llength $::skies]} }
proc skyOf {n} { lindex $::skies [expr {$n - [llength $::levels]}] }
# A level: {cur mods theme}, with cur in the form of `levels`.
proc levelData {n} {
    variable ::lvcache
    if {[info exists lvcache($n)]} { return $lvcache($n) }
    if {$n < [llength $::levels]} { return [set lvcache($n) [list [lindex $::levels $n] {} 0]] }
    lassign [skyOf $n] name seed style mods theme
    set cur [gen::sky $seed $style $mods]
    lset cur 0 $name
    set lvcache($n) [list $cur $mods $theme]
}
proc levelName {n} { lindex [levelData $n] 0 0 }
proc levelMods {n} { lindex [levelData $n] 1 }
proc levelTheme {n} { lindex [levelData $n] 2 }
proc levelIdea {n} {
    if {$n < [llength $::levels]} { return "Made by hand" }
    dict get {plains "Plains" hills "Hills" spires "Spires" canyon "Canyon"} [lindex [skyOf $n] 2]
}
proc done {n} { expr {$n < [llength $::levels] ? [info exists ::best($n)] : [info exists ::sbest($n)]} }
proc stars {n} {
    if {$n < [llength $::levels]} { return [expr {[info exists ::best($n)] ? 3 : 0}] }
    expr {[info exists ::sbest($n)] ? [lindex $::sbest($n) 1] : 0}
}
proc doneCount {} { set k 0; for {set n 0} {$n < [count]} {incr n} { if {[done $n]} { incr k } }; return $k }
proc isOpen {n} {
    if {$n < 3} { return 1 }
    for {set k [expr {$n - 3}]} {$k < $n} {incr k} { if {[done $k]} { return 1 } }
    return 0
}
proc openCount {} { set k 0; for {set n 0} {$n < [count]} {incr n} { if {[isOpen $n]} { incr k } }; return $k }
proc continueAt {} {
    for {set n 0} {$n < [count]} {incr n} { if {[isOpen $n] && ![done $n]} { return $n } }
    return 0
}

# ---------------------------------------------------------------------
# Themes. Theme 0 is the night of the levels made by hand. Each other
# theme has a hue of the sky, a time (night, dusk, or dawn), colors of
# the balloon, and a weather (none, snow, or dust). The rules of
# contrast: the envelope of the balloon and the motes on the sky, the
# pad on the ground, and the text on the sky. A color that fails gets
# lighter until it passes.
# ---------------------------------------------------------------------
array set classic [array get ink]
set classic(weather) none
proc themeInk {seed} {
    variable ::themeCache
    if {[info exists themeCache($seed)]} { return $themeCache($seed) }
    if {$seed == 0} { return [set themeCache(0) [array get ::classic]] }
    set r [expr {($seed * 48271) % 2147483647}]
    set u {}
    for {set k 0} {$k < 5} {incr k} { set r [expr {($r * 48271) % 2147483647}]; lappend u [expr {$r / 2147483647.0}] }
    lassign $u a b c d e
    set h [expr {$a * 360}]
    set tod [lindex {night dusk dawn} [expr {int($b * 3)}]]
    set L [dict get {night 0.08 dusk 0.14 dawn 0.2} $tod]
    set t [dict create sky0 [hsl $h 0.5 $L] sky1 [hsl $h 0.45 [expr {$L + 0.08}]] sky2 [hsl [expr {$h + ($tod eq "dawn" ? 40 : 10)}] 0.45 [expr {$L + 0.17}]] \
        moon [hsl [expr {40 + $c * 30}] 0.6 0.85] ground [hsl [expr {$h + 30}] 0.25 [expr {$L + 0.03}]] ridge [hsl [expr {$h + 30}] 0.25 [expr {$L + 0.2}]] \
        text [hsl $h 0.3 0.94] dim [hsl $h 0.25 0.7] env1 [hsl [expr {$d * 360}] 0.75 0.58] env2 [hsl [expr {$d * 360 + 30}] 0.6 0.88] \
        basket #8a5a2b pad [hsl [expr {$h + 150}] 0.6 0.62] mote [hsl [expr {$h + 180}] 0.7 0.82] \
        weather [lindex {none snow dust} [expr {int($e * 3)}]] tod $tod hue $h]
    foreach {k on want} {env1 sky2 3.0 mote sky2 3.0 pad ground 3.0 dim sky0 4.5 ridge sky2 1.3} {
        for {set i 0} {$i < 20 && [contrast [dict get $t $k] [dict get $t $on]] < $want} {incr i} {
            lassign [rgb2hsl [dict get $t $k]] hh ss ll
            if {$ll >= 0.95} break
            dict set t $k [hsl $hh $ss [expr {$ll + 0.04}]]
        }
    }
    set themeCache($seed) $t
}
proc themeOk {seed} {
    set t [themeInk $seed]
    expr {[contrast [dict get $t env1] [dict get $t sky2]] >= 3 && [contrast [dict get $t mote] [dict get $t sky2]] >= 3 &&
          [contrast [dict get $t pad] [dict get $t ground]] >= 3 && [contrast [dict get $t dim] [dict get $t sky0]] >= 4.5}
}
proc themeName {seed} {
    if {$seed == 0} { return "Classic" }
    set t [themeInk $seed]
    set names {Ember Amber Pollen Moss Mint Jade Lagoon Glacier Iris Violet Orchid Rose}
    return "[lindex $names [expr {int([dict get $t hue] / 30) % 12}]] [string totitle [dict get $t tod]][dict get {none "" snow ", snow" dust ", dust"} [dict get $t weather]]"
}
proc rgb2hsl {c} {
    scan $c #%2x%2x%2x r g b
    set r [expr {$r / 255.0}]; set g [expr {$g / 255.0}]; set b [expr {$b / 255.0}]
    set mx [expr {max($r, $g, $b)}]; set mn [expr {min($r, $g, $b)}]
    set l [expr {($mx + $mn) / 2}]
    if {$mx == $mn} { return [list 0 0 $l] }
    set d [expr {$mx - $mn}]
    set s [expr {$l > 0.5 ? $d / (2 - $mx - $mn) : $d / ($mx + $mn)}]
    if {$mx == $r} { set h [expr {fmod(($g - $b) / $d + 6, 6)}] } elseif {$mx == $g} { set h [expr {($b - $r) / $d + 2}] } else { set h [expr {($r - $g) / $d + 4}] }
    list [expr {$h * 60}] $s $l
}
proc useTheme {seed} {
    global ink
    array set ink [themeInk $seed]
    . configure -background $ink(sky0)
    foreach w {.side .side.heatT .side.fuelT .side.score} { $w configure -background $ink(sky0) }
    .c configure -background $ink(sky0)
}
# The weather: 20 flakes of snow or grains of dust over the view.
proc weatherTick {} {
    global ink g
    if {$ink(weather) eq "none"} return
    if {![llength [.c find withtag wx]]} {
        for {set k 0} {$k < 20} {incr k} {
            set x [expr {$g(skyX) + ($k * 97) % 420}]; set y [expr {($k * 41) % 236}]
            .c create oval $x $y [expr {$x + 2}] [expr {$y + 2}] -width 0 -fill [expr {$ink(weather) eq "snow" ? "#eef3ff" : "#c8a878"}] -tags wx
        }
    }
    set k 0
    foreach id [.c find withtag wx] {
        lassign [.c coords $id] x y
        set dx [expr {[wind $y] * 1.2 + ($ink(weather) eq "snow" ? 0 : 0.6)}]
        set dy [expr {$ink(weather) eq "snow" ? 0.7 : 0.15 * sin(($g(frames) + $k * 13) / 20.0)}]
        set rx [expr {$x - $g(skyX)}]
        if {$y > 236 || $rx < -10 || $rx > 430} { .c move $id [expr {$g(skyX) + fmod($k * 97 + $g(frames), 420) - $x}] [expr {($ink(weather) eq "snow" ? 0 : ($k * 41) % 236) - $y}] } else { .c move $id $dx $dy }
        incr k
    }
}

# The title: the balloon over the first level, and three entries:
# Continue, all levels, and the picker.
proc title {} {
    global g best toy ink VW cur mods
    set g(state) title; set toy(music) title
    set cur [lindex $::levels 0]; set mods {}
    useTheme 0
    set g(level) 0
    world
    array set ::b {x 200 y 150 vx 0 vy 0 sway 0 swayV 0 landed 0}
    set ::streaks {}
    for {set k 0} {$k < 26} {incr k} { lappend ::streaks [list [expr {rand() * $VW}] [expr {10 + rand() * 190}]] }
    set g(cam) 0
    if {$g(pick) ni {continue levels}} { set g(pick) continue }
    .c create text 210 70 -text "TIN MOON" -fill $ink(text) -font {TkFixedFont 26 bold} -tags title
    if {$g(pick) eq "continue"} {
        set n [continueAt]
        set line "Continue: [expr {$n + 1}]. [levelName $n]"; set sub "[doneCount] of [count] flights done"
    } else { set line "All skies"; set sub "[openCount] of [count] open" }
    .c create text 210 104 -text "◀  $line  ▶" -fill $ink(text) -font {TkFixedFont 11 bold} -tags title
    .c create text 210 124 -text $sub -fill $ink(dim) -font {TkFixedFont 9} -tags title
    .c create text 210 222 -text [expr {$toy(touch) ? "Tap here: fly     Tap a side: more" : "A: fly     Left, Right: more"}] -fill $ink(dim) -font {TkFixedFont 9 bold} -tags "title blink"
    .side.score configure -text "[doneCount]/[count]"
}

# The picker: ten cards on a page, each with the ground and the pad of
# its sky, its number, its stars, and the letters of its modifiers.
proc picker {{sel ""}} {
    global g
    set g(state) pick
    if {$sel ne ""} { set g(sel) [expr {max(0, min([count] - 1, $sel))}] }
    useTheme 0
    .c xview moveto 0
    set g(skyX) 0; set g(msgX) 0
    drawPicker
}
proc drawPicker {} {
    global g
    set g(page) [expr {$g(sel) / 10}]
    .c delete all
    .c create rectangle 0 0 420 236 -width 0 -fill #0d1726
    for {set i 0} {$i < 10} {incr i} {
        set n [expr {$g(page) * 10 + $i}]
        if {$n >= [count]} break
        set x0 [expr {4 + ($i % 5) * 83}]; set y0 [expr {4 + ($i / 5) * 92}]
        set open [isOpen $n]
        .c create rectangle $x0 $y0 [expr {$x0 + 79}] [expr {$y0 + 88}] -fill #1a2c47 \
            -outline [expr {$n == $g(sel) ? "#f2a541" : "#2f4770"}] -width [expr {$n == $g(sel) ? 3 : 1}]
        lassign [levelData $n] cur mods theme
        set t [themeInk $theme]
        .c create rectangle [expr {$x0 + 4}] [expr {$y0 + 4}] [expr {$x0 + 75}] [expr {$y0 + 58}] -width 0 -fill [dict get $t sky1]
        set W [lindex $cur 1]; set k [expr {71.0 / $W}]
        set pts [list [expr {$x0 + 4}] [expr {$y0 + 58}]]
        foreach {x y} [lindex $cur 3] { lappend pts [expr {$x0 + 4 + $x * $k}] [expr {$y0 + 4 + $y * 0.229}] }
        lappend pts [expr {$x0 + 75}] [expr {$y0 + 58}]
        .c create polygon {*}$pts -width 0 -fill [dict get $t ridge]
        lassign [lindex $cur 5] p0 p1 py
        .c create rectangle [expr {$x0 + 4 + $p0 * $k}] [expr {$y0 + 2 + $py * 0.229}] [expr {$x0 + 4 + $p1 * $k}] [expr {$y0 + 5 + $py * 0.229}] -width 0 -fill [dict get $t pad]
        lassign [lindex $cur 4] sx sy
        .c create oval [expr {$x0 + 1 + $sx * $k}] [expr {$y0 - 6 + $sy * 0.229}] [expr {$x0 + 7 + $sx * $k}] [expr {$y0 + $sy * 0.229}] -width 0 -fill [dict get $t env1]
        .c create text [expr {$x0 + 6}] [expr {$y0 + 70}] -anchor w -text [expr {$n + 1}] -fill #f1ead8 -font {TkFixedFont 10 bold}
        miniStars .c [expr {$x0 + 77}] [expr {$y0 + 70}] [stars $n]
        .c create text [expr {$x0 + 6}] [expr {$y0 + 82}] -anchor w -text [join [lmap m $mods { string index [dict get $::modName $m] 0 }] " "] -fill #8fa3bf -font {TkFixedFont 8 bold}
        if {!$open} {
            .c create rectangle [expr {$x0 + 4}] [expr {$y0 + 4}] [expr {$x0 + 75}] [expr {$y0 + 18}] -width 0 -fill #1a2c47
            .c create text [expr {$x0 + 40}] [expr {$y0 + 11}] -text "closed" -fill #8fa3bf -font {TkFixedFont 8 bold}
        }
    }
    foreach {x0 x1 text} {4 52 "◀" 368 416 "▶"} {
        .c create rectangle $x0 190 $x1 232 -fill #22324d -outline #2f4770
        .c create text [expr {($x0 + $x1) / 2}] 211 -text $text -fill #f1ead8 -font {TkFixedFont 12 bold}
    }
    set n $g(sel)
    .c create text 210 202 -text "[expr {$n + 1}]. [levelName $n]" -fill #f1ead8 -font {TkFixedFont 10 bold}
    .c create text 210 220 -text "[join [concat [list [levelIdea $n]] [lmap m [levelMods $n] { dict get $::modName $m }]] {, }]   [themeName [levelTheme $n]][expr {[isOpen $n] ? "" : "   closed"}]" -fill #8fa3bf -font {TkFixedFont 8}
}
proc pickMove {d} {
    global g
    set n [expr {$g(sel) + $d}]
    if {$n < 0 || $n >= [count]} return
    set g(sel) $n; sfx move; drawPicker
}
proc pickPlay {n} {
    if {![isOpen $n]} { sfx crash; return }
    sfx start; start $n
}
proc pickTap {x y} {
    global g
    if {$y > 188} {
        if {$x < 54} { pickMove -10 } elseif {$x > 366} { pickMove [expr {min(10, [count] - 1 - $g(sel))}] }
        return
    }
    set col [expr {int(($x - 4) / 83)}]; set row [expr {int(($y - 4) / 92)}]
    if {$col < 0 || $col > 4 || $row < 0 || $row > 1} return
    set n [expr {$g(page) * 10 + $row * 5 + $col}]
    if {$n >= [count]} return
    if {$n == $g(sel) || $::toy(touch)} { set g(sel) $n; pickPlay $n } else { set g(sel) $n; sfx move; drawPicker }
}
proc miniStars {c x y n} {
    for {set k 0} {$k < 3} {incr k} {
        set cx [expr {$x - 5 - (2 - $k) * 11}]; set pts {}
        for {set i 0} {$i < 10} {incr i} {
            set r [expr {$i % 2 ? 2.2 : 5}]; set a [expr {-1.5708 + $i * 0.6283}]
            lappend pts [expr {$cx + $r * cos($a)}] [expr {$y + $r * sin($a)}]
        }
        $c create polygon {*}$pts -fill [expr {$k < $n ? "#ffc93c" : "#4a5a78"}] -width 0
    }
}

title
tick
Live
0.85 msCPU time of a frame with 1,000 widgets, 99th percentile
1.52 msCPU time of a scroll frame of a canvas with 10,000 items, 99th percentile
1.6 msfrom start to the first frame, headless
1.9 MBthe WebAssembly build with gzip, with the fonts

For agents

Build it, see it, check it, ship it.

An agent gets the same view of the app as a person. The tools are commands of ztk, so a check is a Tcl script that runs in CI.

Works

See

ztk::snapshot . gives a PNG of the window. ztk --headless --screenshot writes one with no display. It renders with the CPU renderer on each platform.

Works

Read and drive

ztk::tree lists each widget with its class and its box. ztk::inject sends a click, a key, or text through the hit test and the focus, as a real backend does.

Works

Trust

A script has the commands of Tk and of the ztcl core. Host access needs --allow. In a browser a script has no file, network, or process access. The code is short, so a person can read it.

Works

Ship

ztk bundle makes one program file for Linux, macOS, or Windows from any computer. It also makes a macOS app, an iOS app, and an Android APK. An app in one file. A build from the web page is in progress.

Works

Ask why

ztk::debug why gives the source of each option, geometry the chain of the layout, and trace each event and redraw. The Inspect panel shows the same in the page, and ztk --mcp gives it to an agent. Debugging.

Works

Files for agents

llms.txt, llms-full.txt, an API index, and a skill with a check script that CI runs.

Works

Watch it get built

A replay of an agent that builds an app, step by step. The app is live at each step, and the check of each step runs in it.

Works

Runs on ztk

Well-known Tcl/Tk apps with no change to their code: the widget demo of Tk, tkcon, BWidget, Tablelist, tklib, and gitk. A script drives each app in the CI run.

Works

Learn with games

Three games, each one a short Tcl script: a platform game on a ttk::notebook, a puzzle with a listbox bag, and a balloon flight on a ttk::scale. A tutorial for each game builds it step by step.

Themed widgets

ttk widgets, modern or classic.

The same script in two themes. ttk::button, ttk::checkbutton with the switch style, ttk::radiobutton, ttk::entry, ttk::labelframe, ttk::separator, and ttk::sizegrip keep the options and the messages of wish. ttk::style restyles them, and each setting becomes a CSS rule.

The ttk widgets in the modern theme: a blue Apply button, Cancel, a disabled button, a check box, a switch, three radio buttons, a separator, two entries, and a size grip.
examples/themes.tclModernRound corners, an accent color, a light and a dark scheme, and transitions on each state.
The same ttk widgets in the classic theme, with the gray and the square reliefs of Tk on X11.
examples/themes-classic.tclClassicThe reliefs and the gray of Tk on X11. One line selects it: ztk::style theme classic.
Accent.TButton
ttk::style configure Accent.TButton \
    -foreground white \
    -background #2563eb
ttk::style map Accent.TButton \
    -background {active #1d4ed8}
ttk::button .ok -text "Apply" \
    -style Accent.TButton
/* the same rules in CSS */
TButton.Accent {
  color: white;
  background-color: #2563eb;
}
TButton.Accent:hover {
  background-color: #1d4ed8;
}

Themed widgets documents each ttk widget, and Styling and themes has ttk::style.

What it renders

Tk scripts, rendered by ztk.

When a card scrolls into view, its script runs live in its place: ztk in WebAssembly, rendered with WebGPU where the browser has it and WebGL 2 elsewhere. Click, type, drag, and toggle in it. Each script also runs in wish 8.6, and the cards follow the color scheme of your system.

A spreadsheet with a formula bar, Undo, Copy, and Paste buttons, number formats, and a grid of costs by quarter with totals, averages, percent shares, and the errors #DIV/0 and #REF in red.
examples/spreadsheet.tclA spreadsheet10,000 rows on a canvas, with items only for the cells in view and a header row and column that stay in place. Formulas such as =sum(B2:B7) are Tcl expressions, with recalculation and cycle errors. Arrows, Tab, Enter, and Shift select; typing edits in an entry over the cell. Columns resize by a drag, and ranges copy and paste as text with tabs.
A drawing tool with a column of tools, a page with a sky, a sun with selection handles, two mountains, and a tilted red square, a properties panel with color swatches and sliders, and a console.
examples/vector.tclA vector drawing toolRectangles, ellipses, lines, polygons, freehand paths, and text, with handles that move, resize, and rotate. The wheel zooms, and a drag with Space held pans. It has undo, groups, the z-order, and SVG export. The console runs Tcl in a child interpreter with a compute limit: press Up in it for the sample scripts.
A window titled Print farm with three tiles in blue, green, and violet gradients and a list of five jobs with colored status badges.
examples/dashboard.tclA status boardFrames with gradients, shadows, and round corners, and labels as badges. The colors come from the variables of its stylesheet.
A sign-in card with a title, an email entry, a password entry that shows stars, and Cancel and Sign in buttons.
examples/signin.tclA sign-in formA card frame with a shadow on a gradient window. The password entry uses -show, and it has the focus ring.
A window titled Widget gallery with cards of buttons, check buttons and switches, radio buttons with a segmented control, text entries with a search field and two spinboxes, a scale with ticks, an entry with a scrollbar, themed ttk widgets, and a labelframe with a message.
examples/gallery.tclA widget galleryButtons, check buttons with a mixed state, two switches, radio buttons, a segmented control, entries, a search field with a placeholder, two spinboxes, a scale, an entry that scrolls with an overlay scrollbar, and a card of ttk widgets with a style of the script, and a labelframe with a message, in cards that pack and grid place.
A calculator with an expression, the result 144, and a keypad of buttons in five rows.
examples/calculator.tclA calculatorA keypad of buttons in a grid. The 0 key spans two columns.
A settings page with Network and Hardware groups of labels and entries, and Reset and Save buttons.
examples/settings.tclA settings pageGroups of labels and entries, a text selection, a disabled entry, and a disabled button.
The Stage 1 demo: a title, a name entry, and Greet, Count, and Quit buttons.
examples/demo.tclThe Stage 1 demoThe script and the stylesheet at the top of this page.

Make the images again with zig build and tools/shots.sh. One image: ztk --headless --scale 2 --exit-after-frames 1 --screenshot out.png script.tcl, with --dark for the dark scheme.

Fluid

Smooth frames, even with a busy script.

The script makes a scene of quads, and a render thread renders it. The render thread also moves transitions, switches, sliders, and scrollbars by its own clock, so they keep moving while your script works.

CPU time of one frame, 99th percentile

Milliseconds, zig build bench, ReleaseFast, on an Intel Core i7-6700K with other load, 2026-11-23 to 2026-11-25. The dashed line is the budget of 8 ms. A shorter bar is faster.

Hover, 1,000 widgets
0.85 ms
ttk hover, 1,000 widgets
1.04 ms
Transition, 1,000 widgets
1.36 ms
Canvas scroll, 10,000 items
1.52 ms
Vector pan, 10,000 shapes
3.86 ms
Spreadsheet scroll, 10,000 rows
5.20 ms

No frames when idle

A window with no change renders no frame and wakes no thread.

Fast to start

1.6 ms from start to the first frame on the headless backend, and 3.0 ms on Wayland. The demo uses 11.2 MB of private memory.

Animation in the API

CSS transitions, @keyframes, springs, and ztk::animate for widget options and canvas items. Reduced motion shows each end state at once.

All the numbers

Native GPU rendering

One renderer for each platform API.

Each platform renders with its own GPU API, with no translation layer between ztk and the driver. ztk does not use MoltenVK, ANGLE, or DXVK. A CPU renderer gives the same image on each machine, and the tests compare the GPU output with it.

Works

CPU renderer

The reference renderer. It renders the demo into a Wayland shared memory buffer and into a framebuffer.

Works

Vulkan on Linux

The Vulkan renderer matches the CPU renderer on two GPUs, within 2 levels. On Wayland it renders the window into dma-bufs.

Works

AppKit and Metal on macOS

Native windows rendered with Metal, the system menu bar with NSMenu, input methods, the clipboard, file dialogs, the Dock, the tray, and dark mode and the accent color.

Works

Win32 and Direct3D 12 on Windows

Native windows with a Direct3D 12 swapchain, text with DirectWrite, native menus, input methods with TSF, the clipboard, file dialogs, the taskbar, the tray, and dark mode.

Works

WebGPU and WebGL 2 on the web

WebGPU with WGSL shaders where the browser gives an adapter, else WebGL 2, else the CPU renderer into a 2D canvas. No library is in the WebAssembly file.

First version

X11 on Linux

The X11 client of ztk with the CPU renderer, for a desktop with no Wayland compositor: one window, the keys, and the pointer.

Modern features

Style Tk widgets with CSS.

A stylesheet in a subset of CSS gives the default look. Styling and themes has the details. Your stylesheet changes it, with selectors, states, variables, and transitions.

  • A modern theme from a stylesheet, with a dark scheme.
  • A font engine with no library. It reads TrueType outlines and the kerning of the GPOS table.
  • A classic theme with the sizes and the colors of Tk on X11.
  • Transitions and keyframes on each state, with springs.
style.css
Button {
  border-radius: 6px;
  padding: 6px 12px;
  transition: all 120ms;
}
Button:hover {
  background: var(--accent);
  color: var(--accent-fg);
}

Built on ztcl. No bloat.

The sandbox of ztcl, and no third-party library.

ztk adds the Tk commands to ztcl and uses it as a Zig package. It needs only the interfaces of the platform, ztcl, and the Zig standard library. The build has two dependencies: ztcl, and the Vulkan headers for the types of Vulkan. Through ztcl it also builds libghostty-vt for ztk::terminal. The font reader and rasterizer, the text shaping, the PNG code, the CSS engine, and the renderers are code of ztk. ztk.wasm on this site is 6,103,995 bytes, and 1,887,009 bytes with gzip -9 (measured 2026-11-26).

No capability by default

The ztk library turns on no capability of ztcl. It reaches the host only through its backend. Only the ztk program turns on a capability, from a flag.

One static program

The core, the text code, the headless backend, and the direct backend link no library. The build with the direct and headless backends and no Vulkan is one static program.

Vulkan at run time

No build links the Vulkan loader. The program opens it at run time, so it also starts on a machine with no Vulkan.

Backends

Works

Headless

For tests and for the oracle that compares ztk with wish. It runs on Linux, macOS, and Windows. Pull requests check Linux, and the full run checks macOS and Windows every 6 hours.

Works

Wayland

Our own client of the Wayland protocol and the XKB key map, with no libwayland, so a static Linux program opens a window. The CPU renderer into shared memory. tests/wayland-input.sh checks keys, a resize, the scale 1.5, and the clipboard on a private headless sway.

Not tried on a device

Direct

For a Linux device with no display server: the framebuffer and evdev. Tests use fake hosts. --direct needs the flag --direct-unsafe-test-device.

100% AI-driven, on purpose

AI agents write the code, the tests, and the docs.

A person sets the direction.

It is an experiment in how far a project can go when you let go of how software "should" be developed and move as fast as the agents permit. An optimization that was too much work before is a 15-minute change now, so we try each one.

The world changed. Tk looks like a toolkit for people to learn. ztk is for AI. It is for agents.

Status

Experimental. ztk is not yet a drop-in Tk. The widgets of Tk 8.6 are in (with text, ttk::treeview, ttk::notebook, and native menus), and AppKit and Win32 backends render native windows. Still to come: the native look of each platform (#154). AI coding agents wrote the code and the docs, under human direction, so review the code before you depend on it. The security model lists what a script can reach. Differences from Tk lists the gaps, and the plan has the roadmap.

The interpreter under ztk

ztcl: fast, sandboxed Tcl in Zig

A Tcl 8.6 interpreter with a bytecode VM, exact step and memory limits, real threads, and an optional JIT up to 28 times as fast as tclsh.

Visit ztcl